问:
How to display SUM of Revenue and SUM of Target together in Descending order where Revenue column and Target column belongs to 2 different table?
Table  [Revenue Raw Data] has the following columns:

Table [Targets Raw Data] has the following columns:

Table yt_Calendar_lookup has the following columns:

Now the question is:

Which account number is performing the best in terms of Revenue versus Target in the Fiscal Year 2021?

Initially this is what I have tried:

```<code>SELECT [Revenue Raw Data].Account_No,
[Total Revenue in 2021],
[Total Target in 2021]
FROM
(SELECT Account_No, SUM(Revenue) AS 'Total Revenue in 2021'
FROM [Revenue Raw Data]
 WHERE Account_No IN
(SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup WHERE
 Fiscal_Year = 'FY21')
 GROUP BY Account_No) [Revenue Raw Data]
 INNER JOIN
(SELECT Account_No,
 SUM(Target) AS 'Total Target in 2021'
  FROM [Targets Raw Data]
 WHERE Account_No IN
(SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup
 WHERE Fiscal_Year = 'FY21')
 GROUP BY Account_No) [Targets Raw Data]
 ON [Revenue Raw Data].Account_No = [Targets Raw Data].Account_No
</code>```

And I got the following result:

With the next query, I was trying to display the same result but this time I want to display both SUM of Revenue and SUM of Target in Descending Order.

And this is what I have tried:

```<code>SELECT [Revenue Raw Data].Account_No,
[Total Revenue in 2021],
[Total Target in 2021]
FROM
(SELECT Account_No,
 SUM(Revenue) AS 'Total Revenue in 2021'
 FROM [Revenue Raw Data]
 WHERE Account_No IN
 (SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup
 WHERE Fiscal_Year = 'FY21')
 GROUP BY Account_No
 ORDER BY SUM(Revenue) DESC
 )
 [Revenue Raw Data]
 INNER JOIN
(SELECT Account_No,
 SUM(Target) AS 'Total Target in 2021'
 FROM [Targets Raw Data]
 WHERE Account_No IN
 (SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup
 WHERE Fiscal_Year = 'FY21')
 GROUP BY Account_No
 ORDER BY SUM(Target) DESC)
 [Targets Raw Data]
 ON [Revenue Raw Data].Account_No
  = [Targets Raw Data].Account_No
</code>```

And I received the following error message:

I even tried adding ORDER BY SUM(Revenue) DESC and ORDER BY SUM(Target) DESC outside the Subquery, and still it is showing error.

How can this issue be solved ?

答:
A couple of things to think about here:

You can't put ORDER BY in a sub-query. Order by is used once at the end of a query

Even if you could, that doesn't make sense when you're using the sub-query as the values list for an IN predicate

Generally I would advise against using sub-queries as the value list for an IN predicate. I believe you'll get better performance if you achieve the same filtering using an INNER JOIN

Sorting two independent measurements of the same (single) grouping variable descending at the same time doesn't make sense - the max value for one measurement might be account 1, but account 1 might not have the max value for the other measurement. What then?

If you are joining on account_no throughout, you don't need to apply the FY21 filter twice

In fact, I think your query can be simplified along these lines:

```<code>SELECT  raw.Account_No,
        SUM(raw.Revenue) AS 'Total Revenue in 2021',
        target.[Total Target in 2021]
 FROM [Revenue Raw Data] raw
      INNER JOIN (SELECT Account_No, SUM(Target) AS 'Total Target in 2021'
                  FROM [Targets Raw Data]
                  GROUP BY account_no) target ON raw.account_no = target.account_no
      INNER JOIN (SELECT DISTINCT Account_No
                  FROM yt_Calendar_lookup
                  WHERE Fiscal_Year = 'FY21') fltr ON raw.account_no = fltr.account_no
GROUP BY raw.account_no
ORDER BY SUM(raw.revenue);
</code>```

Again, when you only have one row per account ID, you either sort by one measure or the other. Sorting by both will be the same as sorting by the first one listed. Unless you expect multiple accounts with the same value in the first sort key, but different values int he second sort key. In which case:

```<code>ORDER BY SUM(raw.revenue), target.[Total Target in 2021];
</code>```

Body:
Table  [Revenue Raw Data] has the following columns:

Table [Targets Raw Data] has the following columns:

Table yt_Calendar_lookup has the following columns:

Now the question is:

Which account number is performing the best in terms of Revenue versus Target in the Fiscal Year 2021?

Initially this is what I have tried:

SELECT [Revenue Raw Data].Account_No,
[Total Revenue in 2021],
[Total Target in 2021]
FROM
(SELECT Account_No, SUM(Revenue) AS 'Total Revenue in 2021'
FROM [Revenue Raw Data]
 WHERE Account_No IN
(SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup WHERE
 Fiscal_Year = 'FY21')
 GROUP BY Account_No) [Revenue Raw Data]
 INNER JOIN
(SELECT Account_No,
 SUM(Target) AS 'Total Target in 2021'
  FROM [Targets Raw Data]
 WHERE Account_No IN
(SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup
 WHERE Fiscal_Year = 'FY21')
 GROUP BY Account_No) [Targets Raw Data]
 ON [Revenue Raw Data].Account_No = [Targets Raw Data].Account_No

And I got the following result:

With the next query, I was trying to display the same result but this time I want to display both SUM of Revenue and SUM of Target in Descending Order.

And this is what I have tried:

SELECT [Revenue Raw Data].Account_No,
[Total Revenue in 2021],
[Total Target in 2021]
FROM
(SELECT Account_No,
 SUM(Revenue) AS 'Total Revenue in 2021'
 FROM [Revenue Raw Data]
 WHERE Account_No IN
 (SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup
 WHERE Fiscal_Year = 'FY21')
 GROUP BY Account_No
 ORDER BY SUM(Revenue) DESC
 )
 [Revenue Raw Data]
 INNER JOIN
(SELECT Account_No,
 SUM(Target) AS 'Total Target in 2021'
 FROM [Targets Raw Data]
 WHERE Account_No IN
 (SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup
 WHERE Fiscal_Year = 'FY21')
 GROUP BY Account_No
 ORDER BY SUM(Target) DESC)
 [Targets Raw Data]
 ON [Revenue Raw Data].Account_No
  = [Targets Raw Data].Account_No

And I received the following error message:

I even tried adding ORDER BY SUM(Revenue) DESC and ORDER BY SUM(Target) DESC outside the Subquery, and still it is showing error.

How can this issue be solved ?

Body:
A couple of things to think about here:

You can't put ORDER BY in a sub-query. Order by is used once at the end of a query

Even if you could, that doesn't make sense when you're using the sub-query as the values list for an IN predicate

Generally I would advise against using sub-queries as the value list for an IN predicate. I believe you'll get better performance if you achieve the same filtering using an INNER JOIN

Sorting two independent measurements of the same (single) grouping variable descending at the same time doesn't make sense - the max value for one measurement might be account 1, but account 1 might not have the max value for the other measurement. What then?

If you are joining on account_no throughout, you don't need to apply the FY21 filter twice

In fact, I think your query can be simplified along these lines:

SELECT  raw.Account_No,
        SUM(raw.Revenue) AS 'Total Revenue in 2021',
        target.[Total Target in 2021]
 FROM [Revenue Raw Data] raw
      INNER JOIN (SELECT Account_No, SUM(Target) AS 'Total Target in 2021'
                  FROM [Targets Raw Data]
                  GROUP BY account_no) target ON raw.account_no = target.account_no
      INNER JOIN (SELECT DISTINCT Account_No
                  FROM yt_Calendar_lookup
                  WHERE Fiscal_Year = 'FY21') fltr ON raw.account_no = fltr.account_no
GROUP BY raw.account_no
ORDER BY SUM(raw.revenue);

Again, when you only have one row per account ID, you either sort by one measure or the other. Sorting by both will be the same as sorting by the first one listed. Unless you expect multiple accounts with the same value in the first sort key, but different values int he second sort key. In which case:

ORDER BY SUM(raw.revenue), target.[Total Target in 2021];


来源: stackexchange

问:
NoReverseMatch Django using pk
Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['basic_app/update/(?P[0-9]+)/\Z']

```<code>9     <p>Location: {{school_detail.location}} </p>
10    <h3>Students:</h3>
11    {% for student in school_detail.students.all %}
12    <p>{{student.name}} who is {{student.age}} years old</p>
13    {% endfor %}
14
15
16  </div>
17
18  <div class="container">
19  <p><a class='btn btn-warning' href="{% url 'basic_app:update' pk=school_details.pk %}">Update</a></p>
20
21  </div>
22  {% endblock %}
</code>```

Here is urls.py

```<code>from django.urls import path
from basic_app import views
app_name='basic_app'

urlpatterns = [
    path('',views.SchoolListView.as_view(),name='list'),
    path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail'),
    path('create/',views.SchoolCreateView.as_view(),name='create'),
    path('update/<int:pk>/',views.SchoolUpdateView.as_view(),name='update'),
    ]
</code>```

答:
Typo:

```<code>{% url 'basic_app:update' pk=school_details.pk %}
</code>```

Should be:

```<code>{% url 'basic_app:update' pk=school_detail.pk %}
</code>```

ContentLicense: CC BY-SA 4.0

Title: NoReverseMatch Django using pk

Body:
Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['basic_app/update/(?P[0-9]+)/\Z']

9
Location: {{school_detail.location}}

10
Students:

11    {% for student in school_detail.students.all %}
12
{{student.name}} who is {{student.age}} years old

13    {% endfor %}
14
15
16

17
18

19
Update

20
21

22  {% endblock %}

Here is urls.py

from django.urls import path
from basic_app import views
app_name='basic_app'

urlpatterns = [
    path('',views.SchoolListView.as_view(),name='list'),
    path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail'),
    path('create/',views.SchoolCreateView.as_view(),name='create'),
    path('update/<int:pk>/',views.SchoolUpdateView.as_view(),name='update'),
    ]

Body:
Typo:

{% url 'basic_app:update' pk=school_details.pk %}

Should be:

{% url 'basic_app:update' pk=school_detail.pk %}


问:
Why does python print memory location rather than class.name in some cases but not others in my code?
My code has a mathematical function that iterates over a list of county class objects and returns the county with the max voter turnout along with that turnout in a tuple.

Code here:

```<code>class County:
  def __init__(self, init_name, init_population, init_voters):
    self.name = init_name
    self.population = init_population
    self.voters = init_voters

def highest_turnout(data) :
  max_turnout_county = data[0]
  max_turnout = (data[0].voters / data[0].population)
  for i in range(0,6):
    if (data[i].voters / data[i].population) > max_turnout:
      max_turnout_county = data[i].name
      max_turnout = (data[i].voters / data[i].population)

  return (max_turnout_county, max_turnout)

allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]

result = highest_turnout(data)
print(result) # prints the output of the function
</code>```

In its current state, it will return the desired output.
('chester', 0.7215045058280377)

