问:
cannot set header before they are sent to client error
I am facing error while showing JSON response.

My code is here.

```<code>app.get('/api/:id/:uid?',(req,res)=>{//? mean optional parameter
    console.log(req.params);// to get parameter in console
    const id=req.params.id*1;
    console.log(id);
    const tour=tours.find(el=>el.id===id);
    res.status(200).json({
        "staus":"success",
        "tours":tour
    })
    res.send("done");
})
</code>```

showing Cannot set headers after they are sent to the client

答:
I think error message is Cannot set headers after they are sent to the client, not before. It means that you already sent response back to the client. Just remove res.send("done"); this line.

But, be careful about other case like below. You'll also get Cannot set headers after they are sent to the client.

app.get("/path", (req, res) => {
    some_condition = true
    if (some_condition) {
        res.status(200).json({success: true})
    }
    res.status(200).json({success: false})
})
```
<p>So, you should add <code>return</code> in front of <code>res.status(200).json({success: true})</code> like below.</p>
<pre class="lang-js prettyprint-override"><code>app.get("/path", (req, res) => {
    some_condition = true
    if (some_condition) {
        return res.status(200).json({success: true})
    }
    res.status(200).json({success: false})
})
</code>```

Then, it'll not show up Cannot set headers after they are sent to the client this error message.

Body:
I am facing error while showing JSON response.

My code is here.

app.get('/api/:id/:uid?',(req,res)=>{//? mean optional parameter
    console.log(req.params);// to get parameter in console
    const id=req.params.id*1;
    console.log(id);
    const tour=tours.find(el=>el.id===id);
    res.status(200).json({
        "staus":"success",
        "tours":tour
    })
    res.send("done");
})

showing Cannot set headers after they are sent to the client

Body:
I think error message is Cannot set headers after they are sent to the client, not before. It means that you already sent response back to the client. Just remove res.send("done"); this line.

But, be careful about other case like below. You'll also get Cannot set headers after they are sent to the client.

app.get("/path", (req, res) => {
    some_condition = true
    if (some_condition) {
        res.status(200).json({success: true})
    }
    res.status(200).json({success: false})
})

So, you should add return in front of res.status(200).json({success: true}) like below.

app.get("/path", (req, res) => {
    some_condition = true
    if (some_condition) {
        return res.status(200).json({success: true})
    }
    res.status(200).json({success: false})
})

Then, it'll not show up Cannot set headers after they are sent to the client this error message.


来源: stackexchange

问:
How to declare array size at runtime without using dynamic memory allocation
Can I declare an array of size n at runtime without using dynamic memory allocation (malloc etc.) in c?</p>

答:
Short answer: Just use malloc, calloc and free unless you really can't computationally afford it.

Since C99, VLAs (variable-length arrays) were made standard:

```<code>int N;
scanf("%i", &N);
type Array[N]; //Size determined at runtime, grabbed from the stack
</code>```

However, in the C11 standard they were made optional to implement, because their addition was widely criticized.

Major compilers implement them, but I'd discourage you to use them (unless as a temporary solution), because:

Messy semantics with 2D arrays,

Might blow up your stack (if you're not cautious),

Aditionally, VLAs are not a part of the C++ spec.

Don't get me wrong though, they have their uses in ex. embedded programming, where heap allocations (i.e. *alloc-family functions) might be unreliable!

If you're using msvc, you can examine _malloca (and _alloca), which perform explicit dynamically-sized-stack-allocation.

But think again if you really need these.

ContentLicense: CC BY-SA 4.0

Body:
Short answer: Just use malloc, calloc and free unless you really can't computationally afford it.

Since C99, VLAs (variable-length arrays) were made standard:

int N;
scanf("%i", &N);
type Array[N]; //Size determined at runtime, grabbed from the stack

However, in the C11 standard they were made optional to implement, because their addition was widely criticized.

Major compilers implement them, but I'd discourage you to use them (unless as a temporary solution), because:

Messy semantics with 2D arrays,

Might blow up your stack (if you're not cautious),

Aditionally, VLAs are not a part of the C++ spec.

Don't get me wrong though, they have their uses in ex. embedded programming, where heap allocations (i.e. *alloc-family functions) might be unreliable!

If you're using msvc, you can examine _malloca (and _alloca), which perform explicit dynamically-sized-stack-allocation.

But think again if you really need these.


问:
Domino recursion
I have a recursion assignment where I have to input into console the following data:

On the first line a natural number equal with the number of tiles I have to input on the following lines (in my example the first number is 6).

On the following lines the domino tiles in the following order:

1 2

1 3

3 4

2 3

3 5

4 5

On the last line another number representing the number of tiles that needs to be returned on each separate line (in my example the number is equal with 3).

With this data I have to display all possible combinations of pairs. For each separate line the number the second number from the first pair has to be equal with the first number of the following pair and so on. I had a hint for this assignment where I have to declare an intermediary list that is equal with the function (using recursion from the start) but when I'm trying to run the code it gives me a null exception for the intermediaryList.

In the first instance I read the data as a 2d array but settled with a simple string array where.
This is my code so far, could you help me with a suggestion, how to avoid the null exception?
(sorry if I missed something from the explanation, this is my second post here so far and thank you in advance). Also I have to mention that I'm allowed to use just "using System;" Not allowed to use Linq or anything else.

```<code>enter code here

static string[] ReadDominoTiles(int n)
        {
            string[] input = new string[n];
            for (int i = 0; i < n; i++)
            {
                input[i] = Console.ReadLine();
            }

            return input;
        }

        static string[] DominoSolution(string[] dominoTiles, int numberOfPairs)
        {
            string[] finalList = new string[numberOfPairs];

            if (numberOfPairs == 1)
            {
                return finalList;
            }

            string[] intermediaryList = DominoSolution(dominoTiles, numberOfPairs - 1);
            for (int i = 0; i < intermediaryList.Length; i++)
            {
                for (int j = 0; j < dominoTiles.Length; j++)
                {
                   // This is where I get the nullref exception, every value from intermediaryList is null
                    if (intermediaryList[i] != dominoTiles[j] && intermediaryList[j][1] == dominoTiles[j][0])
                    {
                        finalList[j] += intermediaryList[j] + " " + dominoTiles[j];
                    }
                }
            }

            return finalList;
        }

        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            string[] dominoTiles = ReadDominoTiles(n);
            int numberOfPairs = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(DominoSolution(dominoTiles, numberOfPairs));
        }
</code>```

答:
This is where I get the nullref exception, every value from intermediaryList is null

That's correct, you call the function recursively after doing exactly zero work, besides adding a recursion termination condition which returns an array of nulls. So the first time you come out of your recursion you have in intermediaryList a number of null elements, so when you pretend they're strings and try to get intermediaryList[j][1] you'll get a null reference exception.

As to the solution, it's not exactly clear what's with all the arrays you're allocating. Use a List<> with an actual type and do your work properly. Though I hate to break it to you but if I understand your assignment correctly the solution will use backtracking and combinatorics, which is much more code and much better structured than what you have here.

Title: Domino recursion

Body:
I have a recursion assignment where I have to input into console the following data:

On the first line a natural number equal with the number of tiles I have to input on the following lines (in my example the first number is 6).

On the following lines the domino tiles in the following order:

1 2

1 3

3 4

2 3

3 5

4 5

On the last line another number representing the number of tiles that needs to be returned on each separate line (in my example the number is equal with 3).

With this data I have to display all possible combinations of pairs. For each separate line the number the second number from the first pair has to be equal with the first number of the following pair and so on. I had a hint for this assignment where I have to declare an intermediary list that is equal with the function (using recursion from the start) but when I'm trying to run the code it gives me a null exception for the intermediaryList.

In the first instance I read the data as a 2d array but settled with a simple string array where.
This is my code so far, could you help me with a suggestion, how to avoid the null exception?
(sorry if I missed something from the explanation, this is my second post here so far and thank you in advance). Also I have to mention that I'm allowed to use just "using System;" Not allowed to use Linq or anything else.

enter code here

static string[] ReadDominoTiles(int n)
        {
            string[] input = new string[n];
            for (int i = 0; i < n; i++)
            {
                input[i] = Console.ReadLine();
            }

            return input;
        }

        static string[] DominoSolution(string[] dominoTiles, int numberOfPairs)
        {
            string[] finalList = new string[numberOfPairs];

            if (numberOfPairs == 1)
            {
                return finalList;
            }

            string[] intermediaryList = DominoSolution(dominoTiles, numberOfPairs - 1);
            for (int i = 0; i < intermediaryList.Length; i++)
            {
                for (int j = 0; j < dominoTiles.Length; j++)
                {
                   // This is where I get the nullref exception, every value from intermediaryList is null
                    if (intermediaryList[i] != dominoTiles[j] && intermediaryList[j][1] == dominoTiles[j][0])
                    {
                        finalList[j] += intermediaryList[j] + " " + dominoTiles[j];
                    }
                }
            }

            return finalList;
        }

        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            string[] dominoTiles = ReadDominoTiles(n);
            int numberOfPairs = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(DominoSolution(dominoTiles, numberOfPairs));
        }


问:
How can I remove a parameter from a subclass constructor in Java?
In my superclass, I have defined the parameters a, b, c and d. For its subclass, I want to remove d. Is there any way for me to do this?

abstract class Prescription {
    protected Medicine Medicine;
    protected Doctor doctor;
    protected int patientID, thing;
    public Resept(Medicine medicine, Doctor doctor, int patientID, int thing) {
        this.legemiddel = legemiddel;
        this.lege = utskrivendeLege;
        this.pasientID = pasientID;
        this.thing = thing;
```
<p>And in my subclass, I would like to create a constructor without the last parameter "thing"</p>
<pre class="lang-java prettyprint-override"><code>public class TypeBPrescription extends Prescription {
    public TypeBPresciption(Medicine medicine, Doctor doctor, int patientID){
        super(Medicine medicine, Doctor doctor, int patientID,)
    }
}
</code>```

Writing it like this gives me the error that the constructor in the subclass TypeBPrescription is undefined. I want the subclass to not have "thing", but I want my superclass to have it. Is there any way to do this?

答:
Add multiple constructors to the super to clarify thing is optional:

```<code>abstract class Prescription {
    private static final int DEFAULT_THING = 0;
    protected Medicine Medicine;
    protected Doctor doctor;
    protected int patientID, thing;

    public Prescription (Medicine medicine, Doctor doctor, int patientID)
   {
    this(medicine, doctor, paitentId, DEFAULT_THING);

    public Prescription (Medicine medicine, Doctor doctor, int patientID, int thing) {
    this.legemiddel = legemiddel;
    this.lege = utskrivendeLege;
    this.pasientID = pasientID;
    this.thing = thing;
}
</code>```

Then a sub-class can use whichever constructor fits their context.

Body:
In my superclass, I have defined the parameters a, b, c and d. For its subclass, I want to remove d. Is there any way for me to do this?

abstract class Prescription {
    protected Medicine Medicine;
    protected Doctor doctor;
    protected int patientID, thing;
    public Resept(Medicine medicine, Doctor doctor, int patientID, int thing) {
        this.legemiddel = legemiddel;
        this.lege = utskrivendeLege;
        this.pasientID = pasientID;
        this.thing = thing;

And in my subclass, I would like to create a constructor without the last parameter "thing"

public class TypeBPrescription extends Prescription {
    public TypeBPresciption(Medicine medicine, Doctor doctor, int patientID){
        super(Medicine medicine, Doctor doctor, int patientID,)
    }
}

Writing it like this gives me the error that the constructor in the subclass TypeBPrescription is undefined. I want the subclass to not have "thing", but I want my superclass to have it. Is there any way to do this?

Body:
Add multiple constructors to the super to clarify thing is optional:

abstract class Prescription {
    private static final int DEFAULT_THING = 0;
    protected Medicine Medicine;
    protected Doctor doctor;
    protected int patientID, thing;

    public Prescription (Medicine medicine, Doctor doctor, int patientID)
   {
    this(medicine, doctor, paitentId, DEFAULT_THING);

    public Prescription (Medicine medicine, Doctor doctor, int patientID, int thing) {
    this.legemiddel = legemiddel;
    this.lege = utskrivendeLege;
    this.pasientID = pasientID;
    this.thing = thing;
}

Then a sub-class can use whichever constructor fits their context.


问:
Efficient way to Insert the data after generating random sequence
I use the below query to randomly select 10% of IDs (MYSQL(version MySQL 8.0))

select id from
(WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY RAND()) rn, COUNT(*) OVER () cnt
    FROM table1
    where submitted between date_sub(now(),INTERVAL 1 WEEK) and now()
)
SELECT *
FROM cte
WHERE rn < 0.1 * cnt
) as tt;
```
<p>Sample IDs generated:
IDs:
4
7
8
9</p>
<p>Now, I want the selected IDs to be inserted to Tom, Dick and Harry</p>
<p>I can write the Insert statement something like this:</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO table2 (ID,analystName)
select id, 'Tom' from
(WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY RAND()) rn, COUNT(*) OVER () cnt
    FROM table1
    where submitted between date_sub(now(),INTERVAL 1 WEEK) and now()
)
SELECT *
FROM cte
WHERE rn < 0.1 * cnt
) as tt;
</code>```

However, I cannot use the SQL again to insert it for 'Dick' and 'Harry' as the id's generated would be different.
Is there an efficient way to insert the data for the three person in a single INSERT statement?

I want the end result to be:

```<code>IDs AnalystName
4    Tom
7    Tom
8    Tom
9    Tom
4    Dick
7    Dick
8    Dick
9    Dick
4    Harry
7    Harry
8    Harry
9    Harry
</code>```

Table2 where this data would be inserted, doesn't have a data field to filter the data, and this insertion would be a weekly exercise, such that these three users get assigned the same random IDs.

答:
```<code>INSERT INTO
  table2 (
    ID,
    analystName
  )
WITH
  sample
AS
(
  SELECT *, ROW_NUMBER() OVER (ORDER BY RAND()) rn, COUNT(*) OVER () cnt
    FROM table1
   WHERE submitted BETWEEN DATE_SUB(now(),INTERVAL 1 WEEK) AND now()
),
  analyst(name)
AS
(
            SELECT 'tom'
  UNION ALL SELECT 'dick'
  UNION ALL SELECT 'harry'
)
SELECT
  sample.id,
  analyst.name
FROM
  sample
CROSS JOIN
  analyst
WHERE
  sample.rn < sample.cnt * 0.1
</code>```

Body:
I use the below query to randomly select 10% of IDs (MYSQL(version MySQL 8.0))

select id from
(WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY RAND()) rn, COUNT(*) OVER () cnt
    FROM table1
    where submitted between date_sub(now(),INTERVAL 1 WEEK) and now()
)
SELECT *
FROM cte
WHERE rn < 0.1 * cnt
) as tt;

Sample IDs generated:
IDs:
4
7
8
9

Now, I want the selected IDs to be inserted to Tom, Dick and Harry

I can write the Insert statement something like this:

INSERT INTO table2 (ID,analystName)
select id, 'Tom' from
(WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY RAND()) rn, COUNT(*) OVER () cnt
    FROM table1
    where submitted between date_sub(now(),INTERVAL 1 WEEK) and now()
)
SELECT *
FROM cte
WHERE rn < 0.1 * cnt
) as tt;

However, I cannot use the SQL again to insert it for 'Dick' and 'Harry' as the id's generated would be different.
Is there an efficient way to insert the data for the three person in a single INSERT statement?

I want the end result to be:

IDs AnalystName
4    Tom
7    Tom
8    Tom
9    Tom
4    Dick
7    Dick
8    Dick
9    Dick
4    Harry
7    Harry
8    Harry
9    Harry

Table2 where this data would be inserted, doesn't have a data field to filter the data, and this insertion would be a weekly exercise, such that these three users get assigned the same random IDs.


问:
"A JDBC Driver or DataSource class name must be specified in the ConnectionDriverName property." Error
Hi I'm trying to create a simple JPA class using SQLite. I have everything set up then this shows up everytime I try to run main:
"A JDBC Driver or DataSource class name must be specified in the ConnectionDriverName property."
Is it because I have the wrong value for the sqlite driver name?
I can't seem to find out what the value of the property is for sqlite. Here is my persistence.xml:

```<code>    <?xml version="1.0"?>
<persistence>
    <persistence-unit name="testjpa" transaction-type="RESOURCE_LOCAL">
        <provider>
            org.apache.openjpa.persistence.PersistenceProviderImpl
        </provider>
        <class>entity.Discography</class>
        <properties>
            <property name="openjpa.ConnectionURL" value="jdbc:sqlite:C:\\sqlitedb\\repo.db" />
            <property name="openjpa.ConnectionDriverName" value="org.sqlite.JDBC" />
            <property name="openjpa.ConnectionUserName" value="" />
            <property name="openjpa.ConnectionPassword" value="" />
            <property name="openjpa.Log" value="SQL=TRACE" />
        </properties>
    </persistence-unit>
</persistence>
</code>```

Thanks for the help! :)

