问:
How to delete or add column in SQLITE?
I want to delete or add column in sqlite database

I am using following query  to delete column.

```<code>ALTER TABLE TABLENAME DROP COLUMN COLUMNNAME
</code>```

But it gives error

```<code>System.Data.SQLite.SQLiteException: SQLite error
near "DROP": syntax error
</code>```

答:
```<code>public void DeleteColFromTable(String DbName, String TableName, String ColName){
    SQLiteDatabase db = openOrCreateDatabase(""+DbName+"", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS "+TableName+"(1x00dff);");
    Cursor c = db.rawQuery("PRAGMA table_info("+TableName+")", null);
    if (c.getCount() == 0) {

    } else {
        String columns1 = "";
        String columns2 = "";
        while (c.moveToNext()) {
            if (c.getString(1).equals(ColName)) {
            } else {
                columns1 = columns1 + ", " + c.getString(1) + " " + c.getString(2);
                columns2 = columns2 + ", " + c.getString(1);
            }
            if (c.isLast()) {
                db.execSQL("CREATE TABLE IF NOT EXISTS DataBackup (" + columns1 + ");");
                db.execSQL("INSERT INTO DataBackup SELECT " + columns2 + " FROM "+TableName+";");
                db.execSQL("DROP TABLE "+TableName+"");
                db.execSQL("ALTER TABLE DataBackup RENAME TO "+TableName+";");
            }
        }
    }
}
</code>```

and just call a method

```<code>DeleteColFromTable("Database name","Table name","Col name which want to delete");
</code>```

Title: How to delete or add column in SQLITE?

Body:
I want to delete or add column in sqlite database

I am using following query  to delete column.

ALTER TABLE TABLENAME DROP COLUMN COLUMNNAME

But it gives error

System.Data.SQLite.SQLiteException: SQLite error
near "DROP": syntax error

Body:
public void DeleteColFromTable(String DbName, String TableName, String ColName){
    SQLiteDatabase db = openOrCreateDatabase(""+DbName+"", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS "+TableName+"(1x00dff);");
    Cursor c = db.rawQuery("PRAGMA table_info("+TableName+")", null);
    if (c.getCount() == 0) {

    } else {
        String columns1 = "";
        String columns2 = "";
        while (c.moveToNext()) {
            if (c.getString(1).equals(ColName)) {
            } else {
                columns1 = columns1 + ", " + c.getString(1) + " " + c.getString(2);
                columns2 = columns2 + ", " + c.getString(1);
            }
            if (c.isLast()) {
                db.execSQL("CREATE TABLE IF NOT EXISTS DataBackup (" + columns1 + ");");
                db.execSQL("INSERT INTO DataBackup SELECT " + columns2 + " FROM "+TableName+";");
                db.execSQL("DROP TABLE "+TableName+"");
                db.execSQL("ALTER TABLE DataBackup RENAME TO "+TableName+";");
            }
        }
    }
}

and just call a method

DeleteColFromTable("Database name","Table name","Col name which want to delete");


来源: stackexchange

问:
Bootstrap row with two columns and textareas fill up page
I'm trying to make a simple page that have a header on a row, then a row with two columns. Each column will include a textarea. I want the columns and the textareas to fill up the rest of the page. I have been searching but i can't solve this. I'm using boostrap v4.0.0-beta.2.

Here is my snippet:

  label { font-weight: bold; }
            html, body, .container-fluid {
                height: 100%;
                min-height: 100%;
            }
            textarea.form-control {
                height: 100%;
                width: 100%;
                min-height: 100%;
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid" style="background: #DDDDDD">
   <div class="row">
       <div class="col-lg-12 jumbotron text-center">
           <h1>Formatter</h1>
           <p>Enter raw input to see output</p>
       </div>
   </div>
   <div class="row" style="background: #CCCCCC;">
       <div class="col-lg-6">
           <label for="input">Input:</label>
           <textarea class="form-control" id="input">
           </textarea>
       </div>
       <div class="col-lg-6">
           <label for="output">Output:</label>
           <textarea readonly class="form-control" id="output"></textarea>
        </div>
    </div>
</div></code>```

答:
You can do this by set window height with jQuery .height() function. You can check snippet but remember to add jQuery file.

  $(document).ready(function(){
    var textareaHeight = $(window).height();
    $(".form-control").height(textareaHeight - 30);
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label { font-weight: bold; }
            html, body, .container-fluid {
                height: 100%;
                min-height: 100%;
            }
            textarea.form-control {
                height: 100%;
                width: 100%;
                min-height: 100%;
            }</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Formatter

Enter raw input to see output

           Input:
           <textarea class="form-control" id="input">
           </textarea>

           Output:
           <textarea readonly class="form-control" id="output"></textarea>

```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make a simple page that have a header on a row, then a row with two columns. Each column will include a textarea. I want the columns and the textareas to fill up the rest of the page. I have been searching but i can't solve this. I'm using boostrap v4.0.0-beta.2.

Here is my snippet:

  label { font-weight: bold; }
            html, body, .container-fluid {
                height: 100%;
                min-height: 100%;
            }
            textarea.form-control {
                height: 100%;
                width: 100%;
                min-height: 100%;
            }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Formatter

Enter raw input to see output

           Input:
           <textarea class="form-control" id="input">
           </textarea>

           Output:
           <textarea readonly class="form-control" id="output"></textarea>

Body:
You can do this by set window height with jQuery .height() function. You can check snippet but remember to add jQuery file.

  $(document).ready(function(){
    var textareaHeight = $(window).height();
    $(".form-control").height(textareaHeight - 30);
  });

label { font-weight: bold; }
            html, body, .container-fluid {
                height: 100%;
                min-height: 100%;
            }
            textarea.form-control {
                height: 100%;
                width: 100%;
                min-height: 100%;
            }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container-fluid" style="background: #DDDDDD">
   <div class="row">
       <div class="col-lg-12 jumbotron text-center">
           <h1>Formatter</h1>
           <p>Enter raw input to see output</p>
       </div>
   </div>
   <div class="row" style="background: #CCCCCC;">
       <div class="col-lg-6">
           <label for="input">Input:</label>
           <textarea class="form-control" id="input">
           </textarea>
       </div>
       <div class="col-lg-6">
           <label for="output">Output:</label>
           <textarea readonly class="form-control" id="output"></textarea>
        </div>
    </div>
</div>


问:
Issue to resize element content properly
The text of second h5 element doesnt resize properly and get out over the background color, I also tested put the h5 inside a div and apply css to the div but it didnt work, what am I missing?

Here is the relevant code (I had to remove other elements and css properties):

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}
.card .front {
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
}
.card .front h5 {
    background-color: #5E92F2;
    padding: 10px 0 10px 0;
    margin-top: 98%;
    width: 198px;
    height: 44px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</head>
<body>
<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section>

<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1 With more text</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section></code>```

答:
For h5 you are adding height: 44px; so the font-size is taking default h5 font size if you decrease the font size it will fix the issue or increase the height of h5

so use something like

```<code>.card .front h5{
 font-size:16px;
}
</code>```

or

```<code>.card .front h5{
 height:64px;
}
</code>```

Body:
The text of second h5 element doesnt resize properly and get out over the background color, I also tested put the h5 inside a div and apply css to the div but it didnt work, what am I missing?

Here is the relevant code (I had to remove other elements and css properties):

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}
.card .front {
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
}
.card .front h5 {
    background-color: #5E92F2;
    padding: 10px 0 10px 0;
    margin-top: 98%;
    width: 198px;
    height: 44px;
}

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

Image 1

Abc

Image 1 With more text

Abc

Body:
For h5 you are adding height: 44px; so the font-size is taking default h5 font size if you decrease the font size it will fix the issue or increase the height of h5

so use something like

.card .front h5{
 font-size:16px;
}

or

.card .front h5{
 height:64px;
}


问:
java servlet sort json data by month name
I have a json array having single object with key as month name. When coming from Db it looks like
 [{
    "January": "January",
    "February": "February",
    "March": "March",
    "April": "April",
    "May": "May",
    "June": "June",
    "July": "July",
    "August": "August",
    "September": "September",
    "October": "October",
    "November": "November",
    "December": "December"
}]
and on frontend it looks like

```<code><select data-field-id="317" class="form-control selectchange to_month" id="searchform_to_month" name="searchform_to_month"><option value="">Select To Month</option><option value="June">June</option><option value="October">October</option><option value="December">December</option><option value="May">May</option><option value="September">September</option><option value="March">March</option><option value="July">July</option><option value="January">January</option><option value="February">February</option><option value="April">April</option><option value="August">August</option><option value="November">November</option></select>
</code>```

How can I sort it by month name so that it comes in dropdown like Jan, Feb and so on..

Below is the piece of code used

```<code>JSONArray jsonArray = new JSONArray(rowfielddata.getString("option_values"));
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        Iterator<String> keys = json.keys();
                        while (keys.hasNext()) {
                            String key = keys.next();
                            f2 = f2 + "<option value='" + key + "'>" + json.get(key) + "</option>";
                        }

                    }
</code>```

Thanks in advance!!

答:
Perhaps you can change the part that iterates over the keys by the following solution:

If you have a single object with the months as keys you may need an aditional array that maps the month as a number to the key of the single object.

```<code>String []  monthsMapping = new String[12];
monthsMapping[0] = "January";
...
monthsMapping[11] = "December";
</code>```

Then you genereate the options looping through this array:

```<code>for(int i=0; i<12; i++){
   //Generate the 12 options
   ... +  singleMonthJSONObject.getString(monthsMapping[i]) + ...;
}
</code>```

Body:
I have a json array having single object with key as month name. When coming from Db it looks like
 [{
    "January": "January",
    "February": "February",
    "March": "March",
    "April": "April",
    "May": "May",
    "June": "June",
    "July": "July",
    "August": "August",
    "September": "September",
    "October": "October",
    "November": "November",
    "December": "December"
}]
and on frontend it looks like

<select data-field-id="317" class="form-control selectchange to_month" id="searchform_to_month" name="searchform_to_month"><option value="">Select To Month</option><option value="June">June</option><option value="October">October</option><option value="December">December</option><option value="May">May</option><option value="September">September</option><option value="March">March</option><option value="July">July</option><option value="January">January</option><option value="February">February</option><option value="April">April</option><option value="August">August</option><option value="November">November</option></select>

How can I sort it by month name so that it comes in dropdown like Jan, Feb and so on..

Below is the piece of code used

JSONArray jsonArray = new JSONArray(rowfielddata.getString("option_values"));
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        Iterator<String> keys = json.keys();
                        while (keys.hasNext()) {
                            String key = keys.next();
                            f2 = f2 + "<option value='" + key + "'>" + json.get(key) + "</option>";
                        }

                    }

Thanks in advance!!

Body:
Perhaps you can change the part that iterates over the keys by the following solution:

If you have a single object with the months as keys you may need an aditional array that maps the month as a number to the key of the single object.

String []  monthsMapping = new String[12];
monthsMapping[0] = "January";
...
monthsMapping[11] = "December";

Then you genereate the options looping through this array:

for(int i=0; i<12; i++){
   //Generate the 12 options
   ... +  singleMonthJSONObject.getString(monthsMapping[i]) + ...;
}


问:
How to do player movement calculations on c# console from unity movement
Question: How do i go about doing a equation on a c# console for where the player should be based on player input from unity.

To explain farther, the client is ran in unity and the server is a c# console application. When the player presses a movement key ex. (w, witch moves the player forward based on local position, as to always make the player move forward) it sends to the server that player pressed w, and then the sever responds and tells the client that it pressed w, changing the player w is pressed bool to true. Then the character moves.

Essentially I am trying to figure out how to make a equation that will do what unity does, but without a transform, or even how the transform works so that i can apply it to the server side.

Here is the client side code:

```<code> private void Update()
{
    SendKeysToServer();
    PlayerController();
    PlayerPositionUpdateChecker();
}

public void PlayerController()
{
    if (gameObject.name == ntwmng.Playername)
    {
        MovementControllerPlayer();
        JumpControllerPlayer();
        RotationControllerPlayer();
        MovementFinalizer();
    }
    else
    {
        MovementControllerClones();
        JumpControllerClones();
        RotationControllerClones();
        MovementFinalizerClones();
    }
}

public void MovementControllerPlayer()
{
    if (CharContr.isGrounded)
    {
        moveDirection = new Vector3(0, 0, 0);

        if (wKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(0, 0, speed * Time.deltaTime);
        }
        if (sKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(0, 0, -speed * Time.deltaTime);
        }
        if (qKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(-speed * Time.deltaTime, 0, 0);
        }
        if (eKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(speed * Time.deltaTime, 0, 0);
        }

        moveDirection = transform.TransformDirection(moveDirection);
        //moveDirection *= speed;
    }

}

public void RotationControllerPlayer()
{
    if (dKeyDownPlayer)
    {
        transform.Rotate(0, RotationSpeed * Time.deltaTime, 0);
    }
    if(aKeyDownPlayer)
    {
        transform.Rotate(0, -RotationSpeed * Time.deltaTime, 0);
    }
}

public void JumpControllerPlayer()
{
    if (CharContr.isGrounded)
    {

        if (SpaceKeyDownPlayer)
        {
            moveDirection.y = jumpSpeed * Time.deltaTime;
        }
    }
}

public void MovementFinalizer()
{
    moveDirection.y -= gravity * Time.deltaTime;
    CharContr.Move(moveDirection);
}

public void CameraAndListenerController()
{
    if (gameObject.name == ntwmng.Playername)
    {
        if (playercam.enabled == false)
        {
            playercam.enabled = true;
        }
        if (AudioListener.enabled == false)
        {
            AudioListener.enabled = true;
        }
    }
    else
    {
        if (playercam.enabled == true)
        {
            playercam.enabled = false;
        }
        if (AudioListener.enabled == true)
        {
            AudioListener.enabled = false;
        }
    }
}

public void SendKeysToServer()
{
    NetworkStream NtwrkStrm = ServerConnection.GetStream();
    IFormatter Formatter = new BinaryFormatter();

    foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
    {
        if(Input.GetKeyDown(kcode))
        {
            string type = "Movement Update Key Down";
            string kycode = Convert.ToString(kcode);
            //Debug.Log(kycode);
            Formatter.Serialize(NtwrkStrm, type);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, ntwmng.Playername);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, kycode);
            NtwrkStrm.Flush();
        }else
        if(Input.GetKeyUp(kcode))
        {
            string type = "Movement Update Key Up";
            string kycode = Convert.ToString(kcode);
            //Debug.Log(kycode);
            Formatter.Serialize(NtwrkStrm, type);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, ntwmng.Playername);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, kycode);
            NtwrkStrm.Flush();
        }
    }
}

