问:
I am facing a problem in redirecting my angular js controller to c# controller.Below is my scrip controller code and c# controller code
Dear Community,
               I am facing a problem in redirecting my angular js controller to c# controller.Below is my scrip controller code and c# controller code.Am i making any mistakes in url or is there any routing needed to take my angular controller to c# controller.When the controller is hit,it calls error callback with error alert instantly.please provide me with a solution.

angular controller code:

```<code>var httpTimeout = 1800000;
var httpTimeoutSearch = 3600000;
angular.module('MyApp', [])
var app = angular.module('myApp', []);
app.controller('LoginController', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {
    $scope.username = "";
    $scope.password = "";
    $scope.Login = function () {
        if ($scope.username != null && $scope.username != "") {
            if ($scope.password != null && $scope.password != "") {
                try {
                    $http({
                        method: 'POST',
                        url: '/Account/Maxi',
                        data: { Username: $scope.username, Passord: $scope.password },
                        timeout: httpTimeout,
                    }).then(function successCallback(response) {
                        alert("sucess");
                    }, function errorCallback(response) {
                        alert("error");
                    });
                }
                catch (ex)
                { alert(ex); }
            }
        }

    }
}]);
</code>```

My C# Controller code:

```<code>[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Maxi(LoginModel data, string returnUrl)
{
    string strReturn = "";
    string ConStr = "";
    string Code = "";
    if (data.UserName != null)
   {
       if (data.Password != null)
       {

           DataSet ds = new DataSet();
           SqlParameter[] parameters =
            {

             new SqlParameter( "@name", SqlDbType.VarChar, 20) { Value = data.UserName } ,
             new SqlParameter("@Roll_No", SqlDbType.Int) { Value = data.Password  } ,

            };
           ConStr = "Data Source=" + "192.168.1.9" + ";Initial Catalog=" + "MyFistDataBase" + ";User id=" + "sa" + ";Password=" + "123" + ";";
           using (SqlConnection con = new SqlConnection(ConStr))
           {
               using (SqlCommand cmd = new SqlCommand("Maxi", con))
               {
                   cmd.CommandType = CommandType.StoredProcedure;
                   SqlDataAdapter da = new SqlDataAdapter();
                   cmd.Parameters.AddRange(parameters);
                   da.SelectCommand = cmd;
                   da.Fill(ds);
               }
           }

           string errmsg = "";

           if (errmsg != "")
           {
               Code = "0"; strReturn = errmsg;
           }
           else
           {
               if (ds.Tables.Count > 0)
               {
                   if (ds.Tables[0].Rows.Count > 0)
                   {
                       Code = "1";

                       foreach (DataRow dr in ds.Tables[0].Rows)
                       {
                           strReturn += dr[0].ToString();
                       }
                       if (strReturn == "1")
                       {
                           Console.Write("Updated");
                       }

                   }
                   //TripDT = TripDT.ToShortDateString();
               }

           }
       }
   }
    return View(data);
}
</code>```

答:
first this first you need to correct your spelling mistakes in code that is BIG mistake in programming.
Try this type of data
C# class like this

```<code> public class EmployeeInfo
    {
       [Key]
        public int EmpNo { get; set; }
        public string EmpName { get; set; }
        public decimal Salary { get; set; }
    }
</code>```

js object like this

```<code> var Employee = {
            EmpNo: $scope.EmpNo,
            EmpName: $scope.EmpName,
            Salary: $scope.Salary,
        };
</code>```

http part change like this

```<code> $http({
            method: "post",
            url: "/Account/Maxi",
            data: Employee
        }).then(function successCallback(response) {
                        alert("sucess");
            }, function errorCallback(response) {
                        alert("error");
            });

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Maxi(EmployeeInfo emp)
{
     your code here
}
</code>```

hope this will help you

Body:
Dear Community,
               I am facing a problem in redirecting my angular js controller to c# controller.Below is my scrip controller code and c# controller code.Am i making any mistakes in url or is there any routing needed to take my angular controller to c# controller.When the controller is hit,it calls error callback with error alert instantly.please provide me with a solution.

angular controller code:

var httpTimeout = 1800000;
var httpTimeoutSearch = 3600000;
angular.module('MyApp', [])
var app = angular.module('myApp', []);
app.controller('LoginController', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {
    $scope.username = "";
    $scope.password = "";
    $scope.Login = function () {
        if ($scope.username != null && $scope.username != "") {
            if ($scope.password != null && $scope.password != "") {
                try {
                    $http({
                        method: 'POST',
                        url: '/Account/Maxi',
                        data: { Username: $scope.username, Passord: $scope.password },
                        timeout: httpTimeout,
                    }).then(function successCallback(response) {
                        alert("sucess");
                    }, function errorCallback(response) {
                        alert("error");
                    });
                }
                catch (ex)
                { alert(ex); }
            }
        }

    }
}]);

My C# Controller code:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Maxi(LoginModel data, string returnUrl)
{
    string strReturn = "";
    string ConStr = "";
    string Code = "";
    if (data.UserName != null)
   {
       if (data.Password != null)
       {

           DataSet ds = new DataSet();
           SqlParameter[] parameters =
            {

             new SqlParameter( "@name", SqlDbType.VarChar, 20) { Value = data.UserName } ,
             new SqlParameter("@Roll_No", SqlDbType.Int) { Value = data.Password  } ,

            };
           ConStr = "Data Source=" + "192.168.1.9" + ";Initial Catalog=" + "MyFistDataBase" + ";User id=" + "sa" + ";Password=" + "123" + ";";
           using (SqlConnection con = new SqlConnection(ConStr))
           {
               using (SqlCommand cmd = new SqlCommand("Maxi", con))
               {
                   cmd.CommandType = CommandType.StoredProcedure;
                   SqlDataAdapter da = new SqlDataAdapter();
                   cmd.Parameters.AddRange(parameters);
                   da.SelectCommand = cmd;
                   da.Fill(ds);
               }
           }

           string errmsg = "";

           if (errmsg != "")
           {
               Code = "0"; strReturn = errmsg;
           }
           else
           {
               if (ds.Tables.Count > 0)
               {
                   if (ds.Tables[0].Rows.Count > 0)
                   {
                       Code = "1";

                       foreach (DataRow dr in ds.Tables[0].Rows)
                       {
                           strReturn += dr[0].ToString();
                       }
                       if (strReturn == "1")
                       {
                           Console.Write("Updated");
                       }

                   }
                   //TripDT = TripDT.ToShortDateString();
               }

           }
       }
   }
    return View(data);
}

Body:
first this first you need to correct your spelling mistakes in code that is BIG mistake in programming.
Try this type of data
C# class like this

 public class EmployeeInfo
    {
       [Key]
        public int EmpNo { get; set; }
        public string EmpName { get; set; }
        public decimal Salary { get; set; }
    }

js object like this

 var Employee = {
            EmpNo: $scope.EmpNo,
            EmpName: $scope.EmpName,
            Salary: $scope.Salary,
        };

http part change like this

 $http({
            method: "post",
            url: "/Account/Maxi",
            data: Employee
        }).then(function successCallback(response) {
                        alert("sucess");
            }, function errorCallback(response) {
                        alert("error");
            });

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Maxi(EmployeeInfo emp)
{
     your code here
}

hope this will help you


来源: stackexchange

问:
Flutter: How do I change main.dart(entry point) to some other page in Flutter?

I started working on the "home page" of the application in main.dart.

Then I created "Login.dart" page, and now I want my application to start with "Login.dart" page.

I am newbie in Flutter.

答:
We have a separate file for this. Please follow below steps:

1.Go to test> widget.test.dart

2.Change import package:flutter_async/main.dart
to package:flutter_async/your_file_name.dart

and in the class which you have defined you can use your MyApp (which runapp function will take as a input) class or you can rename Myapp class also to some other class from widget.testfile as a first screen for your app.

ContentLicense: CC BY-SA 4.0


问:
Question about Optional chaining and Nullish coalescing JavaScript operators support in PhpStorm
I wanted to ask if anyone knows how one can support the JavaScript nullish coalescing operator (??) and the optional chaining operator (?.) in PhpStorm.

Currently I am developing a project in react-native in PhpStorm, both operators work fine but PhpStorm sets an expression expected error and all files using these operators become error underlined.

How can I add support for these features so the IDE is happy?

答:
JavaScript Nullish Coalescing support was implemented more than a year ago,  see WEB-32660.
Please make sure that you are using the most recent IDE version and that the JavaScript language version is set to ECMAScript 6 or React JSX in Settings | Languages & Frameworks | JavaScript


问:
How to avoid getting ftplib.error_perm: 550 The process cannot access the file because it is being used by another process?
I'm writting a python code to upload many image files to a FTP server with ftplib for my company, but my code must be applied for network instability. Therefore, when a image file is uploading to FTP server, maybe it will fail, and then I get an error "ftplib.error_perm: 550 The process cannot access the file because it is being used by another process". By the way, the FTP server is managed by another company.