答:
```<code>org.sqlite.JDBC
</code>```

You can download the driver here

Use code like this:

```<code>Class.forName("org.sqlite.JDBC"); // This doesn't actually do anything useful, it just asserts you can find the class
Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stat = conn.createStatement();
stat.executeQuery("select * from table");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I'm trying to create a simple JPA class using SQLite. I have everything set up then this shows up everytime I try to run main:
"A JDBC Driver or DataSource class name must be specified in the ConnectionDriverName property."
Is it because I have the wrong value for the sqlite driver name?
I can't seem to find out what the value of the property is for sqlite. Here is my persistence.xml:

    <?xml version="1.0"?>
<persistence>
    <persistence-unit name="testjpa" transaction-type="RESOURCE_LOCAL">
        <provider>
            org.apache.openjpa.persistence.PersistenceProviderImpl
        </provider>
        <class>entity.Discography</class>
        <properties>
            <property name="openjpa.ConnectionURL" value="jdbc:sqlite:C:\\sqlitedb\\repo.db" />
            <property name="openjpa.ConnectionDriverName" value="org.sqlite.JDBC" />
            <property name="openjpa.ConnectionUserName" value="" />
            <property name="openjpa.ConnectionPassword" value="" />
            <property name="openjpa.Log" value="SQL=TRACE" />
        </properties>
    </persistence-unit>
</persistence>

Thanks for the help! :)

Body:
org.sqlite.JDBC

You can download the driver here

Use code like this:

Class.forName("org.sqlite.JDBC"); // This doesn't actually do anything useful, it just asserts you can find the class
Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stat = conn.createStatement();
stat.executeQuery("select * from table");


问:
Take value from paragraph in repeater with C#
I have this Asp code:

```<code><asp:Repeater id="repCustomers" runat="server" OnItemDataBound="repCustomers_ItemDataBound">
 <p class="casualRight" runat="server" id="pCompanyValue" >
  <%# string.Format("{0:N}",((System.Data.DataRowView)Container.DataItem)["Value"]) %>
 </p>
</asp:Repeater>

<tr>
 <td class="CellNameButton">
  <asp:Button runat="server"  ID="btnValue" Text="Value > 0" OnClick="btnConfirm_Click" />
 </td>
</tr>
</code>```

And this C# code:

```<code>protected void btnConfirm_Click(object sender, EventArgs e) {
            // Customers and popup
            var isChecked = ((CheckBox)sender).Checked;
            foreach (RepeaterItem item in repCustomers.Items) {
                // Checking the item is a data item
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) {
                    HtmlGenericControl pVal = item.FindControl("pCompanyValuer") as HtmlGenericControl;
                    string pvall = pVal.InnerText;
                    if (pvall?.Length == 0) {
                        var chkbox = item.FindControl("chkCustomer") as CheckBox;
                        chkbox.Checked = isChecked;
                    }
                }
            }
        }
</code>```

When I click on the button, I want to check my checkboxes only for those that have no value. I did this C# code but it doesn't work. I don't know where I'm wrong. Can anyone explain to me where I am wrong?
Example of how it looks

答:
If the button is inside of that repeater? Then no need for looping.

Just do this to get the current repeater row:

```<code>       // demo how to get clicked row.
        Button cmdRow = sender as Button;
        RepeaterItem rRow = cmdRow.NamingContainer as RepeaterItem;

        Debug.WriteLine("Row clicked on = " + rRow.ItemIndex);
        Debug.WriteLine("Hotel Name from repeater = " + ((TextBox) rRow.FindControl("HotelName")).Text );

     var chkbox = item.FindControl("chkCustomer") as CheckBox;
     chkbox.Checked = isChecked;