public void MovementControllerClones()
{
    if (CharContr.isGrounded)
    {
        moveDirection = new Vector3(0, 0, 0);

        if (wKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(0, 0, speed * Time.deltaTime);
        }
        if (sKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(0, 0, -speed * Time.deltaTime);
        }
        if (qKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(-speed * Time.deltaTime, 0, 0);
        }
        if (eKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(speed * Time.deltaTime, 0, 0);
        }

        moveDirection = transform.TransformDirection(moveDirection);
        //moveDirection *= speed;
    }

}

public void RotationControllerClones()
{
    if (dKeyDownClone)
    {
        transform.Rotate(0, RotationSpeed * Time.deltaTime, 0);
    }
    if (aKeyDownClone)
    {
        transform.Rotate(0, -RotationSpeed * Time.deltaTime, 0);
    }
}

public void JumpControllerClones()
{
    if (CharContr.isGrounded)
    {

        if (SpaceKeyDownClone)
        {
            moveDirection.y = jumpSpeed* Time.deltaTime;
        }
    }
}

public void MovementFinalizerClones()
{
    moveDirection.y -= gravity * Time.deltaTime;
    CharContr.Move(moveDirection);
}

public void CloneKeyUpdater(string type,string kcode)
{
    //Debug.Log("Key " + kcode + " Clone Updating");
    if (type == "Movement Update Key Down")
    {
        if (kcode == "W")
        {
            wKeyDownClone = true;
        }
        if (kcode == "A")
        {
            aKeyDownClone = true;
        }
        if (kcode == "D")
        {
            dKeyDownClone = true;
        }
        if (kcode == "S")
        {
            sKeyDownClone = true;
        }
        if (kcode == "Q")
        {
            qKeyDownClone = true;
        }
        if (kcode == "E")
        {
            eKeyDownClone = true;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownClone = true;
        }
    }
    else if (type == "Movement Update Key Up")
    {
        if (kcode == "W")
        {
            wKeyDownClone = false;
        }
        if (kcode == "A")
        {
            aKeyDownClone = false;
        }
        if (kcode == "D")
        {
            dKeyDownClone = false;
        }
        if (kcode == "S")
        {
            sKeyDownClone = false;
        }
        if (kcode == "Q")
        {
            qKeyDownClone = false;
        }
        if (kcode == "E")
        {
            eKeyDownClone = false;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownClone = false;
        }
    }
}

