问:
How to disable OOTB entryMergeFilterConfigurableProduct in custom extension?
I wanted to disable one of the entry filters(entryMergeFilterConfigurableProduct) provided by Hybris OOTB. Because of this filter, some cart entries are getting merged, though it is not supposed to as per our business logic.

I would like to override the definition in my custom extension. But it is not working as expected.

OOTB xml code:

```<code>    <alias name="defaultEntryMergeStrategy" alias="entryMergeStrategy"/>
        <bean id="defaultEntryMergeStrategy" class="de.hybris.platform.commerceservices.order.strategies.impl.DefaultEntryMergeStrategy">
        <property name="entryMergeFilters" ref="commerceCartEntryMergeFilters"/>
    </bean>

<bean id="entryMergeFilterConfigurableProduct" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterConfigurableProduct">
        <property name="productConfigurableChecker" ref="productConfigurableChecker" />
    </bean>

    <bean id="entryMergeFilterIsEntryUpdatable" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterIsEntryUpdatable">
        <property name="entryOrderChecker" ref="commerceOrderEntryModifiableChecker" />
    </bean>

    <bean id="entryMergeFilterPointOfService" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterPointOfService"/>

    <bean id="entryMergeFilterGiveAway" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterGiveAway"/>

    <bean id="entryMergeFilterProduct" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterProduct"/>

    <bean id="entryMergeFilterUnits" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterUnits"/>

    <bean id="entryMergeFilterEntryGroup" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterEntryGroup"/>

    <util:list id="commerceCartEntryMergeFilters" value-type="de.hybris.platform.commerceservices.order.EntryMergeFilter">
        <ref bean="entryMergeFilterEntryGroup"/>
        <ref bean="entryMergeFilterGiveAway"/>
        <ref bean="entryMergeFilterProduct"/>
        <ref bean="entryMergeFilterUnits"/>
        <ref bean="entryMergeFilterPointOfService"/>
        <ref bean="entryMergeFilterConfigurableProduct"/>
        <ref bean="entryMergeFilterIsEntryUpdatable"/>
    </util:list>
</code>```

Can you please let me know what needs to be changed to disable particular filter?

答:
For this purpose, ListMegreDerective might be helpful but a remove capability has not been introduced yet. This is available only for the populators list.
https://help.sap.com/viewer/b490bb4e85bc42a7aa09d513d0bcb18e/1905/en-US/515ccff5d01b427f851694fb8ec989e6.html

A usual solution is to override the bean e.g entryMergeFilterProduct or define the new bean for filters without the particular filter and make an alias.

```<code><alias name="customizedYourAssignedCartEntryMergeFilters" alias="commerceCartEntryMergeFilters"/>

<util:list id="customizedYourAssignedCartEntryMergeFilters" value-type="de.hybris.platform.commerceservices.order.EntryMergeFilter">
    <ref bean="entryMergeFilterEntryGroup"/>
    <!-Your list of the Filters-->
</util:list>
</code>```

Body:
I wanted to disable one of the entry filters(entryMergeFilterConfigurableProduct) provided by Hybris OOTB. Because of this filter, some cart entries are getting merged, though it is not supposed to as per our business logic.

I would like to override the definition in my custom extension. But it is not working as expected.

OOTB xml code:

    <alias name="defaultEntryMergeStrategy" alias="entryMergeStrategy"/>
        <bean id="defaultEntryMergeStrategy" class="de.hybris.platform.commerceservices.order.strategies.impl.DefaultEntryMergeStrategy">
        <property name="entryMergeFilters" ref="commerceCartEntryMergeFilters"/>
    </bean>

<bean id="entryMergeFilterConfigurableProduct" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterConfigurableProduct">
        <property name="productConfigurableChecker" ref="productConfigurableChecker" />
    </bean>

    <bean id="entryMergeFilterIsEntryUpdatable" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterIsEntryUpdatable">
        <property name="entryOrderChecker" ref="commerceOrderEntryModifiableChecker" />
    </bean>

    <bean id="entryMergeFilterPointOfService" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterPointOfService"/>

    <bean id="entryMergeFilterGiveAway" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterGiveAway"/>

    <bean id="entryMergeFilterProduct" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterProduct"/>

    <bean id="entryMergeFilterUnits" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterUnits"/>

    <bean id="entryMergeFilterEntryGroup" class="de.hybris.platform.commerceservices.order.impl.EntryMergeFilterEntryGroup"/>

    <util:list id="commerceCartEntryMergeFilters" value-type="de.hybris.platform.commerceservices.order.EntryMergeFilter">
        <ref bean="entryMergeFilterEntryGroup"/>
        <ref bean="entryMergeFilterGiveAway"/>
        <ref bean="entryMergeFilterProduct"/>
        <ref bean="entryMergeFilterUnits"/>
        <ref bean="entryMergeFilterPointOfService"/>
        <ref bean="entryMergeFilterConfigurableProduct"/>
        <ref bean="entryMergeFilterIsEntryUpdatable"/>
    </util:list>

Can you please let me know what needs to be changed to disable particular filter?

Body:
For this purpose, ListMegreDerective might be helpful but a remove capability has not been introduced yet. This is available only for the populators list.
https://help.sap.com/viewer/b490bb4e85bc42a7aa09d513d0bcb18e/1905/en-US/515ccff5d01b427f851694fb8ec989e6.html

A usual solution is to override the bean e.g entryMergeFilterProduct or define the new bean for filters without the particular filter and make an alias.

<alias name="customizedYourAssignedCartEntryMergeFilters" alias="commerceCartEntryMergeFilters"/>

<util:list id="customizedYourAssignedCartEntryMergeFilters" value-type="de.hybris.platform.commerceservices.order.EntryMergeFilter">
    <ref bean="entryMergeFilterEntryGroup"/>
    <!-Your list of the Filters-->
</util:list>


来源: stackexchange

问:
Reading value from QML in C++
I am trying to read an int value from my QML side on c++ but this value remains 0 and doesn't update on c++ side while console.log() clearly shows me that it increments after each click . What am I doing wrong here?

.qml file

```<code>FocusScope {

        property alias myrecordint: startbutton.recordint

        Rectangle {
            id: buttonPaneShadow
            width: bottomColumn.width + 16
            height: parent.height
            anchors.top: parent.top
            anchors.right: parent.right
            color: "white"

            Column {
                anchors {
                    right: parent.right
                    top: parent.top
                    margins: 8
                }

                id: buttonsColumn
                anchors.rightMargin: 20
                anchors.topMargin: 20
                spacing: 12

                CameraButton {
                    id: startbutton
                    property int recordint:0
                    text: "Record"
                    visible: camera.videoRecorder.recorderStatus == CameraRecorder.LoadedStatus
                    onClicked:
                    {
                        recordint=recordint+1
                        camera.videoRecorder.record()
                        console.log(recordint)

                    }
                }
           }
      }
 }
</code>```

.cpp file

```<code>   QQmlEngine engine;
   QQmlComponent component(&engine, QUrl("qrc:/VideoCaptureControls.qml"));
   QObject *object = component.create();
   qDebug() << "Property value:" << QQmlProperty::read(object, "myrecordint").toInt();
</code>```

答:
EDIT

After commenting back and forth, it seems you are not using the instance you should use, since you are creating a new instance on a button click.

Also, the reading of the property is execute-once and not auto-updated.

All-in-all this is a classic XY problem and you should strive to use a C++ model as also pointed out by Arnes (example 1 and example 2)

Original answer (wrong since the property is top-level)

You can only read properties from the top-level of a QML object (when reading from outside the object). You should move the property as suggested below:

```<code>Rectangle {
        id: buttonPaneShadow
        width: bottomColumn.width + 16
        height: parent.height
        anchors.top: parent.top
        anchors.right: parent.right
        color: "white"

        property int recordint:0 //move to here

        Column {
            anchors {
                right: parent.right
                top: parent.top
                margins: 8
            }

            id: buttonsColumn
            anchors.rightMargin: 20
            anchors.topMargin: 20
            spacing: 12

            CameraButton {
                id: startbutton
                text: "Record"
                visible: camera.videoRecorder.recorderStatus == CameraRecorder.LoadedStatus
                onClicked:
                {
                    recordint=recordint+1
                    camera.videoRecorder.record()
                    console.log(recordint)

                }
            }
    }
}
</code>```

Personally, I dislike the way you seem to implement this. I would rather go for a C++ model with properties that get updated, but that's up to you

ContentLicense: CC BY-SA 4.0

Title: Reading value from QML in C++

Body:
I am trying to read an int value from my QML side on c++ but this value remains 0 and doesn't update on c++ side while console.log() clearly shows me that it increments after each click . What am I doing wrong here?

.qml file

FocusScope {

        property alias myrecordint: startbutton.recordint

        Rectangle {
            id: buttonPaneShadow
            width: bottomColumn.width + 16
            height: parent.height
            anchors.top: parent.top
            anchors.right: parent.right
            color: "white"

            Column {
                anchors {
                    right: parent.right
                    top: parent.top
                    margins: 8
                }

                id: buttonsColumn
                anchors.rightMargin: 20
                anchors.topMargin: 20
                spacing: 12

                CameraButton {
                    id: startbutton
                    property int recordint:0
                    text: "Record"
                    visible: camera.videoRecorder.recorderStatus == CameraRecorder.LoadedStatus
                    onClicked:
                    {
                        recordint=recordint+1
                        camera.videoRecorder.record()
                        console.log(recordint)

                    }
                }
           }
      }
 }

.cpp file

   QQmlEngine engine;
   QQmlComponent component(&engine, QUrl("qrc:/VideoCaptureControls.qml"));
   QObject *object = component.create();
   qDebug() << "Property value:" << QQmlProperty::read(object, "myrecordint").toInt();

Body:
EDIT