</code>```

So, you have the button click (sender). From that you get repeater row as per above. And from that you can use find control to get any control FROM the given row.

I am going on the assumption that you left out controls you have inside of the repeater - such as the check boxes. Give the above idea a try - so, you don't need a loop to get the current row click, just use "naming container".

Body:
I have this Asp code:

<asp:Repeater id="repCustomers" runat="server" OnItemDataBound="repCustomers_ItemDataBound">

  <%# string.Format("{0:N}",((System.Data.DataRowView)Container.DataItem)["Value"]) %>

</asp:Repeater>

  <asp:Button runat="server"  ID="btnValue" Text="Value > 0" OnClick="btnConfirm_Click" />

And this C# code:

protected void btnConfirm_Click(object sender, EventArgs e) {
            // Customers and popup
            var isChecked = ((CheckBox)sender).Checked;
            foreach (RepeaterItem item in repCustomers.Items) {
                // Checking the item is a data item
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) {
                    HtmlGenericControl pVal = item.FindControl("pCompanyValuer") as HtmlGenericControl;
                    string pvall = pVal.InnerText;
                    if (pvall?.Length == 0) {
                        var chkbox = item.FindControl("chkCustomer") as CheckBox;
                        chkbox.Checked = isChecked;
                    }
                }
            }
        }

When I click on the button, I want to check my checkboxes only for those that have no value. I did this C# code but it doesn't work. I don't know where I'm wrong. Can anyone explain to me where I am wrong?
Example of how it looks

Body:
If the button is inside of that repeater? Then no need for looping.

Just do this to get the current repeater row:

       // demo how to get clicked row.
        Button cmdRow = sender as Button;
        RepeaterItem rRow = cmdRow.NamingContainer as RepeaterItem;

        Debug.WriteLine("Row clicked on = " + rRow.ItemIndex);
        Debug.WriteLine("Hotel Name from repeater = " + ((TextBox) rRow.FindControl("HotelName")).Text );

     var chkbox = item.FindControl("chkCustomer") as CheckBox;
     chkbox.Checked = isChecked;

So, you have the button click (sender). From that you get repeater row as per above. And from that you can use find control to get any control FROM the given row.

I am going on the assumption that you left out controls you have inside of the repeater - such as the check boxes. Give the above idea a try - so, you don't need a loop to get the current row click, just use "naming container".


问:
What logic determines the insert order of Entity Framework 6
So, I have a DBContext, and I am doing the following operations:

```<code>dbContext.SomeTables1.Add(object1)
dbContext.SomeTables2.AddRange(objectArray2)
dbContext.SomeTables3.AddRange(objectArray3)
dbContext.SaveChanges();
</code>```

The EF doesn't insert the db records in this order, it inserts them in a random order. To insert them in the same order, I have to do a dbContext.SaveChanges() after each addition. This is not an efficient solution and in my case, it is taking 10 seconds to do all my inserts, while the random order with one save takes around 3 seconds.

N.B. I need the right order to solve a deadlock issue.

My questions are:

Is this issue resolved in EF7?

I can profile EF and determine the random order, however, is there a guarantee that it will be consistently with the same random order or
  does it change between requests? (I can adopt my other code if the
  answer to this question is positive).

Is there a better way of maintaining the order than dbContext.SaveChanges() on every addition?

答:
I've found a very simple solution.

Just set the property for the ID (primary key) of the entity to a value that matches your desired order.
SaveChanges() first sorts by this ID, then by other properties.
The assigned ID may already exist in the database. A unique ID is assigned when writing to the database.

```<code>for(int i = 0; i < objectArray2.Count(); i++)
{
   objectArray2[i].Id = i;
}

dbContext.SomeTables2.AddRange(objectArray2)
</code>```

Body:
So, I have a DBContext, and I am doing the following operations:

dbContext.SomeTables1.Add(object1)
dbContext.SomeTables2.AddRange(objectArray2)
dbContext.SomeTables3.AddRange(objectArray3)
dbContext.SaveChanges();

The EF doesn't insert the db records in this order, it inserts them in a random order. To insert them in the same order, I have to do a dbContext.SaveChanges() after each addition. This is not an efficient solution and in my case, it is taking 10 seconds to do all my inserts, while the random order with one save takes around 3 seconds.

N.B. I need the right order to solve a deadlock issue.

My questions are:

Is this issue resolved in EF7?

I can profile EF and determine the random order, however, is there a guarantee that it will be consistently with the same random order or
  does it change between requests? (I can adopt my other code if the
  answer to this question is positive).

Is there a better way of maintaining the order than dbContext.SaveChanges() on every addition?

Body:
I've found a very simple solution.

Just set the property for the ID (primary key) of the entity to a value that matches your desired order.
SaveChanges() first sorts by this ID, then by other properties.
The assigned ID may already exist in the database. A unique ID is assigned when writing to the database.

for(int i = 0; i < objectArray2.Count(); i++)
{
   objectArray2[i].Id = i;
}

dbContext.SomeTables2.AddRange(objectArray2)


问:
How to insert accented characters in ASCII-encoded Rd files?
Can LaTeX escapes for accents be used in Rd files? I tried the standard \'e and many variants (\'{e}, {\'e}, \\'e, \\'{e}, {\\'e}, etc.), but none is rendered as an accented character in the PDF or HTML output.

I want my References section (i.e. \references{}) to be rendered with accented characters, but I do not want to type non-ASCII characters in my Rd files. Is there good/recommended practice? Should I simply replace non-ASCII characters with their ASCII equivalents (é → e, ø → o)?

To be clear, I know it is possible to type accented characters (e.g., é) directly in UTF-8-encoded files, but I would prefer to keep ASCII-encoded files.

This question is not about:

how to type special/accented letters in LaTeX

how to use UTF-8 in LaTeX

accents/special characters in R Markdown

or variants.

Minimal test package

Package structure:

test
test/man
test/man/one.Rd
test/R
test/R/one.R
test/DESCRIPTION
```
<p><code>test/man/one.Rd</code>:</p>
<pre class="lang-tex prettyprint-override"><code>\name{one}
\alias{one}
\title{Get One}
\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
\usage{
one()
}
</code>```

test/R/one.R:

one <- function() 1
```
<p><code>test/DESCRIPTION</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>Package: test
Version: 0.1
Title: Test
Author: Nobody
Maintainer: Nobody <no@body.org>
Description: Test.
License: GPL-3
</code>```

Build, check, and install with:

$ R CMD build test
$ R CMD check test_0.1.tar.gz
$ R CMD INSTALL test_0.1.tar.gz
```

答:
Using math mode it works. Not sure 100% if this is what you are looking for.

Here are some examples:

```<code>  \'{e} {\'e} \\'e \\'{e} {\\'e}

$\acute{e}$

$\grave{e}$

$\tilde{e}$

</code>```

PDF output:

```<code>’{e} {’e} \‘e \’{e} {\’e}
é
è
ẽ
</code>```

Update:

```<code>\newcommand\latexcode[1]{#1}

\latexcode{\'{a}}

Thoma\latexcode{\'{s}}
</code>```

That works Thomas !

Body:
Can LaTeX escapes for accents be used in Rd files? I tried the standard \'e and many variants (\'{e}, {\'e}, \\'e, \\'{e}, {\\'e}, etc.), but none is rendered as an accented character in the PDF or HTML output.

I want my References section (i.e. \references{}) to be rendered with accented characters, but I do not want to type non-ASCII characters in my Rd files. Is there good/recommended practice? Should I simply replace non-ASCII characters with their ASCII equivalents (é → e, ø → o)?

To be clear, I know it is possible to type accented characters (e.g., é) directly in UTF-8-encoded files, but I would prefer to keep ASCII-encoded files.

This question is not about:

how to type special/accented letters in LaTeX

how to use UTF-8 in LaTeX

accents/special characters in R Markdown

or variants.

Minimal test package

Package structure:

test
test/man
test/man/one.Rd
test/R
test/R/one.R
test/DESCRIPTION

test/man/one.Rd:

\name{one}
\alias{one}
\title{Get One}
\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
\usage{
one()
}

test/R/one.R:

one <- function() 1

test/DESCRIPTION:

Package: test
Version: 0.1
Title: Test
Author: Nobody
Maintainer: Nobody <no@body.org>
Description: Test.
License: GPL-3

Build, check, and install with:

$ R CMD build test
$ R CMD check test_0.1.tar.gz
$ R CMD INSTALL test_0.1.tar.gz

Body:
Using math mode it works. Not sure 100% if this is what you are looking for.

Here are some examples:

  \'{e} {\'e} \\'e \\'{e} {\\'e}

$\acute{e}$

$\grave{e}$

$\tilde{e}$

PDF output:

’{e} {’e} \‘e \’{e} {\’e}
é
è
ẽ

Update:

\newcommand\latexcode[1]{#1}

\latexcode{\'{a}}

Thoma\latexcode{\'{s}}

That works Thomas !


问:
Login Form text boxes won't disappear
I've created this simple Login form for a uni project and for some reason the box around the text field is still showing, I want it to be invisible.
How the form works is; when a user clicks on either field, the placeholder lifts up and they type below it (refer to screenshot)
For some reason, however, the text box is still there.
Any help would be greatly appreciated.

.center {
      position:fixed;
      top: 40%;
      left: 70%;
      transform: translate(-50%, -50%);
      width: 720px;
      height: 350px;
      background: linear-gradient(180deg, white, silver );
      size: 100%;
      border-style: solid;
      border-color: black;
      border-width: 1px;

    }

    .center h1{
      text-align: center;
      padding: 0 0 20px 0;
      border-bottom: 1px solid silver;
    }

    .center form {
        padding: 0 40px;
    }

    form .txt_field {
    position: relative;
    border-bottom: 2px solid #adadad;
    margin: 30px 0;
    }

    .txt-field input {
     width: 100%;
     padding: 0 5px;
     height: 40px;
     font-size: 16px;
     border: none;
     background: none;
     outline: none;
    }

    .no-outlin:focus{
      outline: none;
    }

    .txt_field label{
      position: absolute;
      top: 50%;
      left: 5px;
      color: #adadad;
      transform: translateY(-50%);
      font-size: 16px;
      pointer-events: none;
      transition: .7s;
      border: none;
    }

    .txt_field span::before{
      content: '';
      position: absolute;
      top: 40px;
      left: 0;
      width: 0%;
      height: 2px;
      background: #2691d9;
      transition: .7s;
    }

    .txt_field input:focus ~ label,
    .txt_field input:valid ~ label {
      top: -5px;
      color: #2691d9;
    }

    .txt_field input:focus ~ span::before,
    .txt_field input:valid ~ span::before {
      width: 100%;
    }

    .pass {
      margin: -5px 0 20px 5px;
      color: #a6a6a6;
      cursor: pointer;
    }

    .pass:hover {
      text-decoration: underline;
    }

    input[type="submit"]{
      width: 100%;
      height: 50px;
      border: 1px solid;
      background: #2691d9;
      border-radius: 25px;
      font-size: 18px;
      color: #e9f4fb;
      font-weight: 700;
      cursor: pointer;
      outline: none;
    }

    input[type="submit"]:hover{
      border-color: #2691d9;
      transition: .5s;
    }

    .signup_link {
      margin: 30px;
      text-align: center;
      font-size: 16px;
      color: #666666;
    }

    .signup_link a{
      color: #2691d9;
      text-decoration: none;
    }

    .signup_link a:hover{
      color: #2691d9;
      text-decoration: underline;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>

    </head>
    <body class="Body">

      <div class="center">
        <h1> Login </h1>
        <form method="post" class="Box">
         <div class="txt_field">
           <input  type="text" required>
           <span></span>
           <label>Username</label>
      </div>
      <div class="txt_field">
        <input type="password" required>
        <span></span>
        <label>Password</label>
    </div>
    <div class="pass"> Forgotten Password? </div>
    <input type="submit" value="Login">
    <div class="signup_link">
      Not a Member? Create an Account!
    </div>

    </form>
    </div></code>```

Click here for sceenshot

答:
target the input not thee div

.center {
  position: fixed;
  top: 40%;
  left: 70%;
  transform: translate(-50%, -50%);
  width: 720px;
  height: 350px;
  background: linear-gradient(180deg, white, silver);
  size: 100%;
  border-style: solid;
  border-color: black;
  border-width: 1px;
}

.center h1 {
  text-align: center;
  padding: 0 0 20px 0;
  border-bottom: 1px solid silver;
}

.center form {
  padding: 0 40px;
}

form .txt_field {
  position: relative;
  border-bottom: 2px solid #adadad;
  margin: 30px 0;
}

.txt_field input:focus {
  outline: none;
}

.no-outlin:focus {
  outline: none;
}

.txt_field label {
  position: absolute;
  top: 50%;
  left: 5px;
  color: #adadad;
  transform: translateY(-50%);
  font-size: 16px;
  pointer-events: none;
  transition: .7s;
  border: none;
}

.txt_field span::before {
  content: '';
  position: absolute;
  top: 40px;
  left: 0;
  width: 0%;
  height: 2px;
  background: #2691d9;
  transition: .7s;
}

.txt_field input:focus~label,
.txt_field input:valid~label {
  top: -5px;
  color: #2691d9;
}

.txt_field input:focus~span::before,
.txt_field input:valid~span::before {
  width: 100%;
}

.pass {
  margin: -5px 0 20px 5px;
  color: #a6a6a6;
  cursor: pointer;
}

.pass:hover {
  text-decoration: underline;
}

input[type="submit"] {
  width: 100%;
  height: 50px;
  border: 1px solid;
  background: #2691d9;
  border-radius: 25px;
  font-size: 18px;
  color: #e9f4fb;
  font-weight: 700;
  cursor: pointer;
  outline: none;
}

input[type="submit"]:hover {
  border-color: #2691d9;
  transition: .5s;
}

.signup_link {
  margin: 30px;
  text-align: center;
  font-size: 16px;
  color: #666666;
}

.signup_link a {
  color: #2691d9;
  text-decoration: none;
}

.signup_link a:hover {
  color: #2691d9;
  text-decoration: underline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>

</head>

<body class="Body">

  <div class="center">
    <h1> Login </h1>
    <form method="post" class="Box">
      <div class="txt_field">
        <input type="text" required>
        <span></span>
        <label>Username</label>
      </div>
      <div class="txt_field">
        <input type="password" required>
        <span></span>
        <label>Password</label>
      </div>
      <div class="pass"> Forgotten Password? </div>
      <input type="submit" value="Login">
      <div class="signup_link">
        Not a Member? Create an Account!
      </div>

    </form>
  </div></code>```

Title: Login Form text boxes won't disappear

Body:
I've created this simple Login form for a uni project and for some reason the box around the text field is still showing, I want it to be invisible.
How the form works is; when a user clicks on either field, the placeholder lifts up and they type below it (refer to screenshot)
For some reason, however, the text box is still there.
Any help would be greatly appreciated.

.center {
      position:fixed;
      top: 40%;
      left: 70%;
      transform: translate(-50%, -50%);
      width: 720px;
      height: 350px;
      background: linear-gradient(180deg, white, silver );
      size: 100%;
      border-style: solid;
      border-color: black;
      border-width: 1px;

    }

    .center h1{
      text-align: center;
      padding: 0 0 20px 0;
      border-bottom: 1px solid silver;
    }

    .center form {
        padding: 0 40px;
    }

    form .txt_field {
    position: relative;
    border-bottom: 2px solid #adadad;
    margin: 30px 0;
    }

    .txt-field input {
     width: 100%;
     padding: 0 5px;
     height: 40px;
     font-size: 16px;
     border: none;
     background: none;
     outline: none;
    }

    .no-outlin:focus{
      outline: none;
    }

    .txt_field label{
      position: absolute;
      top: 50%;
      left: 5px;
      color: #adadad;
      transform: translateY(-50%);
      font-size: 16px;
      pointer-events: none;
      transition: .7s;
      border: none;
    }

    .txt_field span::before{
      content: '';
      position: absolute;
      top: 40px;
      left: 0;
      width: 0%;
      height: 2px;
      background: #2691d9;
      transition: .7s;
    }

    .txt_field input:focus ~ label,
    .txt_field input:valid ~ label {
      top: -5px;
      color: #2691d9;
    }

    .txt_field input:focus ~ span::before,
    .txt_field input:valid ~ span::before {
      width: 100%;
    }

    .pass {
      margin: -5px 0 20px 5px;
      color: #a6a6a6;
      cursor: pointer;
    }

    .pass:hover {
      text-decoration: underline;
    }

    input[type="submit"]{
      width: 100%;
      height: 50px;
      border: 1px solid;
      background: #2691d9;
      border-radius: 25px;
      font-size: 18px;
      color: #e9f4fb;
      font-weight: 700;
      cursor: pointer;
      outline: none;
    }

    input[type="submit"]:hover{
      border-color: #2691d9;
      transition: .5s;
    }

    .signup_link {
      margin: 30px;
      text-align: center;
      font-size: 16px;
      color: #666666;
    }

    .signup_link a{
      color: #2691d9;
      text-decoration: none;
    }

    .signup_link a:hover{
      color: #2691d9;
      text-decoration: underline;
    }

 Login

        <form method="post" class="Box">

           <input  type="text" required>

           Username

        <input type="password" required>

        Password

 Forgotten Password?

    <input type="submit" value="Login">

      Not a Member? Create an Account!

    </form>

Click here for sceenshot

Body:
target the input not thee div

.center {
  position: fixed;
  top: 40%;
  left: 70%;
  transform: translate(-50%, -50%);
  width: 720px;
  height: 350px;
  background: linear-gradient(180deg, white, silver);
  size: 100%;
  border-style: solid;
  border-color: black;
  border-width: 1px;
}

.center h1 {
  text-align: center;
  padding: 0 0 20px 0;
  border-bottom: 1px solid silver;
}

.center form {
  padding: 0 40px;
}

form .txt_field {
  position: relative;
  border-bottom: 2px solid #adadad;
  margin: 30px 0;
}

.txt_field input:focus {
  outline: none;
}

.no-outlin:focus {
  outline: none;
}

.txt_field label {
  position: absolute;
  top: 50%;
  left: 5px;
  color: #adadad;
  transform: translateY(-50%);
  font-size: 16px;
  pointer-events: none;
  transition: .7s;
  border: none;
}

.txt_field span::before {
  content: '';
  position: absolute;
  top: 40px;
  left: 0;
  width: 0%;
  height: 2px;
  background: #2691d9;
  transition: .7s;
}

.txt_field input:focus~label,
.txt_field input:valid~label {
  top: -5px;
  color: #2691d9;
}

.txt_field input:focus~span::before,
.txt_field input:valid~span::before {
  width: 100%;
}

.pass {
  margin: -5px 0 20px 5px;
  color: #a6a6a6;
  cursor: pointer;
}

.pass:hover {
  text-decoration: underline;
}

input[type="submit"] {
  width: 100%;
  height: 50px;
  border: 1px solid;
  background: #2691d9;
  border-radius: 25px;
  font-size: 18px;
  color: #e9f4fb;
  font-weight: 700;
  cursor: pointer;
  outline: none;
}

input[type="submit"]:hover {
  border-color: #2691d9;
  transition: .5s;
}

.signup_link {
  margin: 30px;
  text-align: center;
  font-size: 16px;
  color: #666666;
}

.signup_link a {
  color: #2691d9;
  text-decoration: none;
}

.signup_link a:hover {
  color: #2691d9;
  text-decoration: underline;
}

<head>

</head>

<body class="Body">

  <div class="center">
    <h1> Login </h1>
    <form method="post" class="Box">
      <div class="txt_field">
        <input type="text" required>
        <span></span>
        <label>Username</label>
      </div>
      <div class="txt_field">
        <input type="password" required>
        <span></span>
        <label>Password</label>
      </div>
      <div class="pass"> Forgotten Password? </div>
      <input type="submit" value="Login">
      <div class="signup_link">
        Not a Member? <a class="nav-item-nav-link" routerLink="/register">Create an Account!</a>
      </div>

    </form>
  </div>


问:
How can I have an image anchor when I scroll through text?
I have a page on my site that has a lot of text on the right hand side, and I have an image on the left hand side. I want that image to stay with the user as they scroll through the text.</p>

答: Set the image's parent element to position:relative, then set the image's element to position:sticky and top:0.  The image will now 'stick' to it's location even if the user scrolls away from it.


问:
What is the difference between Docker Unix socket on ubuntu vs alpine?
I am running through a problem where I can't mount Unix docker socket to an alpine container but works with ubuntu container.

docker-compose using alpine image

version: '3.8'

services:
  cluster:
    image:  alpine
    tty: true
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"
      - "/usr/bin/docker:/usr/bin/docker"
```
<p>running docker command in the alpine container:</p>
<pre class="lang-sh prettyprint-override"><code>/ # docker --version
sh: docker: not found
</code>```

docker-compose using ubuntu image

version: '3.8'

services:
  cluster:
    image:  ubuntu:20.04
    tty: true
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"
      - "/usr/bin/docker:/usr/bin/docker"
```
<p>running docker command in the ubuntu container:</p>
<pre class="lang-sh prettyprint-override"><code>root@5f30b4143c43:/# docker --version
Docker version 20.10.12, build e91ed57
</code>```

I don't get why I can access my host docker env using the ubuntu container but not with the alpine one? is there anything missing in the configuration?

答:
Your error has nothing to do with the socket:

```<code>/ # docker --version
sh: docker: not found
</code>```

You're seeing this because you're trying to run a binary compiled for glibc platform, while Alpine is built using MUSL libc.

You would need to install a version of the docker client built specifically for use under Alpine (or just pick almost any other image).

Body:
I am running through a problem where I can't mount Unix docker socket to an alpine container but works with ubuntu container.

docker-compose using alpine image

version: '3.8'

services:
  cluster:
    image:  alpine
    tty: true
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"
      - "/usr/bin/docker:/usr/bin/docker"

running docker command in the alpine container:

/ # docker --version
sh: docker: not found

docker-compose using ubuntu image

version: '3.8'

services:
  cluster:
    image:  ubuntu:20.04
    tty: true
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"
      - "/usr/bin/docker:/usr/bin/docker"

running docker command in the ubuntu container:

root@5f30b4143c43:/# docker --version
Docker version 20.10.12, build e91ed57

I don't get why I can access my host docker env using the ubuntu container but not with the alpine one? is there anything missing in the configuration?

Body:
Your error has nothing to do with the socket:

/ # docker --version
sh: docker: not found

You're seeing this because you're trying to run a binary compiled for glibc platform, while Alpine is built using MUSL libc.

You would need to install a version of the docker client built specifically for use under Alpine (or just pick almost any other image).


问:
Sending parameter by docker-compose does not work on appsettings in .NET6
I have a docker-compose with environment variables for the ConnectionString :

```<code>services:
  nameservice:
  ...
  environment:
    ConnectionStrings__mysqlDatabase: "Server=db;Uid=root;Pwd=password;"
</code>```

I have on the .NET side in a console program, an AppSettings file (.NET6):

```<code>{
  "ConnectionStrings": {
    "mysqlDatabase": "Server=localhost;Uid=root;Pwd=password;"
  }
}
</code>```

and my program.cs :

```<code>IConfiguration Config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
ConnectionStringConstant.mysqlDatabase = Config.GetConnectionString("mysqlDatabase");
</code>```

my problem is that in docker after creating a container, it keeps the value in AppSettings (which is not good for production) and it does not take the value passed by the docker-compose file.

Can you help me?

答:
When building configuration manually (without using hosting) setup for environment variables support is required:

var configurationRoot = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .Build();
```

Read more:

Configuration in .NET

Body:
I have a docker-compose with environment variables for the ConnectionString :

services:
  nameservice:
  ...
  environment:
    ConnectionStrings__mysqlDatabase: "Server=db;Uid=root;Pwd=password;"

I have on the .NET side in a console program, an AppSettings file (.NET6):

{
  "ConnectionStrings": {
    "mysqlDatabase": "Server=localhost;Uid=root;Pwd=password;"
  }
}

and my program.cs :

IConfiguration Config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
ConnectionStringConstant.mysqlDatabase = Config.GetConnectionString("mysqlDatabase");

my problem is that in docker after creating a container, it keeps the value in AppSettings (which is not good for production) and it does not take the value passed by the docker-compose file.

Can you help me?

Body:
When building configuration manually (without using hosting) setup for environment variables support is required:

var configurationRoot = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .Build();

Read more:

Configuration in .NET


问:
Scan an int after a letter
I'm building a program and I encounter a small problem and I can't find a solution to it.
So my goal is to scan a certain letter and when that happens, I just get the number in front of it. Here's the code:

#include <stdio.h>

int main(){

    int pag = 1;
    char *op = malloc(sizeof(char));
    char* opt = malloc(sizeof(char));

    printf("P      -> Next\n");
    printf("A      -> Back\n");
    printf("S <N>  -> Jump to N\n");
    printf("B      -> Sair\n");
    printf("\n");

    printf("Insert option: ");
    fgets(op, 4, stdin);

    if(op[0] == 'S'){

        opt = strsep(&op, " ");

        pag = atoi(op);
    }

    printf("Page: %d\n", pag);

    free(op);
    free(opt);
}
```

When I execute the program and I chose the option "S 5" for example, my goal is to get the "5". The problem is when I chose a number with more than 2 digits, for example, "S 12" gives me the number "1", not the number 12, I don't know if the problem is with the memory allocation or something else.

答:
First:

```<code>char *op = malloc(sizeof(char));
char* opt = malloc(sizeof(char));
</code>```

won't allocate more than 1 byte for storage of your input string.

```<code>fgets(op, 4, stdin);
</code>```

wont read enough characters for the following string "S 12" as the length parameter value includes the string null terminator.

Try:

```<code>const int length= 5;
char *op = malloc(length);
char* opt = malloc(length);
</code>```

and

```<code>fgets(op, length, stdin);
</code>```

Title: Scan an int after a letter

Body:
I'm building a program and I encounter a small problem and I can't find a solution to it.
So my goal is to scan a certain letter and when that happens, I just get the number in front of it. Here's the code:

#include <stdio.h>

int main(){

    int pag = 1;
    char *op = malloc(sizeof(char));
    char* opt = malloc(sizeof(char));

    printf("P      -> Next\n");
    printf("A      -> Back\n");
    printf("S <N>  -> Jump to N\n");
    printf("B      -> Sair\n");
    printf("\n");

    printf("Insert option: ");
    fgets(op, 4, stdin);

    if(op[0] == 'S'){

        opt = strsep(&op, " ");

        pag = atoi(op);
    }

    printf("Page: %d\n", pag);

    free(op);
    free(opt);
}

When I execute the program and I chose the option "S 5" for example, my goal is to get the "5". The problem is when I chose a number with more than 2 digits, for example, "S 12" gives me the number "1", not the number 12, I don't know if the problem is with the memory allocation or something else.

Body:
First:

char *op = malloc(sizeof(char));
char* opt = malloc(sizeof(char));

won't allocate more than 1 byte for storage of your input string.

fgets(op, 4, stdin);

wont read enough characters for the following string "S 12" as the length parameter value includes the string null terminator.

Try:

const int length= 5;
char *op = malloc(length);
char* opt = malloc(length);

and

fgets(op, length, stdin);


问:
Babel incorrect transformation of spread
Babel incorrectly converting/transpiling the following code

const arr = [...new Set([1, 2, 3, 1])]
```
<p>into</p>
<pre class="lang-js prettyprint-override"><code>var arr = [].concat(new Set([1, 2, 3, 1]))
</code>```

The first returns a list of numbers, whereas the other returns a list of set(s)

Is this a Babel bug?

Using @babel/plugin-transform-spread@7.14.6 and @babel/plugin-transform-destructuring@7.14.7

答:
This looks like it’s related to babel/babel#9108 Correctly transform spreads to use proper concat method, which was merged in v7.2.2.

As mentioned in smashercosmo’s comment on the PR…

One bad thing about this PR is that before it if somebody tried to spread Set in loose mode, clear error was thrown, but now he will get wrong output of [Set()], which will be harder to spot.

I think this is exactly what you’re seeing here.  It might be because your Babel config has loose set to true, maybe, but I’m not sure.

A potential workaround would be to use Array.from:

const myArrayWithDupes = ['a', 'b', 'c', 'a'];

console.log([...new Set(myArrayWithDupes)]); // your original line
console.log([].concat(new Set(myArrayWithDupes))); // incorrect when `loose` is set to `true`
console.log(Array.from(new Set(myArrayWithDupes))); // a potential workaround```

Body:
Babel incorrectly converting/transpiling the following code

const arr = [...new Set([1, 2, 3, 1])]

into

var arr = [].concat(new Set([1, 2, 3, 1]))

The first returns a list of numbers, whereas the other returns a list of set(s)

Is this a Babel bug?

Using @babel/plugin-transform-spread@7.14.6 and @babel/plugin-transform-destructuring@7.14.7


问:
Why does Apache on Ubuntu show blank for unknown file extension ... even with DefaultType text/plain?
I have installed Apache in a VM environment for both CentOS and Ubuntu.  In both environments, the Apache configuration variable DefaultType is set to text/plain.

If I have a file with an unknown extension - say, dummy.xxx, containing just a few random characters, located in the document root folder, and I type localhost/dummy.xxx into firefox, then on CentOS, the random characters appear in the browser output.  However, on Ubuntu, they do not - an empty page appears (even when you 'view source').  (Note that regular .htm files do appear properly on Ubuntu.)

This issue may be relevant to an unrelated problem I'm having that I am not discussing here (for simplicity, and to save time) - so this question is not just for interest's sake.

I know this is a short question - if any other details are necessary, such as the version of the various software components, please do ask and I'll dig that information up.  Thanks.

答:
Have you looked at the actual headers coming back from the server to see if they include a Content-Type: header?   If you do have a Content-Type: header, and it is set to text/plain, then your problem is client-side, not server side.

Also, double-check your mime.types file.  Any matching entry in mime.types will override the apache.conf's DefaultType setting.


问:
Getting 403/Forbidden Response from BIM360 and Construction Cloud Assets Endpoints
I'm attempting to run a GET request against a BIM360 project's assets endpoint. Would someone please advise if this is a bug or if I'm missing something?

Though my auth token is working for just about any other endpoint I've tried (hubs, projects, top folders, and folder), I keep getting a 403 response from the server:

```<code>{
  "title": "Forbidden",
  "detail": "Forbidden",
  "errorCode": "GENERAL_ERROR",
  "type": "https://developer.api.autodesk.com/bim360/assets/v1/error-codes/GENERAL_ERROR"
}
</code>```

The request that produced this:

```<code>curl --request GET \
  --url https://developer.api.autodesk.com/bim360/assets/v2/projects/{project_id}/assets \
  --header 'Authorization: Bearer eyJ...'
</code>```

My app is registered in the account admin page, and the account I'm auth'd with here is an admin. My app also has BIM360 and Construction Cloud selected:

Thank you.

答:
I found the issue - the project I was querying didn't have Assets enabled within the Project Admin. Once I enabled Assets, I was able to hit the endpoint successfully. If anyone else is looking at this issue in the future, follow these steps to enable Assets.

May I offer a couple of feedback requests for the AD team to consider?

Update the error message to explain what's actually happening. The Forbidden code is a little misleading here. Responders to the question and I thought this was an issue with the token/user/etc when really it wasn't.

Mention the requirement that Assets should be enabled in the Before You Begin sections of the assets tutorials and/or the assets endpoint docs.

Body:
I'm attempting to run a GET request against a BIM360 project's assets endpoint. Would someone please advise if this is a bug or if I'm missing something?

Though my auth token is working for just about any other endpoint I've tried (hubs, projects, top folders, and folder), I keep getting a 403 response from the server:

{
  "title": "Forbidden",
  "detail": "Forbidden",
  "errorCode": "GENERAL_ERROR",
  "type": "https://developer.api.autodesk.com/bim360/assets/v1/error-codes/GENERAL_ERROR"
}

The request that produced this:

curl --request GET \
  --url https://developer.api.autodesk.com/bim360/assets/v2/projects/{project_id}/assets \
  --header 'Authorization: Bearer eyJ...'

My app is registered in the account admin page, and the account I'm auth'd with here is an admin. My app also has BIM360 and Construction Cloud selected:

Thank you.


问:
How to display loading message during the execution of my function?
Some functions take a long time to execute. I want to make the user wait with a progress bar.
Unfortunately, when I run this one, it runs but only at the end of my function and not when I would like.
Let me explain, I launch my progress bar with the "sendloading()" method but during my tests this bar is only displayed after the processing of the other functions "copyAssets" or "createOnClicBtnInsert()".
Can someone explain to me why?

Here is my code :

```<code> @Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    view.findViewById(R.id.btnInsertDataset2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!hasPermissions(getContext(),Permissions)){
                lay_dataset2 = view.findViewById(R.id.lay_dataset2);
                messagePerm();
            }else {
                sendLoading(); //MY PROGRESS BAR
                btnInsert = view.findViewById(R.id.btnInsertDataset2);
                /** if perm ok -> insert*/
                copyAssets();
                createOnClicBtnInsert();
                view.findViewById(R.id.btnDeleteDataset2).setEnabled(true);
                Toast.makeText(getContext(), "Insert Success", Toast.LENGTH_SHORT).show();
            }

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

Here is my code for the progress bar :

```<code>    public void sendLoading() {
    int llPadding = 30;
    LinearLayout ll = new LinearLayout(getContext());
    ll.setOrientation(LinearLayout.HORIZONTAL);
    ll.setPadding(llPadding, llPadding, llPadding, llPadding);
    ll.setGravity(Gravity.CENTER);
    LinearLayout.LayoutParams llParam = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    llParam.gravity = Gravity.CENTER;
    ll.setLayoutParams(llParam);

    ProgressBar progressBar = new ProgressBar(getContext());
    progressBar.setIndeterminate(true);
    progressBar.setPadding(0, 0, llPadding, 0);
    progressBar.setLayoutParams(llParam);

    llParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    llParam.gravity = Gravity.CENTER;
    TextView tvText = new TextView(getContext());
    tvText.setText("Loading ...");
    tvText.setTextColor(Color.parseColor("#000000"));
    tvText.setTextSize(20);
    tvText.setLayoutParams(llParam);

    ll.addView(progressBar);
    ll.addView(tvText);

    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setCancelable(true);
    builder.setView(ll);

    AlertDialog dialog = builder.create();
    dialog.show();
    Window window = dialog.getWindow();
    if (window != null) {
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.copyFrom(dialog.getWindow().getAttributes());
        layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
        layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(layoutParams);
    }

}
</code>```

答:
Android is an event driven OS that runs on a single main thread.  Drawing is an event.  That means in order to draw the main thread needs to return to the event loop.  Your code does not return to the event loop until after you do all your processing.  Thus it won't draw until after the processing is done.

The way to solve this is to use either a Thread or a Kotlin coroutine to do the processing, and allow the main thread to return to the event loop.  BTW, if you have long lasting processing you should not be doing it on the main thread anyway-  it freezes your UI and makes your app appear non responsive, for the same reason.  The main thread should do short quick calculations and respond to OS events only.

Body:
Some functions take a long time to execute. I want to make the user wait with a progress bar.
Unfortunately, when I run this one, it runs but only at the end of my function and not when I would like.
Let me explain, I launch my progress bar with the "sendloading()" method but during my tests this bar is only displayed after the processing of the other functions "copyAssets" or "createOnClicBtnInsert()".
Can someone explain to me why?

Here is my code :

 @Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    view.findViewById(R.id.btnInsertDataset2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!hasPermissions(getContext(),Permissions)){
                lay_dataset2 = view.findViewById(R.id.lay_dataset2);
                messagePerm();
            }else {
                sendLoading(); //MY PROGRESS BAR
                btnInsert = view.findViewById(R.id.btnInsertDataset2);
                /** if perm ok -> insert*/
                copyAssets();
                createOnClicBtnInsert();
                view.findViewById(R.id.btnDeleteDataset2).setEnabled(true);
                Toast.makeText(getContext(), "Insert Success", Toast.LENGTH_SHORT).show();
            }

        }
    });
}

Here is my code for the progress bar :

    public void sendLoading() {
    int llPadding = 30;
    LinearLayout ll = new LinearLayout(getContext());
    ll.setOrientation(LinearLayout.HORIZONTAL);
    ll.setPadding(llPadding, llPadding, llPadding, llPadding);
    ll.setGravity(Gravity.CENTER);
    LinearLayout.LayoutParams llParam = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    llParam.gravity = Gravity.CENTER;
    ll.setLayoutParams(llParam);

    ProgressBar progressBar = new ProgressBar(getContext());
    progressBar.setIndeterminate(true);
    progressBar.setPadding(0, 0, llPadding, 0);
    progressBar.setLayoutParams(llParam);

    llParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    llParam.gravity = Gravity.CENTER;
    TextView tvText = new TextView(getContext());
    tvText.setText("Loading ...");
    tvText.setTextColor(Color.parseColor("#000000"));
    tvText.setTextSize(20);
    tvText.setLayoutParams(llParam);

    ll.addView(progressBar);
    ll.addView(tvText);

    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setCancelable(true);
    builder.setView(ll);

    AlertDialog dialog = builder.create();
    dialog.show();
    Window window = dialog.getWindow();
    if (window != null) {
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.copyFrom(dialog.getWindow().getAttributes());
        layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
        layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(layoutParams);
    }

}


问:
How to make tsyringe (dep injection lib) resolve classes that have dependencies?
I am clearly misunderstanding how TSyringe is supposed to resolve classes with dependencies.

I created a minimal repro. In my index.tsx, I do as they indicate in the docs and import reflect-metadata. This example works if I inject a singleton class with no dependencies:

```<code>// index.tsx
import "reflect-metadata";
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(<App />,  document.getElementById('root'));
</code>```

A single singleton class:

```<code>// _A.ts
import {inject, singleton} from 'tsyringe';

@singleton()
export class A {
    get_msg() {
        return "Worked!";
    }
}
</code>```

And the component that uses it:

```<code>// App.tsx
import React from 'react';
import './App.css';
import {container} from "tsyringe";
import {A} from "./_A";

interface Props {
  a?: A
}

function App({a = container.resolve(A)}: Props) {
  return (
    <div className="App">
          {a.get_msg()}
    </div>
  );
}

export default App;
</code>```

When I run the app, the Worked! text is printed as expected.

However, if I create a second singleton called B:

```<code>// _B.ts
import {singleton} from 'tsyringe';

@singleton()
export class B {
    get_msg() {
        return "Worked!";
    }
}
</code>```

And then inject B into A to get the message:

```<code>// _A.ts
import {inject, singleton} from 'tsyringe';
import {B} from "./_B";

@singleton()
export class _A {
    constructor(private b: B) {
    }

    get_msg() {
        return this.b.get_msg();
    }
}
</code>```

Then it fails with Uncaught Error: TypeInfo not known for "A"

I have:

```<code>"experimentalDecorators": true,
"emitDecoratorMetadata": true,
</code>```

on my tsconfig.ts, as they indicate in the README.

Shouldn't Syringe resolve B automatically, inject B into A and then inject A into my app component so I can print the message?

What am I missing?

答:
OK so I figured this out.

To keep the typescript metadata and allow reflect-metadata to do its thing, we need to add babel-plugin-transform-typescript-metadata to the project.

However, in order to customize create-react-app, you need the craco library. There are several out there, but craco is the only one I could that supports CRA 4.x. You cannot be on the latest (CRA 5.0) as none of these libs support it yet.

So:

1 - Install Craco and set it up.

2 - Install babel-plugin-transform-typescript-metadata as a dev dependency

3 - Add a craco.config.js file to your project to load this plugin:

```<code>module.exports = function ({ env: _env }) {
    return {
        babel: {
            plugins: [
                "babel-plugin-transform-typescript-metadata"
            ]
        },
    };
};
</code>```

4 - Make sure to update your package.json to launch with craco so that the config override takes place:

```<code>  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "craco eject"
  },
</code>```

That's it, it will work now. Hope it helps someone out there.

Body:
I am clearly misunderstanding how TSyringe is supposed to resolve classes with dependencies.

I created a minimal repro. In my index.tsx, I do as they indicate in the docs and import reflect-metadata. This example works if I inject a singleton class with no dependencies:

// index.tsx
import "reflect-metadata";
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(<App />,  document.getElementById('root'));

A single singleton class:

// _A.ts
import {inject, singleton} from 'tsyringe';

@singleton()
export class A {
    get_msg() {
        return "Worked!";
    }
}

And the component that uses it:

// App.tsx
import React from 'react';
import './App.css';
import {container} from "tsyringe";
import {A} from "./_A";

interface Props {
  a?: A
}

function App({a = container.resolve(A)}: Props) {
  return (

          {a.get_msg()}

  );
}

export default App;

When I run the app, the Worked! text is printed as expected.

However, if I create a second singleton called B:

// _B.ts
import {singleton} from 'tsyringe';

@singleton()
export class B {
    get_msg() {
        return "Worked!";
    }
}

And then inject B into A to get the message:

// _A.ts
import {inject, singleton} from 'tsyringe';
import {B} from "./_B";

@singleton()
export class _A {
    constructor(private b: B) {
    }

    get_msg() {
        return this.b.get_msg();
    }
}

Then it fails with Uncaught Error: TypeInfo not known for "A"

I have:

"experimentalDecorators": true,
"emitDecoratorMetadata": true,

on my tsconfig.ts, as they indicate in the README.

Shouldn't Syringe resolve B automatically, inject B into A and then inject A into my app component so I can print the message?

What am I missing?

Body:
OK so I figured this out.

To keep the typescript metadata and allow reflect-metadata to do its thing, we need to add babel-plugin-transform-typescript-metadata to the project.

However, in order to customize create-react-app, you need the craco library. There are several out there, but craco is the only one I could that supports CRA 4.x. You cannot be on the latest (CRA 5.0) as none of these libs support it yet.

So:

1 - Install Craco and set it up.

2 - Install babel-plugin-transform-typescript-metadata as a dev dependency

3 - Add a craco.config.js file to your project to load this plugin:

module.exports = function ({ env: _env }) {
    return {
        babel: {
            plugins: [
                "babel-plugin-transform-typescript-metadata"
            ]
        },
    };
};

4 - Make sure to update your package.json to launch with craco so that the config override takes place:

  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "craco eject"
  },

That's it, it will work now. Hope it helps someone out there.


问:
How do you test the functionality of less CSS with Jest?
I've recently joined a new organisation and they use a lot of CSS to hide/show elements.

First of all, is this good practice? I have always (in most cases) shown and hidden components using a boolean to add or remove it from the dom (this is also easy to test)

Whilst trying to add tests using @testing-library/react I've found that the classes are visible by using the identity-obj-proxy module.

However, when trying to test the functionality of an element being visible or not, it becomes difficult because I don't think the less code is being compiled.

Is it possible to compile less code so it will be reflected in the tests?

Could it be something to do with the classnames module being used?

failing test

```<code>  it('should open and close when clicked', async () => {
    render(
      <Collapse
        label="Collapse"
        testId="collapse-test"
        isHidden
      >
        <div>
          <h1>just some demo text</h1>
        </div>
      </Collapse>
    )
    const content = screen.getByTestId('collapse-test-content')
    expect(content).not.toBeVisible()
    userEvent.click(screen.getByTestId('collapse-test-button'))
    await waitFor(() => expect(content).toBeVisible())
  })

====================result====================
expect(element).not.toBeVisible()

    Received element is visible:
      <div aria-expanded="false" class="accordionContent contentHidden" data-testid="collapse-test-content" />

      38 |     )
      39 |     const content = screen.getByTestId('collapse-test-content')
    > 40 |     expect(content).not.toBeVisible()
         |                         ^
      41 |     userEvent.click(screen.getByTestId('collapse-test-button'))
      42 |     await waitFor(() => expect(content).toBeVisible())
      43 |   })