However, if I change the county with the highest output, for example, if I change Allegheny voters from 645469 to 1000480 so that Allegheny is now the max turnout county the output will no longer return the county name in the tuple as expected, but rather the memory location.

Output here:
(<submission.County object at 0x7f8e37d3cc18>, 0.9999900048976001)

Why is my code outputting memory location in the second case but not the first case and how would I fix this?

答:
There is bug in your code.
In first line, you are assigning whole County object to the max_county_variable

max_turnout_county = data[0]
```
<p>later, you are assigning only the attribute name:</p>
<pre class="lang-python prettyprint-override"><code> max_turnout_county = data[i].name
</code>```

To fix, you can just change first line to:

max_turnout_county = data[0].name
```

Body:
My code has a mathematical function that iterates over a list of county class objects and returns the county with the max voter turnout along with that turnout in a tuple.

Code here:

class County:
  def __init__(self, init_name, init_population, init_voters):
    self.name = init_name
    self.population = init_population
    self.voters = init_voters

def highest_turnout(data) :
  max_turnout_county = data[0]
  max_turnout = (data[0].voters / data[0].population)
  for i in range(0,6):
    if (data[i].voters / data[i].population) > max_turnout:
      max_turnout_county = data[i].name
      max_turnout = (data[i].voters / data[i].population)

  return (max_turnout_county, max_turnout)

allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]

result = highest_turnout(data)
print(result) # prints the output of the function

In its current state, it will return the desired output.
('chester', 0.7215045058280377)

However, if I change the county with the highest output, for example, if I change Allegheny voters from 645469 to 1000480 so that Allegheny is now the max turnout county the output will no longer return the county name in the tuple as expected, but rather the memory location.

Output here:
(<submission.County object at 0x7f8e37d3cc18>, 0.9999900048976001)

Why is my code outputting memory location in the second case but not the first case and how would I fix this?

Body:
There is bug in your code.
In first line, you are assigning whole County object to the max_county_variable

max_turnout_county = data[0]

later, you are assigning only the attribute name:

 max_turnout_county = data[i].name

To fix, you can just change first line to:

max_turnout_county = data[0].name


问:
How can i convert NSString to uint8_t array
I have an NSString like so: 850210

How can i convert it to uint8_t data[]={0x85,0x02,0x10};

Could someone please help me out with this??

BR,
Suppi

答:
Loop over the string and start by checking for strings of length < 3. If it is just simply call intValue on the NSString itself and you have your first and only byte.

If it's larger than or equal to three start by reading in three numbers and checking if that is larger than 255. If it is re-read in the two bytes and check what value they have and that's a byte. If it's not then take the three first numbers and that's a byte.

Repeat this process on the remaining string that you have (a string created by disregarding the numbers you have already read in).

Good luck :)

I was assuming that string was in decimal format. If that's hex then simply read in two numbers at a time. And use this question to help you: How can I convert hex number to integers and strings in Objective C?

Second edit:

I have not tested this but you if there are any errors they should be easy to fix:

```<code>NSString *hexString = @"8510A0";
uint8_t *result = (uint8_t *)malloc(sizeof(uint8_t) * ([hexString length] / 2));
for(int i = 0; i < [hexString length]; i += 2) {
    NSRange range = { i, 2 };
    NSString *subString = [hexString subStringWithRange:range];
    unsigned value;
    [[NSScanner scannerWithString:subString] scanHexInt:&value];
    result[i / 2] = (uint8_t)value;
}
// result now contains what you want
free(result)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Loop over the string and start by checking for strings of length < 3. If it is just simply call intValue on the NSString itself and you have your first and only byte.

If it's larger than or equal to three start by reading in three numbers and checking if that is larger than 255. If it is re-read in the two bytes and check what value they have and that's a byte. If it's not then take the three first numbers and that's a byte.

Repeat this process on the remaining string that you have (a string created by disregarding the numbers you have already read in).

Good luck :)

I was assuming that string was in decimal format. If that's hex then simply read in two numbers at a time. And use this question to help you: How can I convert hex number to integers and strings in Objective C?

Second edit:

I have not tested this but you if there are any errors they should be easy to fix:

NSString *hexString = @"8510A0";
uint8_t *result = (uint8_t *)malloc(sizeof(uint8_t) * ([hexString length] / 2));
for(int i = 0; i < [hexString length]; i += 2) {
    NSRange range = { i, 2 };
    NSString *subString = [hexString subStringWithRange:range];
    unsigned value;
    [[NSScanner scannerWithString:subString] scanHexInt:&value];
    result[i / 2] = (uint8_t)value;
}
// result now contains what you want
free(result)


问:
React: how to use onclick function in a loop in class component?
what i want is to run an onClick event handler in a loop.
what i have done is :

my component looks something like this.

```<code>import React, { Component } from "react";
import Link from 'next/link';

class VehicleSpecifications extends Component {

constructor(props) {
super(props);
this.setActiveClass = this.setActiveClass.bind(this)

this.state = {
    tabStatus: "",
};
}

setActiveClass = (e) => {
  console.log(e)
}

render() {
const vehicleSpecs = this.props.vehicleSpecs;
console.log(this.props.vehicleSpecs)
return (
  <React.Fragment>
    <div className="vertical-tabs" >
      <ul className="nav nav-tabs" role="tablist">
        {
          Object.entries(vehicleSpecs).map(function (items, car_index) {
            let typeAndName = items[0].split(':-:');
            return (
              <li className="nav-item"   onClick={ ()=> setActiveClass("#pag") }>
                <Link
                  className="nav-link active"
                  data-toggle="tab"
                  href={"#pag" + car_index}
                  role="tab"
                  aria-controls="performance">
                  {typeAndName[0].replace('_', ' ').toUpperCase()}

                </Link>
              </li>
            )
          })
        }
      </ul>

    </div>
  </React.Fragment>
);
}
}
</code>```

export default VehicleSpecifications;

i have tried things but this onclick function sometime gives _this is undefined or says function is undefined.

答:
Here check this out I created a simple example for you.

since you are using the arrow function inside onClick you don't need to do the binding inside the constructor;

Check the example code below,

or open this codesandbox link to see it live

```<code>import { Component } from "react";

const seed = ["Matt", "Jake", "Ross", "Michale"];

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tab: ""
    };
  }

  // setSomeState = (label) => {
  //   console.log(label);
  //   this.setState({ tab: label });
  // };

  // Doesn't matter what type of this function is

  setSomeState(label) {
    console.log(label);
    this.setState({ tab: label });
  }

  render() {
    const { tab } = this.state;
    return (
      <div style={{ fontFamily: "sans-serif", textAlign: "center" }}>
        <h1>{tab ? tab : "No Value Selected"}</h1>
        {seed.map((label, index) => (
          <h2
            key={`${label} ${index}`}
            onClick={() => this.setSomeState(label)}
            style={{
              background: "#efefef",
              padding: "20px",
              cursor: "pointer"
            }}
          >
            {label}
          </h2>
        ))}
      </div>
    );
  }
}

export default App;
</code>```

Body:
what i want is to run an onClick event handler in a loop.
what i have done is :

my component looks something like this.

import React, { Component } from "react";
import Link from 'next/link';

class VehicleSpecifications extends Component {

constructor(props) {
super(props);
this.setActiveClass = this.setActiveClass.bind(this)

this.state = {
    tabStatus: "",
};
}

setActiveClass = (e) => {
  console.log(e)
}

render() {
const vehicleSpecs = this.props.vehicleSpecs;
console.log(this.props.vehicleSpecs)
return (
  <React.Fragment>

        {
          Object.entries(vehicleSpecs).map(function (items, car_index) {
            let typeAndName = items[0].split(':-:');
            return (

 setActiveClass("#pag") }>
                <Link
                  className="nav-link active"
                  data-toggle="tab"
                  href={"#pag" + car_index}
                  role="tab"
                  aria-controls="performance">
                  {typeAndName[0].replace('_', ' ').toUpperCase()}

                </Link>

            )
          })
        }

  </React.Fragment>
);
}
}

export default VehicleSpecifications;

i have tried things but this onclick function sometime gives _this is undefined or says function is undefined.

Body:
Here check this out I created a simple example for you.

since you are using the arrow function inside onClick you don't need to do the binding inside the constructor;

Check the example code below,

or open this codesandbox link to see it live

import { Component } from "react";

const seed = ["Matt", "Jake", "Ross", "Michale"];

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tab: ""
    };
  }

  // setSomeState = (label) => {
  //   console.log(label);
  //   this.setState({ tab: label });
  // };

  // Doesn't matter what type of this function is

  setSomeState(label) {
    console.log(label);
    this.setState({ tab: label });
  }

  render() {
    const { tab } = this.state;
    return (
      <div style={{ fontFamily: "sans-serif", textAlign: "center" }}>
        <h1>{tab ? tab : "No Value Selected"}</h1>
        {seed.map((label, index) => (
          <h2
            key={`${label} ${index}`}
            onClick={() => this.setSomeState(label)}
            style={{
              background: "#efefef",
              padding: "20px",
              cursor: "pointer"
            }}
          >
            {label}
          </h2>
        ))}
      </div>
    );
  }
}

export default App;


答:
You initialize max_turnout_county with an instance of County from the argument:

```<code>max_turnout_county = data[0]
</code>```

That should be initialized to the name of the county:

```<code>max_turnout_county = data[0].name
</code>```

Alternatively, you can add a turnout property to your County class:

```<code>class County :
  def __init__(self, init_name, init_population, init_voters):
    self.name = init_name
    self.population = init_population
    self.voters = init_voters

  @property
  def turnout(self):
     return self.voters / self.population
</code>```

which simplifies your function greatly:

```<code>def highest_turnout(data) :
  return max(data, key=lambda c: c.turnout)
  # Or, if you really want to return a tuple instead of
  # an instance of County,
  # c = max(data, key=lambda c: c.turnout)
  # return (c.name, c.turnout)

</code>```

Title: Why does python print memory location rather than class.name in some cases but not others in my code?

Body:
You initialize max_turnout_county with an instance of County from the argument:

max_turnout_county = data[0]

That should be initialized to the name of the county:

max_turnout_county = data[0].name

Alternatively, you can add a turnout property to your County class:

class County :
  def __init__(self, init_name, init_population, init_voters):
    self.name = init_name
    self.population = init_population
    self.voters = init_voters

  @property
  def turnout(self):
     return self.voters / self.population

which simplifies your function greatly:

def highest_turnout(data) :
  return max(data, key=lambda c: c.turnout)
  # Or, if you really want to return a tuple instead of
  # an instance of County,
  # c = max(data, key=lambda c: c.turnout)
  # return (c.name, c.turnout)


问:
Long press a custom physical button on android device with appium java
I have a an custom-made phone in which it has a specific SOS button that I need to long press.

I am trying to do key press like this.

```<code>   driver.longPressKey(new KeyEvent( AndroidKey.HOME) );
</code>```

which is working but Custom key code 287. How do I send that? I tried something like this

```<code>driver.longPressKey(new KeyEvent( AndroidKey.valueOf("287")) );
</code>```

