问:
How to resolve permissions for this particular scenario in Azure Devops?
We want to manage vendors(external users) within ADO. What we want is that the vendors should have customised permissions and have only access to the projects they are added to. SO I believe we cannot use AAD groups as there is no point in making AAD group for each project.

The structure we have is that there is one Organisation and all the projects will be under that ORG. For internal users they should be able to see all the projects and view everything that is happening on all of those projects. The idea behind that is if someone wants to re-use that is already done in some other project, they can do it so that it saves time as they don’t have to re-invent the wheel.
To resolve this I have created AAD group and added all the internal users to it. Now this AAD group will be linked to ADO security group. That was easy but I am unable to resolve a problem where vendors should have restricted permissions to only projects they are working on.

Now, if I create an ADO security group for each project with customise permissions and add vendors to that group but it may be overwritten by a Project admin when he creates a team's group, add vendors to that teams group and add that teams to the member of Contributor group. They will inherit all the powers of the contributors group which eventually will give them more permissions that what we want to give them.

What is the best approach to resolve this scenario?

答: Provide Stakeholder access to the AAD group which you created for external users. Stakeholder doesn't give you full permissions. So you can limit the access to external users</p>


来源: stackexchange

问:
How to parse a time into a Date object from user input in JavaScript?
I am working on a form widget for users to enter a time of day into a text input (for a calendar application). Using JavaScript (we are using jQuery FWIW), I want to find the best way to parse the text that the user enters into a JavaScript Date() object so I can easily perform comparisons and other things on it.

I tried the parse() method and it is a little too picky for my needs. I would expect it to be able to successfully parse the following example input times (in addition to other logically similar time formats) as the same Date() object:

1:00 pm

1:00 p.m.

1:00 p

1:00pm

1:00p.m.

1:00p

1 pm

1 p.m.

1 p

1pm

1p.m.

1p

13:00

13

I am thinking that I might use regular expressions to split up the input and extract the information I want to use to create my Date() object. What is the best way to do this?

答:
The main upvoted and selected answers were causing trouble for me and outputting ridiculous results. Below is my stab at it which seems to solve all the issues most people were having, including mine. An added functionality to mine is the ability to specify 'am' or 'pm' as a time of day to default to should the user input not specify (e.g. 1:00). By default, it's set to 'pm'.

One thing to note is this function assumes the user wants to (and attempted to) provide a string representing a time input. Because of this, the "input validation and sanitation" only goes so far as to rule out anything that would cause an error, not anything that doesn't necessarily look like a time. This is best represented by the final three test entries in the array towards the bottom of the code snippet.

const parseTime = (timeString, assumedTimeOfDay = "pm") => {
  // Validate timeString input
  if (!timeString) return null

  const regex = /(\d{1,2})(\d{2})?([a|p]m?)?/
  const noOfDigits = timeString.replace(/[^\d]/g, "").length

  if (noOfDigits === 0) return null

  // Seconds are unsupported (rare use case in my eyes, feel free to edit)
  if (noOfDigits > 4) return null

  // Add a leading 0 to prevent bad regex match (i.e. 100 = 1hr 00min, not 10hr 0min)
  const sanitized = `${noOfDigits === 3 ? "0" : ""}${timeString}`
    .toLowerCase()
    .replace(/[^\dapm]/g, "")
  const parsed = sanitized.match(regex)

  if (!parsed) return null

  // Clean up and name parsed data
  const {
    input,
    hours,
    minutes,
    meridian
  } = {
    input: parsed[0],
    hours: Number(parsed[1] || 0),
    minutes: Number(parsed[2] || 0),
    // Defaults to pm if user provided assumedTimeOfDay is not am or pm
    meridian: /am/.test(`${parsed[3] || assumedTimeOfDay.toLowerCase()}m`) ?
      "am" : "pm",
  }

  // Quick check for valid numbers
  if (hours < 0 || hours >= 24 || minutes < 0 || minutes >= 60) return null

  // Convert hours to 24hr format
  const timeOfDay = hours >= 13 ? "pm" : meridian
  const newHours =
    hours >= 13 ?
    hours :
    hours === 12 && timeOfDay === "am" ?
    0 :
    (hours === 12 && timeOfDay === "pm") || timeOfDay === "am" ?
    hours :
    hours + 12

  // Convert data to Date object and return
  return new Date(new Date().setHours(newHours, minutes, 0))
}

const times = [
  '12',
  '12p',
  '12pm',
  '12p.m.',
  '12 p',
  '12 pm',
  '12 p.m.',
  '12:00',
  '12:00p',
  '12:00pm',
  '12:00p.m.',
  '12:00 p',
  '12:00 pm',
  '12:00 p.m.',
  '12:00',
  '12:00p',
  '12:00pm',
  '12:00p.m.',
  '12:00 p',
  '12:00 pm',
  '12:00 p.m.',
  '1200',
  '1200p',
  '1200pm',
  '1200p.m.',
  '1200 p',
  '1200 pm',
  '1200 p.m.',
  '12',
  '1200',
  '12:00',
  '1',
  '1p',
  '1pm',
  '1p.m.',
  '1 p',
  '1 pm',
  '1 p.m.',
  '1:00',
  '1:00p',
  '1:00pm',
  '1:00p.m.',
  '1:00 p',
  '1:00 pm',
  '1:00 p.m.',
  '01:00',
  '01:00p',
  '01:00pm',
  '01:00p.m.',
  '01:00 p',
  '01:00 pm',
  '01:00 p.m.',
  '0100',
  '0100p',
  '0100pm',
  '0100p.m.',
  '0100 p',
  '0100 pm',
  '0100 p.m.',
  '13',
  '1300',
  '13:00',
  'random',
  '092fsd9)*(U243',
  '092fsd9)*(U'
]