My uploading image files code:

with open(img_list[0][0], "rb") as oFile:
    check_chars = oFile.read()[-2:]
# End of with-block
if check_chars != b"\xff\xd9":
    time.sleep(1)
    continue
# End of if-condition

print("準備上傳： %s" %(img_list[0][1]))
if cut_switch:
    img = Cut_image(img_list[0][0])
    ftp.storbinary('STOR '+img_list[0][1], img)
else:
    with open(img_list[0][0], 'rb') as imageReader:
        ftp.storbinary('STOR '+img_list[0][1], imageReader)
    # End of with-block
# End of if-else-condition
```

I hope somebody could gives me suggestions to solve the error, please.

答:
Try this:

```<code>    oFile = open(img_list[0][0], "rb")
    check_chars = oFile.read()[-2:]
    if check_chars != b"\xff\xd9":
        time.sleep(1)
    oFile.close()

    print("準備上傳： %s" %(img_list[0][1]))
    if cut_switch:
        img = Cut_image(img_list[0][0])
        ftp.storbinary('STOR '+img_list[0][1], img)
    else:
        with open(img_list[0][0], 'rb') as imageReader:
            ftp.storbinary('STOR '+img_list[0][1], imageReader)
</code>```

The error occur because you haven't close the file (you are opening it)
And you should remember that you don't need to continue to quit the if-else condition

Body:
I'm writting a python code to upload many image files to a FTP server with ftplib for my company, but my code must be applied for network instability. Therefore, when a image file is uploading to FTP server, maybe it will fail, and then I get an error "ftplib.error_perm: 550 The process cannot access the file because it is being used by another process". By the way, the FTP server is managed by another company.

My uploading image files code:

with open(img_list[0][0], "rb") as oFile:
    check_chars = oFile.read()[-2:]
# End of with-block
if check_chars != b"\xff\xd9":
    time.sleep(1)
    continue
# End of if-condition

print("準備上傳： %s" %(img_list[0][1]))
if cut_switch:
    img = Cut_image(img_list[0][0])
    ftp.storbinary('STOR '+img_list[0][1], img)
else:
    with open(img_list[0][0], 'rb') as imageReader:
        ftp.storbinary('STOR '+img_list[0][1], imageReader)
    # End of with-block
# End of if-else-condition

I hope somebody could gives me suggestions to solve the error, please.

Body:
Try this:

    oFile = open(img_list[0][0], "rb")
    check_chars = oFile.read()[-2:]
    if check_chars != b"\xff\xd9":
        time.sleep(1)
    oFile.close()

    print("準備上傳： %s" %(img_list[0][1]))
    if cut_switch:
        img = Cut_image(img_list[0][0])
        ftp.storbinary('STOR '+img_list[0][1], img)
    else:
        with open(img_list[0][0], 'rb') as imageReader:
            ftp.storbinary('STOR '+img_list[0][1], imageReader)

The error occur because you haven't close the file (you are opening it)
And you should remember that you don't need to continue to quit the if-else condition


问:
How to efficiently update a Keras variable slice?
Suppose we have x = K.zeros((4, 6)), and we wish to add 1 to row 0: x[0] += 1. The variable is created via Layer's add_weight() w/ training=False, so it isn't updated via backprop. What is the most speed-efficient way to do so?

Relevant Git

Context: I'm implementing recurrent batch normalization, with moving_mean and moving_variance variables distinct for each timestep in an RNN - each thus having a shape of (units, timesteps). The goal is to update one timesteps slice per step via K.moving_average_update(). One approach is as follows:

import keras.backend as K
units, timesteps = 4, 6
x = K.zeros((units, timesteps), dtype='float32', name='x')

x_new = x[:units, 0].assign(K.ones((units,), dtype='float32'))  # dummy example
K.set_value(x, K.get_value(x_new))
print(K.get_value(x))
```

<pre class="lang-py prettyprint-override"><code>[[1. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0.]]
</code>```

Looks good - except, a new copy of x was created. In practice, we can have timesteps > 100 (e.g. 120), so we are creating an array 120x larger than it needs to be, 120 times (1 / step), making it an O(timesteps**2) operation - as opposed to usual slicing, O(timesteps). Inspecting Keras' Backend, its update_ methods all involve copying the original array.

Is there anything more efficient in Keras? If not, in TensorFlow?

Note: I'm aware of the "append to list* then assign via array at last step" alternative, which is a lot more efficient, but we can do better - at least as in terms of 'traditional' arrays (* or fill zeros-array). Though admittedly, there's also the GPU factor, which works better in batch-assignments than iterative - but I cannot benchmark latter effectively per what I described.

答:
Figured out direct slice-update:

x_slice = x[4:5]
x_slice.assign(math_ops.sub(x_slice, some_tensor))
```

x_slice appears to nicely reference the original tensor array; for some reason, assign_sub fails at this; see clarifying comment.

Body:
Suppose we have x = K.zeros((4, 6)), and we wish to add 1 to row 0: x[0] += 1. The variable is created via Layer's add_weight() w/ training=False, so it isn't updated via backprop. What is the most speed-efficient way to do so?

Relevant Git

Context: I'm implementing recurrent batch normalization, with moving_mean and moving_variance variables distinct for each timestep in an RNN - each thus having a shape of (units, timesteps). The goal is to update one timesteps slice per step via K.moving_average_update(). One approach is as follows:

import keras.backend as K
units, timesteps = 4, 6
x = K.zeros((units, timesteps), dtype='float32', name='x')

x_new = x[:units, 0].assign(K.ones((units,), dtype='float32'))  # dummy example
K.set_value(x, K.get_value(x_new))
print(K.get_value(x))

[[1. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0.]]

Looks good - except, a new copy of x was created. In practice, we can have timesteps > 100 (e.g. 120), so we are creating an array 120x larger than it needs to be, 120 times (1 / step), making it an O(timesteps**2) operation - as opposed to usual slicing, O(timesteps). Inspecting Keras' Backend, its update_ methods all involve copying the original array.

Is there anything more efficient in Keras? If not, in TensorFlow?

Note: I'm aware of the "append to list* then assign via array at last step" alternative, which is a lot more efficient, but we can do better - at least as in terms of 'traditional' arrays (* or fill zeros-array). Though admittedly, there's also the GPU factor, which works better in batch-assignments than iterative - but I cannot benchmark latter effectively per what I described.

Body:
Figured out direct slice-update:

x_slice = x[4:5]
x_slice.assign(math_ops.sub(x_slice, some_tensor))

x_slice appears to nicely reference the original tensor array; for some reason, assign_sub fails at this; see clarifying comment.


问:
Swift Execution Order ViewController UIKit
I'm new to swift and want to use the data from an api in form of a json file. I'm using the TableViewController but the execution order in it seems to be jumping around between the functions and not executing them fully. To see in which order the execution is happening I inserted some print statements.

```<code>
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var Info = Array<String>()

    override func viewDidLoad() {
        super.viewDidLoad()

            parse() { result in
                print("parse")
                if result != nil {
                    self.Info = result!
                    tableView.reloadData()
                }
                else {return}
            }

        print("viewDidLoad")
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("numberOfRows")
        //
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("cellForRowAt")
        //
    }

}

</code>```

The result of executing it is:

viewDidLoad
numberOfRows
numberOfRows
parse

So my Question would be:

How do i get the jsonParse completionHandler to execute before numberofRows and why is cellForRowAt not executing ?

Thank you in advance.

答:
The order is correct. The single steps are

First "viewDidLoad" is printed because parse works asynchronously.

Then the framework calls tableView.reloadData() once implicitly. This causes to print "numberOfRows" (sometimes more than once). At this moment the data source array is empty so cellForRowAt is not going to be called.

Meanwhile parse has finished its job, the closure is executed and "parse" is printed.

Finally the explicit tableView.reloadData() is executed and updates the UI with the received data. If parse is performed on a background thread you have to reload the table view on the main thread

```<code>DispatchQueue.main.async {
     self.tableview.reloadData()
}
</code>```

Body:
I'm new to swift and want to use the data from an api in form of a json file. I'm using the TableViewController but the execution order in it seems to be jumping around between the functions and not executing them fully. To see in which order the execution is happening I inserted some print statements.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var Info = Array<String>()

    override func viewDidLoad() {
        super.viewDidLoad()

            parse() { result in
                print("parse")
                if result != nil {
                    self.Info = result!
                    tableView.reloadData()
                }
                else {return}
            }

        print("viewDidLoad")
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("numberOfRows")
        //
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("cellForRowAt")
        //
    }

}

The result of executing it is:

viewDidLoad
numberOfRows
numberOfRows
parse

So my Question would be:

How do i get the jsonParse completionHandler to execute before numberofRows and why is cellForRowAt not executing ?

Thank you in advance.