but this gives an enum error

Version: java-client: 7.5.1

答:
Error Reason

AndroidKey is Enum and valueOf method works like:

```<code>AndroidKey.valueOf("HOME");
</code>```

while the HOME is defined in Enum.

```<code>public enum AndroidKey {
    UNKNOWN(0),
    ...
    HOME(3),
    ...
</code>```

Press Custom Key Code

Key Code 287 is not present in AndroidKey Enum.

But KeyEvent constructor requires it.

For this case I suggest to make a custom KeyEvent child class.

```<code>import com.google.common.collect.ImmutableMap
import io.appium.java_client.android.nativekey.KeyEvent

import static java.util.Optional.ofNullable

class MyKeyEvent extends KeyEvent {

    private int keyCode;

    public MyKeyEvent(int keyCode) {
        this.keyCode = keyCode;
    }

    @Override
    public Map<String, Object> build() {
        final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
        final int keyCode = ofNullable(this.keyCode)
                .orElseThrow(() -> new IllegalStateException("The key code must be set"));
        builder.put("keycode", keyCode);
        return builder.build();
    }
}
</code>```

and for the long press:

```<code>driver.longPressKey(new MyKeyEvent(287));
</code>```

Disclaimer

As I see this might work (since the Appium command executor will get the valid structure for long-press command), but I haven't the ability to run this code on some device or emulator. And I don't know the driver behavior once it'll try to execute some unknown key code.

So, let me know if it doesn't work, and I'll try to improve/fix.

Body:
I have a an custom-made phone in which it has a specific SOS button that I need to long press.

I am trying to do key press like this.

   driver.longPressKey(new KeyEvent( AndroidKey.HOME) );

which is working but Custom key code 287. How do I send that? I tried something like this

driver.longPressKey(new KeyEvent( AndroidKey.valueOf("287")) );

but this gives an enum error

Version: java-client: 7.5.1

Body:
Error Reason

AndroidKey is Enum and valueOf method works like:

AndroidKey.valueOf("HOME");

while the HOME is defined in Enum.

public enum AndroidKey {
    UNKNOWN(0),
    ...
    HOME(3),
    ...

Press Custom Key Code

Key Code 287 is not present in AndroidKey Enum.

But KeyEvent constructor requires it.

For this case I suggest to make a custom KeyEvent child class.

import com.google.common.collect.ImmutableMap
import io.appium.java_client.android.nativekey.KeyEvent

import static java.util.Optional.ofNullable

class MyKeyEvent extends KeyEvent {

    private int keyCode;

    public MyKeyEvent(int keyCode) {
        this.keyCode = keyCode;
    }