times.map(t => {
  const parsed = parseTime(t)

  if (parsed) {
    console.log(`${parsed.toLocaleTimeString()} from ${t}`)
  } else {
    console.log(`Invalid Time (${t})`)
  }
})```

Although I've tested this quite a bit, I'm sure I tunnel-visioned on something. If someone is able to break it (in a reasonable way), please comment and I'll see about updating!

OwnerDisplayName: lencioni

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Andy Lester

Body:
The main upvoted and selected answers were causing trouble for me and outputting ridiculous results. Below is my stab at it which seems to solve all the issues most people were having, including mine. An added functionality to mine is the ability to specify 'am' or 'pm' as a time of day to default to should the user input not specify (e.g. 1:00). By default, it's set to 'pm'.

One thing to note is this function assumes the user wants to (and attempted to) provide a string representing a time input. Because of this, the "input validation and sanitation" only goes so far as to rule out anything that would cause an error, not anything that doesn't necessarily look like a time. This is best represented by the final three test entries in the array towards the bottom of the code snippet.

const parseTime = (timeString, assumedTimeOfDay = "pm") => {
  // Validate timeString input
  if (!timeString) return null

  const regex = /(\d{1,2})(\d{2})?([a|p]m?)?/
  const noOfDigits = timeString.replace(/[^\d]/g, "").length

  if (noOfDigits === 0) return null

  // Seconds are unsupported (rare use case in my eyes, feel free to edit)
  if (noOfDigits > 4) return null

  // Add a leading 0 to prevent bad regex match (i.e. 100 = 1hr 00min, not 10hr 0min)
  const sanitized = `${noOfDigits === 3 ? "0" : ""}${timeString}`
    .toLowerCase()
    .replace(/[^\dapm]/g, "")
  const parsed = sanitized.match(regex)

  if (!parsed) return null

  // Clean up and name parsed data
  const {
    input,
    hours,
    minutes,
    meridian
  } = {
    input: parsed[0],
    hours: Number(parsed[1] || 0),
    minutes: Number(parsed[2] || 0),
    // Defaults to pm if user provided assumedTimeOfDay is not am or pm
    meridian: /am/.test(`${parsed[3] || assumedTimeOfDay.toLowerCase()}m`) ?
      "am" : "pm",
  }

  // Quick check for valid numbers
  if (hours < 0 || hours >= 24 || minutes < 0 || minutes >= 60) return null

  // Convert hours to 24hr format
  const timeOfDay = hours >= 13 ? "pm" : meridian
  const newHours =
    hours >= 13 ?
    hours :
    hours === 12 && timeOfDay === "am" ?
    0 :
    (hours === 12 && timeOfDay === "pm") || timeOfDay === "am" ?
    hours :
    hours + 12

  // Convert data to Date object and return
  return new Date(new Date().setHours(newHours, minutes, 0))
}

const times = [
  '12',
  '12p',
  '12pm',
  '12p.m.',
  '12 p',
  '12 pm',
  '12 p.m.',
  '12:00',
  '12:00p',
  '12:00pm',
  '12:00p.m.',
  '12:00 p',
  '12:00 pm',
  '12:00 p.m.',
  '12:00',
  '12:00p',
  '12:00pm',
  '12:00p.m.',
  '12:00 p',
  '12:00 pm',
  '12:00 p.m.',
  '1200',
  '1200p',
  '1200pm',
  '1200p.m.',
  '1200 p',
  '1200 pm',
  '1200 p.m.',
  '12',
  '1200',
  '12:00',
  '1',
  '1p',
  '1pm',
  '1p.m.',
  '1 p',
  '1 pm',
  '1 p.m.',
  '1:00',
  '1:00p',
  '1:00pm',
  '1:00p.m.',
  '1:00 p',
  '1:00 pm',
  '1:00 p.m.',
  '01:00',
  '01:00p',
  '01:00pm',
  '01:00p.m.',
  '01:00 p',
  '01:00 pm',
  '01:00 p.m.',
  '0100',
  '0100p',
  '0100pm',
  '0100p.m.',
  '0100 p',
  '0100 pm',
  '0100 p.m.',
  '13',
  '1300',
  '13:00',
  'random',
  '092fsd9)*(U243',
  '092fsd9)*(U'
]

times.map(t => {
  const parsed = parseTime(t)

  if (parsed) {
    console.log(`${parsed.toLocaleTimeString()} from ${t}`)
  } else {
    console.log(`Invalid Time (${t})`)
  }
})

Although I've tested this quite a bit, I'm sure I tunnel-visioned on something. If someone is able to break it (in a reasonable way), please comment and I'll see about updating!


问:
Compiler error - is private within this context - Line 31
```<code>#include<iostream>
#include<string>
using namespace std;

class Item{
    private:
        string type;
        string abbrv;
        string uID;
        int aircraft;
        double weight;
        string destination;
    public:
        void print(){
        cout << "ULD: " << type << endl;
        cout << "Abbreviation: " << abbrv << endl;
        cout << "ULD-ID: " << uID << endl;
        cout << "Aircraft: " << aircraft << endl;
        cout << "Weight: " << weight << " Kilograms" << endl;
        cout << "Destination: " << destination << endl;
   }

    friend void kilotopound(Item);
};
void kilotopound(Item I){
    cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl;
}

int main(){
   Item I;
   I.type = "Container";
   I.uID = "AYK68943IB";
   I.abbrv = "AYK";
   I.aircraft = 737;
   I.weight = 1654;
   I.destination = "PDX";
   I.print();
   kilotopound(I);

   return 0;
}
</code>```

Starting on line 31 I'm getting the error 'std::__cxxll::string Item::type' is private within this context

I'm basically trying to make the data private from this code

```<code>class Item{
    public:
        string type;
        string abbrv;
        string uID;
        int aircraft;
        double weight;
        string destination;
    void print(){
        cout << "ULD: " << type << endl;
        cout << "Abbreviation: " << abbrv << endl;
        cout << "ULD-ID: " << uID << endl;
        cout << "Aircraft: " << aircraft << endl;
        cout << "Weight: " << weight << " Kilograms" << endl;
        cout << "Destination: " << destination << endl;
   }

    friend void kilotopound(Item);
};
void kilotopound(Item I){
    cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl;
}

int main(){
   Item I;
   I.type = "Container";
   I.uID = "AYK68943IB";
   I.abbrv = "AYK";
   I.aircraft = 737;
   I.weight = 1654;
   I.destination = "PDX";
   I.print();
   kilotopound(I);

   return 0;
}
</code>```

Any help would be greatly appreciated, I'm just sort of lost on how I can resolve the error. Thanks!

Also I need to be able to copy and output the copied data once again if anyone can help with that as well, with private data too. Thanks again!

答:
```<code>#include<iostream>
#include<string>

using namespace std;

class Item{
    private:
        string type;
        string abbrv;
        string uID;
        int aircraft;
        double weight;
        string destination;
    public:
        Item(string t, string a, string u, int aC, double w, string d){
            type = t;
            abbrv = a;
            uID = u;
            aircraft = aC;
            weight = w;
            destination = d;
        }
        void print() {
          cout << "ULD: " << type << endl;
          cout << "Abbreviation: " << abbrv << endl;
          cout << "ULD-ID: " << uID << endl;
          cout << "Aircraft: " << aircraft << endl;
          cout << "Weight: " << weight << " Kilograms" << endl;
          cout << "Destination: " << destination << endl;
        }

    friend void kilotopound(Item);
};

void kilotopound(Item I){
    cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl;
}

int main(){
   Item I ("Container", "AYK68943IB", "AYK", 737, 1654, "PDX");
   I.print();
   kilotopound(I);

   return 0;
}