Body:
The order is correct. The single steps are

First "viewDidLoad" is printed because parse works asynchronously.

Then the framework calls tableView.reloadData() once implicitly. This causes to print "numberOfRows" (sometimes more than once). At this moment the data source array is empty so cellForRowAt is not going to be called.

Meanwhile parse has finished its job, the closure is executed and "parse" is printed.

Finally the explicit tableView.reloadData() is executed and updates the UI with the received data. If parse is performed on a background thread you have to reload the table view on the main thread

DispatchQueue.main.async {
     self.tableview.reloadData()
}


问:
How to extract all string that match a certain pattern and explode as rows in SQL
I have a table like

```<code>memberid  content
1         hello @abc
2         I'm happy @sunny @rainy
</code>```

My expected output

```<code>memberid  text_after_@
1         abc
2         sunny
2         rainy
</code>```

SQLFidle

答:
This may be an ugly way of doing it, but works.

```<code>WITH RECURSIVE CTE(memberid,c1,n,cnt) AS (
SELECT MEMBERID,
       SUBSTRING(content FROM (LOCATE('@',content))+1) as c1,
       1 as n,
       LENGTH(content)-LENGTH(REPLACE(content ,'@','')) as cnt FROM TEST
union all
SELECT MEMBERID,
       SUBSTRING(c1 FROM (LOCATE('@',c1))+1),
       n+1,
       cnt FROM cte
where n<cnt
)
SELECT DISTINCT MEMBERID,
                SUBSTRING_INDEX(c1, ' ', 1) AS TEXT_AFTER
FROM CTE
ORDER BY MEMBERID
</code>```

CHECK DEMO HERE

Body:
I have a table like

memberid  content
1         hello @abc
2         I'm happy @sunny @rainy

My expected output

memberid  text_after_@
1         abc
2         sunny
2         rainy

SQLFidle

Body:
This may be an ugly way of doing it, but works.

WITH RECURSIVE CTE(memberid,c1,n,cnt) AS (
SELECT MEMBERID,
       SUBSTRING(content FROM (LOCATE('@',content))+1) as c1,
       1 as n,
       LENGTH(content)-LENGTH(REPLACE(content ,'@','')) as cnt FROM TEST
union all
SELECT MEMBERID,
       SUBSTRING(c1 FROM (LOCATE('@',c1))+1),
       n+1,
       cnt FROM cte
where n<cnt
)
SELECT DISTINCT MEMBERID,
                SUBSTRING_INDEX(c1, ' ', 1) AS TEXT_AFTER
FROM CTE
ORDER BY MEMBERID

CHECK DEMO HERE


问:
How to change the order in which files are listed by bash
I have some files. When I list them I get the order:

```<code>frame0001i0002.png
frame0001.png
frame0002i0003.png
frame0002.png
frame0003i0004.png
frame0003.png
frame0004.png
frame0005.png
frame0006.png
</code>```

I had assumed that frame0001.png would come before frame0001i0002.png, because I need to operate on them in the order:

```<code>frame0001.png
frame0001i0002.png
frame0002.png
frame0002i0003.png
frame0003.png
frame0003i0004.png
frame0004.png
frame0005.png
frame0006.png
</code>```

Do I need to rename them to appear in the order that I want?

Ultimately I want to change their names to:

```<code>frame0001.png
frame0002.png
frame0003.png
frame0004.png
frame0005.png
frame0006.png
frame0007.png
frame0008.png
frame0009.png
</code>```

and in the order from the cell above.

答:
ls can also do this with -v option

```<code>$ ls -vw1 *png
frame0001.png
frame0001i0002.png
frame0002.png
frame0002i0003.png
frame0003.png
frame0003i0004.png
frame0004.png
frame0005.png
frame0006.png
</code>```

From ls help

```<code>$ ls --help
...
  -v                         natural sort of (version) numbers within text
  -w, --width=COLS           set output width to COLS.  0 means no limit
...
</code>```

Body:
I have some files. When I list them I get the order:

frame0001i0002.png
frame0001.png
frame0002i0003.png
frame0002.png
frame0003i0004.png
frame0003.png
frame0004.png
frame0005.png
frame0006.png

I had assumed that frame0001.png would come before frame0001i0002.png, because I need to operate on them in the order:

frame0001.png
frame0001i0002.png
frame0002.png
frame0002i0003.png
frame0003.png
frame0003i0004.png
frame0004.png
frame0005.png
frame0006.png

Do I need to rename them to appear in the order that I want?

Ultimately I want to change their names to:

frame0001.png
frame0002.png
frame0003.png
frame0004.png
frame0005.png
frame0006.png
frame0007.png
frame0008.png
frame0009.png

and in the order from the cell above.

Body:
ls can also do this with -v option

$ ls -vw1 *png
frame0001.png
frame0001i0002.png
frame0002.png
frame0002i0003.png
frame0003.png
frame0003i0004.png
frame0004.png
frame0005.png
frame0006.png

From ls help

$ ls --help
...
  -v                         natural sort of (version) numbers within text
  -w, --width=COLS           set output width to COLS.  0 means no limit
...


问:
How to pass object in CLI in corda projects
I was trying to run car insurance project in corda but but i am not able to know how to pass the claimInfo data in object type can any one help me

https://github.com/corda/samples/tree/release-V4/carinsurance-QueryableState

i am trying to pass the data like this

```<code>start InsuranceClaimInitiator claimInfo: {claimNumber: "aa",claimDescription: "rrrr", claimAmount: 9}, policyNumber: "aaa"
</code>```

is this right or should we need to pass differently ????

its showing me this error

```<code>Wed Feb 19 16:34:55 IST 2020>>> flow start InsuranceClaimFlow$InsuranceClaimInitiator claimInfo: {claimNmuber: "c001",claimDescription: "hello",claimAmount: 123}, policyNumber: "hello"
No matching constructor found:
- [class net.corda.examples.carinsurance.flows.ClaimInfo, class java.lang.String]: Could not parse as a command: Cannot construct instance of `net.corda.examples.carinsurance.flows.ClaimInfo` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: UNKNOWN; line: -1, column: -1]

Wed Feb 19 16:35:16 IST 2020>>> flow start InsuranceClaimFlow$InsuranceClaimInitiator {claimInfo: {claimNmuber: "c001",claimDescription: "hello",claimAmount: 123}}, policyNumber: "hello"
flow start InsuranceClaimFlow$InsuranceClaimInitiator {claimInfo: {claimNmuber: "c001",claimDescription: "hello",claimAmount: 123}}, policyNumber: "hello": exception: Expected a field name (Scalar value in YAML), got this instead: <org.yaml.snakeyaml.events.MappingStartEvent(anchor=null, tag=null, implicit=true)>
 at [Source: (StringReader); line: 1, column: 4]
Wed Feb 19 16:36:00 IST 2020>>> [ERROR] 16:36:00+0530 [pool-8-thread-5] command.CRaSHSession. - Error while evaluating request 'flow start InsuranceClaimFlow$InsuranceClaimInitiator {claimInfo: {claimNmuber: "c001",claimDescription: "hello",claimAmount: 123}}, policyNumber: "hello"' flow start InsuranceClaimFlow$InsuranceClaimInitiator {claimInfo: {claimNmuber: "c001",claimDescription: "hello",claimAmount: 123}}, policyNumber: "hello": exception: Expected a field name (Scalar value in YAML), got this instead: <org.yaml.snakeyaml.events.MappingStartEvent(anchor=null, tag=null, implicit=true)>
 at [Source: (StringReader); line: 1, column: 4] [errorCode=rc1dem, moreInformationAt=https://errors.corda.net/OS/4.3/rc1dem]
</code>```

答:
Add a default constructor to the ClaimInfo and it should work fine. Also mark the parameterized constructor with @ConstructorForDeserialization. It requires a default constructor to deserialize.

```<code>public ClaimInfo(){
    this.claimNumber = null;
    this.claimDescription = null;
    this.claimAmount = 0;
}

@ConstructorForDeserialization
public ClaimInfo(String claimNumber, String claimDescription, int claimAmount) {
    this.claimNumber = claimNumber;
    this.claimDescription = claimDescription;
    this.claimAmount = claimAmount;
}
</code>```

I think we should update this in the sample, or better you could make a PR if you wish.

Body:
I was trying to run car insurance project in corda but but i am not able to know how to pass the claimInfo data in object type can any one help me

https://github.com/corda/samples/tree/release-V4/carinsurance-QueryableState

i am trying to pass the data like this

start InsuranceClaimInitiator claimInfo: {claimNumber: "aa",claimDescription: "rrrr", claimAmount: 9}, policyNumber: "aaa"

is this right or should we need to pass differently ????

its showing me this error