public void PlayerKeyUpdater(string type, string kcode)
{
    //Debug.Log("Key down " + kcode + " Updating");
    if (type == "Movement Update Key Down")
    {
        if (kcode == "W")
        {
            wKeyDownPlayer = true;
        }
        if (kcode == "A")
        {
            aKeyDownPlayer = true;
        }
        if (kcode == "D")
        {
            dKeyDownPlayer = true;
        }
        if (kcode == "S")
        {
            sKeyDownPlayer = true;
        }
        if (kcode == "Q")
        {
            qKeyDownPlayer = true;
        }
        if (kcode == "E")
        {
            eKeyDownPlayer = true;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownPlayer = true;
        }
    }
    else if (type == "Movement Update Key Up")
    {
        if (kcode == "W")
        {
            wKeyDownPlayer = false;
        }
        if (kcode == "A")
        {
            aKeyDownPlayer = false;
        }
        if (kcode == "D")
        {
            dKeyDownPlayer = false;
        }
        if (kcode == "S")
        {
            sKeyDownPlayer = false;
        }
        if (kcode == "Q")
        {
            qKeyDownPlayer = false;
        }
        if (kcode == "E")
        {
            eKeyDownPlayer = false;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownPlayer = false;
        }
    }
}
</code>```

Any help will be muchly appreciated. :)

Edit:
so i have figured out a equation that i am using to try and mimic player movement, as of right now it only work between 0 and 90 degrees, just tell i get it exact. the equation comes out really close, but is just a tiny bit off. Any suggestions? Also, this is running on client side, no server influence, so that I can get the math to an exact. The math comes out about 1 unit per second slower then the players current position. Basically after pressing w for 1 second with speed = 20 the math comes out to 19 and actual position is 20.

here is code

```<code>    if (CharContr.velocity != Vector3.zero)//checks if the player is moving
    {
        if (rotation < 90f && rotation > 0f) // makes sure the rotation is 0-90
        {
            percent = (100 / (90 / rotation)) / 100; // gets the percent
            x = x + (percent * speed * Time.deltaTime); //adds to current position multiplied by speed and delta time
            invertPercent = 1 - percent; //gets the percent for z
            z = z + (invertPercent * speed * Time.deltaTime); // adds and stuff again
        }
</code>```

答:
Sending keycode to server and syncronize position based on bool is not best practice.

The good practice would be, sending 3 float value of x, y, and z position to the server, then broadcast it to other player.
so other player has the exact position without approximation

Sorry if i answer in wrong place, because i don't have enough rep to make comment.

Body:
Question: How do i go about doing a equation on a c# console for where the player should be based on player input from unity.

To explain farther, the client is ran in unity and the server is a c# console application. When the player presses a movement key ex. (w, witch moves the player forward based on local position, as to always make the player move forward) it sends to the server that player pressed w, and then the sever responds and tells the client that it pressed w, changing the player w is pressed bool to true. Then the character moves.

Essentially I am trying to figure out how to make a equation that will do what unity does, but without a transform, or even how the transform works so that i can apply it to the server side.

Here is the client side code:

 private void Update()
{
    SendKeysToServer();
    PlayerController();
    PlayerPositionUpdateChecker();
}

public void PlayerController()
{
    if (gameObject.name == ntwmng.Playername)
    {
        MovementControllerPlayer();
        JumpControllerPlayer();
        RotationControllerPlayer();
        MovementFinalizer();
    }
    else
    {
        MovementControllerClones();
        JumpControllerClones();
        RotationControllerClones();
        MovementFinalizerClones();
    }
}

public void MovementControllerPlayer()
{
    if (CharContr.isGrounded)
    {
        moveDirection = new Vector3(0, 0, 0);

        if (wKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(0, 0, speed * Time.deltaTime);
        }
        if (sKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(0, 0, -speed * Time.deltaTime);
        }
        if (qKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(-speed * Time.deltaTime, 0, 0);
        }
        if (eKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(speed * Time.deltaTime, 0, 0);
        }

        moveDirection = transform.TransformDirection(moveDirection);
        //moveDirection *= speed;
    }

}

public void RotationControllerPlayer()
{
    if (dKeyDownPlayer)
    {
        transform.Rotate(0, RotationSpeed * Time.deltaTime, 0);
    }
    if(aKeyDownPlayer)
    {
        transform.Rotate(0, -RotationSpeed * Time.deltaTime, 0);
    }
}

public void JumpControllerPlayer()
{
    if (CharContr.isGrounded)
    {

        if (SpaceKeyDownPlayer)
        {
            moveDirection.y = jumpSpeed * Time.deltaTime;
        }
    }
}

public void MovementFinalizer()
{
    moveDirection.y -= gravity * Time.deltaTime;
    CharContr.Move(moveDirection);
}

public void CameraAndListenerController()
{
    if (gameObject.name == ntwmng.Playername)
    {
        if (playercam.enabled == false)
        {
            playercam.enabled = true;
        }
        if (AudioListener.enabled == false)
        {
            AudioListener.enabled = true;
        }
    }
    else
    {
        if (playercam.enabled == true)
        {
            playercam.enabled = false;
        }
        if (AudioListener.enabled == true)
        {
            AudioListener.enabled = false;
        }
    }
}

public void SendKeysToServer()
{
    NetworkStream NtwrkStrm = ServerConnection.GetStream();
    IFormatter Formatter = new BinaryFormatter();

    foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
    {
        if(Input.GetKeyDown(kcode))
        {
            string type = "Movement Update Key Down";
            string kycode = Convert.ToString(kcode);
            //Debug.Log(kycode);
            Formatter.Serialize(NtwrkStrm, type);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, ntwmng.Playername);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, kycode);
            NtwrkStrm.Flush();
        }else
        if(Input.GetKeyUp(kcode))
        {
            string type = "Movement Update Key Up";
            string kycode = Convert.ToString(kcode);
            //Debug.Log(kycode);
            Formatter.Serialize(NtwrkStrm, type);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, ntwmng.Playername);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, kycode);
            NtwrkStrm.Flush();
        }
    }
}

public void MovementControllerClones()
{
    if (CharContr.isGrounded)
    {
        moveDirection = new Vector3(0, 0, 0);

        if (wKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(0, 0, speed * Time.deltaTime);
        }
        if (sKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(0, 0, -speed * Time.deltaTime);
        }
        if (qKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(-speed * Time.deltaTime, 0, 0);
        }
        if (eKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(speed * Time.deltaTime, 0, 0);
        }

        moveDirection = transform.TransformDirection(moveDirection);
        //moveDirection *= speed;
    }

}

public void RotationControllerClones()
{
    if (dKeyDownClone)
    {
        transform.Rotate(0, RotationSpeed * Time.deltaTime, 0);
    }
    if (aKeyDownClone)
    {
        transform.Rotate(0, -RotationSpeed * Time.deltaTime, 0);
    }
}

public void JumpControllerClones()
{
    if (CharContr.isGrounded)
    {

        if (SpaceKeyDownClone)
        {
            moveDirection.y = jumpSpeed* Time.deltaTime;
        }
    }
}

public void MovementFinalizerClones()
{
    moveDirection.y -= gravity * Time.deltaTime;
    CharContr.Move(moveDirection);
}

public void CloneKeyUpdater(string type,string kcode)
{
    //Debug.Log("Key " + kcode + " Clone Updating");
    if (type == "Movement Update Key Down")
    {
        if (kcode == "W")
        {
            wKeyDownClone = true;
        }
        if (kcode == "A")
        {
            aKeyDownClone = true;
        }
        if (kcode == "D")
        {
            dKeyDownClone = true;
        }
        if (kcode == "S")
        {
            sKeyDownClone = true;
        }
        if (kcode == "Q")
        {
            qKeyDownClone = true;
        }
        if (kcode == "E")
        {
            eKeyDownClone = true;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownClone = true;
        }
    }
    else if (type == "Movement Update Key Up")
    {
        if (kcode == "W")
        {
            wKeyDownClone = false;
        }
        if (kcode == "A")
        {
            aKeyDownClone = false;
        }
        if (kcode == "D")
        {
            dKeyDownClone = false;
        }
        if (kcode == "S")
        {
            sKeyDownClone = false;
        }
        if (kcode == "Q")
        {
            qKeyDownClone = false;
        }
        if (kcode == "E")
        {
            eKeyDownClone = false;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownClone = false;
        }
    }
}

public void PlayerKeyUpdater(string type, string kcode)
{
    //Debug.Log("Key down " + kcode + " Updating");
    if (type == "Movement Update Key Down")
    {
        if (kcode == "W")
        {
            wKeyDownPlayer = true;
        }
        if (kcode == "A")
        {
            aKeyDownPlayer = true;
        }
        if (kcode == "D")
        {
            dKeyDownPlayer = true;
        }
        if (kcode == "S")
        {
            sKeyDownPlayer = true;
        }
        if (kcode == "Q")
        {
            qKeyDownPlayer = true;
        }
        if (kcode == "E")
        {
            eKeyDownPlayer = true;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownPlayer = true;
        }
    }
    else if (type == "Movement Update Key Up")
    {
        if (kcode == "W")
        {
            wKeyDownPlayer = false;
        }
        if (kcode == "A")
        {
            aKeyDownPlayer = false;
        }
        if (kcode == "D")
        {
            dKeyDownPlayer = false;
        }
        if (kcode == "S")
        {
            sKeyDownPlayer = false;
        }
        if (kcode == "Q")
        {
            qKeyDownPlayer = false;
        }
        if (kcode == "E")
        {
            eKeyDownPlayer = false;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownPlayer = false;
        }
    }
}

Any help will be muchly appreciated. :)

Edit:
so i have figured out a equation that i am using to try and mimic player movement, as of right now it only work between 0 and 90 degrees, just tell i get it exact. the equation comes out really close, but is just a tiny bit off. Any suggestions? Also, this is running on client side, no server influence, so that I can get the math to an exact. The math comes out about 1 unit per second slower then the players current position. Basically after pressing w for 1 second with speed = 20 the math comes out to 19 and actual position is 20.

here is code

    if (CharContr.velocity != Vector3.zero)//checks if the player is moving
    {
        if (rotation < 90f && rotation > 0f) // makes sure the rotation is 0-90
        {
            percent = (100 / (90 / rotation)) / 100; // gets the percent
            x = x + (percent * speed * Time.deltaTime); //adds to current position multiplied by speed and delta time
            invertPercent = 1 - percent; //gets the percent for z
            z = z + (invertPercent * speed * Time.deltaTime); // adds and stuff again
        }


问:
Woocommerce: Add Price Suffix incl. Hyperlink
is it possible to add a Hyperlink to the Price Suffix of WooCommerce?

To add a Suffix, I used this Code

```<code>add_filter( 'woocommerce_get_price_html', 'custom_price_suffix', 100, 2 );

function custom_price_suffix( $price, $product ){
        $price = $price . 'zzgl. Versandkosten' ;
            return apply_filters( 'woocommerce_get_price', $price );
}
</code>```

To Show the Text "zzgl. Versandkosten". I want to add a Hyperlink to "zzgl. Versandkosten" where Customers can read a PDF Documentation about our Shipping prices.

Thanks

Mauro

答:
Can you try this?</p>

```<code>    add_filter( 'woocommerce_get_price_html', 'custom_price_suffix', 100, 2 );

function custom_price_suffix( $price, $product ){
        $price = '<a href="link">' . $price . 'zzgl. Versandkosten </a>' ;
            return apply_filters( 'woocommerce_get_price', $price );
}
</code>```

Body:
is it possible to add a Hyperlink to the Price Suffix of WooCommerce?

To add a Suffix, I used this Code

add_filter( 'woocommerce_get_price_html', 'custom_price_suffix', 100, 2 );

function custom_price_suffix( $price, $product ){
        $price = $price . 'zzgl. Versandkosten' ;
            return apply_filters( 'woocommerce_get_price', $price );
}

To Show the Text "zzgl. Versandkosten". I want to add a Hyperlink to "zzgl. Versandkosten" where Customers can read a PDF Documentation about our Shipping prices.

Thanks

Mauro

Body:
Can you try this?

    add_filter( 'woocommerce_get_price_html', 'custom_price_suffix', 100, 2 );

function custom_price_suffix( $price, $product ){
        $price = '<a href="link">' . $price . 'zzgl. Versandkosten </a>' ;
            return apply_filters( 'woocommerce_get_price', $price );
}


问:
objectdatasource question
For the moment, I'm binding my gridviews by calling a linq query that returns a list collection of objects MyObject. In my gridview, if I'm using a boundfield I set its Datafield property to the name of the property of MyObject and if I'm using an itemtemplate I work with Eval. In my code behind, I have

```<code>MyGridview.DataSource = MyListOfMyObject;
MyGridview.DataBind();
</code>```

All seems to work fine.

What's the purpose of adding an ObjectDataSource control in the aspx file. What does it do extra?

Thanks.

PS: I'm new to the .net framework and I'm still figuring things out.

答:
From here:

ObjectDataSource belongs to the family
  of data source controls in ASP.NET,
  which enables a declarative
  databinding model against a variety of
  underlying data stores, such as SQL
  databases or XML. Most data source
  controls encourage a two-tiered
  application architecture, where the
  presentation layer (the page)
  interacts directly with the backend
  data provider.

However, it is also
  common for page developers to
  encapsulate data retrieval (and
  optionally business logic) into a
  component object, introducing an
  additional layer between the
  presentation page and data provider.
  The ObjectDataSource control allows
  developers to structure their
  applications using this traditional
  three-tiered architecture and still
  take advantage of the ease-of-use
  benefits of the declarative
  databinding model in ASP.NET.

ContentLicense: CC BY-SA 2.5

Title: objectdatasource question

Body:
For the moment, I'm binding my gridviews by calling a linq query that returns a list collection of objects MyObject. In my gridview, if I'm using a boundfield I set its Datafield property to the name of the property of MyObject and if I'm using an itemtemplate I work with Eval. In my code behind, I have

MyGridview.DataSource = MyListOfMyObject;
MyGridview.DataBind();

All seems to work fine.

What's the purpose of adding an ObjectDataSource control in the aspx file. What does it do extra?

Thanks.

PS: I'm new to the .net framework and I'm still figuring things out.


问:
Increase index of a form's input field's name attribute in a dynamic form
Suppose I have this form with indexed input fields username and level:

```<code><form>
 <table>
  <tr class="trToClone">
    <td>
      <label>Username:</label>
      <input type="text" name="username[0]" />
    </td>
    <td>
      <label>Level:</label>
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>
    </td>
    <td><input type="button" class="addField" value="Add" /></td>
  </tr>
 </table>
</form>
</code>```

The row can be repeated using this jQuery:

```<code>$("input.addField").on('click', function() {
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone();
  $clone.find(':text').val('');
  $tr.after($clone);
});
</code>```

Now for every subsequent row I add, I want to increase the indices of the name attribute (i.e. username[1],level[1]; username[2],level[2]; and so on...). How can I do this? I've looked for possible solutions, but to no avail.

答:
For adding the name attribute you first need to find the index of current row and then you can add 1 to the index and again update the name attribute for both text and select list. Try with the code below-

Note- You should also hide the add button from previous row and bind the click function again for the newly cloned row.

 $("input.addField").on('click', function() {
      var $tr = $(this).closest('.trToClone');
      var $clone = $tr.clone();
      var lastIndexName= $clone.find(':text').attr("name").split('[');
      var lastIndex=parseInt(lastIndexName[1].substring(0,1));
      var updatedNameValue="username["+(lastIndex+1)+"]";
      $clone.find(':text').attr("name",updatedNameValue);
      $clone.find(':text').val('');
      $clone.find('select').attr("name","level["+(lastIndex+1)+"]")
      $tr.after($clone);
    });```

Body:
Suppose I have this form with indexed input fields username and level:

<form>

      Username:
      <input type="text" name="username[0]" />

      Level:
      <select name="level[0]">
        <option value="">---</option>
        <option value="a">A</option>
        <option value="b">B</option>
        <option value="c">C</option>
      </select>

    <input type="button" class="addField" value="Add" />

</form>

The row can be repeated using this jQuery:

$("input.addField").on('click', function() {
  var $tr = $(this).closest('.trToClone');
  var $clone = $tr.clone();
  $clone.find(':text').val('');
  $tr.after($clone);
});

Now for every subsequent row I add, I want to increase the indices of the name attribute (i.e. username[1],level[1]; username[2],level[2]; and so on...). How can I do this? I've looked for possible solutions, but to no avail.


问:
Apply different style to last x characters of input field
I am faced with a task as of current I am not sure on how to complete. Essentially, is there any way I could go about getting the last x characters of an  field to display differently from the rest of the field?

Something to the effect of this, assuming this was a typed input into an <input> field:
"TheLast6LettersOfThisShouldBeBigger"

That would be the intended effect. The only potential approach I could think of for completing this is to use two separate input fields and always have the last x characters in the second input styled differently. This would, however, provide problems with user interaction (backspacing at the front of the second input field would result in no previous character being deleted).

Any ideas or thoughts?

Update: I forget to mention before, this is intended to be a dynamic thing as the user is typing.

答:
I believe you won't be able to use a classic textarea cause you can't have styles inside it. I gave it a try with a contenteditable div. No jQuery involved, works live as you type.

const charLimit = 6; // replace by numbers of characters you want

const txt = document.getElementById('myInput');

txt.addEventListener('keyup', function(e) {
  const value = txt.textContent;
  const endString = value.length > charLimit ?
        value.substr(value.length - charLimit) :
        value.substr(-value.length);
  const firstString = value.slice(0, -charLimit);

  txt.innerHTML = firstString + '' + endString + '';
  setEndOfContenteditable(txt);
});

// From https://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity/3866442#3866442
function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    {
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  font-family: sans-serif;
}

#myInput {
  border: 1px solid #ccc;
  padding: 10px;
}