</code>```

Body:
#include<iostream>
#include<string>
using namespace std;

class Item{
    private:
        string type;
        string abbrv;
        string uID;
        int aircraft;
        double weight;
        string destination;
    public:
        void print(){
        cout << "ULD: " << type << endl;
        cout << "Abbreviation: " << abbrv << endl;
        cout << "ULD-ID: " << uID << endl;
        cout << "Aircraft: " << aircraft << endl;
        cout << "Weight: " << weight << " Kilograms" << endl;
        cout << "Destination: " << destination << endl;
   }

    friend void kilotopound(Item);
};
void kilotopound(Item I){
    cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl;
}

int main(){
   Item I;
   I.type = "Container";
   I.uID = "AYK68943IB";
   I.abbrv = "AYK";
   I.aircraft = 737;
   I.weight = 1654;
   I.destination = "PDX";
   I.print();
   kilotopound(I);

   return 0;
}

Starting on line 31 I'm getting the error 'std::__cxxll::string Item::type' is private within this context

I'm basically trying to make the data private from this code

class Item{
    public:
        string type;
        string abbrv;
        string uID;
        int aircraft;
        double weight;
        string destination;
    void print(){
        cout << "ULD: " << type << endl;
        cout << "Abbreviation: " << abbrv << endl;
        cout << "ULD-ID: " << uID << endl;
        cout << "Aircraft: " << aircraft << endl;
        cout << "Weight: " << weight << " Kilograms" << endl;
        cout << "Destination: " << destination << endl;
   }

    friend void kilotopound(Item);
};
void kilotopound(Item I){
    cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl;
}

int main(){
   Item I;
   I.type = "Container";
   I.uID = "AYK68943IB";
   I.abbrv = "AYK";
   I.aircraft = 737;
   I.weight = 1654;
   I.destination = "PDX";
   I.print();
   kilotopound(I);

   return 0;
}

Any help would be greatly appreciated, I'm just sort of lost on how I can resolve the error. Thanks!

Also I need to be able to copy and output the copied data once again if anyone can help with that as well, with private data too. Thanks again!


问:
Copy original array with empty values
I have the following array:

```<code>arr1 = [{Name: "John", Email: "john@example.com", Age: "29"}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
</code>```

How can I get this array as:

```<code>arr2 = [{Name: "", Email: "", Age: ""}]
</code>```

without mutating arr1

I have tried doing:

```<code>let arr2 = arr1[0]

for (let i in arr2) {
    arr2[i] = ""
}

console.log(arr1) //returns [{Name: "", Email: "", Age: ""}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
console.log(arr2) //returns [{Name: "", Email: "", Age: ""}]
</code>```

but this mutates arr1[0] with empty values as well

I have searched a lot of questions on SO, but couldn't get anything that would set all the values empty.

答:
Just Simple replace the values using for loop or in the way you want to change it.

var myDog = {
  "name": "Coder",
  "legs": 4,
  "tails": 1,
  "friends": ["freeCodeCamp Campers"]
};

// Update the name value
myDog.name = "Happy Coder";
document.getElementById("p1").innerHTML = Object.values(myDog);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='p1'></div></code>```

Title: Copy original array with empty values

Body:
I have the following array:

arr1 = [{Name: "John", Email: "john@example.com", Age: "29"}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]

How can I get this array as:

arr2 = [{Name: "", Email: "", Age: ""}]

without mutating arr1

I have tried doing:

let arr2 = arr1[0]

for (let i in arr2) {
    arr2[i] = ""
}

console.log(arr1) //returns [{Name: "", Email: "", Age: ""}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
console.log(arr2) //returns [{Name: "", Email: "", Age: ""}]

but this mutates arr1[0] with empty values as well

I have searched a lot of questions on SO, but couldn't get anything that would set all the values empty.

Body:
Just Simple replace the values using for loop or in the way you want to change it.

var myDog = {
  "name": "Coder",
  "legs": 4,
  "tails": 1,
  "friends": ["freeCodeCamp Campers"]
};

// Update the name value
myDog.name = "Happy Coder";
document.getElementById("p1").innerHTML = Object.values(myDog);

<div id='p1'></div>


问:
SQL for Monthly YOY (percentage change while keeping the monthly data frequency)?
Suppose I have a table called monthly metrics. Sample row in table below:

EOM
BRAND
METRIC

1/31/2021
Nike
100

2/28/2021
Adidas
68

1/31/2022
Nike
110

2/28/2022
Adidas
68

...
...
...

How do I get:

EOM
BRAND
METRIC
YOY_CHANGE

1/31/2021
Nike
100
Null

1/31/2021
Adidas
68
Null

1/31/2022
Nike
110
10%

2/28/2022
Adidas
68
0

...
...
...
...

Would love something that works in Snowflake (SQL: ANSI), but welcome any general ideas.

答:
A CASE statement and LAG function can do this:

```<code>WITH data(EOM, BRAND, METRIC) AS (
    SELECT to_date(column1, 'mm/dd/yyyy'), column2, column3
    FROM VALUES
        ('1/31/2021','Nike',100),
        ('2/28/2021','Adidas',68),
        ('1/31/2022','Nike',110),
        ('2/28/2022','Adidas',68),
        ('2/08/2022','Tesla',0),
        ('2/08/2022','Tesla',99999)
)
SELECT
    eom,
    brand,
    metric,
    lag(metric)over(partition by brand order by eom) as prior_metic,
    case
        when prior_metic is null then null
        when prior_metic = metric then '0'
        when prior_metic = 0 then '+infinity'
        else round(((metric - prior_metic) / prior_metic)*100,0)::text || '%'
    end as YOY_CHANGE
FROM data
ORDER BY 1,2;
</code>```

EOM
BRAND
METRIC
PRIOR_METIC
YOY_CHANGE

2021-01-31
Nike
100

2021-02-28
Adidas
68

2022-01-31
Nike
110
100
10%

2022-02-08
Tesla
0

2022-02-08
Tesla
99,999
0
+infinity

2022-02-28
Adidas
68
68
0

If you want strictly ASNI then the reusing the prior_metric is not allowed so you an mash the LAG in N times, and hope the DB is smart enough..

```<code>SELECT
    eom,
    brand,
    metric,
    case
        when lag(metric)over(partition by brand order by eom) is null then null
        when lag(metric)over(partition by brand order by eom) = metric then '0'
        when lag(metric)over(partition by brand order by eom) = 0 then '+infinity'
        else round(((metric - lag(metric)over(partition by brand order by eom)) / lag(metric)over(partition by brand order by eom))*100,0)::text || '%'
    end as YOY_CHANGE
FROM data
ORDER BY 1,2;
</code>```

Or use a CTE/Sub-select:

```<code>SELECT
    eom,
    brand,
    metric,
    case
        when prior_metric is null then null
        when prior_metric = metric then '0'
        when prior_metric = 0 then '+infinity'
        else round(((metric - prior_metric) / prior_metric)*100,0)::text || '%'
    end as YOY_CHANGE
FROM (
    SELECT
        eom,
        brand,
        metric,
        lag(metric)over(partition by brand order by eom) as prior_metric
    FROM data
)
ORDER BY 1,2;
</code>```

Body:
A CASE statement and LAG function can do this:

WITH data(EOM, BRAND, METRIC) AS (
    SELECT to_date(column1, 'mm/dd/yyyy'), column2, column3
    FROM VALUES
        ('1/31/2021','Nike',100),
        ('2/28/2021','Adidas',68),
        ('1/31/2022','Nike',110),
        ('2/28/2022','Adidas',68),
        ('2/08/2022','Tesla',0),
        ('2/08/2022','Tesla',99999)
)
SELECT
    eom,
    brand,
    metric,
    lag(metric)over(partition by brand order by eom) as prior_metic,
    case
        when prior_metic is null then null
        when prior_metic = metric then '0'
        when prior_metic = 0 then '+infinity'
        else round(((metric - prior_metic) / prior_metic)*100,0)::text || '%'
    end as YOY_CHANGE
FROM data
ORDER BY 1,2;

EOM
BRAND
METRIC
PRIOR_METIC
YOY_CHANGE

2021-01-31
Nike
100

2021-02-28
Adidas
68

2022-01-31
Nike
110
100
10%

2022-02-08
Tesla
0

2022-02-08
Tesla
99,999
0
+infinity

2022-02-28
Adidas
68
68
0

If you want strictly ASNI then the reusing the prior_metric is not allowed so you an mash the LAG in N times, and hope the DB is smart enough..

SELECT
    eom,
    brand,
    metric,
    case
        when lag(metric)over(partition by brand order by eom) is null then null
        when lag(metric)over(partition by brand order by eom) = metric then '0'
        when lag(metric)over(partition by brand order by eom) = 0 then '+infinity'
        else round(((metric - lag(metric)over(partition by brand order by eom)) / lag(metric)over(partition by brand order by eom))*100,0)::text || '%'
    end as YOY_CHANGE
FROM data
ORDER BY 1,2;

Or use a CTE/Sub-select:

SELECT
    eom,
    brand,
    metric,
    case
        when prior_metric is null then null
        when prior_metric = metric then '0'
        when prior_metric = 0 then '+infinity'
        else round(((metric - prior_metric) / prior_metric)*100,0)::text || '%'
    end as YOY_CHANGE
FROM (
    SELECT
        eom,
        brand,
        metric,
        lag(metric)over(partition by brand order by eom) as prior_metric
    FROM data
)
ORDER BY 1,2;


问:
Django error showing none type when it isn't none when calling a function
can any one explain why the following error occurs
AttributeError: 'NoneType' object has no attribute 'check_data'

the error occurs  when i tried to call "passdata = self.check_data(request)" method
can any one explain why it occurs were iam going wrong

class UpdateRepo:

```<code>def update_marks(self,request):
    passdata = self.check_data(request)
    get_values = Marks.objects.filter(id=request.data['id'])
    if get_values.exists():
        thr = get_values.update(
            English = passdata[0],
            Tamil = passdata[1],
            Maths = passdata[2]
        )
    return thr

def check_data(self,request):
    if int(request.data['English']) >50:
        English = request.data['English']
    else:
        English = constants.Marks['English']
    if int(request.data['Tamil']) >50:
        Tamil = request.data['Tamil']
    else:
        Tamil = constants.Marks['Tamil']
    if int(request.data['Maths']) >50:
        Maths = request.data['Maths']
    else:
        Maths = constants.Marks['Maths']
    return [English,Tamil,Maths]
</code>```

答:
It seems you haven't created an instance for your class. for example, if your method belong to class "Something". then add:</p>
```<code>abc = Something()
abc.update_marks(request)
</code>```

Body:
can any one explain why the following error occurs
AttributeError: 'NoneType' object has no attribute 'check_data'

the error occurs  when i tried to call "passdata = self.check_data(request)" method
can any one explain why it occurs were iam going wrong

class UpdateRepo:

def update_marks(self,request):
    passdata = self.check_data(request)
    get_values = Marks.objects.filter(id=request.data['id'])
    if get_values.exists():
        thr = get_values.update(
            English = passdata[0],
            Tamil = passdata[1],
            Maths = passdata[2]
        )
    return thr

def check_data(self,request):
    if int(request.data['English']) >50:
        English = request.data['English']
    else:
        English = constants.Marks['English']
    if int(request.data['Tamil']) >50:
        Tamil = request.data['Tamil']
    else:
        Tamil = constants.Marks['Tamil']
    if int(request.data['Maths']) >50:
        Maths = request.data['Maths']
    else:
        Maths = constants.Marks['Maths']
    return [English,Tamil,Maths]

Body:
It seems you haven't created an instance for your class. for example, if your method belong to class "Something". then add:

abc = Something()
abc.update_marks(request)


问:
Zend redirect() is not working with AJAX request?
For example I have an action in Controller.

```<code>public function redirectnowAction() {
   $this->_redirect( '/module/controller/action' );
}
</code>```

When I call above action in normal way then it redirect successfully to desired location But when I call above action by AJAX then it does not redirect to required URL and only show desired page content in firebug.

JS code for AJAX

```<code>jQuery('.AjaxLink').live( 'click', function(event) {
    event.preventDefault();
    // load the href attribute of the link that was clicked
    jQuery.getJSON(this.href, function(snippets) {
        for(var id in snippets) {
            // updated to deal with any type of HTML
            jQuery('#' + id).html( snippets[id] );
        }
    });
});
</code>```

How to redirect to action after AJAX request ?

Thanks

答: The ajax request itself would be subject to the redirect, not the browser window. Hence you would see the redirected content as the data returned via ajax. One solution would be to do a javascript redirect once the ajax request has been successfully run.</p>

ContentLicense: CC BY-SA 3.0

Body:
For example I have an action in Controller.

public function redirectnowAction() {
   $this->_redirect( '/module/controller/action' );
}

When I call above action in normal way then it redirect successfully to desired location But when I call above action by AJAX then it does not redirect to required URL and only show desired page content in firebug.

JS code for AJAX

jQuery('.AjaxLink').live( 'click', function(event) {
    event.preventDefault();
    // load the href attribute of the link that was clicked
    jQuery.getJSON(this.href, function(snippets) {
        for(var id in snippets) {
            // updated to deal with any type of HTML
            jQuery('#' + id).html( snippets[id] );
        }
    });
});

How to redirect to action after AJAX request ?

Thanks


问:
How can I compare two arrays and run a function depending on the number of matching items (regardless of index)?
I had a previous solution with .forEach that didn't consider the fact that the answers can be selected in the wrong order, so the items at to be at the same exact index. If it was selected in the wrong order it wouldn't match (even though it was the right answer).

Now I'm trying a solution with .every, but it's not changing score when the button "check answers" is clicked. In case you'd like to check the entire code here it is (it's a bit too much to type in - I'm new to stackoverflow so lmk if a better method is suggested to share multiple components): https://replit.com/@arshia93/Quizzical#sections/QuizData.jsx

```<code>function scoreQuiz(allCorrectAnswers, selections) {
  let totalScore = 0;
  if(allCorrectAnswers.length === selections.length) {
    return allCorrectAnswers.every((element, index) => {
      element === selections[index] ? totalScore++ : totalScore
    })
    setScore(totalScore)
  }
  setFinished(!finished)
}
</code>```

答:
What alonealgorithm said is true that you should not return the .every() call, since you want to perform a state update after it is complete. However, I don't think .every() is the array method you want to use here. It will check every item and perform the totalScore++, but it is not the most declarative way to do so.

I would recommend using the .reduce() method, since that is essentially what you're trying to do here. This should help you out:

```<code>const totalScore = selections.reduce((score, selection) =>
  score + (allCorrectAnswers.includes(selection) ? 1 : 0)
, 0);

setScore(totalScore);
</code>```

Note! If it is possible for 2 questions to have the same answer option, then this will not work and incorrectly identify a correct answer. In order to accommodate for this, you would need to replace the selection at a particular index (rather than appending each one as it is selected), or match each selection to a question id.

Body:
I had a previous solution with .forEach that didn't consider the fact that the answers can be selected in the wrong order, so the items at to be at the same exact index. If it was selected in the wrong order it wouldn't match (even though it was the right answer).

Now I'm trying a solution with .every, but it's not changing score when the button "check answers" is clicked. In case you'd like to check the entire code here it is (it's a bit too much to type in - I'm new to stackoverflow so lmk if a better method is suggested to share multiple components): https://replit.com/@arshia93/Quizzical#sections/QuizData.jsx

function scoreQuiz(allCorrectAnswers, selections) {
  let totalScore = 0;
  if(allCorrectAnswers.length === selections.length) {
    return allCorrectAnswers.every((element, index) => {
      element === selections[index] ? totalScore++ : totalScore
    })
    setScore(totalScore)
  }
  setFinished(!finished)
}

Body:
What alonealgorithm said is true that you should not return the .every() call, since you want to perform a state update after it is complete. However, I don't think .every() is the array method you want to use here. It will check every item and perform the totalScore++, but it is not the most declarative way to do so.

I would recommend using the .reduce() method, since that is essentially what you're trying to do here. This should help you out:

const totalScore = selections.reduce((score, selection) =>
  score + (allCorrectAnswers.includes(selection) ? 1 : 0)
, 0);

setScore(totalScore);

Note! If it is possible for 2 questions to have the same answer option, then this will not work and incorrectly identify a correct answer. In order to accommodate for this, you would need to replace the selection at a particular index (rather than appending each one as it is selected), or match each selection to a question id.


问:
How to return a numpy array of the indices of the first element in each row of a numpy array with a given value?
Given a numpy array of shape (2, 4):

```<code>input = np.array([[False, True, False, True], [False, False, True, True]])
</code>```

I want to return an array of shape (N,) where each element of the array is the index of the first True value:

```<code>expected = np.array([1, 2])
</code>```

Is there an easy way to do this using numpy functions and without resorting to standard loops?

答:
This worked for me:</p>
```<code>nonzeros = np.nonzero(input)
u, indices = np.unique(nonzeros[0], return_index=True)
expected = nonzeros[1][indices]
</code>```

Body:
Given a numpy array of shape (2, 4):

input = np.array([[False, True, False, True], [False, False, True, True]])

I want to return an array of shape (N,) where each element of the array is the index of the first True value:

expected = np.array([1, 2])

Is there an easy way to do this using numpy functions and without resorting to standard loops?

Body:
This worked for me:

nonzeros = np.nonzero(input)
u, indices = np.unique(nonzeros[0], return_index=True)
expected = nonzeros[1][indices]


问:
Node.js 17.0.1 Gatsby error - "digital envelope routines::unsupported ... ERR_OSSL_EVP_UNSUPPORTED"
I am building a Gatsby site. I upgraded Node.js to v17.0.1, and when I run a build, there is an error:

Error: digital envelope routines::unsupported

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'
```

If I downgrade it to v16, it works fine, and the build will be successful. How can I fix this?

From googling, this may be a similar issue:
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt #48

答: I think you should downgrade your Node.js or use nvm to switch between Node.js versions. I did this and React worked fine.</p>

Body:
I am building a Gatsby site. I upgraded Node.js to v17.0.1, and when I run a build, there is an error:

Error: digital envelope routines::unsupported

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

If I downgrade it to v16, it works fine, and the build will be successful. How can I fix this?

From googling, this may be a similar issue:
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt #48


问:
Spring Boot container won't connect to MySQL
I want to connect my Spring Boot container with my database container. I can connect with a db app like db beaver.

Here is my setup:

docker-compose.yml

version: '3'

services:

  mysql-db:
    image: mysql:5.7
    ports:
      - '127.0.0.1:3306:3306'
    environment:
      MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
    volumes:
      - mysql-data:/var/lib/mysql

  reporter-service:
    image: openjdk:11-jdk
    depends_on:
      - mysql-db
    container_name: reporter-service
    volumes:
      - ./reporter-service/build/libs:/usr/app
      - ./wait-for-it.sh:/usr/local/bin/wait-for-it.sh
    working_dir: /usr/app
    command: wait-for-it.sh mysql-db:3306 -t 240 -- java -jar reporter-service-*.jar

volumes:
  mysql-data:
```
<p>Spring Boot <strong>application.properties</strong></p>
```spring.datasource.url=jdbc:mysql://localhost:3306/reporter-db
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=
```
<p><strong>gradle.properties</strong></p>
```mariadbVersion=2.7.4
mysqlVersion=8.0.28
springBootVersion=2.6.3
mapstructVersion=1.4.2.Final
lombokVersion=1.18.20
liquibaseVersion=4.4.3
hibernate5Version=4.4.3
```
<p><strong>build.gradle</strong></p>
```plugins {
    id 'org.springframework.boot' version "$springBootVersion"
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'org.liquibase.gradle' version '2.0.4'
    id 'java'
}

group = 'com.codesmith.reporterservice'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.springframework.boot:spring-boot-autoconfigure"
    implementation "org.springframework.boot:spring-boot-starter"
    implementation "org.springframework.boot:spring-boot-starter-actuator"
    implementation "org.springframework.boot:spring-boot-starter-data-jpa"
    implementation "org.springframework.boot:spring-boot-starter-security"
    implementation "org.springframework.boot:spring-boot-starter-validation"
    implementation "org.springframework.boot:spring-boot-starter-web"

    implementation "org.mariadb.jdbc:mariadb-java-client:$mariadbVersion"
    implementation "mysql:mysql-connector-java:$mysqlVersion"

    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'

    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.h2database:h2'
    runtimeOnly 'mysql:mysql-connector-java'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

springBoot {
    mainClass = 'com.codesmith.reporterservice.ReporterServiceApplication'
}

tasks.named('test') {
    useJUnitPlatform()
}

tasks.withType(JavaCompile) {
    options.compilerArgs += ['-Xlint:deprecation']
}

tasks.withType(Copy).all {
    duplicatesStrategy 'warn'
}

jar {
    enabled = false
}
```

Exception

reporter-service  | java.sql.SQLNonTransientConnectionException: Could not connect to address=(host=localhost)(port=3306)(type=master) : Socket fail to connect to host:localhost, port:3306. Connection refused (Connection refused)
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:197) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1394) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:635) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:150) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.Driver.connect(Driver.java:89) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:181) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:175) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:173) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1460) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1494) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at com.codesmith.reporterservice.ReporterServiceApplication.main(ReporterServiceApplication.java:10) ~[classes!/:na]
reporter-service  |     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
reporter-service  |     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
reporter-service  |     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
reporter-service  |     at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
reporter-service  |     at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  | Caused by: java.sql.SQLNonTransientConnectionException: Socket fail to connect to host:localhost, port:3306. Connection refused (Connection refused)
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:188) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.createSocket(AbstractConnectProtocol.java:257) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.createConnection(AbstractConnectProtocol.java:521) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1389) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     ... 57 common frames omitted
reporter-service  | Caused by: java.net.ConnectException: Connection refused (Connection refused)
reporter-service  |     at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
reporter-service  |     at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412) ~[na:na]
reporter-service  |     at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255) ~[na:na]
reporter-service  |     at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237) ~[na:na]
reporter-service  |     at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:na]
reporter-service  |     at java.base/java.net.Socket.connect(Socket.java:609) ~[na:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.createSocket(AbstractConnectProtocol.java:252) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     ... 59 common frames omitted
reporter-service  |
reporter-service  | 2022-02-12 22:23:24.425  WARN 1 --- [           main] o.h.e.j.e.i.JdbcEnvironmentInitiator     : HHH000342: Could not obtain connection to query metadata
reporter-service  |
reporter-service  | java.sql.SQLNonTransientConnectionException: Could not connect to address=(host=localhost)(port=3306)(type=master) : Socket fail to connect to host:localhost, port:3306. Connection refused (Connection refused)
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:197) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1394) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:635) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:150) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.Driver.connect(Driver.java:89) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:181) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:175) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:173) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1460) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1494) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at com.codesmith.reporterservice.ReporterServiceApplication.main(ReporterServiceApplication.java:10) ~[classes!/:na]
reporter-service  |     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
reporter-service  |     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
reporter-service  |     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
reporter-service  |     at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
reporter-service  |     at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  | Caused by: java.sql.SQLNonTransientConnectionException: Socket fail to connect to host:localhost, port:3306. Connection refused (Connection refused)
reporter-service  | 2022-02-12 22:23:25.256  WARN 1 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
```

At this point I'm stuck. The error does not tell me anything specific and it is difficult to find a solution here. I have tried to use other drivers so far but from my point of view everything is configured correctly, isn't it? The error occurs when I start the docker-compose up.

答:
Try adding a network and environments so that containers can communicate,

```<code>version: '3'