Wed Feb 19 16:34:55 IST 2020>>> flow start InsuranceClaimFlow$InsuranceClaimInitiator claimInfo: {claimNmuber: "c001",claimDescription: "hello",claimAmount: 123}, policyNumber: "hello"
No matching constructor found:
- [class net.corda.examples.carinsurance.flows.ClaimInfo, class java.lang.String]: Could not parse as a command: Cannot construct instance of `net.corda.examples.carinsurance.flows.ClaimInfo` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: UNKNOWN; line: -1, column: -1]

Wed Feb 19 16:35:16 IST 2020>>> flow start InsuranceClaimFlow$InsuranceClaimInitiator {claimInfo: {claimNmuber: "c001",claimDescription: "hello",claimAmount: 123}}, policyNumber: "hello"
flow start InsuranceClaimFlow$InsuranceClaimInitiator {claimInfo: {claimNmuber: "c001",claimDescription: "hello",claimAmount: 123}}, policyNumber: "hello": exception: Expected a field name (Scalar value in YAML), got this instead: <org.yaml.snakeyaml.events.MappingStartEvent(anchor=null, tag=null, implicit=true)>
 at [Source: (StringReader); line: 1, column: 4]
Wed Feb 19 16:36:00 IST 2020>>> [ERROR] 16:36:00+0530 [pool-8-thread-5] command.CRaSHSession. - Error while evaluating request 'flow start InsuranceClaimFlow$InsuranceClaimInitiator {claimInfo: {claimNmuber: "c001",claimDescription: "hello",claimAmount: 123}}, policyNumber: "hello"' flow start InsuranceClaimFlow$InsuranceClaimInitiator {claimInfo: {claimNmuber: "c001",claimDescription: "hello",claimAmount: 123}}, policyNumber: "hello": exception: Expected a field name (Scalar value in YAML), got this instead: <org.yaml.snakeyaml.events.MappingStartEvent(anchor=null, tag=null, implicit=true)>
 at [Source: (StringReader); line: 1, column: 4] [errorCode=rc1dem, moreInformationAt=https://errors.corda.net/OS/4.3/rc1dem]

Body:
Add a default constructor to the ClaimInfo and it should work fine. Also mark the parameterized constructor with @ConstructorForDeserialization. It requires a default constructor to deserialize.

public ClaimInfo(){
    this.claimNumber = null;
    this.claimDescription = null;
    this.claimAmount = 0;
}

@ConstructorForDeserialization
public ClaimInfo(String claimNumber, String claimDescription, int claimAmount) {
    this.claimNumber = claimNumber;
    this.claimDescription = claimDescription;
    this.claimAmount = claimAmount;
}

I think we should update this in the sample, or better you could make a PR if you wish.


问:
How to transfer photos to x-www-form-urlencoded immediately after taking a picture EXPO
I want to take a picture, save it to an album and send the image right away.
(Do not select from album.)

There is no problem in taking the current picture, saving it in an album and checking the uri.

but the x-www-form-urlencoded sending process does not work properly.

I think there may be a problem with the format of sending the API.

postman is also attached. (No problem in Postman.)

```<code> takePictureAndCreateAlbum = async () => {
    const { uri } = await this.camera.takePictureAsync();
    console.log('uri', uri);
    const asset = await MediaLibrary.createAssetAsync(uri);
    console.log('asset', asset);

    const filename = asset.filename;

    MediaLibrary.createAlbumAsync('Expo', asset)

      // POST API
      .then(() => {

        var file = new FormData();
        file.append({file: uri});

        return fetch(/* API_URL */, {
              method: 'POST',
              headers:{

                  'Content-Type':'application/x-www-form-urlencoded',
                  'Accept': 'application/json'
             } , body : file} )

         .then((response) => response.text())
              .then((responseData) => {
                  console.log(responseData);
              })
              .done();

      })
      .catch(error => {
        Alert.alert('An Error Occurred!')
      });
  };
</code>```

Postman Header

Postman Body

答:
When appending to a FormData instance, the first parameter is the field name (What your server will be getting as an object key for this file), the second one is an object in the following form:

```<code>{
  uri: // The uri you received from the camera,
  type: // The file type (i.e.: image/png),
  name: // The file name
}
</code>```

In your case, it would be like this:

```<code>// Split the uri by `.` (periods)
const uriParts = uri.split('.');
// Grab the file type at the end of the uri
const fileType = uriParts[uriParts.length - 1];

file.append('picture', {
  uri,
  type: `image/${fileType}`,
  name: 'FILE-NAME.${fileType}`
});
</code>```

Also, when sending files, your Content-Type header should be multipart/form-data

Body:
I want to take a picture, save it to an album and send the image right away.
(Do not select from album.)

There is no problem in taking the current picture, saving it in an album and checking the uri.

but the x-www-form-urlencoded sending process does not work properly.

I think there may be a problem with the format of sending the API.

postman is also attached. (No problem in Postman.)

 takePictureAndCreateAlbum = async () => {
    const { uri } = await this.camera.takePictureAsync();
    console.log('uri', uri);
    const asset = await MediaLibrary.createAssetAsync(uri);
    console.log('asset', asset);

    const filename = asset.filename;

    MediaLibrary.createAlbumAsync('Expo', asset)

      // POST API
      .then(() => {

        var file = new FormData();
        file.append({file: uri});

        return fetch(/* API_URL */, {
              method: 'POST',
              headers:{

                  'Content-Type':'application/x-www-form-urlencoded',
                  'Accept': 'application/json'
             } , body : file} )

         .then((response) => response.text())
              .then((responseData) => {
                  console.log(responseData);
              })
              .done();

      })
      .catch(error => {
        Alert.alert('An Error Occurred!')
      });
  };

Postman Header

Postman Body

Body:
When appending to a FormData instance, the first parameter is the field name (What your server will be getting as an object key for this file), the second one is an object in the following form:

{
  uri: // The uri you received from the camera,
  type: // The file type (i.e.: image/png),
  name: // The file name
}

In your case, it would be like this:

// Split the uri by `.` (periods)
const uriParts = uri.split('.');
// Grab the file type at the end of the uri
const fileType = uriParts[uriParts.length - 1];

file.append('picture', {
  uri,
  type: `image/${fileType}`,
  name: 'FILE-NAME.${fileType}`
});

Also, when sending files, your Content-Type header should be multipart/form-data


问:
Can you filter an xml document to a subset of nodes using XPath in C#?
I'm trying to filter an Xml document so into a subset of itself using XPath.

I have used XPath get an XmlNodeList, but I need to transform this into an XML document.

Is there a way to either transform an XMLNodeList into an XmlDocument or to produce an XmlDocument by filtering another XmlDocument directly?

答:
I've actualy just thought of a way to do this but it doesn't seem very elegant.

use a StringBuilder to combine the OuterXml of each of the XmlNodes in the XmlNodeList...

As I said it's inelegant but I think it might work. I'd appreciate any other suggestion...

OwnerDisplayName: Omar Kooheji

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Omar Kooheji


问:
Convert pandas Series to DataFrame
I have a Pandas series sf:

```<code>email
email1@email.com    [1.0, 0.0, 0.0]
email2@email.com    [2.0, 0.0, 0.0]
email3@email.com    [1.0, 0.0, 0.0]
email4@email.com    [4.0, 0.0, 0.0]
email5@email.com    [1.0, 0.0, 3.0]
email6@email.com    [1.0, 5.0, 0.0]
</code>```

And I would like to transform it to the following DataFrame:

```<code>index | email             | list
_____________________________________________
0     | email1@email.com  | [1.0, 0.0, 0.0]
1     | email2@email.com  | [2.0, 0.0, 0.0]
2     | email3@email.com  | [1.0, 0.0, 0.0]
3     | email4@email.com  | [4.0, 0.0, 0.0]
4     | email5@email.com  | [1.0, 0.0, 3.0]
5     | email6@email.com  | [1.0, 5.0, 0.0]
</code>```

I found a way to do it, but I doubt it's the more efficient one:

```<code>df1 = pd.DataFrame(data=sf.index, columns=['email'])
df2 = pd.DataFrame(data=sf.values, columns=['list'])
df = pd.merge(df1, df2, left_index=True, right_index=True)
</code>```

答:
Series.to_frame can be used to convert a Series to DataFrame.

```<code># The provided name (columnName) will substitute the series name
df = series.to_frame('columnName')
</code>```

For example,

```<code>s = pd.Series(["a", "b", "c"], name="vals")
df = s.to_frame('newCol')
print(df)

   newCol
0    a
1    b
2    c
</code>```

Title: Convert pandas Series to DataFrame

Body:
I have a Pandas series sf:

email
email1@email.com    [1.0, 0.0, 0.0]
email2@email.com    [2.0, 0.0, 0.0]
email3@email.com    [1.0, 0.0, 0.0]
email4@email.com    [4.0, 0.0, 0.0]
email5@email.com    [1.0, 0.0, 3.0]
email6@email.com    [1.0, 5.0, 0.0]

And I would like to transform it to the following DataFrame:

index | email             | list
_____________________________________________
0     | email1@email.com  | [1.0, 0.0, 0.0]
1     | email2@email.com  | [2.0, 0.0, 0.0]
2     | email3@email.com  | [1.0, 0.0, 0.0]
3     | email4@email.com  | [4.0, 0.0, 0.0]
4     | email5@email.com  | [1.0, 0.0, 3.0]
5     | email6@email.com  | [1.0, 5.0, 0.0]

I found a way to do it, but I doubt it's the more efficient one:

df1 = pd.DataFrame(data=sf.index, columns=['email'])
df2 = pd.DataFrame(data=sf.values, columns=['list'])
df = pd.merge(df1, df2, left_index=True, right_index=True)

Body:
Series.to_frame can be used to convert a Series to DataFrame.

# The provided name (columnName) will substitute the series name
df = series.to_frame('columnName')

For example,

s = pd.Series(["a", "b", "c"], name="vals")
df = s.to_frame('newCol')
print(df)

   newCol
0    a
1    b
2    c


问:
(2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
I am using docker 19.03.6, docker-compose 1.25.3 and ubuntu 18. When I run docker-compose up the web container works, but mysql container is not reachable. What can I do?

The problem can be the mysqlclient package?

My Python code:

```<code>db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBM", port=3306)
</code>```

Note : I already tried src_db_1 instead of localhost!

Dockerfile:

```<code>FROM python:3.8
ENV PYTHONUNBUFFERED 1
RUN mkdir /api_rest_mix_1_0
WORKDIR /api_rest_mix_1_0
ADD requirements.txt /api_rest_mix_1_0/
RUN pip install --upgrade pip && pip install -r requirements.txt
ADD . /api_rest_mix_1_0/
</code>```

Docker-compose:

```<code>version: '3'

services:
  db:
    image: mysql:5.7
    ports:
      - '3306:3306'
    environment:
       MYSQL_DATABASE: 'DBM'
       MYSQL_USER: 'root'
       MYSQL_PASSWORD: 'password'
       MYSQL_ROOT_PASSWORD: 'password'
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/my_app_dir
    ports:
      - "8000:8000"
    depends_on:
      - db
</code>```

Requirements.txt:

```<code>Django==3.0.3
mysqlclient==1.4.6
</code>```

My commando on terminal : docker-compose up
Output from my command :

```<code>Creating network "src_default" with the default driver
Creating src_db_1 ... done
Creating src_web_1 ... done
Attaching to src_db_1, src_web_1
db_1   | 2020-02-19 11:23:18+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.29-1debian9 started.
db_1   | 2020-02-19 11:23:18+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db_1   | 2020-02-19 11:23:18+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.29-1debian9 started.
db_1   | 2020-02-19 11:23:18+00:00 [Note] [Entrypoint]: Initializing database files
db_1   | 2020-02-19T11:23:18.929128Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1   | 2020-02-19T11:23:22.350394Z 0 [Warning] InnoDB: New log files created, LSN=45790
db_1   | 2020-02-19T11:23:23.042973Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
db_1   | 2020-02-19T11:23:23.291068Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 3d632fc3-530a-11ea-9cd8-0242ac140002.
db_1   | 2020-02-19T11:23:23.361130Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
db_1   | 2020-02-19T11:23:24.557385Z 0 [Warning] CA certificate ca.pem is self signed.
web_1  | Watching for file changes with StatReloader
web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).
web_1  | February 19, 2020 - 11:23:25
web_1  | Django version 3.0.3, using settings 'api_rest_mix_1_0.settings'
web_1  | Starting development server at http://0.0.0.0:8000/
web_1  | Quit the server with CONTROL-C.
db_1   | 2020-02-19T11:23:25.254876Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
db_1   | 2020-02-19 11:23:43+00:00 [Note] [Entrypoint]: Database files initialized
db_1   | 2020-02-19 11:23:43+00:00 [Note] [Entrypoint]: Starting temporary server
db_1   | 2020-02-19 11:23:43+00:00 [Note] [Entrypoint]: Waiting for server startup
db_1   | 2020-02-19T11:23:43.925550Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1   | 2020-02-19T11:23:43.927341Z 0 [Note] mysqld (mysqld 5.7.29) starting as process 81 ...
db_1   | 2020-02-19T11:23:43.932133Z 0 [Note] InnoDB: PUNCH HOLE support available
db_1   | 2020-02-19T11:23:43.932155Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1   | 2020-02-19T11:23:43.932160Z 0 [Note] InnoDB: Uses event mutexes
db_1   | 2020-02-19T11:23:43.932164Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db_1   | 2020-02-19T11:23:43.932168Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db_1   | 2020-02-19T11:23:43.932172Z 0 [Note] InnoDB: Using Linux native AIO
db_1   | 2020-02-19T11:23:43.932473Z 0 [Note] InnoDB: Number of pools: 1
db_1   | 2020-02-19T11:23:43.932591Z 0 [Note] InnoDB: Using CPU crc32 instructions
db_1   | 2020-02-19T11:23:43.934281Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db_1   | 2020-02-19T11:23:43.946320Z 0 [Note] InnoDB: Completed initialization of buffer pool
db_1   | 2020-02-19T11:23:43.948809Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1   | 2020-02-19T11:23:43.960693Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db_1   | 2020-02-19T11:23:44.063103Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1   | 2020-02-19T11:23:44.063192Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1   | 2020-02-19T11:23:44.347746Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1   | 2020-02-19T11:23:44.348505Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db_1   | 2020-02-19T11:23:44.348523Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db_1   | 2020-02-19T11:23:44.348922Z 0 [Note] InnoDB: 5.7.29 started; log sequence number 2630649
db_1   | 2020-02-19T11:23:44.349095Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1   | 2020-02-19T11:23:44.349223Z 0 [Note] Plugin 'FEDERATED' is disabled.
db_1   | 2020-02-19T11:23:44.350675Z 0 [Note] InnoDB: Buffer pool(s) load completed at 200219 11:23:44
db_1   | 2020-02-19T11:23:44.354928Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db_1   | 2020-02-19T11:23:44.354950Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
db_1   | 2020-02-19T11:23:44.355643Z 0 [Warning] CA certificate ca.pem is self signed.
db_1   | 2020-02-19T11:23:44.355680Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
db_1   | 2020-02-19T11:23:44.393563Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db_1   | 2020-02-19T11:23:44.420138Z 0 [Note] Event Scheduler: Loaded 0 events
db_1   | 2020-02-19T11:23:44.420413Z 0 [Note] mysqld: ready for connections.
db_1   | Version: '5.7.29'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server (GPL)
db_1   | 2020-02-19 11:23:44+00:00 [Note] [Entrypoint]: Temporary server started.
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:45] "GET /api/statistics/4 HTTP/1.1" 500 82444
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:46] "GET /api/statistics/4 HTTP/1.1" 500 82444
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:47] "GET /api/statistics/4 HTTP/1.1" 500 82444
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:47] "GET /api/statistics/4 HTTP/1.1" 500 82444
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:47] "GET /api/statistics/4 HTTP/1.1" 500 82444
db_1   | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
db_1   | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:48] "GET /api/statistics/4 HTTP/1.1" 500 82444
db_1   | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
db_1   | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
db_1   | 2020-02-19 11:23:52+00:00 [Note] [Entrypoint]: Creating database DBMix_hml
db_1   | 2020-02-19 11:23:52+00:00 [Note] [Entrypoint]: Creating user root
db_1   | ERROR 1396 (HY000) at line 1: Operation CREATE USER failed for 'root'@'%'
src_db_1 exited with code 1

</code>```

答:
Change host="localhost" to  change host="db" like

db = MySQLdb.connect(host="db", user="root", passwd="password", db="DBM", port=3306)

docker-compose.yml

```<code>services:
  db:
    image: mysql:5.7
    ports:
      - '3306:3306'
    environment:
       MYSQL_DATABASE: 'DBM'
       MYSQL_USER: 'root'
       MYSQL_PASSWORD: 'password'
       MYSQL_ROOT_PASSWORD: 'password'
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/my_app_dir
    ports:
      - "8000:8000"
    depends_on:
      - db
    links: # <-- add this
      - db # <-- add this
</code>```

Body:
I am using docker 19.03.6, docker-compose 1.25.3 and ubuntu 18. When I run docker-compose up the web container works, but mysql container is not reachable. What can I do?

The problem can be the mysqlclient package?

My Python code:

db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBM", port=3306)

Note : I already tried src_db_1 instead of localhost!

Dockerfile:

FROM python:3.8
ENV PYTHONUNBUFFERED 1
RUN mkdir /api_rest_mix_1_0
WORKDIR /api_rest_mix_1_0
ADD requirements.txt /api_rest_mix_1_0/
RUN pip install --upgrade pip && pip install -r requirements.txt
ADD . /api_rest_mix_1_0/

Docker-compose:

version: '3'

services:
  db:
    image: mysql:5.7
    ports:
      - '3306:3306'
    environment:
       MYSQL_DATABASE: 'DBM'
       MYSQL_USER: 'root'
       MYSQL_PASSWORD: 'password'
       MYSQL_ROOT_PASSWORD: 'password'
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/my_app_dir
    ports:
      - "8000:8000"
    depends_on:
      - db

Requirements.txt:

Django==3.0.3
mysqlclient==1.4.6

My commando on terminal : docker-compose up
Output from my command :

Creating network "src_default" with the default driver
Creating src_db_1 ... done
Creating src_web_1 ... done
Attaching to src_db_1, src_web_1
db_1   | 2020-02-19 11:23:18+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.29-1debian9 started.
db_1   | 2020-02-19 11:23:18+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db_1   | 2020-02-19 11:23:18+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.29-1debian9 started.
db_1   | 2020-02-19 11:23:18+00:00 [Note] [Entrypoint]: Initializing database files
db_1   | 2020-02-19T11:23:18.929128Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1   | 2020-02-19T11:23:22.350394Z 0 [Warning] InnoDB: New log files created, LSN=45790
db_1   | 2020-02-19T11:23:23.042973Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
db_1   | 2020-02-19T11:23:23.291068Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 3d632fc3-530a-11ea-9cd8-0242ac140002.
db_1   | 2020-02-19T11:23:23.361130Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
db_1   | 2020-02-19T11:23:24.557385Z 0 [Warning] CA certificate ca.pem is self signed.
web_1  | Watching for file changes with StatReloader
web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).
web_1  | February 19, 2020 - 11:23:25
web_1  | Django version 3.0.3, using settings 'api_rest_mix_1_0.settings'
web_1  | Starting development server at http://0.0.0.0:8000/
web_1  | Quit the server with CONTROL-C.
db_1   | 2020-02-19T11:23:25.254876Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
db_1   | 2020-02-19 11:23:43+00:00 [Note] [Entrypoint]: Database files initialized
db_1   | 2020-02-19 11:23:43+00:00 [Note] [Entrypoint]: Starting temporary server
db_1   | 2020-02-19 11:23:43+00:00 [Note] [Entrypoint]: Waiting for server startup
db_1   | 2020-02-19T11:23:43.925550Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1   | 2020-02-19T11:23:43.927341Z 0 [Note] mysqld (mysqld 5.7.29) starting as process 81 ...
db_1   | 2020-02-19T11:23:43.932133Z 0 [Note] InnoDB: PUNCH HOLE support available
db_1   | 2020-02-19T11:23:43.932155Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1   | 2020-02-19T11:23:43.932160Z 0 [Note] InnoDB: Uses event mutexes
db_1   | 2020-02-19T11:23:43.932164Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db_1   | 2020-02-19T11:23:43.932168Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db_1   | 2020-02-19T11:23:43.932172Z 0 [Note] InnoDB: Using Linux native AIO
db_1   | 2020-02-19T11:23:43.932473Z 0 [Note] InnoDB: Number of pools: 1
db_1   | 2020-02-19T11:23:43.932591Z 0 [Note] InnoDB: Using CPU crc32 instructions
db_1   | 2020-02-19T11:23:43.934281Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db_1   | 2020-02-19T11:23:43.946320Z 0 [Note] InnoDB: Completed initialization of buffer pool
db_1   | 2020-02-19T11:23:43.948809Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1   | 2020-02-19T11:23:43.960693Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db_1   | 2020-02-19T11:23:44.063103Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1   | 2020-02-19T11:23:44.063192Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1   | 2020-02-19T11:23:44.347746Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1   | 2020-02-19T11:23:44.348505Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db_1   | 2020-02-19T11:23:44.348523Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db_1   | 2020-02-19T11:23:44.348922Z 0 [Note] InnoDB: 5.7.29 started; log sequence number 2630649
db_1   | 2020-02-19T11:23:44.349095Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1   | 2020-02-19T11:23:44.349223Z 0 [Note] Plugin 'FEDERATED' is disabled.
db_1   | 2020-02-19T11:23:44.350675Z 0 [Note] InnoDB: Buffer pool(s) load completed at 200219 11:23:44
db_1   | 2020-02-19T11:23:44.354928Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db_1   | 2020-02-19T11:23:44.354950Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
db_1   | 2020-02-19T11:23:44.355643Z 0 [Warning] CA certificate ca.pem is self signed.
db_1   | 2020-02-19T11:23:44.355680Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
db_1   | 2020-02-19T11:23:44.393563Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db_1   | 2020-02-19T11:23:44.420138Z 0 [Note] Event Scheduler: Loaded 0 events
db_1   | 2020-02-19T11:23:44.420413Z 0 [Note] mysqld: ready for connections.
db_1   | Version: '5.7.29'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server (GPL)
db_1   | 2020-02-19 11:23:44+00:00 [Note] [Entrypoint]: Temporary server started.
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:45] "GET /api/statistics/4 HTTP/1.1" 500 82444
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:46] "GET /api/statistics/4 HTTP/1.1" 500 82444
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:47] "GET /api/statistics/4 HTTP/1.1" 500 82444
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:47] "GET /api/statistics/4 HTTP/1.1" 500 82444
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:47] "GET /api/statistics/4 HTTP/1.1" 500 82444
db_1   | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
db_1   | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
web_1  | Internal Server Error: /api/statistics/4
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
web_1  |     response = get_response(request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
web_1  |     response = self.process_exception_by_middleware(e, request)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
web_1  |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 171, in statistics
web_1  |     json_response = stt_sex_status_total()
web_1  |   File "/api_rest_mix_1_0/api/views.py", line 99, in stt_sex_status_total
web_1  |     db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="DBMix_hml", charset='utf8', use_unicode=True)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1  |     return Connection(*args, **kwargs)
web_1  |   File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1  |     super(Connection, self).__init__(*args, **kwargs2)
web_1  | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
web_1  | [19/Feb/2020 11:23:48] "GET /api/statistics/4 HTTP/1.1" 500 82444
db_1   | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
db_1   | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
db_1   | 2020-02-19 11:23:52+00:00 [Note] [Entrypoint]: Creating database DBMix_hml
db_1   | 2020-02-19 11:23:52+00:00 [Note] [Entrypoint]: Creating user root
db_1   | ERROR 1396 (HY000) at line 1: Operation CREATE USER failed for 'root'@'%'
src_db_1 exited with code 1