#myInput:focus {
  outline: none;
  border: 1px solid #333;
}

#myInput > span {
  font-weight: bold;
}</code>```

```

Body:
I believe you won't be able to use a classic textarea cause you can't have styles inside it. I gave it a try with a contenteditable div. No jQuery involved, works live as you type.

const charLimit = 6; // replace by numbers of characters you want

const txt = document.getElementById('myInput');

txt.addEventListener('keyup', function(e) {
  const value = txt.textContent;
  const endString = value.length > charLimit ?
        value.substr(value.length - charLimit) :
        value.substr(-value.length);
  const firstString = value.slice(0, -charLimit);

  txt.innerHTML = firstString + '<span>' + endString + '</span>';
  setEndOfContenteditable(txt);
});

// From https://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity/3866442#3866442
function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    {
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}

* {
  font-family: sans-serif;
}

#myInput {
  border: 1px solid #ccc;
  padding: 10px;
}

#myInput:focus {
  outline: none;
  border: 1px solid #333;
}

#myInput > span {
  font-weight: bold;
}

<div id="myInput" contenteditable></div>


问:
Append for array of maps raplaces all previous array items on the latest one
The question may sound very stupid but I really don't understand what's wrong.

I want to create an array of maps like this:

```<code>values := make([]map[string]string, 0)
</code>```

Then I create some map:

```<code>row := make(map[string]string)
row["item1"] = "value1"
row["item2"] = "value2"
</code>```

Then append it to the array:

```<code>values = append(values, row)
</code>```

Printing values now gives:

```<code>[map[item1:value1 item2:value2]]
</code>```

Do the same using some other values:

```<code>row["item1"] = "value3"
row["item2"] = "value4"
values = append(values, row)
</code>```

Now printing values gives:

```<code>[map[item1:value3 item2:value4] map[item1:value3 item2:value4]]
</code>```

So the first array item = the second one.
What can cause this?

Full code:

```<code>package main

import "fmt"

func main() {
  values := make([]map[string]string, 0)
  row := make(map[string]string)
  row["item1"] = "value1"
  row["item2"] = "value2"
  values = append(values, row)
  fmt.Println(values)
  row["item1"] = "value3"
  row["item2"] = "value4"
  values = append(values, row)
  fmt.Println(values)
}
</code>```

答:
Got in a minute after posting the question...

Looks like append doesn't copy map, just inserts the same.. So recreating the map each time I need to append it helps:

```<code>package main

import "fmt"

func main() {
  values := make([]map[string]string, 0)
  row := make(map[string]string)
  row["item1"] = "value1"
  row["item2"] = "value2"
  values = append(values, row)
  fmt.Println(values)
  row2 := make(map[string]string)
  row2["item1"] = "value3"
  row2["item2"] = "value4"
  values = append(values, row2)
  fmt.Println(values)
}
</code>```

Body:
The question may sound very stupid but I really don't understand what's wrong.

I want to create an array of maps like this:

values := make([]map[string]string, 0)

Then I create some map:

row := make(map[string]string)
row["item1"] = "value1"
row["item2"] = "value2"

Then append it to the array:

values = append(values, row)

Printing values now gives:

[map[item1:value1 item2:value2]]

Do the same using some other values:

row["item1"] = "value3"
row["item2"] = "value4"
values = append(values, row)

Now printing values gives:

[map[item1:value3 item2:value4] map[item1:value3 item2:value4]]

So the first array item = the second one.
What can cause this?

Full code:

package main

import "fmt"

func main() {
  values := make([]map[string]string, 0)
  row := make(map[string]string)
  row["item1"] = "value1"
  row["item2"] = "value2"
  values = append(values, row)
  fmt.Println(values)
  row["item1"] = "value3"
  row["item2"] = "value4"
  values = append(values, row)
  fmt.Println(values)
}

Body:
Got in a minute after posting the question...

Looks like append doesn't copy map, just inserts the same.. So recreating the map each time I need to append it helps:

package main

import "fmt"

func main() {
  values := make([]map[string]string, 0)
  row := make(map[string]string)
  row["item1"] = "value1"
  row["item2"] = "value2"
  values = append(values, row)
  fmt.Println(values)
  row2 := make(map[string]string)
  row2["item1"] = "value3"
  row2["item2"] = "value4"
  values = append(values, row2)
  fmt.Println(values)
}


问:
How to add all of the migrations/ to git .gitignore file in django?
In my Django project, I have many migrations directory, I want to add to my .gitignore file:

Because they are under each app directory, I do not want to add every one.

How can I add all the migrations directories in it?

Now in it only like this:

```<code>.idea/
</code>```

答: You can add "**/migrations/*" to your .gitignore file, this will add all folders and it's contents called migrations to git ignore. More informations here</p>

Body:
In my Django project, I have many migrations directory, I want to add to my .gitignore file:

Because they are under each app directory, I do not want to add every one.

How can I add all the migrations directories in it?

Now in it only like this:

.idea/


问:
Office Fabric UI - onClick IconButton does not working when I Package-Solution
I have the following table:

Rows are drawn in a dynamic way and also the buttons to delete each row.

```<code><span className="ms-Table-cell">
  <div>
    <IconButton
      onClick= { this._removeItemFromDetail }
      id={ detail.Id.toString() }
      iconProps={ { iconName: 'Cancel' } }
      title='Delete' />
  </div>
</span>

private _removeItemFromDetail(e) {
    console.log("e.target",e.target);
}
</code>```

The issue is that every time I click on a delete button in console it shows me:

So, I can't access to Button Id Property, but this only happens when I have published the Webpart.
Does anyone know how it can be fixed?

Thank you!

答:
In the onClick of the IconButton you could write the following;

```<code>onClick={() => {this._removeItemFromDetail(detail.Id)}}
</code>```

This should allow you to accept an ID as a parameter. If you still need the "event" in the _removeItemFromDetail method you can add it as follows;

```<code>onClick={(event) => {this._removeItemFromDetail(event, detail.Id)}}
</code>```

which would mean your method would look like this;

```<code>private _removeItemFromDetail(event, itemId) {
    console.log("itemId: " + itemId);
}
</code>```

Body:
I have the following table:

Rows are drawn in a dynamic way and also the buttons to delete each row.

    <IconButton
      onClick= { this._removeItemFromDetail }
      id={ detail.Id.toString() }
      iconProps={ { iconName: 'Cancel' } }
      title='Delete' />

