问:
Can't recreate this floating widget
I'm currently blocked trying to create a widget (like a tooltip box) that is represented by the image below. I should probably be able to create it by relying on a Painter class, but i'm not familiar doing so...

https://pasteboard.co/IgccNxD.png

(it's small, yes, max height = ~35px)

答:
The code ended being something like:

```<code>void paint(Canvas canvas, Size size) {
   Paint p = Paint()
     ..color = Colors.red
     ..isAntiAlias = true
     ..style = PaintingStyle.fill;

   Offset nw = Offset(0, 0);
   Offset se = Offset(size.width, size.height * 0.8);

   final Rect rect = Rect.fromPoints(nw, se);
   final RRect r = RRect.fromRectAndRadius(rect, Radius.circular(10));

   canvas.drawRRect(r, p);

   Offset bottomPoint = Offset((size.width / 2), size.height);
   Offset rightPoint = Offset((size.width / 2) * 0.80, size.height * 0.80);
   Offset leftPoint = Offset((size.width / 2) * 1.20, size.height * 0.80);

   var path1 = Path()
     ..moveTo(rightPoint.dx, rightPoint.dy)
     ..lineTo(bottomPoint.dx, bottomPoint.dy)
     ..lineTo(leftPoint.dx, leftPoint.dy)
     ..lineTo(rightPoint.dx, rightPoint.dy);
   canvas.drawPath(path1, p);
}
</code>```

For the text inside, I've stacked it above this painting.

Title: Can't recreate this floating widget

Body:
The code ended being something like:

void paint(Canvas canvas, Size size) {
   Paint p = Paint()
     ..color = Colors.red
     ..isAntiAlias = true
     ..style = PaintingStyle.fill;

   Offset nw = Offset(0, 0);
   Offset se = Offset(size.width, size.height * 0.8);

   final Rect rect = Rect.fromPoints(nw, se);
   final RRect r = RRect.fromRectAndRadius(rect, Radius.circular(10));

   canvas.drawRRect(r, p);

   Offset bottomPoint = Offset((size.width / 2), size.height);
   Offset rightPoint = Offset((size.width / 2) * 0.80, size.height * 0.80);
   Offset leftPoint = Offset((size.width / 2) * 1.20, size.height * 0.80);

   var path1 = Path()
     ..moveTo(rightPoint.dx, rightPoint.dy)
     ..lineTo(bottomPoint.dx, bottomPoint.dy)
     ..lineTo(leftPoint.dx, leftPoint.dy)
     ..lineTo(rightPoint.dx, rightPoint.dy);
   canvas.drawPath(path1, p);
}

For the text inside, I've stacked it above this painting.


来源: stackexchange

问:
Fixed div on the bottom of the scrollable div
I need a create 4 cards with non-changable height with buttons on the bottom, but there are different text amount in each card.

Position Fixed is connected to body element,
position absolute scrolls with content,
position sticky appears when content ends.

https://codepen.io/anatoli101/pen/NVzbGY Here is a basic exemple of my problem

```<code>.content{
  display:flex;
  width: 100%;
  justify-content: space-around;
}

.fixed-div{
  background-color: red;
  height: 400px;
  width: 300px;
  overflow-y: auto;
}

.button{
  position:sticky;
  bottom:0;
  background-color: grey;
  width: 100%;
  height: 30px;
}
</code>```

答:
You can try code:

```<code>.fixed-div p{
   display: block;
   margin: 0;
   padding: 10px;
   height: 350px;
}
</code>```

This is a demo: https://codepen.io/phuongnm153/pen/zQaobq

ContentLicense: CC BY-SA 4.0

Body:
I need a create 4 cards with non-changable height with buttons on the bottom, but there are different text amount in each card.

Position Fixed is connected to body element,
position absolute scrolls with content,
position sticky appears when content ends.

https://codepen.io/anatoli101/pen/NVzbGY Here is a basic exemple of my problem

.content{
  display:flex;
  width: 100%;
  justify-content: space-around;
}

.fixed-div{
  background-color: red;
  height: 400px;
  width: 300px;
  overflow-y: auto;
}

.button{
  position:sticky;
  bottom:0;
  background-color: grey;
  width: 100%;
  height: 30px;
}

Body:
You can try code:

.fixed-div p{
   display: block;
   margin: 0;
   padding: 10px;
   height: 350px;
}

This is a demo: https://codepen.io/phuongnm153/pen/zQaobq


问:
Regex to replace multiple patterns with single not working
I am working on replacing multiple occurance of string 0000 with single random number in HANA SQL

I have used these patterns

'(\w+)\s+\1'

'([0000 ]+) \1'

but all occurrences are replaced except the last occurrence of the pattern

```<code>SELECT REPLACE_REGEXPR('(\w+)\s+\1' IN '0000 0000 0000' WITH ROUND(RAND()*1000) OCCURRENCE ALL) AS a2
FROM DUMMY;
</code>```

Current output is

```<code>RANDOM 0000
</code>```

expected output is

```<code>RANDOM
</code>```

答:
You may use

```<code>\b(\d+)(?:\s+\1)+\b
</code>```

See the regex demo

You need \d to match digits (if you need to match letters and _ keep on using \w).
Also, to match 1 or more repetitions of a sequence of patterns you need (?:....)+, a + quantified non-capturing group.

Pattern details

\b - word boundary

(\d+) - Group 1: one or more digits

(?:\s+\1)+ - 1+ repetitions of 1+ whitespaces and the same value as captured in Group 1

\b - word boundary

Regex graph:

Body:
I am working on replacing multiple occurance of string 0000 with single random number in HANA SQL

I have used these patterns

'(\w+)\s+\1'

'([0000 ]+) \1'

but all occurrences are replaced except the last occurrence of the pattern

SELECT REPLACE_REGEXPR('(\w+)\s+\1' IN '0000 0000 0000' WITH ROUND(RAND()*1000) OCCURRENCE ALL) AS a2
FROM DUMMY;

Current output is

RANDOM 0000

expected output is

RANDOM

Body:
You may use

\b(\d+)(?:\s+\1)+\b

See the regex demo

You need \d to match digits (if you need to match letters and _ keep on using \w).
Also, to match 1 or more repetitions of a sequence of patterns you need (?:....)+, a + quantified non-capturing group.

Pattern details

\b - word boundary

(\d+) - Group 1: one or more digits

(?:\s+\1)+ - 1+ repetitions of 1+ whitespaces and the same value as captured in Group 1

\b - word boundary

Regex graph:


问:
Put multiple values in arrays from cvs file
Values are separated with comma, following format:

```<code>Country,Timescale,Vendor,Units
Africa,2010 Q3,Fujitsu Siemens,2924.742632
</code>```

I want to make array for every value. How can I do it?

I tried many things, code below:

```<code>BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {

    br = new BufferedReader(new FileReader(csvFile));
    while ((line = br.readLine()) != null) {
        String[] country = line.split(cvsSplitBy);
        country[0] +=",";
        String[] Krajina = country[0].split(",");
</code>```

答:
Always try to use try-with-resources when using I/O

The following code should help you out:

```<code>String line = "";
String cvsSplitBy = ",";
List<String> countries = new ArrayList<>();
List<String> timeScales = new ArrayList<>();
List<String> vendors = new ArrayList<>();
List<String> units = new ArrayList<>();

//use try-with resources
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
  while ((line = br.readLine()) != null) {

    String[] parts = line.split(cvsSplitBy);
    countries.add(parts[0]);
    timeScales.add(parts[1]);
    vendors.add(parts[2]);
    units.add(parts[3]);
  }

}
catch (FileNotFoundException e) {
  e.printStackTrace();
}
catch (IOException e) {
  e.printStackTrace();
}

for (String country: countries) {
  System.out.println(country);
}

for (String scale: timeScales) {
  System.out.println(scale);
}

for (String vendor: vendors) {
  System.out.println(vendor);
}

for (String unit: units) {
  System.out.println(unit);
}
</code>```

Body:
Values are separated with comma, following format:

Country,Timescale,Vendor,Units
Africa,2010 Q3,Fujitsu Siemens,2924.742632

I want to make array for every value. How can I do it?

I tried many things, code below:

BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {

    br = new BufferedReader(new FileReader(csvFile));
    while ((line = br.readLine()) != null) {
        String[] country = line.split(cvsSplitBy);
        country[0] +=",";
        String[] Krajina = country[0].split(",");

Body:
Always try to use try-with-resources when using I/O

The following code should help you out:

String line = "";
String cvsSplitBy = ",";
List<String> countries = new ArrayList<>();
List<String> timeScales = new ArrayList<>();
List<String> vendors = new ArrayList<>();
List<String> units = new ArrayList<>();

//use try-with resources
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
  while ((line = br.readLine()) != null) {

    String[] parts = line.split(cvsSplitBy);
    countries.add(parts[0]);
    timeScales.add(parts[1]);
    vendors.add(parts[2]);
    units.add(parts[3]);
  }

}
catch (FileNotFoundException e) {
  e.printStackTrace();
}
catch (IOException e) {
  e.printStackTrace();
}

for (String country: countries) {
  System.out.println(country);
}

for (String scale: timeScales) {
  System.out.println(scale);
}

for (String vendor: vendors) {
  System.out.println(vendor);
}

for (String unit: units) {
  System.out.println(unit);
}


问:
Supported versions of nginx
Trustwave PCI (Payment Card Industry) compliance has just failed with 'The remote host is running a version of nginx that is no longer supported'. I am running the latest LTS version of ubuntu server 18.04 with the latest version of nginx 1.14.2.

I have looked on line, but I cant find a list of which versions of nginx are still supported/unsupported. I would like to find either a way to determine if 1.14.2 is supported, or an authoritative list to dispute the finding.

答: Thanks to @lex-li, everything listed under "legacy" is unsupported here, though I thought nginx 1.14.2 was the latest because using the ppa for a stable version of nginx, apt install was telling me that it was the latest version. Recently nginx must have changed their install so that if you want to upgrade past 1.14, you need to uninstall nginx, then follow the instructions here

Title: Supported versions of nginx


问:
grails 3.3: org.hibernate.TransientObjectException with findOrSaveWhere
In bootstrap.goovy, we need to create the static/test database records if they don't already exist (i.e. created when app was previously run)

```<code> def admin1 =  Operator.findOrSaveWhere(username: "admin", password: "test", firstName: "admin", lastName: "admin", email: "a@b.com")
</code>```

This creates the record if it doesn't exist, or read it if it does.  Great.

The problem comes when we want to use admin1 as a field in another sql statement, e.g.

```<code>  def note1 =  Note.findOrSaveWhere(user: user1, operator: operator1, note: "This is a note. Pretty dull. User is Boib. you can trust him 1")
</code>```

This fails with:

```<code>org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: come.me.myapp.Operator
</code>```

findOrSaveWhere presumably has just created the operator, but its not flushed to the DB.

normally, if you use admin1.save(flush:true), it would solve this issue. Is there a way to flush something created with findOrSaveWhere?

答:
You could use findOrCreateWhere:

```<code>def admin1 =  Operator.findOrCreateWhere( yadda:yadda, tadda:tadda )
if( !admin1.id ) admin.save flush:true
def note1 =  Note.findOrSaveWhere(user: admin1)
</code>```

Another option:

You should put your code in bootstrap in explicit transaction Operator.withTransaction{...} then your original code should work.

Body:
In bootstrap.goovy, we need to create the static/test database records if they don't already exist (i.e. created when app was previously run)

 def admin1 =  Operator.findOrSaveWhere(username: "admin", password: "test", firstName: "admin", lastName: "admin", email: "a@b.com")

This creates the record if it doesn't exist, or read it if it does.  Great.

The problem comes when we want to use admin1 as a field in another sql statement, e.g.

  def note1 =  Note.findOrSaveWhere(user: user1, operator: operator1, note: "This is a note. Pretty dull. User is Boib. you can trust him 1")

This fails with:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: come.me.myapp.Operator

findOrSaveWhere presumably has just created the operator, but its not flushed to the DB.

normally, if you use admin1.save(flush:true), it would solve this issue. Is there a way to flush something created with findOrSaveWhere?

Body:
You could use findOrCreateWhere:

def admin1 =  Operator.findOrCreateWhere( yadda:yadda, tadda:tadda )
if( !admin1.id ) admin.save flush:true
def note1 =  Note.findOrSaveWhere(user: admin1)

Another option:

You should put your code in bootstrap in explicit transaction Operator.withTransaction{...} then your original code should work.


问:
Where to put setInterval and clearInterval
I have a working slider. I would like to to autoplay the slides and stop the autoplay when user clicks the next or previous button.

I have tried to include setInterval-function but I am not sure how I should apply it in order to make it work. So far I did not manage to do this.

enter code here

var interleaveOffset = 0.2;

var swiperOptions = {
  loop: true,
  speed: 500,
  grabCursor: true,
  watchSlidesProgress: true,
  mousewheelControl: true,
  keyboardControl: true,
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev"
  },
  on: {
    progress: function() {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        var slideProgress = swiper.slides[i].progress;
        var innerOffset = swiper.width * interleaveOffset;
        var innerTranslate = slideProgress * innerOffset;
        swiper.slides[i].querySelector(".slide-inner").style.transform =
          "translate3d(" + innerTranslate + "px, 0, 0)";
      }
    },
    touchStart: function() {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        swiper.slides[i].style.transition = "";
      }
    },
    setTransition: function(speed) {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        swiper.slides[i].style.transition = speed + "ms";
        swiper.slides[i].querySelector(".slide-inner").style.transition =
          speed + "ms";
      }
    }
  }
};