Body:
Change host="localhost" to  change host="db" like

db = MySQLdb.connect(host="db", user="root", passwd="password", db="DBM", port=3306)

docker-compose.yml

services:
  db:
    image: mysql:5.7
    ports:
      - '3306:3306'
    environment:
       MYSQL_DATABASE: 'DBM'
       MYSQL_USER: 'root'
       MYSQL_PASSWORD: 'password'
       MYSQL_ROOT_PASSWORD: 'password'
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/my_app_dir
    ports:
      - "8000:8000"
    depends_on:
      - db
    links: # <-- add this
      - db # <-- add this


问:
Volley status code and message return on jsonobjectrequest and jsonarrayrequest
I'm using Volley to hit a REST API. Most of my calls return 200, if it returns 400, 401, or 409, I pass back a json response with different error messages as to what's wrong. I've been looking at the parseNetworkRequest, but I'm not really understanding it.

Here's my JsonArrayRequest. It's only supposed to return a status code. No message, which will probably change to adding a json message on 400 or 401

```<code>    JsonArrayRequest postVerification = new JsonArrayRequest(url,amountArray,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                realm = Realm.getInstance(getApplicationContext());
                realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.where(AccountsModel.class).beginsWith("actId", accountId).findFirst().setActverified("true");
                    }
                });
                dismissDialog();
                updateView();                    }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("error", "Error: " + error.getMessage());
            dismissDialog();
            Toast message = Toast.makeText(getApplicationContext(),"Unable to verify account at this time", Toast.LENGTH_SHORT);
             message.show();
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            Log.i("Auth", "Bearer " + NetworkEngine.access_token);
            headers.put("Authorization", auth);
            return headers;
        }

        @Override
        public int getMethod() {
            return Method.POST;
        }
        @Override
        protected Response<T> parseNetworkResponse(
                NetworkResponse response) {
            try {
                String json = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
                return Response.success(json,),
                        HttpHeaderParser.parseCacheHeaders(response));
            } catch(Exception e){}

        }
    };
</code>```

I have an error on the parseNetworkResponse line

```<code>error: cannot find symbol
        protected Response<T> parseNetworkResponse(
</code>```

When I hover over the Response it says it's trying to use an incompatible return type.  I really have no idea what to do from here. Not sure what to put in the Response.sucess() or how to actually get the status code. Any help would be appreciated.

答:
To get status code from JsonArrayRequest try the following. Hope it helps.

@Override
        protected Response parseNetworkResponse(NetworkResponse response) {
            mStatusCode = response.statusCode;
            return super.parseNetworkResponse(response);
        }

ContentLicense: CC BY-SA 3.0

