问:
Bootstrap 5 dropdown doesn't open using Angular13
Hey guys so I'm working on an angular project and using bootstrap 5. I wanted to implement a dropdown multiselect and unfortunately the dropdown doesn't get expanded.

I am following this example: Creating Multi-Select Dropdown with Angular and Bootstrap 5

I've created a stackblitz example: https://stackblitz.com/edit/github-va1hpx?

Hope someone can help with that.

答:
FIXED

The problem was that in the example used the alpha version of bootstrap5 and I'm using 5.1.3.
In that time bootstrap made some changes on what classes should be added to buttons etc.
So you should write

this:

 <button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true"
```
<p>instead of this:</p>
<pre class="lang-js prettyprint-override"><code> <button class="btn dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true"
</code>```

And also other html elements should be getting specific classes like the margin classes

ms-1 ms-2 ....
```
<p>on the input elements</p>
<p>So in my case it wasn't a problem of adding</p>
<pre class="lang-js prettyprint-override"><code>jQuery.js or popper.js
</code>```

to my angular.json like mentioned in other threads: https://stackoverflow.com/search?tab=Relevance&pagesize=30&q=popper.js%20bootstrap&s=144706d6-c9be-4120-b105-c37f2b848352

It was just the default bootstrap5 classes.

Body:
FIXED

The problem was that in the example used the alpha version of bootstrap5 and I'm using 5.1.3.
In that time bootstrap made some changes on what classes should be added to buttons etc.
So you should write

this:

 <button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true"

instead of this:

 <button class="btn dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true"

And also other html elements should be getting specific classes like the margin classes

ms-1 ms-2 ....

on the input elements

So in my case it wasn't a problem of adding

jQuery.js or popper.js

to my angular.json like mentioned in other threads: https://stackoverflow.com/search?tab=Relevance&pagesize=30&q=popper.js%20bootstrap&s=144706d6-c9be-4120-b105-c37f2b848352

It was just the default bootstrap5 classes.


来源: stackexchange

问:
Calling Oracle stored procedure using Entity Framework with output parameter?
I have a simple Oracle stored procedure that gets three parameters passed in, and has one output parameter:

```<code>CREATE OR REPLACE PROCEDURE RA.RA_REGISTERASSET
(
    INPROJECTNAME IN VARCHAR2
    ,INCOUNTRYCODE IN VARCHAR2
    ,INLOCATION IN VARCHAR2
    ,OUTASSETREGISTERED OUT VARCHAR2
)
AS
BEGIN
  SELECT
      INPROJECTNAME || ', ' || INLOCATION || ', ' || INCOUNTRYCODE
  INTO
      OUTASSETREGISTERED
  FROM
      DUAL;
END RA_REGISTERASSET;
</code>```

I am trying to use Entity Framework 6.1 to get back the OutAssetRegistered value, however, I get a null after calling SqlQuery with no exception:

```<code>public class CmdRegisterAssetDto
{
        public string inProjectName { get; set; }
        public string inCountryCode { get; set; }
        public string inLocation { get; set; }
        public string OutAssetRegistered { get; set; }
}
</code>```

//------------------------------------------------------------

```<code>string projectName = "EXCO";
string location = "ANYWHERE";
string countryCode = "XX";

using (var ctx = new RAContext())
{
    var projectNameParam = new OracleParameter("inProjectName", OracleDbType.Varchar2, projectName, ParameterDirection.Input);
    var countryCodeParam = new OracleParameter("inCountryCode", OracleDbType.Varchar2, countryCode, ParameterDirection.Input);
    var locationParam = new OracleParameter("inLocation", OracleDbType.Varchar2, location, ParameterDirection.Input);
    var assetRegisteredParam = new OracleParameter("OutAssetRegistered", OracleDbType.Varchar2, ParameterDirection.Output);

    var sql = "BEGIN RA.RA_RegisterAsset(:inProjectName, :inCountryCode, :inLocation, :OutAssetRegistered); END;";
    var query = ctx.Database.SqlQuery<CmdRegisterAssetDto>(sql, projectNameParam, countryCodeParam, locationParam, assetRegisteredParam
    );

    assetRegistered = (string)assetRegisteredParam.Value;
}
</code>```

I have been battling to get this to work to no avail, have checked different blogs, all the other crud operations work, can anyone please assist and direct me where I am going wrong?

答:
If you need to pass in and/or out a date:</p>
```<code>        public DateTime GetDate(string dateIn)
        {
            Regex regex = new Regex(@"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)");

            if (!regex.IsMatch(dateIn))
            {
                throw new ArgumentException($"dateIn must be given in the YYYY-MM-DD\"T\"hh24:mi:ss\"Z\" format. " +
                    $"Value given: {dateIn}");
            }

            OracleParameter dateInParam = new OracleParameter("DATE_IN_", dateIn);
            createdParam.OracleDbType = OracleDbType.TimeStampTZ;
            OracleParameter dateOutParam= new OracleParameter("DATE_OUT_", OracleDbType.Date, System.Data.ParameterDirection.Output);

            var sql = "BEGIN " +
                $"Get_Date(:DATE_IN_, TO_TIMESTAMP_TZ('{dateIn}','YYYY-MM-DD\"T\"hh24:mi:ss\"Z\"'), :DATE_OUT_ ); " +
                "END;";

#pragma warning disable EF1000 // Possible SQL injection vulnerability.
            context.Database.ExecuteSqlCommand(sql, dateInParam, dateOutParam);
#pragma warning restore EF1000 // Possible SQL injection vulnerability.

            return (DateTime)(OracleDate)dateOutParam.Value;
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a simple Oracle stored procedure that gets three parameters passed in, and has one output parameter:

CREATE OR REPLACE PROCEDURE RA.RA_REGISTERASSET
(
    INPROJECTNAME IN VARCHAR2
    ,INCOUNTRYCODE IN VARCHAR2
    ,INLOCATION IN VARCHAR2
    ,OUTASSETREGISTERED OUT VARCHAR2
)
AS
BEGIN
  SELECT
      INPROJECTNAME || ', ' || INLOCATION || ', ' || INCOUNTRYCODE
  INTO
      OUTASSETREGISTERED
  FROM
      DUAL;
END RA_REGISTERASSET;

I am trying to use Entity Framework 6.1 to get back the OutAssetRegistered value, however, I get a null after calling SqlQuery with no exception:

public class CmdRegisterAssetDto
{
        public string inProjectName { get; set; }
        public string inCountryCode { get; set; }
        public string inLocation { get; set; }
        public string OutAssetRegistered { get; set; }
}

//------------------------------------------------------------

string projectName = "EXCO";
string location = "ANYWHERE";
string countryCode = "XX";

using (var ctx = new RAContext())
{
    var projectNameParam = new OracleParameter("inProjectName", OracleDbType.Varchar2, projectName, ParameterDirection.Input);
    var countryCodeParam = new OracleParameter("inCountryCode", OracleDbType.Varchar2, countryCode, ParameterDirection.Input);
    var locationParam = new OracleParameter("inLocation", OracleDbType.Varchar2, location, ParameterDirection.Input);
    var assetRegisteredParam = new OracleParameter("OutAssetRegistered", OracleDbType.Varchar2, ParameterDirection.Output);

    var sql = "BEGIN RA.RA_RegisterAsset(:inProjectName, :inCountryCode, :inLocation, :OutAssetRegistered); END;";
    var query = ctx.Database.SqlQuery<CmdRegisterAssetDto>(sql, projectNameParam, countryCodeParam, locationParam, assetRegisteredParam
    );

    assetRegistered = (string)assetRegisteredParam.Value;
}

I have been battling to get this to work to no avail, have checked different blogs, all the other crud operations work, can anyone please assist and direct me where I am going wrong?

Body:
If you need to pass in and/or out a date:

        public DateTime GetDate(string dateIn)
        {
            Regex regex = new Regex(@"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)");

            if (!regex.IsMatch(dateIn))
            {
                throw new ArgumentException($"dateIn must be given in the YYYY-MM-DD\"T\"hh24:mi:ss\"Z\" format. " +
                    $"Value given: {dateIn}");
            }

            OracleParameter dateInParam = new OracleParameter("DATE_IN_", dateIn);
            createdParam.OracleDbType = OracleDbType.TimeStampTZ;
            OracleParameter dateOutParam= new OracleParameter("DATE_OUT_", OracleDbType.Date, System.Data.ParameterDirection.Output);

            var sql = "BEGIN " +
                $"Get_Date(:DATE_IN_, TO_TIMESTAMP_TZ('{dateIn}','YYYY-MM-DD\"T\"hh24:mi:ss\"Z\"'), :DATE_OUT_ ); " +
                "END;";

#pragma warning disable EF1000 // Possible SQL injection vulnerability.
            context.Database.ExecuteSqlCommand(sql, dateInParam, dateOutParam);
#pragma warning restore EF1000 // Possible SQL injection vulnerability.

            return (DateTime)(OracleDate)dateOutParam.Value;
        }

ContentLicense: CC BY-SA 4.0


问:
Angular Material Datepicker internationalization example doesn't work
This example is in Angular Material documentation for dynamically changing locale for date picker component. But it doesn't work. What's weird is that the code snippet on documentation page works but the stackblitz doesn't.</p>

答:
It is possible to change locale dynamically for Angular material date picker.

working example - https://codesandbox.io/s/material-date-locale-jyylz


问:
How to filter an associative arrays using array of keys in PHP?
I have an associative arrays and an array of keys.

```<code>$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');
</code>```

How I build an associative array from all element of $A where the key is in $B?
For the example above, the answer should be

```<code>$C = array('a'=>'book', 'b'=>'pencil');
</code>```

答:
array_intersect_key($A,array_combine($B,$B))

or better: array_intersect_key($my_array, array_flip($allowed))

from the question: PHP: How to use array_filter() to filter array keys?

Body:
I have an associative arrays and an array of keys.

$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');

How I build an associative array from all element of $A where the key is in $B?
For the example above, the answer should be

$C = array('a'=>'book', 'b'=>'pencil');


问:
solve an equation (with max-statement) in python
i am seeking a solution for the following equation in Python.

```<code>    345-0.25*t = 37.5 * x_a
    'with'
    t = max(0, 10-x_a)*(20-10) + max(0,25-5*x_a)*(3-4) + max(0,4-0.25*x_a)*(30-12.5)
    'x_a = ??'