services:
  mysql-db:
    ...
    networks:
      - backend

  reporter-service:
    ...
    environment:
      spring.datasource.url: jdbc:mysql://mysql-db:3306/reporter-db
      spring.datasource.driver-class-name: org.mariadb.jdbc.Driver
      spring.datasource.username: root
      spring.datasource.password:

    networks:
      - backend

volumes:
  mysql-data:

networks:
  backend:
</code>```

Note: spring.datasource.url must have MySQL docker service name as a host, which is, mysql-db in your case.

Body:
I want to connect my Spring Boot container with my database container. I can connect with a db app like db beaver.

Here is my setup:

docker-compose.yml

version: '3'

services:

  mysql-db:
    image: mysql:5.7
    ports:
      - '127.0.0.1:3306:3306'
    environment:
      MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
    volumes:
      - mysql-data:/var/lib/mysql

  reporter-service:
    image: openjdk:11-jdk
    depends_on:
      - mysql-db
    container_name: reporter-service
    volumes:
      - ./reporter-service/build/libs:/usr/app
      - ./wait-for-it.sh:/usr/local/bin/wait-for-it.sh
    working_dir: /usr/app
    command: wait-for-it.sh mysql-db:3306 -t 240 -- java -jar reporter-service-*.jar

volumes:
  mysql-data:

Spring Boot application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/reporter-db
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=

gradle.properties

mariadbVersion=2.7.4
mysqlVersion=8.0.28
springBootVersion=2.6.3
mapstructVersion=1.4.2.Final
lombokVersion=1.18.20
liquibaseVersion=4.4.3
hibernate5Version=4.4.3

build.gradle

plugins {
    id 'org.springframework.boot' version "$springBootVersion"
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'org.liquibase.gradle' version '2.0.4'
    id 'java'
}

group = 'com.codesmith.reporterservice'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.springframework.boot:spring-boot-autoconfigure"
    implementation "org.springframework.boot:spring-boot-starter"
    implementation "org.springframework.boot:spring-boot-starter-actuator"
    implementation "org.springframework.boot:spring-boot-starter-data-jpa"
    implementation "org.springframework.boot:spring-boot-starter-security"
    implementation "org.springframework.boot:spring-boot-starter-validation"
    implementation "org.springframework.boot:spring-boot-starter-web"

    implementation "org.mariadb.jdbc:mariadb-java-client:$mariadbVersion"
    implementation "mysql:mysql-connector-java:$mysqlVersion"

    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'

    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.h2database:h2'
    runtimeOnly 'mysql:mysql-connector-java'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

springBoot {
    mainClass = 'com.codesmith.reporterservice.ReporterServiceApplication'
}

tasks.named('test') {
    useJUnitPlatform()
}

tasks.withType(JavaCompile) {
    options.compilerArgs += ['-Xlint:deprecation']
}

tasks.withType(Copy).all {
    duplicatesStrategy 'warn'
}

jar {
    enabled = false
}

Exception

reporter-service  | java.sql.SQLNonTransientConnectionException: Could not connect to address=(host=localhost)(port=3306)(type=master) : Socket fail to connect to host:localhost, port:3306. Connection refused (Connection refused)
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:197) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1394) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:635) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:150) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.Driver.connect(Driver.java:89) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:181) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:175) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:173) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1460) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1494) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at com.codesmith.reporterservice.ReporterServiceApplication.main(ReporterServiceApplication.java:10) ~[classes!/:na]
reporter-service  |     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
reporter-service  |     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
reporter-service  |     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
reporter-service  |     at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
reporter-service  |     at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  | Caused by: java.sql.SQLNonTransientConnectionException: Socket fail to connect to host:localhost, port:3306. Connection refused (Connection refused)
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:188) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.createSocket(AbstractConnectProtocol.java:257) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.createConnection(AbstractConnectProtocol.java:521) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1389) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     ... 57 common frames omitted
reporter-service  | Caused by: java.net.ConnectException: Connection refused (Connection refused)
reporter-service  |     at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
reporter-service  |     at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412) ~[na:na]
reporter-service  |     at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255) ~[na:na]
reporter-service  |     at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237) ~[na:na]
reporter-service  |     at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:na]
reporter-service  |     at java.base/java.net.Socket.connect(Socket.java:609) ~[na:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.createSocket(AbstractConnectProtocol.java:252) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     ... 59 common frames omitted
reporter-service  |
reporter-service  | 2022-02-12 22:23:24.425  WARN 1 --- [           main] o.h.e.j.e.i.JdbcEnvironmentInitiator     : HHH000342: Could not obtain connection to query metadata
reporter-service  |
reporter-service  | java.sql.SQLNonTransientConnectionException: Could not connect to address=(host=localhost)(port=3306)(type=master) : Socket fail to connect to host:localhost, port:3306. Connection refused (Connection refused)
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:197) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1394) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:635) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:150) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at org.mariadb.jdbc.Driver.connect(Driver.java:89) ~[mariadb-java-client-2.7.4.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-4.0.3.jar!/:na]
reporter-service  |     at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:181) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:175) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:173) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1460) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1494) ~[hibernate-core-5.6.4.Final.jar!/:5.6.4.Final]
reporter-service  |     at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.15.jar!/:5.3.15]
reporter-service  |     at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.6.3.jar!/:2.6.3]
reporter-service  |     at com.codesmith.reporterservice.ReporterServiceApplication.main(ReporterServiceApplication.java:10) ~[classes!/:na]
reporter-service  |     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
reporter-service  |     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
reporter-service  |     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
reporter-service  |     at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
reporter-service  |     at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  |     at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[reporter-service-0.0.1-SNAPSHOT.jar:na]
reporter-service  | Caused by: java.sql.SQLNonTransientConnectionException: Socket fail to connect to host:localhost, port:3306. Connection refused (Connection refused)
reporter-service  | 2022-02-12 22:23:25.256  WARN 1 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning

At this point I'm stuck. The error does not tell me anything specific and it is difficult to find a solution here. I have tried to use other drivers so far but from my point of view everything is configured correctly, isn't it? The error occurs when I start the docker-compose up.

Body:
Try adding a network and environments so that containers can communicate,

version: '3'

services:
  mysql-db:
    ...
    networks:
      - backend

  reporter-service:
    ...
    environment:
      spring.datasource.url: jdbc:mysql://mysql-db:3306/reporter-db
      spring.datasource.driver-class-name: org.mariadb.jdbc.Driver
      spring.datasource.username: root
      spring.datasource.password:

    networks:
      - backend

volumes:
  mysql-data:

networks:
  backend:

Note: spring.datasource.url must have MySQL docker service name as a host, which is, mysql-db in your case.


问:
How can I make HTTP request wait before continuing
I'm developing an extension for Google Chrome and I'm monitoring HTTP requests. In the event handler for chrome.webRequest.onHeadersReceived I'm trying to make a delay. It cannot wait asynchronously (unlike WebExtensions in Firefox) and it doesn't support something like Thread.Sleep or CriticalSection or ResetEvent or anything. The only solution that I see is spin waiting which is a very bad choice. Even synchronous XMLHTTPRequest is deprecated and doesn't work.

```<code>var headersReceived = function (e) {
    /// ?????? some method to delay synchronously
    return {cancel: false};
};