Body:
I'm using Volley to hit a REST API. Most of my calls return 200, if it returns 400, 401, or 409, I pass back a json response with different error messages as to what's wrong. I've been looking at the parseNetworkRequest, but I'm not really understanding it.

Here's my JsonArrayRequest. It's only supposed to return a status code. No message, which will probably change to adding a json message on 400 or 401

    JsonArrayRequest postVerification = new JsonArrayRequest(url,amountArray,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                realm = Realm.getInstance(getApplicationContext());
                realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.where(AccountsModel.class).beginsWith("actId", accountId).findFirst().setActverified("true");
                    }
                });
                dismissDialog();
                updateView();                    }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("error", "Error: " + error.getMessage());
            dismissDialog();
            Toast message = Toast.makeText(getApplicationContext(),"Unable to verify account at this time", Toast.LENGTH_SHORT);
             message.show();
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            Log.i("Auth", "Bearer " + NetworkEngine.access_token);
            headers.put("Authorization", auth);
            return headers;
        }

        @Override
        public int getMethod() {
            return Method.POST;
        }
        @Override
        protected Response<T> parseNetworkResponse(
                NetworkResponse response) {
            try {
                String json = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
                return Response.success(json,),
                        HttpHeaderParser.parseCacheHeaders(response));
            } catch(Exception e){}

        }
    };

I have an error on the parseNetworkResponse line

error: cannot find symbol
        protected Response<T> parseNetworkResponse(

When I hover over the Response it says it's trying to use an incompatible return type.  I really have no idea what to do from here. Not sure what to put in the Response.sucess() or how to actually get the status code. Any help would be appreciated.


问:
Java batch: jobContext transientUserData not passed through steps
I'm using JBeret implementation of jsr-352 specs.

This is my job configuration, in short:

```<code><job id="expired-customer-cancellation" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/jobXML_1_0.xsd"
     version="1.0" jsl-name="job-parent" parent="job-parent">
    <step id="step1" next="step2">
        <chunk item-count="#{jobParameters['chunksize']}?:3">
            <reader ref="eccReader">
            </reader>
            <writer ref="eccWriter" />
        </chunk>
        <partition>
            <mapper ref="eccMapper">
                <properties>
                    <property name="threads" value="#{jobParameters['threads']}?:3"/>
                    <property name="records" value="#{jobParameters['records']}?:30"/>
                </properties>
            </mapper>
        </partition>
    </step>
    <step id="step2">
        <batchlet ref="eccMailBatchlet" />
    </step>
</job>
</code>```

The Itemwriter class does something like this:

```<code>@Named
public class EccWriter extends AbstractItemWriter {

    @Inject
    Logger logger;

    @Inject
    JobContext jobContext;

    @Override
    public void writeItems(List<Object> list) throws Exception {
        @SuppressWarnings("unchecked")
        ArrayList<String> processed = Optional.ofNullable(jobContext.getTransientUserData()).map(ArrayList.class::cast).orElse(new ArrayList<String>());
        list.stream().map(UserLogin.class::cast).forEach(input -> {

            if (someConditions) {

                processed.add(input.getUserId());

            }
        });

        jobContext.setTransientUserData(processed); // update job transient data with processed list
    }
}
</code>```

Now I'd expect to achieve the updated list when calling jobContext.getTransientUserData() on step2, instead all I get is a null value.

Furthermore, each partition has its own jobContext.transientUserData, so it will start always with null value at partition begin.

I think that jobContext could itself mislead to common errors due to its name.

What is the natural way to bring some data through entire job ?

答:
This is a gap in the current API, and the "thread local" behavior can be surprising, I agree.

One technique you can use is to use the step persistent user data instead.

E.g. from step 1:

StepExecution.setPersistentUserData(processed);

Then from step 2:

```<code>@Inject
JobContext ctx;

List<StepExecution> stepExecs = BatchRuntime.getJobOperator().getStepExecutions(ctx.getInstanceId());

// ... not shown here, but sort through stepExecs and find the one from step1.
StepExecution step2Exec = ... ;

Serializable userData = step2Exec.getPersistentUserData()
</code>```

This has been noted before as an area for improvement, and should be considered for future enhancements for Jakarta Batch (the new home of the specification).

Body:
I'm using JBeret implementation of jsr-352 specs.

This is my job configuration, in short:

<job id="expired-customer-cancellation" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/jobXML_1_0.xsd"
     version="1.0" jsl-name="job-parent" parent="job-parent">
    <step id="step1" next="step2">
        <chunk item-count="#{jobParameters['chunksize']}?:3">
            <reader ref="eccReader">
            </reader>
            <writer ref="eccWriter" />
        </chunk>
        <partition>
            <mapper ref="eccMapper">
                <properties>
                    <property name="threads" value="#{jobParameters['threads']}?:3"/>
                    <property name="records" value="#{jobParameters['records']}?:30"/>
                </properties>
            </mapper>
        </partition>
    </step>
    <step id="step2">
        <batchlet ref="eccMailBatchlet" />
    </step>
</job>

The Itemwriter class does something like this:

@Named
public class EccWriter extends AbstractItemWriter {

    @Inject
    Logger logger;

    @Inject
    JobContext jobContext;

    @Override
    public void writeItems(List<Object> list) throws Exception {
        @SuppressWarnings("unchecked")
        ArrayList<String> processed = Optional.ofNullable(jobContext.getTransientUserData()).map(ArrayList.class::cast).orElse(new ArrayList<String>());
        list.stream().map(UserLogin.class::cast).forEach(input -> {

            if (someConditions) {

                processed.add(input.getUserId());

            }
        });

        jobContext.setTransientUserData(processed); // update job transient data with processed list
    }
}

Now I'd expect to achieve the updated list when calling jobContext.getTransientUserData() on step2, instead all I get is a null value.

Furthermore, each partition has its own jobContext.transientUserData, so it will start always with null value at partition begin.

I think that jobContext could itself mislead to common errors due to its name.

What is the natural way to bring some data through entire job ?

Body:
This is a gap in the current API, and the "thread local" behavior can be surprising, I agree.

One technique you can use is to use the step persistent user data instead.

E.g. from step 1:

StepExecution.setPersistentUserData(processed);

Then from step 2:

@Inject
JobContext ctx;

List<StepExecution> stepExecs = BatchRuntime.getJobOperator().getStepExecutions(ctx.getInstanceId());

// ... not shown here, but sort through stepExecs and find the one from step1.
StepExecution step2Exec = ... ;

Serializable userData = step2Exec.getPersistentUserData()

This has been noted before as an area for improvement, and should be considered for future enhancements for Jakarta Batch (the new home of the specification).


问:
How to convert \u009
im tryng to convert Ba\u009aka Voda to its correct characters using html_entity_decode

```<code>    echo html_entity_decode("Ba	aka Voda\n", ENT_COMPAT);
    echo html_entity_decode("Ba	aka Voda\n", ENT_QUOTES );
    echo html_entity_decode("Ba	aka Voda\n", ENT_QUOTES, 'UTF-8');
    echo html_entity_decode("Ba	aka Voda\n", ENT_NOQUOTES);
    echo html_entity_decode("Ba	aka Voda\n", ENT_HTML401);
    echo html_entity_decode("Ba	aka Voda\n", ENT_XML1);
    echo html_entity_decode("Ba	aka Voda\n", ENT_XHTML);
    echo html_entity_decode("Ba	aka Voda\n", ENT_HTML5);
</code>```

Response is always:

Ba aka Voda

expected result should be : Baška Voda

what im doing wrong?

答:
Use mb_convert_encoding() in combination with preg_replace_callback():

```<code>$input = "Baška Voda";

$output = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input);

echo $output; // Baška Voda
</code>```

Title: How to convert \u009

Body:
im tryng to convert Ba\u009aka Voda to its correct characters using html_entity_decode

    echo html_entity_decode("Ba	aka Voda\n", ENT_COMPAT);
    echo html_entity_decode("Ba	aka Voda\n", ENT_QUOTES );
    echo html_entity_decode("Ba	aka Voda\n", ENT_QUOTES, 'UTF-8');
    echo html_entity_decode("Ba	aka Voda\n", ENT_NOQUOTES);
    echo html_entity_decode("Ba	aka Voda\n", ENT_HTML401);
    echo html_entity_decode("Ba	aka Voda\n", ENT_XML1);
    echo html_entity_decode("Ba	aka Voda\n", ENT_XHTML);
    echo html_entity_decode("Ba	aka Voda\n", ENT_HTML5);

Response is always:

Ba aka Voda

expected result should be : Baška Voda

what im doing wrong?

Body:
Use mb_convert_encoding() in combination with preg_replace_callback():

$input = "Baška Voda";

$output = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input);

echo $output; // Baška Voda


问:
Instagram Basic Display API Error - Invalid scope: ['basic'] OR Invalid redirect_uri
I'm using Magento 2.4.1, installed Social Login Extension and getting below error while login to Instagram, I'm using Hybrid auth libraries to login.