</code>```

Component

```<code>import React, { useState } from 'react'
import cn from 'classnames'
import styles from './styles.less'

const AccordionContent = ({ children, hidden, testId }) => {
  const displayClass = hidden ? styles.contentHidden : styles.contentBlock

  const accordionContentClass = cn(styles.accordionContent, displayClass)
  return (
    <div
      className={ accordionContentClass }
      aria-expanded={ !hidden }
      data-testid={ `${testId}-content` }
    >
      {children}
    </div>
  )
}

const CollapseComponent= ({
  isHidden,
  onClick,
  label,
  children,
  testId
}) => {
  const [hidden, toggleHidden] = useState(isHidden)

  const handleOnpress = () => {
    toggleHidden((curr) => !curr)
    if (onClick) { onClick }
  }

  return (
    <div
      className={ styles.accordionWrapper }
      data-testid={ testId }
    >
      <AccordionButton
        onPress={ handleOnpress }
        buttonLabel={ label }
        testId={ testId }
      />
      <AccordionContent
        hidden={ !!hidden }
        testId={ testId }
      >
        {children}
      </AccordionContent>
    </div>
  )
}

</code>```

styles.less

```<code>.accordion-content {
  background-color: @preservica-gray-1;
  display: flex;
}

.content-hidden {
  display: none;
}