    @Override
    public Map<String, Object> build() {
        final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
        final int keyCode = ofNullable(this.keyCode)
                .orElseThrow(() -> new IllegalStateException("The key code must be set"));
        builder.put("keycode", keyCode);
        return builder.build();
    }
}

and for the long press:

driver.longPressKey(new MyKeyEvent(287));

Disclaimer

As I see this might work (since the Appium command executor will get the valid structure for long-press command), but I haven't the ability to run this code on some device or emulator. And I don't know the driver behavior once it'll try to execute some unknown key code.

So, let me know if it doesn't work, and I'll try to improve/fix.


问:
Why does if($x = 1 && $x == 1) throw error but if ($x == 1 && $x = 2) doesn't in php?
In php the following code gives a warning of undefined variable $x:

if($x = 1 && $x == 1)

I thought it was equivalent to if( ($x = 1) && ($x == 1) ), but that's not the case. I've been told, it's because && has higher precedence than =, which causes the expression to get converted to:

if($x = (1 && ($x == 1)))

So far so good, but now consider:

$x=1; if($x == 1 && $x = 2)

This doesn't throw error. Why doesn't it get converted to:

$x=1; if(  (($x == 1) && $x) = 2  )

I've been told thats due to = being right assosiative, but https://www.php.net/manual/en/language.operators.precedence.php says When operators have equal precedence their associativity decides how the operators are grouped.. Here we have =, && and == all being of different precedence.

P.S; My actual code is if($result != false && $res = $stmt->get_result()), which has been copied from some other reputable source, so seems like not using unneeded parenthesis is common in php.

答:
I've played with several conditions and below is what I've got.

First, let's consider that we init $x before if statements to avoid undefined variable notice.

Second, let's confirm the precedence for operators:

== is applied 1st

&& is applied 2nd

= is applied 3rd

This returns true:

```<code>$x = 1;
if ($x = 1 && $x == 1) {
    echo 'true';
} else {
    echo 'false';
}
</code>```

It goes like ($x = (1 && ($x == 1))) -> ($x = (1 && true)) -> ($x = true) -> true.

If we compare $x to another value than the assigned one we will get false:

```<code>$x = 1;
if ($x = 2 && $x == 2) {
    echo 'true';
} else {
    echo 'false';
}
</code>```

It goes like ($x = (2 && ($x == 2))) -> ($x = (2 && false)) -> ($x = false) -> false.

The last one returns true:

```<code>$x = 1;
if ($x == 1 && $x = 2) {
    echo 'true';
} else {
    echo 'false';
}
</code>```

It goes like ((($x == 1) && $x) = 2) -> ((true && $x) = 2) -> (true = 2) -> true.

The last comparison can't be interpreted by PHP so it's an approximate view.

It looks like the last action (true = 2) totally depends on the left operand. If we put $x = 2; we will get (false = 2) -> false.

I'm not sure about the last one and here is the only place were some mistakes can happen.

Otherwise, it looks like precedence works as expected.

Anyway, I always put parenthesis for an assignment action inside if operator (especially inside ternary if) to be sure that I will get what I expect.
I don't think this affects performance or readability too much, but it may prevent some logical errors.

UPDATE:

Concering your code if($result != false && $res = $stmt->get_result()) it's not correct to compare it to if($x == 1 && $x = 2) because in your code are two different variables.

In this case logical operator will not call the second part at all if the fisrt one is false, see the 1st example here

UPDATE-2:

After the discussion under this answer we can see that the last conditions ($x == 1 && $x = 2) work like like (($x == 1) && ($x = 2)) -> ((1 == 1) && 2) -> true and $x becomes 2 after it.

Body:
I've played with several conditions and below is what I've got.

First, let's consider that we init $x before if statements to avoid undefined variable notice.

Second, let's confirm the precedence for operators:

== is applied 1st

&& is applied 2nd

= is applied 3rd

This returns true:

$x = 1;
if ($x = 1 && $x == 1) {
    echo 'true';
} else {
    echo 'false';
}

It goes like ($x = (1 && ($x == 1))) -> ($x = (1 && true)) -> ($x = true) -> true.

If we compare $x to another value than the assigned one we will get false:

$x = 1;
if ($x = 2 && $x == 2) {
    echo 'true';
} else {
    echo 'false';
}

It goes like ($x = (2 && ($x == 2))) -> ($x = (2 && false)) -> ($x = false) -> false.

The last one returns true:

$x = 1;
if ($x == 1 && $x = 2) {
    echo 'true';
} else {
    echo 'false';
}

It goes like ((($x == 1) && $x) = 2) -> ((true && $x) = 2) -> (true = 2) -> true.

The last comparison can't be interpreted by PHP so it's an approximate view.

It looks like the last action (true = 2) totally depends on the left operand. If we put $x = 2; we will get (false = 2) -> false.

I'm not sure about the last one and here is the only place were some mistakes can happen.

Otherwise, it looks like precedence works as expected.

Anyway, I always put parenthesis for an assignment action inside if operator (especially inside ternary if) to be sure that I will get what I expect.
I don't think this affects performance or readability too much, but it may prevent some logical errors.

UPDATE:

Concering your code if($result != false && $res = $stmt->get_result()) it's not correct to compare it to if($x == 1 && $x = 2) because in your code are two different variables.

In this case logical operator will not call the second part at all if the fisrt one is false, see the 1st example here

UPDATE-2:

After the discussion under this answer we can see that the last conditions ($x == 1 && $x = 2) work like like (($x == 1) && ($x = 2)) -> ((1 == 1) && 2) -> true and $x becomes 2 after it.


问:
Create Virtual Environment with native Python (w/out Conda_
Goal: create Python 3.8.8 venv.

I've Python 3.8.10 installed

Poetry project is Python 3.8.8

don't have conda

I tried installing suggested package for creating a venv but this didn't work.

How can I create a Python 3.8.8 venv without conda?

Terminal:

@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/foo/bar$ poetry install
The currently activated Python version 3.8.10 is not supported by the project (3.8.8).
Trying to find and use a compatible version.

  NoCompatiblePythonVersionFound

  Poetry was unable to find a compatible version. If you have one, you can explicitly use it via the "env use" command.

  at ~/.poetry/lib/poetry/utils/env.py:768 in create_venv
       764│                     python_minor = ".".join(python_patch.split(".")[:2])
       765│                     break
       766│
       767│             if not executable:
    →  768│                 raise NoCompatiblePythonVersionFound(
       769│                     self._poetry.package.python_versions
       770│                 )
       771│
       772│         if root_venv:
me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/foo/bar$ conda create -n sdg python=3.8.8
conda: command not found
me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/foo/bar$ python3 -m venv sdg python=3.8
The virtual environment was not created successfully because ensurepip is not
available.  On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.

    apt install python3.8-venv

You may need to use sudo with that command.  After installing the python3-venv
package, recreate your virtual environment.

Failing command: ['/mnt/c/Users/me/Documents/GitHub/foo/bar/sdg/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']

me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/foo/bar$ apt install python3.8-venv
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/foo/bar$ sudo apt install python3.8-venv
[sudo] password for me:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  python3.8-venv
0 upgraded, 1 newly installed, 0 to remove and 68 not upgraded.
Need to get 5452 B of archives.
After this operation, 27.6 kB of additional disk space will be used.
Ign:1 http://archive.ubuntu.com/ubuntu focal-updates/universe amd64 python3.8-venv amd64 3.8.10-0ubuntu1~20.04.1
Err:1 http://security.ubuntu.com/ubuntu focal-updates/universe amd64 python3.8-venv amd64 3.8.10-0ubuntu1~20.04.1
  404  Not Found [IP: 91.189.88.142 80]
E: Failed to fetch http://security.ubuntu.com/ubuntu/pool/universe/p/python3.8/python3.8-venv_3.8.10-0ubuntu1~20.04.1_amd64.deb  404  Not Found [IP: 91.189.88.142 80]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?
me@PF2DCSXD:/mnt/c/Users/me/Documents/GitHub/foo/bar$ virtualenv --python=python3.8.8 sdg
RuntimeError: failed to find interpreter for Builtin discover of python_spec='python3.8.8'
```

答:
See one of the links below:

https://python-guide-cn.readthedocs.io/en/latest/dev/virtualenvs.html
or
https://virtualenv.pypa.io/en/latest/installation.html

But I strongly recommend to use conda for create and manage venv


答:
Does this work?
I think the ORDER BY should be outside of the subquery, so it's the output of the main SELECT you're ordering. Ie no ORDER within brackets, but ORDER BY [Total Revenue in 2021] DESC, [Total Target in 2021] at the end</p>
```<code>SELECT [Revenue Raw Data].Account_No,
[Total Revenue in 2021],
[Total Target in 2021]
FROM
(SELECT Account_No,
 SUM(Revenue) AS 'Total Revenue in 2021'
 FROM [Revenue Raw Data]
 WHERE Account_No IN
 (SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup
 WHERE Fiscal_Year = 'FY21')
 GROUP BY Account_No
  )
 [Revenue Raw Data]
 INNER JOIN
(SELECT Account_No,
 SUM(Target) AS 'Total Target in 2021'
 FROM [Targets Raw Data]
 WHERE Account_No IN
 (SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup
 WHERE Fiscal_Year = 'FY21')
 GROUP BY Account_No
 )
 [Targets Raw Data]
 ON [Revenue Raw Data].Account_No
  = [Targets Raw Data].Account_No

ORDER BY [Total Revenue in 2021] DESC, [Total Target in 2021]
</code>```

Title: How to display SUM of Revenue and SUM of Target together in Descending order where Revenue column and Target column belongs to 2 different table?

Body:
Does this work?
I think the ORDER BY should be outside of the subquery, so it's the output of the main SELECT you're ordering. Ie no ORDER within brackets, but ORDER BY [Total Revenue in 2021] DESC, [Total Target in 2021] at the end

SELECT [Revenue Raw Data].Account_No,
[Total Revenue in 2021],
[Total Target in 2021]
FROM
(SELECT Account_No,
 SUM(Revenue) AS 'Total Revenue in 2021'
 FROM [Revenue Raw Data]
 WHERE Account_No IN
 (SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup
 WHERE Fiscal_Year = 'FY21')
 GROUP BY Account_No
  )
 [Revenue Raw Data]
 INNER JOIN
(SELECT Account_No,
 SUM(Target) AS 'Total Target in 2021'
 FROM [Targets Raw Data]
 WHERE Account_No IN
 (SELECT DISTINCT Account_No
 FROM yt_Calendar_lookup
 WHERE Fiscal_Year = 'FY21')
 GROUP BY Account_No
 )
 [Targets Raw Data]
 ON [Revenue Raw Data].Account_No
  = [Targets Raw Data].Account_No

ORDER BY [Total Revenue in 2021] DESC, [Total Target in 2021]


问:
Passing a variable as to communicate in subprocess
How can i pass a variable password which is a user's password as a input to the popen communicate,

below is my code

```<code>password = payload["password"]
proc = subprocess.Popen(['sudo', '-S', 'sh', '/home/admin/temp/test1.sh'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate(input='{0}\n'.format(password))[0]
</code>```

this gives the following error

```<code>TypeError: memoryview: a bytes-like object is required, not 'str'
</code>```

If i hardcode the password as this

```<code>proc = subprocess.Popen(['sudo', '-S', 'sh', '/home/admin/temp/test1.sh'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate(input=b'password\n')
</code>```

it works fine
Please help :)

答:
You need to convert string to bytes. Here is the corrected code:

#!/usr/bin/python3
import subprocess

password = "password"
password_bytes = bytes(password + '\n', encoding='utf-8') # Convert string to bytes
proc = subprocess.Popen(['sudo', '-S', 'sh', '/home/admin/temp/test1.sh'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate(input=password_bytes)
```

Body:
How can i pass a variable password which is a user's password as a input to the popen communicate,

below is my code

password = payload["password"]
proc = subprocess.Popen(['sudo', '-S', 'sh', '/home/admin/temp/test1.sh'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate(input='{0}\n'.format(password))[0]

this gives the following error

TypeError: memoryview: a bytes-like object is required, not 'str'

If i hardcode the password as this

proc = subprocess.Popen(['sudo', '-S', 'sh', '/home/admin/temp/test1.sh'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate(input=b'password\n')

it works fine
Please help :)


问:
facebook REST API - infinite session key
How to get the infinite session key using facebook REST API (PHP)?

can someone show me a step by step code/procedure?

Thanks a lot

答:
Lets see this answer.Its code for Graph api but you have to check permission.You need to add offline access.

Graph api

Let me know its work or not.

Thanks

ContentLicense: CC BY-SA 2.5


问:
How to send the message between two nodes correctly in OMNeT++
I am new to OMNeT++ and I do not have much experience in C++.
In my OMNeT++ scenario I have two nodes (coming from SUMO scenario). I want to send a node_indicator from Python (in this case it is 0), then send some message from node 0 to node 1 and return that message back to Python. I am trying to achieve this with the following code:

```<code>Define_Module(veins::TraCIDemo11p);

void TraCIDemo11p::initialize(int stage)
{
    DemoBaseApplLayer::initialize(stage);
    if (stage == 0) {
        sentMessage = false;
        lastDroveAt = simTime();
        currentSubscribedServiceId = -1;

    }
    this->communicate_with_python();
}

void TraCIDemo11p::communicate_with_python() {

    //  Prepare our context and socket
    zmq::context_t context(1);
    zmq::socket_t socket(context, ZMQ_REP);
    socket.bind("tcp://*:5555");

    zmq::message_t request;
    //  Wait for next request from client
    socket.recv(request);
    std::string requestMessage = std::string(static_cast<char *>(request.data()), request.size());
    // Print out received message
    EV << "Received from Python: " + requestMessage << std::endl;  //requestMessage = 0

    std::string msgToClient(" ");
    this->message_exchange(stoi(requestMessage));

    //  Send reply back to client
    msgToClient = message_to_python;
    EV << "Returning Message back to Python" << "\n";
    socket.send(zmq::message_t(msgToClient.data(), msgToClient.size()), zmq::send_flags::none);
}

void TraCIDemo11p::message_exchange(int node_indicator) {
    // Send the message from node 0 to node 1
        if (findHost()->getIndex()==node_indicator) {
            sentMessage=true;
            TraCIDemo11pMessage* wsm = new TraCIDemo11pMessage();
            populateWSM(wsm);

            std::string message = "Message from node 0 to node 1";

            wsm->setDemoData(message.c_str());
            EV << "Sending Now!" << "\n";
            sendDown(wsm);
    }
}

void TraCIDemo11p::onWSM(BaseFrame1609_4* frame)
{
    TraCIDemo11pMessage* wsm = check_and_cast<TraCIDemo11pMessage*>(frame);

    EV << "Message from node 0 received! " << wsm->getDemoData() << " on node " << findHost()->getFullName() << "\n";
    if (strcmp("0", python_request.c_str()) == 0) {
        message_to_python = wsm->getDemoData();
        EV << "Assigned Message to Python!" << "\n";
    }
</code>```

It does not work. In Python only '' gets returned.
My problem is that I do not understand in which sequence the compiler evaluates the statements. I expect the following sequence

Method communicate_with_python

Receive the node indicator from Python

Method message_exchange

Node 0 sends the message to node 1

Method onWSM

Node 1 receives the message from node 0 and saves it to message_to_python variable

Method communicate_with_python

Assigns the traversed message to msgToClient and sends it to Python

In reality, I get the following outputs at my console

```<code>...
INFO (TraCIDemo11p)RSUExampleScenario.node[1].appl:Received from Python: 0
INFO (TraCIDemo11p)RSUExampleScenario.node[1].appl:Returning Message back to Python
...
INFO:Message from node 0 received! Message from node 0 to node 1 on node node[1]
...
INFO:Message from node 0 received! Message from node 0 to node 1 on node node[1]
...
</code>```

Could somebody explain to me how the methods are called inside my class? And also how do I implement it correctly.

Thank you!

答: Have you tried it the conventional way as given in TraciDemo11p example. Can you please explain the need of using sockets here. Thanks</p>

Body:
I am new to OMNeT++ and I do not have much experience in C++.
In my OMNeT++ scenario I have two nodes (coming from SUMO scenario). I want to send a node_indicator from Python (in this case it is 0), then send some message from node 0 to node 1 and return that message back to Python. I am trying to achieve this with the following code:

Define_Module(veins::TraCIDemo11p);

void TraCIDemo11p::initialize(int stage)
{
    DemoBaseApplLayer::initialize(stage);
    if (stage == 0) {
        sentMessage = false;
        lastDroveAt = simTime();
        currentSubscribedServiceId = -1;

    }
    this->communicate_with_python();
}

void TraCIDemo11p::communicate_with_python() {

    //  Prepare our context and socket
    zmq::context_t context(1);
    zmq::socket_t socket(context, ZMQ_REP);
    socket.bind("tcp://*:5555");

    zmq::message_t request;
    //  Wait for next request from client
    socket.recv(request);
    std::string requestMessage = std::string(static_cast<char *>(request.data()), request.size());
    // Print out received message
    EV << "Received from Python: " + requestMessage << std::endl;  //requestMessage = 0

    std::string msgToClient(" ");
    this->message_exchange(stoi(requestMessage));

    //  Send reply back to client
    msgToClient = message_to_python;
    EV << "Returning Message back to Python" << "\n";
    socket.send(zmq::message_t(msgToClient.data(), msgToClient.size()), zmq::send_flags::none);
}

void TraCIDemo11p::message_exchange(int node_indicator) {
    // Send the message from node 0 to node 1
        if (findHost()->getIndex()==node_indicator) {
            sentMessage=true;
            TraCIDemo11pMessage* wsm = new TraCIDemo11pMessage();
            populateWSM(wsm);

            std::string message = "Message from node 0 to node 1";

            wsm->setDemoData(message.c_str());
            EV << "Sending Now!" << "\n";
            sendDown(wsm);
    }
}

void TraCIDemo11p::onWSM(BaseFrame1609_4* frame)
{
    TraCIDemo11pMessage* wsm = check_and_cast<TraCIDemo11pMessage*>(frame);

    EV << "Message from node 0 received! " << wsm->getDemoData() << " on node " << findHost()->getFullName() << "\n";
    if (strcmp("0", python_request.c_str()) == 0) {
        message_to_python = wsm->getDemoData();
        EV << "Assigned Message to Python!" << "\n";
    }

It does not work. In Python only '' gets returned.
My problem is that I do not understand in which sequence the compiler evaluates the statements. I expect the following sequence

Method communicate_with_python

Receive the node indicator from Python

Method message_exchange

Node 0 sends the message to node 1

Method onWSM

Node 1 receives the message from node 0 and saves it to message_to_python variable

Method communicate_with_python

Assigns the traversed message to msgToClient and sends it to Python

In reality, I get the following outputs at my console

...
INFO (TraCIDemo11p)RSUExampleScenario.node[1].appl:Received from Python: 0
INFO (TraCIDemo11p)RSUExampleScenario.node[1].appl:Returning Message back to Python
...
INFO:Message from node 0 received! Message from node 0 to node 1 on node node[1]
...
INFO:Message from node 0 received! Message from node 0 to node 1 on node node[1]
...

Could somebody explain to me how the methods are called inside my class? And also how do I implement it correctly.

Thank you!


问:
Simulate mouseenter with pure css
I need to style an element when I hover with the mouse above it. But, I don't want to style its parent DOM elements. However, when I use :hover the element in question is styled just as I want, but unfortunately, all of its parents are styled too

```<code>*:hover {
    border-color: red;
}
</code>```

DEMO

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover {
  border-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <article>
    <div>

    </div>
  </article>
</main></code>```

The outer border shall be red only if the cursor is between the outer border and the middle border. The middle order shall be red only if the cursor is between the middle border and the inner border. The inner border shall be red only if the cursor is inside the inner border.

Is there a way to only style the DOM element being hovered (which can be any element)? or can I only achieve this goal with javascript?

答:
Currently you are applying the :hover to all elements on the page by using the *-selector, you can read more about that here: https://developer.mozilla.org/en-US/docs/Web/CSS/Universal_selectors

Make it more specific by selecting the div:

div:hover {
  /* your rules here */
}
```

Title: Simulate mouseenter with pure css

Body:
I need to style an element when I hover with the mouse above it. But, I don't want to style its parent DOM elements. However, when I use :hover the element in question is styled just as I want, but unfortunately, all of its parents are styled too

*:hover {
    border-color: red;
}

DEMO

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover {
  border-color: red;
}

The outer border shall be red only if the cursor is between the outer border and the middle border. The middle order shall be red only if the cursor is between the middle border and the inner border. The inner border shall be red only if the cursor is inside the inner border.

Is there a way to only style the DOM element being hovered (which can be any element)? or can I only achieve this goal with javascript?


问:
Given a 2D list (matrix), how to find the largest element and print its row and column number?
I need to find the row and column number for the largest element of an MxN 2D list. If there is more than on, I want to report the one with the smallest row and column number. If possible, I want to do it without numpy as I am still trying to get the hang of Python by doing these exercises.

Here is an example of what I would like to do:

```<code># m rows and n integers (columns)
m = 3
n = 4
# The 2D-list
arr = [[0, 3, 2, 4],
       [2, 3, 5, 5],
       [5, 1, 2, 3]]
</code>```

And the output would then need to be:

```<code>[1, 2]
</code>```

As the first 5 is the largest element with the smallest row and column number.

I have gotten as far as finding the largest value per row, but now I just need to compare this per column and the print the indices. This is what I have up to now:

```<code># m rows and n integers (columns)
m = 3
n = 4
MxN = [m, n]
# The 2D-list
arr = [[0, 3, 2, 4],
       [2, 3, 5, 5],
       [5, 1, 2, 3]]

for i in range(MxN[0]):
    row = arr[i]
    maxValue = max(row)
    index = row.index(maxValue)
    print(maxValue, index)
</code>```

Which gives me the output:

```<code>4 3
5 2
5 0
</code>```

I have no idea how to go on further.

答:
You can just iterate over rows and columns save the index when find a larger number.

# m rows and n integers (columns)
m = 3
n = 4
MxN = [m, n]
# The 2D-list
arr = [[0, 3, 2, 4],
       [2, 3, 5, 5],
       [5, 1, 2, 3]]

max_num = float("-inf")
index = [-1, -1]

for i in range(MxN[0]):
    for j in range(MxN[1]):
        if arr[i][j] > max_num:
            max_num = arr[i][j]
            index = [i, j]

print(index)
```

Body:
I need to find the row and column number for the largest element of an MxN 2D list. If there is more than on, I want to report the one with the smallest row and column number. If possible, I want to do it without numpy as I am still trying to get the hang of Python by doing these exercises.

Here is an example of what I would like to do:

# m rows and n integers (columns)
m = 3
n = 4
# The 2D-list
arr = [[0, 3, 2, 4],
       [2, 3, 5, 5],
       [5, 1, 2, 3]]

And the output would then need to be:

[1, 2]

As the first 5 is the largest element with the smallest row and column number.

I have gotten as far as finding the largest value per row, but now I just need to compare this per column and the print the indices. This is what I have up to now:

# m rows and n integers (columns)
m = 3
n = 4
MxN = [m, n]
# The 2D-list
arr = [[0, 3, 2, 4],
       [2, 3, 5, 5],
       [5, 1, 2, 3]]

for i in range(MxN[0]):
    row = arr[i]
    maxValue = max(row)
    index = row.index(maxValue)
    print(maxValue, index)

Which gives me the output:

4 3
5 2
5 0

I have no idea how to go on further.


问:
How to make a reusable Material UI tabs component in React
I am working on a React project, and I divided some of the pages into tabs using the MUI Tab component, so I can have multiple components in one page and render each component accordingly, so I have created the Tabs component. However, I can only see one first index tab.

Reusable tab MUI component:

```<code>export default function useTabs(props) {
  const { children, value, index, label, ...other } = props;

  const [selectedValue, setSelectedValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setSelectedValue(newValue);
  };

  return (
    <Box sx={{ width: "100%" }}>
      <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
        <Tabs
          value={selectedValue}
          onChange={handleChange}
          className={classes.tab}
          textColor="primary"
          indicatorColor="primary"
        >
          <Tab label={label} {...a11yProps(0)} className={classes.tabText} />
          {/* <Tab className={classes.tabText} label={label} {...a11yProps(1)} /> */}
        </Tabs>
      </Box>
      <TabPanel value={selectedValue} index={index}>
        {children} // Rendering tab children here, but getting only the first component
      </TabPanel>
    </Box>
  );
}
</code>```

Here is how I am using it:

```<code>// Import the reusable component
import Tab from "../common/Tabs";
export default function JobsRecruitments() {
    return (
    <>
    <Tab label="tab name" index={0}>
        <MyComponent />
    </Tab>
    </>
    )
}
</code>```

答:
I don't think it's a good idea to use children if you want reusable tabs. That's because your tabs have to be consistent: if you have 3 child nodes, you should also have 3 tab labels. If you're using children, you can easily lose track of that.

However, if you want to make a reusable tab component, I would suggest passing an array of objects containing the tab label and Component as a property to your custom Tab component. Here's an example of what I mean:

export default function BasicTabs({ tabs }) {
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <Box sx={{ width: "100%" }}>
      <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
        <Tabs
          value={value}
          onChange={handleChange}
          aria-label="basic tabs example"
        >
          {tabs.map(({ label }, i) => (
            <Tab label={label} key={i} />
          ))}
        </Tabs>
      </Box>
      {tabs.map(({ Component }, i) => (
        <TabPanel value={value} index={i} key={i}>
          {Component}
        </TabPanel>
      ))}
    </Box>
  );
}
```
<p>And then you can use this component like this:</p>
<pre class="lang-js prettyprint-override"><code>import Tabs from "./MyTabs";

const tabs = [
  {
    label: "Tab 1",
    Component: <div>Hello, I am tab 1</div>
  },
  {
    label: "Tab 2",
    Component: <div>Hello, I am tab 2</div>
  },
  {
    label: "Tab 3",
    Component: (
      <div>
        <h1>Tab with heading</h1>
        <p>Hello I am a tab with a heading</p>
      </div>
    )
  }
];

export default function App() {
  return (
    <div>
      <Tabs tabs={tabs} />
    </div>
  );
}
</code>```

Here's the Codesandbox with the full example

Body:
I am working on a React project, and I divided some of the pages into tabs using the MUI Tab component, so I can have multiple components in one page and render each component accordingly, so I have created the Tabs component. However, I can only see one first index tab.

Reusable tab MUI component:

export default function useTabs(props) {
  const { children, value, index, label, ...other } = props;

  const [selectedValue, setSelectedValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setSelectedValue(newValue);
  };

  return (
    <Box sx={{ width: "100%" }}>
      <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
        <Tabs
          value={selectedValue}
          onChange={handleChange}
          className={classes.tab}
          textColor="primary"
          indicatorColor="primary"
        >
          <Tab label={label} {...a11yProps(0)} className={classes.tabText} />
          {/* <Tab className={classes.tabText} label={label} {...a11yProps(1)} /> */}
        </Tabs>
      </Box>
      <TabPanel value={selectedValue} index={index}>
        {children} // Rendering tab children here, but getting only the first component
      </TabPanel>
    </Box>
  );
}

Here is how I am using it:

// Import the reusable component
import Tab from "../common/Tabs";
export default function JobsRecruitments() {
    return (
    <>
    <Tab label="tab name" index={0}>
        <MyComponent />
    </Tab>
    </>
    )
}

Body:
I don't think it's a good idea to use children if you want reusable tabs. That's because your tabs have to be consistent: if you have 3 child nodes, you should also have 3 tab labels. If you're using children, you can easily lose track of that.

However, if you want to make a reusable tab component, I would suggest passing an array of objects containing the tab label and Component as a property to your custom Tab component. Here's an example of what I mean:

export default function BasicTabs({ tabs }) {
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <Box sx={{ width: "100%" }}>
      <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
        <Tabs
          value={value}
          onChange={handleChange}
          aria-label="basic tabs example"
        >
          {tabs.map(({ label }, i) => (
            <Tab label={label} key={i} />
          ))}
        </Tabs>
      </Box>
      {tabs.map(({ Component }, i) => (
        <TabPanel value={value} index={i} key={i}>
          {Component}
        </TabPanel>
      ))}
    </Box>
  );
}

And then you can use this component like this:

import Tabs from "./MyTabs";

const tabs = [
  {
    label: "Tab 1",
    Component: <div>Hello, I am tab 1</div>
  },
  {
    label: "Tab 2",
    Component: <div>Hello, I am tab 2</div>
  },
  {
    label: "Tab 3",
    Component: (
      <div>
        <h1>Tab with heading</h1>
        <p>Hello I am a tab with a heading</p>
      </div>
    )
  }
];

export default function App() {
  return (
    <div>
      <Tabs tabs={tabs} />
    </div>
  );
}

Here's the Codesandbox with the full example


问:
Understanding why UNION is used in this SQL injection example
I'm trying to understand more about SQL injection, so I found this lesson from Red Tiger Labs.

According to the solution, the cat=1 part of the URL is vulnerable to SQL injection.

I can understand that you can append ORDER BY X# and keep incrementing X to establish the number of columns, which is 4.

However according to the solution, the next step is to do:

cat=1 union select 1,2,3,4 from level1_users #

The table name is provided, so that's ok. But I'm really having trouble understanding the purpose of the UNION. My guess is the underlying code does something like:

SELECT * FROM level1_users where cat=1

Presumably it would expect only 0 or 1 results. Then it prints out some number of columns onto the screen. According to the example, it prints out:

This hackit is cool :)

My cats are sweet.

Miau

3

4

The first three lines were printed out without the extra SQL injection. So what's going on, and what's the significance?

I would not expect the union to do anything, I assume the numbers refer to columns?

答:
So, I've managed to figure out what's going on here.

cat=1 union select 1,2,3,4 from level1_users #

The select part selects the numbers 1, 2, 3, 4 as columns. You could actually use anything here, like select 'cats', 'fish', 'bread', 42 and sometimes you have to do this as the union select must match the column types in the target table. The level1_users table is integers (or at least, integers work), hence selecting numbers.

I actually thought it might be selecting columns by their index, because often in sql you can do ORDER BY 1 for example to order by the first column, however that's not the case.

What tripped me up was that this particular SQL injection website dumps the entire contents of the result set to the screen, and I wasn't expecting that.  If you think about it though it is looking for a category id and therefore it's not unreasonable to expect it to list everything in that category.

By performing a union it first shows that extra rows will be printed to the screen, and because we've numbered the columns, it shows which columns, columns 3 and 4.

From there it's possible to simply select username and password into those columns (you have to guess the table headers in this instance because although you can normally union onto the db data it has been disabled for this exercise).


答:
Add this

```<code> def __str__(self):
        return self.name
</code>```

str method is used to show name of objects rather than memory location and it must be a string.

Body:
Add this

 def __str__(self):
        return self.name

str method is used to show name of objects rather than memory location and it must be a string.


问:
Google Calendar API not returning attendees when listing events
When retrieving events using the Google Calendar Api v3 the attendees array is not included in the results. I'm authenticating with a service account, so there should be no access restrictions on individual fields.

My request looks like this (authentication code omitted for brevity):

async function fetchEvents() {
  const calendar = google.calendar('v3')
  google.options({ auth: await auth() })

  return await calendar.events.list({
    calendarId:
      '<the-actual-calendar-id>@group.calendar.google.com',
    fields:
      'items(summary,description,attendees)',
    maxAttendees: 99,
    timeMin: new Date().toISOString(),
    maxResults: 5,
    singleEvents: true,
    orderBy: 'startTime'
  })
}
```

Omitting the fields parameter entirely also doesn't include the attendees although the field is part of the Events Resource.

Likewise, omitting maxAttendees also doesn't change anything.

Following the htmlLink returned from the API, I can verify that a particular event has a list of attendees.

答:
As pointed out in DalmTo's answer an event's attendees is a privileged field that can't be retrieved with a service account unless it is used to impersonate the calendar's owner.

Setting up a service account to impersonate a user

Enable domain-wide delegation for the service account in the Admin Console. The OAuth scope required is https://www.googleapis.com/auth/calendar.events.

Use google.auth.JWT to impersonate the user (from this GitHub issue):

  const auth = google.auth.JWT({
    subject: 'user@your-workspace-domain.com',
    keyFile: '/path/to/service-account-keyfile.json',
    scopes: ['https://www.googleapis.com/auth/calendar.events']
  })

  const calendar = google.calendar({ version: 'v3', auth })

  const { data } = await calendar.events.list({ ... })
```

Body:
When retrieving events using the Google Calendar Api v3 the attendees array is not included in the results. I'm authenticating with a service account, so there should be no access restrictions on individual fields.

My request looks like this (authentication code omitted for brevity):

async function fetchEvents() {
  const calendar = google.calendar('v3')
  google.options({ auth: await auth() })

  return await calendar.events.list({
    calendarId:
      '<the-actual-calendar-id>@group.calendar.google.com',
    fields:
      'items(summary,description,attendees)',
    maxAttendees: 99,
    timeMin: new Date().toISOString(),
    maxResults: 5,
    singleEvents: true,
    orderBy: 'startTime'
  })
}

Omitting the fields parameter entirely also doesn't include the attendees although the field is part of the Events Resource.

Likewise, omitting maxAttendees also doesn't change anything.

Following the htmlLink returned from the API, I can verify that a particular event has a list of attendees.


问:
JavaScript/DOM - Is there a difference between a "CSS Selector" and an attribute?
Excluding declarative event handlers:

href='#' onclick=<handler> ... />

Is there any material difference between an Attribute and a CSS Selector?  If I provide my own attribute:

href='#' my-data-node-type='1'/>

Is "my-data-node-type" an attribute, a CSS Selector or both?  I think what I'm really asking here is, are the terms "attribute" and "css selector" synonymous?  Or is a "css selector" only an attribute recognized by CSS as eligible for styling?

答:
A css selector is just a way that css identifies groups of elements to apply styles to. An attribute is a property of an element.

In your example, my-data-node-type='1' is an attribute. Attributes can be used as part of css selectors however. a[my-data-node-type="1"] will select all 'a' tags with my-data-node-type=1.

Body:
Excluding declarative event handlers:

<a href='#' onclick=<handler> ... />

Is there any material difference between an Attribute and a CSS Selector?  If I provide my own attribute:

Is "my-data-node-type" an attribute, a CSS Selector or both?  I think what I'm really asking here is, are the terms "attribute" and "css selector" synonymous?  Or is a "css selector" only an attribute recognized by CSS as eligible for styling?


问:
Execute all cursors of a postgres function via c# Ado.net
I have created a function postgres which returns 2 resultsets from different tables using refcursors. Now I want to call this function from C# but I can only call one cursor at a time by hardcoding the cursor name which is not ideal at all.  Is it possible to loop through the multiple cursors and execute them using C# ?</p>
```<code>CREATE OR REPLACE FUNCTION multipleresultset()
RETURNS SETOF refcursor AS
$BODY$
DECLARE
ref1 refcursor := 'cursor1';
ref2 refcursor := 'cursor2';
BEGIN open ref1 FOR SELECT * FROM table1;
RETURN NEXT ref1;

open ref2 FOR SELECT * FROM table2;
RETURN NEXT ref2;
--RETURN;END;$BODY$
LANGUAGE 'plpgsql';
</code>```
```<code>public DataTable GetMultipleResults()
{
    string connection = GetConnectionString("conn");
    NpgsqlConnection npgsqlConnection = new NpgsqlConnection(connection);
    DataTable dataTable = new DataTable();
    try
    {
        npgsqlConnection.Open();
        NpgsqlTransaction tran = npgsqlConnection.BeginTransaction();
        string query = "multipleresultset";
        NpgsqlCommand npgsqlCommand = new NpgsqlCommand(query, npgsqlConnection);
        npgsqlCommand.CommandType = CommandType.StoredProcedure;
        npgsqlCommand.ExecuteNonQuery();
        npgsqlCommand.CommandText = "fetch all in \"cursor1\"";
        npgsqlCommand.CommandType = CommandType.Text;

        NpgsqlDataAdapter npgsqlDataAdapter = new NpgsqlDataAdapter(npgsqlCommand);
        npgsqlDataAdapter.Fill(dataTable);

        tran.Commit();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        npgsqlConnection.Close();
    }

    return dataTable;
}
</code>```

答:
Adding something like this inside Npgsql is tracked by https://github.com/npgsql/npgsql/issues/1785 (not currently planned).

But it should be trivial to write an extension method that does this (some options are linked to from that issue).. Basically you'd read the cursor names coming back from the method, and then execute another roundtrip to get all the data from them. Issue #1785 is basically about doing that inside Npgsql, but it wouldn't have any advantage over doing it yourself (except for less code of course).

Finally, consider if you really need a stored function which returns multiple resultsets.. If you split it into two functions, each returning a single resultset, it's easier and more efficient (less roundtrips) to simply batch two calls together together. Or just batch the queries themselves, without functions at all. I'm saying this because people coming from other databases are sometimes in the habit of creating stored functions where none are necessarily needed.

Body:
I have created a function postgres which returns 2 resultsets from different tables using refcursors. Now I want to call this function from C# but I can only call one cursor at a time by hardcoding the cursor name which is not ideal at all.  Is it possible to loop through the multiple cursors and execute them using C# ?

CREATE OR REPLACE FUNCTION multipleresultset()
RETURNS SETOF refcursor AS
$BODY$
DECLARE
ref1 refcursor := 'cursor1';
ref2 refcursor := 'cursor2';
BEGIN open ref1 FOR SELECT * FROM table1;
RETURN NEXT ref1;

open ref2 FOR SELECT * FROM table2;
RETURN NEXT ref2;
--RETURN;END;$BODY$
LANGUAGE 'plpgsql';

public DataTable GetMultipleResults()
{
    string connection = GetConnectionString("conn");
    NpgsqlConnection npgsqlConnection = new NpgsqlConnection(connection);
    DataTable dataTable = new DataTable();
    try
    {
        npgsqlConnection.Open();
        NpgsqlTransaction tran = npgsqlConnection.BeginTransaction();
        string query = "multipleresultset";
        NpgsqlCommand npgsqlCommand = new NpgsqlCommand(query, npgsqlConnection);
        npgsqlCommand.CommandType = CommandType.StoredProcedure;
        npgsqlCommand.ExecuteNonQuery();
        npgsqlCommand.CommandText = "fetch all in \"cursor1\"";
        npgsqlCommand.CommandType = CommandType.Text;

        NpgsqlDataAdapter npgsqlDataAdapter = new NpgsqlDataAdapter(npgsqlCommand);
        npgsqlDataAdapter.Fill(dataTable);

        tran.Commit();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        npgsqlConnection.Close();
    }

    return dataTable;
}


问:
Why the navbar dropdown in bootstrap 5 doesn't work
When I copy the code of the navbar dropdown from the documentation of bootstrap 5 the dropdown doesn't work, if I click on the dropdown the links ("action", "another action", "something else")  of this last one don't show up, what should I do?

here is the code :

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

  Logo

      Link 1

      Link 2

              Dropdown link

        Link 1
        Link 2
        Link 3

Navbar With Dropdown

This example adds a dropdown menu in the navbar.

Navbar

    Navbar
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

          </button>

          Home

          Link

                  Dropdown

Action

Another action

Something else here

```

答:
Not only do you need the CSS CDN. But you also need the JavaScript CDN's for the dropdown-menu to work.

You can find all documentation and Scripts for Bootstrap 5 Navbars and Bootstrap Dropdowns in the links provided.

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

Navbar

    Navbar
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

          </button>

          Home

          Link

                  Dropdown

Action

Another action

Something else here

Navbar With Dropdown

This example adds a dropdown menu in the navbar.

```

Body:
Not only do you need the CSS CDN. But you also need the JavaScript CDN's for the dropdown-menu to work.

You can find all documentation and Scripts for Bootstrap 5 Navbars and Bootstrap Dropdowns in the links provided.

<head>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
</head>

<h1>Navbar</h1>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                  Dropdown
                </a>
          <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li><a class="dropdown-item" href="#">Another action</a></li>
            <li>
              <hr class="dropdown-divider">
            </li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
          </ul>
      </ul>
    </div>
  </div>
</nav>

<div class="container">
  <h3>Navbar With Dropdown</h3>
  <p>This example adds a dropdown menu in the navbar.</p>
</div>


问:
Button onlick show alert box
I have a modal and after pressing the password update button, the modal should close and an alert box should appear on my homepage. however, the alert box will not appear when the page is first opened. how can I do it? Do you have any examples you can share?</p>

答:
Complementing Apollo79's answer, you can also use an inline event listener, but this is no longer recommended. There are some specific cases for this, but if you really don't need one, use Apollo79's answer instead.

```<code><button id="urButton" onclick="alertAndDisappear()">
</code>```

or

```<code>yourCloseButton.onclick = function(){}
</code>```

which is equivalent to the first one.

Again, only use these if you really need them

Title: Button onlick show alert box

Body:
Complementing Apollo79's answer, you can also use an inline event listener, but this is no longer recommended. There are some specific cases for this, but if you really don't need one, use Apollo79's answer instead.

<button id="urButton" onclick="alertAndDisappear()">

or

yourCloseButton.onclick = function(){}

which is equivalent to the first one.

Again, only use these if you really need them


问:
What is the best way to compare a value against 'undefined'?
Is there any differences between

```<code>var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")
</code>```

Which one should we use?

答:
```<code>var a;
(a == undefined) //true
(a === undefined) //true
((typeof a) == "undefined") //true
((typeof a) === "undefined") //true
</code>```

BUT:

```<code>var a;
(a == "undefined") //false
(a === "undefined") //false
((typeof a) == undefined) //false
((typeof a) === undefined) //false
</code>```

Body:
Is there any differences between

var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")

Which one should we use?

Body:
var a;
(a == undefined) //true
(a === undefined) //true
((typeof a) == "undefined") //true
((typeof a) === "undefined") //true

BUT:

var a;
(a == "undefined") //false
(a === "undefined") //false
((typeof a) == undefined) //false
((typeof a) === undefined) //false


问:
Android Studio could not find any version that matches com.android.support:appcompat-v7:+
Running a project in Android Studio fails with this error: could not find any version that matches com.android.support:appcompat-v7:+

How can I fix this error?

答:
Got the same error but version 26.

Downloading the libraries through the SDK Manager is no longer supported. The support libraries are now available through Google's Maven repository.

Solution:

In build.gradle (project) inside both buildscript/repositories and allprojects/repositories add this:

```<code>maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
</code>```

Result:

```<code>buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

It worked for me.

Body:
Got the same error but version 26.

Downloading the libraries through the SDK Manager is no longer supported. The support libraries are now available through Google's Maven repository.

Solution:

In build.gradle (project) inside both buildscript/repositories and allprojects/repositories add this:

maven {
            url 'https://maven.google.com/'
            name 'Google'
        }

Result:

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

It worked for me.


问:
Copy an array reference in VBA
Is there any way to copy an array reference in VBA (or VB6)?

In VBA, arrays are value types. Assigning one array variable to another copies the entire array. I want to get two array variables to point to the same array. Is there any way to accomplish this, perhaps using some API memory functions and/or the VarPtr function, which does in fact return the address of a variable in VBA?

Dim arr1(), arr2(), ref1 As LongPtr
arr1 = Array("A", "B", "C")

' Now I want to make arr2 refer to the same array object as arr1
' If this was C#, simply assign, since in .NET arrays are reference types:
arr2 = arr1

' ...Or if arrays were COM objects:
Set arr2 = arr1

' VarPtr lets me get the address of arr1 like this:
ref1 = VarPtr(arr1)

' ... But I don't know of a way to *set* address of arr2.
```

<p>Incidentally, it is possible to get multiple references to the same array by passing the same array variable <code>ByRef</code> to multiple parameters of a method:</p>

<pre class="lang-vb prettyprint-override"><code>Sub DuplicateRefs(ByRef Arr1() As String, ByRef Arr2() As String)
    Arr2(0) = "Hello"
    Debug.Print Arr1(0)
End Sub

Dim arrSource(2) As String
arrSource(0) = "Blah"

' This will print 'Hello', because inside DuplicateRefs, both variables
' point to the same array. That is, VarPtr(Arr1) == VarPtr(Arr2)
Call DuplicateRefs(arrSource, arrSource)
</code>```

But this still does not allow one to simply manufacture a new reference in the same scope as an existing one.

答:
You could use the method called GetArrayByRef from my repository VBA-MemoryTools. However, if you don't want the extra reference you could use this limited, slower code:

```<code>Option Explicit

#If Mac Then
    #If VBA7 Then
        Public Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr
    #Else
        Public Declare Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As Long) As Long
    #End If
#Else 'Windows
    'https://msdn.microsoft.com/en-us/library/mt723419(v=vs.85).aspx
    #If VBA7 Then
        Public Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
    #Else
        Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    #End If
#End If

Public Const VT_BYREF As Long = &H4000
#If Win64 Then
    Public Const PTR_SIZE As Long = 8
#Else
    Public Const PTR_SIZE As Long = 4
#End If

Public Function GetArrayByRef(ByRef arr As Variant) As Variant
    If IsArray(arr) Then
        GetArrayByRef = VarPtrArr(arr)
        Dim vt As VbVarType: vt = VarType(arr) Or VT_BYREF
        CopyMemory GetArrayByRef, vt, 2
    Else
        Err.Raise 5, "GetArrayByRef", "Array required"
    End If
End Function

#If Win64 Then
Public Function VarPtrArr(ByRef arr As Variant) As LongLong
#Else
Public Function VarPtrArr(ByRef arr As Variant) As Long
#End If
    Const vtArrByRef As Long = vbArray + VT_BYREF
    Dim vt As VbVarType
    CopyMemory vt, arr, 2
    If (vt And vtArrByRef) = vtArrByRef Then
        Const pArrayOffset As Long = 8
        CopyMemory VarPtrArr, ByVal VarPtr(arr) + pArrayOffset, PTR_SIZE
    Else
        Err.Raise 5, "VarPtrArr", "Array required"
    End If
End Function
</code>```

Quick test:

```<code>Sub Demo()
    Dim arr() As String
    ReDim arr(1 To 2)
    arr(1) = "AAA"

    Dim v As Variant

    v = GetArrayByRef(arr)
    v(2) = "BBB"

    Debug.Assert arr(2) = "BBB"
End Sub
</code>```

It's also safe - you don't have to worry about memory deallocation

Title: Copy an array reference in VBA

Body:
Is there any way to copy an array reference in VBA (or VB6)?

In VBA, arrays are value types. Assigning one array variable to another copies the entire array. I want to get two array variables to point to the same array. Is there any way to accomplish this, perhaps using some API memory functions and/or the VarPtr function, which does in fact return the address of a variable in VBA?

Dim arr1(), arr2(), ref1 As LongPtr
arr1 = Array("A", "B", "C")

' Now I want to make arr2 refer to the same array object as arr1
' If this was C#, simply assign, since in .NET arrays are reference types:
arr2 = arr1

' ...Or if arrays were COM objects:
Set arr2 = arr1

' VarPtr lets me get the address of arr1 like this:
ref1 = VarPtr(arr1)

' ... But I don't know of a way to *set* address of arr2.

Incidentally, it is possible to get multiple references to the same array by passing the same array variable ByRef to multiple parameters of a method:

Sub DuplicateRefs(ByRef Arr1() As String, ByRef Arr2() As String)
    Arr2(0) = "Hello"
    Debug.Print Arr1(0)
End Sub

Dim arrSource(2) As String
arrSource(0) = "Blah"

' This will print 'Hello', because inside DuplicateRefs, both variables
' point to the same array. That is, VarPtr(Arr1) == VarPtr(Arr2)
Call DuplicateRefs(arrSource, arrSource)

But this still does not allow one to simply manufacture a new reference in the same scope as an existing one.

Body:
You could use the method called GetArrayByRef from my repository VBA-MemoryTools. However, if you don't want the extra reference you could use this limited, slower code:

Option Explicit

#If Mac Then
    #If VBA7 Then
        Public Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr
    #Else
        Public Declare Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As Long) As Long
    #End If
#Else 'Windows
    'https://msdn.microsoft.com/en-us/library/mt723419(v=vs.85).aspx
    #If VBA7 Then
        Public Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
    #Else
        Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    #End If
#End If

Public Const VT_BYREF As Long = &H4000
#If Win64 Then
    Public Const PTR_SIZE As Long = 8
#Else
    Public Const PTR_SIZE As Long = 4
#End If

Public Function GetArrayByRef(ByRef arr As Variant) As Variant
    If IsArray(arr) Then
        GetArrayByRef = VarPtrArr(arr)
        Dim vt As VbVarType: vt = VarType(arr) Or VT_BYREF
        CopyMemory GetArrayByRef, vt, 2
    Else
        Err.Raise 5, "GetArrayByRef", "Array required"
    End If
End Function

#If Win64 Then
Public Function VarPtrArr(ByRef arr As Variant) As LongLong
#Else
Public Function VarPtrArr(ByRef arr As Variant) As Long
#End If
    Const vtArrByRef As Long = vbArray + VT_BYREF
    Dim vt As VbVarType
    CopyMemory vt, arr, 2
    If (vt And vtArrByRef) = vtArrByRef Then
        Const pArrayOffset As Long = 8
        CopyMemory VarPtrArr, ByVal VarPtr(arr) + pArrayOffset, PTR_SIZE
    Else
        Err.Raise 5, "VarPtrArr", "Array required"
    End If
End Function

Quick test:

Sub Demo()
    Dim arr() As String
    ReDim arr(1 To 2)
    arr(1) = "AAA"

    Dim v As Variant

    v = GetArrayByRef(arr)
    v(2) = "BBB"

    Debug.Assert arr(2) = "BBB"
End Sub

It's also safe - you don't have to worry about memory deallocation


问:
importing basemap in r
I'm working with ggplot2 to complete some mapping in R. However, I need to use the United Nations "Carto Tile" as my basemap - available here: https://www.un.org/geospatial/mapsgeo/webservices

Any ideas on how to import this map or if there is an R package for it?

I'm currently using the basemap in the "maps" package as an alternative.

Thank you.

答:
I also use this basemap because the borders are compliant with UN policies on maps. Here is the mapbox gl.js library: https://github.com/UN-Geospatial/cartotile-plain-design.

You should be able to extract the data as an .geojson file which you can use as a basemap.

Title: importing basemap in r


问:
JS array of objects destructuring?
For a react project I need to simplify an array of objects.

I've an array of objects coming from wp rest api axios request. Inside objects there are objects. I would like to "remove" this nested object in order to have this :

```<code>   [
      {
        "id": 101,
        "title": "CTC20180018",
        "fielda": "valuea",
        "fieldb": "valueb",
        "fieldc": "valuec"
      },
      {
        "id": 102,
        "title": "D2021063365",
        "fielda": "valuea",
        "fieldb": "valueb",
        "fieldc": "valuec"
      },
      ...
    ]
</code>```

What is the best solution ? .map() the array and use destructuring ?

The original array :

```<code>[
  {
    "id": 101,
    "title": {
      "rendered": "CTC20180018"
    },
    "acf": {
      "fielda": "valuea",
      "fieldb": "valueb",
      "fieldc": "valuec"
    }
  },
  {
    "id": 102,
    "title": {
      "rendered": "D2021063365"
    },
    "acf": {
      "fielda": "valuea",
      "fieldb": "valueb",
      "fieldc": "valuec"
    }
  },
  ...
]
</code>```

答:
Try something like below using map, Object destructuring and spread operator

const data = [{
    "id": 101,
    "title": {
      "rendered": "CTC20180018"
    },
    "acf": {
      "fielda": "valuea",
      "fieldb": "valueb",
      "fieldc": "valuec"
    }
  },
  {
    "id": 102,
    "title": {
      "rendered": "D2021063365"
    },
    "acf": {
      "fielda": "valuea",
      "fieldb": "valueb",
      "fieldc": "valuec"
    }
  }
]

const result = data.map(({
  id,
  title,
  acf
}) => ({
  id: id,
  title: title.rendered,
  ...acf
}));

console.log(result);```

Title: JS array of objects destructuring?

Body:
For a react project I need to simplify an array of objects.

I've an array of objects coming from wp rest api axios request. Inside objects there are objects. I would like to "remove" this nested object in order to have this :

   [
      {
        "id": 101,
        "title": "CTC20180018",
        "fielda": "valuea",
        "fieldb": "valueb",
        "fieldc": "valuec"
      },
      {
        "id": 102,
        "title": "D2021063365",
        "fielda": "valuea",
        "fieldb": "valueb",
        "fieldc": "valuec"
      },
      ...
    ]

What is the best solution ? .map() the array and use destructuring ?

The original array :

[
  {
    "id": 101,
    "title": {
      "rendered": "CTC20180018"
    },
    "acf": {
      "fielda": "valuea",
      "fieldb": "valueb",
      "fieldc": "valuec"
    }
  },
  {
    "id": 102,
    "title": {
      "rendered": "D2021063365"
    },
    "acf": {
      "fielda": "valuea",
      "fieldb": "valueb",
      "fieldc": "valuec"
    }
  },
  ...
]


问:
Column multiplication to replace original columns within panda dataframe
I am trying to find a way to bring the new calculated columns back to the dataframe after doing the multiplication. However, I want them to replace the value under original columns like '2018, 2019, 2020'. Is there a way to do it alongside with the multiplication, especially if I have a long list of columns to be multiplied?</p>
```<code>import pandas as pd

df1 = pd.DataFrame({
    'ID':  ['a1', 'b1', 'c1'],
    '2018': [1, 5, 9],
    '2019': [2, 6, 10],
    '2020': [3, 7, 11]})

df2 = pd.DataFrame({
    'ID':  ['a1', 'b1'],
    'percentage': [0.6, 0.4]})

df1.filter(regex='2018|2019|2020').multiply(df2["percentage"], axis="index")

Expected:
   ID 2018  2019  2020
0  a1  0.6   1.2   1.8
1  b1  2.0   2.4   2.8
2  c1  NaN   NaN   NaN
</code>```

答:
You can align indices by converting both ID columns to indexes and then processing all columns:

```<code>df = df1.set_index('ID').multiply(df2.set_index('ID')["percentage"], axis="index")

print(df)
    2018  2019  2020
ID
a1   0.6   1.2   1.8
b1   2.0   2.4   2.8
c1   NaN   NaN   NaN
</code>```

```<code>df2 = pd.DataFrame({
    'ID':  ['a1', 'c1'],
    'percentage': [0.6, 0.4]})

df = df1.set_index('ID').multiply(df2.set_index('ID')["percentage"], axis="index")

print(df)
    2018  2019  2020
ID
a1   0.6   1.2   1.8
b1   NaN   NaN   NaN
c1   3.6   4.0   4.4
</code>```

If only needing to multiply some columns:

```<code>cols = ['2018','2019']
df1 = df1.set_index('ID')
df1[cols] = df1[cols].multiply(df2.set_index('ID')["percentage"], axis="index")

print(df1)

    2018  2019  2020
ID
a1   0.6   1.2     3
b1   NaN   NaN     7
c1   3.6   4.0    11
</code>```

HI why are you setting index in the last part of the answer of yours

Because not setting the index before multiplying produces incorrect output:

```<code>df2 = pd.DataFrame({
    'ID':  ['a1', 'c1'],
    'percentage': [0.6, 0.4]})

cols = ['2018', '2019', '2020']

df1[cols] = df1[cols].mul(df2["percentage"], axis=0)
print (df1)
   ID  2018  2019  2020
0  a1   0.6   1.2   1.8
1  b1   2.0   2.4   2.8 <- incorrect result (aligned on index 1 not b1)
2  c1   NaN   NaN   NaN <- incorrect result (aligned on index 2 not c1)
</code>```

Body:
I am trying to find a way to bring the new calculated columns back to the dataframe after doing the multiplication. However, I want them to replace the value under original columns like '2018, 2019, 2020'. Is there a way to do it alongside with the multiplication, especially if I have a long list of columns to be multiplied?

import pandas as pd

df1 = pd.DataFrame({
    'ID':  ['a1', 'b1', 'c1'],
    '2018': [1, 5, 9],
    '2019': [2, 6, 10],
    '2020': [3, 7, 11]})

df2 = pd.DataFrame({
    'ID':  ['a1', 'b1'],
    'percentage': [0.6, 0.4]})

df1.filter(regex='2018|2019|2020').multiply(df2["percentage"], axis="index")

Expected:
   ID 2018  2019  2020
0  a1  0.6   1.2   1.8
1  b1  2.0   2.4   2.8
2  c1  NaN   NaN   NaN

Body:
You can align indices by converting both ID columns to indexes and then processing all columns:

df = df1.set_index('ID').multiply(df2.set_index('ID')["percentage"], axis="index")

print(df)
    2018  2019  2020
ID
a1   0.6   1.2   1.8
b1   2.0   2.4   2.8
c1   NaN   NaN   NaN

df2 = pd.DataFrame({
    'ID':  ['a1', 'c1'],
    'percentage': [0.6, 0.4]})

df = df1.set_index('ID').multiply(df2.set_index('ID')["percentage"], axis="index")

print(df)
    2018  2019  2020
ID
a1   0.6   1.2   1.8
b1   NaN   NaN   NaN
c1   3.6   4.0   4.4

If only needing to multiply some columns:

cols = ['2018','2019']
df1 = df1.set_index('ID')
df1[cols] = df1[cols].multiply(df2.set_index('ID')["percentage"], axis="index")

print(df1)

    2018  2019  2020
ID
a1   0.6   1.2     3
b1   NaN   NaN     7
c1   3.6   4.0    11

HI why are you setting index in the last part of the answer of yours

Because not setting the index before multiplying produces incorrect output:

df2 = pd.DataFrame({
    'ID':  ['a1', 'c1'],
    'percentage': [0.6, 0.4]})

cols = ['2018', '2019', '2020']

df1[cols] = df1[cols].mul(df2["percentage"], axis=0)
print (df1)
   ID  2018  2019  2020
0  a1   0.6   1.2   1.8
1  b1   2.0   2.4   2.8 <- incorrect result (aligned on index 1 not b1)
2  c1   NaN   NaN   NaN <- incorrect result (aligned on index 2 not c1)


问:
Importing a file in a multi-level directory structure
I would like to do the following import:

```<code>from . import foo.bar.foobar
</code>```

Why is that a problem for python? Alternatively

```<code>from .foo.bar import foobar
</code>```

does not work either.

The foobar module should be imported from the example.py file as seen in this folder structure:

```<code>test/
|____foo/
|    |____bar/
|         |___ __init__.py
|         |___ foobar.py
|
|____core/
     |____ example.py
</code>```

What works is

```<code>sys.path.insert(0, r"../foo/bar")
import foobar
</code>```

but i wondered if there was another way.

答:
My recommendation in your case is to stick to absolute import path in example:
from foo.bar import foobar

Then suppose you are in the test folder, you can run your example.py file with the below command:

python -m core.example

This allow you program to know that it should consider the current folder as the source and then the import will work.

Another way out could be to just move example.py directly in test and everything would work fine but it probably don't suit your case.

Body:
I would like to do the following import:

from . import foo.bar.foobar

Why is that a problem for python? Alternatively

from .foo.bar import foobar

does not work either.

The foobar module should be imported from the example.py file as seen in this folder structure:

test/
|____foo/
|    |____bar/
|         |___ __init__.py
|         |___ foobar.py
|
|____core/
     |____ example.py

What works is

sys.path.insert(0, r"../foo/bar")
import foobar

but i wondered if there was another way.


答:
Just taking a guess with the ambiguous question example.  You can say what NOT to style as well. You said "all" with *:hover so it does that.

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover:not(.not-me) {
  border-color: red;
}

main:hover:not(.not-me) {
  border-color: green;
}

article:hover:not(.not-me) {
  border-color: blue;
}

main>article>div:hover:not(.not-me) {
  border-color: inherit;
  border-color: orange;
  background-color: #ffdddd;
}

main.not-me:hover:not(*),
main.not-me *.not-me *:hover:not(*) {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <article>
    <div>

    </div>
    <div class="not-me">
      not me
    </div>
  </article>
  <article class="not-me">
    <div>
      not me either, I am inside not-me
    </div>
    <div class="not-me">
      not me
    </div>
  </article>
</main>
<main class="not-me">
  nothing in here
  <article class="not-me">
    <div>
      ME I want in also!
    </div>
    <div>
      ME!
    </div>
  </article>
  <article class="not-me">
    <div>
      Me ME! I am inside not-me
    </div>
    <div class="not-me">
      not me
    </div>
  </article>
</main></code>```

Title: Simulate mouseenter with pure css

Body:
I need to style an element when I hover with the mouse above it. But, I don't want to style its parent DOM elements. However, when I use :hover the element in question is styled just as I want, but unfortunately, all of its parents are styled too

*:hover {
    border-color: red;
}

DEMO

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover {
  border-color: red;
}

The outer border shall be red only if the cursor is between the outer border and the middle border. The middle order shall be red only if the cursor is between the middle border and the inner border. The inner border shall be red only if the cursor is inside the inner border.

Is there a way to only style the DOM element being hovered (which can be any element)? or can I only achieve this goal with javascript?

Body:
Just taking a guess with the ambiguous question example.  You can say what NOT to style as well. You said "all" with *:hover so it does that.

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover:not(.not-me) {
  border-color: red;
}

main:hover:not(.not-me) {
  border-color: green;
}

article:hover:not(.not-me) {
  border-color: blue;
}

main>article>div:hover:not(.not-me) {
  border-color: inherit;
  border-color: orange;
  background-color: #ffdddd;
}

main.not-me:hover:not(*),
main.not-me *.not-me *:hover:not(*) {}

<main>
  <article>
    <div>

    </div>
    <div class="not-me">
      not me
    </div>
  </article>
  <article class="not-me">
    <div>
      not me either, I am inside not-me
    </div>
    <div class="not-me">
      not me
    </div>
  </article>
</main>
<main class="not-me">
  nothing in here
  <article class="not-me">
    <div>
      ME I want in also!
    </div>
    <div>
      ME!
    </div>
  </article>
  <article class="not-me">
    <div>
      Me ME! I am inside not-me
    </div>
    <div class="not-me">
      not me
    </div>
  </article>
</main>