</code>```

If there is more than one solution to the problem (I am not even sure, whether this can happen from a mathematical point of view?), I want my code to return a positive(!) value for x_a, that minimizes t.

With my previous knowledge in the Basics of Python, Pandas and NumPy I actually have no clue, how to tackle this problem. Can someone give me a hint?

For Clarification: I inserted some exemplary numbers in the equation to make it easier to gasp the problem. In my final code, there might of course be different numbers for different scenarios. However, in every scenario x_a is the only unknown variable.

Update

I thought about the problem again and came up with the following solution, which yields the same result as the calculations done by Michał Mazur:

```<code>import itertools
from sympy import Eq, Symbol, solve
import numpy as np

x_a = Symbol('x_a')
possible_elements = np.array([10-x_a, 25-5*x_a, 4-0.25*x_a])
assumptions = np.array(list(itertools.product([True, False], repeat=3)))

for assumption in assumptions:
    x_a = Symbol('x_a')
    elements = assumption.astype(int) * possible_elements

    t = elements[0]*(20-10) + elements[1]*(3-4) + elements[2]*(30-12.5)
    eqn = Eq(300-0.25*t, 40*x_a)

    solution = solve(eqn)
    if len(solution)>2:
        print('Warning! the code may suppress possible solutions')
    if len(solution)==1:
        solution = solution[0]
        if (((float(possible_elements[0].subs(x_a,solution))) > 0) == assumption[0]) &\
        (((float(possible_elements[1].subs(x_a,solution))) > 0) == assumption[1]) &\
        (((float(possible_elements[2].subs(x_a,solution)))> 0) == assumption[2]):
            print('solution:', solution)
</code>```

Compared to the already suggested approach this may have an little advantage as it does not rely on testing all possible values and therefore can be used for very small as well as very big solutions without taking a lot of time (?). However, it probably only is useful as long as you don't have more complex functions for t (even having for example 5 max(...) statements and therefore (2^5=)32 scenarios to test seems quite cumbersome).

As far as I'm concerned, I just realized that my problem is even more complex as i thought. For my project the calculations needed to derive the value of "t" are pretty entangled and can not be written in just one equation. However it still is a function, that only relies on x_a. So I am still hoping for a Python-Solution similar to the proposed Solver in Excel... or I will stick to the approach of simply testing out all possible numbers.

答:
If you are interested in a solution a bit different than the Python one, then I will give you a hand. Open up your Excel, with Solver extention and plug in
the data you are interested in cheking, as the following:

Into the E2 you plug the command I just have writen, into E4 you plug in

```<code>=300-0,25*E2
</code>```

Into the F4 you plug:

```<code>=40*F2
</code>```

Then you open up your Solver menu

Into the Set Objective you put the variable t, which you want to minimize.
Into Changing Variables you put the a.
Into Constraint Menu you put the equality of E4 and F4 cells.
You check the "Make Unconstarained Variables be non-negative" which will prevent your a variable to go below 0. Your method of computing is strictly non-linear, so you leave this option there.

You click solve. The computed value is presented in the screen.

The python approach I can think of:

```<code>minimumval=10100
minxa=10000
eps=0.01
for i in range(100000):
    k=i/10000
    x_a=k
    t = max(0, 10-x_a)*(20-10) + max(0,25-5*x_a)*(3-4) + max(0,4-0.25*x_a)*(30-12.5)
    val=abs(300-0.25*t-40*x_a)
    if (val<eps):
        if t<minimumval:
            minimumval=t
            minxa=x_a

</code>```

It isn't direct solution, as in it only controls the error that you make in the equality by eps value. However, it gives solution.

Body:
i am seeking a solution for the following equation in Python.

    345-0.25*t = 37.5 * x_a
    'with'
    t = max(0, 10-x_a)*(20-10) + max(0,25-5*x_a)*(3-4) + max(0,4-0.25*x_a)*(30-12.5)
    'x_a = ??'

If there is more than one solution to the problem (I am not even sure, whether this can happen from a mathematical point of view?), I want my code to return a positive(!) value for x_a, that minimizes t.

With my previous knowledge in the Basics of Python, Pandas and NumPy I actually have no clue, how to tackle this problem. Can someone give me a hint?

For Clarification: I inserted some exemplary numbers in the equation to make it easier to gasp the problem. In my final code, there might of course be different numbers for different scenarios. However, in every scenario x_a is the only unknown variable.

Update

I thought about the problem again and came up with the following solution, which yields the same result as the calculations done by Michał Mazur:

import itertools
from sympy import Eq, Symbol, solve
import numpy as np

x_a = Symbol('x_a')
possible_elements = np.array([10-x_a, 25-5*x_a, 4-0.25*x_a])
assumptions = np.array(list(itertools.product([True, False], repeat=3)))

for assumption in assumptions:
    x_a = Symbol('x_a')
    elements = assumption.astype(int) * possible_elements

    t = elements[0]*(20-10) + elements[1]*(3-4) + elements[2]*(30-12.5)
    eqn = Eq(300-0.25*t, 40*x_a)

    solution = solve(eqn)
    if len(solution)>2:
        print('Warning! the code may suppress possible solutions')
    if len(solution)==1:
        solution = solution[0]
        if (((float(possible_elements[0].subs(x_a,solution))) > 0) == assumption[0]) &\
        (((float(possible_elements[1].subs(x_a,solution))) > 0) == assumption[1]) &\
        (((float(possible_elements[2].subs(x_a,solution)))> 0) == assumption[2]):
            print('solution:', solution)

Compared to the already suggested approach this may have an little advantage as it does not rely on testing all possible values and therefore can be used for very small as well as very big solutions without taking a lot of time (?). However, it probably only is useful as long as you don't have more complex functions for t (even having for example 5 max(...) statements and therefore (2^5=)32 scenarios to test seems quite cumbersome).

As far as I'm concerned, I just realized that my problem is even more complex as i thought. For my project the calculations needed to derive the value of "t" are pretty entangled and can not be written in just one equation. However it still is a function, that only relies on x_a. So I am still hoping for a Python-Solution similar to the proposed Solver in Excel... or I will stick to the approach of simply testing out all possible numbers.

Body:
If you are interested in a solution a bit different than the Python one, then I will give you a hand. Open up your Excel, with Solver extention and plug in
the data you are interested in cheking, as the following:

Into the E2 you plug the command I just have writen, into E4 you plug in

=300-0,25*E2

Into the F4 you plug:

=40*F2

Then you open up your Solver menu

Into the Set Objective you put the variable t, which you want to minimize.
Into Changing Variables you put the a.
Into Constraint Menu you put the equality of E4 and F4 cells.
You check the "Make Unconstarained Variables be non-negative" which will prevent your a variable to go below 0. Your method of computing is strictly non-linear, so you leave this option there.

You click solve. The computed value is presented in the screen.

The python approach I can think of:

minimumval=10100
minxa=10000
eps=0.01
for i in range(100000):
    k=i/10000
    x_a=k
    t = max(0, 10-x_a)*(20-10) + max(0,25-5*x_a)*(3-4) + max(0,4-0.25*x_a)*(30-12.5)
    val=abs(300-0.25*t-40*x_a)
    if (val<eps):
        if t<minimumval:
            minimumval=t
            minxa=x_a

It isn't direct solution, as in it only controls the error that you make in the equality by eps value. However, it gives solution.


问:
How to determine root cause for Communication link failure TCP Provider: The specified network name is no longer available?
Here is my latest effort at revising this question. But this time, I am trying to follow the good counsel given by Oded in his article Getting good answers on StackOverflow.

I need to find out how I can determine the root cause for the following error:

Communication link failure

TCP Provider: The specified network name is no longer available

From time to time, I am seeing this error when running a set of SSIS packages. This error can occur when one to many packages are run from:

A SQL Server Agent Job

A batch file

In debug mode from BIDS

The full error message I see is as follows:

SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80004005.
      An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0"  Hresult: 0x80004005  Description: "Communication link failure".
      An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0"  Hresult: 0x80004005  Description: "TCP Provider: The specified network name is no longer available.
      ".

SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80004005.
      An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0" Hresult: 0x80004005  Description: "Protocol error in TDS stream".
      An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0" Hresult: 0x80004005  Description: "Communication link failure".
      An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0" Hresult: 0x80004005  Description: "TCP Provider: An existing connection was forcibly closed by the remote host."

This is an overview of how I have designed the ETL process:

Two servers

Both are virtual machines

The SSIS packages run on an application server

The SQL Server database lives on a database server

I use an OLE DB connection manager to connect from the SSIS package on the application server to the SQL Server database on the database server.

The packages run as a file system deployment on the application server and not as a database deployment on the database server.

The main reason for this is that the ETL is integrated with a set of tools no found on and drives not accessible to the database server. These tools include Apex Data Loader for Salesforce and pgAdmin III.

So far I cannot consistently reproduce this error. However, this is what I have observed:

Failure occurs more frequently during regular business hours

Failure occurs less frequently during off hours

For about a two hour period on a Friday morning I was able to successfully reproduce the error on a specific package.

The error occurred during a large data flow if a child package call that precedes the large data flow was enabled.

The error did not occur during the same large data flow if the child package call that precedes the large data flow was disabled.

The child package in question calls back to the database to retrieve a tiny amount of information for use in an email body and then sends the email.

It feels like maybe a resource limit is being exceeded?

Maybe a connection limit?

I am wondering what tools I should be using to try and determine the root cause of the error.

Technical details about the two servers involved are listed below:

SQL Server and Database Server info:

  Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)   Jun 17 2011 00:54:03   Copyright (c) Microsoft Corporation  Enterprise Edition (64-bit) on Windows NT 6.1  (Build 7601: Service Pack 1) (Hypervisor)

SSIS info:

  Microsoft Visual Studio 2008 Version 9.0.30729.1 SP
  Microsoft .NET Framework Version 3.5 SP1

Application Server info:

  OS name: Microsoft Windows Server 2008 R2 Standard
  Version: 6.1.7601 Service Pack 1 Build 7601

I have researched the error message online and found these, but would really like to get an expert's insight before proceeding:

How to Disable TCP Chimney, TCPIP Offload Engine (TOE) or TCP Segmentation Offload (TSO).

Using Netsh Commands to Enable or Disable TCP Chimney Offload

Any help is appreciated.

Thanks

UPDATE:

Further testing shows that this is not "an SSIS thing" as the same error is seen at the same rate when using SQL Server Management Studio. The complexity of the query does not make the error more or less likely. In an attempt to resolve, we have tried one fix (below):

 #1 How to Disable TCP Chimney, TCPIP Offload Engine (TOE) or TCP Segmentation Offload (TSO).

This was our first attempt. TCP Chimney is now disabled on the Application Server and the Database Server. Testing shows that the same error occurs at the same rate.

So where to go from here? Honestly I am not sure. One seemingly good option remains:

Application Server and Database Server SQL Server installations do not exactly match

Application Server = SQL Server 2008 (SP1) - 10.0.2531.0 (X64)

Database Server = SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)

The plan is to upgrade the SQL Server installation on the Application server. Its kind of a hit and hope, but at this point this seems like the best option. Something in my brain tells me that this might be solved by fixing a hardware issue (by that I mean a repair or a replace) and that there might not be anything that hardware and software configuration can do about it.

However, I am still not sure how to go about determining a root cause. I am still left wondering what tools I should be using to diagnose the root cause.

答: It seems there are multiple causes for this issue. For me it was the SQL file being too big at about 150MiB. Splitting it into smaller files worked for me.</p>


问:
How do I get the git rev-list --count number from an external build.gradle.kts file?
I wrote this function for Groovy Gradle (call it functions.gradle)

```<code>static def gitVersionCode() {
    return "git rev-list --count HEAD".execute().text.trim().toInteger()
}