chrome.webRequest.onHeadersReceived.addListener(headersReceived,
                                                {urls: ["*://*/*"]},
                                                ["blocking", "responseHeaders"]);
</code>```

答:
You can try and reference to this plugin: network-spinner-devtool it is a browser devtools extension, with capacity of URL level configuration and control, to allow introducing delay before sending http request or after receiving response(support in firefox only).

it supports both Chrome and Firefox browser

Can install from Chrome web store as well Chrome DevTools

Body:
I'm developing an extension for Google Chrome and I'm monitoring HTTP requests. In the event handler for chrome.webRequest.onHeadersReceived I'm trying to make a delay. It cannot wait asynchronously (unlike WebExtensions in Firefox) and it doesn't support something like Thread.Sleep or CriticalSection or ResetEvent or anything. The only solution that I see is spin waiting which is a very bad choice. Even synchronous XMLHTTPRequest is deprecated and doesn't work.

var headersReceived = function (e) {
    /// ?????? some method to delay synchronously
    return {cancel: false};
};

chrome.webRequest.onHeadersReceived.addListener(headersReceived,
                                                {urls: ["*://*/*"]},
                                                ["blocking", "responseHeaders"]);


问:
My character's horizontal movement is stopping me from using rigidBody2D.AddForce(Vector2.right) or any horizontal axis
I keep trying to Addforce to the left or right but nothing happens. This happened to me in another game before. I just figured out what it was

```<code>rb.velocity = new Vector2(speed * moveX * Time.deltaTime, rb.velocity.y);
</code>```

Here, I'm setting the velocity to 0 if I'm not moving (moveX is Input.GetAxisRaw("Horizontal") )
How do I AddForce horizontally while not having to disable my normal movement? I know I can use transform.Translate but I'd prefer using rb.velocity for now.

答:
I have faced this several times but

if you are using AddForce what you can do is either make sure to add a good amount of speed value to it

```<code>rb.AddForce(inputMove.x * speed);
</code>```

if you are using Time.deltatime or don't use time at
all...something like:

```<code>rb.AddForce(inputMove.x * Time.deltatime * speed);
</code>```

Body:
I keep trying to Addforce to the left or right but nothing happens. This happened to me in another game before. I just figured out what it was

rb.velocity = new Vector2(speed * moveX * Time.deltaTime, rb.velocity.y);

Here, I'm setting the velocity to 0 if I'm not moving (moveX is Input.GetAxisRaw("Horizontal") )
How do I AddForce horizontally while not having to disable my normal movement? I know I can use transform.Translate but I'd prefer using rb.velocity for now.

Body:
I have faced this several times but

if you are using AddForce what you can do is either make sure to add a good amount of speed value to it

rb.AddForce(inputMove.x * speed);

if you are using Time.deltatime or don't use time at
all...something like:

rb.AddForce(inputMove.x * Time.deltatime * speed);


问:
Python: concat rows of two dataframes of different shapes
I have two dataframes:

```<code>df1 = pd.DataFrame(index = [0,1,2], columns=['USD', 'CAD'])
df1['USD'] = [1,2,3]
df1['CAD'] = [4,5,6]
df1:
    USD CAD