var swiper = new Swiper(".swiper-container", swiperOptions);```

I expect that slider plays the slides automatically and the autoplay stops when user clicks either next or previous button.

答:
Use autoplay

```<code>autoplay: {
        delay: 2500,
        disableOnInteraction: true,
},
</code>```

disableOnInteraction will disable autoplay when you will click on arrows.

Body:
I have a working slider. I would like to to autoplay the slides and stop the autoplay when user clicks the next or previous button.

I have tried to include setInterval-function but I am not sure how I should apply it in order to make it work. So far I did not manage to do this.

enter code here

var interleaveOffset = 0.2;

var swiperOptions = {
  loop: true,
  speed: 500,
  grabCursor: true,
  watchSlidesProgress: true,
  mousewheelControl: true,
  keyboardControl: true,
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev"
  },
  on: {
    progress: function() {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        var slideProgress = swiper.slides[i].progress;
        var innerOffset = swiper.width * interleaveOffset;
        var innerTranslate = slideProgress * innerOffset;
        swiper.slides[i].querySelector(".slide-inner").style.transform =
          "translate3d(" + innerTranslate + "px, 0, 0)";
      }
    },
    touchStart: function() {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        swiper.slides[i].style.transition = "";
      }
    },
    setTransition: function(speed) {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        swiper.slides[i].style.transition = speed + "ms";
        swiper.slides[i].querySelector(".slide-inner").style.transition =
          speed + "ms";
      }
    }
  }
};

var swiper = new Swiper(".swiper-container", swiperOptions);

I expect that slider plays the slides automatically and the autoplay stops when user clicks either next or previous button.

Body:
Use autoplay

autoplay: {
        delay: 2500,
        disableOnInteraction: true,
},

disableOnInteraction will disable autoplay when you will click on arrows.


问:
How to Select between two periode of month and year eg: january 2018 - january 2019?
SQL query problem</p>

```<code>select *
from app_contract_hd
where year(created_datetime) between 2018 and 2018 and MONTH(created_datetime)between 4 and 4
</code>```

答:
you could try this</p>

```<code>SELECT * FROM APP_CONTRACT_HD

WHERE
(YEAR(CREATED_DATETIME) >=2018 AND MONTH(CREATED_DATETIME)>=1)

OR
(YEAR(CREATED_DATETIME) <=2019 AND MONTH(CREATED_DATETIME)<=1)
</code>```

Body:
SQL query problem

select *
from app_contract_hd
where year(created_datetime) between 2018 and 2018 and MONTH(created_datetime)between 4 and 4

Body:
you could try this

SELECT * FROM APP_CONTRACT_HD

WHERE
(YEAR(CREATED_DATETIME) >=2018 AND MONTH(CREATED_DATETIME)>=1)

OR
(YEAR(CREATED_DATETIME) <=2019 AND MONTH(CREATED_DATETIME)<=1)


答:
You have to define your arrays before processing your file :

```<code>String[] country = new String[30];
String[] timescale = new String[30];
String[] vendor = new String[30];
String[] units = new String[30];
</code>```

And while reading lines you have to put the values in the defined arrays with the same index, to keep the index use another variable and increase it at every iteration. It should look like this:

```<code>int index = 0;

while (true) {
    if (!((line = br.readLine()) != null)) break;
    String[] splitted = line.split(",");
    country[index] = splitted[0];
    timescale[index] = splitted[1];
    vendor[index] = splitted[2];
    units[index] = splitted[3];
    index++;
}
</code>```

Since your csv would probably include headers in it, you may also want to skip the first line too.

Title: Put multiple values in arrays from cvs file

Body:
You have to define your arrays before processing your file :

String[] country = new String[30];
String[] timescale = new String[30];
String[] vendor = new String[30];
String[] units = new String[30];

And while reading lines you have to put the values in the defined arrays with the same index, to keep the index use another variable and increase it at every iteration. It should look like this:

int index = 0;

while (true) {
    if (!((line = br.readLine()) != null)) break;
    String[] splitted = line.split(",");
    country[index] = splitted[0];
    timescale[index] = splitted[1];
    vendor[index] = splitted[2];
    units[index] = splitted[3];
    index++;
}

Since your csv would probably include headers in it, you may also want to skip the first line too.


问:
How to recover local files reset by git commands?
I had accidentally reset a repository on my git account. The heads or commits (can't remember properly) were further from the local files. Now, the files in the local repository have vanished and synced with the git account repository. Is there any way we can recover those files?

When I pushed files into the bitbucket account, it always used to get stuck on 57%. I searched through the internet and found git repo reset codes. This caused all the files after the previous commit to disappear from the local repository. Now, I don't have those files on both local and git repositories.

答:
Following codes should be able to solve such problems:

First use, git reflog to see all the commits.

Secondly, git reset --hard <commit_number_from_reflog>.

Then, git checkout -b <new_branch_name> <commit_number>.

Finally, git checkout <new_branch_name>.

These commands shall get your committed and unsaved files back.


问:
How do I prevent Selenium RC from stealing window focus while my tests are running?
I know I'm probably in a small minority, but I have to use my machine at the same time my tests are running. The thing that always gets in my way is that the browser window is always stealing focus when I run test cases using Selenium RC. Which prevents me from running my tests more than once a day, at the end of the day right before I log out. I tried Selenium Grid, but I can't get it to only listen for requests on localhost, not 0.0.0.0 (a requirement from my network admin).

I've dug through the Selenium documentation, and tons of Selenium sites, but I haven't been able to find a definitive answer. Can I prevent Selenium RC tests from Stealing windows focus while my test are running?

I'm using Firefox 3.6.13.

答: We can't do that in the same machine. Either we need VM or we should program it in the controller level so that our script will not launch any browser to run the scripts.</p>

ContentLicense: CC BY-SA 3.0


问:
Hibernate Criteria query doesn't give the complete result
```<code>Criteria criteria = createEntityCriteria().addOrder(Order.asc("dtname"));
ProjectionList projection = Projections.projectionList();
projection.add(Projections.distinct(Projections.property("dtncode")));
projection.add(Projections.property("dtname"));
criteria.setProjection(projection);
List<VillageMaster> villageMasters = (List<VillageMaster>)
criteria.list();
</code>```

I have written above code but code not giving the exact result.
Anyone please help me to resolve issue. Sql query is generated is as below:

```<code>select distinct this.dtncode as y0, this.dtname11 as y1
from village_master this
order by this.dtname11 asc
</code>```

答:
Use below code</p>

```<code>Criteria criteria = createEntityCriteria().addOrder(Order.asc("dtname"));
ProjectionList projection = Projections.projectionList();
projection.add(Projections.property("dtncode"));
projection.add(Projections.property("dtname"));
criteria.setProjection(Projections.distinct(projection));
List<VillageMaster> villageMasters = (List<VillageMaster>)
criteria.list();
</code>```

Body:
Criteria criteria = createEntityCriteria().addOrder(Order.asc("dtname"));
ProjectionList projection = Projections.projectionList();
projection.add(Projections.distinct(Projections.property("dtncode")));
projection.add(Projections.property("dtname"));
criteria.setProjection(projection);
List<VillageMaster> villageMasters = (List<VillageMaster>)
criteria.list();

I have written above code but code not giving the exact result.
Anyone please help me to resolve issue. Sql query is generated is as below:

select distinct this.dtncode as y0, this.dtname11 as y1
from village_master this
order by this.dtname11 asc

Body:
Use below code

Criteria criteria = createEntityCriteria().addOrder(Order.asc("dtname"));
ProjectionList projection = Projections.projectionList();
projection.add(Projections.property("dtncode"));
projection.add(Projections.property("dtname"));
criteria.setProjection(Projections.distinct(projection));
List<VillageMaster> villageMasters = (List<VillageMaster>)
criteria.list();


问:
Make all the elemant zero except max n element in each row in numpy 2d-array
Let's say I have a 2D numpy array like:

```<code>[[1, 8, 3, 4, 5],
 [10,13,13,12,15]]