.content-block {
  display: flex;
}
</code>```

jest.config

```<code>const config = {
  testEnvironment: 'jsdom',
  coverageThreshold: {
    global: {
      statements: 80,
      branches: 75,
      functions: 75,
      lines: 80
    }
  },
  testPathIgnorePatterns: [
    "./src/components/atoms/Icons",
    "./src/models"
  ],
  coveragePathIgnorePatterns: [
    "./src/components/atoms/Icons",
    "./src/models"
  ],
  setupFilesAfterEnv: [
    "<rootDir>/src/setupTests.ts"
  ],
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
    "\\.(css|less)$": "identity-obj-proxy",
    "^@root(.*)$": "<rootDir>/src$1",
    "^common(.*)$": "<rootDir>/src/common$1",
    "^translation(.*)$": "<rootDir>/src/translation$1",
    "^view(.*)$": "<rootDir>/src/view$1",
    "^actions(.*)$": "<rootDir>/src/actions$1",
    "^usecases(.*)$": "<rootDir>/src/usecases$1",
    "^repository(.*)$": "<rootDir>/src/repository$1",
    "^models(.*)$": "<rootDir>/src/models$1",
    "^router(.*)$": "<rootDir>/src/router$1",
  },
  transform: {
    "^.+\\.(ts|tsx|js|jsx)$": "ts-jest",
  },
  snapshotSerializers: [
    "enzyme-to-json/serializer"
  ]
}
</code>```

答:
You can read more on how Jest handles mocking CSS modules in the Jest docs. You could perhaps write your own module name mapper or custom transform to load and process the Less files. However, you'd have to figure out how to actually inject the CSS into the code under test (that's something that Webpack normally handles). Something like jest-transform-css might do this.

Personally, I'd just test whether the CSS class is present, like @jonrsharpe suggests. Think of it from the perspective of the test pyramid: your Jest tests should likely be focused at the unit test level, with an emphasis on speed and simplicity. Unit tests are ideally fast enough that you can run them nearly instantly, whenever you save a file; adding the complexity to parse and insert Less CSS may work against that.

It's okay if the unit tests don't test the entire stack; you have other tests, higher up in the pyramid, to do this. For example, you could have a handful of Cypress tests that run your app in the actual browser and verify that a couple of controls are actually hidden, then it should be safe to assume that (1) Jest validating all controls set the correct class plus (2) Cypress validating that a few controls with the correct class are correctly hidden means that (3) all controls are correctly hidden.

To help make your tests more self-documenting, and to make them easier to maintain if you ever change how controls are shown and hidden, you can use Jest's expect.extend to make your own matcher. Perhaps something like this (untested):

expect.extend({
  toBeVisibleViaCss(received) {
    const pass = !received.classList.contains('content-hidden');
    const what = pass ? 'not visible' : 'visible';
    return {
      message: () => `expected ${received} to be ${what}`,
      pass,
    };
  },
});
```