ext {
    gitVersionCode = this.&gitVersionCode
}
</code>```

Where I can just call gitVersionCode() from an external build.gradle file to get the revision count. I am trying to re-write this for kts, but I am having trouble with

a) calling it from another script, and

b) Executing the bash command and returning it as an integer. I was able to get this as a string, but not an int.

What It tried looks sort of like this (functions.gradle.kts)

```<code>val gitBuildNumber: String by lazy {
    val stdout = ByteArrayOutputStream()
    rootProject.exec {
        commandLine("git", "rev-list", "--count", "HEAD")
        standardOutput = stdout
    }
    stdout.toString().trim()
}
</code>```

答:
Convert your result to int using .toInt()

```<code>val gitBuildNumber: Int by lazy {
    val stdout = org.apache.commons.io.output.ByteArrayOutputStream()
    rootProject.exec {
        commandLine("git", "rev-list", "--count", "HEAD")
        standardOutput = stdout
    }
    stdout.toString().trim().toInt()
}
</code>```

Body:
I wrote this function for Groovy Gradle (call it functions.gradle)

static def gitVersionCode() {
    return "git rev-list --count HEAD".execute().text.trim().toInteger()
}

ext {
    gitVersionCode = this.&gitVersionCode
}

Where I can just call gitVersionCode() from an external build.gradle file to get the revision count. I am trying to re-write this for kts, but I am having trouble with

a) calling it from another script, and

b) Executing the bash command and returning it as an integer. I was able to get this as a string, but not an int.

What It tried looks sort of like this (functions.gradle.kts)

val gitBuildNumber: String by lazy {
    val stdout = ByteArrayOutputStream()
    rootProject.exec {
        commandLine("git", "rev-list", "--count", "HEAD")
        standardOutput = stdout
    }
    stdout.toString().trim()
}

Body:
Convert your result to int using .toInt()

val gitBuildNumber: Int by lazy {
    val stdout = org.apache.commons.io.output.ByteArrayOutputStream()
    rootProject.exec {
        commandLine("git", "rev-list", "--count", "HEAD")
        standardOutput = stdout
    }
    stdout.toString().trim().toInt()
}


问:
Why is an eleven-class selector not trumping a single id?
I have an example of a selector with 11 classes. According to W3Schools, a class is worth 10 points, meaning that 11 classes should clearly trump a single id. Why is it not doing so in this case? The selector is correct and only applies the blue colour when adding !important.

The code:

#test { color: red } /* 100 points */
div .test { color: green } /* 11 points */
.test1.test2.test3.test4.test5.test6.test7.test8.test9.test10.test11 {
  color: blue; /* works with !important */
} /* not 110 points? */
p { color: orange } /* 1 point */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <p id='test' class='test1 test2 test3 test4 test5 test6 test7 test8 test9 test10 test11'>Test</p>
</div></code>```

Are W3Schools wrong or am I missing something?

答:
You can refer to this CSS-tricks article (doc). Which explains this properly.

To summarize this in short. Basically, The point system is just a way to help you remember the specificity of the elements which are like below.

```<code>inline > id > class >elements
</code>```

As mentioned in the article, It tells CSS applies vastly different specificity weights to classes and IDs. In fact, an ID has infinitely more specificity value! That is, no amount of classes alone can outweigh an ID.

Also, Keep in mind the only exception to this rule is the usage of !important
which will override the inline styles.

Body:
I have an example of a selector with 11 classes. According to W3Schools, a class is worth 10 points, meaning that 11 classes should clearly trump a single id. Why is it not doing so in this case? The selector is correct and only applies the blue colour when adding !important.

The code:

#test { color: red } /* 100 points */
div .test { color: green } /* 11 points */
.test1.test2.test3.test4.test5.test6.test7.test8.test9.test10.test11 {
  color: blue; /* works with !important */
} /* not 110 points? */
p { color: orange } /* 1 point */

Test

Are W3Schools wrong or am I missing something?

Body:
You can refer to this CSS-tricks article (doc). Which explains this properly.

To summarize this in short. Basically, The point system is just a way to help you remember the specificity of the elements which are like below.

inline > id > class >elements

As mentioned in the article, It tells CSS applies vastly different specificity weights to classes and IDs. In fact, an ID has infinitely more specificity value! That is, no amount of classes alone can outweigh an ID.

Also, Keep in mind the only exception to this rule is the usage of !important
which will override the inline styles.


问:
How to render inner Css - Angular
I have an object "Content" contains two properties:

```<code>Content:{
html:string;
css:string
}
</code>```

and I need to render a div depending on this object, for the html I could do that using:

```<code><div [innnerHtml]="Content.html"></div>
</code>```

but I couldn't render the css of the object.
Content example:

```<code>Content:{
html:"<p>test rendering the object</p> <br> <div class="div1"></div>",
css:"p{color:red} .div1{background-color:black}"
}
</code>```

答:
The solution for me was appending the style content programmatically, like this:</p>
```<code>ngOnInit() {
  const css = 'a {color: pink;}';
  const head = document.getElementsByTagName('div')[0];
  const style = document.createElement('style');
  style.type = 'text/css';
  style.appendChild(document.createTextNode(css));
  head.appendChild(style);
}
</code>```

Title: How to render inner Css - Angular

Body:
I have an object "Content" contains two properties:

Content:{
html:string;
css:string
}

and I need to render a div depending on this object, for the html I could do that using:

but I couldn't render the css of the object.
Content example:

Content:{
html:"
test rendering the object

",
css:"p{color:red} .div1{background-color:black}"
}

Body:
The solution for me was appending the style content programmatically, like this:

ngOnInit() {
  const css = 'a {color: pink;}';
  const head = document.getElementsByTagName('div')[0];
  const style = document.createElement('style');
  style.type = 'text/css';
  style.appendChild(document.createTextNode(css));
  head.appendChild(style);
}


问:
Python concurrent.futures
I have a multiprocessing code, and each process have to analyse same data differently.

I have implemented:

```<code>with concurrent.futures.ProcessPoolExecutor() as executor:
   res = executor.map(goal_fcn, p, [global_DataFrame], [global_String])

for f in concurrent.futures.as_completed(res):
   fp = res
</code>```

and function:

```<code>def goal_fcn(x, DataFrame, String):
   return heavy_calculation(x, DataFrame, String)

</code>```

the problem is goal_fcn is called only once, while should be multiple time

In debugger, I checked now the variable p is looking, and it has multiple columns and rows. Inside goal_fcn, variable x have only first row - looks good.

But the function is called only once. There is no error, the code just execute next steps.

Even if I modify variable p = [1,3,4,5], and of course code. goal_fcn is executed only once

I have to use map() because keeping the order between input and output is required