After commenting back and forth, it seems you are not using the instance you should use, since you are creating a new instance on a button click.

Also, the reading of the property is execute-once and not auto-updated.

All-in-all this is a classic XY problem and you should strive to use a C++ model as also pointed out by Arnes (example 1 and example 2)

Original answer (wrong since the property is top-level)

You can only read properties from the top-level of a QML object (when reading from outside the object). You should move the property as suggested below:

Rectangle {
        id: buttonPaneShadow
        width: bottomColumn.width + 16
        height: parent.height
        anchors.top: parent.top
        anchors.right: parent.right
        color: "white"

        property int recordint:0 //move to here

        Column {
            anchors {
                right: parent.right
                top: parent.top
                margins: 8
            }

            id: buttonsColumn
            anchors.rightMargin: 20
            anchors.topMargin: 20
            spacing: 12

            CameraButton {
                id: startbutton
                text: "Record"
                visible: camera.videoRecorder.recorderStatus == CameraRecorder.LoadedStatus
                onClicked:
                {
                    recordint=recordint+1
                    camera.videoRecorder.record()
                    console.log(recordint)

                }
            }
    }
}

Personally, I dislike the way you seem to implement this. I would rather go for a C++ model with properties that get updated, but that's up to you


问:
Lex :Match multiple regex at the same time
I have the code below:
I want to count the number of characters using

```<code>(.)   {charCount++;}
</code>```

and at the same time count the number of words using

```<code>([a-zA-Z0-9])*    {wordcount++;}
</code>```

is this possible using lex rules, or do I have to count it "manaully/programmatically" using  the file stream in c code . Basically is there code for "continue matching/ regex"

```<code>%%
[\t ]+  ; //ignore white space
"\n" ;  //ignore next line //
([a-zA-Z0-9])*    {wordcount++;}
(.)   {charCount++;}
%%
int yywrap(void){}
int main()
{
    // The function that starts the analysis
    yyin=fopen("input.txt", "r");
    yylex();
    printf("The number of words in the file is %d and charCount %d",count,wordSize);
    return 0;
}
</code>```

答:
The number of characters matched by a rule is available in yyleng, so you can do this:

```<code>[ \t\n]         ;
[a-zA-Z0-9]+    { ++wordcount; charcount += yyleng; }
.               { ++charcount; }
</code>```

But (f)lex is not designed to do multiple scans over the input. So there's no simple general solution.

FWIW, I'd use [[:alnum:]] instead of [a-zA-Z0-9] and [[:space:]] instead of [ \t\n].

Body:
I have the code below:
I want to count the number of characters using

(.)   {charCount++;}

and at the same time count the number of words using

([a-zA-Z0-9])*    {wordcount++;}

is this possible using lex rules, or do I have to count it "manaully/programmatically" using  the file stream in c code . Basically is there code for "continue matching/ regex"

%%
[\t ]+  ; //ignore white space
"\n" ;  //ignore next line //
([a-zA-Z0-9])*    {wordcount++;}
(.)   {charCount++;}
%%
int yywrap(void){}
int main()
{
    // The function that starts the analysis
    yyin=fopen("input.txt", "r");
    yylex();
    printf("The number of words in the file is %d and charCount %d",count,wordSize);
    return 0;
}

Body:
The number of characters matched by a rule is available in yyleng, so you can do this:

[ \t\n]         ;
[a-zA-Z0-9]+    { ++wordcount; charcount += yyleng; }
.               { ++charcount; }

But (f)lex is not designed to do multiple scans over the input. So there's no simple general solution.

FWIW, I'd use [[:alnum:]] instead of [a-zA-Z0-9] and [[:space:]] instead of [ \t\n].


问:
Looking for debugging advice on SSL errors from EKS using varnish
I know this is somewhat specific of a question, but I'm having a problem I can't seem to track down. I have a single pod deployed to EKS - the pod contains a python app, and a varnish reverse caching proxy. I'm serving chunked json (that is, streaming lines of json, a la http://jsonlines.org/), and it can be multiple GB of data.

The first time I make a request, and it hits the python server, everything acts correctly. It takes (much) longer than the cached version, but the entire set of json lines is downloaded. However, now that it's cached in varnish, if I use curl, I get:

```<code>curl: (56) GnuTLS recv error (-110): The TLS connection was non-properly terminated.
</code>```

or

```<code>curl: (56) GnuTLS recv error (-9): A TLS packet with unexpected length was received.
</code>```