First of all, is this good practice? I have always (in most cases) shown and hidden components using a boolean to add or remove it from the dom (this is also easy to test).

Hiding components via CSS is certainly not what I'm used to. Without knowing your codebase, I'd wonder if the developers were used to previous jQuery-style approaches of hiding via manipulating the class lists. The main advantage I'm aware of keeping components always rendered is that you can animate their transitions if you want to. I'm not sure how performance compares; the browser might find it faster to toggle a CSS class than to add or remove an element, but removing the element means that React has less to render, which could help performance.

Body:
I've recently joined a new organisation and they use a lot of CSS to hide/show elements.

First of all, is this good practice? I have always (in most cases) shown and hidden components using a boolean to add or remove it from the dom (this is also easy to test)

Whilst trying to add tests using @testing-library/react I've found that the classes are visible by using the identity-obj-proxy module.

However, when trying to test the functionality of an element being visible or not, it becomes difficult because I don't think the less code is being compiled.

Is it possible to compile less code so it will be reflected in the tests?

Could it be something to do with the classnames module being used?

failing test

  it('should open and close when clicked', async () => {
    render(
      <Collapse
        label="Collapse"
        testId="collapse-test"
        isHidden
      >

just some demo text

      </Collapse>
    )
    const content = screen.getByTestId('collapse-test-content')
    expect(content).not.toBeVisible()
    userEvent.click(screen.getByTestId('collapse-test-button'))
    await waitFor(() => expect(content).toBeVisible())
  })

====================result====================
expect(element).not.toBeVisible()

    Received element is visible:

      38 |     )
      39 |     const content = screen.getByTestId('collapse-test-content')
    > 40 |     expect(content).not.toBeVisible()
         |                         ^
      41 |     userEvent.click(screen.getByTestId('collapse-test-button'))
      42 |     await waitFor(() => expect(content).toBeVisible())
      43 |   })

Component

import React, { useState } from 'react'
import cn from 'classnames'
import styles from './styles.less'

const AccordionContent = ({ children, hidden, testId }) => {
  const displayClass = hidden ? styles.contentHidden : styles.contentBlock

  const accordionContentClass = cn(styles.accordionContent, displayClass)
  return (
    <div
      className={ accordionContentClass }
      aria-expanded={ !hidden }
      data-testid={ `${testId}-content` }
    >
      {children}

  )
}

const CollapseComponent= ({
  isHidden,
  onClick,
  label,
  children,
  testId
}) => {
  const [hidden, toggleHidden] = useState(isHidden)

  const handleOnpress = () => {
    toggleHidden((curr) => !curr)
    if (onClick) { onClick }
  }

  return (

      <AccordionButton
        onPress={ handleOnpress }
        buttonLabel={ label }
        testId={ testId }
      />
      <AccordionContent
        hidden={ !!hidden }
        testId={ testId }
      >
        {children}
      </AccordionContent>

  )
}

styles.less

.accordion-content {
  background-color: @preservica-gray-1;
  display: flex;
}

.content-hidden {
  display: none;
}

.content-block {
  display: flex;
}

jest.config

const config = {
  testEnvironment: 'jsdom',
  coverageThreshold: {
    global: {
      statements: 80,
      branches: 75,
      functions: 75,
      lines: 80
    }
  },
  testPathIgnorePatterns: [
    "./src/components/atoms/Icons",
    "./src/models"
  ],
  coveragePathIgnorePatterns: [
    "./src/components/atoms/Icons",
    "./src/models"
  ],
  setupFilesAfterEnv: [
    "<rootDir>/src/setupTests.ts"
  ],
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
    "\\.(css|less)$": "identity-obj-proxy",
    "^@root(.*)$": "<rootDir>/src$1",
    "^common(.*)$": "<rootDir>/src/common$1",
    "^translation(.*)$": "<rootDir>/src/translation$1",
    "^view(.*)$": "<rootDir>/src/view$1",
    "^actions(.*)$": "<rootDir>/src/actions$1",
    "^usecases(.*)$": "<rootDir>/src/usecases$1",
    "^repository(.*)$": "<rootDir>/src/repository$1",
    "^models(.*)$": "<rootDir>/src/models$1",
    "^router(.*)$": "<rootDir>/src/router$1",
  },
  transform: {
    "^.+\\.(ts|tsx|js|jsx)$": "ts-jest",
  },
  snapshotSerializers: [
    "enzyme-to-json/serializer"
  ]
}

Body:
You can read more on how Jest handles mocking CSS modules in the Jest docs. You could perhaps write your own module name mapper or custom transform to load and process the Less files. However, you'd have to figure out how to actually inject the CSS into the code under test (that's something that Webpack normally handles). Something like jest-transform-css might do this.

Personally, I'd just test whether the CSS class is present, like @jonrsharpe suggests. Think of it from the perspective of the test pyramid: your Jest tests should likely be focused at the unit test level, with an emphasis on speed and simplicity. Unit tests are ideally fast enough that you can run them nearly instantly, whenever you save a file; adding the complexity to parse and insert Less CSS may work against that.

It's okay if the unit tests don't test the entire stack; you have other tests, higher up in the pyramid, to do this. For example, you could have a handful of Cypress tests that run your app in the actual browser and verify that a couple of controls are actually hidden, then it should be safe to assume that (1) Jest validating all controls set the correct class plus (2) Cypress validating that a few controls with the correct class are correctly hidden means that (3) all controls are correctly hidden.

To help make your tests more self-documenting, and to make them easier to maintain if you ever change how controls are shown and hidden, you can use Jest's expect.extend to make your own matcher. Perhaps something like this (untested):

expect.extend({
  toBeVisibleViaCss(received) {
    const pass = !received.classList.contains('content-hidden');
    const what = pass ? 'not visible' : 'visible';
    return {
      message: () => `expected ${received} to be ${what}`,
      pass,
    };
  },
});

