问:
Unable to execute commands using Ride-Robot-SSH Library
I am exploring options of using RIDE-Robot Framework for my Project. Here, I am using SSH Library.

I am trying to login into my server and then try to execute some commands

Manually, I am trying to login to the server and then give a sudo admin command and then execute the set of commands.

Using Ride- I am using Open Connection, Execute Command keywords

I am able to login to the server with the username and password, but I am not able to execute commands.

Can you please help me understand how to execute commands?

I am able to open Connection and Login with username and password.

Paramiko

```<code>import paramiko

from paramiko import SSHClient

ssh = SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('10.184.59.41', username='******', password='*******')

shell=ssh.invoke_shell()

shell.settimeout(0.5)

ssh.exec_command("sudo -u tradmin -E bash")

ssh.exec_command("/ThomsonReuters/apps/hillfarber")
</code>```

******Ride******

```<code>Open Connection    10.184.59.41
Login    ${username}    ${password}
Execute Command    sudo - u tradmin -E bash
${stdout}=     Execute Command     /ThomsonReuters/tools/bin/adsmon -key 29 -get IDBFeed  c205xcmpdfh01.ECP_TUL.IDBFeed.IDBFeed PageCount
</code>```

Unable to execute the commands, no error is displayed

答:
Each invocation of Execute Command is in a new shell - thus the sudo from the first does not influence the user in the second. See the keyword documentation, it's suggested there to use Write and Read keywords for continuity of commands execution within the same shell.

Alternatively you could combine the two calls in a single command - sudo ... adsmon ....

Body:
I am exploring options of using RIDE-Robot Framework for my Project. Here, I am using SSH Library.

I am trying to login into my server and then try to execute some commands

Manually, I am trying to login to the server and then give a sudo admin command and then execute the set of commands.

Using Ride- I am using Open Connection, Execute Command keywords

I am able to login to the server with the username and password, but I am not able to execute commands.

Can you please help me understand how to execute commands?

I am able to open Connection and Login with username and password.

Paramiko

import paramiko

from paramiko import SSHClient

ssh = SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('10.184.59.41', username='******', password='*******')

shell=ssh.invoke_shell()

shell.settimeout(0.5)

ssh.exec_command("sudo -u tradmin -E bash")

ssh.exec_command("/ThomsonReuters/apps/hillfarber")

******Ride******

Open Connection    10.184.59.41
Login    ${username}    ${password}
Execute Command    sudo - u tradmin -E bash
${stdout}=     Execute Command     /ThomsonReuters/tools/bin/adsmon -key 29 -get IDBFeed  c205xcmpdfh01.ECP_TUL.IDBFeed.IDBFeed PageCount

Unable to execute the commands, no error is displayed


来源: stackexchange

问:
Convert pandas dataframe to NumPy array
How do I convert a pandas dataframe into a NumPy array?

DataFrame:

```<code>import numpy as np
import pandas as pd

index = [1, 2, 3, 4, 5, 6, 7]
a = [np.nan, np.nan, np.nan, 0.1, 0.1, 0.1, 0.1]
b = [0.2, np.nan, 0.2, 0.2, 0.2, np.nan, np.nan]
c = [np.nan, 0.5, 0.5, np.nan, 0.5, 0.5, np.nan]
df = pd.DataFrame({'A': a, 'B': b, 'C': c}, index=index)
df = df.rename_axis('ID')
</code>```

gives

```<code>label   A    B    C
ID
1   NaN  0.2  NaN
2   NaN  NaN  0.5
3   NaN  0.2  0.5
4   0.1  0.2  NaN
5   0.1  0.2  0.5
6   0.1  NaN  0.5
7   0.1  NaN  NaN
</code>```

I would like to convert this to a NumPy array, like so:

```<code>array([[ nan,  0.2,  nan],
       [ nan,  nan,  0.5],
       [ nan,  0.2,  0.5],
       [ 0.1,  0.2,  nan],
       [ 0.1,  0.2,  0.5],
       [ 0.1,  nan,  0.5],
       [ 0.1,  nan,  nan]])
</code>```

Also, is it possible to preserve the dtypes, like this?

```<code>array([[ 1, nan,  0.2,  nan],
       [ 2, nan,  nan,  0.5],
       [ 3, nan,  0.2,  0.5],
       [ 4, 0.1,  0.2,  nan],
       [ 5, 0.1,  0.2,  0.5],
       [ 6, 0.1,  nan,  0.5],
       [ 7, 0.1,  nan,  nan]],
     dtype=[('ID', '<i4'), ('A', '<f8'), ('B', '<f8'), ('B', '<f8')])
</code>```

答:
I went through the answers above. The "as_matrix()" method works but its obsolete now. For me, What worked was ".to_numpy()".

This returns a multidimensional array. I'll prefer using this method if you're reading data from excel sheet and you need to access data from any index. Hope this helps :)

ContentLicense: CC BY-SA 4.0

Title: Convert pandas dataframe to NumPy array

Body:
How do I convert a pandas dataframe into a NumPy array?

DataFrame:

import numpy as np
import pandas as pd

index = [1, 2, 3, 4, 5, 6, 7]
a = [np.nan, np.nan, np.nan, 0.1, 0.1, 0.1, 0.1]
b = [0.2, np.nan, 0.2, 0.2, 0.2, np.nan, np.nan]
c = [np.nan, 0.5, 0.5, np.nan, 0.5, 0.5, np.nan]
df = pd.DataFrame({'A': a, 'B': b, 'C': c}, index=index)
df = df.rename_axis('ID')

gives

label   A    B    C
ID
1   NaN  0.2  NaN
2   NaN  NaN  0.5
3   NaN  0.2  0.5
4   0.1  0.2  NaN
5   0.1  0.2  0.5
6   0.1  NaN  0.5
7   0.1  NaN  NaN

I would like to convert this to a NumPy array, like so:

array([[ nan,  0.2,  nan],
       [ nan,  nan,  0.5],
       [ nan,  0.2,  0.5],
       [ 0.1,  0.2,  nan],
       [ 0.1,  0.2,  0.5],
       [ 0.1,  nan,  0.5],
       [ 0.1,  nan,  nan]])

Also, is it possible to preserve the dtypes, like this?

array([[ 1, nan,  0.2,  nan],
       [ 2, nan,  nan,  0.5],
       [ 3, nan,  0.2,  0.5],
       [ 4, 0.1,  0.2,  nan],
       [ 5, 0.1,  0.2,  0.5],
       [ 6, 0.1,  nan,  0.5],
       [ 7, 0.1,  nan,  nan]],
     dtype=[('ID', '<i4'), ('A', '<f8'), ('B', '<f8'), ('B', '<f8')])


问:
Swift: Swipe action to strikethrough row in TableView
Evening ladies and gentleman,
I am currently getting used to Swift and wanted to start with a little todo app. So far I can add an item and safe it persistently in a context. When an item has been added, it will be shown in a tableview. Now, I want to use a check swipe to strikethrough items, which have been added and safe this information in my context. Deleting using a swipe works perfectly fine.

Has anybody an idea how realize this? I tried to solve it by myself, but couldnt get it done. A similar question has been asked here before, but didnt get a proper answer: Add strikethrough to tableview row with a swipe

```<code>func checkAccessoryType(cell: UITableViewCell, isCompleted: Bool) {
    if isCompleted {
        cell.accessoryType = .checkmark

    } else {
        cell.accessoryType = .none
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let todo = CoreDataManager.shared.getTodoItem(index: indexPath.row)
    todo.completed = !todo.completed
    CoreDataManager.shared.safeContext()

    if let cell = tableView.cellForRow(at: indexPath){
        checkAccessoryType(cell: cell, isCompleted: todo.completed)
    }
}
</code>```

答:
Looking at the link that you provided, you need swipe action on your UITableViewCell.

Try looking into:

leadingSwipeActionsConfigurationForRowAt

trailingSwipeActionsConfigurationForRowAt

You need this action to perform the strikethrough label or delete:

```<code>func tableView(_ tableView: UITableView,
                leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
 {
     let closeAction = UIContextualAction(style: .normal, title:  "Close", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
             print("OK, marked as Closed")
             success(true)
         })
         closeAction.image = UIImage(named: "tick")
         closeAction.backgroundColor = .purple

         return UISwipeActionsConfiguration(actions: [closeAction])

 }

 func tableView(_ tableView: UITableView,
                trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
 {
     let modifyAction = UIContextualAction(style: .normal, title:  "Update", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
         print("Update action ...")
         success(true)
     })
     modifyAction.image = UIImage(named: "hammer")
     modifyAction.backgroundColor = .blue

     return UISwipeActionsConfiguration(actions: [modifyAction])
 }
</code>```

Source: https://developerslogblog.wordpress.com/2017/06/28/ios-11-swipe-leftright-in-uitableviewcell/

Body:
Evening ladies and gentleman,
I am currently getting used to Swift and wanted to start with a little todo app. So far I can add an item and safe it persistently in a context. When an item has been added, it will be shown in a tableview. Now, I want to use a check swipe to strikethrough items, which have been added and safe this information in my context. Deleting using a swipe works perfectly fine.

Has anybody an idea how realize this? I tried to solve it by myself, but couldnt get it done. A similar question has been asked here before, but didnt get a proper answer: Add strikethrough to tableview row with a swipe