</code>```

I want to convert all the elements to zero except the maximum or maximum 2 elements in each row. The output I'd like to get is:

```<code>[[0, 8, 0,0, 5],
 [0,13,13,0,15]]
</code>```

How can I do this?

答:
For solving this problem, we need to sort your data. If x is your numpy array data, at the first we sort it.

```<code>import numpy as np
x = np.array([[1,8,3,4,5],[10,13,13,12,15]])
x.sort()
</code>```

After sorting only two final elements of each rows show max values. So, we zero value is lied for another elements and we save x in f.

```<code>for i in range(0,len(x)):
    x[i][0:-2]=0
f = x
</code>```

Then, f is:

```<code>array([[ 0,  0,  0,  5,  8],
       [ 0,  0,  0, 13, 15]])
</code>```

Now we needinitial x and f:

```<code>x = np.array([[1,8,3,4,5],[10,13,13,12,15]])
</code>```

x is:

```<code>array([[ 0,  8,  0,  0,  5],
       [ 0, 13, 13,  0, 15]])
</code>```

Finally, we compare x and f for reach to our goal:

```<code>for i in range(0,len(f)):
    for j in range(0,len(f[i])):
        if x[i][j] not in f[i]:
            x[i][j]=0
</code>```

RESULT for x will be like this:

```<code>array([[ 0,  8,  0,  0,  5],
       [ 0, 13, 13,  0, 15]])
</code>```

Body:
Let's say I have a 2D numpy array like:

[[1, 8, 3, 4, 5],
 [10,13,13,12,15]]

I want to convert all the elements to zero except the maximum or maximum 2 elements in each row. The output I'd like to get is:

[[0, 8, 0,0, 5],
 [0,13,13,0,15]]

How can I do this?

Body:
For solving this problem, we need to sort your data. If x is your numpy array data, at the first we sort it.

import numpy as np
x = np.array([[1,8,3,4,5],[10,13,13,12,15]])
x.sort()

After sorting only two final elements of each rows show max values. So, we zero value is lied for another elements and we save x in f.

for i in range(0,len(x)):
    x[i][0:-2]=0
f = x

Then, f is:

array([[ 0,  0,  0,  5,  8],
       [ 0,  0,  0, 13, 15]])

Now we needinitial x and f:

x = np.array([[1,8,3,4,5],[10,13,13,12,15]])

x is:

array([[ 0,  8,  0,  0,  5],
       [ 0, 13, 13,  0, 15]])

Finally, we compare x and f for reach to our goal:

for i in range(0,len(f)):
    for j in range(0,len(f[i])):
        if x[i][j] not in f[i]:
            x[i][j]=0

RESULT for x will be like this:

array([[ 0,  8,  0,  0,  5],
       [ 0, 13, 13,  0, 15]])


问:
Node Exporter bind address is already running
Node Exporter is always running on my local machine on localhost:9100 even if I don't execute it with terminal following this error message:

```FATA[0000] listen tcp :9100: bind: address already in use  source="node_exporter.go:172"```

By which I can understand that this port number is already being used by another application but the thing is I don't have anything hosted there.
This is what netstat | grep 9100 gives:

```
tcp        0      0 localhost:60232         localhost:9100          ESTABLISHED
tcp6       0      0 localhost:9100          localhost:60232         ESTABLISHED
```

答: All I had to do was to "kill" the 9100 port in which Node Exporter was running by using fuser -k 9100/tcp as this was shown on How to kill a process running on particular port in Linux?.

Body:
Node Exporter is always running on my local machine on localhost:9100 even if I don't execute it with terminal following this error message:

FATA[0000] listen tcp :9100: bind: address already in use  source="node_exporter.go:172"

By which I can understand that this port number is already being used by another application but the thing is I don't have anything hosted there.
This is what netstat | grep 9100 gives:

tcp        0      0 localhost:60232         localhost:9100          ESTABLISHED
tcp6       0      0 localhost:9100          localhost:60232         ESTABLISHED


问:
WebView in RecyclerView show false data
I used WebView to load data html for each item of RecyclerView.
I have problems when did it:

Some time WebView display fail data. When I scrolling RecyclerView some item will show data of another item.[Solved]

Height of webview fail. Some item will hold height of another item in RecyclerVew.

How I can fix them?
Here is my adapter:

class ParentAdapter extends RecyclerView.Adapter<ParentAdapter.MyViewHolder> {
    private String[] urlList;
    public ParentAdapter(String[] urlList) {
        this.urlList = urlList;
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row_my_web, parent, false);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final @NonNull MyViewHolder holder, int position) {
        holder.myWebView.loadData(content + styleWebView, "text/html", "UTF-8");
    }

    @Override
    public int getItemCount() {
        return urlList.length;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        WebView myWebView;
        TextView tv;

        MyViewHolder(View itemView) {
            super(itemView);
            myWebView = itemView.findViewById(R.id.myWebView);
            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            webSettings.setAppCacheEnabled(false);
            myWebView.setWebChromeClient(new WebChromeClient());
            myWebView.addJavascriptInterface(new WebAppInterface(myWebView.getContext()), "Android");
            myWebView.setWebViewClient(new WebViewClient());
        }
    }

    class WebAppInterface {
        Context mContext;

        WebAppInterface1(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void clickMention(String idMention) {
            Toast.makeText(mContext, idMention, Toast.LENGTH_SHORT).show();
        }

        @JavascriptInterface
        public void clickPhone(String phone) {
            Toast.makeText(mContext, phone, Toast.LENGTH_SHORT).show();
        }

        @JavascriptInterface
        public void clickEmail(String phone) {
            Toast.makeText(mContext, phone, Toast.LENGTH_SHORT).show();
        }
    }```
</div>
</div>

My <code>row_my_web.xml</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#888585"
    android:orientation="vertical"
    android:paddingBottom="10dp">
    <WebView
        android:id="@+id/myWebView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff" />
</LinearLayout></code>```

答:
Answer to your first question :

Try this solution :

RecyclerView items duplicate and constantly changing

Maybe this solution will fix your second problem as well. Do let me know if not solved !

Title: WebView in RecyclerView show false data

Body:
I used WebView to load data html for each item of RecyclerView.
I have problems when did it:

Some time WebView display fail data. When I scrolling RecyclerView some item will show data of another item.[Solved]

Height of webview fail. Some item will hold height of another item in RecyclerVew.

How I can fix them?
Here is my adapter:

class ParentAdapter extends RecyclerView.Adapter<ParentAdapter.MyViewHolder> {
    private String[] urlList;
    public ParentAdapter(String[] urlList) {
        this.urlList = urlList;
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row_my_web, parent, false);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final @NonNull MyViewHolder holder, int position) {
        holder.myWebView.loadData(content + styleWebView, "text/html", "UTF-8");
    }

    @Override
    public int getItemCount() {
        return urlList.length;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        WebView myWebView;
        TextView tv;

        MyViewHolder(View itemView) {
            super(itemView);
            myWebView = itemView.findViewById(R.id.myWebView);
            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            webSettings.setAppCacheEnabled(false);
            myWebView.setWebChromeClient(new WebChromeClient());
            myWebView.addJavascriptInterface(new WebAppInterface(myWebView.getContext()), "Android");
            myWebView.setWebViewClient(new WebViewClient());
        }
    }

    class WebAppInterface {
        Context mContext;

        WebAppInterface1(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void clickMention(String idMention) {
            Toast.makeText(mContext, idMention, Toast.LENGTH_SHORT).show();
        }

        @JavascriptInterface
        public void clickPhone(String phone) {
            Toast.makeText(mContext, phone, Toast.LENGTH_SHORT).show();
        }

        @JavascriptInterface
        public void clickEmail(String phone) {
            Toast.makeText(mContext, phone, Toast.LENGTH_SHORT).show();
        }
    }

My row_my_web.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#888585"
    android:orientation="vertical"
    android:paddingBottom="10dp">
    <WebView
        android:id="@+id/myWebView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff" />
</LinearLayout>


答: use position: relative; for the parent (fixed-div) and position:absolute;bottom:0; for the child (button)

Title: Fixed div on the bottom of the scrollable div

Body:
I need a create 4 cards with non-changable height with buttons on the bottom, but there are different text amount in each card.

Position Fixed is connected to body element,
position absolute scrolls with content,
position sticky appears when content ends.

https://codepen.io/anatoli101/pen/NVzbGY Here is a basic exemple of my problem

.content{
  display:flex;
  width: 100%;
  justify-content: space-around;
}

.fixed-div{
  background-color: red;
  height: 400px;
  width: 300px;
  overflow-y: auto;
}

.button{
  position:sticky;
  bottom:0;
  background-color: grey;
  width: 100%;
  height: 30px;
}


问:
Validator textarea does not work and always returns false
I am trying to use kendo UI validator over a textarea using validateinput but always returns false. This Dojo contains the script.

Thanks for your help.

https://dojo.telerik.com/ifIhEGIy

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Untitled</title>

  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.514/styles/kendo.common.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.514/styles/kendo.rtl.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.514/styles/kendo.default.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.2.514/styles/kendo.mobile.all.min.css">

<form id="hechoForm">

<textarea rows="10" cols="30" id="txtDescripcion" name="txtDescripcion"></textarea>

  <button onclick="validateFormHecho()">Click me</button>

</form>

```

