问:
How do I change unique row values into another set of unique row values in a data frame in R?
I have a data frame with the experimental results coming from participants who took my test online. In the data file, each unique participant is identified by a randomly generated code given to them at the end of the experiment. Since it is cumbersome to identify each person by a random code that looks like gibberish, I would like to replace these codes by readable labels like Participant_1, Participant_2, etc.

So I think I need a piece of code that identifies each unique random code in the data file and replaces them with the participant labels one by one. But I could not figure it out and any help would be much appreciated.

Here is a piece of code that shows the output I have vs. the output I want. Note that each participant has answered different numbers of questions, so this cannot be used as an easy way out to parse them.

```<code>Participant_Identifiers <- c(rep("QHDKWEFHWKHFFH", 4), rep("WHWIHFJNWFKWF", 7), rep("HEIFFFBBKQLSD", 3))

Participant_Scores <- c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97)

df <- data.frame("Participant_Identifiers" = c(rep("QHDKWEFHWKHFFH", 4), rep("WHWIHFJNWFKWF", 7), rep("HEIFFFBBKQLSD", 3)),
                  "Participant_Scores" = c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97, 35, 67))

df

df_I_want <- data.frame("Participant_Identifiers" = c(rep("Participant_1", 4), rep("Participant_2", 7), rep("Participant_3", 3)),
                       "Participant_Scores" = c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97, 35, 67))

df_I_want
</code>```

答:
Here is what you can do: </p>

```<code># example
ano <- replicate(5, paste(letters[sample(1:25, 12, replace = TRUE)], collapse = ""))
df <- data.frame(pat = sample(ano, 15, replace = TRUE), var = runif(15),
  stringsAsFactors = FALSE )

# 1. create another data frame with the id you want
patu <- unique(df$pat)
df_id <- data.frame(pat = patu, id = paste0("Participant_", seq_along(patu)))

# 2. merge with your df
res <- merge(df, df_id)
</code>```

Body:
I have a data frame with the experimental results coming from participants who took my test online. In the data file, each unique participant is identified by a randomly generated code given to them at the end of the experiment. Since it is cumbersome to identify each person by a random code that looks like gibberish, I would like to replace these codes by readable labels like Participant_1, Participant_2, etc.

So I think I need a piece of code that identifies each unique random code in the data file and replaces them with the participant labels one by one. But I could not figure it out and any help would be much appreciated.

Here is a piece of code that shows the output I have vs. the output I want. Note that each participant has answered different numbers of questions, so this cannot be used as an easy way out to parse them.

Participant_Identifiers <- c(rep("QHDKWEFHWKHFFH", 4), rep("WHWIHFJNWFKWF", 7), rep("HEIFFFBBKQLSD", 3))

Participant_Scores <- c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97)

df <- data.frame("Participant_Identifiers" = c(rep("QHDKWEFHWKHFFH", 4), rep("WHWIHFJNWFKWF", 7), rep("HEIFFFBBKQLSD", 3)),
                  "Participant_Scores" = c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97, 35, 67))

df

df_I_want <- data.frame("Participant_Identifiers" = c(rep("Participant_1", 4), rep("Participant_2", 7), rep("Participant_3", 3)),
                       "Participant_Scores" = c(20, 30, 59, 20, 47, 84, 21, 90,54,78,90,97, 35, 67))

df_I_want

Body:
Here is what you can do:

# example
ano <- replicate(5, paste(letters[sample(1:25, 12, replace = TRUE)], collapse = ""))
df <- data.frame(pat = sample(ano, 15, replace = TRUE), var = runif(15),
  stringsAsFactors = FALSE )

# 1. create another data frame with the id you want
patu <- unique(df$pat)
df_id <- data.frame(pat = patu, id = paste0("Participant_", seq_along(patu)))

# 2. merge with your df
res <- merge(df, df_id)


来源: stackexchange

问:
How to make a reverse Foreign Key in multiple tables with annotate
I have 3 models connected to one by a Foreign Key:

```<code>class A(models.Model):
    name = models.CharField(max_length=20)

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_b = models.FloatField()

class C(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_c = models.FloatField()

class D(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_d = models.FloatField()
</code>```

And I want to make a JOIN query based on the foreign keys using Django ORM to get the sum of each amount.

In SQL I would make something like:

```<code>SELECT
  a.name,
  b_sum,
  c_sum,
  d_sum
FROM A AS a
  LEFT JOIN (SELECT b.a, sum(amount_b) as b_sum
              from B as b
              group by b.a) as AB AB.a = a.id
  LEFT JOIN (SELECT c.a, sum(amount_c) as c_sum
              from C as c
              group by a) AS AC ON AC.a = a.id
  LEFT JOIN (SELECT d.a, sum(amount_d) as d_sum
              from D as d
              group by a) AS AD ON AD.a = a.id
WHERE a.name LIKE 'init%'
</code>```

But I didn't find something like that on django ORM.

答:
B.amount_b and D.amount_d are CharFields, performing a sum on those fields could cause issues if they do not contain numeric values. You should consider changing them to numeric fields

Something like the following would give you a queryset of A objects annotated with those sums

```<code>queryset = A.objects.annotate(
    b_sum=Sum('b__amount_b'),  # It's either "b" or "b_set"
    c_sum=Sum('c__amount_c'),
    d_sum=Sum('c__amount_d'),
)
for a in queryset:
    print(a.name, a.b_sum, a.c_sum, a.d_sum)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 3 models connected to one by a Foreign Key:

class A(models.Model):
    name = models.CharField(max_length=20)

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_b = models.FloatField()

class C(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_c = models.FloatField()

class D(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_d = models.FloatField()

And I want to make a JOIN query based on the foreign keys using Django ORM to get the sum of each amount.

In SQL I would make something like:

SELECT
  a.name,
  b_sum,
  c_sum,
  d_sum
FROM A AS a
  LEFT JOIN (SELECT b.a, sum(amount_b) as b_sum
              from B as b
              group by b.a) as AB AB.a = a.id
  LEFT JOIN (SELECT c.a, sum(amount_c) as c_sum
              from C as c
              group by a) AS AC ON AC.a = a.id
  LEFT JOIN (SELECT d.a, sum(amount_d) as d_sum
              from D as d
              group by a) AS AD ON AD.a = a.id
WHERE a.name LIKE 'init%'

But I didn't find something like that on django ORM.

Body:
B.amount_b and D.amount_d are CharFields, performing a sum on those fields could cause issues if they do not contain numeric values. You should consider changing them to numeric fields

Something like the following would give you a queryset of A objects annotated with those sums

queryset = A.objects.annotate(
    b_sum=Sum('b__amount_b'),  # It's either "b" or "b_set"
    c_sum=Sum('c__amount_c'),
    d_sum=Sum('c__amount_d'),
)
for a in queryset:
    print(a.name, a.b_sum, a.c_sum, a.d_sum)


问:
Terraform: store the contents of a set of files into a single variable
This is in TF V0.12 if that helps
In a directory, I have a variable number of single-line files.

I need to somehow read the contents of them all concatenating them with a newline between and store the result into a single variable. (not an array of strings)
I know I can get the list of files to read using:

```<code>locals{
  my files=tolist(fileset("${var.file_path}", "**")) }