答:
map works like zip. It terminates once at least one input sequence is at its end. Your [global_DataFrame] and [global_String] lists have one element each, so that is where map ends.

There are two ways around this:

Use itertools.product. This is the equivalent of running "for all data frames, for all strings, for all p". Something like this:

def goal_fcn(x_DataFrame_String):
    x, DataFrame, String = x_DataFrame_String
    ...

executor.map(goal_fcn, itertools.product(p, [global_DataFrame], [global_String]))
```
<ol start="2">
<li>Bind the fixed arguments instead of abusing the sequence arguments.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>def goal_fcn(x, DataFrame, String):
    pass

bound = functools.partial(goal_fcn, DataFrame=global_DataFrame, String=global_String)
executor.map(bound, p)
</code>```

Title: Python concurrent.futures

Body:
I have a multiprocessing code, and each process have to analyse same data differently.

I have implemented:

with concurrent.futures.ProcessPoolExecutor() as executor:
   res = executor.map(goal_fcn, p, [global_DataFrame], [global_String])

for f in concurrent.futures.as_completed(res):
   fp = res

and function:

def goal_fcn(x, DataFrame, String):
   return heavy_calculation(x, DataFrame, String)

the problem is goal_fcn is called only once, while should be multiple time

In debugger, I checked now the variable p is looking, and it has multiple columns and rows. Inside goal_fcn, variable x have only first row - looks good.

But the function is called only once. There is no error, the code just execute next steps.

Even if I modify variable p = [1,3,4,5], and of course code. goal_fcn is executed only once

I have to use map() because keeping the order between input and output is required

Body:
map works like zip. It terminates once at least one input sequence is at its end. Your [global_DataFrame] and [global_String] lists have one element each, so that is where map ends.

There are two ways around this:

Use itertools.product. This is the equivalent of running "for all data frames, for all strings, for all p". Something like this:

def goal_fcn(x_DataFrame_String):
    x, DataFrame, String = x_DataFrame_String
    ...

executor.map(goal_fcn, itertools.product(p, [global_DataFrame], [global_String]))

Bind the fixed arguments instead of abusing the sequence arguments.

def goal_fcn(x, DataFrame, String):
    pass

bound = functools.partial(goal_fcn, DataFrame=global_DataFrame, String=global_String)
executor.map(bound, p)


问:
Keystone.js 6 access denied adminMeta
i want to seed data onConnect,  but i have access denied,  using this query :

```<code>
{
        keystone: keystone {
        adminMeta {
          lists {
            key
            description
            label
            singular
            plural
            path
            fields {
              path
            }
          }
        }
      }

</code>```

i have this error even iam using sudo, context.sudo().graphql.raw :

```<code>
[
  Error: Access denied
      at /Users/sidalitemkit/work/web/yet/wirxe/wirxe-app/node_modules/@keystone-next/admin-ui/system/dist/admin-ui.cjs.dev.js:552:19
      at processTicksAndRejections (node:internal/process/task_queues:94:5)
      at async Promise.all (index 0)
      at async Promise.all (index 0) {
    locations: [ [Object] ],
    path: [ 'keystone', 'adminMeta' ]
  }
]

</code>```

here my config :

```<code>export default auth.withAuth(
  config({
    db: {
      adapter: 'prisma_postgresql',
      url:
        'postgres://admin:aj093bf7l6jdx5hm@wirxe-app-database-do-user-9126376-0.b.db.ondigitalocean.com:25061/wirxepool?schema=public&pgbouncer=true&sslmode=require',
      onConnect: initialiseData,
    },
    ui: {
      isAccessAllowed: (context) => !!context.session?.data,
    },
    lists,
    session: withItemData(
      statelessSessions({
        maxAge: sessionMaxAge,
        secret: sessionSecret,
      }),
      { User: 'email' },
    ),
  }),
);
</code>```

i figured out that when i do :

isAccessAllowed: (context) => true

it's working

any advice here

答:
You can find a working example in keystonejs repository (blog)

You have to await and pass context to the initialiseData() method. The onConnect hook already provides this context for you

also, you can look for an argument like '--seed-data' so it's only run once
and run the code as:

```<code>keystone --seed-data
</code>```
```<code>export default auth.withAuth(
  config({
    db: {
      adapter: 'prisma_postgresql',
      url:
        'postgres://admin:aj093bf7l6jdx5hm@wirxe-app-database-do-user-9126376-0.b.db.ondigitalocean.com:25061/wirxepool?schema=public&pgbouncer=true&sslmode=require',
      async onConnect(context) {
        if (process.argv.includes('--seed-data')) {
          await initialiseData(context);
        }
      },
    },
    ui: {
      isAccessAllowed: (context) => !!context.session?.data,
    },
    lists,
    session: withItemData(
      statelessSessions({
        maxAge: sessionMaxAge,
        secret: sessionSecret,
      }),
      { User: 'email' },
    ),
  }),
);
</code>```

Title: Keystone.js 6 access denied adminMeta

Body:
i want to seed data onConnect,  but i have access denied,  using this query :

{
        keystone: keystone {
        adminMeta {
          lists {
            key
            description
            label
            singular
            plural
            path
            fields {
              path
            }
          }
        }
      }

i have this error even iam using sudo, context.sudo().graphql.raw :

[
  Error: Access denied
      at /Users/sidalitemkit/work/web/yet/wirxe/wirxe-app/node_modules/@keystone-next/admin-ui/system/dist/admin-ui.cjs.dev.js:552:19
      at processTicksAndRejections (node:internal/process/task_queues:94:5)
      at async Promise.all (index 0)
      at async Promise.all (index 0) {
    locations: [ [Object] ],
    path: [ 'keystone', 'adminMeta' ]
  }
]

here my config :

export default auth.withAuth(
  config({
    db: {
      adapter: 'prisma_postgresql',
      url:
        'postgres://admin:aj093bf7l6jdx5hm@wirxe-app-database-do-user-9126376-0.b.db.ondigitalocean.com:25061/wirxepool?schema=public&pgbouncer=true&sslmode=require',
      onConnect: initialiseData,
    },
    ui: {
      isAccessAllowed: (context) => !!context.session?.data,
    },
    lists,
    session: withItemData(
      statelessSessions({
        maxAge: sessionMaxAge,
        secret: sessionSecret,
      }),
      { User: 'email' },
    ),
  }),
);

i figured out that when i do :

isAccessAllowed: (context) => true

it's working

any advice here

Body:
You can find a working example in keystonejs repository (blog)

You have to await and pass context to the initialiseData() method. The onConnect hook already provides this context for you

also, you can look for an argument like '--seed-data' so it's only run once
and run the code as:

keystone --seed-data

export default auth.withAuth(
  config({
    db: {
      adapter: 'prisma_postgresql',
      url:
        'postgres://admin:aj093bf7l6jdx5hm@wirxe-app-database-do-user-9126376-0.b.db.ondigitalocean.com:25061/wirxepool?schema=public&pgbouncer=true&sslmode=require',
      async onConnect(context) {
        if (process.argv.includes('--seed-data')) {
          await initialiseData(context);
        }
      },
    },
    ui: {
      isAccessAllowed: (context) => !!context.session?.data,
    },
    lists,
    session: withItemData(
      statelessSessions({
        maxAge: sessionMaxAge,
        secret: sessionSecret,
      }),
      { User: 'email' },
    ),
  }),
);


问:
Find file in directory with the max number given a set of different file names
Problem Description

I have a list of files ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]. That list has 3 different file names FA, FB and FC. For each of FA, FB and FC, I am trying to retrieve the one with the max number.  The following script that I coded does that. But it's so complicated and ugly.

Is there a way to make it simpler?

A similar question was asked in Find file in directory with the highest number in the filename. But, they are only using the same file name.

```<code>#!/usr/bin/env python

import sys
import os
from collections import defaultdict

def load_newest_files():
    # Retrieve all files for the component in question
    list_of_files = defaultdict(list)
    new_list_of_files = []
    files = ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]

    # Split files and take the filename without the id.
    # The files are not separated in bucket of FA, FB and FC
    # I can now retrieve the file with the max number and put
    # it in a list
    for file in files:
        list_of_files[file.split("_")[0]].append(file)

    for key,value in list_of_files.items():
        new_list_of_files.append(max(value))

    print(new_list_of_files)

def main():
    load_newest_files()

if __name__ == "__main__":
    main()
</code>```

答:
You can use the regex library and sort(). An example is shown below.

```<code>import re

def load_newest_files():
    files = ["FA_1", "FA_2", "FB_1", "FB_2", "FC_1", "FC_2"]
    # Sort the list
    files.sort()
    concat_files = " ".join(files)
    a = dict(re.findall('(.*?)_([0-9])[ ]?', concat_files))
    new_list_of_files = ["%s_%s" % (i, j) for i, j in a.items()]
    return new_list_of_files

def main():
    newest_files = load_newest_files()
    print(newest_files)

if __name__ == "__main__":
    main()
</code>```

Body:
Problem Description

I have a list of files ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]. That list has 3 different file names FA, FB and FC. For each of FA, FB and FC, I am trying to retrieve the one with the max number.  The following script that I coded does that. But it's so complicated and ugly.

Is there a way to make it simpler?

A similar question was asked in Find file in directory with the highest number in the filename. But, they are only using the same file name.

#!/usr/bin/env python

import sys
import os
from collections import defaultdict

def load_newest_files():
    # Retrieve all files for the component in question
    list_of_files = defaultdict(list)
    new_list_of_files = []
    files = ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]

    # Split files and take the filename without the id.
    # The files are not separated in bucket of FA, FB and FC
    # I can now retrieve the file with the max number and put
    # it in a list
    for file in files:
        list_of_files[file.split("_")[0]].append(file)

    for key,value in list_of_files.items():
        new_list_of_files.append(max(value))

    print(new_list_of_files)