private _removeItemFromDetail(e) {
    console.log("e.target",e.target);
}

The issue is that every time I click on a delete button in console it shows me:

So, I can't access to Button Id Property, but this only happens when I have published the Webpart.
Does anyone know how it can be fixed?

Thank you!

Body:
In the onClick of the IconButton you could write the following;

onClick={() => {this._removeItemFromDetail(detail.Id)}}

This should allow you to accept an ID as a parameter. If you still need the "event" in the _removeItemFromDetail method you can add it as follows;

onClick={(event) => {this._removeItemFromDetail(event, detail.Id)}}

which would mean your method would look like this;

private _removeItemFromDetail(event, itemId) {
    console.log("itemId: " + itemId);
}


问:
Add an array to a SQL database (java)
I want to add a list of values of a variable size in a row of a single SQL database. As i understood from the following topic, it's not possible with a List<> object:

How to add a list to a SQL database (using java)

But it works with a String, which is basically an object containing an array of char:

```<code>ContentValues values = new ContentValues();
values.put(MyDB.COLUMN_NAME, contact.getName());
mDb.insert(MyDB.TABLE_CONTACTS, null, values);
</code>```

So is it possible to add an array of an other type (like double[] myList , possibly contained in an object) in the database, the same way as we added TEXT?

I am using java on Android Studio.

答:
I don't think its possible but you don't need that.

you cant save objects in Java and they save as a text so you can put that in the field as a string and read that in your java again.
but the saving string is meaningless and you have to read it with java or do some scripting.

Title: Add an array to a SQL database (java)

Body:
I want to add a list of values of a variable size in a row of a single SQL database. As i understood from the following topic, it's not possible with a List<> object:

How to add a list to a SQL database (using java)

But it works with a String, which is basically an object containing an array of char:

ContentValues values = new ContentValues();
values.put(MyDB.COLUMN_NAME, contact.getName());
mDb.insert(MyDB.TABLE_CONTACTS, null, values);

So is it possible to add an array of an other type (like double[] myList , possibly contained in an object) in the database, the same way as we added TEXT?

I am using java on Android Studio.


问:
Why does delete method is not working in ruby
The destroy method doesn't work but i get redirected to index page but record is not deleted.

HTML.erb link:

```<code><%= link_to "Delete", posts_path(@post), method: :delete, data: {confirm: 'are you sure?'},:class => 'btn btn-danger' %>
</code>```

Controller:

```<code>def destroy
  @post = Post.find(params[:id])
  @post.destroy
  redirect_to posts_path
end
</code>```

答:
posts_path is the path to index action. Change posts_path to post_path in the delete link tag to route to destroy action.

```<code><%= link_to "Delete", post_path(@post), method: :delete, data: {confirm: 'are you sure?'},:class => 'btn btn-danger' %>
</code>```

Body:
The destroy method doesn't work but i get redirected to index page but record is not deleted.

HTML.erb link:

<%= link_to "Delete", posts_path(@post), method: :delete, data: {confirm: 'are you sure?'},:class => 'btn btn-danger' %>

Controller:

def destroy
  @post = Post.find(params[:id])
  @post.destroy
  redirect_to posts_path
end

Body:
posts_path is the path to index action. Change posts_path to post_path in the delete link tag to route to destroy action.

<%= link_to "Delete", post_path(@post), method: :delete, data: {confirm: 'are you sure?'},:class => 'btn btn-danger' %>


问:
css adding delimeters to nav
I have a navigation menu that is basically a list of links that wraps on to multiple with n number of links on each dependent of length of link etc,

Above is what I am trying to recreate, as you can the last link on each line does not have a delimeter, is it possible to replicate this? Currently I have managed to get a delimeter between each link and at the end of every row.

I have no control over the HTML other wise I would loop through the links and only display x number of links on each line, I could then do nth-child() however I will never know how many links will be shown on each line.

Here is a link to a test, as you can last link on each line has a border-right ideally I would want to turn these off if there is no sibling on the same line.

https://jsbin.com/givaquyozu/edit?html,css,output

答:
Given we don't see all markup, you could use the same trick many framework does when they add a margin between elements, where they have overflow set to hidden on the parent and then move the element with a negative margin.

The great with this, it is transparent to its background, in case of using i.e. an image, and here using the pseudo ::before for the delimiter.

Stack snippet