答: There simple is not input element with that id. If you search for any element with that id, you get your true: alert(validator.validateInput($("#txtDescripcion")));


问:
Property displayed as undefined in React Component - Retrieve props.match and additional property in component
I have an index.js from which i am calling a Component like this

```<code>const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" component={MyComponent} prop1={prop1}/>
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);
</code>```

But in MyComponent.js, this.props.prop1 is displayed as undefined. Any idea why ?
I need to able to get this.props.match.params and prop1

答:
This will pass match, location, history and custom prop to new component.

```<code>const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" render={(props) => <MyComponent {...props} prop1={prop1} />} />
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);
</code>```

Code Sandbox link

Body:
I have an index.js from which i am calling a Component like this

const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" component={MyComponent} prop1={prop1}/>
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);

But in MyComponent.js, this.props.prop1 is displayed as undefined. Any idea why ?
I need to able to get this.props.match.params and prop1

Body:
This will pass match, location, history and custom prop to new component.

const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" render={(props) => <MyComponent {...props} prop1={prop1} />} />
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);

Code Sandbox link


问:
Adding +1 to multiple values in one cell via excel formula
I got an excel file with a data source sheet. To be able to parse the data at the next step I need to add 1 to every value and get it into a new sheet. The thing is, that there are multiple values per cell, each separated by comma, and this number is not static. Adding the +1 at a later point is sadly not an option so I need to do this in excel.</p>

```<code>  Source sheet              Prepared data sheet

| MyValues   |             | MyValues + 1 |
|------------|             |--------------|
| 0,1,2,3    |             |  1,2,3,4     |
| 3          |   ----->    |  4           |
| 2,4,6      |             |  3,5,7       |
| 1          |             |  2           |
</code>```

答:
I try to create a VBA code (i know that VBA is not tagged) to fulfill this task.

```<code>Option Explicit

Sub test()

    Dim LastRow As Long, i As Long, Count As Long, j As Long
    Dim str As Variant, strNew As String

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 1 To LastRow

            Count = Len(.Range("A" & i).Value) - Len(Replace(.Range("A" & i).Value, ",", ""))
            str = Split(.Range("A" & i).Value, ",")

            If Count > 0 Then

                For j = 0 To Count

                    str(j) = str(j) + 1

                    If .Range("B" & i).Value = "" Then
                        .Range("B" & i).Value = str(j)
                    Else
                        .Range("B" & i).Value = .Range("B" & i).Value & "," & str(j)
                    End If

                Next j

            Else

                .Range("B" & i).Value = .Range("A" & i).Value + 1

            End If

        Next i

    End With

End Sub
</code>```

Results:

Body:
I got an excel file with a data source sheet. To be able to parse the data at the next step I need to add 1 to every value and get it into a new sheet. The thing is, that there are multiple values per cell, each separated by comma, and this number is not static. Adding the +1 at a later point is sadly not an option so I need to do this in excel.

  Source sheet              Prepared data sheet

| MyValues   |             | MyValues + 1 |
|------------|             |--------------|
| 0,1,2,3    |             |  1,2,3,4     |
| 3          |   ----->    |  4           |
| 2,4,6      |             |  3,5,7       |
| 1          |             |  2           |

Body:
I try to create a VBA code (i know that VBA is not tagged) to fulfill this task.

Option Explicit

Sub test()

    Dim LastRow As Long, i As Long, Count As Long, j As Long
    Dim str As Variant, strNew As String

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 1 To LastRow

            Count = Len(.Range("A" & i).Value) - Len(Replace(.Range("A" & i).Value, ",", ""))
            str = Split(.Range("A" & i).Value, ",")

            If Count > 0 Then

                For j = 0 To Count

                    str(j) = str(j) + 1

                    If .Range("B" & i).Value = "" Then
                        .Range("B" & i).Value = str(j)
                    Else
                        .Range("B" & i).Value = .Range("B" & i).Value & "," & str(j)
                    End If

                Next j

            Else

                .Range("B" & i).Value = .Range("A" & i).Value + 1

            End If

        Next i

    End With

End Sub

Results:


问:
How do i retain parent values when using Save & New Button
I have enabled the SaveAndNew button using Ribbon Workbench but users are requesting that the related forms retain certain values from the parent record when a new form is created. Is there a way using JS which can getValues prior to OnSave and SetValues OnLoad (without erroring the standard Save/Save&Close functions).

I am using Dynamics 365 Online - The entities in question already have 1:n relationships but after the first form create, the parent mappings are lost. Please help...

答:
From the SDK (V9.0):</p>

```<code>var entityFormOptions = {};
entityFormOptions["entityName"] = "contact";

// Set default values for the Contact form
var formParameters = {};
formParameters["firstname"] = "Sample";
formParameters["lastname"] = "Contact";
formParameters["fullname"] = "Sample Contact";
formParameters["emailaddress1"] = "contact@adventure-works.com";
formParameters["jobtitle"] = "Sr. Marketing Manager";
formParameters["donotemail"] = "1";
formParameters["description"] = "Default values for this record were set     programmatically.";

// Open the form.
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
        console.log(success);
},
function (error) {
    console.log(error);
});

//Old versions:
Xrm.Utility.openEntityForm("contact", null, formParameters);
</code>```

Body:
From the SDK (V9.0):

var entityFormOptions = {};
entityFormOptions["entityName"] = "contact";

// Set default values for the Contact form
var formParameters = {};
formParameters["firstname"] = "Sample";
formParameters["lastname"] = "Contact";
formParameters["fullname"] = "Sample Contact";
formParameters["emailaddress1"] = "contact@adventure-works.com";
formParameters["jobtitle"] = "Sr. Marketing Manager";
formParameters["donotemail"] = "1";
formParameters["description"] = "Default values for this record were set     programmatically.";

// Open the form.
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
        console.log(success);
},
function (error) {
    console.log(error);
});

//Old versions:
Xrm.Utility.openEntityForm("contact", null, formParameters);


问:
Python Hangman not ending when player guesses all letters
My problem is that when I run the program and get all the letters correct, it does not move on from there and I'm in an infinite loop. I expect it to say "Good Job!" and end the program when the player gets the word right. I am very new to coding, and would greatly appreciate any help.</p>

```<code>import random
import time

name = input("What is your name? ")
print(name + ", ay?")
time.sleep(1)
start = input("Up for a game of Hangman?(y/n) ")

lis = random.choice(["yet"])
dash = []
while len(dash) != len(lis):
   dash.append("_")
guess = []
guesscomb = "".join(guess)
wrongcount=int(0)
alphabet = "abcdefghijklmnopqrstuvwxyz"

if start == "y":
    print("One game of Hangman comin' right up,",name)
    letter = input("Alright then, Guess a letter: ")
    thing = ''.join(dash)

    while guesscomb != thing:
        if letter == "" or letter == " " or len(letter) != 1:
            print("I don't understand. Please only use singular letters.")
            letter = input("Guess a letter: ")

        elif letter in lis and letter in alphabet:
            print("Nice!")

            location = lis.find(letter)
            dash[location] = letter
            guess.append(letter)
            alphabet.replace(letter," ")
            guesscomb = "".join(guess)

            letter = input("Guess a letter: ")

        else:
            print("Wrong.")
            wrongcount = wrongcount + 1

            print("Total Mistakes:",wrongcount)
            letter = input("Guess a letter: ")

elif start == "n":
    input("Shame.")
    quit()

print("Good Job!")
time.sleep(10)
</code>```

答:
The thing variable is equal to ___ while lis is always equal to "yet".

guesscomb cannot be equal to thing as you validate a letter when the guess is equal to a letter in lis

Body:
My problem is that when I run the program and get all the letters correct, it does not move on from there and I'm in an infinite loop. I expect it to say "Good Job!" and end the program when the player gets the word right. I am very new to coding, and would greatly appreciate any help.

import random
import time

name = input("What is your name? ")
print(name + ", ay?")
time.sleep(1)
start = input("Up for a game of Hangman?(y/n) ")

lis = random.choice(["yet"])
dash = []
while len(dash) != len(lis):
   dash.append("_")
guess = []
guesscomb = "".join(guess)
wrongcount=int(0)
alphabet = "abcdefghijklmnopqrstuvwxyz"

if start == "y":
    print("One game of Hangman comin' right up,",name)
    letter = input("Alright then, Guess a letter: ")
    thing = ''.join(dash)

    while guesscomb != thing:
        if letter == "" or letter == " " or len(letter) != 1:
            print("I don't understand. Please only use singular letters.")
            letter = input("Guess a letter: ")

        elif letter in lis and letter in alphabet:
            print("Nice!")

            location = lis.find(letter)
            dash[location] = letter
            guess.append(letter)
            alphabet.replace(letter," ")
            guesscomb = "".join(guess)

            letter = input("Guess a letter: ")

        else:
            print("Wrong.")
            wrongcount = wrongcount + 1

            print("Total Mistakes:",wrongcount)
            letter = input("Guess a letter: ")

elif start == "n":
    input("Shame.")
    quit()

print("Good Job!")
time.sleep(10)


问:
Excel Userform animated dots on loading
There are a lot of tutorials in the Internet. However I was not able to find anything suitable. Is there any way to make animated dots on loading?

The idea is to make a loop of animated dots ..... on userform so they would appear one after another and then would start over after some amount of dots.

So I input a dot to Label1 and move it to left after certain time criteria?

My current code for UserForm:

```<code>    Private Sub UserForm_Initialize()
HideTitleBar.HideTitleBar Me
    Call loadingdots
End Sub
</code>```

Code for Private Sub Workbook_Open():