def main():
    load_newest_files()

if __name__ == "__main__":
    main()

Body:
You can use the regex library and sort(). An example is shown below.

import re

def load_newest_files():
    files = ["FA_1", "FA_2", "FB_1", "FB_2", "FC_1", "FC_2"]
    # Sort the list
    files.sort()
    concat_files = " ".join(files)
    a = dict(re.findall('(.*?)_([0-9])[ ]?', concat_files))
    new_list_of_files = ["%s_%s" % (i, j) for i, j in a.items()]
    return new_list_of_files

def main():
    newest_files = load_newest_files()
    print(newest_files)

if __name__ == "__main__":
    main()


问:
JavaScript concat string with backspace
I have a function f similar to

```<code>function f(str){
    alert("abc"+str);
}
</code>```

Now, I want to use JavaScript special charecter "\b" in such a way that I can choose if I want to display the hardcoded string "abc" or not. For example,

```<code>f("\b\b"+"yz"); //should output "ayz"
</code>```

I tried the same, but it does not work. In other words, I want to concat a string with a backspace character so that I can remove last characters from the string.

Can we do this in JavaScript?

EDIT
The real code is too much big (its a HUGE 1 liner that concats many many strings). To map that in above example, we cannot edit the function f, so do whatever you want from outside function f.

答:
I'm processing the backspace \b, but it always has the ANSI erase in line \x1B[K after the \bs. So what I do is this:

function applyBackspaces(str) {
  // Catch character + \b or character + \b\x1B[K and delete it
  const re = /.?[\u0008](\u001b\[K)?/
  while (re.test(str)) {
    str = str.replace(re, "");
  }
  return str;
}

// wrote "up", backspace+erase, backspace+erase (used backspace key)
// wrote "ls", backspace+backspace+erase (used clear line command C-u)
// wrote uptime
applyBackspaces('up\b\x1B[K\b\x1B[Kls\b\b\x1B[Kuptime') // uptime
```

Title: JavaScript concat string with backspace

Body:
I have a function f similar to

function f(str){
    alert("abc"+str);
}

Now, I want to use JavaScript special charecter "\b" in such a way that I can choose if I want to display the hardcoded string "abc" or not. For example,

f("\b\b"+"yz"); //should output "ayz"

I tried the same, but it does not work. In other words, I want to concat a string with a backspace character so that I can remove last characters from the string.

Can we do this in JavaScript?

EDIT
The real code is too much big (its a HUGE 1 liner that concats many many strings). To map that in above example, we cannot edit the function f, so do whatever you want from outside function f.


问:
Unresolved reference: when i am trying to access view using view binding
I am working on an Ecommerce app, where i am getting data from an online api. After getting data I am trying to get them inside my recycler view. Here i am using View Binding to bind my xml view with the activity using a Recycler View and its adapter. So the problem arise here and it says Unresolved Reference to my View IDS

Errors:

```<code>e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (25, 21): Unresolved reference: hotProductsScreenProgressBar
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (25, 50): Variable expected
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (29, 25): Unresolved reference: hotProductsScreenProgressBar
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (29, 54): Variable expected
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (33, 25): Unresolved reference: hotProductsScreenProgressBar
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (33, 54): Variable expected
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (43, 21): Unresolved reference: hotProductsScreenProgressBar
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (43, 50): Variable expected
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (47, 47): Unresolved reference: hotProductsScreenRecyclerView
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (49, 9): Unresolved reference: adapter
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (50, 9): Unresolved reference: layoutManager
</code>```

Activity

```<code>class HotProducts : AppCompatActivity() {
    private val TAG = "Hot Products"
    private  lateinit var productAdapter: SimpleProductsAdapter
    private lateinit var binding: ActivityHotProductsBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHotProductsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setUpRecyclerView()
        lifecycleScope.launchWhenCreated {
            binding.hotProductsScreenProgressBar.isVisible = true
            val response= try {
                RetrofitInstance.api.getTodos()
            } catch (e: IOException){
                binding.hotProductsScreenProgressBar.isVisible = false
                Log.e(TAG, "IOException: You might not have internet connection!")
                return@launchWhenCreated
            }catch (e: HttpException){
                binding.hotProductsScreenProgressBar.isVisible = false
                Log.e(TAG, "IOException: Unexpected Response!")
                return@launchWhenCreated
            }
            if(response.isSuccessful && response.body()!=null){
                productAdapter.products = response.body()!!
            }
            else{
                Log.e(TAG, "IOException: Unexpected Response!")
            }
            binding.hotProductsScreenProgressBar.isVisible = false
        }
    }

    private fun setUpRecyclerView() = binding.hotProductsScreenRecyclerView.apply{
        productAdapter = SimpleProductsAdapter()
        adapter = productAdapter
        layoutManager = LinearLayoutManager(this@HotProducts)

    }
}
</code>```

Here is my Adapter Class

```<code>package com.example.essstore.data

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.essstore.databinding.GeneralProductCardBinding

class SimpleProductsAdapter : RecyclerView.Adapter<SimpleProductsAdapter.ProductViewHolder>() {

    inner class ProductViewHolder (val binding: GeneralProductCardBinding): RecyclerView.ViewHolder(binding.root)

    private val difCallBack= object : DiffUtil.ItemCallback<product>(){
        override fun areItemsTheSame(oldItem: product, newItem: product): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: product, newItem: product): Boolean {
            return oldItem == newItem
        }
    }

    private val differ = AsyncListDiffer(this, difCallBack)
    var products: List<product>
        set(value) {
            differ.submitList(value)
        }
        get() = differ.currentList

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
        return ProductViewHolder(
            GeneralProductCardBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        holder.binding.apply {
            val product = products[position]
            generalProductCardTitle.text = product.productName
            generalProductCardDescription.text = product.productDescription
            generalProductCardPrice.text = "$ ${product.productPrice}"
        }
    }

    override fun getItemCount(): Int {
        return products.size
    }
}
</code>```

Here is my XML File:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/primary_color"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".view.HotProducts">

    <ImageView
        android:id="@+id/_btn_profile_screen_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon_back"
        android:clickable="true"/>

    <TextView
        android:layout_marginTop="32dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:fontFamily="@font/montserrat_bold"
        android:textSize="24sp"
        android:text="Hot Products"
        android:textColor="@color/white"/>

    <ProgressBar
        android:id="@+id/_hot_products_screen_progress_bar"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:visibility="gone"/>

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

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="none">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/_hot_products_screen_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:listitem="@layout/general_product_card"/>

        </ScrollView>

    </LinearLayout>

</LinearLayout>
</code>```

Kindly Help me out! I tried many solutions but they didn't worked for me.

答:
Try to remove the leading underscore from all view ids in the XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/primary_color"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".view.HotProducts">

    <ImageView
        android:id="@+id/btn_profile_screen_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon_back"
        android:clickable="true"/>

    ...

    <ProgressBar
        android:id="@+id/hot_products_screen_progress_bar"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:visibility="gone"/>

        ...

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/hot_products_screen_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:listitem="@layout/general_product_card"/>

        ...