.parent {
  overflow: hidden;
}
.parent ul {
  width: 381px;
  padding: 0;
  margin-left: -5px;
}
.parent ul li {
  display: inline-block;
}
.parent ul li::before {
  content: '|';
  padding-right: 5px;
}
a {
  display: inline-block;
  padding-right: 8px;
  padding-left: 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='parent'>
  <ul>
    <li>Link nr 1</li>
    <li>Link nr 2</li>
    <li>Link nr 3</li>
    <li>Link nr 4</li>
    <li>Link nr 5</li>
    <li>Link nr 6</li>
    <li>Link nr 7</li>
  </ul>
</div></code>```

Update

Even if you don't know how many links per row, you can still loop through them with a script, where all items but the first on each row get a class

Codepen demo

```<code>(function ($) {
  //  preload object array to gain performance
  var $items = $('.parent ul li');

  //  run at resize
  $( window ).resize(function() {
    $.fn.setDelimit(false,0);
  });

  $.fn.setDelimit = function(nl,idx) {

    $items.each(function(i, obj) {

      //  did top value changed, then new row
      if ($items.eq(i - 1).offset().top != $(obj).offset().top) {
        nl = true;
      }

      if (!nl) {
        $(obj).addClass('delimiter');
      } else {
        // reset
        $(obj).removeClass('delimiter');
      }
      nl = false;

    });

  }

  //  run at load
  $.fn.setDelimit(true,0);

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

Title: css adding delimeters to nav

Body:
Given we don't see all markup, you could use the same trick many framework does when they add a margin between elements, where they have overflow set to hidden on the parent and then move the element with a negative margin.

The great with this, it is transparent to its background, in case of using i.e. an image, and here using the pseudo ::before for the delimiter.

Stack snippet

.parent {
  overflow: hidden;
}
.parent ul {
  width: 381px;
  padding: 0;
  margin-left: -5px;
}
.parent ul li {
  display: inline-block;
}
.parent ul li::before {
  content: '|';
  padding-right: 5px;
}
a {
  display: inline-block;
  padding-right: 8px;
  padding-left: 8px;
}

<div class='parent'>
  <ul>
    <li><a href='#'>Link nr 1</a></li>
    <li><a href='#'>Link nr 2</a></li>
    <li><a href='#'>Link nr 3</a></li>
    <li><a href='#'>Link nr 4</a></li>
    <li><a href='#'>Link nr 5</a></li>
    <li><a href='#'>Link nr 6</a></li>
    <li><a href='#'>Link nr 7</a></li>
  </ul>
</div>

Update

Even if you don't know how many links per row, you can still loop through them with a script, where all items but the first on each row get a class

Codepen demo

(function ($) {
  //  preload object array to gain performance
  var $items = $('.parent ul li');

  //  run at resize
  $( window ).resize(function() {
    $.fn.setDelimit(false,0);
  });

  $.fn.setDelimit = function(nl,idx) {

    $items.each(function(i, obj) {

      //  did top value changed, then new row
      if ($items.eq(i - 1).offset().top != $(obj).offset().top) {
        nl = true;
      }

      if (!nl) {
        $(obj).addClass('delimiter');
      } else {
        // reset
        $(obj).removeClass('delimiter');
      }
      nl = false;

    });

  }

  //  run at load
  $.fn.setDelimit(true,0);

}(jQuery));


问:
How do I echo the dns_name's string from the ansible elb_application_lb_facts module?
I have part of a JSON object below in my debug which I got via elb_application_lb_facts module. How do I echo the dns_name's string from the object below ?

I can get narrow the output to load_balancers using this JINJA2 {{msg.load_balancers}}

Complete msg JSON object:

```<code>TASK [debug] ***********************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": {
        "changed": false,
        "failed": false,
        "load_balancers": [
            {
                "access_logs_s3_enabled": "true",
                "availability_zones": [
                    {
                        "subnet_id": "xyz",
                        "zone_name": "xyz"
                    },
                    {
                        "subnet_id": "xyz",
                        "zone_name": "xyz"
                    }
                ],
                "canonical_hosted_zone_id": "xyz",
                "created_time": "2017-11-15T10:54:27.230000+00:00",
                "deletion_protection_enabled": "true",
                "dns_name": "myelb.elb.amazonaws.com",
</code>```

答:
For a string with the value of the first element:

```<code>{{ msg.load_balancers[0].dns_name }}"
</code>```

For a ist:

```<code>{{ msg.load_balancers | map (attribute='dns_name') | list }}"
</code>```

Body:
I have part of a JSON object below in my debug which I got via elb_application_lb_facts module. How do I echo the dns_name's string from the object below ?

I can get narrow the output to load_balancers using this JINJA2 {{msg.load_balancers}}

Complete msg JSON object:

TASK [debug] ***********************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": {
        "changed": false,
        "failed": false,
        "load_balancers": [
            {
                "access_logs_s3_enabled": "true",
                "availability_zones": [
                    {
                        "subnet_id": "xyz",
                        "zone_name": "xyz"
                    },
                    {
                        "subnet_id": "xyz",
                        "zone_name": "xyz"
                    }
                ],
                "canonical_hosted_zone_id": "xyz",
                "created_time": "2017-11-15T10:54:27.230000+00:00",
                "deletion_protection_enabled": "true",
                "dns_name": "myelb.elb.amazonaws.com",

Body:
For a string with the value of the first element:

{{ msg.load_balancers[0].dns_name }}"

For a ist:

{{ msg.load_balancers | map (attribute='dns_name') | list }}"


问:
MariaDB 10.2 Xtrabackup. /usr//bin/wsrep_sst_xtrabackup-v2 WSREP_SST_OPT_PORT: unbound variable
I just installed a new set of Ubuntu 16.04 nodes which should work as MariaDB 10.2 master-master cluster, using XtraBackup as SST method.

The first node comes up fine with the command galera_new_cluster, but the second node is unable to join the cluster due to the following error :

```<code>Nov 15 10:59:09 mariadb10 mysqld[15664]: 2017-11-15 10:59:09 140259808827136 [Warning] WSREP: Gap in state sequence. Need state transfer.
Nov 15 10:59:09 mariadb10 mysqld[15664]: 2017-11-15 10:59:09 140259416360704 [Note] WSREP: Running: 'wsrep_sst_xtrabackup-v2 --role 'joiner' --address '10.0.0.10' --datadir '/var/lib/mysql/'   --parent '15664' --binlog '/var/log/mysql/mariadb-bin' '
Nov 15 10:59:09 mariadb10 mysqld[15664]: /usr//bin/wsrep_sst_xtrabackup-v2: line 646: WSREP_SST_OPT_PORT: unbound variable
Nov 15 10:59:09 mariadb10 mysqld[15664]: 2017-11-15 10:59:09 140259416360704 [ERROR] WSREP: Failed to read 'ready <addr>' from: wsrep_sst_xtrabackup-v2 --role 'joiner' --address '10.0.0.10' --datadir '/var/lib/mysql/'   --parent '15664' --binlog '/var/log/mysql/mariadb-bin'
Nov 15 10:59:09 mariadb10 mysqld[15664]: #011Read: '(null)'
Nov 15 10:59:09 mariadb10 mysqld[15664]: 2017-11-15 10:59:09 140259416360704 [ERROR] WSREP: Process completed with error: wsrep_sst_xtrabackup-v2 --role 'joiner' --address '10.0.0.10' --datadir '/var/lib/mysql/'   --parent '15664' --binlog '/var/log/mysql/mariadb-bin' : 1 (Operation not permitted)
Nov 15 10:59:09 mariadb10 mysqld[15664]: 2017-11-15 10:59:09 140259808827136 [ERROR] WSREP: Failed to prepare for 'xtrabackup-v2' SST. Unrecoverable.
</code>```

Main issue in this piece of logging is the WSREP_SST_OPT_PORT which is not set.

Looking at the code of /usr/bin/wsrep_sst_xtrabackup-v2 it "include" the /usr/bin/wsrep_sst_common in which the variable can be set in 2 ways.

Using the --port commandline parameter.

Using a port in the --address commandline parameter (ip:port)

Since I have now clue what parameters mariadb is using to fill the command line parameters for the /usr/bin/wsrep_sst_xtrabackup-v2, I also don't know how to let it use the --port or --address with the correct value.

I did already play around with some parameters in the my.cnf for mariadb without any result. The things I tried were :

Adding parameter wsrep_sst_opt_port=4444 to my.cnf. This resulted in an error since the parameter is not supported (but hey.. the best solutions were the result of just trying)

Added ports to the addresses in wsrep_cluster_adress. This was accepted, but did not result in a portnumber being part of the --address parameter.

Added port to the address in wsrep_node_address. This also was accepted, but did also not reuslt in a portnumber in the --address parameter.

As a workaround I did adapt the /usr/bin/wsrep_sst_common and I added the following code (starting after the comment) :

```<code>if [ -n "${WSREP_SST_OPT_ADDR_PORT:-}" ]; then
  if [ -n "${WSREP_SST_OPT_PORT:-}" ]; then
...
  else
    readonly WSREP_SST_OPT_PORT="$WSREP_SST_OPT_ADDR_PORT"
  fi
fi

# Start of the workaround
if [ -z "${WSREP_SST_OPT_PORT:-}" ]; then
  readonly WSREP_SST_OPT_PORT="4444"
fi
# End of the workaround
</code>```

This at least solved my non-starting cluster, but it would still be nice to know how I can let it work without this workaround...

答:
The behaviour you experience is actually a bug in MariaDB 10.2.10 and the MariaDB team has come up with a fix that will most probably be released in the near future

This is the link to the issue on the MariaDB bug tracker:

https://jira.mariadb.org/browse/MDEV-14256

Body:
I just installed a new set of Ubuntu 16.04 nodes which should work as MariaDB 10.2 master-master cluster, using XtraBackup as SST method.

The first node comes up fine with the command galera_new_cluster, but the second node is unable to join the cluster due to the following error :

Nov 15 10:59:09 mariadb10 mysqld[15664]: 2017-11-15 10:59:09 140259808827136 [Warning] WSREP: Gap in state sequence. Need state transfer.
Nov 15 10:59:09 mariadb10 mysqld[15664]: 2017-11-15 10:59:09 140259416360704 [Note] WSREP: Running: 'wsrep_sst_xtrabackup-v2 --role 'joiner' --address '10.0.0.10' --datadir '/var/lib/mysql/'   --parent '15664' --binlog '/var/log/mysql/mariadb-bin' '
Nov 15 10:59:09 mariadb10 mysqld[15664]: /usr//bin/wsrep_sst_xtrabackup-v2: line 646: WSREP_SST_OPT_PORT: unbound variable
Nov 15 10:59:09 mariadb10 mysqld[15664]: 2017-11-15 10:59:09 140259416360704 [ERROR] WSREP: Failed to read 'ready <addr>' from: wsrep_sst_xtrabackup-v2 --role 'joiner' --address '10.0.0.10' --datadir '/var/lib/mysql/'   --parent '15664' --binlog '/var/log/mysql/mariadb-bin'
Nov 15 10:59:09 mariadb10 mysqld[15664]: #011Read: '(null)'
Nov 15 10:59:09 mariadb10 mysqld[15664]: 2017-11-15 10:59:09 140259416360704 [ERROR] WSREP: Process completed with error: wsrep_sst_xtrabackup-v2 --role 'joiner' --address '10.0.0.10' --datadir '/var/lib/mysql/'   --parent '15664' --binlog '/var/log/mysql/mariadb-bin' : 1 (Operation not permitted)
Nov 15 10:59:09 mariadb10 mysqld[15664]: 2017-11-15 10:59:09 140259808827136 [ERROR] WSREP: Failed to prepare for 'xtrabackup-v2' SST. Unrecoverable.

Main issue in this piece of logging is the WSREP_SST_OPT_PORT which is not set.

Looking at the code of /usr/bin/wsrep_sst_xtrabackup-v2 it "include" the /usr/bin/wsrep_sst_common in which the variable can be set in 2 ways.

Using the --port commandline parameter.

Using a port in the --address commandline parameter (ip:port)

Since I have now clue what parameters mariadb is using to fill the command line parameters for the /usr/bin/wsrep_sst_xtrabackup-v2, I also don't know how to let it use the --port or --address with the correct value.

I did already play around with some parameters in the my.cnf for mariadb without any result. The things I tried were :

Adding parameter wsrep_sst_opt_port=4444 to my.cnf. This resulted in an error since the parameter is not supported (but hey.. the best solutions were the result of just trying)

Added ports to the addresses in wsrep_cluster_adress. This was accepted, but did not result in a portnumber being part of the --address parameter.

Added port to the address in wsrep_node_address. This also was accepted, but did also not reuslt in a portnumber in the --address parameter.

As a workaround I did adapt the /usr/bin/wsrep_sst_common and I added the following code (starting after the comment) :

if [ -n "${WSREP_SST_OPT_ADDR_PORT:-}" ]; then
  if [ -n "${WSREP_SST_OPT_PORT:-}" ]; then
...
  else
    readonly WSREP_SST_OPT_PORT="$WSREP_SST_OPT_ADDR_PORT"
  fi
fi

# Start of the workaround
if [ -z "${WSREP_SST_OPT_PORT:-}" ]; then
  readonly WSREP_SST_OPT_PORT="4444"
fi
# End of the workaround

This at least solved my non-starting cluster, but it would still be nice to know how I can let it work without this workaround...


问:
How can I remove a commit on GitHub?
I "accidentally" pushed a commit to GitHub.

Is it possible to remove this commit?

I want to revert my GitHub repository as it was before this commit.

答:
Delete the most recent commit, keeping the work you've done:

```<code>git reset --soft HEAD~1
</code>```

Delete the most recent commit, destroying the work you've done:

```<code>git reset --hard HEAD~1
</code>```

OwnerDisplayName: hectorsq

Title: How can I remove a commit on GitHub?

Body:
Delete the most recent commit, keeping the work you've done:

git reset --soft HEAD~1

Delete the most recent commit, destroying the work you've done:

git reset --hard HEAD~1


问:
How to predefine XSD file name with jaxb2-maven-plugin
I use a code below to generate an XSD from annotated java-classes. Default name of the XSD is always "schema1.xsd". How should I pre-define it using only that plugin? At the moment I use maven-antrun-plugin for file renaming. Plugin manual doesn't contain relevant information.</p>

```<code><plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>jaxb2-maven-plugin</artifactId>
  <version>2.3</version>
  <executions>
    <execution>
      <goals>
        <goal>schemagen</goal>
      </goals>
      <phase>generate-sources</phase>
      <configuration>
        <sources>
          <source>src/main/java/***some package***</source>
        </sources>
        <outputDirectory>${project.build.directory}/generated-sources/schemas</outputDirectory>
      </configuration>
    </execution>
  </executions>
</plugin>
</code>```

答:
Answer has been found. It is not enough to only annotate your java-classes with the JAXB annotations. In the DTO package should exist file "package-info.java" with the following content:

```<code>@XmlSchema(namespace = "http://your-namespace")
package com.your.package;

import javax.xml.bind.annotation.XmlSchema;
</code>```

And the plugin declaration should look like this:

```<code><plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>jaxb2-maven-plugin</artifactId>
  <version>2.3</version>
  <executions>
    <execution>
      <goals>
        <goal>schemagen</goal>
      </goals>
      <phase>generate-sources</phase>
    </execution>
  </executions>
  <configuration>
    <sources>
      <source>src/main/java/com/your/package</source>
    </sources>
    <outputDirectory>${project.build.directory}/generated-sources/schemas</outputDirectory>
    <transformSchemas>
      <transformSchema>
        <uri>http://your-namespace</uri>
        <toFile>your-namespace.xsd</toFile>
      </transformSchema>
    </transformSchemas>
  </configuration>
</plugin>
</code>```

Body:
I use a code below to generate an XSD from annotated java-classes. Default name of the XSD is always "schema1.xsd". How should I pre-define it using only that plugin? At the moment I use maven-antrun-plugin for file renaming. Plugin manual doesn't contain relevant information.

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>jaxb2-maven-plugin</artifactId>
  <version>2.3</version>
  <executions>
    <execution>
      <goals>
        <goal>schemagen</goal>
      </goals>
      <phase>generate-sources</phase>
      <configuration>
        <sources>
          <source>src/main/java/***some package***</source>
        </sources>
        <outputDirectory>${project.build.directory}/generated-sources/schemas</outputDirectory>
      </configuration>
    </execution>
  </executions>
</plugin>

Body:
Answer has been found. It is not enough to only annotate your java-classes with the JAXB annotations. In the DTO package should exist file "package-info.java" with the following content:

@XmlSchema(namespace = "http://your-namespace")
package com.your.package;

import javax.xml.bind.annotation.XmlSchema;

And the plugin declaration should look like this:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>jaxb2-maven-plugin</artifactId>
  <version>2.3</version>
  <executions>
    <execution>
      <goals>
        <goal>schemagen</goal>
      </goals>
      <phase>generate-sources</phase>
    </execution>
  </executions>
  <configuration>
    <sources>
      <source>src/main/java/com/your/package</source>
    </sources>
    <outputDirectory>${project.build.directory}/generated-sources/schemas</outputDirectory>
    <transformSchemas>
      <transformSchema>
        <uri>http://your-namespace</uri>
        <toFile>your-namespace.xsd</toFile>
      </transformSchema>
    </transformSchemas>
  </configuration>
</plugin>


问:
Can the port be specified for localhost using HTTPoison?
I'm working with a test in which I need to hit a service I'm running locally. The service is a rails application with a JSON api exposed. It's running on port 3000. When I execute this elixir code I get an error:

```<code>json_event = <some valid json built earlier>
my_url = "http://localhost:3000/api/service_call"
response = HTTPoison.post(my_url, json_event)
</code>```

The error I get is:

{:error, %HTTPoison.Error{id: nil, reason: :econnrefused}}

I should note that there is no output found in the service log when I execute that code.

my question is can the port be specified, and if so have I done so correctly by simply building it into the url?

I guess a follow on question would be what are the reasons that I might get this :econnrefused error?

I'm not even sure I'm asking the RIGHT questions :P

thanks

答:
So two parts to the answer here:

Yes, you can specify port, and you can do it by simply putting it into the URL itself. For example, http://localhost:3000/api/service_call.

rebooting fixed whatever was wrong with my system. I have no idea why it made a difference.

Body:
I'm working with a test in which I need to hit a service I'm running locally. The service is a rails application with a JSON api exposed. It's running on port 3000. When I execute this elixir code I get an error:

json_event = <some valid json built earlier>
my_url = "http://localhost:3000/api/service_call"
response = HTTPoison.post(my_url, json_event)

The error I get is:

{:error, %HTTPoison.Error{id: nil, reason: :econnrefused}}

I should note that there is no output found in the service log when I execute that code.

my question is can the port be specified, and if so have I done so correctly by simply building it into the url?

I guess a follow on question would be what are the reasons that I might get this :econnrefused error?

I'm not even sure I'm asking the RIGHT questions :P

thanks


问:
App Should exit on Smart Hub in Samsung smart TV
This is an unanswered issue on samsungdforum, and I have not found a satisfactory answer here so far..

My app has been rejected by Samsung guys because the app does not exit on smart hub. When a user presses the smarthub button, smarthub does come up, but the app is still running in the background. The proof of this is that when we relaunch the app, it starts from where it was left.

As far as I know, this code will take the app to smart hub:

```<code>    var widgetAPI = new Common.API.Widget();
  widgetAPI.sendReturnEvent();
  mwPlugin.SetSource(0);
</code>```

The above code is behaving fine for a blu-ray player but for tv, it is only minimizing the app, and if there is a video running in the app, then this code will mess with the video on the tv.

And this code will exit the app on broadcasting screen:

```<code> var widgetAPI = new Common.API.Widget();
    widgetAPI.sendExitEvent();
 mwPlugin.SetSource(0);
</code>```

So can any one suggest how to exit the app on smart hub in Samsung smart TV?

答:
If you can get your hands on an Application instance, it has an exit() method.

```<code>var app = tizen.application.getCurrentApplication();
app.exit();
</code>```

As described in documentation. Also the Guide has a section on how to terminate applicatons.

Body:
This is an unanswered issue on samsungdforum, and I have not found a satisfactory answer here so far..

My app has been rejected by Samsung guys because the app does not exit on smart hub. When a user presses the smarthub button, smarthub does come up, but the app is still running in the background. The proof of this is that when we relaunch the app, it starts from where it was left.

As far as I know, this code will take the app to smart hub:

    var widgetAPI = new Common.API.Widget();
  widgetAPI.sendReturnEvent();
  mwPlugin.SetSource(0);

The above code is behaving fine for a blu-ray player but for tv, it is only minimizing the app, and if there is a video running in the app, then this code will mess with the video on the tv.

And this code will exit the app on broadcasting screen:

 var widgetAPI = new Common.API.Widget();
    widgetAPI.sendExitEvent();
 mwPlugin.SetSource(0);

So can any one suggest how to exit the app on smart hub in Samsung smart TV?

Body:
If you can get your hands on an Application instance, it has an exit() method.

var app = tizen.application.getCurrentApplication();
app.exit();

As described in documentation. Also the Guide has a section on how to terminate applicatons.


问:
Mac OSX - IllegalStateException: The driver is not executable:
Im new to Mac OSX. Downloaded my Robotframework(Selenium & Java) project from git and tried to execute the code locally wherein I received the below error.

Suite setup failed:
IllegalStateException: The driver is not executable: /Users/roja/Documents/GitHub/testautomation/chromedrivers/chromedriver_osx

To rectify this issue, I followed the below but it didnt work.

Upgraded the selenium-java and standalone version from 2.53.1 to 3.4.0.

Driver path specified to Users/roja/automation

Chromedriver upgraded from 2.31 to 2.33

And the same driver version updated even in the path specified in the exception above.

Also Im unsure why the path is defaulted to /Users/roja/Documents/GitHub/testautomation/chromedrivers/chromedriver_osx.

My git projects are saved in the path usr/local/git/testautomation and chromedriver also saved in the same. please clarify and provide me a solution.

Below code written for launching the browser,

```<code>public void LaunchBrowser() throws InterruptedException {
System.setProperty("Webdriver.chrome.driver", "/Users/roja/Automation/chromedriver_osx");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
</code>```

答:
@debanjan already explain good expalaination to you, I am just giving you correct code:</p>

```<code>public void LaunchBrowser() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "/Users/roja/Automation/chromedriver_osx/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
}
</code>```

Body:
Im new to Mac OSX. Downloaded my Robotframework(Selenium & Java) project from git and tried to execute the code locally wherein I received the below error.

Suite setup failed:
IllegalStateException: The driver is not executable: /Users/roja/Documents/GitHub/testautomation/chromedrivers/chromedriver_osx

To rectify this issue, I followed the below but it didnt work.

Upgraded the selenium-java and standalone version from 2.53.1 to 3.4.0.

Driver path specified to Users/roja/automation

Chromedriver upgraded from 2.31 to 2.33

And the same driver version updated even in the path specified in the exception above.

Also Im unsure why the path is defaulted to /Users/roja/Documents/GitHub/testautomation/chromedrivers/chromedriver_osx.

My git projects are saved in the path usr/local/git/testautomation and chromedriver also saved in the same. please clarify and provide me a solution.

Below code written for launching the browser,

public void LaunchBrowser() throws InterruptedException {
System.setProperty("Webdriver.chrome.driver", "/Users/roja/Automation/chromedriver_osx");
driver = new ChromeDriver();
driver.manage().window().maximize();
}

Body:
@debanjan already explain good expalaination to you, I am just giving you correct code:

public void LaunchBrowser() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "/Users/roja/Automation/chromedriver_osx/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
}


问:
how to access custom annotation values in spring aspect
I am trying to access the custom annotation values from jointCut. But I couldn't find a way.

My sample code :

```<code>@ComponentValidation(input1="input1", typeOfRule="validation", logger=Log.EXCEPTION)
public boolean validator(Map<String,String> mapStr) {
    //blah blah
}
</code>```

Trying to access @Aspect class.

But, i didnt see any scope to access values.

Way i am trying to access is below code

```<code>CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
String[] names = codeSignature.getParameterNames();
MethodSignature methodSignature = (MethodSignature) joinPoint.getStaticPart().getSignature();
Annotation[][] annotations = methodSignature.getMethod().getParameterAnnotations();
Object[] values = joinPoint.getArgs();
</code>```

i didnt see any value returns input = input1. how to achieve this.

答:
For example if you have defined a method in Annotation interface like below :

```<code>@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface AspectParameter {
    String passArgument() default "";
}
</code>```

then you can access the class and the method values in the aspect like below :

```<code>@Slf4j
@Aspect
@Component
public class ParameterAspect {

    @Before("@annotation(AspectParameter)")
    public void validateInternalService(JoinPoint joinPoint, AspectParameter aspectParameter) throws Throwable {
        String customParameter = aspectParameter.passArgument();
    }
}
</code>```

Body:
I am trying to access the custom annotation values from jointCut. But I couldn't find a way.

My sample code :

@ComponentValidation(input1="input1", typeOfRule="validation", logger=Log.EXCEPTION)
public boolean validator(Map<String,String> mapStr) {
    //blah blah
}

Trying to access @Aspect class.

But, i didnt see any scope to access values.

Way i am trying to access is below code

CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
String[] names = codeSignature.getParameterNames();
MethodSignature methodSignature = (MethodSignature) joinPoint.getStaticPart().getSignature();
Annotation[][] annotations = methodSignature.getMethod().getParameterAnnotations();
Object[] values = joinPoint.getArgs();

i didnt see any value returns input = input1. how to achieve this.

Body:
For example if you have defined a method in Annotation interface like below :

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface AspectParameter {
    String passArgument() default "";
}

then you can access the class and the method values in the aspect like below :

@Slf4j
@Aspect
@Component
public class ParameterAspect {

    @Before("@annotation(AspectParameter)")
    public void validateInternalService(JoinPoint joinPoint, AspectParameter aspectParameter) throws Throwable {
        String customParameter = aspectParameter.passArgument();
    }
}


问:
Add multiple instances of the same button
I am creating a simple calculator for a school assignment but I can't get it to work for multiple digits

```<code>package calculator;

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;

public class Calculator implements ActionListener{

JFrame guiFrame;
JPanel buttonPanel;
JTextField numberCalc;
int calcOperation = 0;
int currentCalc;

public static void main(String[] args) {

     //Use the event dispatch thread for Swing components
     EventQueue.invokeLater(new Runnable()
     {

        @Override
         public void run()
         {

             new Calculator();
         }
     });

}

public Calculator()
{
    guiFrame = new JFrame();

    //make sure the program exits when the frame closes
    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    guiFrame.setTitle("Simple Calculator");
    guiFrame.setSize(300,300);

    //This will center the JFrame in the middle of the screen
    guiFrame.setLocationRelativeTo(null);

    numberCalc = new JTextField();
    numberCalc.setHorizontalAlignment(JTextField.RIGHT);
    numberCalc.setEditable(false);

    guiFrame.add(numberCalc, BorderLayout.NORTH);

    buttonPanel = new JPanel();

    //Make a Grid that has three rows and four columns
    buttonPanel.setLayout(new GridLayout(4,4));
    guiFrame.add(buttonPanel, BorderLayout.CENTER);

    //Add the number buttons
    for (int i=1;i<10;i++)
    {
        addButton(buttonPanel, String.valueOf(i));
    }

    JButton addButton = new JButton("+");
    addButton.setActionCommand("+");

    OperatorAction subAction = new OperatorAction(1);
    addButton.addActionListener(subAction);

    JButton subButton = new JButton("-");
    subButton.setActionCommand("-");

    OperatorAction addAction = new OperatorAction(2);
    subButton.addActionListener(addAction);

    JButton multiplyButton = new JButton("*");
    multiplyButton.setActionCommand("*");

    OperatorAction multiAction = new OperatorAction(3);
    multiplyButton.addActionListener(multiAction);

        JButton divideButton = new JButton("/");
        divideButton.setActionCommand("/");

        OperatorAction diviAction = new OperatorAction(4);
        divideButton.addActionListener(diviAction);

        JButton clearButton = new JButton("ce");
        clearButton.setActionCommand("ce");

        OperatorAction clearAction = new OperatorAction(5);
        clearButton.addActionListener(clearAction);

        JButton blankButton = new JButton(" ");

    JButton equalsButton = new JButton("=");
    equalsButton.setActionCommand("=");
    equalsButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent event)
        {

            if (!numberCalc.getText().isEmpty())
            {
                int number = Integer.parseInt(numberCalc.getText());

                if (calcOperation == 1)
                {
                    int calculate = currentCalc  + number;
                    numberCalc.setText(Integer.toString(calculate));
                }
                if (calcOperation == 2)
                {
                    int calculate = currentCalc  - number;
                    numberCalc.setText(Integer.toString(calculate));
                }

                if (calcOperation == 3)
                {
                        int calculate = currentCalc * number;
                        numberCalc.setText(Integer.toString(calculate));
                }

                if (calcOperation == 4)
                {
                        int calculate = currentCalc / number;
                        numberCalc.setText(Integer.toString(calculate));
                }

                if (calcOperation == 5)
                {
                        int calculate = 0;
                        numberCalc.setText(Integer.toString(calculate));
                }
            }
        }
    });

    buttonPanel.add(addButton);
    buttonPanel.add(subButton);
    buttonPanel.add(equalsButton);
    buttonPanel.add(divideButton);
    buttonPanel.add(multiplyButton);
    buttonPanel.add(clearButton);
    buttonPanel.add(blankButton);
    guiFrame.setVisible(true);
}

//All the buttons are following the same pattern
//so create them all in one place.
private void addButton(Container parent, String name)
{
    JButton but = new JButton(name);
    but.setActionCommand(name);
    but.addActionListener(this);
    parent.add(but);
}

//As all the buttons are doing the same thing it's
//easier to make the class implement the ActionListener
//interface and control the button clicks from one place
@Override
public void actionPerformed(ActionEvent event)
{
    //get the Action Command text from the button
    String action = event.getActionCommand();

    //set the text using the Action Command text
    numberCalc.setText(action);
}

private class OperatorAction implements ActionListener
{
    private int operator;

    public OperatorAction(int operation)
    {
        operator = operation;
    }

    public void actionPerformed(ActionEvent event)
    {
        currentCalc = Integer.parseInt(numberCalc.getText());
        calcOperation = operator;
    }
  }
 }
</code>```

However when I run the code It will not allow me to enter in numbers with more than one digit. Also the ce button I created will not reset to zero.

I have included an image of the output.
Thanks in advance.
Output of calculator

答:
The ActionListener is not correct

```<code>@Override
public void actionPerformed(ActionEvent event)
{
    //get the Action Command text from the button
    String action = event.getActionCommand();

    //set the text using the Action Command text
    numberCalc.setText(action);
}
</code>```

This will set the numberCalc text to the value of the button, not append the value.

Use numberCalc.setText(NumberCalc.getText() + action); to append the text

Also, for OperatorAction, you don't update any GUI component

```<code>public void actionPerformed(ActionEvent event)
{
    currentCalc = Integer.parseInt(numberCalc.getText());
    calcOperation = operator;
}
</code>```

You should clear numberCalc to wait for the next value or you will end up with 1 + 12 instead of 1 + 2.

If the button is clearButton, you need to change the logic and reset everything currentCalc, numberCalc, calcOperation, ...

Body:
I am creating a simple calculator for a school assignment but I can't get it to work for multiple digits

package calculator;

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;

public class Calculator implements ActionListener{

JFrame guiFrame;
JPanel buttonPanel;
JTextField numberCalc;
int calcOperation = 0;
int currentCalc;

public static void main(String[] args) {

     //Use the event dispatch thread for Swing components
     EventQueue.invokeLater(new Runnable()
     {

        @Override
         public void run()
         {

             new Calculator();
         }
     });

}

public Calculator()
{
    guiFrame = new JFrame();

    //make sure the program exits when the frame closes
    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    guiFrame.setTitle("Simple Calculator");
    guiFrame.setSize(300,300);

    //This will center the JFrame in the middle of the screen
    guiFrame.setLocationRelativeTo(null);

    numberCalc = new JTextField();
    numberCalc.setHorizontalAlignment(JTextField.RIGHT);
    numberCalc.setEditable(false);

    guiFrame.add(numberCalc, BorderLayout.NORTH);

    buttonPanel = new JPanel();

    //Make a Grid that has three rows and four columns
    buttonPanel.setLayout(new GridLayout(4,4));
    guiFrame.add(buttonPanel, BorderLayout.CENTER);

    //Add the number buttons
    for (int i=1;i<10;i++)
    {
        addButton(buttonPanel, String.valueOf(i));
    }

    JButton addButton = new JButton("+");
    addButton.setActionCommand("+");

    OperatorAction subAction = new OperatorAction(1);
    addButton.addActionListener(subAction);

    JButton subButton = new JButton("-");
    subButton.setActionCommand("-");

    OperatorAction addAction = new OperatorAction(2);
    subButton.addActionListener(addAction);

    JButton multiplyButton = new JButton("*");
    multiplyButton.setActionCommand("*");

    OperatorAction multiAction = new OperatorAction(3);
    multiplyButton.addActionListener(multiAction);

        JButton divideButton = new JButton("/");
        divideButton.setActionCommand("/");

        OperatorAction diviAction = new OperatorAction(4);
        divideButton.addActionListener(diviAction);

        JButton clearButton = new JButton("ce");
        clearButton.setActionCommand("ce");

        OperatorAction clearAction = new OperatorAction(5);
        clearButton.addActionListener(clearAction);

        JButton blankButton = new JButton(" ");

    JButton equalsButton = new JButton("=");
    equalsButton.setActionCommand("=");
    equalsButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent event)
        {

            if (!numberCalc.getText().isEmpty())
            {
                int number = Integer.parseInt(numberCalc.getText());

                if (calcOperation == 1)
                {
                    int calculate = currentCalc  + number;
                    numberCalc.setText(Integer.toString(calculate));
                }
                if (calcOperation == 2)
                {
                    int calculate = currentCalc  - number;
                    numberCalc.setText(Integer.toString(calculate));
                }

                if (calcOperation == 3)
                {
                        int calculate = currentCalc * number;
                        numberCalc.setText(Integer.toString(calculate));
                }

                if (calcOperation == 4)
                {
                        int calculate = currentCalc / number;
                        numberCalc.setText(Integer.toString(calculate));
                }

                if (calcOperation == 5)
                {
                        int calculate = 0;
                        numberCalc.setText(Integer.toString(calculate));
                }
            }
        }
    });

    buttonPanel.add(addButton);
    buttonPanel.add(subButton);
    buttonPanel.add(equalsButton);
    buttonPanel.add(divideButton);
    buttonPanel.add(multiplyButton);
    buttonPanel.add(clearButton);
    buttonPanel.add(blankButton);
    guiFrame.setVisible(true);
}

//All the buttons are following the same pattern
//so create them all in one place.
private void addButton(Container parent, String name)
{
    JButton but = new JButton(name);
    but.setActionCommand(name);
    but.addActionListener(this);
    parent.add(but);
}

//As all the buttons are doing the same thing it's
//easier to make the class implement the ActionListener
//interface and control the button clicks from one place
@Override
public void actionPerformed(ActionEvent event)
{
    //get the Action Command text from the button
    String action = event.getActionCommand();

    //set the text using the Action Command text
    numberCalc.setText(action);
}

private class OperatorAction implements ActionListener
{
    private int operator;

    public OperatorAction(int operation)
    {
        operator = operation;
    }

    public void actionPerformed(ActionEvent event)
    {
        currentCalc = Integer.parseInt(numberCalc.getText());
        calcOperation = operator;
    }
  }
 }

However when I run the code It will not allow me to enter in numbers with more than one digit. Also the ce button I created will not reset to zero.

I have included an image of the output.
Thanks in advance.
Output of calculator

Body:
The ActionListener is not correct

@Override
public void actionPerformed(ActionEvent event)
{
    //get the Action Command text from the button
    String action = event.getActionCommand();

    //set the text using the Action Command text
    numberCalc.setText(action);
}

This will set the numberCalc text to the value of the button, not append the value.

Use numberCalc.setText(NumberCalc.getText() + action); to append the text

Also, for OperatorAction, you don't update any GUI component

public void actionPerformed(ActionEvent event)
{
    currentCalc = Integer.parseInt(numberCalc.getText());
    calcOperation = operator;
}

You should clear numberCalc to wait for the next value or you will end up with 1 + 12 instead of 1 + 2.

If the button is clearButton, you need to change the logic and reset everything currentCalc, numberCalc, calcOperation, ...