```<code>Loading.Show (vbModeless)

Dim RngCom As Range
Dim RngTurb As Range
Dim RngGen As Range

Application.Wait (Now + TimeValue("00:00:06"))

ThisWorkbook.Worksheets("MAIN").ScrollArea = "$A$1:$BL$45"
    Application.DisplayFormulaBar = False
    ActiveWindow.DisplayHeadings = False
    ActiveWindow.DisplayGridlines = False
  etc...
  Unload Loading
'Application.ScreenUpdating = True
  End Sub
</code>```

答:
The most elegant solution would likely to be the OnTime method.

Place a label inside your UF and remove the caption. Next, in a regular module (so not that of the UF), place this subroutine:

```<code>'this function ensures the self-activating sub will stop if the UF has been closed
Public Function IsLoaded(form As String) As Boolean
Dim frm As Object
For Each frm In VBA.UserForms
    If frm.Name = form Then
        IsLoaded = True
        Exit Function
    End If
Next frm
IsLoaded = False
End Function

Public Sub loadingdots()

If IsLoaded("UserForm1") = True Then
    If Len(UserForm1.Label1.Caption = 4) Then
        UserForm1.Label1.Caption = "."
    Else
        UserForm1.Label1.Caption = UserForm1.Label1.Caption & "."
    End If
    Application.OnTime Now + TimeValue("00:00:01"), "loadingdots"
End If

End Sub
</code>```

Next, call the self-activating sub when the UF gets initialised

```<code>Private Sub UserForm_Initialize()
    Call loadingdots
End Sub
</code>```

Do not forget to change the references to the UF to the right name.

Title: Excel Userform animated dots on loading

Body:
There are a lot of tutorials in the Internet. However I was not able to find anything suitable. Is there any way to make animated dots on loading?

The idea is to make a loop of animated dots ..... on userform so they would appear one after another and then would start over after some amount of dots.

So I input a dot to Label1 and move it to left after certain time criteria?

My current code for UserForm:

    Private Sub UserForm_Initialize()
HideTitleBar.HideTitleBar Me
    Call loadingdots
End Sub

Code for Private Sub Workbook_Open():

Loading.Show (vbModeless)

Dim RngCom As Range
Dim RngTurb As Range
Dim RngGen As Range

Application.Wait (Now + TimeValue("00:00:06"))

ThisWorkbook.Worksheets("MAIN").ScrollArea = "$A$1:$BL$45"
    Application.DisplayFormulaBar = False
    ActiveWindow.DisplayHeadings = False
    ActiveWindow.DisplayGridlines = False
  etc...
  Unload Loading
'Application.ScreenUpdating = True
  End Sub

Body:
The most elegant solution would likely to be the OnTime method.

Place a label inside your UF and remove the caption. Next, in a regular module (so not that of the UF), place this subroutine:

'this function ensures the self-activating sub will stop if the UF has been closed
Public Function IsLoaded(form As String) As Boolean
Dim frm As Object
For Each frm In VBA.UserForms
    If frm.Name = form Then
        IsLoaded = True
        Exit Function
    End If
Next frm
IsLoaded = False
End Function

Public Sub loadingdots()

If IsLoaded("UserForm1") = True Then
    If Len(UserForm1.Label1.Caption = 4) Then
        UserForm1.Label1.Caption = "."
    Else
        UserForm1.Label1.Caption = UserForm1.Label1.Caption & "."
    End If
    Application.OnTime Now + TimeValue("00:00:01"), "loadingdots"
End If

End Sub

Next, call the self-activating sub when the UF gets initialised

Private Sub UserForm_Initialize()
    Call loadingdots
End Sub

Do not forget to change the references to the UF to the right name.


问:
Unable to set AudioSession inactive with AVPlayer
I am using an AVPlayer to playback audio in my iOS app (because the audio files I'm playing are not local), and when my track finishes, I want to hide the InfoCenter controls, but I get this error:

AVAudioSession.mm:1079:-[AVAudioSession setActive:withOptions:error:]: Deactivating an audio session that has running I/O. All I/O should be stopped or paused prior to deactivating the audio session.

I am however pausing my AVPlayer before.

This is my code:

player.pause()
player.replaceCurrentItem(with: nil)

MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
try? audioSession.setActive(false, options: .notifyOthersOnDeactivation)
```

Due to this error, the native controls remain visible, but don't work anymore.

答:
A quick way to lose the lock screen controls is to make your audio session mixable (without deactivating your audio session):

```<code>try! AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)
</code>```

Remove the .mixWithOthers when you want them back.

Another, perhaps more palatable way is to remove your MPRemoteCommandCenter targets once you pause playback. e.g. if you set it up like this

```<code>var playTarget: Any? = nil
var pauseTarget: Any? = nil

func addRemoteTargets() {
    let commandCenter = MPRemoteCommandCenter.shared()

    playTarget = commandCenter.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
        print("play \(event)")
        return .success
    }

    pauseTarget = commandCenter.pauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
        print("pause \(event)")
        return .success
    }
}
</code>```

Then remove the targets like so:

```<code>func removeRemoteTargets() {
    let commandCenter = MPRemoteCommandCenter.shared()
    commandCenter.playCommand.removeTarget(playTarget)
    playTarget = nil
    commandCenter.pauseCommand.removeTarget(pauseTarget)
    pauseTarget = nil
}
</code>```

p.s. these are "seems to work!" answers. I don't know how you are supposed to determine when an AVPlayer has finished its audio I/O (apart from polling via setActive:false failing). My reasoning is that becoming the lock screen/"Now Playing App" has 3 pieces (this is sort of documented somewhere, this is the closest thing I can find to that right now, although the most explicit documentation of how this works is in the system logs):

a non mixable audio session category

MPRemoteCommandCenter integration

current or "recently" finished audio IO

so if you can remove any one of these pieces, the lock screen controls should go away.

Body:
I am using an AVPlayer to playback audio in my iOS app (because the audio files I'm playing are not local), and when my track finishes, I want to hide the InfoCenter controls, but I get this error:

AVAudioSession.mm:1079:-[AVAudioSession setActive:withOptions:error:]: Deactivating an audio session that has running I/O. All I/O should be stopped or paused prior to deactivating the audio session.

I am however pausing my AVPlayer before.

This is my code:

player.pause()
player.replaceCurrentItem(with: nil)

MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
try? audioSession.setActive(false, options: .notifyOthersOnDeactivation)

Due to this error, the native controls remain visible, but don't work anymore.

Body:
A quick way to lose the lock screen controls is to make your audio session mixable (without deactivating your audio session):

try! AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)

Remove the .mixWithOthers when you want them back.

Another, perhaps more palatable way is to remove your MPRemoteCommandCenter targets once you pause playback. e.g. if you set it up like this

var playTarget: Any? = nil
var pauseTarget: Any? = nil

func addRemoteTargets() {
    let commandCenter = MPRemoteCommandCenter.shared()

    playTarget = commandCenter.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
        print("play \(event)")
        return .success
    }

    pauseTarget = commandCenter.pauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
        print("pause \(event)")
        return .success
    }
}

Then remove the targets like so:

func removeRemoteTargets() {
    let commandCenter = MPRemoteCommandCenter.shared()
    commandCenter.playCommand.removeTarget(playTarget)
    playTarget = nil
    commandCenter.pauseCommand.removeTarget(pauseTarget)
    pauseTarget = nil
}

p.s. these are "seems to work!" answers. I don't know how you are supposed to determine when an AVPlayer has finished its audio I/O (apart from polling via setActive:false failing). My reasoning is that becoming the lock screen/"Now Playing App" has 3 pieces (this is sort of documented somewhere, this is the closest thing I can find to that right now, although the most explicit documentation of how this works is in the system logs):

a non mixable audio session category

MPRemoteCommandCenter integration

current or "recently" finished audio IO

so if you can remove any one of these pieces, the lock screen controls should go away.


问:
Define a custom InjectionResolver for @Inject
My goal is to add some additional logic around the System Injection Resolver (to decorate it, so to speak). Basically, I want to register a custom injection resolver (e.g. described here), but for the javax.inject.@Inject Annotation. The setup works if I create a different custom annotation, but not when using @Inject. My implementation is as follows:

Injection Resolver:

```<code>@Singleton
@Rank(Integer.MAX_VALUE)
public class InjectInjectionResolver
    implements InjectionResolver<Inject> {

    private final InjectionResolver<Inject> injectionResolver;

    @Inject
    public InjectInjectionResolver(
            @Named(InjectionResolver.SYSTEM_RESOLVER_NAME) final InjectionResolver<Inject> injectionResolver) {
        this.injectionResolver = injectionResolver;
    }

    @Override
    public Object resolve(final Injectee injectee, final ServiceHandle<?> root) {
        throw new RuntimeException("Why is this never called?");
    }

    @Override
    public boolean isConstructorParameterIndicator() {
        return injectionResolver.isConstructorParameterIndicator();
    }

    @Override
    public boolean isMethodParameterIndicator() {
        return injectionResolver.isMethodParameterIndicator();
    }
}
</code>```

And I register the resolver as follows (inside ResourceConfig):

```<code>register(new AbstractBinder() {

        @Override
        protected void configure() {
            bind(InjectInjectionResolver.class).to(new GenericType<InjectionResolver<Inject>>() {}).in(Singleton.class);
        }
    });
</code>```

What I tried so far:

using @Rank

using both the org.glassfish.jersey.internal.inject.AbstractBinder or org.glassfish.hk2.utilities.binding.AbstractBinder with TypeLiteral, along with implementing the org.glassfish.hk2.api.InjectionResolver or org.glassfish.jersey.internal.inject.InjectionResolver

making sure the same setup works with @CustomAnnotation (where both the constructor and the resolve methods are called)

Does anyone know how to solve this issue?

Versions used: jersey 2.27

EDIT: When I @Inject the InjectionResolver itself, it seems that hk2's org.jvnet.hk2.internal.ThreeThirtyResolver is injected for the org.glassfish.hk2.api.InjectionResolver, while my custom injection resolver is injected for org.glassfish.jersey.internal.inject.InjectionResolver. However, the custom injection resolver is not used for injection.

答:
The following configuration works for me, thanks to @jwells131313 for bringing me back on track. I tried to use fully qualified names, else it's probably from the javax.inject.* package.

```<code>@Singleton
@Rank(Integer.MAX_VALUE)
@org.jvnet.hk2.annotations.Service
public class MyHk2InjectionResolver
    implements org.glassfish.hk2.api.InjectionResolver<Inject> {

    private final org.glassfish.hk2.api.InjectionResolver<Inject> injectionResolver;

    @Inject
    public MyHk2InjectionResolver(
        @Named(org.glassfish.hk2.api.InjectionResolver.SYSTEM_RESOLVER_NAME) final org.glassfish.hk2.api.InjectionResolver<Inject> injectionResolver) {
        this.injectionResolver = injectionResolver;
    }

    // ... required methods, could just delegate to system resolver

}
</code>```

To register the resolver, we bind it to the correct type (I do it in the ResourceConfig of a jersey application):

```<code>register(new org.glassfish.hk2.utilities.binding.AbstractBinder() {

        @Override
        protected void configure() {
            bind(MyHk2InjectionResolver.class)
                    .to(new org.glassfish.hk2.api.TypeLiteral<org.glassfish.hk2.api.InjectionResolver<Inject>>() {})
                    .in(Singleton.class);
        }
    });