</LinearLayout>
</code>```

Body:
I am working on an Ecommerce app, where i am getting data from an online api. After getting data I am trying to get them inside my recycler view. Here i am using View Binding to bind my xml view with the activity using a Recycler View and its adapter. So the problem arise here and it says Unresolved Reference to my View IDS

Errors:

e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (25, 21): Unresolved reference: hotProductsScreenProgressBar
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (25, 50): Variable expected
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (29, 25): Unresolved reference: hotProductsScreenProgressBar
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (29, 54): Variable expected
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (33, 25): Unresolved reference: hotProductsScreenProgressBar
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (33, 54): Variable expected
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (43, 21): Unresolved reference: hotProductsScreenProgressBar
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (43, 50): Variable expected
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (47, 47): Unresolved reference: hotProductsScreenRecyclerView
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (49, 9): Unresolved reference: adapter
e: /Users/gama/Desktop/essStore/app/src/main/java/com/example/essstore/view/HotProducts.kt: (50, 9): Unresolved reference: layoutManager

Activity

class HotProducts : AppCompatActivity() {
    private val TAG = "Hot Products"
    private  lateinit var productAdapter: SimpleProductsAdapter
    private lateinit var binding: ActivityHotProductsBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHotProductsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setUpRecyclerView()
        lifecycleScope.launchWhenCreated {
            binding.hotProductsScreenProgressBar.isVisible = true
            val response= try {
                RetrofitInstance.api.getTodos()
            } catch (e: IOException){
                binding.hotProductsScreenProgressBar.isVisible = false
                Log.e(TAG, "IOException: You might not have internet connection!")
                return@launchWhenCreated
            }catch (e: HttpException){
                binding.hotProductsScreenProgressBar.isVisible = false
                Log.e(TAG, "IOException: Unexpected Response!")
                return@launchWhenCreated
            }
            if(response.isSuccessful && response.body()!=null){
                productAdapter.products = response.body()!!
            }
            else{
                Log.e(TAG, "IOException: Unexpected Response!")
            }
            binding.hotProductsScreenProgressBar.isVisible = false
        }
    }

    private fun setUpRecyclerView() = binding.hotProductsScreenRecyclerView.apply{
        productAdapter = SimpleProductsAdapter()
        adapter = productAdapter
        layoutManager = LinearLayoutManager(this@HotProducts)

    }
}

Here is my Adapter Class

package com.example.essstore.data

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.essstore.databinding.GeneralProductCardBinding

class SimpleProductsAdapter : RecyclerView.Adapter<SimpleProductsAdapter.ProductViewHolder>() {

    inner class ProductViewHolder (val binding: GeneralProductCardBinding): RecyclerView.ViewHolder(binding.root)

    private val difCallBack= object : DiffUtil.ItemCallback<product>(){
        override fun areItemsTheSame(oldItem: product, newItem: product): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: product, newItem: product): Boolean {
            return oldItem == newItem
        }
    }

    private val differ = AsyncListDiffer(this, difCallBack)
    var products: List<product>
        set(value) {
            differ.submitList(value)
        }
        get() = differ.currentList

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
        return ProductViewHolder(
            GeneralProductCardBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        holder.binding.apply {
            val product = products[position]
            generalProductCardTitle.text = product.productName
            generalProductCardDescription.text = product.productDescription
            generalProductCardPrice.text = "$ ${product.productPrice}"
        }
    }

    override fun getItemCount(): Int {
        return products.size
    }
}

Here is my XML File:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/primary_color"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".view.HotProducts">

    <ImageView
        android:id="@+id/_btn_profile_screen_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon_back"
        android:clickable="true"/>

    <TextView
        android:layout_marginTop="32dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:fontFamily="@font/montserrat_bold"
        android:textSize="24sp"
        android:text="Hot Products"
        android:textColor="@color/white"/>

    <ProgressBar
        android:id="@+id/_hot_products_screen_progress_bar"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:visibility="gone"/>

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

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="none">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/_hot_products_screen_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:listitem="@layout/general_product_card"/>

        </ScrollView>

    </LinearLayout>

</LinearLayout>

Kindly Help me out! I tried many solutions but they didn't worked for me.

Body:
Try to remove the leading underscore from all view ids in the XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/primary_color"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".view.HotProducts">

    <ImageView
        android:id="@+id/btn_profile_screen_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon_back"
        android:clickable="true"/>

    ...

    <ProgressBar
        android:id="@+id/hot_products_screen_progress_bar"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:visibility="gone"/>

        ...

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/hot_products_screen_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:listitem="@layout/general_product_card"/>

        ...

</LinearLayout>


问:
Jsp page return "The superclass "jakarta.servlet.http.HttpServlet" was not found" error
I was working with sample spring project  , and all of the sudden the Jsp pages starts to

complain about absent of "jakarta.servlet.http.HttpServlet". Im not using any type of Jakarta

feature. My web service is Tomcat 9 and for JSP im using javax.servlet.jsp.jstl-1.2.1 and

javax.servlet.jsp.jstl-api-1.2.1. The project structure is Dynamic Web Project with these

setting :

and error :

答:
http.HttpServlet mostly means you do not have a Tomcat for the project.

Right-click on the project > Properties > Project Facets > Runtimes, make sure that you checkmark the Tomcat > Apply.

If that does not work you can

Right-click on the project > Properties > Java Build Path > Add Library > Server Runtime, and select your Apache Tomcat 9


问:
Summing consecutive elements in a list and appending to a new list
Consider the list:

```<code>a = [1,2,3,4,5]
</code>```

How can I iterate through this list summing the consecutive elements and then producing a new list as follows:

```<code>b = [1,3,6,10,15]
</code>```

such that each element in list b is the sum of all the prior elements up to that index number from list a. i.e. b[0] = a[0], b[1] = a[0]+a[1], b[2] = a[0]+a[1)+a[2] etc.

This is merely pseudo-code. In reality, my real list 'a' has thousands of elements, so i need to automate; not just write b[1] = a[0] + a[1] and do that for the 5 elements of b. Any ideas would be greatly appreciated: I am new to python.

答:
You could use list comprehension as follow:

a = [1,2,3,4,5]
b = [sum(a[:i+1]) for i in range(len(a))]
```

Body:
Consider the list:

a = [1,2,3,4,5]

How can I iterate through this list summing the consecutive elements and then producing a new list as follows:

b = [1,3,6,10,15]

such that each element in list b is the sum of all the prior elements up to that index number from list a. i.e. b[0] = a[0], b[1] = a[0]+a[1], b[2] = a[0]+a[1)+a[2] etc.

This is merely pseudo-code. In reality, my real list 'a' has thousands of elements, so i need to automate; not just write b[1] = a[0] + a[1] and do that for the 5 elements of b. Any ideas would be greatly appreciated: I am new to python.


答:
If you're willing to use numpy this is just the cumsum function:

```<code>import numpy as np
a = [1,2,3,4,5]
np.cumsum(a)
# array([ 1,  3,  6, 10, 15], dtype=int32)
</code>```

Title: Summing consecutive elements in a list and appending to a new list

Body:
If you're willing to use numpy this is just the cumsum function:

import numpy as np
a = [1,2,3,4,5]
np.cumsum(a)
# array([ 1,  3,  6, 10, 15], dtype=int32)


问:
TicTacToe Heavy Win Condition
I made a TicTacToe game in Ruby. I am pretty new to Ruby OOP. My win conditions for checking row, column and diagonals are really heavy and they take too much code line and look pretty horrible. My code also always repeating.

So my question is how to implement the below win conditions into my code?

 WIN_COMBINATIONS = [
[0,1,2], # top_row
[3,4,5], # middle_row
[6,7,8], # bottom_row
[0,3,6], # left_column
[1,4,7], # center_column
[2,5,8], # right_column
[0,4,8], # left_diagonal
[6,4,2] # right_diagonal
]
```
<p>Here is my win conditions:</p>
<pre class="lang-rb prettyprint-override"><code>module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end
</code>```

I invoke these conditions from this line of code:

def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

```
<p>Here is my full of project that it is correctly working.</p>
<pre class="lang-rb prettyprint-override"><code>module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end

# TicTacToe Board
class Board
  include CheckWinner
  attr_accessor :board

  def initialize
    @board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  end

  def print_board
    puts '-------------'
    @board.each do |row|
      print '|'
      row.each do |col|
        print " #{col}"
        print ' | '
      end
      puts
    end
    puts '-------------'
  end

  def twodimentional_board
    @board = @board.each_slice(3).map { |el| el }
  end

  def occupied_error(value)
    puts 'There is a value or wrong place! Try Again!'
    twodimentional_board
    print_board
    value == @player1 ? player2(@player1) : player1(@player2) # Stay same player
  end

  def move_if_possible(place, value)
    @board.flatten!
    if @board[place - 1] == 'X' || @board[place - 1] == 'O' || !place.between?(1, 9)
      occupied_error(value)
    else
      @board[place - 1] = value
      twodimentional_board
      @board
    end
  end

  def full?
    if @board.flatten.all?(String)
      puts 'Draw!'
      true
    end
  end

  def choosing_player
    puts 'Choose for Player1(X or O)'
    loop do
      @player1 = gets.chomp!
      break if @player1 == 'X' || @player1 == 'O'

      puts 'Try Again!(X or O)'
    end
    puts "Player 1 is: #{@player1}"

    @player1 == 'X' ? @player2 = 'O' : @player2 = 'X'
    puts "Player 2 is: #{@player2}"
    print_board
  end

  def player1(player1)
    puts "Choice #{player1} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player1)
    print_board
  end

  def player2(player2)
    puts "Choice #{player2} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player2)
    print_board
  end

  def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

board = Board.new
board.game
</code>```

If you want to live preview here is repl link

答:
I'm not sure if this is exactly what you're after, but there are a few things here.

your @board is an array of 3 rows, but your possible wins is just an array of points. flattening your @board means you can use the index as is.

you already have an array of win conditions, you then ignore this array and work through manually all options

definitions

```<code># example winning board for 'O'
@board = [['O','X','O'], ['X','O','X'], ['X','O','O']]
player1 = 'X'
player2 = 'O'
</code>```