</code>```

And if I only had a single file I know I can read in the contents by using

```<code>locals {
  file_value=file("${var.file_path}\\${local.my_files}") # if there was only a single file
}
</code>```

But my brains just turned to cotton wool how I can do the read for multiple,  I feel like I should be using a count and a concatenate within a null resource but can't seem to work the logic out.
Is that the right path or how should I be doing it?

答:
Concatenate locally with null_resource.</p>

```<code>resource "null_resource" "concatenate_my_files" {
  provisioner "local-exec" {
    working_dir = "${var.file_path}"
    command = <<EOF
      cat "${local.my_files}" > "${var.concatenated_file_name}"
EOF
  }
}
</code>```

Body:
This is in TF V0.12 if that helps
In a directory, I have a variable number of single-line files.

I need to somehow read the contents of them all concatenating them with a newline between and store the result into a single variable. (not an array of strings)
I know I can get the list of files to read using:

locals{
  my files=tolist(fileset("${var.file_path}", "**")) }

And if I only had a single file I know I can read in the contents by using

locals {
  file_value=file("${var.file_path}\\${local.my_files}") # if there was only a single file
}

But my brains just turned to cotton wool how I can do the read for multiple,  I feel like I should be using a count and a concatenate within a null resource but can't seem to work the logic out.
Is that the right path or how should I be doing it?

Body:
Concatenate locally with null_resource.

resource "null_resource" "concatenate_my_files" {
  provisioner "local-exec" {
    working_dir = "${var.file_path}"
    command = <<EOF
      cat "${local.my_files}" > "${var.concatenated_file_name}"
EOF
  }
}


问:
In Visual Basic forms confirm exit using message box
I have a basic me.close() button. I need to add a second step confirmation if it is pressed using a message box pop up.</p>

答:
In your Form's closing event, you should initialize a MessageBox and check if the result from the dialog is not yes. If so, then cancel the event. Something along the lines of:

```<code>Public Sub MyForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles MyForm.FormClosing
    If MessageBox.Show("Do you want to close the form?", "Confirm", MessageBoxButtons.YesNo) <> DialogResult.Yes Then
        e.Cancel = True
    End If