func checkAccessoryType(cell: UITableViewCell, isCompleted: Bool) {
    if isCompleted {
        cell.accessoryType = .checkmark

    } else {
        cell.accessoryType = .none
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let todo = CoreDataManager.shared.getTodoItem(index: indexPath.row)
    todo.completed = !todo.completed
    CoreDataManager.shared.safeContext()

    if let cell = tableView.cellForRow(at: indexPath){
        checkAccessoryType(cell: cell, isCompleted: todo.completed)
    }
}

Body:
Looking at the link that you provided, you need swipe action on your UITableViewCell.

Try looking into:

leadingSwipeActionsConfigurationForRowAt

trailingSwipeActionsConfigurationForRowAt

You need this action to perform the strikethrough label or delete:

func tableView(_ tableView: UITableView,
                leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
 {
     let closeAction = UIContextualAction(style: .normal, title:  "Close", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
             print("OK, marked as Closed")
             success(true)
         })
         closeAction.image = UIImage(named: "tick")
         closeAction.backgroundColor = .purple

         return UISwipeActionsConfiguration(actions: [closeAction])

 }

 func tableView(_ tableView: UITableView,
                trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
 {
     let modifyAction = UIContextualAction(style: .normal, title:  "Update", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
         print("Update action ...")
         success(true)
     })
     modifyAction.image = UIImage(named: "hammer")
     modifyAction.backgroundColor = .blue

     return UISwipeActionsConfiguration(actions: [modifyAction])
 }

Source: https://developerslogblog.wordpress.com/2017/06/28/ios-11-swipe-leftright-in-uitableviewcell/


问:
jquery uncertain error?
i am using this code to access all the hidden elements from a form:

```<code>function get_hidden_val(ids,form_id)
{

    var get_check_val = document.getElementById(ids);
    if(get_check_val.checked){

    var div = $('<div></div>')
    .appendTo('form#bulk_add_cart')
    .attr('id',"bulk_"+form_id)

    $("form#" +form_id).find('input[type="hidden"]').each(function(){
    var value =$(this).val();
    var name = $(this).attr("name");
    var tags = "<input type='hidden' value='" + value + "' name='"+name+"'>";
    $('div#' +form_id).append(tags);
});
}
    else
    {
        $("form#bulk_add_cart").find('div#' +form_id).remove();
    }

}
</code>```

My problem is when I click the first checkbox it give me the result but when i click the second checkbox it doesn't and also the another problem is when i click first checkbox it shows total hidden elements but when i second time checked it, it show 4 less ?

Please suggest a solution.

Thanks

答:
@user704302: Missing >, update var tags to --

```<code>var tags = "<input type='hidden' value='" + value + "' id='"+id+"'>";
</code>```

ContentLicense: CC BY-SA 3.0

Title: jquery uncertain error?

Body:
i am using this code to access all the hidden elements from a form:

function get_hidden_val(ids,form_id)
{

    var get_check_val = document.getElementById(ids);
    if(get_check_val.checked){

    var div = $('

')
    .appendTo('form#bulk_add_cart')
    .attr('id',"bulk_"+form_id)

    $("form#" +form_id).find('input[type="hidden"]').each(function(){
    var value =$(this).val();
    var name = $(this).attr("name");
    var tags = "<input type='hidden' value='" + value + "' name='"+name+"'>";
    $('div#' +form_id).append(tags);
});
}
    else
    {
        $("form#bulk_add_cart").find('div#' +form_id).remove();
    }

}

My problem is when I click the first checkbox it give me the result but when i click the second checkbox it doesn't and also the another problem is when i click first checkbox it shows total hidden elements but when i second time checked it, it show 4 less ?

Please suggest a solution.

Thanks

Body:
@user704302: Missing >, update var tags to --

var tags = "<input type='hidden' value='" + value + "' id='"+id+"'>";


问:
ansible uri module fails (lineno\\": 0\\n}' is not of type u'object) (Input payload validation failed)
ansible 2.7, same call over curl works fine>

```<code>curl -X POST " -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"hostname\": \"string\", \"name\": \"string\", \"service\": \"string\", \"extra\": {}, \"args\": [ \"string\" ], \"module\": \"string\", \"filename\": \"string\", \"pathname\": \"string\", \"requestid\": \"string\", \"message\": \"string\", \"funcname\": \"string\", \"levelname\": \"INFO\", \"lineno\": 0}"
</code>```

uri module gives me the following error:

[WARNING]: provided hosts list is empty, only localhost is available. Note 2 that the implicit localhost does not match 'all' 3 4 5 PLAY [update log via api] ****************************************************** 20:37:30 6 7 TASK [uri] ********************************************************************* 20:37:30 8 [DEPRECATION WARNING]: Supplying headers via HEADER_* is deprecated. Please use 9 headers to supply headers for the request. This feature will be removed in 10 version 2.9. Deprecation warnings can be disabled by setting 11 deprecation_warnings=False in ansible.cfg. 12 fatal: [localhost]: FAILED! => {"access_control_allow_origin": "*", "changed": false, "connection": "Upgrade, close", "content": "{\"message\": \"Input payload validation failed\", \"errors\": {\"\": \"u'{\n \"hostname\": \"string\",\n \"name\": \"string\",\n \"service\": \"string\",\n \"extra\": {},\n \"args\": [\n \"string\"\n ],\n \"module\": \"string\",\n \"filename\": \"string\",\n \"pathname\": \"string\",\n \"requestid\": \"string\",\n \"message\": \"string\",\n \"funcname\": \"string\",\n \"levelname\": \"INFO\",\n \"lineno\": 0\n}' is not of type u'object'\"}}\n", "content_length": "469", "content_type": "application/json", "date": "Thu, 30 May 2019 01:37:35 GMT", "json": {"errors": {"": "u'{\n \"hostname\": \"string\",\n \"name\": \"string\",\n \"service\": \"string\",\n \"extra\": {},\n \"args\": [\n \"string\"\n ],\… 13 14 PLAY RECAP ********************************************************************* 20:37:37 15 localhost : ok=0 changed=0 unreachable=0 failed=1

```<code>---
- hosts: localhost
  name: update log via api
  gather_facts: false
  vars_files:
   vars.yml
  vars:
  tasks:
  - uri:
      url: "{{ api_log_url }}"
      method: POST
      force_basic_auth: yes
      url_username: "{{ api_log_user }}"
      url_password: "{{ api_log_password }}"
      body_format: json
      return_content: yes
      HEADER_Content-Type: "application/json"
      validate_certs: false
      body: "{{ lookup('file','create_body.json') | to_json }}"
</code>```

create_body.json:

```<code>{
  "hostname": "string",
  "name": "string",
  "service": "string",
  "extra": {},
  "args": [
    "string"
  ],
  "module": "string",
  "filename": "string",
  "pathname": "string",
  "requestid": "string",
  "message": "string",
  "funcname": "string",
  "levelname": "INFO",
  "lineno": 0
}
</code>```

答:
"json": {"errors": {"": "u'{\n \"hostname\": \"string\",\n

I'm pretty sure you are getting bitten by the json-to-object-to-string mental bug; since you already have JSON text, the ideal outcome would not be to parse it into an object and then have ansible serialize it back into a string, lest you run the very real risk of exactly what happened here: calling str(body) where body was a dict

Just remove the | to_json from your body: {{ }} expression and I would expect it will end better than what you are currently experiencing

Body:
ansible 2.7, same call over curl works fine>

curl -X POST " -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"hostname\": \"string\", \"name\": \"string\", \"service\": \"string\", \"extra\": {}, \"args\": [ \"string\" ], \"module\": \"string\", \"filename\": \"string\", \"pathname\": \"string\", \"requestid\": \"string\", \"message\": \"string\", \"funcname\": \"string\", \"levelname\": \"INFO\", \"lineno\": 0}"

uri module gives me the following error:

[WARNING]: provided hosts list is empty, only localhost is available. Note 2 that the implicit localhost does not match 'all' 3 4 5 PLAY [update log via api] ****************************************************** 20:37:30 6 7 TASK [uri] ********************************************************************* 20:37:30 8 [DEPRECATION WARNING]: Supplying headers via HEADER_* is deprecated. Please use 9 headers to supply headers for the request. This feature will be removed in 10 version 2.9. Deprecation warnings can be disabled by setting 11 deprecation_warnings=False in ansible.cfg. 12 fatal: [localhost]: FAILED! => {"access_control_allow_origin": "*", "changed": false, "connection": "Upgrade, close", "content": "{\"message\": \"Input payload validation failed\", \"errors\": {\"\": \"u'{\n \"hostname\": \"string\",\n \"name\": \"string\",\n \"service\": \"string\",\n \"extra\": {},\n \"args\": [\n \"string\"\n ],\n \"module\": \"string\",\n \"filename\": \"string\",\n \"pathname\": \"string\",\n \"requestid\": \"string\",\n \"message\": \"string\",\n \"funcname\": \"string\",\n \"levelname\": \"INFO\",\n \"lineno\": 0\n}' is not of type u'object'\"}}\n", "content_length": "469", "content_type": "application/json", "date": "Thu, 30 May 2019 01:37:35 GMT", "json": {"errors": {"": "u'{\n \"hostname\": \"string\",\n \"name\": \"string\",\n \"service\": \"string\",\n \"extra\": {},\n \"args\": [\n \"string\"\n ],\… 13 14 PLAY RECAP ********************************************************************* 20:37:37 15 localhost : ok=0 changed=0 unreachable=0 failed=1

---
- hosts: localhost
  name: update log via api
  gather_facts: false
  vars_files:
   vars.yml
  vars:
  tasks:
  - uri:
      url: "{{ api_log_url }}"
      method: POST
      force_basic_auth: yes
      url_username: "{{ api_log_user }}"
      url_password: "{{ api_log_password }}"
      body_format: json
      return_content: yes
      HEADER_Content-Type: "application/json"
      validate_certs: false
      body: "{{ lookup('file','create_body.json') | to_json }}"

create_body.json:

{
  "hostname": "string",
  "name": "string",
  "service": "string",
  "extra": {},
  "args": [
    "string"
  ],
  "module": "string",
  "filename": "string",
  "pathname": "string",
  "requestid": "string",
  "message": "string",
  "funcname": "string",
  "levelname": "INFO",
  "lineno": 0
}


问:
can anyone explain the use of nested static interface below
I was trying to use jdbc appender from log4j2 for logging information to database. I came across this class for creating connection.

```<code>public class ConnectionFactory {
    //couldn't understand the logic for need of this interface
    private static interface Singleton {
        final ConnectionFactory INSTANCE = new ConnectionFactory();
    }

    private final DataSource dataSource;

    private ConnectionFactory() {
          //necessary connection creation for DataSource datasource
          //connection pooling is used here
    }

    public static Connection getDatabaseConnection() throws SQLException {
        return Singleton.INSTANCE.dataSource.getConnection();
    }
}
</code>```

For getting the connection, all I have to do is call the getDatabaseConnection() class. And it works. But I cannot understand why I need to have the interface named Singleton. What would happen if I don't use it. And by don't use it, I mean, is not just deleting that code but also make other changes accordingly like make constructor public if necessary, getDatabaseConnection() non-static if necessary.

But is that interface named Singleton really used effectively here. I hope I would get cleared on this logic. And thank you.

Also this code is available from https://logging.apache.org/log4j/2.x/manual/appenders.html#JDBCAppender

答:
Basically ConnectionFactory class is implementing singleton design pattern which is used to get only single object/bean of that class.You could study this pattern from various online resources and will understand this class is using Singleton with lazy initialization concept.

Simple definition:-

Singleton pattern is a design solution where an application wants to
  have one and only one instance of any class, in all possible scenarios
  without any exceptional condition.

An implementation of the singleton pattern must:

1)Ensure that only one instance of the singleton class ever exists.

2)Provide global access to that instance.

Typically, this is done by:

1)Declaring all constructors of the class to be private.

2)Providing a static method that returns a reference to the instance.

Few Resources for your better understanding how to implement this design pattern:-
https://howtodoinjava.com/design-patterns/creational/singleton-design-pattern-in-java/

https://dzone.com/articles/singleton-design-pattern

Body:
I was trying to use jdbc appender from log4j2 for logging information to database. I came across this class for creating connection.

public class ConnectionFactory {
    //couldn't understand the logic for need of this interface
    private static interface Singleton {
        final ConnectionFactory INSTANCE = new ConnectionFactory();
    }

    private final DataSource dataSource;

    private ConnectionFactory() {
          //necessary connection creation for DataSource datasource
          //connection pooling is used here
    }

    public static Connection getDatabaseConnection() throws SQLException {
        return Singleton.INSTANCE.dataSource.getConnection();
    }
}

For getting the connection, all I have to do is call the getDatabaseConnection() class. And it works. But I cannot understand why I need to have the interface named Singleton. What would happen if I don't use it. And by don't use it, I mean, is not just deleting that code but also make other changes accordingly like make constructor public if necessary, getDatabaseConnection() non-static if necessary.

But is that interface named Singleton really used effectively here. I hope I would get cleared on this logic. And thank you.

Also this code is available from https://logging.apache.org/log4j/2.x/manual/appenders.html#JDBCAppender


问:
is there any difference in the following sort queries
```<code>DECLARE @Table1 TABLE (ID INT IDENTITY(1,1), Field1 INT, FieldSomethingElse VARCHAR(10))

INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (1, 'b')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (2, null)
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (765, 'a')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (NULL, 'd')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (NULL, 'f')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (76, null)
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (3, 'r')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (40, 'b')

declare @flag bit = 0;

SELECT *
FROM @Table1
ORDER BY
  case when @flag = 1 then  ISNULL(Field1,0) else 0 end  desc , ID  desc

SELECT *
FROM @Table1
ORDER BY
  case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc
</code>```

Is there any difference if I write

```<code> 1. case when @flag = 1 then ISNULL(Field1,0) else 0 end desc, ID desc
</code>```

or

```<code> 2. case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc
</code>```

I was advised to use option 1, but for me both options are same because I see the same result. Is there any difference?

how does 1 and 2 options affect the sorting?

答:
i guess there is a little difference. When flag = 0 the following expressions are same

order by case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc

and

order by case when @flag = 1 then ISNULL(Field1,0) else null end desc, ID desc

let's assume that instead of Field1 and Id we sort two bit columns. In this case, when sorting two columns NULL will be considered.

https://rextester.com/SBDJQ20053

that's why it's recommended to use

```<code>case when @flag = 1 then ISNULL(Field1,0) else 0 end desc, ID desc
</code>```

to avoid null in sorting

Body:
DECLARE @Table1 TABLE (ID INT IDENTITY(1,1), Field1 INT, FieldSomethingElse VARCHAR(10))

INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (1, 'b')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (2, null)
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (765, 'a')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (NULL, 'd')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (NULL, 'f')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (76, null)
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (3, 'r')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (40, 'b')

declare @flag bit = 0;

SELECT *
FROM @Table1
ORDER BY
  case when @flag = 1 then  ISNULL(Field1,0) else 0 end  desc , ID  desc

SELECT *
FROM @Table1
ORDER BY
  case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc

Is there any difference if I write

 1. case when @flag = 1 then ISNULL(Field1,0) else 0 end desc, ID desc

or

 2. case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc

I was advised to use option 1, but for me both options are same because I see the same result. Is there any difference?

how does 1 and 2 options affect the sorting?

Body:
i guess there is a little difference. When flag = 0 the following expressions are same

order by case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc

and

order by case when @flag = 1 then ISNULL(Field1,0) else null end desc, ID desc

let's assume that instead of Field1 and Id we sort two bit columns. In this case, when sorting two columns NULL will be considered.

https://rextester.com/SBDJQ20053

that's why it's recommended to use

case when @flag = 1 then ISNULL(Field1,0) else 0 end desc, ID desc

to avoid null in sorting


问:
Connecting to MySQL Database with Aulux Barcode software
I have a local MySQL Database which stores all the details for my Point of Sale software - Unicenta oPOS. I am able to connect to the database just fine with Unicenta and with my website software.

I am trying to use a piece of software called Aulux Barcode Label Maker 7 to create labels for my products. I cannot seem to get this software to connect to my database. Has anyone done anything similar? Or have any tips that might work?

See attached some screenshots of my Unicenta config which does work and the Aulux which does not. Note that I have tried all different combinations of the host name used in Unicenta, but doesn't seem to matter how I format it...

Unicenta works fine...

Option chosen for Aulux

Fails to connect. I have tried adding port and such...

Thanks for your time!

答:
I had issues myself with this but figured out a way to make it work, hopefully it helps someone else too.

First you need to download the correct MySQL ODBC connector for your system.

Once that is done set it up by typing in "Data Sources (ODBC)" in the windows search.

Add the MySQL ODBC Unicode Driver, along with the name e.g. MySQL, IP Server, User, Password & database.

Once that's done you can go into Aulux Barcode Maker and go to Data Table -> Database

Select Microsoft OLE DB Provider for ODBC Drivers -> Next

Select your newly created connection e.g. MySQL (Or whatever you named it)

Put in the MySQL username and password but leave the following field blank (catalog to use)

That's it, your done. Hope it helps ;)


问:
Customizing Sharepoint 2013 List Header
My company just converted to SP 2013 and I am now trying to create a new list.  I have been trying to customize my header to have the following attribute:

Wrapped Text
Font Color Blue
Text Allignment - Center
Vertical alignment - bottom

I have found a script that allowed me to wrap the headers on all of the columns and I tried adding to it the color and text allignment.  What I keep running into is that it is only updating the color and allignment on my one header that is not filterable.  I have tried to look up what each of the .ms items mean because I am assuming that is my issue, but I can not seem to find the answer to that question.  Any help would be greatly appreciated!

```<code><style>
    .ms-vh, .ms-vh2-nofilter, .ms-vh2-nograd, .ms-vh2, .ms-vb{
        white-space: normal;
        color:#0000ff;
        text-align:center;
        vertical-align:text-bottom;
    }
</style>
</code>```

答:
Add a Script Editor web part, and insert this:

```<code>
/*Choose your background colour*/
.ms-viewheadertr{
background:#00426A;
}

/*Choose font style*/
.ms-vh2-nofilter, .ms-vh2, a.ms-headerSortTitleLink {
font-weight:bold;
color:white;
font-size:1.05em;
}

</style>
</code>```

With thanks to Nate Chamberlain:
https://natechamberlain.com/2018/07/20/customize-styles-formatting-of-sharepoint-list-column-header-rows/

Title: Customizing Sharepoint 2013 List Header

Body:
Add a Script Editor web part, and insert this:

/*Choose your background colour*/
.ms-viewheadertr{
background:#00426A;
}

/*Choose font style*/
.ms-vh2-nofilter, .ms-vh2, a.ms-headerSortTitleLink {
font-weight:bold;
color:white;
font-size:1.05em;
}

</style>

With thanks to Nate Chamberlain:
https://natechamberlain.com/2018/07/20/customize-styles-formatting-of-sharepoint-list-column-header-rows/


问:
How do I disable convention and refactor linting globally?
I've been having problems configuring Pylint in VS Code. I can't figure out how to disable the convention and refactor linting. They should be disabled by default but they are not. Maybe because I also installed pylint-django but I can't find settings for it. This is what it looks like

I have my own strict conventions and refactor rules so these hints are nothing but annoying. Is there a way to get rid of convention and refactor linting globally or for the user or the entire project permanently? I still want to keep errors and warnings, of course.

I tried pylint --disable=R,C *.py and restarted the server and VS code. Nothing changed. I also tried creating .pylintrc and putting disable=R,C in there, but that also had no effect.

答:
Add this to your settings.json (ctrl + shift + p -> Preferences: Open Settings (JSON)):

```<code>{
    ...,
    "python.linting.pylintArgs": ["--disable=R,C", "*.py"],
    ...
}
</code>```

Body:
Add this to your settings.json (ctrl + shift + p -> Preferences: Open Settings (JSON)):

{
    ...,
    "python.linting.pylintArgs": ["--disable=R,C", "*.py"],
    ...
}


问:
How to bring ajax search onkeyup with jquery
My Script to call ajax

```<code><script language="javascript">
function search_func(value)
{
    $.ajax({
       type: "GET",
       url: "sample.php",
       data: {'search_keyword' : value},
       dataType: "text",
       success: function(msg){
                   //Receiving the result of search here
       }
    });
}
</script>
</code>```

HTML

```<code>   <input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
</code>```

Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.

For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.

When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.

Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.

I believe I had explained up to reader knowledge.

答:
You should check if the value has changed over time:

```<code>var searchRequest = null;

$(function () {
    var minlength = 3;

    $("#sample_search").keyup(function () {
        var that = this,
        value = $(this).val();

        if (value.length >= minlength ) {
            if (searchRequest != null)
                searchRequest.abort();
            searchRequest = $.ajax({
                type: "GET",
                url: "sample.php",
                data: {
                    'search_keyword' : value
                },
                dataType: "text",
                success: function(msg){
                    //we need to check if the value is the same
                    if (value==$(that).val()) {
                    //Receiving the result of search here
                    }
                }
            });
        }
    });
});
</code>```

EDIT:

The searchRequest variable was added to prevent multiple unnecessary requests to the server.

Body:
My Script to call ajax

HTML

   <input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">

Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.

For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.

When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.

Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.

I believe I had explained up to reader knowledge.

Body:
You should check if the value has changed over time:

var searchRequest = null;

$(function () {
    var minlength = 3;

    $("#sample_search").keyup(function () {
        var that = this,
        value = $(this).val();

        if (value.length >= minlength ) {
            if (searchRequest != null)
                searchRequest.abort();
            searchRequest = $.ajax({
                type: "GET",
                url: "sample.php",
                data: {
                    'search_keyword' : value
                },
                dataType: "text",
                success: function(msg){
                    //we need to check if the value is the same
                    if (value==$(that).val()) {
                    //Receiving the result of search here
                    }
                }
            });
        }
    });
});

EDIT:

The searchRequest variable was added to prevent multiple unnecessary requests to the server.


问:
iOS 9 canOpenURL error for ADAL login
This just stopped working in XCode 7.2.1 building against 9.2.1.

I'm using Microsoft ADAL from cocoapods.

This is the error:

```<code>canOpenURL: failed for URL: "msauth://broker" - error: "(null)"
</code>```

I've already added msauth to my Info.plist file under LSApplicationQueriesSchemes.

I think I am going to downgrade to XCode 7 to see if that works.

Edit: I added the LSApplicationQueriesSchemes item to the MS ADAL cocoapod and now it's returning data but still giving the same error.

答:
On a real device it works, it's just weird output of the simulator.

Because it not able get some property settings on simulator.Please check on real device.

Title: iOS 9 canOpenURL error for ADAL login

Body:
This just stopped working in XCode 7.2.1 building against 9.2.1.

I'm using Microsoft ADAL from cocoapods.

This is the error:

canOpenURL: failed for URL: "msauth://broker" - error: "(null)"

I've already added msauth to my Info.plist file under LSApplicationQueriesSchemes.

I think I am going to downgrade to XCode 7 to see if that works.

Edit: I added the LSApplicationQueriesSchemes item to the MS ADAL cocoapod and now it's returning data but still giving the same error.


问:
auth attempt is not working but data will store in users
My auth:: an attempt is not working.
but my registration Form data will be stored in the User database and I also applied auth:: check(), it is also not working.

This is the controller

```<code>public function showLoginform(Request $request){

    $this->validate($request,[
        'email' => 'required',
        'password' => 'required',
    ]);

     $user_data = array(
         'email' => $request->get('email'),
         'password' => $request->get('password')
     );

 if(Auth::attempt($user_data)){
        //return \redirect::to("logged in successfuly");
        echo "yes match";
    } else{
        echo "not match";
       // return "oopps something wrong";
    }

}
</code>```

here is my model

class User extends Authenticatable
{
    use Notifiable;

```<code>protected $table="users";

protected $fillable = [ 'name', 'email', 'password', 'phonenumber' , 'profession' , 'images' ];

protected $hidden = [
    'password', 'remember_token',
];
}
</code>```

答:
Use $request->input instead of $request->get</p>

```<code>public function showLoginform(Request $request){

    $this->validate($request,[
        'email' => 'required',
        'password' => 'required',
    ]);

     $user_data = array(
         'email' => $request->input('email'),
         'password' => $request->input('password')
     );

 if(Auth::attempt($user_data)){
        //return \redirect::to("logged in successfuly");
        echo "yes match";
    } else{
        echo "not match";
       // return "oopps something wrong";
    }

}
</code>```

Body:
My auth:: an attempt is not working.
but my registration Form data will be stored in the User database and I also applied auth:: check(), it is also not working.

This is the controller

public function showLoginform(Request $request){

    $this->validate($request,[
        'email' => 'required',
        'password' => 'required',
    ]);

     $user_data = array(
         'email' => $request->get('email'),
         'password' => $request->get('password')
     );

 if(Auth::attempt($user_data)){
        //return \redirect::to("logged in successfuly");
        echo "yes match";
    } else{
        echo "not match";
       // return "oopps something wrong";
    }

}

here is my model

class User extends Authenticatable
{
    use Notifiable;

protected $table="users";

protected $fillable = [ 'name', 'email', 'password', 'phonenumber' , 'profession' , 'images' ];

protected $hidden = [
    'password', 'remember_token',
];
}

Body:
Use $request->input instead of $request->get

public function showLoginform(Request $request){

    $this->validate($request,[
        'email' => 'required',
        'password' => 'required',
    ]);

     $user_data = array(
         'email' => $request->input('email'),
         'password' => $request->input('password')
     );

 if(Auth::attempt($user_data)){
        //return \redirect::to("logged in successfuly");
        echo "yes match";
    } else{
        echo "not match";
       // return "oopps something wrong";
    }

}


问:
Property 'x' is missing in type '() => x' but required in type 'x'
Error: Property 'Control' is missing in type '() => Controls' but required in type 'Controls'.

```<code>export class Controls {
   Control: Control[];
}

page.Sections.push({
    ....
    Controls: () => {
      const c = new Controls();
      c.Control = new Array<Ctrl>();
      section.VisualComponents.forEach(vc => {
          c.Control.push({
            ....
            ....

        });
      });
      return c;
    }
  });
</code>```

What am I doing wrong?

答:
You are required to have Controls[] array but are assigning a function Controls: () => {:

```<code>export class Controls {
   Control: Control[]; /// HERE
}

page.Sections.push({
    ....
    Controls: () => { // HERE
      const c = new Controls();
      c.Control = new Array<Ctrl>();
      section.VisualComponents.forEach(vc => {
          c.Control.push({
            ....
            ....

        });
      });
      return c;
    }
  });
</code>```

Fix

Call the function to get its return value, e.g :

```<code>const createControls = () => {
      const c = new Controls();
      c.Control = new Array<Ctrl>();
      section.VisualComponents.forEach(vc => {
          c.Control.push({
            ....
            ....

        });
      });
      return c;
    };
export class Controls {
   Control: Control[];
}

page.Sections.push({
    ....
    Controls: createControls()
  });
</code>```

Body:
Error: Property 'Control' is missing in type '() => Controls' but required in type 'Controls'.

export class Controls {
   Control: Control[];
}

page.Sections.push({
    ....
    Controls: () => {
      const c = new Controls();
      c.Control = new Array<Ctrl>();
      section.VisualComponents.forEach(vc => {
          c.Control.push({
            ....
            ....

        });
      });
      return c;
    }
  });

What am I doing wrong?

Body:
You are required to have Controls[] array but are assigning a function Controls: () => {:

export class Controls {
   Control: Control[]; /// HERE
}

page.Sections.push({
    ....
    Controls: () => { // HERE
      const c = new Controls();
      c.Control = new Array<Ctrl>();
      section.VisualComponents.forEach(vc => {
          c.Control.push({
            ....
            ....

        });
      });
      return c;
    }
  });

Fix

Call the function to get its return value, e.g :

const createControls = () => {
      const c = new Controls();
      c.Control = new Array<Ctrl>();
      section.VisualComponents.forEach(vc => {
          c.Control.push({
            ....
            ....

        });
      });
      return c;
    };
export class Controls {
   Control: Control[];
}

page.Sections.push({
    ....
    Controls: createControls()
  });


问:
Recall the main method
I have done some code which I think could able to recall the main method. If the user input Y or y, I want the program to restast. The algorithm is already well-working, I just need the solution for the looping part. I tried to run it on command prompt

```<code>import java.util.Scanner;

class Quadratic{

    public static void main(String args[]){
        Scanner input = new Scanner (System.in);

        System.out.print("\nax^2 + bx + c = 0");

        //input value of a.
        System.out.print("\n\na = ");
        int a = input.nextInt();

        //input value of b.
        System.out.print("b = ");
        int b = input.nextInt();

        //input value of c.
        System.out.print("c = ");
        int c = input.nextInt();

        System.out.print("\n");

        //output a-part of the equation.
        if(a != 0){
            if(a == -1) {System.out.print("- ");}
            else if(a == 1) {System.out.print("");}
            else if(a < 0)  {System.out.print("- " + Math.abs(a));}
            else if(a > 0)  {System.out.print(a);}
            System.out.print("x^2 ");}
        //output b-part of the equation.
        if(b != 0){
            if(b == -1) {System.out.print("- ");}
            else if(b == 1) {System.out.print("+ ");}
            else if(b < 0)  {System.out.print("- " + Math.abs(b));}
            else if(b > 0)  {System.out.print("+ " + b);}
            System.out.print("x ");}
        //output c-part of the equation.
        if(c != 0){
            if(c < 0)   {System.out.print("- " + Math.abs(c));}
            else if(c > 0)  {System.out.print("+ " + c);}}
        //if everything is not zero.
        if(a != 0 && b != 0 && c != 0)  {System.out.print(" = 0\n\n");}
        //if everything is zero.
        else if(a == 0 && b == 0 && c == 0) {System.out.print("0 + 0 + 0 = 0\n\n");}

        Quadratic quad = new Quadratic();
        quad.findAnswer(a, b, c);
        quad.additionalRoot(a, b, c);

        quad.runAgain();
    }

    //find the final answer.
    private void findAnswer(int a, int b, int c){
        if(findDiscriminant(a, b, c) < 0){
            System.out.print("Imaginary Root");
        }

        else if(findDiscriminant(a, b, c) == 0){
            System.out.print("One Twin Root");
            findTwoRoot(a, b, c);
        }

        else if(findDiscriminant(a, b, c) > 0){
            System.out.print("Two Different Root");
            findTwoRoot(a, b, c);
        }
    }

    //find the discriminant of the quadratic-equation.
    private int findDiscriminant(int a, int b, int c){
        int discriminant = b*b - 4*a*c;
        return discriminant;
    }

    //find the two root of the quadratic-equation.
    private void findTwoRoot(int a, int b, int c){
        double x1 = (-b + Math.sqrt(findDiscriminant(a, b, c)))/2*a;
        double x2 = (-b - Math.sqrt(findDiscriminant(a, b, c)))/2*a;

        if(x1 == x2)    {System.out.print("\n\nx = " + x1);}
        else    {System.out.print("\nx1 = " + x1 + "\nx2 = " + x2);}
    }

    //find the additional value by root.
    private void additionalRoot(int a, int b, int c){
        double addition = -b/a;
        System.out.print("\n\nX1 + X2 = " + addition);
        double multiplication = c/a;
        System.out.print("\nX1 * X2 = " + multiplication);
        double xp = -b/2*a;
        double yp = findDiscriminant(a, b, c) / -4*a;
        System.out.print("\n\nCoordinate of the extreme value = (" + xp + ", " + yp + ")");
    }

    //rerun the main method.
    private void runAgain(){
        Scanner input = new Scanner(System.in);

        System.out.print("\n\nAgain? (Y/N)\n");
        String repeat = input.next();
        while(repeat == "Y" || repeat == "y"){
            runProgram();
            System.out.print("\n\nAgain? (Y/N)\n");
            repeat = input.next();
        }
    }

    //the main program.
    private void runProgram(){
        Scanner input = new Scanner (System.in);

        System.out.print("\nax^2 + bx + c = 0");

        //input value of a.
        System.out.print("\n\na = ");
        int a = input.nextInt();

        //input value of b.
        System.out.print("b = ");
        int b = input.nextInt();

        //input value of c.
        System.out.print("c = ");
        int c = input.nextInt();

        System.out.print("\n");

        //output a-part of the equation.
        if(a != 0){
            if(a == -1) {System.out.print("- ");}
            else if(a == 1) {System.out.print("");}
            else if(a < 0)  {System.out.print("- " + Math.abs(a));}
            else if(a > 0)  {System.out.print(a);}
            System.out.print("x^2 ");}
        //output b-part of the equation.
        if(b != 0){
            if(b == -1) {System.out.print("- ");}
            else if(b == 1) {System.out.print("+ ");}
            else if(b < 0)  {System.out.print("- " + Math.abs(b));}
            else if(b > 0)  {System.out.print("+ " + b);}
            System.out.print("x ");}
        //output c-part of the equation.
        if(c != 0){
            if(c < 0)   {System.out.print("- " + Math.abs(c));}
            else if(c > 0)  {System.out.print("+ " + c);}}
        //if everything is not zero.
        if(a != 0 && b != 0 && c != 0)  {System.out.print(" = 0\n\n");}
        //if everything is zero.
        else if(a == 0 && b == 0 && c == 0) {System.out.print("0 + 0 + 0 = 0\n\n");}

        Quadratic quad = new Quadratic();
        quad.findAnswer(a, b, c);
        quad.additionalRoot(a, b, c);

        quad.runAgain();
    }
}
</code>```

What should I do to recall the main method?

答:
I made a couple of changes. First, I made runAgain a boolean function and put the main part in a while loop that checks if the player wants to play again. Also, I tried not reopening the Scanner because it was giving me an error on jdoodle (it also wanted the class to be public). Finally, I rewrote the string comparisons to use .equal. The reuslting program appears to do what you want.</p>

```<code>import java.util.Scanner;

public class Quadratic {

public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    boolean keepPlaying = true;
    while (keepPlaying) {
        System.out.print("\nax^2 + bx + c = 0");

        //input value of a.
        System.out.print("\n\na = ");
        int a = input.nextInt();

        //input value of b.
        System.out.print("b = ");
        int b = input.nextInt();

        //input value of c.
        System.out.print("c = ");
        int c = input.nextInt();

        System.out.print("\n");

        //output a-part of the equation.
        if (a != 0) {
            if (a == -1) {
                System.out.print("- ");
            } else if (a == 1) {
                System.out.print("");
            } else if (a < 0) {
                System.out.print("- " + Math.abs(a));
            } else if (a > 0) {
                System.out.print(a);
            }
            System.out.print("x^2 ");
        }
        //output b-part of the equation.
        if (b != 0) {
            if (b == -1) {
                System.out.print("- ");
            } else if (b == 1) {
                System.out.print("+ ");
            } else if (b < 0) {
                System.out.print("- " + Math.abs(b));
            } else if (b > 0) {
                System.out.print("+ " + b);
            }
            System.out.print("x ");
        }
        //output c-part of the equation.
        if (c != 0) {
            if (c < 0) {
                System.out.print("- " + Math.abs(c));
            } else if (c > 0) {
                System.out.print("+ " + c);
            }
        }
        //if everything is not zero.
        if (a != 0 && b != 0 && c != 0) {
            System.out.print(" = 0\n\n");
        }
        //if everything is zero.
        else if (a == 0 && b == 0 && c == 0) {
            System.out.print("0 + 0 + 0 = 0\n\n");
        }

        Quadratic quad = new Quadratic();
        quad.findAnswer(a, b, c);
        quad.additionalRoot(a, b, c);

        keepPlaying = quad.runAgain(input);
    }
}

//find the final answer.
private void findAnswer(int a, int b, int c) {
    if (findDiscriminant(a, b, c) < 0) {
        System.out.print("Imaginary Root");
    } else if (findDiscriminant(a, b, c) == 0) {
        System.out.print("One Twin Root");
        findTwoRoot(a, b, c);
    } else if (findDiscriminant(a, b, c) > 0) {
        System.out.print("Two Different Root");
        findTwoRoot(a, b, c);
    }
}

//find the discriminant of the quadratic-equation.
private int findDiscriminant(int a, int b, int c) {
    int discriminant = b * b - 4 * a * c;
    return discriminant;
}

//find the two root of the quadratic-equation.
private void findTwoRoot(int a, int b, int c) {
    double x1 = (-b + Math.sqrt(findDiscriminant(a, b, c))) / 2 * a;
    double x2 = (-b - Math.sqrt(findDiscriminant(a, b, c))) / 2 * a;

    if (x1 == x2) {
        System.out.print("\n\nx = " + x1);
    } else {
        System.out.print("\nx1 = " + x1 + "\nx2 = " + x2);
    }
}

//find the additional value by root.
private void additionalRoot(int a, int b, int c) {
    double addition = -b / a;
    System.out.print("\n\nX1 + X2 = " + addition);
    double multiplication = c / a;
    System.out.print("\nX1 * X2 = " + multiplication);
    double xp = -b / 2 * a;
    double yp = findDiscriminant(a, b, c) / -4 * a;
    System.out.print("\n\nCoordinate of the extreme value = (" + xp + ", " + yp + ")");
}

//see whether to rerun the main method.
private boolean runAgain(Scanner input) {

    System.out.print("\n\nAgain? (Y/N)\n");
    String repeat = input.next();
    return (repeat.equals("Y") || repeat.equals("y"));
}

}
</code>```

Title: Recall the main method

Body:
I have done some code which I think could able to recall the main method. If the user input Y or y, I want the program to restast. The algorithm is already well-working, I just need the solution for the looping part. I tried to run it on command prompt

import java.util.Scanner;

class Quadratic{

    public static void main(String args[]){
        Scanner input = new Scanner (System.in);

        System.out.print("\nax^2 + bx + c = 0");

        //input value of a.
        System.out.print("\n\na = ");
        int a = input.nextInt();

        //input value of b.
        System.out.print("b = ");
        int b = input.nextInt();

        //input value of c.
        System.out.print("c = ");
        int c = input.nextInt();

        System.out.print("\n");

        //output a-part of the equation.
        if(a != 0){
            if(a == -1) {System.out.print("- ");}
            else if(a == 1) {System.out.print("");}
            else if(a < 0)  {System.out.print("- " + Math.abs(a));}
            else if(a > 0)  {System.out.print(a);}
            System.out.print("x^2 ");}
        //output b-part of the equation.
        if(b != 0){
            if(b == -1) {System.out.print("- ");}
            else if(b == 1) {System.out.print("+ ");}
            else if(b < 0)  {System.out.print("- " + Math.abs(b));}
            else if(b > 0)  {System.out.print("+ " + b);}
            System.out.print("x ");}
        //output c-part of the equation.
        if(c != 0){
            if(c < 0)   {System.out.print("- " + Math.abs(c));}
            else if(c > 0)  {System.out.print("+ " + c);}}
        //if everything is not zero.
        if(a != 0 && b != 0 && c != 0)  {System.out.print(" = 0\n\n");}
        //if everything is zero.
        else if(a == 0 && b == 0 && c == 0) {System.out.print("0 + 0 + 0 = 0\n\n");}

        Quadratic quad = new Quadratic();
        quad.findAnswer(a, b, c);
        quad.additionalRoot(a, b, c);

        quad.runAgain();
    }

    //find the final answer.
    private void findAnswer(int a, int b, int c){
        if(findDiscriminant(a, b, c) < 0){
            System.out.print("Imaginary Root");
        }

        else if(findDiscriminant(a, b, c) == 0){
            System.out.print("One Twin Root");
            findTwoRoot(a, b, c);
        }

        else if(findDiscriminant(a, b, c) > 0){
            System.out.print("Two Different Root");
            findTwoRoot(a, b, c);
        }
    }

    //find the discriminant of the quadratic-equation.
    private int findDiscriminant(int a, int b, int c){
        int discriminant = b*b - 4*a*c;
        return discriminant;
    }

    //find the two root of the quadratic-equation.
    private void findTwoRoot(int a, int b, int c){
        double x1 = (-b + Math.sqrt(findDiscriminant(a, b, c)))/2*a;
        double x2 = (-b - Math.sqrt(findDiscriminant(a, b, c)))/2*a;

        if(x1 == x2)    {System.out.print("\n\nx = " + x1);}
        else    {System.out.print("\nx1 = " + x1 + "\nx2 = " + x2);}
    }

    //find the additional value by root.
    private void additionalRoot(int a, int b, int c){
        double addition = -b/a;
        System.out.print("\n\nX1 + X2 = " + addition);
        double multiplication = c/a;
        System.out.print("\nX1 * X2 = " + multiplication);
        double xp = -b/2*a;
        double yp = findDiscriminant(a, b, c) / -4*a;
        System.out.print("\n\nCoordinate of the extreme value = (" + xp + ", " + yp + ")");
    }

    //rerun the main method.
    private void runAgain(){
        Scanner input = new Scanner(System.in);

        System.out.print("\n\nAgain? (Y/N)\n");
        String repeat = input.next();
        while(repeat == "Y" || repeat == "y"){
            runProgram();
            System.out.print("\n\nAgain? (Y/N)\n");
            repeat = input.next();
        }
    }

    //the main program.
    private void runProgram(){
        Scanner input = new Scanner (System.in);

        System.out.print("\nax^2 + bx + c = 0");

        //input value of a.
        System.out.print("\n\na = ");
        int a = input.nextInt();

        //input value of b.
        System.out.print("b = ");
        int b = input.nextInt();

        //input value of c.
        System.out.print("c = ");
        int c = input.nextInt();

        System.out.print("\n");

        //output a-part of the equation.
        if(a != 0){
            if(a == -1) {System.out.print("- ");}
            else if(a == 1) {System.out.print("");}
            else if(a < 0)  {System.out.print("- " + Math.abs(a));}
            else if(a > 0)  {System.out.print(a);}
            System.out.print("x^2 ");}
        //output b-part of the equation.
        if(b != 0){
            if(b == -1) {System.out.print("- ");}
            else if(b == 1) {System.out.print("+ ");}
            else if(b < 0)  {System.out.print("- " + Math.abs(b));}
            else if(b > 0)  {System.out.print("+ " + b);}
            System.out.print("x ");}
        //output c-part of the equation.
        if(c != 0){
            if(c < 0)   {System.out.print("- " + Math.abs(c));}
            else if(c > 0)  {System.out.print("+ " + c);}}
        //if everything is not zero.
        if(a != 0 && b != 0 && c != 0)  {System.out.print(" = 0\n\n");}
        //if everything is zero.
        else if(a == 0 && b == 0 && c == 0) {System.out.print("0 + 0 + 0 = 0\n\n");}

        Quadratic quad = new Quadratic();
        quad.findAnswer(a, b, c);
        quad.additionalRoot(a, b, c);

        quad.runAgain();
    }
}

What should I do to recall the main method?

Body:
I made a couple of changes. First, I made runAgain a boolean function and put the main part in a while loop that checks if the player wants to play again. Also, I tried not reopening the Scanner because it was giving me an error on jdoodle (it also wanted the class to be public). Finally, I rewrote the string comparisons to use .equal. The reuslting program appears to do what you want.

import java.util.Scanner;

public class Quadratic {

public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    boolean keepPlaying = true;
    while (keepPlaying) {
        System.out.print("\nax^2 + bx + c = 0");

        //input value of a.
        System.out.print("\n\na = ");
        int a = input.nextInt();

        //input value of b.
        System.out.print("b = ");
        int b = input.nextInt();

        //input value of c.
        System.out.print("c = ");
        int c = input.nextInt();

        System.out.print("\n");

        //output a-part of the equation.
        if (a != 0) {
            if (a == -1) {
                System.out.print("- ");
            } else if (a == 1) {
                System.out.print("");
            } else if (a < 0) {
                System.out.print("- " + Math.abs(a));
            } else if (a > 0) {
                System.out.print(a);
            }
            System.out.print("x^2 ");
        }
        //output b-part of the equation.
        if (b != 0) {
            if (b == -1) {
                System.out.print("- ");
            } else if (b == 1) {
                System.out.print("+ ");
            } else if (b < 0) {
                System.out.print("- " + Math.abs(b));
            } else if (b > 0) {
                System.out.print("+ " + b);
            }
            System.out.print("x ");
        }
        //output c-part of the equation.
        if (c != 0) {
            if (c < 0) {
                System.out.print("- " + Math.abs(c));
            } else if (c > 0) {
                System.out.print("+ " + c);
            }
        }
        //if everything is not zero.
        if (a != 0 && b != 0 && c != 0) {
            System.out.print(" = 0\n\n");
        }
        //if everything is zero.
        else if (a == 0 && b == 0 && c == 0) {
            System.out.print("0 + 0 + 0 = 0\n\n");
        }

        Quadratic quad = new Quadratic();
        quad.findAnswer(a, b, c);
        quad.additionalRoot(a, b, c);

        keepPlaying = quad.runAgain(input);
    }
}

//find the final answer.
private void findAnswer(int a, int b, int c) {
    if (findDiscriminant(a, b, c) < 0) {
        System.out.print("Imaginary Root");
    } else if (findDiscriminant(a, b, c) == 0) {
        System.out.print("One Twin Root");
        findTwoRoot(a, b, c);
    } else if (findDiscriminant(a, b, c) > 0) {
        System.out.print("Two Different Root");
        findTwoRoot(a, b, c);
    }
}

//find the discriminant of the quadratic-equation.
private int findDiscriminant(int a, int b, int c) {
    int discriminant = b * b - 4 * a * c;
    return discriminant;
}

//find the two root of the quadratic-equation.
private void findTwoRoot(int a, int b, int c) {
    double x1 = (-b + Math.sqrt(findDiscriminant(a, b, c))) / 2 * a;
    double x2 = (-b - Math.sqrt(findDiscriminant(a, b, c))) / 2 * a;

    if (x1 == x2) {
        System.out.print("\n\nx = " + x1);
    } else {
        System.out.print("\nx1 = " + x1 + "\nx2 = " + x2);
    }
}

//find the additional value by root.
private void additionalRoot(int a, int b, int c) {
    double addition = -b / a;
    System.out.print("\n\nX1 + X2 = " + addition);
    double multiplication = c / a;
    System.out.print("\nX1 * X2 = " + multiplication);
    double xp = -b / 2 * a;
    double yp = findDiscriminant(a, b, c) / -4 * a;
    System.out.print("\n\nCoordinate of the extreme value = (" + xp + ", " + yp + ")");
}

//see whether to rerun the main method.
private boolean runAgain(Scanner input) {

    System.out.print("\n\nAgain? (Y/N)\n");
    String repeat = input.next();
    return (repeat.equals("Y") || repeat.equals("y"));
}

}


问:
how to ignore a property by attribute in nhibernate
How can i ignore a property by decorating a property with an attribute? the base class AttributePropertyConvention doesn't seems to have that ability, or can it? Doesn't find anything sutiable on IPropertyInstance to set..

答:
The following code will prevent a column from generated in your database.</p>

```<code>public class MyEntity
{
    [NotMapped]
    public bool A => true;
}

public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Member member)
    {
        if (member.MemberInfo.GetCustomAttributes(typeof(NotMappedAttribute), true).Length > 0)
        {
            return false;
        }
        return base.ShouldMap(member);
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The following code will prevent a column from generated in your database.

public class MyEntity
{
    [NotMapped]
    public bool A => true;
}

public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Member member)
    {
        if (member.MemberInfo.GetCustomAttributes(typeof(NotMappedAttribute), true).Length > 0)
        {
            return false;
        }
        return base.ShouldMap(member);
    }
}


问:
Not able to predict output in fastai
Noob here.

Here's the dataset that I'm working on https://www.kaggle.com/arpitjain007/game-of-deep-learning-ship-datasets

and I'm using fastai, I've successfully built the model but I have no idea how to test it with 'test.csv' file.

Here's my code

```<code>from fastai import *
from fastai.vision import *

path = '../input/train'
path = Path(path)
path.ls()
df = pd.read_csv(path/'train.csv')
data = ImageDataBunch.from_df('../input/train/images', df, ds_tfms=get_transforms(), size=224, bs=64 ).normalize(imagenet_stats)
learn = cnn_learner(data, models.resnet50, metrics=accuracy,  model_dir='/kaggle/working/models')
learn.fit_one_cycle(5)
df_test = pd.read_csv('../input/test_ApKoW4T.csv')
</code>```

I don't know how to use the Test Dataframe to predict.

答:
All i had to do was create an Image List

```<code>train = ImageList.from_df(df,'../input/train/images')
test = ImageList.from_df(df_test, '../input/train/images')
</code>```

then create ImageDataBunch

```<code>data = ImageDataBunch.from_df('../input/train/images', df,
ds_tfms=get_transforms(), size=224, bs=64 ).normalize(imagenet_stats)
</code>```

then add test

```<code>data.add_test(test)
</code>```

and then predict using

```<code>predictions, *_ = learn.get_preds(DatasetType.Test)
labels = np.argmax(predictions, 1)
df_test['category'] = labels
</code>```

Title: Not able to predict output in fastai

Body:
Noob here.

Here's the dataset that I'm working on https://www.kaggle.com/arpitjain007/game-of-deep-learning-ship-datasets

and I'm using fastai, I've successfully built the model but I have no idea how to test it with 'test.csv' file.

Here's my code

from fastai import *
from fastai.vision import *

path = '../input/train'
path = Path(path)
path.ls()
df = pd.read_csv(path/'train.csv')
data = ImageDataBunch.from_df('../input/train/images', df, ds_tfms=get_transforms(), size=224, bs=64 ).normalize(imagenet_stats)
learn = cnn_learner(data, models.resnet50, metrics=accuracy,  model_dir='/kaggle/working/models')
learn.fit_one_cycle(5)
df_test = pd.read_csv('../input/test_ApKoW4T.csv')

I don't know how to use the Test Dataframe to predict.

Body:
All i had to do was create an Image List

train = ImageList.from_df(df,'../input/train/images')
test = ImageList.from_df(df_test, '../input/train/images')

then create ImageDataBunch

data = ImageDataBunch.from_df('../input/train/images', df,
ds_tfms=get_transforms(), size=224, bs=64 ).normalize(imagenet_stats)

then add test

data.add_test(test)

and then predict using

predictions, *_ = learn.get_preds(DatasetType.Test)
labels = np.argmax(predictions, 1)
df_test['category'] = labels


问:
How to enable TaskO in Azure DevOps
I installed the TaskO extension for my Azure DevOps organization. However, when I open one of my projects that uses the Scrum or Agile process I do not see where to create the automated tasks. Does anyone know how to create tasks with this extension? </p>

答: Following TaskO UI is shown for each project. You can add tasks to the project, edit and delete them. These work as templates for actual tasks which are created by Azure DevOps whenever you add requirement/user story/PBI. You can also see the button to add the tasks for existing requirements. This TaskO UI is not required to be used after you have defined the tasks for that project. Creation of the actual tasks works in the background.</p>

Title: How to enable TaskO in Azure DevOps


问:
Why I can't update my one-to-one model's FileField in Django?
In order to add more features to the default model, I employed one-to-one filed in Django. Then I want to customize my update/edit Userprofile page.
I rewrite the update form like this ：

```<code>{% load static %}
...

<div  id="block-center" class="col-md-6 col-md-offset-3">

<form method="post">
  {% csrf_token %}
          ...
          <div class="form-group">
            <p>
                <label for="id_location">Location:</label> <input class="form-control" placeholder="Location"type="text" name="location" value="{{user.profile.location}}"maxlength="30" id="id_location" />
            </p>
          </div>
          <div class="form-group">
                {% if user.profile.upload.url%}
                <p class="file-upload">Currently: <img src="{{user.profile.upload.url}}" alt="Avatar" class="avatar"><br></p>
                <label for="id_upload">Change:</label> <input type="file" name="upload"  value="{{user.profile.upload}}" id="id_upload" />

                {% else%}
                <label for="id_upload">Avator:</label> <input type="file" name="upload"  value="{{user.profile.upload}}" id="id_upload" />
                {% endif %}
          </div>
          <button class="btn btn-primary" type="submit">Save changes</button>
</form>
</div>
</code>```

My models.py:

```<code>from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    upload = models.FileField()
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()
</code>```

My views.py:

```<code>from django.db import models
from django.contrib.auth.models import User
from users.forms import UserForm,ProfileForm
from django.contrib import messages
from django.shortcuts import render,redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.utils.translation import gettext as _

@login_required
@transaction.atomic
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        profile = request.user.profile
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, _('Your profile was successfully updated!'))
            return redirect('blog:index')
        else:
            messages.error(request, _('Please correct the error below.'))

    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
        user = User.objects.get(id=request.user.id)
        profile = request.user.profile
    return render(request, 'profiles/profile.html', {
        'user_form': user_form,
        'profile_form': profile_form,
        'profile':profile
    })
</code>```

All other fields work well except the filefield upload in Userprofile model. I don't know why. Can any one help me?

答:
Try adding enctype to your form tag:

```<code><form method="post" enctype="multipart/form-data">
</code>```

It's necessary when uploading files.

Body:
In order to add more features to the default model, I employed one-to-one filed in Django. Then I want to customize my update/edit Userprofile page.
I rewrite the update form like this ：

{% load static %}
...

<form method="post">
  {% csrf_token %}
          ...

                Location: <input class="form-control" placeholder="Location"type="text" name="location" value="{{user.profile.location}}"maxlength="30" id="id_location" />

                {% if user.profile.upload.url%}

Currently:

                Change: <input type="file" name="upload"  value="{{user.profile.upload}}" id="id_upload" />

                {% else%}
                Avator: <input type="file" name="upload"  value="{{user.profile.upload}}" id="id_upload" />
                {% endif %}

          <button class="btn btn-primary" type="submit">Save changes</button>
</form>

My models.py:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    upload = models.FileField()
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

My views.py:

from django.db import models
from django.contrib.auth.models import User
from users.forms import UserForm,ProfileForm
from django.contrib import messages
from django.shortcuts import render,redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.utils.translation import gettext as _

@login_required
@transaction.atomic
def update_profile(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        profile = request.user.profile
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, _('Your profile was successfully updated!'))
            return redirect('blog:index')
        else:
            messages.error(request, _('Please correct the error below.'))

    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)
        user = User.objects.get(id=request.user.id)
        profile = request.user.profile
    return render(request, 'profiles/profile.html', {
        'user_form': user_form,
        'profile_form': profile_form,
        'profile':profile
    })

All other fields work well except the filefield upload in Userprofile model. I don't know why. Can any one help me?

Body:
Try adding enctype to your form tag:

<form method="post" enctype="multipart/form-data">

It's necessary when uploading files.


问:
Database is not updating data from one activity to another
I need to pass data from DeleteLayout to update data in historyActivity which will update once I edit the data.It does not throw any error but my data is not updating after editing. What can be done to pass data between activities and update the database.

My updateDatamethod in DatabaseHelper looks like this:

```<code>    public boolean updateData(String goalDate, String goalWeight, String currentWeight){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        String where = "GDATE = ? AND GWEIGHT = ?  AND CWEIGHT = ?";
        contentValues.put(Col2, goalDate);
        contentValues.put(Col3, goalWeight);
        contentValues.put(Col4, currentWeight);
        db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight});
        return true;
    }
</code>```

Deletelayout

```<code>   protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.deletelayout);
        GoalDate = findViewById(R.id.goalDate2);
        CurrentWeight = findViewById(R.id.weighGoal2);
        GoalWeight = findViewById(R.id.weightCurrent2);
        goalD = findViewById(R.id.goalDateInput);
        goalW = findViewById(R.id.goalWeightInput);
        currentW = findViewById(R.id.currentWeightInput);

        imageView = findViewById(R.id.imageShow);
        data = myDB.getListContents();
        deleteB = findViewById(R.id.deleteB);
        updateB = findViewById(R.id.updateButton);
        // Entered information from the user are set to the respective variables.
        int numRows = data.getCount();
        j = new Intent(DeleteLayout.this, historyActivity.class);

        if (numRows == 0) {
            Toast.makeText(DeleteLayout.this, "Nothing in the db", Toast.LENGTH_LONG).show();
        } else {
            int i = 0;
            while (data.moveToNext()) {
                user = new User(data.getString(1), data.getString(2), data.getString(3), data.getString(4), data.getString(5));
                gWt = user.getGoalWeight();
                cWt = user.getCurrentWeight();
                gDt = user.getGoalDate();
                GoalDate.setText(gDt);
                GoalWeight.setText(gWt);
                CurrentWeight.setText(cWt);

                deleteB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDB.deleteContent(GoalDate.getText().toString(), GoalWeight.getText().toString(), CurrentWeight.getText().toString());
                        startActivity(j);
                    }
                });
                updateB.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        boolean myUpdate = myDB.updateData(goalD.getText().toString(), goalW.getText().toString(), currentW.getText().toString());
                        if(myUpdate == true){
                            Toast.makeText(DeleteLayout.this, "Data updated", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            Toast.makeText(DeleteLayout.this, "Data not updated", Toast.LENGTH_SHORT).show();

                        }
                        startActivity(j);
                    }
                });
            }

        }

    }