First, loop through the possible combinations in WIN_COMBINATIONS, and for each of those combinations get those cells from @board as individual arrays, for later checking. store the array of arrays as another array (using #map). the * character is the ruby splat operator, which converts an array into arguments for the called procedure.

shorthand:

```<code>winmap = WIN_COMBINATIONS.map {|w| @board.flatten.values_at(*w)}
</code>```

longhand:

```<code>flat_board = @board.flatten
winmap = WIN_COMBINATIONS.map do |win|
  flat_board.values_at(*win)
end
</code>```

which sets up an array like follows:

```<code>winmap = [
  ["O", "X", "O"], # top_row
  ["X", "O", "X"], # middle_row
  ["X", "O", "O"], # bottom_row
  ["O", "X", "X"], # left_column
  ["X", "O", "O"], # center_column
  ["O", "X", "O"], # right_column
  ["O", "O", "O"], # left_diagonal
  ["X", "O", "O"] # right_diagonal
]
</code>```

once you have the list of all possible winning cells from the board, you can use your existing row searching code, except rather than looping through each array, we use the array operation #any? to identify matches

```<code>player1_win = winmap.any?{|m| m.all?(player1)}
player2_win = winmap.any?{|m| m.all?(player2)}
</code>```

this should eliminate all the individual subroutines, and give you a true/false answer for if anyone has won.

Title: TicTacToe Heavy Win Condition

Body:
I made a TicTacToe game in Ruby. I am pretty new to Ruby OOP. My win conditions for checking row, column and diagonals are really heavy and they take too much code line and look pretty horrible. My code also always repeating.

So my question is how to implement the below win conditions into my code?

 WIN_COMBINATIONS = [
[0,1,2], # top_row
[3,4,5], # middle_row
[6,7,8], # bottom_row
[0,3,6], # left_column
[1,4,7], # center_column
[2,5,8], # right_column
[0,4,8], # left_diagonal
[6,4,2] # right_diagonal
]

Here is my win conditions:

module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end

I invoke these conditions from this line of code:

def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

Here is my full of project that it is correctly working.

module CheckWinner
  def check_horizontal(player1, player2)
    player1_win = false
    player2_win = false
    @board.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_vertical(player1, player2)
    player1_win = false
    player2_win = false
    @board.transpose.each do |row|
      player1_win = row.all?(player1)
      player2_win = row.all?(player2)
      break if player1_win || player2_win
    end
    puts "#{player1} won!" if player1_win
    puts "#{player2} won!" if player2_win
    player1_win || player2_win
  end

  def check_diagonal(player1, player2)
    if @board[0][0] == player1 && board[1][1] == player1 && board[2][2] == player1 ||
       @board[0][2] == player1 && board[1][1] == player1 && board[2][0] == player1
      puts "#{@player1} won!"
      true

    elsif @board[0][0] == player2 && board[1][1] == player2 && board[2][2] == player2 ||
          @board[0][2] == player2 && board[1][1] == player2 && board[2][0] == player2
      puts "#{@player2} won!"
      true
    end
  end
end

# TicTacToe Board
class Board
  include CheckWinner
  attr_accessor :board

  def initialize
    @board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  end

  def print_board
    puts '-------------'
    @board.each do |row|
      print '|'
      row.each do |col|
        print " #{col}"
        print ' | '
      end
      puts
    end
    puts '-------------'
  end

  def twodimentional_board
    @board = @board.each_slice(3).map { |el| el }
  end

  def occupied_error(value)
    puts 'There is a value or wrong place! Try Again!'
    twodimentional_board
    print_board
    value == @player1 ? player2(@player1) : player1(@player2) # Stay same player
  end

  def move_if_possible(place, value)
    @board.flatten!
    if @board[place - 1] == 'X' || @board[place - 1] == 'O' || !place.between?(1, 9)
      occupied_error(value)
    else
      @board[place - 1] = value
      twodimentional_board
      @board
    end
  end

  def full?
    if @board.flatten.all?(String)
      puts 'Draw!'
      true
    end
  end

  def choosing_player
    puts 'Choose for Player1(X or O)'
    loop do
      @player1 = gets.chomp!
      break if @player1 == 'X' || @player1 == 'O'

      puts 'Try Again!(X or O)'
    end
    puts "Player 1 is: #{@player1}"

    @player1 == 'X' ? @player2 = 'O' : @player2 = 'X'
    puts "Player 2 is: #{@player2}"
    print_board
  end

  def player1(player1)
    puts "Choice #{player1} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player1)
    print_board
  end

  def player2(player2)
    puts "Choice #{player2} Place on a board(1 to 10)"
    @place = gets.chomp!.to_i
    move_if_possible(@place, player2)
    print_board
  end

  def game
    choosing_player
    loop do
      player1(@player1)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?

      player2(@player2)
      break if check_vertical(@player1,@player2) == true || check_diagonal(@player1,@player2) == true || check_horizontal(@player1,@player2) == true || full?
    end
  end
end

board = Board.new
board.game

If you want to live preview here is repl link

Body:
I'm not sure if this is exactly what you're after, but there are a few things here.

your @board is an array of 3 rows, but your possible wins is just an array of points. flattening your @board means you can use the index as is.

you already have an array of win conditions, you then ignore this array and work through manually all options

definitions

# example winning board for 'O'
@board = [['O','X','O'], ['X','O','X'], ['X','O','O']]
player1 = 'X'
player2 = 'O'

First, loop through the possible combinations in WIN_COMBINATIONS, and for each of those combinations get those cells from @board as individual arrays, for later checking. store the array of arrays as another array (using #map). the * character is the ruby splat operator, which converts an array into arguments for the called procedure.

shorthand:

winmap = WIN_COMBINATIONS.map {|w| @board.flatten.values_at(*w)}

longhand:

flat_board = @board.flatten
winmap = WIN_COMBINATIONS.map do |win|
  flat_board.values_at(*win)
end

which sets up an array like follows:

winmap = [
  ["O", "X", "O"], # top_row
  ["X", "O", "X"], # middle_row
  ["X", "O", "O"], # bottom_row
  ["O", "X", "X"], # left_column
  ["X", "O", "O"], # center_column
  ["O", "X", "O"], # right_column
  ["O", "O", "O"], # left_diagonal
  ["X", "O", "O"] # right_diagonal
]

once you have the list of all possible winning cells from the board, you can use your existing row searching code, except rather than looping through each array, we use the array operation #any? to identify matches

player1_win = winmap.any?{|m| m.all?(player1)}
player2_win = winmap.any?{|m| m.all?(player2)}

this should eliminate all the individual subroutines, and give you a true/false answer for if anyone has won.


问:
Simple string addition in ruby/rails
This is something I wasn't expecting.

I'm using anemone to count links in pages (anemone is a web spider framework for ruby)

Its pretty straightforward, but why won't this work?

```<code>anemone.on_every_page do |page|
    @myLinks =[]
      page.links.each_with_index do |link,index|
        puts "HOWDY PARDNER"
        @tempLink =(link.to_s + ",")
        @myLinks[index] = @tempLink
      end
end
</code>```

The part in question is the addition of link.to_s  +","

The reason I'm doing this addition is that links.to_s comes down as an entire string with no spaces. I'd like to sepsrate them with a , so I can use .split() later.

答:
If you need json array just consider using

```<code> array.to_json
</code>```

method

Title: Simple string addition in ruby/rails

Body:
This is something I wasn't expecting.

I'm using anemone to count links in pages (anemone is a web spider framework for ruby)

Its pretty straightforward, but why won't this work?

anemone.on_every_page do |page|
    @myLinks =[]
      page.links.each_with_index do |link,index|
        puts "HOWDY PARDNER"
        @tempLink =(link.to_s + ",")
        @myLinks[index] = @tempLink
      end
end

The part in question is the addition of link.to_s  +","

The reason I'm doing this addition is that links.to_s comes down as an entire string with no spaces. I'd like to sepsrate them with a , so I can use .split() later.

Body:
If you need json array just consider using

 array.to_json

method


问:
using styled components i got stuck while displaying a image. i don't know where things went wrong
here is my code I am trying to display an image on my document but it is not visible:
is something wrong with the styled component or I have placed something wrong somewhere

this code is from the lama dev  React e-commerce video I am practicing that eCommerce
https://youtu.be/c1xTDSIXit8

```<code>import { ArrowLeftOutlined, ArrowRightOutlined } from '@material-ui/icons'
import React from 'react'
import styled from "styled-components"
import dummy from '../img/girl.png'

const Container=styled.div`
    height:100vh;
    width:100%;
    display:flex;
    position:relative;
    `
const Arrow= styled.div`
    width:50px;
    height:50px;
    background-color:#fff7f7;
    border-radius:50%;
    display:flex;
    align-items:center;
    justify-content:center;
    position:absolute;
    top:0;
    bottom:0;
    left: ${props=>props.direction === 'left' && '15px'};
    right: ${props=>props.direction === 'right' && '15px'};
    margin:auto;
    cursor:pointer;
    opacity:0.5;
    `
const Wrapper=styled.div`
height:100%;
`
const Slide= styled.div`
width:100vw:
height:100vh;
display:flex;
align-items:center;
`
const ImgContainer= styled.div`
height:100%;
flex:1;
`
const Image= styled.div`
height:80%;
`
const InfoContainer= styled.div`
flex:1;
padding:50px;
`
const Title= styled.h1``
const Description= styled.p``
const Button= styled.button``

const Slider = () => {
  return (
    <Container>
        <Arrow direction='left'>
            <ArrowLeftOutlined/>
        </Arrow>
        <Wrapper>
            <Slide>
            <ImgContainer>
                <Image src={dummy}/>
            </ImgContainer>
            <InfoContainer>
                <Title>SUMMER SAL</Title>
                <Description>DON'T COMPROMISE ON STYLE! GET FLAT 30% OFF FOR NEW ARRIVALS.</Description>
                <Button>SHOW NOW</Button>
            </InfoContainer>
            </Slide>
        </Wrapper>
        <Arrow direction='right'>
            <ArrowRightOutlined/>
        </Arrow>
    </Container>
  )
}

export default Slider
</code>```

there is no error in my code but I can't view the image

答:
const Image = styled.img`
height:80%;
`
```

I guess?

Body:
here is my code I am trying to display an image on my document but it is not visible:
is something wrong with the styled component or I have placed something wrong somewhere

this code is from the lama dev  React e-commerce video I am practicing that eCommerce
https://youtu.be/c1xTDSIXit8

import { ArrowLeftOutlined, ArrowRightOutlined } from '@material-ui/icons'
import React from 'react'
import styled from "styled-components"
import dummy from '../img/girl.png'

const Container=styled.div`
    height:100vh;
    width:100%;
    display:flex;
    position:relative;
    `
const Arrow= styled.div`
    width:50px;
    height:50px;
    background-color:#fff7f7;
    border-radius:50%;
    display:flex;
    align-items:center;
    justify-content:center;
    position:absolute;
    top:0;
    bottom:0;
    left: ${props=>props.direction === 'left' && '15px'};
    right: ${props=>props.direction === 'right' && '15px'};
    margin:auto;
    cursor:pointer;
    opacity:0.5;
    `
const Wrapper=styled.div`
height:100%;
`
const Slide= styled.div`
width:100vw:
height:100vh;
display:flex;
align-items:center;
`
const ImgContainer= styled.div`
height:100%;
flex:1;
`
const Image= styled.div`
height:80%;
`
const InfoContainer= styled.div`
flex:1;
padding:50px;
`
const Title= styled.h1``
const Description= styled.p``
const Button= styled.button``

const Slider = () => {
  return (
    <Container>
        <Arrow direction='left'>
            <ArrowLeftOutlined/>
        </Arrow>
        <Wrapper>
            <Slide>
            <ImgContainer>
                <Image src={dummy}/>
            </ImgContainer>
            <InfoContainer>
                <Title>SUMMER SAL</Title>
                <Description>DON'T COMPROMISE ON STYLE! GET FLAT 30% OFF FOR NEW ARRIVALS.</Description>
                <Button>SHOW NOW</Button>
            </InfoContainer>
            </Slide>
        </Wrapper>
        <Arrow direction='right'>
            <ArrowRightOutlined/>
        </Arrow>
    </Container>
  )
}

export default Slider

there is no error in my code but I can't view the image

Body:
const Image = styled.img`
height:80%;
`

I guess?


问:
Material UI v5 styles applied to class does'nt apply?
I am trying to style the MUI slider,so I decided to style it using the className prop. But the style applied to the main class does'nt get applied,while rest other styles like 'hover' state get applied. If I remove all the classes and just style it using SX prop,everything works fine. But I want to keep the styles seperate into an external css file.

Below is my code :

App.css

```<code>.container{
  margin-left: 30%;
  margin-top: 20%;

}

/* This does'nt get applied */
.slider {
  color: #ff0000;
  width: 300px;
}

.slider:hover {
  color: #2e8b57;
}

.slider > .MuiSlider-thumb {
  border-radius: 1px;
}
</code>```

App.js

```<code>import "./App.css"
import * as React from 'react';
import Slider from '@mui/material/Slider';

export default function App() {
  return (
    <div className="container">
      <Slider className="slider"  defaultValue={30} />
    </div>
  );
}
</code>```

答:
I don't know if it is required, but I use css modules and material-ui. You can rename your css file to

App.module.css

then import like so

```<code>import styles from "./App.module.css"
</code>```

you can then use it like

```<code><Slider className={styles.slider}  defaultValue={30} />
</code>```

In Nextjs you can throw everything in styles.css to make it global, but I don't know if that is also for react as well.

Body:
I am trying to style the MUI slider,so I decided to style it using the className prop. But the style applied to the main class does'nt get applied,while rest other styles like 'hover' state get applied. If I remove all the classes and just style it using SX prop,everything works fine. But I want to keep the styles seperate into an external css file.

Below is my code :

App.css

.container{
  margin-left: 30%;
  margin-top: 20%;

}

/* This does'nt get applied */
.slider {
  color: #ff0000;
  width: 300px;
}

.slider:hover {
  color: #2e8b57;
}

.slider > .MuiSlider-thumb {
  border-radius: 1px;
}

App.js

import "./App.css"
import * as React from 'react';
import Slider from '@mui/material/Slider';

export default function App() {
  return (

      <Slider className="slider"  defaultValue={30} />

  );
}

Body:
I don't know if it is required, but I use css modules and material-ui. You can rename your css file to

App.module.css

then import like so

import styles from "./App.module.css"

you can then use it like

<Slider className={styles.slider}  defaultValue={30} />

In Nextjs you can throw everything in styles.css to make it global, but I don't know if that is also for react as well.


问:
How to measure size of response data in JMeter
How to measure size of response data of multiple http samplers in JMeter. I need to find the overall size of all the responses not for individual responses. I am trying to fetch it through a Beanshell code but it displays the size of the last sample executed:-

```<code>import java.util.io.*;
import java.lang.io.*;
int totalsize;
test = prev.getResponseDataAsString().length();
log.info("size is = "+test);
totalsize = totalsize + test;
log.info("totalsize is = "+totalsize);
</code>```

Thank you.

答:
it's more appropriate to use prev.getBytesAsLong() to get each sampler response size. Take a look at JMeter API

To have combined size of multiple responses you could try grouping needed requests in transaction via Transaction Controller.

Body:
How to measure size of response data of multiple http samplers in JMeter. I need to find the overall size of all the responses not for individual responses. I am trying to fetch it through a Beanshell code but it displays the size of the last sample executed:-

import java.util.io.*;
import java.lang.io.*;
int totalsize;
test = prev.getResponseDataAsString().length();
log.info("size is = "+test);
totalsize = totalsize + test;
log.info("totalsize is = "+totalsize);

Thank you.


问:
Does Spark allow to use Amazon Assumed Role and STS temporary credentials for Glue cross account access on EMR
We are trying to connect to the cross-account AWS Glue catalog with the EMR spark job.
I did a study that AWS supports cross-account access for the Glue catalog in two ways.

IAM role-based.  (This is not working for me)

Resource-based policy. (This worked for me)

So the problem scenario is, Account A creates EMR with its
role role_Account_A. And role role_Account_A wants to access
the glue catalog of Account B.

Account A creates EMR cluster with role role_Account_A

Account B has role role_Account_B which has access to glue and s3     with role_Account_A in trusted entities.

role_Account_A has sts:AssumeRole policy for resource     role_Account_B

using sdk we are able to assume role role_Account_B from     role_Account_A and getting temporary credentials.

EMR has configurations[{"classification":"spark-hive-site","properties":{"hive.metastore.glue.catalogid":"Account_B",  "hive.metastore.client.factory.class": "com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory"}}]

```<code>    SparkSession sparkSession=SparkSession.builder().appName("testing glue")
                .enableHiveSupport()
                .getOrCreate();
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider");
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.access.key", assumedcreds.getAccessKeyId());
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.secret.key", assumedcreds.getSecretAccessKey());
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.session.token", assumedcreds.getSessionToken());
sparkSession.sparkContext().conf().set("fs.s3a.access.key",  assumedcreds.getAccessKeyId());
sparkSession.sparkContext().conf().set("fs.s3a.secret.key",  assumedcreds.getSecretAccessKey());
sparkSession.sparkContext().conf().set("fs.s3a.session.token", assumedcreds.getSessionToken());
sparkSession.sql("show databases").show(10, false);
</code>```

The error that we are getting is

```<code>    Caused by: MetaException(message:User: arn:aws:sts::Account_A:assumed-role/role_Account_A/i-xxxxxxxxxxxx is not authorized to perform: glue:GetDatabase on resource: arn:aws:glue:XX-XXXX-X:Account_B:catalog
because no resource-based policy allows the glue:GetDatabase action (Service: AWSGlue; Status Code: 400; Error Code: AccessDeniedException; Request ID: X93Xbc64-0153-XXXX-XXX-XXXXXXX))
</code>```

Questions:-

Does spark supports glue-based authentication properties for example    aws.glue.access.key?

As per error spark is not using assumed role    role_Account_B. It uses role_Account_A with which EMR was created.    Can we make it use
assumed role role_Account_B?

I will update the question details if I am missing something.

答:
I believe you're having an EMR instance profile role in Account A. If so, you would have to follow these and cross-account access should work

In Account B,

Under Glue, go to settings and add the ( EMR instance profile role A ) as principal and provide access to Account B's glue and S3. It is recommended to provide only for the buckets you need to access

Go to the bucket policy of the bucket that the glue table will be using and add the ( EMR instance profile role A ) as principal and provide read/write access.

Now if you run the EMR job in account A, you'll see the job running with cross-account access

It works for our purpose. Try it out

Body:
We are trying to connect to the cross-account AWS Glue catalog with the EMR spark job.
I did a study that AWS supports cross-account access for the Glue catalog in two ways.

IAM role-based.  (This is not working for me)

Resource-based policy. (This worked for me)

So the problem scenario is, Account A creates EMR with its
role role_Account_A. And role role_Account_A wants to access
the glue catalog of Account B.

Account A creates EMR cluster with role role_Account_A

Account B has role role_Account_B which has access to glue and s3     with role_Account_A in trusted entities.

role_Account_A has sts:AssumeRole policy for resource     role_Account_B

using sdk we are able to assume role role_Account_B from     role_Account_A and getting temporary credentials.

EMR has configurations[{"classification":"spark-hive-site","properties":{"hive.metastore.glue.catalogid":"Account_B",  "hive.metastore.client.factory.class": "com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory"}}]

    SparkSession sparkSession=SparkSession.builder().appName("testing glue")
                .enableHiveSupport()
                .getOrCreate();
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider");
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.access.key", assumedcreds.getAccessKeyId());
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.secret.key", assumedcreds.getSecretAccessKey());
sparkSession.sparkContext().hadoopConfiguration().set("fs.s3a.session.token", assumedcreds.getSessionToken());
sparkSession.sparkContext().conf().set("fs.s3a.access.key",  assumedcreds.getAccessKeyId());
sparkSession.sparkContext().conf().set("fs.s3a.secret.key",  assumedcreds.getSecretAccessKey());
sparkSession.sparkContext().conf().set("fs.s3a.session.token", assumedcreds.getSessionToken());
sparkSession.sql("show databases").show(10, false);

The error that we are getting is

    Caused by: MetaException(message:User: arn:aws:sts::Account_A:assumed-role/role_Account_A/i-xxxxxxxxxxxx is not authorized to perform: glue:GetDatabase on resource: arn:aws:glue:XX-XXXX-X:Account_B:catalog
because no resource-based policy allows the glue:GetDatabase action (Service: AWSGlue; Status Code: 400; Error Code: AccessDeniedException; Request ID: X93Xbc64-0153-XXXX-XXX-XXXXXXX))

Questions:-

Does spark supports glue-based authentication properties for example    aws.glue.access.key?

As per error spark is not using assumed role    role_Account_B. It uses role_Account_A with which EMR was created.    Can we make it use
assumed role role_Account_B?

I will update the question details if I am missing something.