End Sub
</code>```

I would have thought that there is already an example somewhere, and as it turns out there already is on MSDN: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.closing?view=netframework-4.8#examples

When in doubt, try to search the MSDN documentation. This is where I personally get 99% of my information.

Body:
In your Form's closing event, you should initialize a MessageBox and check if the result from the dialog is not yes. If so, then cancel the event. Something along the lines of:

Public Sub MyForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles MyForm.FormClosing
    If MessageBox.Show("Do you want to close the form?", "Confirm", MessageBoxButtons.YesNo) <> DialogResult.Yes Then
        e.Cancel = True
    End If
End Sub

I would have thought that there is already an example somewhere, and as it turns out there already is on MSDN: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.closing?view=netframework-4.8#examples

When in doubt, try to search the MSDN documentation. This is where I personally get 99% of my information.


问:
How can I use number as key?
I have ids like as numbers 374,242,435

I want to use this as key of hash for the object.

```<code>var json = [];
ids = [374,242,435];
for(let i in ids) {
    var id = ids[i];
    json[id] = []; // it makes 372 array!!!
    json[id]['name'] = name;
    json[id]['color'] = color;
}
</code>```

Can I make object using number as key????

This is my silly mistake

I just changed var json = []; -> var json = {}; it works.

and thank you for your comments.

答:
```<code>let json = {};
let ids = [374,242,435];
for(let i in ids) {
    let id = ids[i];
    json[id] = {
        name: 'some name',
        color: '#ff0000'
    };
}
</code>```

EDIT: A better version

```<code>let json = {};
let ids = [374,242,435];
ids.forEach((id) => {
    json[id] = {
        name: 'some name',
        color: '#ff0000'
    };
});
</code>```

Title: How can I use number as key?

Body:
I have ids like as numbers 374,242,435

I want to use this as key of hash for the object.

var json = [];
ids = [374,242,435];
for(let i in ids) {
    var id = ids[i];
    json[id] = []; // it makes 372 array!!!
    json[id]['name'] = name;
    json[id]['color'] = color;
}

Can I make object using number as key????

This is my silly mistake

I just changed var json = []; -> var json = {}; it works.

and thank you for your comments.

Body:
let json = {};
let ids = [374,242,435];
for(let i in ids) {
    let id = ids[i];
    json[id] = {
        name: 'some name',
        color: '#ff0000'
    };
}

EDIT: A better version

let json = {};
let ids = [374,242,435];
ids.forEach((id) => {
    json[id] = {
        name: 'some name',
        color: '#ff0000'
    };
});


问:
How to resize TouchableOpacity according to the component present inside it?
I'm using TouchableOpacity to make a button as I'm learning react-native.

But the problem is, TouchableOpacity takes 100% width of the screen. But, I want to take the size/grow with the component present inside it.

How can I do it?

```<code>import React, { Component } from "react";
import { Text, TouchableOpacity } from "react-native";
export default class App extends Component {
    render(){
        return(
        <TouchableOpacity
            onPress={() => console.log("Pressed!")}
            style={{ backgroundColor: "red" }}
        >

            <Text>Press me!</Text>

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

When I decrease the width of the TouchableOpacity like 10 or 20, it automatically increases its height to fit the Text.

So, it possible for TouchableOpacity to grow with the size of component present inside it?

答: You can actually use alignSelf: 'flex-start' or 'flex-end' depending on which side you want to pin </p>

ContentLicense: CC BY-SA 3.0

Body:
I'm using TouchableOpacity to make a button as I'm learning react-native.

But the problem is, TouchableOpacity takes 100% width of the screen. But, I want to take the size/grow with the component present inside it.

How can I do it?

import React, { Component } from "react";
import { Text, TouchableOpacity } from "react-native";
export default class App extends Component {
    render(){
        return(
        <TouchableOpacity
            onPress={() => console.log("Pressed!")}
            style={{ backgroundColor: "red" }}
        >

            <Text>Press me!</Text>

        </TouchableOpacity>
        );
    }

When I decrease the width of the TouchableOpacity like 10 or 20, it automatically increases its height to fit the Text.

So, it possible for TouchableOpacity to grow with the size of component present inside it?


问:
Dafny not verifying trivial assertion
The code below, also at https://rise4fun.com/Dafny/I4wM ,

```<code>function abst(bits: array<int>,low:int,high: int): int
    requires 0<=low<=high<=8
    requires bits.Length==8
    decreases high-low
    reads bits
{   if low==high
        then 0
        else 2*abst(bits,low+1,high) + bits[low]
}

method M() {

    var byte: int;
    var bits:= new int[8];
    bits[0]:= 1;
    bits[1]:= 1;
    bits[2]:= 1;
    bits[3]:= 1;
    bits[4]:= 1;
    bits[5]:= 1;
    bits[6]:= 1;
    bits[7]:= 1;

    // assert abst(bits,2,2) == 0; // Why is this needed?
    assert abst(bits,0,2) == 3;

}
</code>```

fails to verify the assertion on the last line. (I'm using the on-line Dafny at Rise4Fun.) If the assertion just before is uncommented, the verification succeeds.

I'd be grateful for help. Thanks!

答:
The Dafny verifier unrolls functions only once or twice. Specifically, if the function occurs in an assertion you're trying to prove (like abst does in your example), then the function gets unrolled twice. However, to prove your assertion, the definition of abst needs to be unrolled 3 times. Therefore, the verifier can't prove it automatically. You'll have to help it along.

When you uncomment the first assertion, it gets used in the proof of the second assertion. Since the first assertion provides the last instantiation of abst that you need, it helps prove the second assertion. The first assertion itself is also proved, but that's automatic, since it only requires one unrolling of abst.

If you write out the proof in detail, it looks like:

```<code>calc {
  abst(bits,0,2);
==  // def. abst
  2*abst(bits,1,2) + bits[0];
==  // def. abst
  2*(2*abst(bits,2,2) + bits[1]) + bits[0];
==  // def. abst
  2*(2*0 + bits[1]) + bits[0];
==  // def. bits[0] and bits[1]
  2*(2*0 + 1) + 1;
==  // arithmetic
  3;
}
</code>```

In this proof, you can see the needed instantiations of the function.

Do you really need arrays in your application? Arrays are allocated on the heap and are mutable (which means you need the reads clause and other complications). If you only need an immutable sequence, then I would recommend you change array<int> to seq<int>. This will make things easier (again--if you don't need the mutable qualities of arrays). Moreover, for your assertion above, it brings another benefit: All the arguments you then pass to abst are literals. For literals, Dafny is willing to unroll functions (more or less) without limits. So, then your original assertion verifies automatically.

Rustan

Title: Dafny not verifying trivial assertion

Body:
The code below, also at https://rise4fun.com/Dafny/I4wM ,

function abst(bits: array<int>,low:int,high: int): int
    requires 0<=low<=high<=8
    requires bits.Length==8
    decreases high-low
    reads bits
{   if low==high
        then 0
        else 2*abst(bits,low+1,high) + bits[low]
}

method M() {

    var byte: int;
    var bits:= new int[8];
    bits[0]:= 1;
    bits[1]:= 1;
    bits[2]:= 1;
    bits[3]:= 1;
    bits[4]:= 1;
    bits[5]:= 1;
    bits[6]:= 1;
    bits[7]:= 1;

    // assert abst(bits,2,2) == 0; // Why is this needed?
    assert abst(bits,0,2) == 3;

}

fails to verify the assertion on the last line. (I'm using the on-line Dafny at Rise4Fun.) If the assertion just before is uncommented, the verification succeeds.

I'd be grateful for help. Thanks!

Body:
The Dafny verifier unrolls functions only once or twice. Specifically, if the function occurs in an assertion you're trying to prove (like abst does in your example), then the function gets unrolled twice. However, to prove your assertion, the definition of abst needs to be unrolled 3 times. Therefore, the verifier can't prove it automatically. You'll have to help it along.

When you uncomment the first assertion, it gets used in the proof of the second assertion. Since the first assertion provides the last instantiation of abst that you need, it helps prove the second assertion. The first assertion itself is also proved, but that's automatic, since it only requires one unrolling of abst.

If you write out the proof in detail, it looks like:

calc {
  abst(bits,0,2);
==  // def. abst
  2*abst(bits,1,2) + bits[0];
==  // def. abst
  2*(2*abst(bits,2,2) + bits[1]) + bits[0];
==  // def. abst
  2*(2*0 + bits[1]) + bits[0];
==  // def. bits[0] and bits[1]
  2*(2*0 + 1) + 1;
==  // arithmetic
  3;
}

In this proof, you can see the needed instantiations of the function.

Do you really need arrays in your application? Arrays are allocated on the heap and are mutable (which means you need the reads clause and other complications). If you only need an immutable sequence, then I would recommend you change array<int> to seq<int>. This will make things easier (again--if you don't need the mutable qualities of arrays). Moreover, for your assertion above, it brings another benefit: All the arguments you then pass to abst are literals. For literals, Dafny is willing to unroll functions (more or less) without limits. So, then your original assertion verifies automatically.

Rustan


问:
MATLAB: 2D DATA TO 3D ! How to?
I have a 34200 x 4 table. This table shows the 30 years monthly amount of pr (precipitation) in some latitudes and longitudes. So the columns are lat, lon, date, and pr. I want to convert it to a 3D matrix that longitude x latitude x month.
I attach my table.
Please tell me how to do it I'm a beginner. If I don't want to convert it based on the month I could but this issue is so complicated for me.
Please look at my table it's only 235 KB I upload it to my DropBox so please click on Open in the top right side and click download.

Here is my image

答:
Inspecting your data, your latitude and logitude values actually represent 95 unique locations which are scattered seemingly randomly. You can see that in the figure below.

length(unique(C.lat)) % 95
length(unique(C.lon)) % 95
scatter(C.lat, C.lon)
```

<p><img src="https://i.stack.imgur.com/IbRs0.png" alt="enter image description here"></p>

<p>If the locations were spaced in a grid, it would make sense to use <code>lat</code> and <code>lon</code> as the axes of a data matrix. But instead, it is better to use only one axis representing the unique locations. This then leaves you with a second axis representing the date.</p>

<pre class="lang-matlab prettyprint-override"><code>length(unique(C.date)) % 360
360 * 95 % 34200 - the number of values we have
</code>```

Reformatting the data

Therefore, I would store the data in a 2D matrix as follows.

locations_lat = unique(C.lat, 'stable');
locations_lon = unique(C.lon, 'stable');
dates = unique(C.date, 'stable');
data = reshape(C.pr, length(dates), length(locations_lat)); % size 360 x 95
```

<p>Then, to check that this has worked, choose a random example.</p>

<pre class="lang-matlab prettyprint-override"><code>location_num = 27;
date_num = 242;
lat = locations_lat(location_num) % 14.68055556
lon = locations_lon(location_num) % 65.23111111
date = dates(date_num) % 2/1/2009
precipitation = data(date_num, location_num) % 16.7179
</code>```

Searching for that position and date in the original tale, we have:

```<code>9602|   14.6805555600000    65.2311111100000    '2/1/2009'  16.7179000000000
</code>```

Title: MATLAB: 2D DATA TO 3D ! How to?

Body:
Inspecting your data, your latitude and logitude values actually represent 95 unique locations which are scattered seemingly randomly. You can see that in the figure below.

length(unique(C.lat)) % 95
length(unique(C.lon)) % 95
scatter(C.lat, C.lon)

If the locations were spaced in a grid, it would make sense to use lat and lon as the axes of a data matrix. But instead, it is better to use only one axis representing the unique locations. This then leaves you with a second axis representing the date.

length(unique(C.date)) % 360
360 * 95 % 34200 - the number of values we have

Reformatting the data

Therefore, I would store the data in a 2D matrix as follows.

locations_lat = unique(C.lat, 'stable');
locations_lon = unique(C.lon, 'stable');
dates = unique(C.date, 'stable');
data = reshape(C.pr, length(dates), length(locations_lat)); % size 360 x 95

Then, to check that this has worked, choose a random example.

location_num = 27;
date_num = 242;
lat = locations_lat(location_num) % 14.68055556
lon = locations_lon(location_num) % 65.23111111
date = dates(date_num) % 2/1/2009
precipitation = data(date_num, location_num) % 16.7179

Searching for that position and date in the original tale, we have:

9602|   14.6805555600000    65.2311111100000    '2/1/2009'  16.7179000000000


问:
Trying to build VLC for Unity3D
I have been trying to get the VLC plugin for Unity3D to build.  It is found here: https://code.videolan.org/videolan/vlc-unity/blob/master/README.md

I am trying to do this on Debian 10 (buster).

The first instruction was to: Download and install https://github.com/mstorsjo/llvm-mingw on latest Debian (WSL or otherwise). Add it to path.

I believe I have done that part successfully.

Next is to: Download VLC nightly build and adjust if need be vlc-4.0.0-dev/sdk/lib path to LDFLAGS in Common.mk

This is where my issue is. I've done the snap install of the nightly build, I've downloaded the source with a -dev in name from here: https://nightlies.videolan.org/build/source/

I've also tried to use the master-daily PPA.

But I still cannot find any vlc-4.0.0-dev/sdk/lib path.

I have tried to set the LDFLAGS to some of the vlc lib folders I have, but every time I build I get this error:

```<code>lld: error: unable to find library -lvlc
clang-10: error: linker command failed with exit code 1
</code>```

My end goal, if I can get this VLC plugin working, is to stream one of my Unity3D virtual cameras to a viewer on the network via rtsp.

答:
Since this plugin is currently Windows-only, I'm assuming you are targeting Windows.

Download a nightly from https://nightlies.videolan.org/build/win64-llvm/last/

You will find the libs at vlc-4.0.0-{date}-dev-win64.7z\vlc-4.0.0-dev\sdk\lib\

Title: Trying to build VLC for Unity3D

Body:
I have been trying to get the VLC plugin for Unity3D to build.  It is found here: https://code.videolan.org/videolan/vlc-unity/blob/master/README.md

I am trying to do this on Debian 10 (buster).

The first instruction was to: Download and install https://github.com/mstorsjo/llvm-mingw on latest Debian (WSL or otherwise). Add it to path.

I believe I have done that part successfully.

Next is to: Download VLC nightly build and adjust if need be vlc-4.0.0-dev/sdk/lib path to LDFLAGS in Common.mk

This is where my issue is. I've done the snap install of the nightly build, I've downloaded the source with a -dev in name from here: https://nightlies.videolan.org/build/source/

I've also tried to use the master-daily PPA.

But I still cannot find any vlc-4.0.0-dev/sdk/lib path.

I have tried to set the LDFLAGS to some of the vlc lib folders I have, but every time I build I get this error:

lld: error: unable to find library -lvlc
clang-10: error: linker command failed with exit code 1

My end goal, if I can get this VLC plugin working, is to stream one of my Unity3D virtual cameras to a viewer on the network via rtsp.


问:
How should I handle the scroll down operation in the script?
In order to capture a bitmap located at the end of the web page, I have to scrolldown the page (if not the code is not capturing the bitmap). How should I handle the scroll down operation in the script?</p>

答:
I would prefer the solution of Motti, but if you really, really, really want to perform a scroll down, you can send the type command for the END button to the browser, or just create a Windows Scripting Host object and perform a sendkey "{END}" command.
This should work in that case: </p>

```<code>CreateObject("WScript.Shell").SendKeys "{END}"
</code>```

Body:
I would prefer the solution of Motti, but if you really, really, really want to perform a scroll down, you can send the type command for the END button to the browser, or just create a Windows Scripting Host object and perform a sendkey "{END}" command.
This should work in that case:

CreateObject("WScript.Shell").SendKeys "{END}"


问:
Why Laravel simple paginate doesn't working?
This this my controller

```<code>  class PageController extends Controller
  {

   public function showImageUrl (Request $req){

   $directory = '/public/testukas/';

   $files = collect(Storage::files($directory))->simplePaginate(8);

   return view('welcome')->with('files',$files);

  }
</code>```

and this code from my appServiceprovider

```<code>  if (!Collection::hasMacro('simplePaginate')) {

        Collection::macro('simplePaginate',
            function ($perPage = 15, $page = null, $options = []) {
            $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
            return (
                new Paginator(
                    $this->forPage($page, $perPage),
                    $perPage,
                    $page,
                    $options
                )
            )->withPath('');
        });
    }
</code>```

In blade template i use this to call links

```<code> {!! $files->render() !!}
</code>```

So my question is how to make it work, links doesn't show. Thanks for help.

答:
```<code>public function index()
{
    $allposts = Post::latest()->paginate(2);
    return view('welcome',compact('allposts'));
}

// blade file
{{ $allposts->links() }}
</code>```

Body:
This this my controller

  class PageController extends Controller
  {

   public function showImageUrl (Request $req){

   $directory = '/public/testukas/';

   $files = collect(Storage::files($directory))->simplePaginate(8);

   return view('welcome')->with('files',$files);

  }

and this code from my appServiceprovider

  if (!Collection::hasMacro('simplePaginate')) {

        Collection::macro('simplePaginate',
            function ($perPage = 15, $page = null, $options = []) {
            $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
            return (
                new Paginator(
                    $this->forPage($page, $perPage),
                    $perPage,
                    $page,
                    $options
                )
            )->withPath('');
        });
    }

In blade template i use this to call links

 {!! $files->render() !!}

So my question is how to make it work, links doesn't show. Thanks for help.


问:
React-native Text input color issue in full screen editing

In my react-native android app, This is the same text box in portrait & Landscape views.
I have used selectionColor & underlineColorAndroid properties to set the font color.

```<code><TextInput selectionColor={FormElements.textInputSelectionColor} underlineColorAndroid={FormElements.textInputSelectionColor} placeholder={"Email Address"} placeholderTextColor={FormElements.textInputPlaceholderColor} keyboardType="email-address" value={this.props.email}/>
</code>```

But the issue is in the full screen edit (on landscape mode) it's hard to read in white background.

So I want either to change make full screen edit background color or text color back to black on full screen.

I tried, but couldn't find a solution yet.
Cam someone please give me a solution for this?

This full screen popup doesn't come up only landscape mode. it comes up when ever there is not enough space to occupy the keyboard.

答:
I was encountering this issue too. After a few hours of exploring I found this property of React Native TextInput "disableFullscreenUI"

In my case I only want the normal input editing and don't show the Fullscreen editor.

```<code><TextInput disableFullscreenUI={true} />
</code>```

and the fullscreen mode will go away upon edit then the editing will remain inside the TextInput.

Hope this helps

Body:
In my react-native android app, This is the same text box in portrait & Landscape views.
I have used selectionColor & underlineColorAndroid properties to set the font color.

<TextInput selectionColor={FormElements.textInputSelectionColor} underlineColorAndroid={FormElements.textInputSelectionColor} placeholder={"Email Address"} placeholderTextColor={FormElements.textInputPlaceholderColor} keyboardType="email-address" value={this.props.email}/>

But the issue is in the full screen edit (on landscape mode) it's hard to read in white background.

So I want either to change make full screen edit background color or text color back to black on full screen.

I tried, but couldn't find a solution yet.
Cam someone please give me a solution for this?

This full screen popup doesn't come up only landscape mode. it comes up when ever there is not enough space to occupy the keyboard.

Body:
I was encountering this issue too. After a few hours of exploring I found this property of React Native TextInput "disableFullscreenUI"

In my case I only want the normal input editing and don't show the Fullscreen editor.

<TextInput disableFullscreenUI={true} />

and the fullscreen mode will go away upon edit then the editing will remain inside the TextInput.

Hope this helps


问:
Want to use a floating action button that adds an item to a recyclerview in a specific fragment that is contained in a ViewPager2
I have been having a lot of trouble trying to implement multiple recyclerviews across multiple pages(represented by fragments) in a viewpager2, and I want to use a floating action button that when clicked, props up a page where the user can input data that can eventually be added to the recyclerview within a specific page on the viewpager. The Viewpager2 is applied with a tab layout labeling the days "Monday" to "Sunday." I cannot seem to add to the recyclerview through the activity "activity_add_medication_to_list." There is a long segment of code with 7 intents that is meant to represent adding to a medication list. The project is essentially a medical scheduling/tracking application. For each day of the week, I want to be able to add a specific medication to the list and be able to see it visibly. There are seven fragments representing each of the days of the week. FirstFragment represents Monday, SecondFragment represents Tuesday, etc. I also have a recyclerviewAdapter class and a ViewPagerAdapter class representing the adapters for both the multiple recyclerviews and the viewPager2.

Main problem: After clicking on the floating action button and inputing my data, it is not adding to the end of the recyclerview for any of the pages (represented by FirstFragment class). What am I missing that is not allowing me to see a visible list of items for any of the recyclerviews? How do I properly integrate the recyclerviews into the fragments so that I can update the recyclerviews using the floating action button?

Only 5 of the 7 fragment classes are shown below to conserve space. They are all according to the day of the week. Monday, Tuesday, Wednesday, Thursday, Friday refer to these first 5 fragment classes.

Code:

Add Medication to List class

```<code>package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class add_medication_to_list extends AppCompatActivity {

    String name;
    String time;
    int quantity;
    int dosage;
    String dayOfWeek;
    EditText nameInput;
    EditText timeInput;
    EditText quantityInput;
    EditText dosageInput;
    EditText dayOfWeekInput;
    Button add;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_medication_to_list);
        nameInput =  findViewById(R.id.medicine_name);
        timeInput =  findViewById(R.id.time);
        quantityInput =  findViewById(R.id.medicine_quantity);
        dosageInput = findViewById(R.id.dosage);
        dayOfWeekInput = findViewById(R.id.dayOfWeek);
        add =  findViewById(R.id.addButton);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = nameInput.getText().toString();
                time = timeInput.getText().toString();
                quantity = Integer.parseInt(quantityInput.getText().toString());
                dosage = Integer.parseInt(dosageInput.getText().toString());
                dayOfWeek = dayOfWeekInput.getText().toString();

                // setResult(RESULT_OK);
                    if (dayOfWeek.equalsIgnoreCase("monday")) {
                        FirstFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("tuesday")) {
                        SecondFragmentClass.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("wednesday")) {
                        ThirdFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("thursday")) {
                        FourthFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("friday")) {
                        FifthFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("saturday")) {
                        SixthFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("sunday")) {
                        SeventhFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    }
                }

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

FirstFragment Class

```<code>package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class FirstFragment extends Fragment {
    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist;
    private static recyclerViewAdapter anAdapter;
    private static int positionCounter;
    View view;
    public FirstFragment() {
        // Required empty public constructor
    }

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    public static FirstFragment newInstance(Integer counter) {
        FirstFragment fragment = new FirstFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        medlist = new ArrayList<>();
        positionCounter = 0;
        myRecyclerView = view.findViewById(R.id.prescription_list);
        myRecyclerView.setHasFixedSize(true);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);

        } });

}
    }
</code>```

SecondFragment Class

```<code>package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class SecondFragmentClass extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist;
    private static recyclerViewAdapter anAdapter;
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static SecondFragmentClass newInstance(Integer counter) {
        SecondFragmentClass fragment = new SecondFragmentClass();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        positionCounter = 0;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_2, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        positionCounter = 0;
        medlist = new ArrayList<>();
        myRecyclerView = view.findViewById(R.id.prescription_list_2);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

</code>```

ThirdFragment Class

```<code>package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class ThirdFragment extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist = new ArrayList<>();
    private static recyclerViewAdapter anAdapter = new recyclerViewAdapter(context, medlist);
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static ThirdFragment newInstance(Integer counter) {
        ThirdFragment fragment = new ThirdFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        positionCounter = 0;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_3, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        positionCounter = 0;
        medlist = new ArrayList<>();
        myRecyclerView = view.findViewById(R.id.prescription_list_3);
        myRecyclerView.setHasFixedSize(true);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

</code>```

FourthFragment Class

```<code>package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class FourthFragment extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist;
    private static recyclerViewAdapter anAdapter;
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static FourthFragment newInstance(Integer counter) {
        FourthFragment fragment = new FourthFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_4, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        myRecyclerView = view.findViewById(R.id.prescription_list_4);
        positionCounter = 0;
        medlist = new ArrayList<>();
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setHasFixedSize(true);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

</code>```

FifthFragment class

```<code>package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class FifthFragment extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private  RecyclerView myRecyclerView;
    private  static ArrayList<Medicine> medlist;
    private  static recyclerViewAdapter anAdapter;
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static FifthFragment newInstance(Integer counter) {
        FifthFragment fragment = new FifthFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        positionCounter = 0;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
            positionCounter = 0;

        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_5, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        medlist = new ArrayList<>();
        positionCounter = 0;
        myRecyclerView = view.findViewById(R.id.prescription_list_5);
        myRecyclerView.setHasFixedSize(true);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}
</code>```

ViewPagerAdapter

```<code>package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.ArrayList;

public class ViewPagerAdapter extends FragmentStateAdapter {
    private static final int CARD_ITEM_SIZE = 7;
    private ArrayList<Fragment> arrayList = new ArrayList<>();
    public ViewPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return arrayList.get(position);
    }

    @Override public int getItemCount() {
        return CARD_ITEM_SIZE;
    }

    public void addFragment(Fragment fragment) {
        arrayList.add(fragment);

    }
}
</code>```

recyclerViewAdapter

```<code>package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class recyclerViewAdapter extends RecyclerView.Adapter<recyclerViewAdapter.MyViewHolder> {

    Context data;
    List<Medicine> new_list;

    public recyclerViewAdapter(Context data, List<Medicine> new_list) {
        this.data = data;
        this.new_list = new_list;
    }

    public recyclerViewAdapter() {
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(data).inflate(R.layout.new_items, parent, false);
        MyViewHolder view = new MyViewHolder(v);
        return view;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.new_name.setText(new_list.get(position).getName());
        holder.new_quantity.setText(Integer.toString(new_list.get(position).getFrequency()));
        holder.new_image.setImageResource(new_list.get(position).getPhoto());
        holder.new_time.setText(new_list.get(position).getTime());

    }

    @Override
    public int getItemCount() {
        return new_list.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView new_name;
        private TextView new_quantity;
        private ImageView new_image;
        private TextView  new_time;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            new_name = itemView.findViewById(R.id.prescription_name);
            new_image = itemView.findViewById(R.id.new_image);
            new_quantity = itemView.findViewById(R.id.quantity_items);
            new_time = itemView.findViewById(R.id.new_time);

        }

    }
}

</code>```

Medicine Class

```<code>package com.example.myapplication;

public class Medicine {

    private String name_of_medicine, time_to_take;
    private int quantity_remaining, Photo, frequency, dosage;

    public Medicine(String name_of_medicine, String time_to_take, int quantity, int dosage, int photo) {
        this.name_of_medicine = name_of_medicine;
        this.time_to_take = time_to_take;
        this.quantity_remaining = quantity;
        this.dosage = dosage;
        Photo = photo;
    }

    public String getName()
    {
        return name_of_medicine;
    }
    public String getTime()
    {
        return time_to_take;
    }
    public int getFrequency() {
        return quantity_remaining;
    }
    public int getPhoto() {
        return Photo;
    }
}
</code>```

答: Resolved this issue. Used finish() after calling add_new_item() method. </p>

Body:
I have been having a lot of trouble trying to implement multiple recyclerviews across multiple pages(represented by fragments) in a viewpager2, and I want to use a floating action button that when clicked, props up a page where the user can input data that can eventually be added to the recyclerview within a specific page on the viewpager. The Viewpager2 is applied with a tab layout labeling the days "Monday" to "Sunday." I cannot seem to add to the recyclerview through the activity "activity_add_medication_to_list." There is a long segment of code with 7 intents that is meant to represent adding to a medication list. The project is essentially a medical scheduling/tracking application. For each day of the week, I want to be able to add a specific medication to the list and be able to see it visibly. There are seven fragments representing each of the days of the week. FirstFragment represents Monday, SecondFragment represents Tuesday, etc. I also have a recyclerviewAdapter class and a ViewPagerAdapter class representing the adapters for both the multiple recyclerviews and the viewPager2.

Main problem: After clicking on the floating action button and inputing my data, it is not adding to the end of the recyclerview for any of the pages (represented by FirstFragment class). What am I missing that is not allowing me to see a visible list of items for any of the recyclerviews? How do I properly integrate the recyclerviews into the fragments so that I can update the recyclerviews using the floating action button?

Only 5 of the 7 fragment classes are shown below to conserve space. They are all according to the day of the week. Monday, Tuesday, Wednesday, Thursday, Friday refer to these first 5 fragment classes.

Code:

Add Medication to List class

package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class add_medication_to_list extends AppCompatActivity {

    String name;
    String time;
    int quantity;
    int dosage;
    String dayOfWeek;
    EditText nameInput;
    EditText timeInput;
    EditText quantityInput;
    EditText dosageInput;
    EditText dayOfWeekInput;
    Button add;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_medication_to_list);
        nameInput =  findViewById(R.id.medicine_name);
        timeInput =  findViewById(R.id.time);
        quantityInput =  findViewById(R.id.medicine_quantity);
        dosageInput = findViewById(R.id.dosage);
        dayOfWeekInput = findViewById(R.id.dayOfWeek);
        add =  findViewById(R.id.addButton);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = nameInput.getText().toString();
                time = timeInput.getText().toString();
                quantity = Integer.parseInt(quantityInput.getText().toString());
                dosage = Integer.parseInt(dosageInput.getText().toString());
                dayOfWeek = dayOfWeekInput.getText().toString();

                // setResult(RESULT_OK);
                    if (dayOfWeek.equalsIgnoreCase("monday")) {
                        FirstFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("tuesday")) {
                        SecondFragmentClass.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("wednesday")) {
                        ThirdFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("thursday")) {
                        FourthFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("friday")) {
                        FifthFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("saturday")) {
                        SixthFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("sunday")) {
                        SeventhFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    }
                }

        });
    }
}

FirstFragment Class

package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class FirstFragment extends Fragment {
    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist;
    private static recyclerViewAdapter anAdapter;
    private static int positionCounter;
    View view;
    public FirstFragment() {
        // Required empty public constructor
    }

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    public static FirstFragment newInstance(Integer counter) {
        FirstFragment fragment = new FirstFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        medlist = new ArrayList<>();
        positionCounter = 0;
        myRecyclerView = view.findViewById(R.id.prescription_list);
        myRecyclerView.setHasFixedSize(true);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);

        } });

}
    }

SecondFragment Class

package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class SecondFragmentClass extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist;
    private static recyclerViewAdapter anAdapter;
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static SecondFragmentClass newInstance(Integer counter) {
        SecondFragmentClass fragment = new SecondFragmentClass();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        positionCounter = 0;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_2, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        positionCounter = 0;
        medlist = new ArrayList<>();
        myRecyclerView = view.findViewById(R.id.prescription_list_2);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

ThirdFragment Class

package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class ThirdFragment extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist = new ArrayList<>();
    private static recyclerViewAdapter anAdapter = new recyclerViewAdapter(context, medlist);
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static ThirdFragment newInstance(Integer counter) {
        ThirdFragment fragment = new ThirdFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        positionCounter = 0;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_3, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        positionCounter = 0;
        medlist = new ArrayList<>();
        myRecyclerView = view.findViewById(R.id.prescription_list_3);
        myRecyclerView.setHasFixedSize(true);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

FourthFragment Class

package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class FourthFragment extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist;
    private static recyclerViewAdapter anAdapter;
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static FourthFragment newInstance(Integer counter) {
        FourthFragment fragment = new FourthFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_4, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        myRecyclerView = view.findViewById(R.id.prescription_list_4);
        positionCounter = 0;
        medlist = new ArrayList<>();
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setHasFixedSize(true);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

FifthFragment class

package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class FifthFragment extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private  RecyclerView myRecyclerView;
    private  static ArrayList<Medicine> medlist;
    private  static recyclerViewAdapter anAdapter;
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static FifthFragment newInstance(Integer counter) {
        FifthFragment fragment = new FifthFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        positionCounter = 0;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
            positionCounter = 0;

        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_5, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        medlist = new ArrayList<>();
        positionCounter = 0;
        myRecyclerView = view.findViewById(R.id.prescription_list_5);
        myRecyclerView.setHasFixedSize(true);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

ViewPagerAdapter

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.ArrayList;

public class ViewPagerAdapter extends FragmentStateAdapter {
    private static final int CARD_ITEM_SIZE = 7;
    private ArrayList<Fragment> arrayList = new ArrayList<>();
    public ViewPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return arrayList.get(position);
    }

    @Override public int getItemCount() {
        return CARD_ITEM_SIZE;
    }

    public void addFragment(Fragment fragment) {
        arrayList.add(fragment);

    }
}

recyclerViewAdapter

package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class recyclerViewAdapter extends RecyclerView.Adapter<recyclerViewAdapter.MyViewHolder> {

    Context data;
    List<Medicine> new_list;

    public recyclerViewAdapter(Context data, List<Medicine> new_list) {
        this.data = data;
        this.new_list = new_list;
    }

    public recyclerViewAdapter() {
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(data).inflate(R.layout.new_items, parent, false);
        MyViewHolder view = new MyViewHolder(v);
        return view;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.new_name.setText(new_list.get(position).getName());
        holder.new_quantity.setText(Integer.toString(new_list.get(position).getFrequency()));
        holder.new_image.setImageResource(new_list.get(position).getPhoto());
        holder.new_time.setText(new_list.get(position).getTime());

    }

    @Override
    public int getItemCount() {
        return new_list.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView new_name;
        private TextView new_quantity;
        private ImageView new_image;
        private TextView  new_time;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            new_name = itemView.findViewById(R.id.prescription_name);
            new_image = itemView.findViewById(R.id.new_image);
            new_quantity = itemView.findViewById(R.id.quantity_items);
            new_time = itemView.findViewById(R.id.new_time);

        }

    }
}

Medicine Class

package com.example.myapplication;

public class Medicine {

    private String name_of_medicine, time_to_take;
    private int quantity_remaining, Photo, frequency, dosage;

    public Medicine(String name_of_medicine, String time_to_take, int quantity, int dosage, int photo) {
        this.name_of_medicine = name_of_medicine;
        this.time_to_take = time_to_take;
        this.quantity_remaining = quantity;
        this.dosage = dosage;
        Photo = photo;
    }

    public String getName()
    {
        return name_of_medicine;
    }
    public String getTime()
    {
        return time_to_take;
    }
    public int getFrequency() {
        return quantity_remaining;
    }
    public int getPhoto() {
        return Photo;
    }
}


问:
PHP / MySQL: Display some error after successfully updated the data
Currently, I create a system using CRUD function. I have some problems with my update function. The problem is, it will display the error at view_task.php like:

1) Undefined index: report_id at line 7
2) Undefined variable: task_name at line 50

The problem is, when I check the database, the data has been updated.

Below is my current code:

dashboard.php

```<code>   echo "<form method = 'post' action = 'view_task/view_task.php'>";
     echo "<input type = 'hidden' name = 'report_id' value = '".$report_id."'>";
     echo "<button type = 'submit' class='btn-primary'>View</button>";
   echo "</form>";
</code>```

view_task.php

```<code><?php

  require_once "../../../../config/configPDO.php";
  require_once "../../../../config/check.php";

  $report_id = $_POST['report_id']; //line 7

  $sql = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid LEFT JOIN ot_team ON ot_team.team_id = ot_users.team_id WHERE report_id = :report_id";
  $query = $conn->prepare($sql);
  $query->execute(array(':report_id' => $report_id));
  while($row = $query->fetch(PDO::FETCH_ASSOC)){

      $report_id = $row["report_id"];
      $task_name = $row["task_name"];

  }

?>

<form action="update_task_name.php" method="POST">
  <td><b>Task Name</b></td>
  <td colspan = '2'><input type="text" class="form-control" name="task_name" value="<?php echo $task_name; ?>"/></td> //line 50
  <input type="hidden" name="report_id" value="<?php echo $report_id ?>">
  <td><input type="submit" class="btn btn-primary btn-block" value = "Save" onclick="confirm('Are you sure?')"></td>
</form>
</code>```

update_task_name.php

```<code><?php

    require_once '../../../../config/configPDO.php';

    $update = "UPDATE ot_report SET task_name = :task_name WHERE report_id = :report_id";
    $stmt = $conn->prepare($update);
    $stmt->bindParam(':task_name', $_POST['task_name']);
    $stmt->bindParam(':report_id', $_POST['report_id']);
    $stmt->execute();

    class Result {}
    $response = new Result();
    $response->result = 'OK';
    $response->message = 'Update successful';
    header("Location: view_task.php");

?>
</code>```

Can anyone help me to fix this problem? Thanks

答:
in the view_task.php page the $ _POST ['report_id'] section is not defined after the data update, because in update_task_name.php you use a redirect header ("Location: view_task.php") which becomes the GET method

try to update

update_task_name.php

```<code>header ("Location: view_task.php?report_id=". $ _ POST ['report_id'])
</code>```

view_task.php //line 7

```<code>if (isset ($_POST['report_id'])) {
    $report_id = $_POST['report_id'];
} else if (isset ($_GET['report_id'])) {
    $report_id = $_GET['report_id'];
} else {
    die ("ID NOT DEFINED");
}
</code>```

Body:
Currently, I create a system using CRUD function. I have some problems with my update function. The problem is, it will display the error at view_task.php like:

1) Undefined index: report_id at line 7
2) Undefined variable: task_name at line 50

The problem is, when I check the database, the data has been updated.

Below is my current code:

dashboard.php

   echo "<form method = 'post' action = 'view_task/view_task.php'>";
     echo "<input type = 'hidden' name = 'report_id' value = '".$report_id."'>";
     echo "<button type = 'submit' class='btn-primary'>View</button>";
   echo "</form>";

view_task.php

<?php

  require_once "../../../../config/configPDO.php";
  require_once "../../../../config/check.php";

  $report_id = $_POST['report_id']; //line 7

  $sql = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid LEFT JOIN ot_team ON ot_team.team_id = ot_users.team_id WHERE report_id = :report_id";
  $query = $conn->prepare($sql);
  $query->execute(array(':report_id' => $report_id));
  while($row = $query->fetch(PDO::FETCH_ASSOC)){

      $report_id = $row["report_id"];
      $task_name = $row["task_name"];

  }

?>

<form action="update_task_name.php" method="POST">
  Task Name
  <input type="text" class="form-control" name="task_name" value="<?php echo $task_name; ?>"/>	 //line 50
  <input type="hidden" name="report_id" value="<?php echo $report_id ?>">
  <input type="submit" class="btn btn-primary btn-block" value = "Save" onclick="confirm('Are you sure?')">
</form>

update_task_name.php

<?php

    require_once '../../../../config/configPDO.php';

    $update = "UPDATE ot_report SET task_name = :task_name WHERE report_id = :report_id";
    $stmt = $conn->prepare($update);
    $stmt->bindParam(':task_name', $_POST['task_name']);
    $stmt->bindParam(':report_id', $_POST['report_id']);
    $stmt->execute();

    class Result {}
    $response = new Result();
    $response->result = 'OK';
    $response->message = 'Update successful';
    header("Location: view_task.php");

?>

Can anyone help me to fix this problem? Thanks

Body:
in the view_task.php page the $ _POST ['report_id'] section is not defined after the data update, because in update_task_name.php you use a redirect header ("Location: view_task.php") which becomes the GET method

try to update

update_task_name.php

header ("Location: view_task.php?report_id=". $ _ POST ['report_id'])

view_task.php //line 7

if (isset ($_POST['report_id'])) {
    $report_id = $_POST['report_id'];
} else if (isset ($_GET['report_id'])) {
    $report_id = $_GET['report_id'];
} else {
    die ("ID NOT DEFINED");
}


问:
mysqli query echo data from two tabels
I have two tables:

```<code>bb_users ( user_id, user_name, user_password .... )
bb_topics ( id, time, topic, sender, reciever)
</code>```

sender and reciever are related to user_id in the bb_users table. For example, sender 450 = user_id 450 = user_name "demouser".

When I export the data from the tables, I want to replace receiver and sender with their user_name.

```<code><?php

$con=mysqli_connect("$DB_HOST","$DB_USER","$DB_PASS","$DB_NAME");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,' SELECT * FROM bb_topics LIMIT 3000');

echo "<table border='1'>
<tr>
<th>id</th>
<th>time</th>
<th>topic</th>
<th>sender</th>
<th>receiver</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>"  . $row['time'] . "</td>";
echo "<td>" . $row['topic'] . "</td>";
echo "<td>" . $row['sender'] . "</td>";
echo "<td>" . $row['receiver'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>
</code>```

The export looks like:

```<code>id   | time        | topic      |  sender    | receiver
1    | 1580471226  | demo topic |    320     |  150
</code>```

user_id of sender 320, his user_name in bb_users = "demotest", receiver = "demo2".

I used LIMIT 3000 because there is a lot of data to be exported. Sometimes I got a PHP fatal error.

How can I convert sender and receiver to their real username, and how to convert time from timestamp to date?

答:
I would advise a more complex SQL Query.

Example: http://sqlfiddle.com/#!9/df5e0e8/14/0

```<code>SELECT t.id, FROM_UNIXTIME(t.time, "%Y-%m-%d %H:%i:%s") AS time, t.topic, u1.user_name AS sender, u2.user_name AS receiver
FROM bb_topics AS t
LEFT JOIN bb_users AS u1 ON u1.user_id = t.sender
LEFT JOIN bb_users AS u2 ON u2.user_id = t.receiver;
</code>```

The output would be:

```<code>| id |                time |      topic |   sender | receiver |
|----|---------------------|------------|----------|----------|
|  1 | 2020-01-31 11:47:06 | demo topic | hsimpson | msimpson |
</code>```

You can also send the Epoch Time to JavaScript if you want.

Title: mysqli query echo data from two tabels

Body:
I have two tables:

bb_users ( user_id, user_name, user_password .... )
bb_topics ( id, time, topic, sender, reciever)

sender and reciever are related to user_id in the bb_users table. For example, sender 450 = user_id 450 = user_name "demouser".

When I export the data from the tables, I want to replace receiver and sender with their user_name.

<?php

$con=mysqli_connect("$DB_HOST","$DB_USER","$DB_PASS","$DB_NAME");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,' SELECT * FROM bb_topics LIMIT 3000');

echo "

id
time
topic
sender
receiver

";

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['id'] . "	";
echo ""  . $row['time'] . "	";
echo "" . $row['topic'] . "	";
echo "" . $row['sender'] . "	";
echo "" . $row['receiver'] . "	";
echo "
";
}
echo "
";

mysqli_close($con);
?>

The export looks like:

id   | time        | topic      |  sender    | receiver
1    | 1580471226  | demo topic |    320     |  150

user_id of sender 320, his user_name in bb_users = "demotest", receiver = "demo2".

I used LIMIT 3000 because there is a lot of data to be exported. Sometimes I got a PHP fatal error.

How can I convert sender and receiver to their real username, and how to convert time from timestamp to date?

Body:
I would advise a more complex SQL Query.

Example: http://sqlfiddle.com/#!9/df5e0e8/14/0

SELECT t.id, FROM_UNIXTIME(t.time, "%Y-%m-%d %H:%i:%s") AS time, t.topic, u1.user_name AS sender, u2.user_name AS receiver
FROM bb_topics AS t
LEFT JOIN bb_users AS u1 ON u1.user_id = t.sender
LEFT JOIN bb_users AS u2 ON u2.user_id = t.receiver;

The output would be:

| id |                time |      topic |   sender | receiver |
|----|---------------------|------------|----------|----------|
|  1 | 2020-01-31 11:47:06 | demo topic | hsimpson | msimpson |

You can also send the Epoch Time to JavaScript if you want.


问:
How to sort associative array in Javascript?
I need to sort associative array by JS for one of my projects. I found this function, that works great in firefox, but unfortunately it doesnt work in IE8, OPERA, CHROME... Cant find the way to make it work in other browsers, or find another function that would fit the purpose. I really appreciate any help.</p>

```<code>function sortAssoc(aInput)
{
    var aTemp = [];
    for (var sKey in aInput) aTemp.push([sKey, aInput[sKey].length]);
    aTemp.sort(function () {return arguments[0][1] < arguments[1][1]});
    var aOutput = new Object();
    //for (var nIndex = aTemp.length-1; nIndex >=0; nIndex--)
    for (var nIndex = 0; nIndex <= aTemp.length-1; nIndex++)
        aOutput[aTemp[nIndex][0]] = aInput[aTemp[nIndex][0]];
    //aOutput[aTemp[nIndex][0]] = aTemp[nIndex][1];
    return aOutput;
}
</code>```

答:
I know it's an old post but that work :

problem is

```<code>aTemp.sort(function () {return arguments[0][1] < arguments[1][1]});
</code>```

because the sort function attends a number :

```<code>aTemp.sort(function (a, b) {
    if (a[1] < b[1])
        return 1;
    else if (a[1] > b[1])
        return -1;
    else
        return 0;
});
</code>```

Body:
I need to sort associative array by JS for one of my projects. I found this function, that works great in firefox, but unfortunately it doesnt work in IE8, OPERA, CHROME... Cant find the way to make it work in other browsers, or find another function that would fit the purpose. I really appreciate any help.

function sortAssoc(aInput)
{
    var aTemp = [];
    for (var sKey in aInput) aTemp.push([sKey, aInput[sKey].length]);
    aTemp.sort(function () {return arguments[0][1] < arguments[1][1]});
    var aOutput = new Object();
    //for (var nIndex = aTemp.length-1; nIndex >=0; nIndex--)
    for (var nIndex = 0; nIndex <= aTemp.length-1; nIndex++)
        aOutput[aTemp[nIndex][0]] = aInput[aTemp[nIndex][0]];
    //aOutput[aTemp[nIndex][0]] = aTemp[nIndex][1];
    return aOutput;
}

Body:
I know it's an old post but that work :

problem is

aTemp.sort(function () {return arguments[0][1] < arguments[1][1]});

because the sort function attends a number :

aTemp.sort(function (a, b) {
    if (a[1] < b[1])
        return 1;
    else if (a[1] > b[1])
        return -1;
    else
        return 0;
});


问:
Azure AD B2C policy usage
Shall I use built in userflow for signup/signin and custom policy for forgot password in same react js application?</p>

答:
The answer is yes.

A sign-up or sign-in user flow with local accounts includes a Forgot password? link on the first page of the experience. Clicking this link doesn't automatically trigger a password reset user flow.

Instead, the error code AADB2C90118 is returned to your application. Your application needs to handle this error code by running a specific user flow that resets the password. To see an example, take a look at a simple ASP.NET sample that demonstrates the linking of user flows.

Reference:

https://github.com/damienbod/angular-auth-oidc-client/issues/83

Title: Azure AD B2C policy usage