0   1   4
1   2   5
2   3   6

df2 = pd.DataFrame(index = [0,1], columns = ['currency','balance'])
df2['currency'] = ['USD', 'CAD']
df2['balance'] = [2,3]
df2:
    currency    balance
0   USD         2
1   CAD         3
</code>```

I would like to add a row to df1 at index 0, and fill that row with the balance of df2 based on currency. So the final df should look like this:

```<code>df:
    USD CAD
0   2   3
1   1   4
2   2   5
3   3   6
</code>```

How can I do this in a pythonic way? Thank you

答:
Try the following code:

df = pd.concat([df2.set_index('currency').T, df1], axis=0, ignore_index=True)
```

Body:
I have two dataframes:

df1 = pd.DataFrame(index = [0,1,2], columns=['USD', 'CAD'])
df1['USD'] = [1,2,3]
df1['CAD'] = [4,5,6]
df1:
    USD CAD
0   1   4
1   2   5
2   3   6

df2 = pd.DataFrame(index = [0,1], columns = ['currency','balance'])
df2['currency'] = ['USD', 'CAD']
df2['balance'] = [2,3]
df2:
    currency    balance
0   USD         2
1   CAD         3

I would like to add a row to df1 at index 0, and fill that row with the balance of df2 based on currency. So the final df should look like this:

df:
    USD CAD
0   2   3
1   1   4
2   2   5
3   3   6

How can I do this in a pythonic way? Thank you


问:
How to accept Querystring from URL into Angular route?
I need to accept this format of URL into my Angular app:

```<code>http://localhost:4200/approve/VA/28/20/0=2022-02-02&1=2022-02-03&2=2022-02-04
</code>```

My route path is this

```<code>path: 'approve/:vacation/:id/:vacationsLeft/:dates'
</code>```

Unfortunately when I visit the URL I get :

```<code>http://localhost:4200/approve/VA/28/20/0
</code>```

I am getting the URL from an email and I can't change the format of the query. Is there a way to pass it into Angular route?

答:
To follow-up on my comment, you can encode the dates URL parameters with something like this:

let vacactionCode = 'VA';
let vacationId = 28;
let vacationsLeft = 20;
let dates = encodeURIComponent("0=2022-02-02&1=2022-02-03&2=2022-02-04");

let url = `http://localhost:4200/approve/${vacactionCode}/${vacationId}/${vacationsLeft}?dates=${dates}`;
```

Then you would need to update your route, because :dates is no longer part of the path, it is now an optional parameter:

path: 'approve/:vacation/:id/:vacationsLeft

Body:
I need to accept this format of URL into my Angular app:

http://localhost:4200/approve/VA/28/20/0=2022-02-02&1=2022-02-03&2=2022-02-04

My route path is this

path: 'approve/:vacation/:id/:vacationsLeft/:dates'

Unfortunately when I visit the URL I get :

http://localhost:4200/approve/VA/28/20/0

I am getting the URL from an email and I can't change the format of the query. Is there a way to pass it into Angular route?

Body:
To follow-up on my comment, you can encode the dates URL parameters with something like this:

let vacactionCode = 'VA';
let vacationId = 28;
let vacationsLeft = 20;
let dates = encodeURIComponent("0=2022-02-02&1=2022-02-03&2=2022-02-04");

let url = `http://localhost:4200/approve/${vacactionCode}/${vacationId}/${vacationsLeft}?dates=${dates}`;