"error_type": "OAuthException", "code": 400, "error_message": "Invalid
scope: ['basic']"}

You can check the screenshot below,

Instagram.php

```<code><?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
*  (c) 2009-2012 HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
namespace Vendor\Module\Model\Providers;

/**
* Hybrid_Providers_Instagram (By Sebastian Lasse - https://github.com/sebilasse)
*/
class Instagram extends \Hybrid_Provider_Model_OAuth2
{
    // default permissions
    public $scope = "basic";

    /**
    * IDp wrappers initializer
    */
    public function initialize()
    {
        parent::initialize();

        // Provider api end-points
        $this->api->api_base_url  = "https://api.instagram.com/v1/";
        $this->api->authorize_url = "https://api.instagram.com/oauth/authorize/";
        $this->api->token_url     = "https://api.instagram.com/oauth/access_token";
    }

    /**
    * load the user profile from the IDp api client
    */
    public function getUserProfile()
    {
        $data = $this->api->api("users/self/");

        if ($data->meta->code != 200) {
            throw new \Exception("User profile request failed! {$this->providerId} returned an invalid response.", 6);
        }

        $this->user->profile->identifier  = $data->data->id;
        $this->user->profile->displayName = $data->data->full_name ? $data->data->full_name : $data->data->username;
        $this->user->profile->description = $data->data->bio;
        $this->user->profile->photoURL    = $data->data->profile_picture;

        $this->user->profile->webSiteURL  = $data->data->website;

        $this->user->profile->username    = $data->data->username;

        return $this->user->profile;
    }
    /**
    *
    */
    public function getUserContacts()
    {
        // refresh tokens if needed
        $this->refreshToken();

        //
        $response = array();
        $contacts = array();
        $profile = ((isset($this->user->profile->identifier))?($this->user->profile):($this->getUserProfile()));
        try {
            $response = $this->api->api("users/{$this->user->profile->identifier}/follows");
        } catch (\Exception $e) {
            throw new \Exception("User contacts request failed! {$this->providerId} returned an error: $e");
        }
        //

        if (isset($response) && $response->meta->code == 200) {
            foreach ($response->data as $contact) {
                try {
                    $contactInfo = $this->api->api("users/".$contact->id);
                } catch (\Exception $e) {
                    throw new \Exception("Contact info request failed for user {$contact->username}! {$this->providerId} returned an error: $e");
                }
                //
                $uc = new \Hybrid_User_Contact();
                //
                $uc->identifier     = $contact->id;
                $uc->profileURL     = "https://instagram.com/{$contact->username}";
                $uc->webSiteURL     = @$contactInfo->data->website;
                $uc->photoURL       = @$contact->profile_picture;
                $uc->displayName    = @$contact->full_name;
                $uc->description    = @$contactInfo->data->bio;
                //$uc->email          = ;
                //
                $contacts[] = $uc;
            }
        }
        return $contacts;
    }
}
</code>```

Changing the scope "basic" to "user_profile,user_media", it shows
different error

UPDATE

This is my Redirect URI

https://127.0.0.1/magento_241/sociallogin/social/callback/?hauth.done=Instagram

I'm not sure this could be the reason it's not working but green tick
is not showing next to the Instagram Basic display as it is showing for Facebook Login.

But my app is live here it shows live,

Somehow if I managed to log in (after entering credentials) no matter
what option do I choose in the below screenshot, it displays the error Oops, an error occurred. on this URL https://www.instagram.com/oauth/authorize/?client_id=MY_CLIENT_ID&redirect_uri=http%3A%2F%2F127.0.0.1%2Fmagento_241%2Fsociallogin%2Fsocial%2Fcallback%2F%3Fhauth.done&response_type=code&scope=basic

Let me know if anyone has a solution.

答:
While your redirect_uri might be working properly, have you made sure to add that URI to your Instagram App settings list of Valid OAuth Redirect URIs? If not, you will encounter an invalid redirect uri message.

To add this URI, go to your Facebook App's dashboard, then click on the sidebar to Basic Display:

Then, scrolling down on the right side, you will see the space for adding Valid OAuth Redirect URIs.

Body:
I'm using Magento 2.4.1, installed Social Login Extension and getting below error while login to Instagram, I'm using Hybrid auth libraries to login.

"error_type": "OAuthException", "code": 400, "error_message": "Invalid
scope: ['basic']"}

You can check the screenshot below,

Instagram.php

<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
*  (c) 2009-2012 HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
namespace Vendor\Module\Model\Providers;

/**
* Hybrid_Providers_Instagram (By Sebastian Lasse - https://github.com/sebilasse)
*/
class Instagram extends \Hybrid_Provider_Model_OAuth2
{
    // default permissions
    public $scope = "basic";

    /**
    * IDp wrappers initializer
    */
    public function initialize()
    {
        parent::initialize();

        // Provider api end-points
        $this->api->api_base_url  = "https://api.instagram.com/v1/";
        $this->api->authorize_url = "https://api.instagram.com/oauth/authorize/";
        $this->api->token_url     = "https://api.instagram.com/oauth/access_token";
    }

    /**
    * load the user profile from the IDp api client
    */
    public function getUserProfile()
    {
        $data = $this->api->api("users/self/");

        if ($data->meta->code != 200) {
            throw new \Exception("User profile request failed! {$this->providerId} returned an invalid response.", 6);
        }

        $this->user->profile->identifier  = $data->data->id;
        $this->user->profile->displayName = $data->data->full_name ? $data->data->full_name : $data->data->username;
        $this->user->profile->description = $data->data->bio;
        $this->user->profile->photoURL    = $data->data->profile_picture;

        $this->user->profile->webSiteURL  = $data->data->website;

        $this->user->profile->username    = $data->data->username;

        return $this->user->profile;
    }
    /**
    *
    */
    public function getUserContacts()
    {
        // refresh tokens if needed
        $this->refreshToken();

        //
        $response = array();
        $contacts = array();
        $profile = ((isset($this->user->profile->identifier))?($this->user->profile):($this->getUserProfile()));
        try {
            $response = $this->api->api("users/{$this->user->profile->identifier}/follows");
        } catch (\Exception $e) {
            throw new \Exception("User contacts request failed! {$this->providerId} returned an error: $e");
        }
        //

        if (isset($response) && $response->meta->code == 200) {
            foreach ($response->data as $contact) {
                try {
                    $contactInfo = $this->api->api("users/".$contact->id);
                } catch (\Exception $e) {
                    throw new \Exception("Contact info request failed for user {$contact->username}! {$this->providerId} returned an error: $e");
                }
                //
                $uc = new \Hybrid_User_Contact();
                //
                $uc->identifier     = $contact->id;
                $uc->profileURL     = "https://instagram.com/{$contact->username}";
                $uc->webSiteURL     = @$contactInfo->data->website;
                $uc->photoURL       = @$contact->profile_picture;
                $uc->displayName    = @$contact->full_name;
                $uc->description    = @$contactInfo->data->bio;
                //$uc->email          = ;
                //
                $contacts[] = $uc;
            }
        }
        return $contacts;
    }
}

Changing the scope "basic" to "user_profile,user_media", it shows
different error

UPDATE

This is my Redirect URI

https://127.0.0.1/magento_241/sociallogin/social/callback/?hauth.done=Instagram

I'm not sure this could be the reason it's not working but green tick
is not showing next to the Instagram Basic display as it is showing for Facebook Login.

But my app is live here it shows live,

Somehow if I managed to log in (after entering credentials) no matter
what option do I choose in the below screenshot, it displays the error Oops, an error occurred. on this URL https://www.instagram.com/oauth/authorize/?client_id=MY_CLIENT_ID&redirect_uri=http%3A%2F%2F127.0.0.1%2Fmagento_241%2Fsociallogin%2Fsocial%2Fcallback%2F%3Fhauth.done&response_type=code&scope=basic

Let me know if anyone has a solution.


问:
fputcsv displaying data in browser instead of downloading data as CSV file
I am using fputcsv function to export data as CSV file but it is displaying all data in browser instead of downloading this as CSV file. Here is my code

```<code>header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=export.csv');
$output = fopen('php://output', 'w');
fputcsv($output, $column_headings);
fclose($output);
</code>```

Data is displaying correctly in browser but I want to download this as export.csv file.I do not know what is wrong with this. Any suggestion regarding this will be appreciated.

答: I added ob_start(); at the start of my file and now I can export files.

Body:
I am using fputcsv function to export data as CSV file but it is displaying all data in browser instead of downloading this as CSV file. Here is my code

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=export.csv');
$output = fopen('php://output', 'w');
fputcsv($output, $column_headings);
fclose($output);

Data is displaying correctly in browser but I want to download this as export.csv file.I do not know what is wrong with this. Any suggestion regarding this will be appreciated.