The SSL is terminated at the ELB, and when I use curl from the proxy container itself (using curl http://localhost?....), there is no problem.

The hard part of this is that the problem is somewhat intermittent.

If there is any advice in terms of clever varnishlog usage, or anything of the same ilk on AWS, I'd be much obliged.

Thanks!

答:
Because TLS is terminated on your ELB loadbalancers, the connection between should be in plain HTTP.

The error is probably not coming from Varnish, because Varnish currently doesn't handle TLS  natively. I'm not sure if varnishlog can give you better insights in what is actually happening.

Checklist

The only checklist I can give you is the following:

Make sure the certificate you're using is valid

Make sure you're connecting to your target group over HTTP, not HTTPS

If you enable the PROXY protocol on your ELB, make sure Varnish has a -a listener that listens for PROXY protocol requests, on top of regular HTTP requests.

Debugging

Perform top-down debugging:

Increase the verbosity of your cURL calls and try to get more information about the error

Try accessing the logs of your ELB and get more details there

Get more information from your EKS logs

And finally, perform a varnislog -g request -q "ReqUrl eq '/your-url'" to get a full Varnishlog for a specific URL

Body:
I know this is somewhat specific of a question, but I'm having a problem I can't seem to track down. I have a single pod deployed to EKS - the pod contains a python app, and a varnish reverse caching proxy. I'm serving chunked json (that is, streaming lines of json, a la http://jsonlines.org/), and it can be multiple GB of data.

The first time I make a request, and it hits the python server, everything acts correctly. It takes (much) longer than the cached version, but the entire set of json lines is downloaded. However, now that it's cached in varnish, if I use curl, I get:

curl: (56) GnuTLS recv error (-110): The TLS connection was non-properly terminated.

or

curl: (56) GnuTLS recv error (-9): A TLS packet with unexpected length was received.

The SSL is terminated at the ELB, and when I use curl from the proxy container itself (using curl http://localhost?....), there is no problem.

The hard part of this is that the problem is somewhat intermittent.

If there is any advice in terms of clever varnishlog usage, or anything of the same ilk on AWS, I'd be much obliged.

Thanks!


问:
How can we pass all items in a list from model class repository to controller and then to view?
I need to pass all elements from a list to view through controller. The list was created and it is coded in Model class. I had used findAll but it doesn't work.
I don't need any particular condition to satisfy!
here is my list

```<code>Rq = new List<Customers>()
{
    new Customers{Id=2, Fname="Thomas", Lname="shelby", Location="Canada",Contact=9874561230,Email="thomas@gmail.com",Password="143",Category="developer",Status="pending"},
    new Customers{Id=3, Fname="markuz", Lname="shelby", Location="Britan",Contact=9874561239,Email="mark@gmail.com",Password="13",Category="user",Status="approved"},
    new Customers{Id=1, Fname="James", Lname="M", Location="Kottayam", Contact=9685748596, Email="james@gmail.com", Password="123", Category="admin", Status="approved" },
};
</code>```

I had used this function

```<code>public Customers Addap(Customers customers)
{
    return Rq.FindAll(p => p.Id > 1);
}
</code>```

Addap is my action in home controller.

```<code>public async Task<IActionResult> AddapAsync()
{
    ViewBag.oid = oid;
    HttpResponseMessage Res = await client.GetAsync("https://localhost:44397/api/Values/Addap");
    if (Res.IsSuccessStatusCode)
    {
        Customers user = JsonConvert.DeserializeObject<Customers>(await Res.Content.ReadAsStringAsync());
        ViewBag.Customers = user;
        return View(user);
    }
    else
    {
        return RedirectToAction("Error", "Home");
    }
}
</code>```

my api controller is

```<code>[HttpGet("Addap")]
public IActionResult Addap(Customers customers)
{
    cust = new Customers();
    cust = _customerRepo.Addap(customers);
    if (cust != null)
    {
        return Ok(cust);
    }
    else
    {
        return (null);
    }
}
</code>```

view i have used

```<code>@{Customer.Models.Customers cust = ViewBag.Customers;
    int id = ViewBag.oid;
}
<html>

<head>
</head>

<body>
    <form asp-controller="Home">
        <table class="table">
            <thead>
                <tr>
                    <th>
                        ID
                    </th>
                    <th>
                        FNAME
                    </th>
                    <th>
                        LNAME
                    </th>
                    <th>
                        LOCATION
                    </th>
                    <th>
                        CONTACT
                    </th>
                    <th>
                        EMAIL
                    </th>

                    <th>
                        PASSWORD
                    </th>

                    <th>
                        CATEGORY
                    </th>
                    <th>
                        STATUS
                    </th>

                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model) {
                <tr>

                    <td>@cust.Id</td>
                    <td>@cust.Fname</td>
                    <td>@cust.Lname</td>
                    <td>@cust.Location</td>
                    <td>@cust.Contact</td>
                    <td>@cust.Email</td>
                    <td>**********</td>
                    <td>@cust.Category</td>
                    <td>@cust.Status</td>
                    <td>
                        <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action(" Approve ", "Home ", new { cust.Id})'">Details</button>
                    </td>
                    <td>
                        <button type="button" class="btn btn-primary" onclick="">Activity Log</button>
                    </td>
                </tr>
                }
                <tr>
                    <td>
                        <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action(" Details ", "Home ", new { id})'">Back</button>
                    </td>
                </tr>

            </tbody>
        </table>
    </form>
</body>

</html>
</code>```

答:
Okay, so you need to return a List of customers instead of only one customer therefore in your API method, make an instance of List<Customers>:

```<code>[HttpGet("Addap")]
public IActionResult Addap(Customers customers)
{
  List<Customers> cust = new List<Customers>();
  cust = _customerRepo.Addap(customers);
  if (cust != null)
  {
    return Ok(cust);
  }
  else
  {
    return (null);
  }
}
</code>```

Also your Addap should return a List<Customers>. I also observed that you are sending a Customer object to this method but is that actually required? Maybe you wanted to do something like:

```<code>public List<Customers> Addap(Customers customers)
{
    return Rq.FindAll(p => p.Id > 1);
    //return Rq.FindAll(p => p.Id == customers.Id);
}
</code>```

Now once you are returning the data that you need via your API, you can de-serialize the above response as:

```<code>public async Task<IActionResult> AddapAsync()
{
  ViewBag.oid = oid;
  HttpResponseMessage Res = await client.GetAsync("https://localhost:44397/api/Values/Addap");
  if (Res.IsSuccessStatusCode)
  {
    List<Customers> user = JsonConvert.DeserializeObject<List<Customers>>(await Res.Content.ReadAsStringAsync());
    ViewBag.Customers = user;
    return View(user);
  }
  else
  {
     return RedirectToAction("Error", "Home");
  }
}
</code>```

And finally in your View, you can loop over this ViewBag as:

```<code>@foreach(var customer in ViewBag.Customers)
{
  <tr>
  <td>@customer.Fname</td>
  <td>@customer.LName</td>
  <!-- So On -->
  </tr>
}
</code>```

Body:
I need to pass all elements from a list to view through controller. The list was created and it is coded in Model class. I had used findAll but it doesn't work.
I don't need any particular condition to satisfy!
here is my list

Rq = new List<Customers>()
{
    new Customers{Id=2, Fname="Thomas", Lname="shelby", Location="Canada",Contact=9874561230,Email="thomas@gmail.com",Password="143",Category="developer",Status="pending"},
    new Customers{Id=3, Fname="markuz", Lname="shelby", Location="Britan",Contact=9874561239,Email="mark@gmail.com",Password="13",Category="user",Status="approved"},
    new Customers{Id=1, Fname="James", Lname="M", Location="Kottayam", Contact=9685748596, Email="james@gmail.com", Password="123", Category="admin", Status="approved" },
};

I had used this function

public Customers Addap(Customers customers)
{
    return Rq.FindAll(p => p.Id > 1);
}

Addap is my action in home controller.

public async Task<IActionResult> AddapAsync()
{
    ViewBag.oid = oid;
    HttpResponseMessage Res = await client.GetAsync("https://localhost:44397/api/Values/Addap");
    if (Res.IsSuccessStatusCode)
    {
        Customers user = JsonConvert.DeserializeObject<Customers>(await Res.Content.ReadAsStringAsync());
        ViewBag.Customers = user;
        return View(user);
    }
    else
    {
        return RedirectToAction("Error", "Home");
    }
}

my api controller is

[HttpGet("Addap")]
public IActionResult Addap(Customers customers)
{
    cust = new Customers();
    cust = _customerRepo.Addap(customers);
    if (cust != null)
    {
        return Ok(cust);
    }
    else
    {
        return (null);
    }
}

view i have used

@{Customer.Models.Customers cust = ViewBag.Customers;
    int id = ViewBag.oid;
}

    <form asp-controller="Home">

                        ID

                        FNAME

                        LNAME

                        LOCATION

                        CONTACT

                        EMAIL

                        PASSWORD

                        CATEGORY

                        STATUS

                @foreach (var item in Model) {

                    @cust.Id
                    @cust.Fname
                    @cust.Lname
                    @cust.Location
                    @cust.Contact
                    @cust.Email
                    **********
                    @cust.Category
                    @cust.Status

                        <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action(" Approve ", "Home ", new { cust.Id})'">Details</button>

                        <button type="button" class="btn btn-primary" onclick="">Activity Log</button>

                }

                        <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action(" Details ", "Home ", new { id})'">Back</button>

    </form>

Body:
Okay, so you need to return a List of customers instead of only one customer therefore in your API method, make an instance of List<Customers>:

[HttpGet("Addap")]
public IActionResult Addap(Customers customers)
{
  List<Customers> cust = new List<Customers>();
  cust = _customerRepo.Addap(customers);
  if (cust != null)
  {
    return Ok(cust);
  }
  else
  {
    return (null);
  }
}

Also your Addap should return a List<Customers>. I also observed that you are sending a Customer object to this method but is that actually required? Maybe you wanted to do something like:

public List<Customers> Addap(Customers customers)
{
    return Rq.FindAll(p => p.Id > 1);
    //return Rq.FindAll(p => p.Id == customers.Id);
}

Now once you are returning the data that you need via your API, you can de-serialize the above response as:

public async Task<IActionResult> AddapAsync()
{
  ViewBag.oid = oid;
  HttpResponseMessage Res = await client.GetAsync("https://localhost:44397/api/Values/Addap");
  if (Res.IsSuccessStatusCode)
  {
    List<Customers> user = JsonConvert.DeserializeObject<List<Customers>>(await Res.Content.ReadAsStringAsync());
    ViewBag.Customers = user;
    return View(user);
  }
  else
  {
     return RedirectToAction("Error", "Home");
  }
}

And finally in your View, you can loop over this ViewBag as:

@foreach(var customer in ViewBag.Customers)
{
  <tr>
  <td>@customer.Fname</td>
  <td>@customer.LName</td>
  <!-- So On -->
  </tr>
}


问:
Calling Javascript Function With PHP
I'm trying to call a javascript function with PHP.

Javascript function as below:

```<code><script type="text/javascript">
function printDiv(divName)
{
    var printContents = document.getElementById(divName).innerHTML;
    var originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}
</script>
</code>```

I use this code to run function with PHP:

```<code>if (array_key_exists('ykpost', $_POST)) {
    // do something with php
    $printyk = '<script type="text/javascript">printDiv("PrintableArea");</script>';
    echo $printyk;
}
</code>```

Print content as below:

```<code><div id="printableArea" class="printDiv">
    //some content with created by php
</div>
</code>```

I post with this form:

```<code><form id="ykbarcodepost" method="post">
    <input type="submit" class="btn" value="Print Barcode" name="ykpost" />
</form>
</code>```

But it doesn't open print window. If I change $printyk variable as "Hello" it writes Hello.
So thought problem with javascript. But when I try with another button as below

```<code><input type="button" class="btn" onclick="printDiv('printableArea')" value="Print Barcode" />
</code>```

It shows printDiv. Is there anything which I couldn't see ?

答:
You have errors in your HTML based on what you provided, in this code:

```<code>...
// do something with php
$printyk = '<script type="text/javascript">printDiv("PrintableArea")
...
</code>```

PrintableArea should be printableArea,

One thing to mention here is always use alternative if syntax when mixing if statement and HTML for readability.

Here is a working PHP code I reproduced on my local machine:

```<code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>PRINCE Is Not a Cheat-sheet for Emacs</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta name="generator" content="Prince Backend" />
<meta name="date" content="2020-01-25T19:09:08" />
<meta name="description" content="A mind map for the Emacs commands." />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div id="printableArea" class="printDiv">
    //some content with created by php
    <div>ASDAD</div>
  </div>
  <form id="ykbarcodepost" method="post">
  <input type="submit" class="btn" value="Print Barcode" name="ykpost" />
</form>
<script type="text/javascript">
  function printDiv(divName)
  {
      var printContents = document.getElementById(`${divName}`).innerHTML;
      var originalContents = document.body.innerHTML;
      document.body.innerHTML = printContents;
      window.print();
      document.body.innerHTML = originalContents;
  }

  <?php if (array_key_exists('ykpost', $_POST)) : ?>
    // do something with php
    printDiv("printableArea");
  <?php endif ?>
</script>
</body>
</html>
</code>```

Title: Calling Javascript Function With PHP

Body:
I'm trying to call a javascript function with PHP.

Javascript function as below:

I use this code to run function with PHP:

if (array_key_exists('ykpost', $_POST)) {
    // do something with php
    $printyk = '';
    echo $printyk;
}

Print content as below:

    //some content with created by php

I post with this form:

<form id="ykbarcodepost" method="post">
    <input type="submit" class="btn" value="Print Barcode" name="ykpost" />
</form>

But it doesn't open print window. If I change $printyk variable as "Hello" it writes Hello.
So thought problem with javascript. But when I try with another button as below

<input type="button" class="btn" onclick="printDiv('printableArea')" value="Print Barcode" />

It shows printDiv. Is there anything which I couldn't see ?

Body:
You have errors in your HTML based on what you provided, in this code:

...
// do something with php
$printyk = '<script type="text/javascript">printDiv("PrintableArea")
...

PrintableArea should be printableArea,

One thing to mention here is always use alternative if syntax when mixing if statement and HTML for readability.

Here is a working PHP code I reproduced on my local machine:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>PRINCE Is Not a Cheat-sheet for Emacs</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta name="generator" content="Prince Backend" />
<meta name="date" content="2020-01-25T19:09:08" />
<meta name="description" content="A mind map for the Emacs commands." />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div id="printableArea" class="printDiv">
    //some content with created by php
    <div>ASDAD</div>
  </div>
  <form id="ykbarcodepost" method="post">
  <input type="submit" class="btn" value="Print Barcode" name="ykpost" />
</form>
<script type="text/javascript">
  function printDiv(divName)
  {
      var printContents = document.getElementById(`${divName}`).innerHTML;
      var originalContents = document.body.innerHTML;
      document.body.innerHTML = printContents;
      window.print();
      document.body.innerHTML = originalContents;
  }

  <?php if (array_key_exists('ykpost', $_POST)) : ?>
    // do something with php
    printDiv("printableArea");
  <?php endif ?>
</script>
</body>
</html>


问:
how to load data in table and bind the same to view Model class in .net core mvc (without refreshing the page)
I'm trying to add data in table via server but unable to succeed. I tried many things but nothing worked. I'm getting the data from the server but unable to populate that in table.. can someone please help me out?
I'm getting this :
"DataTables warning: table id=particlarsTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"

Let me explain my code first:
(In View)
When I click on "Add New Particular" button, bootstrap modal will popup with input fields, those fields will send to the server then again back to view and populate the table with the same data without refreshing the whole page.

I'm stuck on the last stage, I'm getting the data on UI/View in ajax success handler but unable to load that data in table.

here is my view :

```<code>
<form class="form-horizontal" method="post" id="createAdHocForm">
    <div class="row">
        <div class="col-md-3">
            <div class="form-group">
                <label>Select Flat</label>
                <select asp-for="AdHocInvoice.FlatRid" asp-items="@(new SelectList(Model.Flats,"FlatRid","FlatNumber"))" class="form-control form-control-sm selectpicker" data-live-search="true">
                    <option selected disabled value="">Select One</option>
                </select>
            </div>
        </div>
    </div>
    <table class="table table-sm table-responsive-md nowrap w-100" id="particlarsTable">
        <thead class="thead-light">
            <tr>
                <th>Particulars</th>
                <th>Amount</th>
                <th></th>
            </tr>
        </thead>
        <tbody class="bg-white">
            @foreach (var item in Model.AdHocInvoice.FlatInvoiceItems)
            {
                <tr>
                    <td>@item.Particular</td>
                    <td>@item.Amount</td>
                    <td></td>
                </tr>
            }
        </tbody>
    </table>
    <button class="btn btn-sm btn-outline-info" type="button" onclick="showParticularForm()">Add New Particular</button>
    <hr />
    <div class="row text-center">
            <button class="btn btn-sm btn-outline-success mx-auto" type="submit">Submit</button>
        </div>
</form>
</code>```

bootstrap modal to fill the table :

```<code><div class="modal fade" id="particularWindow">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Invoice Items</h4>
                <button type="button" class="close" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" method="post" id="particularForm">
                    <div class="row">
                        <div class="col-md-5">
                            <div class="form-group">
                                <label>Enter Particular</label>
                                <input id="particularName" name="particular" class="form-control form-control-sm" required />
                            </div>
                        </div>
                        <div class="col-md-5">
                            <label>Amount</label>
                            <input id="particularAmount" name="amount" class="form-control form-control-sm" required />
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-sm btn-outline-success mt-4" id="btnParticularSubmit" type="button" onclick="addParticular()">Add</button>
                        </div>
                    </div>

                </form>
            </div>
        </div>
    </div>
</div>

</code>```

Scripts:

```<code><link rel="stylesheet" href="~/DataTables/datatables.min.css" />
<script type="text/javascript" src="~/DataTables/datatables.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#particlarsTable').DataTable();
    });

    function showParticularForm() {
        $('#particularWindow').modal('show');
    }

    function addParticular() {
        var particular = $('#particularName').val();
        var amount = $('#particularAmount').val();
        $.ajax({
            url: '/FlatInvoice/AddParticular',
            data: 'particular=' + particular + '&amount=' + amount,
            success: function (response) {
                $('#particlarsTable').DataTable().ajax.reload()
            }
        });
    }
</script>

</code>```

Action Method on controller:

```<code>public JsonResult AddParticular(string particular, decimal amount)
        {
            _flatInvoiceViewModel.AdHocInvoice.FlatInvoiceItems.Add(new FlatInvoiceItem { Particular = particular, Amount = amount });
            return Json(_flatInvoiceViewModel);
        }

</code>```

Class/Model:

```<code>public class FlatInvoiceItem
    {
        public Guid FlatInvoiceItemRid { get; set; }
        public Guid FlatInvoiceRid { get; set; }
        public Guid FundRuleRid { get; set; }
        public string Particular { get; set; }
        public decimal Amount { get; set; }
    }
</code>```

NOTE: this code is in initial phase, I need that input data on server for further process(will add code later) so don't want to use $.('#table_body_id').append("
..
"); type of code.

答:
1.Firstly,reload() is used to send request back to the method which display the DataTable initially(e.g. name this method Test).

2.Secondly,From your AddParticular method,you just add a data to the list but the lifetime is just one request,so when you reload to Test method,the list still contains the initial data without new data.

Conclusion: I suggest that you could save data to database.And get data from database.

Here is a working demo about how to use DataTabale:

1.Model:

```<code>public class Test
{
    public int Id { get; set; }
    public AdHocInvoice AdHocInvoice { get; set; }
}
public class AdHocInvoice
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<FlatInvoiceItem> FlatInvoiceItems { get; set; }
}
public class FlatInvoiceItem
{
    public int Id { get; set; }
    public Guid FlatInvoiceItemRid { get; set; }
    public Guid FlatInvoiceRid { get; set; }
    public Guid FundRuleRid { get; set; }
    public string Particular { get; set; }
    public decimal Amount { get; set; }
}
public class ViewModel
{
    public string Particular { get; set; }
    public decimal Amount { get; set; }
}
</code>```

2.View:

```<code><form class="form-horizontal" method="post" id="createAdHocForm">
    <table class="table table-sm table-responsive-md nowrap w-100" id="particlarsTable">
        <thead class="thead-light">
            <tr>
                <th>Particulars</th>
                <th>Amount</th>
                <th></th>
            </tr>
        </thead>
        @*<tbody class="bg-white">
            @foreach (var item in Model.AdHocInvoice.FlatInvoiceItems)
            {
                <tr>
                    <td id="particular">@item.Particular</td>
                    <td id="amount">@item.Amount</td>
                    <td></td>
                </tr>
            }
        </tbody>*@   //DataTable no need to add this tbody
    </table>
    <button class="btn btn-sm btn-outline-info" type="button" onclick="showParticularForm()">Add New Particular</button>
    <hr />
    <div class="row text-center">
        <button class="btn btn-sm btn-outline-success mx-auto" type="submit">Submit</button>
    </div>
</form>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
    $(document).ready(function () {
        //$('#particlarsTable').DataTable();
        $('#particlarsTable').DataTable({
            ajax: {
                type: 'GET',
                dataType: 'JSON',
                url: '@Url.Action("Test", "Home")',
            },
            columns: [
                { 'data': 'particular' },
                { 'data': 'amount' }
            ]
        })
    });
function showParticularForm() {
    $('#particularWindow').modal('show');
}
function addParticular() {
    var particular = $('#particularName').val();
    var amount = $('#particularAmount').val();
    $.ajax({
        url: '/Home/AddParticular',
        data: 'particular=' + particular + '&amount=' + amount
    }).done(function (data) {
        $('#particularWindow').modal('hide');
        $('#particlarsTable').DataTable().ajax.reload();
    });
}
</script>
</code>```

3.Controller:

```<code>public class HomeController : Controller
{
    private readonly MyDbContext _context;

    public HomeController(MyDbContext context)
    {
        _context = context;
    }
    public IActionResult Index()
    {
        return View();
    }
    public JsonResult Test()
    {
        var _flatInvoiceViewModel = _context.Test.Include(i=>i.AdHocInvoice)
            .ThenInclude(a=>a.FlatInvoiceItems).Where(i => i.Id == 1).FirstOrDefault();
        var list = new List<ViewModel>();
        foreach (var item in  _flatInvoiceViewModel.AdHocInvoice.FlatInvoiceItems)
        {
            var model = new ViewModel() { Amount = item.Amount, Particular = item.Particular };
            list.Add(model);
        }
        return Json(new { data = list });
    }
    public void AddParticular(string particular, decimal amount)
    {
        var _flatInvoiceViewModel = _context.Test.Include(i => i.AdHocInvoice)
.ThenInclude(a => a.FlatInvoiceItems).Where(i => i.Id == 1).FirstOrDefault();
        _flatInvoiceViewModel.AdHocInvoice.FlatInvoiceItems.Add(new FlatInvoiceItem { Particular = particular, Amount = amount });
        _context.SaveChanges();

    }
</code>```

4.Result:

Reference:

https://datatables.net/examples/data_sources/ajax.html

https://stackoverflow.com/a/59449895/11398810

Body:
I'm trying to add data in table via server but unable to succeed. I tried many things but nothing worked. I'm getting the data from the server but unable to populate that in table.. can someone please help me out?
I'm getting this :
"DataTables warning: table id=particlarsTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"

Let me explain my code first:
(In View)
When I click on "Add New Particular" button, bootstrap modal will popup with input fields, those fields will send to the server then again back to view and populate the table with the same data without refreshing the whole page.

I'm stuck on the last stage, I'm getting the data on UI/View in ajax success handler but unable to load that data in table.

here is my view :

<form class="form-horizontal" method="post" id="createAdHocForm">

                Select Flat
                <select asp-for="AdHocInvoice.FlatRid" asp-items="@(new SelectList(Model.Flats,"FlatRid","FlatNumber"))" class="form-control form-control-sm selectpicker" data-live-search="true">
                    <option selected disabled value="">Select One</option>
                </select>

                Particulars
                Amount

            @foreach (var item in Model.AdHocInvoice.FlatInvoiceItems)
            {

                    @item.Particular
                    @item.Amount

            }

    <button class="btn btn-sm btn-outline-info" type="button" onclick="showParticularForm()">Add New Particular</button>

            <button class="btn btn-sm btn-outline-success mx-auto" type="submit">Submit</button>

</form>

bootstrap modal to fill the table :

Invoice Items

                <button type="button" class="close" data-dismiss="modal">×</button>

                <form class="form-horizontal" method="post" id="particularForm">

                                Enter Particular
                                <input id="particularName" name="particular" class="form-control form-control-sm" required />

                            Amount
                            <input id="particularAmount" name="amount" class="form-control form-control-sm" required />

                            <button class="btn btn-sm btn-outline-success mt-4" id="btnParticularSubmit" type="button" onclick="addParticular()">Add</button>

                </form>

Scripts:

<link rel="stylesheet" href="~/DataTables/datatables.min.css" />

Action Method on controller:

public JsonResult AddParticular(string particular, decimal amount)
        {
            _flatInvoiceViewModel.AdHocInvoice.FlatInvoiceItems.Add(new FlatInvoiceItem { Particular = particular, Amount = amount });
            return Json(_flatInvoiceViewModel);
        }

Class/Model:

public class FlatInvoiceItem
    {
        public Guid FlatInvoiceItemRid { get; set; }
        public Guid FlatInvoiceRid { get; set; }
        public Guid FundRuleRid { get; set; }
        public string Particular { get; set; }
        public decimal Amount { get; set; }
    }

NOTE: this code is in initial phase, I need that input data on server for further process(will add code later) so don't want to use $.('#table_body_id').append("
..
"); type of code.

Body:
1.Firstly,reload() is used to send request back to the method which display the DataTable initially(e.g. name this method Test).

2.Secondly,From your AddParticular method,you just add a data to the list but the lifetime is just one request,so when you reload to Test method,the list still contains the initial data without new data.

Conclusion: I suggest that you could save data to database.And get data from database.

Here is a working demo about how to use DataTabale:

1.Model:

public class Test
{
    public int Id { get; set; }
    public AdHocInvoice AdHocInvoice { get; set; }
}
public class AdHocInvoice
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<FlatInvoiceItem> FlatInvoiceItems { get; set; }
}
public class FlatInvoiceItem
{
    public int Id { get; set; }
    public Guid FlatInvoiceItemRid { get; set; }
    public Guid FlatInvoiceRid { get; set; }
    public Guid FundRuleRid { get; set; }
    public string Particular { get; set; }
    public decimal Amount { get; set; }
}
public class ViewModel
{
    public string Particular { get; set; }
    public decimal Amount { get; set; }
}

2.View:

<form class="form-horizontal" method="post" id="createAdHocForm">
    <table class="table table-sm table-responsive-md nowrap w-100" id="particlarsTable">
        <thead class="thead-light">
            <tr>
                <th>Particulars</th>
                <th>Amount</th>
                <th></th>
            </tr>
        </thead>
        @*<tbody class="bg-white">
            @foreach (var item in Model.AdHocInvoice.FlatInvoiceItems)
            {
                <tr>
                    <td id="particular">@item.Particular</td>
                    <td id="amount">@item.Amount</td>
                    <td></td>
                </tr>
            }
        </tbody>*@   //DataTable no need to add this tbody
    </table>
    <button class="btn btn-sm btn-outline-info" type="button" onclick="showParticularForm()">Add New Particular</button>
    <hr />
    <div class="row text-center">
        <button class="btn btn-sm btn-outline-success mx-auto" type="submit">Submit</button>
    </div>
</form>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
    $(document).ready(function () {
        //$('#particlarsTable').DataTable();
        $('#particlarsTable').DataTable({
            ajax: {
                type: 'GET',
                dataType: 'JSON',
                url: '@Url.Action("Test", "Home")',
            },
            columns: [
                { 'data': 'particular' },
                { 'data': 'amount' }
            ]
        })
    });
function showParticularForm() {
    $('#particularWindow').modal('show');
}
function addParticular() {
    var particular = $('#particularName').val();
    var amount = $('#particularAmount').val();
    $.ajax({
        url: '/Home/AddParticular',
        data: 'particular=' + particular + '&amount=' + amount
    }).done(function (data) {
        $('#particularWindow').modal('hide');
        $('#particlarsTable').DataTable().ajax.reload();
    });
}
</script>

3.Controller:

public class HomeController : Controller
{
    private readonly MyDbContext _context;

    public HomeController(MyDbContext context)
    {
        _context = context;
    }
    public IActionResult Index()
    {
        return View();
    }
    public JsonResult Test()
    {
        var _flatInvoiceViewModel = _context.Test.Include(i=>i.AdHocInvoice)
            .ThenInclude(a=>a.FlatInvoiceItems).Where(i => i.Id == 1).FirstOrDefault();
        var list = new List<ViewModel>();
        foreach (var item in  _flatInvoiceViewModel.AdHocInvoice.FlatInvoiceItems)
        {
            var model = new ViewModel() { Amount = item.Amount, Particular = item.Particular };
            list.Add(model);
        }
        return Json(new { data = list });
    }
    public void AddParticular(string particular, decimal amount)
    {
        var _flatInvoiceViewModel = _context.Test.Include(i => i.AdHocInvoice)
.ThenInclude(a => a.FlatInvoiceItems).Where(i => i.Id == 1).FirstOrDefault();
        _flatInvoiceViewModel.AdHocInvoice.FlatInvoiceItems.Add(new FlatInvoiceItem { Particular = particular, Amount = amount });
        _context.SaveChanges();

    }

4.Result:

Reference:

https://datatables.net/examples/data_sources/ajax.html

https://stackoverflow.com/a/59449895/11398810


问:
Why a || a = 'bar' will get a reference error in javascript?
The code snippet is:

```<code>var a = 'foo'
a || a = 'bar'
</code>```

What I expected is that it can work normally which means a will be 'bar' finally.But I got an error

Uncaught SyntaxError: Invalid left-hand side in assignment.

According to the error,I thought maybe it is something wrong with the left hand side expression a || a.It seems that a || a is invalid here.But why?I turn to ecmascript language specification for help.In 12.15.1 Static Semantics: Early Errors, I find:

It is an early Reference Error if LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral and AssignmentTargetType of LeftHandSideExpression is invalid.

So, the AssignmentTargetType of LeftHandSideExpression a||a is invalid.But I am confused why a||a 's AssignmentTargetType is invalid.About this,the specification just said:

12.15.3 Static Semantics: AssignmentTargetType

AssignmentExpression:

YieldExpression

ArrowFunction

AsyncArrowFunction

LeftHandSideExpression = AssignmentExpression

LeftHandSideExpression AssignmentOperator AssignmentExpression

Return invalid.

I can't figure out why a||a 's AssignmentTargetType is invalid based on what is given.

My question is: Why a||a = 'bar' will get a reference error in javascript?If it is something with invalid AssignmentTargetType of LeftHandSideExpression,why a||a is invalid?

答:
My question is: Why a||a = 'bar' will get a reference error in javascript?

It's not a reference error but a syntax error. That means the code you have written cannot be parsed into a valid program.

If it is something with invalid AssignmentTargetType of LeftHandSideExpression,why a||a is invalid?

It's much simpler than that: The syntax of an assignment expression, among other things, is

```<code>LeftHandSideExpression = AssignmentExpression
</code>```

That means on the left side of the = we need a LeftHandSideExpression.

|| is a LogicalORExpression but not a LeftHandSideExpression and therefore it cannot appear in this position.

You can think of the different types of expressions being organized in a hierarchy (I simplified the following example by leaving out some type of expressions):

```<code>AssignmentExpression
         ^
         |
LogicalORExpression
         ^
         |
LeftHandSideExpression
         ^
         |
PrimaryExpression
         ^
         |
Identifier Reference
</code>```

That is: An Identifier Reference is a PrimaryExpression is a LeftHandSideExpression, etc.

LogicalORExpression is higher up in the hierarchy which makes it a superset that includes LeftHandSideExpression. That means there are some expressions, such as ||, which are a LogicalORExpression but not a LeftHandSideExpression.

Body:
The code snippet is:

var a = 'foo'
a || a = 'bar'

What I expected is that it can work normally which means a will be 'bar' finally.But I got an error

Uncaught SyntaxError: Invalid left-hand side in assignment.

According to the error,I thought maybe it is something wrong with the left hand side expression a || a.It seems that a || a is invalid here.But why?I turn to ecmascript language specification for help.In 12.15.1 Static Semantics: Early Errors, I find:

It is an early Reference Error if LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral and AssignmentTargetType of LeftHandSideExpression is invalid.

So, the AssignmentTargetType of LeftHandSideExpression a||a is invalid.But I am confused why a||a 's AssignmentTargetType is invalid.About this,the specification just said:

12.15.3 Static Semantics: AssignmentTargetType

AssignmentExpression:

YieldExpression

ArrowFunction

AsyncArrowFunction

LeftHandSideExpression = AssignmentExpression

LeftHandSideExpression AssignmentOperator AssignmentExpression

Return invalid.

I can't figure out why a||a 's AssignmentTargetType is invalid based on what is given.

My question is: Why a||a = 'bar' will get a reference error in javascript?If it is something with invalid AssignmentTargetType of LeftHandSideExpression,why a||a is invalid?

Body:
My question is: Why a||a = 'bar' will get a reference error in javascript?

It's not a reference error but a syntax error. That means the code you have written cannot be parsed into a valid program.

If it is something with invalid AssignmentTargetType of LeftHandSideExpression,why a||a is invalid?

It's much simpler than that: The syntax of an assignment expression, among other things, is

LeftHandSideExpression = AssignmentExpression

That means on the left side of the = we need a LeftHandSideExpression.

|| is a LogicalORExpression but not a LeftHandSideExpression and therefore it cannot appear in this position.

You can think of the different types of expressions being organized in a hierarchy (I simplified the following example by leaving out some type of expressions):

AssignmentExpression
         ^
         |
LogicalORExpression
         ^
         |
LeftHandSideExpression
         ^
         |
PrimaryExpression
         ^
         |
Identifier Reference

That is: An Identifier Reference is a PrimaryExpression is a LeftHandSideExpression, etc.

LogicalORExpression is higher up in the hierarchy which makes it a superset that includes LeftHandSideExpression. That means there are some expressions, such as ||, which are a LogicalORExpression but not a LeftHandSideExpression.


问:
How to get an array from Firestore?
I have the data structure illustrated below stored in Cloud Firestore. I want to save the dungeon_group which is an array of strings stored in Firestore.

I have difficulty in getting the data and stored as an array. I am just able to get a weird string but any method to store as a string array? Below is the code I used.

I am able to achieve this in Swift as follow, but not sure how to do the same in Android.

Swift:

```<code>Firestore.firestore().collection("dungeon").document("room_en").getDocument {
    (document, error) in
    if let document = document {
        let group_array = document["dungeon_group"] as? Array ?? [""]
        print(group_array)
    }
}
</code>```

Java Android:

```<code>FirebaseFirestore.getInstance().collection("dungeon")
                 .document("room_en").get()
                 .addOnCompleteListener(new
                     OnCompleteListener<DocumentSnapshot>() {
                     @Override
                     public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                         DocumentSnapshot document = task.getResult();
                         String group_string= document.getData().toString();
                         String[] group_array = ????
                         Log.d("myTag", group_string);
                     }
                 });
</code>```

Console output as the follow:

{dungeon_group=[3P, Urgent, Mission Challenge, Descended,
Collaboration, Daily, Technical, Normal]}

答:
Since Your document looks like this "dongeon_group=[SP, urgent, missinon challenge,...] when you convert it to string, say via String.valueOf(document.getData())

I think another way to simply achieve this is by unpacking the document right away into a string of array as follows:

String[] unpackedDoc = document.getData().entrySet().toArray()[0].toString().split("=")[1].split(",");

Explanation

The document is gotten from documentSnapshot.getDocuments() which return a list containing you documents.

Since your documents, from the firestore, seem to be nested, calling the document.getData() will return the list, a list with single element of course, of your document.
document.getData().entrySet() will make the document ready to be converted to array (you can't do that with getData() alone) also containing single element.
Accessing the single element document.getData().entrySet().toArray()[0] and then converting it to string, document.getData().entrySet().toArray()[0].toString() will leave with a string that you can then split (using the = found in the string) and then take the second part.
The second part can also be split into an array containing the values of your document.

Since this solution convert one element at a time, you can wrap it within a loop so you can convert all the documents available.

For example:

for(DocumentSnapshot document :documentSnapshot.getDocuments()){
   String[] unpackedDoc = document.getData().entrySet().toArray()[0].toString().split("=")[1].split(",");
//do something with the unpacked doc

}

Title: How to get an array from Firestore?

Body:
I have the data structure illustrated below stored in Cloud Firestore. I want to save the dungeon_group which is an array of strings stored in Firestore.

I have difficulty in getting the data and stored as an array. I am just able to get a weird string but any method to store as a string array? Below is the code I used.

I am able to achieve this in Swift as follow, but not sure how to do the same in Android.

Swift:

Firestore.firestore().collection("dungeon").document("room_en").getDocument {
    (document, error) in
    if let document = document {
        let group_array = document["dungeon_group"] as? Array ?? [""]
        print(group_array)
    }
}

Java Android:

FirebaseFirestore.getInstance().collection("dungeon")
                 .document("room_en").get()
                 .addOnCompleteListener(new
                     OnCompleteListener<DocumentSnapshot>() {
                     @Override
                     public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                         DocumentSnapshot document = task.getResult();
                         String group_string= document.getData().toString();
                         String[] group_array = ????
                         Log.d("myTag", group_string);
                     }
                 });

Console output as the follow:

{dungeon_group=[3P, Urgent, Mission Challenge, Descended,
Collaboration, Daily, Technical, Normal]}


问:
How can I retrieve all rows which depend on other rows in the same table?
So I have this table scheme

|id| item_id | dependency_item_id | completed |

The idea is to have rows in this table to point to other rows in the same table by dependency_item_id -> item_id.

What I want is to retrieve all records which have a dependency_item_id with a value of NULL and completed with a value of 0

AND

All records which have their parent, row which is the one with the item_id = dependency_item_id, with status completed = 1 and their status completed = 0

Example:

```<code>These are the records in the database.
|id|task_id|dependency_item_id|completed|
|1 |1      |null              |1        |
|2 |2      |null              |0        |
|3 |3      |1                 |0        |
|4 |4      |2                 |0        |
|5 |5      |2                 |0        |

With the query we should get only the second record
|id|task_id|dependency_item_id|completed|
|2 |2      |null              |0        |
|3 |3      |1                 |0        |
</code>```

The query I have by this point is the following:

```<code>SELECT process.*
    FROM tasks AS tasks
        JOIN tasks AS dep ON dep.dependency_item_id = process.task_id
    WHERE (dep.completed = 1 and tasks.completed = 0) OR tasks.dependency_item_id IS NULL
</code>```

答:
This is the case where you would require a correlated subquery.</p>

```<code>Select * from items as I where (dependency_item is null and completed = 0 )
OR
item_id in (Select item_id from items as S where I.dependency_item = S.item_id and
I.completed = 0 and S.completed = 1)`
</code>```

Body:
So I have this table scheme

|id| item_id | dependency_item_id | completed |

The idea is to have rows in this table to point to other rows in the same table by dependency_item_id -> item_id.

What I want is to retrieve all records which have a dependency_item_id with a value of NULL and completed with a value of 0

AND

All records which have their parent, row which is the one with the item_id = dependency_item_id, with status completed = 1 and their status completed = 0

Example:

These are the records in the database.
|id|task_id|dependency_item_id|completed|
|1 |1      |null              |1        |
|2 |2      |null              |0        |
|3 |3      |1                 |0        |
|4 |4      |2                 |0        |
|5 |5      |2                 |0        |

With the query we should get only the second record
|id|task_id|dependency_item_id|completed|
|2 |2      |null              |0        |
|3 |3      |1                 |0        |

The query I have by this point is the following:

SELECT process.*
    FROM tasks AS tasks
        JOIN tasks AS dep ON dep.dependency_item_id = process.task_id
    WHERE (dep.completed = 1 and tasks.completed = 0) OR tasks.dependency_item_id IS NULL

Body:
This is the case where you would require a correlated subquery.

Select * from items as I where (dependency_item is null and completed = 0 )
OR
item_id in (Select item_id from items as S where I.dependency_item = S.item_id and
I.completed = 0 and S.completed = 1)`


问:
AWS Windows EC2 Instance is not connecting to internet
I am having a EC2 Windows instance in my AWS account. I have used 2019 base to create my machine, I am able to connect to my machine and I do not have internet connectivity in the instance. I am new to AWS, kindly provide your inputs to resolve the issue.</p>

答: Check whether you have created NAT gateway, and also check whether it is in available state. And also NAT should be created in Public subnet. Check these settings. And also check whether you are allowing outbound traffic to internet. </p>


问:
How to iterate over array in object with async pipe and dynamic property?
I have two objects layers$ and arrayByLayerId$ that I get asynchronously in my component, the structure of the objects is as following :

```<code>interface Layer {
   id: number;
   ...
}
</code>```

```<code>{
   1: []
   2: []
   ...
}
</code>```

Is there a way to iterate over arrayByLayerId$ arrays with the async pipe in the template like something below (the syntax is not correct it's just to illustrate what I try to achieve) :

```<code><div *ngFor="let layer of layers$ | async"
     [attr.id]="layer.id">

    <my-component *ngFor="let array of arrayByLayerId$[layer.id] | async" [array]="array"><my-component/>
</div>
</code>```

Thanks !

答:
arrayByLayerId$ does not have a value yet before you access its "layer.id" property. It should be like this :

```<code> <my-component *ngFor="let array of (arrayByLayerId$ | async)[layer.id]" [array]="array"><my-component/>
</code>```

Body:
I have two objects layers$ and arrayByLayerId$ that I get asynchronously in my component, the structure of the objects is as following :

interface Layer {
   id: number;
   ...
}

{
   1: []
   2: []
   ...
}

Is there a way to iterate over arrayByLayerId$ arrays with the async pipe in the template like something below (the syntax is not correct it's just to illustrate what I try to achieve) :

    <my-component *ngFor="let array of arrayByLayerId$[layer.id] | async" [array]="array"><my-component/>

Thanks !

Body:
arrayByLayerId$ does not have a value yet before you access its "layer.id" property. It should be like this :

 <my-component *ngFor="let array of (arrayByLayerId$ | async)[layer.id]" [array]="array"><my-component/>


问:
declaring constraint/polymorphic types in Common Lisp
In Haskell (and chicken scheme) you can declare constrained types,
for example map :: (a -> b) -> [a] -> [b] declares
that map will take a list containing the type of the function input, and return a list containing the function output.
Is the same possible in common lisp function declarations?
Could I do something analogous like this:

```<code>(declaim (ftype (function (function (a) b)
                          (list a))
                (list b)
                map))
</code>```

"you can't do that" would be a satisfactory answer :)

答: Not in a single type declaration.  We don't have type variables.</p>

Body:
In Haskell (and chicken scheme) you can declare constrained types,
for example map :: (a -> b) -> [a] -> [b] declares
that map will take a list containing the type of the function input, and return a list containing the function output.
Is the same possible in common lisp function declarations?
Could I do something analogous like this:

(declaim (ftype (function (function (a) b)
                          (list a))
                (list b)
                map))

"you can't do that" would be a satisfactory answer :)


问:
Date Format from Date in String to Date

Possible Duplicate:

String to Date in Different Format in Java

Hi,

I m receiving date as String data type in MM/dd/yyyy format and need to convert in data Datatype in format yyyy-MM-dd to store in DB.

答:
Use formatter for parsing the date to particular type</p>

```<code> String date="07/25/2011";
    SimpleDateFormat dateFormatter=new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date d=dateFormatter.parse(date);

            } catch (ParseException e) {
                  e.printStackTrace();
            }
</code>```

Title: Date Format from Date in String to Date

Body:
Use formatter for parsing the date to particular type

 String date="07/25/2011";
    SimpleDateFormat dateFormatter=new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date d=dateFormatter.parse(date);

            } catch (ParseException e) {
                  e.printStackTrace();
            }

ContentLicense: CC BY-SA 3.0


问:
how to check 2D array for duplicates
I am trying to remove duplicates from my 2D array but no success.

Here is what I am doing any idea where am making mistake?

function Remove_duplicates_from_2d_array(data_array) {
  if (data_array.length > 0) {
    let unique_index_counter = 0;
    // loop on target array
    for (var a = 0; a < data_array.length; a++) {
      var unique_array = data_array[unique_index_counter];

      if (a === unique_index_counter) {
        continue;
      }
      console.log('comparing index: ' + a + ' ( ' + data_array[a] + ' ) -- index: ' + a + ' ( ' + data_array[a] + ' )');
      if (data_array[a].sort().join(',') === unique_array.sort().join(',')) {
        console.log('match it index ' + a + ' - ' + unique_index_counter);
        // same arrays
        data_array.splice(a, 1);
        a = 0; // reset for loop as splice will rebuilt array
      }
      // a will be equal to data_array length incase there is no match found
      if (a === data_array.length) {
        unique_index_counter++;
      }
   if(unique_index_counter != data_array.length) {
  a = 0; // reset for loop because we have not checked all items
   }
    }

    return data_array;
  } else {
    return [];
  }
}

var a1 = [1, 2, 3];
b1 = [4, 4, 5];
c1 = [3, 4, 5];
d1 = [4, 4, 5];
var data_array = [];
data_array.push(a1);
data_array.push(b1);
data_array.push(c1);
data_array.push(d1);
console.log('original array.');
console.log(data_array);

var r = Remove_duplicates_from_2d_array(data_array);
console.log('unique array.');
console.log(r);  // [[1,2,3],[4,4,5],[3,4,5]]```

答:
You could take a Set for seen sorted string and filter the array by checking the occurences.

function removeDuplicates(array) {
    var seen = new Set;
    return array.filter(a => (s => !seen.has(s) && seen.add(s))(a.join()));
}

console.log(removeDuplicates([[1, 2, 3], [4, 4, 5], [3, 4, 5], [4, 4, 5]]));
// [[1, 2, 3], [4, 4, 5], [3, 4, 5]]```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

With an object.

function removeDuplicates(array) {
    var seen = {};
    return array.filter(v => !seen[v] && (seen[v] = true));
}

console.log(removeDuplicates([[1, 2, 3], [4, 4, 5], [3, 4, 5], [4, 4, 5]]));
// [[1, 2, 3], [4, 4, 5], [3, 4, 5]]```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: how to check 2D array for duplicates

Body:
You could take a Set for seen sorted string and filter the array by checking the occurences.

function removeDuplicates(array) {
    var seen = new Set;
    return array.filter(a => (s => !seen.has(s) && seen.add(s))(a.join()));
}

console.log(removeDuplicates([[1, 2, 3], [4, 4, 5], [3, 4, 5], [4, 4, 5]]));
// [[1, 2, 3], [4, 4, 5], [3, 4, 5]]

.as-console-wrapper { max-height: 100% !important; top: 0; }

With an object.

function removeDuplicates(array) {
    var seen = {};
    return array.filter(v => !seen[v] && (seen[v] = true));
}

console.log(removeDuplicates([[1, 2, 3], [4, 4, 5], [3, 4, 5], [4, 4, 5]]));
// [[1, 2, 3], [4, 4, 5], [3, 4, 5]]

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Custom AlertDialog.Builder positive and negative buttons not showing
Hello I followed every tutorial in Stack Overflow and YouTube anyways once I got to display my RecyclerView then I needed to accomplish other things with no problem at all. Anyways my only problem is that the positive button and the negative buttons disappeared. I assume that the problem might be that the things I have done in my XML is overlapping with the buttons in the view but I only have 3 items in the RecyclerView, so this is my big doubt. I made the dialog in an onLongClick then I added a RecyclerView method to get the position and the data present in the row that's why I cant call the alertDialog.setPositiveButton() in another place. This is quite a challenge would be appreciated to get some help in this.

This is my XML

```<code><androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <TextView
        android:id="@+id/text_adm_asigna_asesor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:fontFamily="@font/poppins_bold"
        android:text="Asigna un asesor"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="30dp"
        android:visibility="visible"
        android:layout_marginRight="30dp" />

        <LinearLayout
            android:id="@+id/linear_dialog_testDrive"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:visibility="gone"
           >

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/circle_imagen_seleccion_alert"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:visibility="gone"
                android:src="@drawable/lifeon_logo"
                android:layout_marginLeft="40dp">

            </de.hdodenhof.circleimageview.CircleImageView>

            <TextView
                android:id="@+id/alert_cambia_test_drive_nombre"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/poppins_bold"
                android:textColor="@android:color/black"
                android:text="@string/nombre"
                android:visibility="gone"
                android:layout_marginLeft="30dp">

            </TextView>

        </LinearLayout>

        <Button
            android:id="@+id/cambiar_seleccion_alert_test_drive"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:background="@drawable/button_shape"
            android:text="@string/cambiar_seleccion"
            android:layout_gravity="center_horizontal"
            android:visibility="gone"
            >

        </Button>

    </LinearLayout>
    </LinearLayout>

</androidx.core.widget.NestedScrollView>
</code>```

This is the java code

```<code>      recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
        @Override
        public void onClick(View view, int position) {

        }

        @Override
        public void onLongClick(View view, int position) {
            asesores.clear();

            ParseObject itemTestDrive = listadoTestDrive.get(position);

            testDriveObjectId = itemTestDrive.getObjectId();

            LayoutInflater inflater = getLayoutInflater();
            View convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_agreements, null);
            alertDialog.setView(convertView);

            RecyclerView list = convertView.findViewById(R.id.list);
            TextView txt = convertView.findViewById(R.id.text_adm_asigna_asesor);
            CircleImageView ima=convertView.findViewById(R.id.circle_imagen_seleccion_alert);
            TextView txtNombreSeleccion=convertView.findViewById(R.id.alert_cambia_test_drive_nombre);
            Button botonCambiarSeleccion=convertView.findViewById(R.id.cambiar_seleccion_alert_test_drive);
            LinearLayout linearLayout=convertView.findViewById(R.id.linear_dialog_testDrive);

            botonCambiarSeleccion.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.setVisibility(View.VISIBLE);
                    ima.setVisibility(View.GONE);
                    txtNombreSeleccion.setVisibility(View.GONE);
                    botonCambiarSeleccion.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.GONE);
                }
            });

            ParseQuery<ParseObject> query1 = ParseQuery.getQuery("CitaTestDrive");
            query1.include("ComercialAsignado");
            query1.getInBackground(testDriveObjectId, new GetCallback<ParseObject>() {
                @Override
                public void done(ParseObject object, ParseException e) {
                    if (object.getParseObject("ComercialAsignado") != null) {
                        txt.setText(getActivity().getResources().getString(R.string.Advertencia_asignacion_a_alguien));

                    }

                }
            });

            ParseUser user = ParseUser.getCurrentUser();

            ParseObject sucursal = user.getParseObject("PerteneceSucursal");
            String sucurObjectId = sucursal.getObjectId();

            ParseQuery<ParseUser> query = ParseUser.getQuery();
            ParseObject suc = ParseObject.createWithoutData("Sucursal", sucurObjectId);
            query.whereEqualTo("PerteneceSucursal", suc);
            query.include("PerteneceSucursal");
            query.whereEqualTo("Rol","Asesor");
            query.findInBackground(new FindCallback<ParseUser>() {
                @Override
                public void done(List<ParseUser> objects, ParseException e) {
                    if (e == null) {
                        for (ParseUser obj : objects) {
                            asesores.add(obj);
                        }
                        list.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                        list.setHasFixedSize(true);
                        ListAsesorAdminAsignaTestDrive adapter = new ListAsesorAdminAsignaTestDrive(getApplicationContext(), asesores);
                        list.setAdapter(adapter);
                    }
                }
            });
            list.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), list, new RecyclerTouchListener.ClickListener() {
                @Override
                public void onClick(View view, int position) {
                    ParseUser item = asesores.get(position);

                    list.setVisibility(view.GONE);
                    ima.setVisibility(view.VISIBLE);
                    txtNombreSeleccion.setVisibility(view.VISIBLE);
                    botonCambiarSeleccion.setVisibility(View.VISIBLE);
                    linearLayout.setVisibility(View.VISIBLE);

                    ParseFile parseFile = item.getParseFile("Avatar");
                    if (parseFile != null) {
                        parseFile.getDataInBackground(new GetDataCallback() {
                            @Override
                            public void done(byte[] data, ParseException e) {
                                if (e == null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
                                    if (bmp != null) {
                                        ima.setImageBitmap(bmp);
                                    }
                                }
                            }
                        });
                    }

                    String asesorObjectId = item.getObjectId();
                    String asesorNombre = item.getString("Nombre");
                    txtNombreSeleccion.setText(asesorNombre);

                    alertDialog.setPositiveButton(getApplicationContext().getResources().getString(R.string.guardar), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ParseQuery<ParseObject> query = ParseQuery.getQuery("CitaTestDrive");

                            query.getInBackground(testDriveObjectId, new GetCallback<ParseObject>() {
                                @Override
                                public void done(ParseObject object, ParseException e) {

                                    object.put("ComercialAsignado", ParseObject.createWithoutData("_User", asesorObjectId));
                                    object.put("PendienteAsignacionAdmin", "Asignado");
                                    object.saveInBackground(new SaveCallback() {
                                        @Override
                                        public void done(ParseException e) {
                                            if (e == null) {
                                                Toast.makeText(getApplicationContext(), "Test drive asignado a:" + asesorNombre, Toast.LENGTH_LONG).show();
                                            } else {
                                                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();

                                            }
                                        }
                                    });

                                }

                            });

                            adapter.notifyDataSetChanged();

                        }
                    });

                    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                }

                @Override
                public void onLongClick(View view, int position) {

                }
            }));

            list.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
            list.setHasFixedSize(true);

            ListAsesorAdminAsignaTestDrive adapter = new ListAsesorAdminAsignaTestDrive(getApplicationContext(), asesores);
            list.setAdapter(adapter);

            alertDialog.show();

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

Appreciate if you don't answer if you don't know the correct answer or way to solve this.

Update: Android is gone crazy!!!.When I make the first onLongClick the alert dialog still doesn't work since I don't have a way to go back I click in the outside of the alert dialog and it disappears. Then I make another long Click and it works!!! this is very weird why does this happen????? nothing have changed.

答:
I. Declare custom drawable.xml for dialog background.

```<code>android:insetLeft="16dp"
android:insetTop="16dp"
android:insetRight="16dp"
android:insetBottom="16dp">
<shape android:shape="rectangle">
    <corners android:radius="2dp" />
    <solid android:color="@color/indigo" />
</shape>
</code>```

II. Declare custom styles in your styles.xml file.

```<code><!--buttons color-->
<item name="colorAccent">@color/pink</item>
<!--title and message color-->
<item name="android:textColorPrimary">@android:color/white</item>
<!--dialog background-->
<item name="android:windowBackground">@drawable/drawable</item>
</code>```

III. Create your dialog and use style as parameter in AlertDialog.Builder.

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyDialogTheme);

AlertDialog dialog = builder.create();

dialog.show();

Body:
Hello I followed every tutorial in Stack Overflow and YouTube anyways once I got to display my RecyclerView then I needed to accomplish other things with no problem at all. Anyways my only problem is that the positive button and the negative buttons disappeared. I assume that the problem might be that the things I have done in my XML is overlapping with the buttons in the view but I only have 3 items in the RecyclerView, so this is my big doubt. I made the dialog in an onLongClick then I added a RecyclerView method to get the position and the data present in the row that's why I cant call the alertDialog.setPositiveButton() in another place. This is quite a challenge would be appreciated to get some help in this.

This is my XML

<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <TextView
        android:id="@+id/text_adm_asigna_asesor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:fontFamily="@font/poppins_bold"
        android:text="Asigna un asesor"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="30dp"
        android:visibility="visible"
        android:layout_marginRight="30dp" />

        <LinearLayout
            android:id="@+id/linear_dialog_testDrive"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:visibility="gone"
           >

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/circle_imagen_seleccion_alert"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:visibility="gone"
                android:src="@drawable/lifeon_logo"
                android:layout_marginLeft="40dp">

            </de.hdodenhof.circleimageview.CircleImageView>

            <TextView
                android:id="@+id/alert_cambia_test_drive_nombre"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="@font/poppins_bold"
                android:textColor="@android:color/black"
                android:text="@string/nombre"
                android:visibility="gone"
                android:layout_marginLeft="30dp">

            </TextView>

        </LinearLayout>

        <Button
            android:id="@+id/cambiar_seleccion_alert_test_drive"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:background="@drawable/button_shape"
            android:text="@string/cambiar_seleccion"
            android:layout_gravity="center_horizontal"
            android:visibility="gone"
            >

        </Button>

    </LinearLayout>
    </LinearLayout>

</androidx.core.widget.NestedScrollView>

This is the java code

      recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
        @Override
        public void onClick(View view, int position) {

        }

        @Override
        public void onLongClick(View view, int position) {
            asesores.clear();

            ParseObject itemTestDrive = listadoTestDrive.get(position);

            testDriveObjectId = itemTestDrive.getObjectId();

            LayoutInflater inflater = getLayoutInflater();
            View convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_agreements, null);
            alertDialog.setView(convertView);

            RecyclerView list = convertView.findViewById(R.id.list);
            TextView txt = convertView.findViewById(R.id.text_adm_asigna_asesor);
            CircleImageView ima=convertView.findViewById(R.id.circle_imagen_seleccion_alert);
            TextView txtNombreSeleccion=convertView.findViewById(R.id.alert_cambia_test_drive_nombre);
            Button botonCambiarSeleccion=convertView.findViewById(R.id.cambiar_seleccion_alert_test_drive);
            LinearLayout linearLayout=convertView.findViewById(R.id.linear_dialog_testDrive);

            botonCambiarSeleccion.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.setVisibility(View.VISIBLE);
                    ima.setVisibility(View.GONE);
                    txtNombreSeleccion.setVisibility(View.GONE);
                    botonCambiarSeleccion.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.GONE);
                }
            });

            ParseQuery<ParseObject> query1 = ParseQuery.getQuery("CitaTestDrive");
            query1.include("ComercialAsignado");
            query1.getInBackground(testDriveObjectId, new GetCallback<ParseObject>() {
                @Override
                public void done(ParseObject object, ParseException e) {
                    if (object.getParseObject("ComercialAsignado") != null) {
                        txt.setText(getActivity().getResources().getString(R.string.Advertencia_asignacion_a_alguien));

                    }

                }
            });

            ParseUser user = ParseUser.getCurrentUser();

            ParseObject sucursal = user.getParseObject("PerteneceSucursal");
            String sucurObjectId = sucursal.getObjectId();

            ParseQuery<ParseUser> query = ParseUser.getQuery();
            ParseObject suc = ParseObject.createWithoutData("Sucursal", sucurObjectId);
            query.whereEqualTo("PerteneceSucursal", suc);
            query.include("PerteneceSucursal");
            query.whereEqualTo("Rol","Asesor");
            query.findInBackground(new FindCallback<ParseUser>() {
                @Override
                public void done(List<ParseUser> objects, ParseException e) {
                    if (e == null) {
                        for (ParseUser obj : objects) {
                            asesores.add(obj);
                        }
                        list.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                        list.setHasFixedSize(true);
                        ListAsesorAdminAsignaTestDrive adapter = new ListAsesorAdminAsignaTestDrive(getApplicationContext(), asesores);
                        list.setAdapter(adapter);
                    }
                }
            });
            list.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), list, new RecyclerTouchListener.ClickListener() {
                @Override
                public void onClick(View view, int position) {
                    ParseUser item = asesores.get(position);

                    list.setVisibility(view.GONE);
                    ima.setVisibility(view.VISIBLE);
                    txtNombreSeleccion.setVisibility(view.VISIBLE);
                    botonCambiarSeleccion.setVisibility(View.VISIBLE);
                    linearLayout.setVisibility(View.VISIBLE);

                    ParseFile parseFile = item.getParseFile("Avatar");
                    if (parseFile != null) {
                        parseFile.getDataInBackground(new GetDataCallback() {
                            @Override
                            public void done(byte[] data, ParseException e) {
                                if (e == null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
                                    if (bmp != null) {
                                        ima.setImageBitmap(bmp);
                                    }
                                }
                            }
                        });
                    }

                    String asesorObjectId = item.getObjectId();
                    String asesorNombre = item.getString("Nombre");
                    txtNombreSeleccion.setText(asesorNombre);

                    alertDialog.setPositiveButton(getApplicationContext().getResources().getString(R.string.guardar), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ParseQuery<ParseObject> query = ParseQuery.getQuery("CitaTestDrive");

                            query.getInBackground(testDriveObjectId, new GetCallback<ParseObject>() {
                                @Override
                                public void done(ParseObject object, ParseException e) {

                                    object.put("ComercialAsignado", ParseObject.createWithoutData("_User", asesorObjectId));
                                    object.put("PendienteAsignacionAdmin", "Asignado");
                                    object.saveInBackground(new SaveCallback() {
                                        @Override
                                        public void done(ParseException e) {
                                            if (e == null) {
                                                Toast.makeText(getApplicationContext(), "Test drive asignado a:" + asesorNombre, Toast.LENGTH_LONG).show();
                                            } else {
                                                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();

                                            }
                                        }
                                    });

                                }

                            });

                            adapter.notifyDataSetChanged();

                        }
                    });

                    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                }

                @Override
                public void onLongClick(View view, int position) {

                }
            }));

            list.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
            list.setHasFixedSize(true);

            ListAsesorAdminAsignaTestDrive adapter = new ListAsesorAdminAsignaTestDrive(getApplicationContext(), asesores);
            list.setAdapter(adapter);

            alertDialog.show();

        }
    }));

Appreciate if you don't answer if you don't know the correct answer or way to solve this.

Update: Android is gone crazy!!!.When I make the first onLongClick the alert dialog still doesn't work since I don't have a way to go back I click in the outside of the alert dialog and it disappears. Then I make another long Click and it works!!! this is very weird why does this happen????? nothing have changed.

Body:
I. Declare custom drawable.xml for dialog background.

android:insetLeft="16dp"
android:insetTop="16dp"
android:insetRight="16dp"
android:insetBottom="16dp">
<shape android:shape="rectangle">
    <corners android:radius="2dp" />
    <solid android:color="@color/indigo" />
</shape>

II. Declare custom styles in your styles.xml file.

<!--buttons color-->
<item name="colorAccent">@color/pink</item>
<!--title and message color-->
<item name="android:textColorPrimary">@android:color/white</item>
<!--dialog background-->
<item name="android:windowBackground">@drawable/drawable</item>

III. Create your dialog and use style as parameter in AlertDialog.Builder.

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyDialogTheme);

AlertDialog dialog = builder.create();

dialog.show();