</code>```

答:
Issues

One issue you have is that you are not asking for any changes to be made.

Additionally you are always assuming that a row or rows have always been update, i.e. you are not checking to see if any updates have been performed.

The SQliteDatabase update method returns an int that has the number of rows that have been updated. If  none are updated then it will return 0.

Explanation

Consider that goalDate is 2019-01-01 and goalWeight is 100 and currentWeight is 200, then you are saying

update

goalDate to 2019-01-01 and

goalWeight to 100 and

currentWeight to 200

for the row(s) where

goalDate is 2019-01-01 and

goalWeight is 100 and

currentWeight is 200

Fix

Instead of :-

```<code>public boolean updateData(String goalDate, String goalWeight, String currentWeight){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    String where = "GDATE = ? AND GWEIGHT = ?  AND CWEIGHT = ?";
    contentValues.put(Col2, goalDate);
    contentValues.put(Col3, goalWeight);
    contentValues.put(Col4, currentWeight);
    db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight});
    return true;
}
</code>```

What you want is something along the lines of :-

```<code>public boolean updateData(String goalDate, String goalWeight, String currentWeight, String newGoaldate, String newGoalWeight, String newCurrentWeight){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    String where = "GDATE = ? AND GWEIGHT = ?  AND CWEIGHT = ?";
    contentValues.put(Col2, newGoalDate);
    contentValues.put(Col3, newGoalWeight);
    contentValues.put(Col4, newCurrentWeight);
    if (db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight}) > 0) {
        return true;
    }
    return false;
}
</code>```

The first 3 parameters are the original values (used to locate the row to be updated), the second set are the values to be used to update the located row or rows).

Extra

Ideally you should also change :-

```<code> String where = "GDATE = ? AND GWEIGHT = ?  AND CWEIGHT = ?";
</code>```

to :-

```<code>String where = Col2 + "=? AND " + Col3 + "=?  AND " + Col4 +"=?";
</code>```

Body:
I need to pass data from DeleteLayout to update data in historyActivity which will update once I edit the data.It does not throw any error but my data is not updating after editing. What can be done to pass data between activities and update the database.

My updateDatamethod in DatabaseHelper looks like this:

    public boolean updateData(String goalDate, String goalWeight, String currentWeight){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        String where = "GDATE = ? AND GWEIGHT = ?  AND CWEIGHT = ?";
        contentValues.put(Col2, goalDate);
        contentValues.put(Col3, goalWeight);
        contentValues.put(Col4, currentWeight);
        db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight});
        return true;
    }

Deletelayout

   protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.deletelayout);
        GoalDate = findViewById(R.id.goalDate2);
        CurrentWeight = findViewById(R.id.weighGoal2);
        GoalWeight = findViewById(R.id.weightCurrent2);
        goalD = findViewById(R.id.goalDateInput);
        goalW = findViewById(R.id.goalWeightInput);
        currentW = findViewById(R.id.currentWeightInput);

        imageView = findViewById(R.id.imageShow);
        data = myDB.getListContents();
        deleteB = findViewById(R.id.deleteB);
        updateB = findViewById(R.id.updateButton);
        // Entered information from the user are set to the respective variables.
        int numRows = data.getCount();
        j = new Intent(DeleteLayout.this, historyActivity.class);

        if (numRows == 0) {
            Toast.makeText(DeleteLayout.this, "Nothing in the db", Toast.LENGTH_LONG).show();
        } else {
            int i = 0;
            while (data.moveToNext()) {
                user = new User(data.getString(1), data.getString(2), data.getString(3), data.getString(4), data.getString(5));
                gWt = user.getGoalWeight();
                cWt = user.getCurrentWeight();
                gDt = user.getGoalDate();
                GoalDate.setText(gDt);
                GoalWeight.setText(gWt);
                CurrentWeight.setText(cWt);

                deleteB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDB.deleteContent(GoalDate.getText().toString(), GoalWeight.getText().toString(), CurrentWeight.getText().toString());
                        startActivity(j);
                    }
                });
                updateB.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        boolean myUpdate = myDB.updateData(goalD.getText().toString(), goalW.getText().toString(), currentW.getText().toString());
                        if(myUpdate == true){
                            Toast.makeText(DeleteLayout.this, "Data updated", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            Toast.makeText(DeleteLayout.this, "Data not updated", Toast.LENGTH_SHORT).show();

                        }
                        startActivity(j);
                    }
                });
            }

        }

    }

Body:
Issues

One issue you have is that you are not asking for any changes to be made.

Additionally you are always assuming that a row or rows have always been update, i.e. you are not checking to see if any updates have been performed.

The SQliteDatabase update method returns an int that has the number of rows that have been updated. If  none are updated then it will return 0.

Explanation

Consider that goalDate is 2019-01-01 and goalWeight is 100 and currentWeight is 200, then you are saying

update

goalDate to 2019-01-01 and

goalWeight to 100 and

currentWeight to 200

for the row(s) where

goalDate is 2019-01-01 and

goalWeight is 100 and

currentWeight is 200

Fix

Instead of :-

public boolean updateData(String goalDate, String goalWeight, String currentWeight){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    String where = "GDATE = ? AND GWEIGHT = ?  AND CWEIGHT = ?";
    contentValues.put(Col2, goalDate);
    contentValues.put(Col3, goalWeight);
    contentValues.put(Col4, currentWeight);
    db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight});
    return true;
}

What you want is something along the lines of :-

public boolean updateData(String goalDate, String goalWeight, String currentWeight, String newGoaldate, String newGoalWeight, String newCurrentWeight){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    String where = "GDATE = ? AND GWEIGHT = ?  AND CWEIGHT = ?";
    contentValues.put(Col2, newGoalDate);
    contentValues.put(Col3, newGoalWeight);
    contentValues.put(Col4, newCurrentWeight);
    if (db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight}) > 0) {
        return true;
    }
    return false;
}

The first 3 parameters are the original values (used to locate the row to be updated), the second set are the values to be used to update the located row or rows).

Extra

Ideally you should also change :-

 String where = "GDATE = ? AND GWEIGHT = ?  AND CWEIGHT = ?";

to :-

String where = Col2 + "=? AND " + Col3 + "=?  AND " + Col4 +"=?";


问:
RegEx for capturing numbers in parentheses
Example

```<code>Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]
</code>```

I want to get 15.7 from Alarm Level 1 and -12.7 from Alarm Level 2.  I tried to use \((.*?)\) but it get both D1 and 15.7 in Alarm Level 1.

答:
The easiest to way to handle this would probably be to match on the following pattern:

```<code>\[[^(]+\((-?\d+(?:\.\d+)?)\)\]
</code>```

The strategy here is to match an entire term such as [High (-12.7)], and then capture the number inside round parentheses.

For example, in Python we can try the following:

```<code>input = """Alarm Level 1 (D1) [Low (15.7)]
           Alarm Level 2 [High (-12.7)]"""

matches = re.findall(r'\[[^(]+\((-?\d+(?:\.\d+)?)\)\]', input)
print(matches)
</code>```

This prints:

```<code>['15.7', '-12.7']
</code>```

Body:
Example

Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]

I want to get 15.7 from Alarm Level 1 and -12.7 from Alarm Level 2.  I tried to use \((.*?)\) but it get both D1 and 15.7 in Alarm Level 1.

Body:
The easiest to way to handle this would probably be to match on the following pattern:

\[[^(]+\((-?\d+(?:\.\d+)?)\)\]

The strategy here is to match an entire term such as [High (-12.7)], and then capture the number inside round parentheses.

For example, in Python we can try the following:

input = """Alarm Level 1 (D1) [Low (15.7)]
           Alarm Level 2 [High (-12.7)]"""

matches = re.findall(r'\[[^(]+\((-?\d+(?:\.\d+)?)\)\]', input)
print(matches)

This prints:

['15.7', '-12.7']


问:
In group sort table join a another table use first func
First I use window func sort my table t1 by charge_time and put t1 join with t2 on user_id.
I want to get first record if t1 has more than one record.
I use first func to implement this

```<code>    _df = ss.sql("""
                    SELECT
                        t1.user_id,
                        t1.pay_id,
                        t1.sku_mode,
                        t1.charge_time,
                        t1.exchange_type_t01,
                        ROW_NUMBER() OVER(PARTITION BY t1.user_id ORDER BY t1.charge_time)
                    FROM
                        {} t1
                    WHERE
                        t1.refund_state = 0
                """.format(exchange_info_table))
    _df.createOrReplaceTempView('d_exchange_info')

    df = ss.sql("""
            SELECT
                first(t1.sku_mode) AS sku_mode,
                first(t1.exchange_type_t01) AS exchange_type_t01,
                first(t1.user_id) AS user_id,
                first(t1.pay_id) AS pay_id,
                first(t1.charge_time) AS charge_time,
                first(t2.has_yxs_payment) AS has_yxs_payment,
                first(t2.has_sxy_payment) AS has_sxy_payment,
                first(t2.has_cxy_payment) AS has_cxy_payment,
                first(t2.has_sxy19_payment) AS has_sxy19_payment,
                first(t2.sxy19_join_time) AS sxy19_join_time,
                first(t2.yxs_join_time) AS yxs_join_time
            FROM
                d_exchange_info t1
            JOIN
                analytics_db.md_day_dump_users t2
            ON
                t2.the_day = '{}'
                AND t1.user_id = t2.user_id
            GROUP BY
                t1.user_id
    """.format(st))
</code>```

I use first func but I will get an unstable record by sort with charge_time record.
If records more than one, sometimes I get a one sometimes a get another

Why it happen and how to fix it?
It's a sparksql prob or my sql have some prob?

PS: I already know how to fix it with another way but I want to know why first func  not effective.

Thanks!

答:
I don't know a lot about spark, but from the documentation:

```<code>The function is non-deterministic because its results depends on order of rows
which may be non-deterministic after a shuffle.
</code>```

Your window function seems to be producing a row_number, but you are not using that anywhere.

You either need to sort your result set or if your intention is to use the row number you generated then add where row_number=1. You also have to name your row_number column unless it is done explicitly by spark.

Body:
First I use window func sort my table t1 by charge_time and put t1 join with t2 on user_id.
I want to get first record if t1 has more than one record.
I use first func to implement this

    _df = ss.sql("""
                    SELECT
                        t1.user_id,
                        t1.pay_id,
                        t1.sku_mode,
                        t1.charge_time,
                        t1.exchange_type_t01,
                        ROW_NUMBER() OVER(PARTITION BY t1.user_id ORDER BY t1.charge_time)
                    FROM
                        {} t1
                    WHERE
                        t1.refund_state = 0
                """.format(exchange_info_table))
    _df.createOrReplaceTempView('d_exchange_info')

    df = ss.sql("""
            SELECT
                first(t1.sku_mode) AS sku_mode,
                first(t1.exchange_type_t01) AS exchange_type_t01,
                first(t1.user_id) AS user_id,
                first(t1.pay_id) AS pay_id,
                first(t1.charge_time) AS charge_time,
                first(t2.has_yxs_payment) AS has_yxs_payment,
                first(t2.has_sxy_payment) AS has_sxy_payment,
                first(t2.has_cxy_payment) AS has_cxy_payment,
                first(t2.has_sxy19_payment) AS has_sxy19_payment,
                first(t2.sxy19_join_time) AS sxy19_join_time,
                first(t2.yxs_join_time) AS yxs_join_time
            FROM
                d_exchange_info t1
            JOIN
                analytics_db.md_day_dump_users t2
            ON
                t2.the_day = '{}'
                AND t1.user_id = t2.user_id
            GROUP BY
                t1.user_id
    """.format(st))

I use first func but I will get an unstable record by sort with charge_time record.
If records more than one, sometimes I get a one sometimes a get another

Why it happen and how to fix it?
It's a sparksql prob or my sql have some prob?

PS: I already know how to fix it with another way but I want to know why first func  not effective.

Thanks!

Body:
I don't know a lot about spark, but from the documentation:

The function is non-deterministic because its results depends on order of rows
which may be non-deterministic after a shuffle.

Your window function seems to be producing a row_number, but you are not using that anywhere.

You either need to sort your result set or if your intention is to use the row number you generated then add where row_number=1. You also have to name your row_number column unless it is done explicitly by spark.


问:
How to animate negative margin only
I have this

```<code>ul{
    -webkit-transition: all 1000ms linear;
    transition: all 1000ms linear;
}
</code>```

Then with javascript, amongst other things

```<code>let px = 295 // increments through other things
document.getElementsByTagName('ul')[0].style.marginLeft = `-${px}px`;
</code>```

Then the ul comes back to margin-left:0, but I want it to animate on negative margin and just snap on margin-left:0

edit:

The first answer sounds as though I'm not clear. I want to click on an element and have it animate one way, and then snap back to the default position. The usual  transitions animate both ways

答:
Try to use class for animation and use jQuery to manage these classes

Take a look at my example

$('button').click(function() {
  $('ul').toggleClass('animated');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  margin-left: 200px;
  -webkit-transition: margin 1000ms linear;
  transition: margin 1000ms linear;
}

ul.animated {
  margin-left: 0;
}</code>```

test

<button>Animate</button>```

Title: How to animate negative margin only

Body:
I have this

ul{
    -webkit-transition: all 1000ms linear;
    transition: all 1000ms linear;
}

Then with javascript, amongst other things

let px = 295 // increments through other things
document.getElementsByTagName('ul')[0].style.marginLeft = `-${px}px`;

Then the ul comes back to margin-left:0, but I want it to animate on negative margin and just snap on margin-left:0

edit:

The first answer sounds as though I'm not clear. I want to click on an element and have it animate one way, and then snap back to the default position. The usual  transitions animate both ways

Body:
Try to use class for animation and use jQuery to manage these classes

Take a look at my example

$('button').click(function() {
  $('ul').toggleClass('animated');
});

ul {
  margin-left: 200px;
  -webkit-transition: margin 1000ms linear;
  transition: margin 1000ms linear;
}

ul.animated {
  margin-left: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>test</li>
</ul>

<button>Animate</button>


问:
What is the name of this type of function in PHP
I usually see this type of functions in classes when I explore a few laravel packages code, i want to know what is the name of this type of functions and how to use it, for example:

```<code>protected function getFiles(): Filesystem
{

}
</code>```

or

```<code>protected function getConfigPath(): string
{

}
</code>```

A PHP Documentation link would be useful.

答:
Return type declarations were added in PHP 7.

Similar to argument type declarations, return type declarations
define the type of the value that will be returned by a function. The available types are the same as those available for argument type declarations.

```<code><?php
function sum($a, $b): float {
    return $a + $b;
}
</code>```

As of PHP 7.1.0, return values can be marked as nullable by prefixing
  the type name with a question mark (?).

```<code>?string ?int ?array ?bool ?float
</code>```

This allows the function to return the type defined or null, anything else will throw a TypeError if using Strict Mode, the default.

The strict_types directive can be set globally, or toggled in code using the declare construct.

```<code>declare(strict_types=1);
</code>```

One of the primary benefits of using these features in PHP is clearer code. There is no ambiguity about the functions input and output. It also help detect silly mistakes like comparing a string and integer type value - or rather perform those evaluations in a more predictable way.

Here are some other discussions on this topic:

Reference — What does this symbol mean in PHP?

Type casting variables in PHP, what is the practical reason for doing this?

What does strict types do in PHP?

Are scalar and strict types in PHP7 a performance enhancing feature?

Body:
I usually see this type of functions in classes when I explore a few laravel packages code, i want to know what is the name of this type of functions and how to use it, for example:

protected function getFiles(): Filesystem
{

}

or

protected function getConfigPath(): string
{

}

A PHP Documentation link would be useful.

Body:
Return type declarations were added in PHP 7.

Similar to argument type declarations, return type declarations
define the type of the value that will be returned by a function. The available types are the same as those available for argument type declarations.

<?php
function sum($a, $b): float {
    return $a + $b;
}

As of PHP 7.1.0, return values can be marked as nullable by prefixing
  the type name with a question mark (?).

?string ?int ?array ?bool ?float

This allows the function to return the type defined or null, anything else will throw a TypeError if using Strict Mode, the default.

The strict_types directive can be set globally, or toggled in code using the declare construct.

declare(strict_types=1);

One of the primary benefits of using these features in PHP is clearer code. There is no ambiguity about the functions input and output. It also help detect silly mistakes like comparing a string and integer type value - or rather perform those evaluations in a more predictable way.

Here are some other discussions on this topic:

Reference — What does this symbol mean in PHP?

Type casting variables in PHP, what is the practical reason for doing this?

What does strict types do in PHP?

Are scalar and strict types in PHP7 a performance enhancing feature?