</code>```

With this setup, you can keep using the @Inject annotation and write some custom injection logic around it, possibly using the default system injection resolver as a fallback.

Body:
My goal is to add some additional logic around the System Injection Resolver (to decorate it, so to speak). Basically, I want to register a custom injection resolver (e.g. described here), but for the javax.inject.@Inject Annotation. The setup works if I create a different custom annotation, but not when using @Inject. My implementation is as follows:

Injection Resolver:

@Singleton
@Rank(Integer.MAX_VALUE)
public class InjectInjectionResolver
    implements InjectionResolver<Inject> {

    private final InjectionResolver<Inject> injectionResolver;

    @Inject
    public InjectInjectionResolver(
            @Named(InjectionResolver.SYSTEM_RESOLVER_NAME) final InjectionResolver<Inject> injectionResolver) {
        this.injectionResolver = injectionResolver;
    }

    @Override
    public Object resolve(final Injectee injectee, final ServiceHandle<?> root) {
        throw new RuntimeException("Why is this never called?");
    }

    @Override
    public boolean isConstructorParameterIndicator() {
        return injectionResolver.isConstructorParameterIndicator();
    }

    @Override
    public boolean isMethodParameterIndicator() {
        return injectionResolver.isMethodParameterIndicator();
    }
}

And I register the resolver as follows (inside ResourceConfig):

register(new AbstractBinder() {

        @Override
        protected void configure() {
            bind(InjectInjectionResolver.class).to(new GenericType<InjectionResolver<Inject>>() {}).in(Singleton.class);
        }
    });

What I tried so far:

using @Rank

using both the org.glassfish.jersey.internal.inject.AbstractBinder or org.glassfish.hk2.utilities.binding.AbstractBinder with TypeLiteral, along with implementing the org.glassfish.hk2.api.InjectionResolver or org.glassfish.jersey.internal.inject.InjectionResolver

making sure the same setup works with @CustomAnnotation (where both the constructor and the resolve methods are called)

Does anyone know how to solve this issue?

Versions used: jersey 2.27

EDIT: When I @Inject the InjectionResolver itself, it seems that hk2's org.jvnet.hk2.internal.ThreeThirtyResolver is injected for the org.glassfish.hk2.api.InjectionResolver, while my custom injection resolver is injected for org.glassfish.jersey.internal.inject.InjectionResolver. However, the custom injection resolver is not used for injection.

Body:
The following configuration works for me, thanks to @jwells131313 for bringing me back on track. I tried to use fully qualified names, else it's probably from the javax.inject.* package.

@Singleton
@Rank(Integer.MAX_VALUE)
@org.jvnet.hk2.annotations.Service
public class MyHk2InjectionResolver
    implements org.glassfish.hk2.api.InjectionResolver<Inject> {

    private final org.glassfish.hk2.api.InjectionResolver<Inject> injectionResolver;

    @Inject
    public MyHk2InjectionResolver(
        @Named(org.glassfish.hk2.api.InjectionResolver.SYSTEM_RESOLVER_NAME) final org.glassfish.hk2.api.InjectionResolver<Inject> injectionResolver) {
        this.injectionResolver = injectionResolver;
    }

    // ... required methods, could just delegate to system resolver

}

To register the resolver, we bind it to the correct type (I do it in the ResourceConfig of a jersey application):

register(new org.glassfish.hk2.utilities.binding.AbstractBinder() {

        @Override
        protected void configure() {
            bind(MyHk2InjectionResolver.class)
                    .to(new org.glassfish.hk2.api.TypeLiteral<org.glassfish.hk2.api.InjectionResolver<Inject>>() {})
                    .in(Singleton.class);
        }
    });

With this setup, you can keep using the @Inject annotation and write some custom injection logic around it, possibly using the default system injection resolver as a fallback.


问:
How do I check if each UITextField in an Array has a user input?
I have a list of UITextFields in an Array for users to key in phone numbers. When I click the Send Button, it will connect with my server to send an automated message to the numbers listed. This portion works well. What I want to do now is to check which of the UITextFields has a phone number in it and to check if it has the prefix + before it connects to my server. If any of the UITextField has a phone number without the prefix +, the border color of that UITextField should change colours. If the UITextField does not have a phone number, no action should be taken. How do I go about achieving that?

This is the portion of the code that I need help in

```<code>
    @IBAction func sendbutton(_ sender: Any) {

        var numArray: Array<Any>

        numArray = [phonenumber.text!, phonenumber1.text!, phonenumber2.text!, phonenumber3.text!]

        let myColor = UIColor.red

        for num in numArray {
            if (num as AnyObject).hasPrefix("+") {
                print("Has + symbol")

            } else {
                print("Does Not Have Symbol")

            }
        }

</code>```

答:
I don't think you should loop over an array of strings, instead loop over the text fields so you can set the color directly</p>

```<code>var textFields: Array<UITextField> = [phonenumber, phonenumber1, phonenumber2, phonenumber3]
var numbersToSend = [String]()
let myColor = UIColor.red

for textField in textFields {
    let number = textField.text ?? ""
    if validatePhoneNumber(number) { //extract validation into separate function for clarity
        numbersToSend.append(number)
    } else {
        textField.backgroundColor = myColor //or whatever property you want to change
    }
}
</code>```

Body:
I have a list of UITextFields in an Array for users to key in phone numbers. When I click the Send Button, it will connect with my server to send an automated message to the numbers listed. This portion works well. What I want to do now is to check which of the UITextFields has a phone number in it and to check if it has the prefix + before it connects to my server. If any of the UITextField has a phone number without the prefix +, the border color of that UITextField should change colours. If the UITextField does not have a phone number, no action should be taken. How do I go about achieving that?

This is the portion of the code that I need help in

    @IBAction func sendbutton(_ sender: Any) {

        var numArray: Array<Any>

        numArray = [phonenumber.text!, phonenumber1.text!, phonenumber2.text!, phonenumber3.text!]

        let myColor = UIColor.red

        for num in numArray {
            if (num as AnyObject).hasPrefix("+") {
                print("Has + symbol")

            } else {
                print("Does Not Have Symbol")

            }
        }

Body:
I don't think you should loop over an array of strings, instead loop over the text fields so you can set the color directly

var textFields: Array<UITextField> = [phonenumber, phonenumber1, phonenumber2, phonenumber3]
var numbersToSend = [String]()
let myColor = UIColor.red

for textField in textFields {
    let number = textField.text ?? ""
    if validatePhoneNumber(number) { //extract validation into separate function for clarity
        numbersToSend.append(number)
    } else {
        textField.backgroundColor = myColor //or whatever property you want to change
    }
}


问:
In Spring + Mybatis, how can I get dao method's parameter names in runtime?
In code, when I only know the beanId that point to dao object, how can I get method (in dao object) parameter names in runtime?

I'm using Java 7, Spring 4.1.6.RELEASE, Mybatis 3.2.8. And I am completely clueless

String daoBeanId = "IUserDao";
String methodName = "insertUser";

ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();

Object daoInstance = applicationContext.getBean(daoBeanId);
Class daoClass = daoInstance.getClass();

Method method = ReflectUtil.getMethod(daoClass,methodName);

//some code to get this method's parameter names
```

this is different from “Can I obtain method parameter name using Java reflection? ”，because in mybatis，dao object is proxy object，proxy object seems don't have the parameter names information，so it makes this question more complicated and difficult

答:
If you are using Java 8, Please have a look at the below link to get the method parameter names using reflection.

https://www.baeldung.com/java-parameter-reflection

Body:
In code, when I only know the beanId that point to dao object, how can I get method (in dao object) parameter names in runtime?

I'm using Java 7, Spring 4.1.6.RELEASE, Mybatis 3.2.8. And I am completely clueless

String daoBeanId = "IUserDao";
String methodName = "insertUser";

ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();

Object daoInstance = applicationContext.getBean(daoBeanId);
Class daoClass = daoInstance.getClass();

Method method = ReflectUtil.getMethod(daoClass,methodName);

//some code to get this method's parameter names

this is different from “Can I obtain method parameter name using Java reflection? ”，because in mybatis，dao object is proxy object，proxy object seems don't have the parameter names information，so it makes this question more complicated and difficult


问:
SQL Xml for Xpath query
Trying to return the value of an XML field via Xpath query.

Here is what the XML looks like in a snap shot.

```<code><?xml version="1.0" encoding="utf-16"?>
<ArrayOfCustomProperty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CustomProperty>
    <DeveloperId>Test123</DeveloperId>
    <Key>AgreedToTerms</Key>
    <Value>True</Value>
</CustomProperty>
<CustomProperty>
    <DeveloperId>Test456</DeveloperId>
    <Key>ValidForLoyaltyPoints</Key>
    <Value>False</Value>
</CustomProperty>
</ArrayOfCustomProperty>
</code>```

(sorry for the poorly-formatted XML...StackOverflows RCE is having issues with rendering it out.  The ArrayOfCustomProperty is closed at the end, just not displayed for some reason)

This query works for me....

```<code>  SET @return = CAST(CAST(@xmlData AS xml).query('ArrayOfCustomProperty/CustomProperty/Key[text()=sql:variable("@key")]/../Value/text()') AS nvarchar(255))
</code>```

It allows me to have a function where the parameters are @xmlData and @key for what needs to be searched.  I need to have another function (or might modify this one) where I can also search the [DeveloperId] node as well, so a third parameter will be passed in as @devId.  I've tried quite a few different things but nothing has worked for me yet.  I'd like a query where I can get the [Value] when [DeveloperId] and [Key] are present using the same structure (if possible) to how the current Xpath query works.

Thanks in advance for any help.

答:
You should rather try to return as little as possible from the XML.

The best was to reduce the amount the engine has to parse to the needed minimum.

And you should avoid backward-navigation using ../. This is a well known performance killer.

Try this:

```<code>DECLARE @tbl TABLE(YourXml XML);
INSERT INTO @tbl VALUES
(N'<?xml version="1.0" encoding="utf-16"?>
<ArrayOfCustomProperty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CustomProperty>
    <DeveloperId>Test123</DeveloperId>
    <Key>AgreedToTerms</Key>
    <Value>True</Value>
</CustomProperty>
<CustomProperty>
    <DeveloperId>Test456</DeveloperId>
    <Key>ValidForLoyaltyPoints</Key>
    <Value>False</Value>
</CustomProperty>
</ArrayOfCustomProperty>');
</code>```

--Your Key-variable

```<code>DECLARE @key VARCHAR(100)='ValidForLoyaltyPoints' ;
</code>```

--the Query

```<code>SELECT cp.value('(DeveloperId/text())[1]','nvarchar(250)') AS DeveloperId
      ,cp.value('(Value/text())[1]','nvarchar(250)') AS Value
FROM @tbl t
CROSS APPLY t.YourXml.nodes('/ArrayOfCustomProperty/CustomProperty[(Key/text())[1]=sql:variable("@key")]') A(cp);
</code>```

The XPath/XQuery within .nodes() will dive down to <CustomProperty> and will return the one with a <Key>, where the key's text is like the given filter. The found <CustomProperty> is returned. Using .value() we can read the elements below this given property.

UPDATE

It looks, as if you'd try to fetch the <Value> as a scalar value depending in <DeveloperId> and <Key>. You can use a simple predicate to query both at once:

```<code>DECLARE @key VARCHAR(100)='ValidForLoyaltyPoints' ;
DECLARE @devId VARCHAR(100)='Test456';
--the Query

SELECT t.YourXml.value(N'(/ArrayOfCustomProperty
                          /CustomProperty[(DeveloperId/text())[1]=sql:variable("@devId")
                                      and (Key/text())[1]=sql:variable("@key")]
                          /Value/text())[1]',N'nvarchar(100)')
FROM @tbl t;
</code>```

You read this as

Dive into the array

Dive deeper into CustomProperty

Find an element, where the filter matches ...

... and return its value

Title: SQL Xml for Xpath query

Body:
Trying to return the value of an XML field via Xpath query.

Here is what the XML looks like in a snap shot.

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfCustomProperty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CustomProperty>
    <DeveloperId>Test123</DeveloperId>
    <Key>AgreedToTerms</Key>
    <Value>True</Value>
</CustomProperty>
<CustomProperty>
    <DeveloperId>Test456</DeveloperId>
    <Key>ValidForLoyaltyPoints</Key>
    <Value>False</Value>
</CustomProperty>
</ArrayOfCustomProperty>

(sorry for the poorly-formatted XML...StackOverflows RCE is having issues with rendering it out.  The ArrayOfCustomProperty is closed at the end, just not displayed for some reason)

This query works for me....

  SET @return = CAST(CAST(@xmlData AS xml).query('ArrayOfCustomProperty/CustomProperty/Key[text()=sql:variable("@key")]/../Value/text()') AS nvarchar(255))

It allows me to have a function where the parameters are @xmlData and @key for what needs to be searched.  I need to have another function (or might modify this one) where I can also search the [DeveloperId] node as well, so a third parameter will be passed in as @devId.  I've tried quite a few different things but nothing has worked for me yet.  I'd like a query where I can get the [Value] when [DeveloperId] and [Key] are present using the same structure (if possible) to how the current Xpath query works.

Thanks in advance for any help.

Body:
You should rather try to return as little as possible from the XML.

The best was to reduce the amount the engine has to parse to the needed minimum.

And you should avoid backward-navigation using ../. This is a well known performance killer.

Try this:

DECLARE @tbl TABLE(YourXml XML);
INSERT INTO @tbl VALUES
(N'<?xml version="1.0" encoding="utf-16"?>
<ArrayOfCustomProperty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CustomProperty>
    <DeveloperId>Test123</DeveloperId>
    <Key>AgreedToTerms</Key>
    <Value>True</Value>
</CustomProperty>
<CustomProperty>
    <DeveloperId>Test456</DeveloperId>
    <Key>ValidForLoyaltyPoints</Key>
    <Value>False</Value>
</CustomProperty>
</ArrayOfCustomProperty>');

--Your Key-variable

DECLARE @key VARCHAR(100)='ValidForLoyaltyPoints' ;

--the Query

SELECT cp.value('(DeveloperId/text())[1]','nvarchar(250)') AS DeveloperId
      ,cp.value('(Value/text())[1]','nvarchar(250)') AS Value
FROM @tbl t
CROSS APPLY t.YourXml.nodes('/ArrayOfCustomProperty/CustomProperty[(Key/text())[1]=sql:variable("@key")]') A(cp);

The XPath/XQuery within .nodes() will dive down to <CustomProperty> and will return the one with a <Key>, where the key's text is like the given filter. The found <CustomProperty> is returned. Using .value() we can read the elements below this given property.

UPDATE

It looks, as if you'd try to fetch the <Value> as a scalar value depending in <DeveloperId> and <Key>. You can use a simple predicate to query both at once:

DECLARE @key VARCHAR(100)='ValidForLoyaltyPoints' ;
DECLARE @devId VARCHAR(100)='Test456';
--the Query

SELECT t.YourXml.value(N'(/ArrayOfCustomProperty
                          /CustomProperty[(DeveloperId/text())[1]=sql:variable("@devId")
                                      and (Key/text())[1]=sql:variable("@key")]
                          /Value/text())[1]',N'nvarchar(100)')
FROM @tbl t;

You read this as

Dive into the array

Dive deeper into CustomProperty

Find an element, where the filter matches ...

... and return its value


问:
Firebase Failed to resolve: firebase-messaging-15.0.0 (Previous solutions disconnect Firebase Connection)
I have been trying to set up Firebase Cloud Messaging on an app. Everything runs ok until I add FCM dependencies to the app. I immediately get this error:

Failed to resolve: firebase-messaging-15.0.0
  Open File

Here are the dependencies;

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.google.firebase:firebase-core:16.0.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.6'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-messaging:17.0.0:15.0.0'
}

apply plugin: 'com.google.gms.google-services'
</code>```

I have been reading answers like this all day and the only solution that works involves deleting everything from ": - 0" in the last line of the code.

The problem is that it immediately removes the connection to FCM. New to android programming, so forgive any obvious oversight. Thanks

答:
This happens because the version of the dependencies conflict. You can remove one of the version and select the preferred one. In this case your

implementation 'com.google.firebase:firebase-messaging:17.0.0:15.0.0'

seems to have double version. You should choose whether to use 17.0.0 or 15.0.0 one.
The detail can be found in this video
https://youtu.be/NN_Ch5qzFWQ

cheers !

Body:
I have been trying to set up Firebase Cloud Messaging on an app. Everything runs ok until I add FCM dependencies to the app. I immediately get this error:

Failed to resolve: firebase-messaging-15.0.0
  Open File

Here are the dependencies;

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.google.firebase:firebase-core:16.0.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.6'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-messaging:17.0.0:15.0.0'
}

apply plugin: 'com.google.gms.google-services'

I have been reading answers like this all day and the only solution that works involves deleting everything from ": - 0" in the last line of the code.

The problem is that it immediately removes the connection to FCM. New to android programming, so forgive any obvious oversight. Thanks


问:
Fixed div on the bottom of the scrollable div
I need a create 4 cards with non-changable height with buttons on the bottom, but there are different text amount in each card.

Position Fixed is connected to body element,
position absolute scrolls with content,
position sticky appears when content ends.

https://codepen.io/anatoli101/pen/NVzbGY Here is a basic exemple of my problem

```<code>.content{
  display:flex;
  width: 100%;
  justify-content: space-around;
}

.fixed-div{
  background-color: red;
  height: 400px;
  width: 300px;
  overflow-y: auto;
}

.button{
  position:sticky;
  bottom:0;
  background-color: grey;
  width: 100%;
  height: 30px;
}
</code>```

答:
A good way to achieve this is by wrapping the element with the class fixed-div inside a container, and moving the element with the class button outside of the element with the class fixed-div, so that it is the direct child of the container element. Then you can set position: relative to the container element, and position: absolute to the element with the class button. As the container element will have the exact same size (and especially the same height) as the element with the class fixed-div, the element with the class button will be positioned at its bottom.

You also will need to add a bottom padding to the element with the class fixed-div so that the button doesn't not hide its content, and so that it doesn't affect its defined height, you can set its box-sizing property to border-box.

See the following code:

.content {
  display: flex;
  width: 100%;
  justify-content: space-around;
}

.container {
  position: relative;
}

.fixed-div {
  box-sizing: border-box;
  width: 150px;
  height: 400px;
  padding-bottom: 30px;
  overflow-y: auto;
  background-color: red;
}

.button {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 30px;
  background-color: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>I need grey area fixed on the bottom, non depending of text amount  </h1>
<div class="content">
  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est ipsam quae optio!loremLorem ipsum dolor sit amet consectetur adipisicing elit. Itaque molestias natus officiis labore omnis corporis cupiditate quisquam nihil? Mollitia aperiam iusto iste minima ratione culpa veniam architecto facilis neque deleniti?Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis.Lore Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae?</p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum.</p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est ipsam quae optio!loremLorem ipsum dolor sit amet consectetur adipisicing elit. Itaque molestias natus officiis labore omnis corporis cupiditate quisquam nihil? Mollitia aperiam iusto iste minima ratione culpa veniam architecto facilis neque deleniti?Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis.Lore Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae?</p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est ipsam quae optio!loremLorem ipsum dolor sit amet consectetur adipisicing elit. Itaque molestias natus officiis labore omnis corporis cupiditate quisquam nihil? Mollitia aperiam iusto iste minima ratione culpa veniam architecto facilis neque deleniti?Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis.Lore Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae? </p>
    </div>
    <div class="button"></div>
  </div>
</div></code>```

I reduced the width of the text elements so that it works within a narrow container, you can run the code in full page if it is still too narrow.

Leaving the button inside the scrolling element and setting position: relative to the latter and position: absolute to the former wouldn't work as the bottom of the button would be positioned inside the scrolling element at 400px which is the height of the scrolling element, and would scroll with its content.

Hope that helps.

Body:
I need a create 4 cards with non-changable height with buttons on the bottom, but there are different text amount in each card.

Position Fixed is connected to body element,
position absolute scrolls with content,
position sticky appears when content ends.

https://codepen.io/anatoli101/pen/NVzbGY Here is a basic exemple of my problem

.content{
  display:flex;
  width: 100%;
  justify-content: space-around;
}

.fixed-div{
  background-color: red;
  height: 400px;
  width: 300px;
  overflow-y: auto;
}

.button{
  position:sticky;
  bottom:0;
  background-color: grey;
  width: 100%;
  height: 30px;
}

Body:
A good way to achieve this is by wrapping the element with the class fixed-div inside a container, and moving the element with the class button outside of the element with the class fixed-div, so that it is the direct child of the container element. Then you can set position: relative to the container element, and position: absolute to the element with the class button. As the container element will have the exact same size (and especially the same height) as the element with the class fixed-div, the element with the class button will be positioned at its bottom.

You also will need to add a bottom padding to the element with the class fixed-div so that the button doesn't not hide its content, and so that it doesn't affect its defined height, you can set its box-sizing property to border-box.

See the following code:

.content {
  display: flex;
  width: 100%;
  justify-content: space-around;
}

.container {
  position: relative;
}

.fixed-div {
  box-sizing: border-box;
  width: 150px;
  height: 400px;
  padding-bottom: 30px;
  overflow-y: auto;
  background-color: red;
}

.button {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 30px;
  background-color: grey;
}

<h1>I need grey area fixed on the bottom, non depending of text amount  </h1>
<div class="content">
  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est ipsam quae optio!loremLorem ipsum dolor sit amet consectetur adipisicing elit. Itaque molestias natus officiis labore omnis corporis cupiditate quisquam nihil? Mollitia aperiam iusto iste minima ratione culpa veniam architecto facilis neque deleniti?Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis.Lore Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae?</p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum.</p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est ipsam quae optio!loremLorem ipsum dolor sit amet consectetur adipisicing elit. Itaque molestias natus officiis labore omnis corporis cupiditate quisquam nihil? Mollitia aperiam iusto iste minima ratione culpa veniam architecto facilis neque deleniti?Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis.Lore Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae?</p>
    </div>
    <div class="button"></div>
  </div>

  <div class="container">
    <div class="fixed-div">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dolores aspernatur error rem aliquam omnis eveniet consequuntur asperiores, aut explicabo eaque eos quos facere necessitatibus sit est ipsam quae optio!loremLorem ipsum dolor sit amet consectetur adipisicing elit. Itaque molestias natus officiis labore omnis corporis cupiditate quisquam nihil? Mollitia aperiam iusto iste minima ratione culpa veniam architecto facilis neque deleniti?Lorem, ipsum dolor sit amet consectetur adipisicing elit. Cumque aut, eum, quia facere inventore perferendis aperiam recusandae nihil at aliquam ipsum excepturi eligendi animi, nam vel unde. Suscipit, tenetur veritatis.Lore Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eaque, quam. Hic unde nam dolor debitis voluptates officia earum, nostrum ut quae recusandae voluptate eveniet commodi ipsa dolorum nulla totam molestiae? </p>
    </div>
    <div class="button"></div>
  </div>
</div>

I reduced the width of the text elements so that it works within a narrow container, you can run the code in full page if it is still too narrow.

Leaving the button inside the scrolling element and setting position: relative to the latter and position: absolute to the former wouldn't work as the bottom of the button would be positioned inside the scrolling element at 400px which is the height of the scrolling element, and would scroll with its content.

Hope that helps.


问:
Why does multimap allow duplicate key-value pairs?
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

```<code>#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}
</code>```

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?

答:
EDIT: This answer does not answer the current question anymore. I'll keep it as it is because it got upvoted a lot so it must be useful for some.

The multi in multimap stands for the fact that the same key can occur multiple times.

The standard puts no limit on the type used as value, so one cannot assume that operator==() is defined. Because we don't want the result of your code depend on whether the operator==() is defined or not, it is never used.

std::multimap is not a replacement for std::map. As you noticed, it behaves differently when the same key is inserted multiple times. If you want std::map's behaviour, use std::map.

There is also a std::multiset.

The rational: sometimes one would like to keep all old entries for the same key around as well. [TBD: Insert some example here]

Personally, I barely ever use std::multimap. If I want multiple entries for the same key, I usually rely on std::map<std::vector<T> >.

Body:
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?


问:
override equals method for string class in a package in a scala project
So the problem statement is as it says. I want to override the behaviour of equals in string class in a specific package.

I've looked around and mostly it seems there's no way to do this.

The closest i got to defining a method on an existing class was this -

implicit class StringImprovements(s: String) {
  def increment = s.map(c => (c + 1).toChar)
}
```

<p>and then use it like this - </p>

<pre class="lang-scala prettyprint-override"><code>"HAL".increment
</code>```

Which is quite honestly amazing. But then i tried overriding equals using the same approach, it doesn't work.
I looked around and found this question from 2015 - override library method using Scala Implicit

Citing a line from above mentioned question -

Implicits are used if scala compiler cannot find method without it, so you can`t override methods with implicits

But given that scala releases are very frequent and things keep changing all the time, I was wondering whether it's possible to do so now, by this means or any other.

Thanks in advance!

答: No, it's not possible. And if it were, I would expect a lot of library code to break because it expected normal behavior from String#equals!

Body:
So the problem statement is as it says. I want to override the behaviour of equals in string class in a specific package.

I've looked around and mostly it seems there's no way to do this.

The closest i got to defining a method on an existing class was this -

implicit class StringImprovements(s: String) {
  def increment = s.map(c => (c + 1).toChar)
}

and then use it like this -

"HAL".increment

Which is quite honestly amazing. But then i tried overriding equals using the same approach, it doesn't work.
I looked around and found this question from 2015 - override library method using Scala Implicit

Citing a line from above mentioned question -

Implicits are used if scala compiler cannot find method without it, so you can`t override methods with implicits

But given that scala releases are very frequent and things keep changing all the time, I was wondering whether it's possible to do so now, by this means or any other.

Thanks in advance!


问:
Where to put setInterval and clearInterval
I have a working slider. I would like to to autoplay the slides and stop the autoplay when user clicks the next or previous button.

I have tried to include setInterval-function but I am not sure how I should apply it in order to make it work. So far I did not manage to do this.

enter code here

var interleaveOffset = 0.2;

var swiperOptions = {
  loop: true,
  speed: 500,
  grabCursor: true,
  watchSlidesProgress: true,
  mousewheelControl: true,
  keyboardControl: true,
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev"
  },
  on: {
    progress: function() {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        var slideProgress = swiper.slides[i].progress;
        var innerOffset = swiper.width * interleaveOffset;
        var innerTranslate = slideProgress * innerOffset;
        swiper.slides[i].querySelector(".slide-inner").style.transform =
          "translate3d(" + innerTranslate + "px, 0, 0)";
      }
    },
    touchStart: function() {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        swiper.slides[i].style.transition = "";
      }
    },
    setTransition: function(speed) {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        swiper.slides[i].style.transition = speed + "ms";
        swiper.slides[i].querySelector(".slide-inner").style.transition =
          speed + "ms";
      }
    }
  }
};