Then you would need to update your route, because :dates is no longer part of the path, it is now an optional parameter:

path: 'approve/:vacation/:id/:vacationsLeft


问:
Git changes are not pulled on to the local branch
I have branch named BDD-tests and have several commits on that branch.
One of the other developers pushed their changes on remote repo (on github) which changed a lot of the UI.

Now, I need to bring in the changes in my local branch (BDD-tests) and see the changes on my local app.

So, I went to the terminal and ran git pull, which is suppose to fetch the changes from the remote repo and merge it with my local branch?

I refreshed the local app, but I don't see any changes on the front end.

I went to the terminal and did 'git checkout master' and refreshed the web page (local app) and the UI changes from the other developer was there.

Am I missing something here?

I also, followed the following posts but still getting the same issue:
http://blog.mikepearce.net/2010/05/18/the-difference-between-git-pull-git-fetch-and-git-clone-and-git-rebase/

git pull from master into the development branch

I could perhaps switch to my local master and do a pull which would resolve the issue but I don't want to work on the local master (because it's always a good practice to branch out)

答: git pull  worked fine,all updated changes in  origin/master got updated


问:
How to get row data based on the other table row data?
I'm not sure if I write my questions title correctly, but my example would probably explain it better.

Join table_1 and table_2 and get table_1 row, if there is no is_validated= 1.
The query will get table_1, id 1 and 3, because they dont have is_validated = 1

table_1

```<code>id
1
2
3
</code>```

table_2

```<code>id      table_1_id    is_validated
1       1             0
2       2             1
3       2             0
4       3             0
5       3             0
</code>```

expected result

```<code>id
1
3
</code>```

I've try to use this query, but it doesn't get the result that I want.

```<code>SELECT * FROM table_1 t1
JOIN table_2 t2 ON t1.id=t2.table_1_id AND t2.is_validated = 0
GROUP BY t2.table_1_id
</code>```

答:
Exists logic works nicely here:

SELECT t1.id
FROM table_1 t1
WHERE NOT EXISTS (SELECT 1 FROM table_2 t2
                  WHERE t2.table_1_id = t1.id AND t2.is_validated = 1);
```

Body:
I'm not sure if I write my questions title correctly, but my example would probably explain it better.

Join table_1 and table_2 and get table_1 row, if there is no is_validated= 1.
The query will get table_1, id 1 and 3, because they dont have is_validated = 1

table_1

id
1
2
3

table_2

id      table_1_id    is_validated
1       1             0
2       2             1
3       2             0
4       3             0
5       3             0

expected result

id
1
3

I've try to use this query, but it doesn't get the result that I want.

SELECT * FROM table_1 t1
JOIN table_2 t2 ON t1.id=t2.table_1_id AND t2.is_validated = 0
GROUP BY t2.table_1_id


问:
How to filter objects based on given condition in JavaScript?
I'm new to this community and just started programming I couldn't find anything about this topic can anyone please solve this.
I need to filter names who's each points in array above 75.
i have tried this and unable iterate over an array.

const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}]

const arrayOfSelecetedCandidates=[]
  for(let object of candidatesList){
      if (candidatesList.every(candidatesList.points>75)){
         arrayOfSelecetedCandidates.push(candidatesList.name)
      }
  }
  console.log(arrayOfSelecetedCandidates);```

答:
Maybe you want this?

const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}]

const arrayOfSelecetedCandidates=[]
  for(let object of candidatesList){
      if (object.points.every(i=>i>75))
         arrayOfSelecetedCandidates.push(object.name)
  }
  console.log(arrayOfSelecetedCandidates);```
</div>
</div>
</p>
<p>But as @Dai pointed out filter is always better if you want to test an array and return item that pass the test:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}]

const arrayOfSelecetedCandidates=candidatesList.filter(i=>i.points.every(y=>y>75))
console.log(arrayOfSelecetedCandidates)</code>```

Body:
Maybe you want this?

const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}]

const arrayOfSelecetedCandidates=[]
  for(let object of candidatesList){
      if (object.points.every(i=>i>75))
         arrayOfSelecetedCandidates.push(object.name)
  }
  console.log(arrayOfSelecetedCandidates);

But as @Dai pointed out filter is always better if you want to test an array and return item that pass the test:

const candidatesList = [{'name':'Blake Hodges', 'points':[76,98,88,84]},{'name':'James Anderson', 'points':[0,98,12,13]}]

const arrayOfSelecetedCandidates=candidatesList.filter(i=>i.points.every(y=>y>75))
console.log(arrayOfSelecetedCandidates)