First of all, is this good practice? I have always (in most cases) shown and hidden components using a boolean to add or remove it from the dom (this is also easy to test).

Hiding components via CSS is certainly not what I'm used to. Without knowing your codebase, I'd wonder if the developers were used to previous jQuery-style approaches of hiding via manipulating the class lists. The main advantage I'm aware of keeping components always rendered is that you can animate their transitions if you want to. I'm not sure how performance compares; the browser might find it faster to toggle a CSS class than to add or remove an element, but removing the element means that React has less to render, which could help performance.


问:
How do I find out which UUID I should use to request data from my Polar H10 sensor?
I want to connect to my Polar H10 and read its Heart Rate (PPI) values. I am basically following this example Python code which reads Acceleration from the same device. I am however stuck in finding out which UUID I should use to request the Heart Rate data. The example uses a byte array of unknown origin (to me) to request the Acceleration data and I have no clue where I should retrieve the UUID for heart rate from. All I can find is this document, but it gives a, I believe hexidecimal, code which I cannot use. What do I do to get the right UUID? I'm new to this kind of sensor stuff so nothing seems obvious to me.

EDIT 1:

So these are the GATT characteristics on my device

This is the PMD measurement type I am trying to extract

And of that I want Byte0: Heart rate in bpm

What I am doing now (I'm not sure if you want all the code so I'm gonna post what seems relevant). In Python:

For setting the request for specific data (I think? this is what the example does with different data from the same sensor)

```<code>ECG_WRITE = bytearray([0x02, 0x00, 0x00, 0x01, 0x82, 0x00, 0x01, 0x01, 0x0E, 0x00])
</code>```

What I've tried to change ECG data to heart rate data is:

```<code>RR_UUID = "0000180D-0000-1000-8000-00805f9b34fb"
</code>```

But I feel like it isn't working because it isn't a byte array.

Then later on these lines are executed for actual data retrievement I think (again, I'm following a guide I'm not 100% sure what the code does)

```<code>
    att_read = await client.read_gatt_char(PMD_CONTROL)
    await client.write_gatt_char(PMD_CONTROL,  ECG_WRITE)

    ## ECG stream started
    await client.start_notify(PMD_DATA, data_conv)
</code>```

And from there on the data_conv method converts the data into usable data, and in this same method I can just print out the data and see it. However, since I don't know what I should enter as byte array to request the heart rate data, I haven't been able to get any data out of it yet. It also gives no errors/exceptions whatshowever so I am not sure what is going wrong.
So I am working from a Windows computer using Python code, and the target machine is a Polar H10 heart sensor.

答:
I've been trying to solve the same problem for some time now and finally got the hang of it.

The documentation is confusing as it leads one to think that the H10 sensor doesn't support HR and PPI readings. The reality, however, is that those measurements are of course supported by the sensor—just not through the PMD_DATA stream. The UUID for HR readings is:

```<code>HR_UUID = "00002A37-0000-1000-8000-00805F9B34FB"
</code>```

So when you start a client.notify(HR_UUID), you will get a 6 byte data stream, that follows the specifications given in the Polar Specification Document (see image below)

Body:
I want to connect to my Polar H10 and read its Heart Rate (PPI) values. I am basically following this example Python code which reads Acceleration from the same device. I am however stuck in finding out which UUID I should use to request the Heart Rate data. The example uses a byte array of unknown origin (to me) to request the Acceleration data and I have no clue where I should retrieve the UUID for heart rate from. All I can find is this document, but it gives a, I believe hexidecimal, code which I cannot use. What do I do to get the right UUID? I'm new to this kind of sensor stuff so nothing seems obvious to me.

EDIT 1:

So these are the GATT characteristics on my device

This is the PMD measurement type I am trying to extract

And of that I want Byte0: Heart rate in bpm

What I am doing now (I'm not sure if you want all the code so I'm gonna post what seems relevant). In Python:

For setting the request for specific data (I think? this is what the example does with different data from the same sensor)

ECG_WRITE = bytearray([0x02, 0x00, 0x00, 0x01, 0x82, 0x00, 0x01, 0x01, 0x0E, 0x00])

What I've tried to change ECG data to heart rate data is:

RR_UUID = "0000180D-0000-1000-8000-00805f9b34fb"

But I feel like it isn't working because it isn't a byte array.

Then later on these lines are executed for actual data retrievement I think (again, I'm following a guide I'm not 100% sure what the code does)

    att_read = await client.read_gatt_char(PMD_CONTROL)
    await client.write_gatt_char(PMD_CONTROL,  ECG_WRITE)

    ## ECG stream started
    await client.start_notify(PMD_DATA, data_conv)

And from there on the data_conv method converts the data into usable data, and in this same method I can just print out the data and see it. However, since I don't know what I should enter as byte array to request the heart rate data, I haven't been able to get any data out of it yet. It also gives no errors/exceptions whatshowever so I am not sure what is going wrong.
So I am working from a Windows computer using Python code, and the target machine is a Polar H10 heart sensor.

Body:
I've been trying to solve the same problem for some time now and finally got the hang of it.

The documentation is confusing as it leads one to think that the H10 sensor doesn't support HR and PPI readings. The reality, however, is that those measurements are of course supported by the sensor—just not through the PMD_DATA stream. The UUID for HR readings is:

HR_UUID = "00002A37-0000-1000-8000-00805F9B34FB"

So when you start a client.notify(HR_UUID), you will get a 6 byte data stream, that follows the specifications given in the Polar Specification Document (see image below)


问:
Testing with Rocket and Diesel
I am trying to work on a web app with Diesel and Rocket, by following the rocket guide. I have not able to understand how to do testing of this app.

```<code>//in main.rs

#[database("my_db")]
struct PgDbConn(diesel::PgConnection);

#[post("/users", format="application/json", data="<user_info>")]
fn create_new_user(conn: PgDbConn, user_info: Json<NewUser>) {
    use schema::users;
    diesel::insert_into(users::table).values(&*user_info).execute(&*conn).unwrap();
}

fn main() {
    rocket::ignite()
        .attach(PgDbConn::fairing())
        .mount("/", routes![create_new_user])
        .launch();
}

</code>```
```<code>// in test.rs

use crate::PgDbConn;

#[test]
fn test_user_creation() {
    let rocket = rocket::ignite().attach(PgDbConn::fairing());
    let client = Client::new(rocket).unwrap();
    let response = client
        .post("/users")
        .header(ContentType::JSON)
        .body(r#"{"username": "xyz", "email": "temp@abc.com"}"#)
        .dispatch();
    assert_eq!(response.status(), Status::Ok);
}
</code>```

But this modifies the database. How can I make sure that the test does not alter the database.

I tried to create two database and use them in the following way(I am not sure if this is recommended)

```<code>#[cfg(test)]
#[database("test_db")]
struct PgDbConn(diesel::PgConnection);

#[cfg(not(test))]
#[database("live_db")]
struct PgDbConn(diesel::PgConnection);
</code>```

Now I thought I can use the test_transaction method of the diesel::connection::Connection trait in the following way:-

```<code>use crate::PgDbConn;

#[test]
fn test_user_creation() {
    // !!This statment is wrong as PgDbConn is an Fn object instead of a struct
    // !!I am not sure how it works but it seems that this Fn object is resolved
    // !!into struct only when used as a Request Guard
    let conn = PgDbConn;

    // Deref trait for PgDbConn is implemented, So I thought that dereferencing
    // it will return a diesel::PgConnection
    (*conn).test_transaction::<_, (), _>(|| {
        let rocket = rocket::ignite().attach(PgDbConn::fairing());
        let client = Client::new(rocket).unwrap();
        let response = client
            .post("/users")
            .header(ContentType::JSON)
            .body(r#"{"username": "Tushar", "email": "temp@abc.com"}"#)
            .dispatch();
        assert_eq!(response.status(), Status::Ok);
        Ok(())
    });
}
</code>```

The above code obviously fails to compile. Is there a way to resolve this Fn object into the struct and obtain the PgConnection in it. And I am not even sure if this is the right to way to do things.

Is there a recommended way to do testing while using both Rocket and Diesel?

答: This will fundamentally not work as you imagined there, as conn will be a different connection than whatever rocket generates for you. The test_transaction pattern assumes that you use the same connection for everything.

Title: Testing with Rocket and Diesel

Body:
I am trying to work on a web app with Diesel and Rocket, by following the rocket guide. I have not able to understand how to do testing of this app.

//in main.rs

#[database("my_db")]
struct PgDbConn(diesel::PgConnection);

#[post("/users", format="application/json", data="<user_info>")]
fn create_new_user(conn: PgDbConn, user_info: Json<NewUser>) {
    use schema::users;
    diesel::insert_into(users::table).values(&*user_info).execute(&*conn).unwrap();
}

fn main() {
    rocket::ignite()
        .attach(PgDbConn::fairing())
        .mount("/", routes![create_new_user])
        .launch();
}

// in test.rs

use crate::PgDbConn;

#[test]
fn test_user_creation() {
    let rocket = rocket::ignite().attach(PgDbConn::fairing());
    let client = Client::new(rocket).unwrap();
    let response = client
        .post("/users")
        .header(ContentType::JSON)
        .body(r#"{"username": "xyz", "email": "temp@abc.com"}"#)
        .dispatch();
    assert_eq!(response.status(), Status::Ok);
}

But this modifies the database. How can I make sure that the test does not alter the database.

I tried to create two database and use them in the following way(I am not sure if this is recommended)

#[cfg(test)]
#[database("test_db")]
struct PgDbConn(diesel::PgConnection);

#[cfg(not(test))]
#[database("live_db")]
struct PgDbConn(diesel::PgConnection);

Now I thought I can use the test_transaction method of the diesel::connection::Connection trait in the following way:-

use crate::PgDbConn;

#[test]
fn test_user_creation() {
    // !!This statment is wrong as PgDbConn is an Fn object instead of a struct
    // !!I am not sure how it works but it seems that this Fn object is resolved
    // !!into struct only when used as a Request Guard
    let conn = PgDbConn;

    // Deref trait for PgDbConn is implemented, So I thought that dereferencing
    // it will return a diesel::PgConnection
    (*conn).test_transaction::<_, (), _>(|| {
        let rocket = rocket::ignite().attach(PgDbConn::fairing());
        let client = Client::new(rocket).unwrap();
        let response = client
            .post("/users")
            .header(ContentType::JSON)
            .body(r#"{"username": "Tushar", "email": "temp@abc.com"}"#)
            .dispatch();
        assert_eq!(response.status(), Status::Ok);
        Ok(())
    });
}

The above code obviously fails to compile. Is there a way to resolve this Fn object into the struct and obtain the PgConnection in it. And I am not even sure if this is the right to way to do things.

Is there a recommended way to do testing while using both Rocket and Diesel?