var swiper = new Swiper(".swiper-container", swiperOptions);```

I expect that slider plays the slides automatically and the autoplay stops when user clicks either next or previous button.

答:
From top of my head you can use something like this

```<code>
let timer = null

const startSwiping = () => {
 timer = setInterval(() => {
   swiper.slideNext(100); // transition duration (ms) as argument
 }, 500)
}

const stopSwiping = () => clearInterval(timer)

</code>```

I did not try that but Swiper docs dont show any other option than swiper.slideNext(speed)

Body:
I have a working slider. I would like to to autoplay the slides and stop the autoplay when user clicks the next or previous button.

I have tried to include setInterval-function but I am not sure how I should apply it in order to make it work. So far I did not manage to do this.

enter code here

var interleaveOffset = 0.2;

var swiperOptions = {
  loop: true,
  speed: 500,
  grabCursor: true,
  watchSlidesProgress: true,
  mousewheelControl: true,
  keyboardControl: true,
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev"
  },
  on: {
    progress: function() {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        var slideProgress = swiper.slides[i].progress;
        var innerOffset = swiper.width * interleaveOffset;
        var innerTranslate = slideProgress * innerOffset;
        swiper.slides[i].querySelector(".slide-inner").style.transform =
          "translate3d(" + innerTranslate + "px, 0, 0)";
      }
    },
    touchStart: function() {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        swiper.slides[i].style.transition = "";
      }
    },
    setTransition: function(speed) {
      var swiper = this;
      for (var i = 0; i < swiper.slides.length; i++) {
        swiper.slides[i].style.transition = speed + "ms";
        swiper.slides[i].querySelector(".slide-inner").style.transition =
          speed + "ms";
      }
    }
  }
};

var swiper = new Swiper(".swiper-container", swiperOptions);

I expect that slider plays the slides automatically and the autoplay stops when user clicks either next or previous button.

Body:
From top of my head you can use something like this

let timer = null

const startSwiping = () => {
 timer = setInterval(() => {
   swiper.slideNext(100); // transition duration (ms) as argument
 }, 500)
}

const stopSwiping = () => clearInterval(timer)

I did not try that but Swiper docs dont show any other option than swiper.slideNext(speed)