问:
JavaScript print info of an array inside an array of object in a html section
I have this array of object that contains info string number array

I'm trying to print all the info of  touristActivities inside an html

I want to print first the information of stepOne in a section tag then the information of stepTwo in another section tag

touristActivities array can contain more the these two steps

my code below i can only print the info without the section

How can i print the info of each steps inside a different section for each step

example:

```<code><section class="stepOne">
all step One information
</section>

<section class="stepTwo">
all step Two information
</section>
</code>```

const database = [{
    sectorId: 1,
    sectorName: "السياحة",
    sectorIcon: "icon-1.png",
    sectorN: "tourism",
    licenseTitle: ["إصدار ترخيص مرافق الإيواء السياحي", "الأنشطة السياحية"],
    licenseDesc: ["تقديم خدمات الترخيص لنشاط الفنادق والشقق المخدومة والمخيمات  والنزل وفنادق الكبائن والشاليهات.", "تقديم خدمات الترخيص لوكالات السياحة والسفر وتنظيم الرحلات السياحية وحجز وحدات الإيواء السياحي وتسويقها."],
    licenseNum: ["7960", "7961"],
    touristActivities: [
        stepOne = {
            subTitle: "إصدار رخصة استثمار للمستثمر الأجنبي",
            description: "إصدار رخصة استثمار لغير السعوديين لمزاولة الأنشطة التجارية بما يتوافق مع الاشتراطات والمتطلبات المحددة.",
            },
       stepTwo = {
           subTitle: "إصدار سجل تجاري",
           description: "وثيقة قانونية تحتوي على بيانات التاجر والنشاط التابع له تمكنه من مزاولة نشاطه بتصريح رسمي وفق الاشتراطات والمتطلبات المحددة.",
                }
        ]
},
{
    sectorId: 2,
},
];

let title = document.querySelector(".title");
let rightSection = document.querySelector('.right');

function getInfo(id) {
for (let i = 0; i < database.length; i++) {
    if (database[i].sectorId === parseInt(id)) {
        title.innerHTML += `<img src='img/${database[i].sectorIcon}' alt='image'>`;
        title.innerHTML += `<h2>${name}</h2>`;
        for (let j = 0; j < database[i].touristActivities.length; j++) {
            subTitle(database[i].touristActivities[j].subTitle);
            description(database[i].touristActivities[j].description);
        }
    }
}
}
getInfo(1);

function subTitle(st) {
let subTitle = `

${st}

`;
rightSection.innerHTML += subTitle;
}

function description(desc) {
    let description = `

وصف الخطوة

${desc}

    `;
    rightSection.innerHTML += description;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <div class="container">
            <div class="title">

            </div>
            <div class="right">
                <div class="subTitle">

                </div>

            </div>
            <div class="left"></div>
        </div></code>```

答:
You can use Array.reduce() method to group activities by index:

let data = getDatabase();

// collect activities
let activities = [];
for (let sect of data) {
  activities.push(sect.touristActivities);
}

// group by index
let groupedActivities = activities.reduce((groups, activities, index) => {
  activities.forEach((step, i) => {
    groups[i] = groups[i] || [];
    groups[i].push(step);
  });
  return groups;
}, []);

// display in html

groupedActivities.forEach((group, index) => {
  let sec = document.createElement('section');
  sec.innerHTML += `<hr><strong>Section step ${index + 1}</strong><br>`;

  for (let act of group)
    sec.innerHTML += `${act.subTitle}<br>`;

  document.body.appendChild(sec);
});

function getDatabase() {
  return [{
      sectorId: 1,
      sectorName: "sector Name",
      licenseNum: ["7960", "7961"],
      touristActivities: [
        stepOne = {
          subTitle: "sector1 stepOne",
          description: "1 dsescription ",
        },
      ]
    },
    {
      sectorId: 2,
      sectorName: "sector Name",
      licenseNum: ["7960", "7961"],
      touristActivities: [
        stepOne = {
          subTitle: "sector2 stepOne",
          description: "sector2 dsescription",
        },
        stepTwo = {
          subTitle: "sector2 stepTwo",
          description: "sector2 dsescription",
        },
      ]
    },
    {
      sectorId: 3,
      sectorName: "sector Name",
      licenseNum: ["7960", "7961"],
      touristActivities: [
        stepOne = {
          subTitle: "sector3 stepOne",
          description: "sector3 dsescription",
        },
        stepTwo = {
          subTitle: "sector3 stepTwo",
          description: "sector3 dsescription",
        },
        stepThree = {
          subTitle: "sector3 stepThree",
          description: "sector3 dsescription",
        }
      ]
    },

  ];
}```
</div>
</div>
</p>
<hr />
<p>If you are doing a lot of complex queries on object structure then you can use jsonpath library.</p>
<pre class="lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/jsonpath@1.1.1/jsonpath.min.js"></script>
<script>
  let activities = jsonpath.query(database, '$..touristActivities');
</script>
</code>```

Body:
I have this array of object that contains info string number array

I'm trying to print all the info of  touristActivities inside an html

I want to print first the information of stepOne in a section tag then the information of stepTwo in another section tag

touristActivities array can contain more the these two steps

my code below i can only print the info without the section

How can i print the info of each steps inside a different section for each step

example:

all step One information

all step Two information

const database = [{
    sectorId: 1,
    sectorName: "السياحة",
    sectorIcon: "icon-1.png",
    sectorN: "tourism",
    licenseTitle: ["إصدار ترخيص مرافق الإيواء السياحي", "الأنشطة السياحية"],
    licenseDesc: ["تقديم خدمات الترخيص لنشاط الفنادق والشقق المخدومة والمخيمات  والنزل وفنادق الكبائن والشاليهات.", "تقديم خدمات الترخيص لوكالات السياحة والسفر وتنظيم الرحلات السياحية وحجز وحدات الإيواء السياحي وتسويقها."],
    licenseNum: ["7960", "7961"],
    touristActivities: [
        stepOne = {
            subTitle: "إصدار رخصة استثمار للمستثمر الأجنبي",
            description: "إصدار رخصة استثمار لغير السعوديين لمزاولة الأنشطة التجارية بما يتوافق مع الاشتراطات والمتطلبات المحددة.",
            },
       stepTwo = {
           subTitle: "إصدار سجل تجاري",
           description: "وثيقة قانونية تحتوي على بيانات التاجر والنشاط التابع له تمكنه من مزاولة نشاطه بتصريح رسمي وفق الاشتراطات والمتطلبات المحددة.",
                }
        ]
},
{
    sectorId: 2,
},
];

let title = document.querySelector(".title");
let rightSection = document.querySelector('.right');

function getInfo(id) {
for (let i = 0; i < database.length; i++) {
    if (database[i].sectorId === parseInt(id)) {
        title.innerHTML += `<img src='img/${database[i].sectorIcon}' alt='image'>`;
        title.innerHTML += `<h2>${name}</h2>`;
        for (let j = 0; j < database[i].touristActivities.length; j++) {
            subTitle(database[i].touristActivities[j].subTitle);
            description(database[i].touristActivities[j].description);
        }
    }
}
}
getInfo(1);

function subTitle(st) {
let subTitle = `

${st}

`;
rightSection.innerHTML += subTitle;
}

function description(desc) {
    let description = `

وصف الخطوة

${desc}

    `;
    rightSection.innerHTML += description;
}

Body:
You can use Array.reduce() method to group activities by index:

let data = getDatabase();

// collect activities
let activities = [];
for (let sect of data) {
  activities.push(sect.touristActivities);
}

// group by index
let groupedActivities = activities.reduce((groups, activities, index) => {
  activities.forEach((step, i) => {
    groups[i] = groups[i] || [];
    groups[i].push(step);
  });
  return groups;
}, []);

// display in html <section>
groupedActivities.forEach((group, index) => {
  let sec = document.createElement('section');
  sec.innerHTML += `<hr><strong>Section step ${index + 1}</strong><br>`;

  for (let act of group)
    sec.innerHTML += `${act.subTitle}<br>`;

  document.body.appendChild(sec);
});

function getDatabase() {
  return [{
      sectorId: 1,
      sectorName: "sector Name",
      licenseNum: ["7960", "7961"],
      touristActivities: [
        stepOne = {
          subTitle: "sector1 stepOne",
          description: "1 dsescription ",
        },
      ]
    },
    {
      sectorId: 2,
      sectorName: "sector Name",
      licenseNum: ["7960", "7961"],
      touristActivities: [
        stepOne = {
          subTitle: "sector2 stepOne",
          description: "sector2 dsescription",
        },
        stepTwo = {
          subTitle: "sector2 stepTwo",
          description: "sector2 dsescription",
        },
      ]
    },
    {
      sectorId: 3,
      sectorName: "sector Name",
      licenseNum: ["7960", "7961"],
      touristActivities: [
        stepOne = {
          subTitle: "sector3 stepOne",
          description: "sector3 dsescription",
        },
        stepTwo = {
          subTitle: "sector3 stepTwo",
          description: "sector3 dsescription",
        },
        stepThree = {
          subTitle: "sector3 stepThree",
          description: "sector3 dsescription",
        }
      ]
    },

  ];
}

If you are doing a lot of complex queries on object structure then you can use jsonpath library.

<script src="https://cdn.jsdelivr.net/npm/jsonpath@1.1.1/jsonpath.min.js"></script>
<script>
  let activities = jsonpath.query(database, '$..touristActivities');
</script>


来源: stackexchange

问:
How to read textbox.Text value from another thread in WPF?
In my WPF form I have a textbox.

When a timer elapses, the content of the textbox needs to be fetched.

The timer elapsed is working in a different thread then the UI.

The question is kinda two-fold:

What is the easiest, most readable way to read the value from a GUI thread cross thread (I found several and they look too verbose for what should be something really basic)?

Can't I read the text in a non-blocking way? I don't care about thread safety in this case.

--EDIT--

I used the Dispatcher, but had a more verbose call then what John had:

```<code>originalTextBox.Dispatcher.Invoke(
    DispatcherPriority.Normal,
    (ThreadStart) delegate{text=originalTextBox.Text;}
);
</code>```

Wouldn't mind even terser though. Accessing a text property should be utterly basic.

答:
There is no "quick hack" for reading a GUI object's values from a differing thread than the one that created it. WPF will just not allow you to do it all. Windows Forms would complain occassionally, but WPF is way more strict.

You need to learn about the Dispatcher. It might look verbose, but it really isn't that hard to understand. You pass a delegate to the dispatcher that points to a method you want called on the GUI thread, and it does it.

Here's a nice simple example:

http://www.switchonthecode.com/tutorials/working-with-the-wpf-dispatcher

OwnerDisplayName: boris callens

ContentLicense: CC BY-SA 2.5

Body:
In my WPF form I have a textbox.

When a timer elapses, the content of the textbox needs to be fetched.

The timer elapsed is working in a different thread then the UI.

The question is kinda two-fold:

What is the easiest, most readable way to read the value from a GUI thread cross thread (I found several and they look too verbose for what should be something really basic)?

Can't I read the text in a non-blocking way? I don't care about thread safety in this case.

--EDIT--

I used the Dispatcher, but had a more verbose call then what John had:

originalTextBox.Dispatcher.Invoke(
    DispatcherPriority.Normal,
    (ThreadStart) delegate{text=originalTextBox.Text;}
);

Wouldn't mind even terser though. Accessing a text property should be utterly basic.

LastEditorDisplayName: boris callens

ContentLicense: CC BY-SA 3.0


问:
Android Hardware Menu button isn't working for me
I'm using this code to display a menu, but it isn't doing anything when I press the menu button.

This is in a view flipper, I don't know if that has anything to do with the problem.

I used this before and with no problems at all:

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()){
    case R.id.new_game:

        return true;
    case R.id.help:
        finish();

        return true;
    }
    return false;
}

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"

          android:title="new_game" />
    <item android:id="@+id/help"

          android:title="clear" />
</menu>
</code>```

答: You are not calling the superclass methods.</p>

Body:
I'm using this code to display a menu, but it isn't doing anything when I press the menu button.

This is in a view flipper, I don't know if that has anything to do with the problem.

I used this before and with no problems at all:

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()){
    case R.id.new_game:

        return true;
    case R.id.help:
        finish();

        return true;
    }
    return false;
}

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"

          android:title="new_game" />
    <item android:id="@+id/help"

          android:title="clear" />
</menu>


问:
How to display the ID's of all the leaves related to a given level along with this level
I have a tree structure:

```<code>CARS (ID = 3)
    | AUDI (ID: 5, ParentId: 3)
        | DIR1 (ID: 9, ParentId: 5)
        | DIR2 (ID: 7, ParentId: 5)
        | DIR3 (ID: 8, ParentId: 5)
    | FIAT (ID: 10, ParentId: 3)
    | FORD (ID: 11, ParentId: 3)
        | DIR4 (ID: 12, ParentId: 11)
    | RENAULT (ID: 6, ParentId: 3)
    | TOYOTA (ID: 4, ParentId: 3)
</code>```

I need to display the ID's of all the leaves related to a given level along with this level as follows:

ID
Name
ID2
Name2

3
CARS
3

3
CARS
5
AUDI

3
CARS
9
DIR1

3
CARS
7
DIR2

3
CARS
8
DIR3

3
CARS
10
FIAT

3
CARS
11
FORD

3
CARS
12
DIR4

3
CARS
6
RENAULT

3
CARS
4
TOYOTA

5
AUDI
5

5
AUDI
9
DIR1

5
AUDI
7
DIR2

5
AUDI
8
DIR3

9
DIR1
9
DIR1

7
DIR2
7
DIR2

8
DIR3
8
DIR3

10
FIAT
10

11
FORD
11

11
FORD
12
DIR4

12
DIR4
12
DIR4

6
RENAULT
6

4
TOYOTA
4

This is a dynamic structure, users can delete and add leaves so I need a function or procedure.

I have created the following code but maybe there is a better, more elegant way to get the results:

```<code>DECLARE @T AS TABLE
              (
                  ID int,
                  Name varchar(255),
                  ParentId int,
                  Level int,
                  Leaf int
              )

INSERT INTO @T
VALUES (3, 'CARS', NULL, 1, 0),
       (4, 'TOYOTA', 3, 2, 1),
       (5, 'AUDI', 3, 2, 2),
       (6, 'RENAULT', 3, 2, 3),
       (7, 'DIR2', 5, 3, 1),
       (8, 'DIR3', 5, 3, 2),
       (9, 'DIR1', 5, 3, 3),
       (10, 'FIAT', 3, 2, 4),
       (11, 'FORD', 3, 2, 5),
       (12, 'DIR4', 11, 3, 1)

;WITH cte1 AS
(
    SELECT
        ID, Name, ParentId, Level, Leaf
    FROM
        @T
), cte2 AS
(
    SELECT
        ID, Name, ParentId, 1 AS [Level],
        CAST((RTRIM(LTRIM(STR(ID, 15, 0)))) AS VARCHAR(MAX)) AS Ids
    FROM
        @T t1
    WHERE
        ParentId IS NULL

    UNION ALL

    SELECT
        t2.ID, t2.Name, t2.ParentId, M.[level] + 1 AS [Level],
        CAST((M.Ids + ',' + RTRIM(LTRIM(STR(t2.ID, 15, 0)))) AS VARCHAR(MAX)) AS Ids
    FROM
        @T AS t2
    JOIN
        cte2 AS M ON t2.ParentId = M.ID
)
SELECT
    B.ID, B.Name AS Name,
    cte2.ID AS ID2, cte2.Name
FROM
    cte2
CROSS APPLY
    (SELECT Split.a.value('.', 'VARCHAR(1024)') AS gId
     FROM
         (SELECT
              CAST ('<M>' + REPLACE(Ids, ',', '</M><M>') + '</M>' AS XML) AS String) A
     CROSS APPLY
         String.nodes ('/M') AS Split(a)) AS A
CROSS APPLY
    (SELECT CAST(gId as int) AS G_ID) AS G_ID
INNER JOIN
    @T B ON B.Id = G_ID
</code>```

答:
Is it what you are after?

```<code>WITH cte AS (
    SELECT  ID, Name, ID id2, Name Name2, ParentId, 1 AS [Level]
      , CAST(STR(ID,15,0) AS VARCHAR(MAX)) AS Ids
    FROM    tbl
    UNION ALL

    SELECT  m.ID, m.Name, t2.id, t2.name,  t2.ParentId, M.[level] + 1
      , M.Ids + ',' + STR(t2.ID,15,0)
    FROM tbl AS t2
    JOIN cte AS M ON t2.ParentId = M.ID2
)
select ID, Name, id2, Name2, level, replace(ids, ' ', '')
from cte
order by id, ids;
</code>```

All paths from a node.

db<>fiddle

ContentLicense: CC BY-SA 4.0

Body:
I have a tree structure:

CARS (ID = 3)
    | AUDI (ID: 5, ParentId: 3)
        | DIR1 (ID: 9, ParentId: 5)
        | DIR2 (ID: 7, ParentId: 5)
        | DIR3 (ID: 8, ParentId: 5)
    | FIAT (ID: 10, ParentId: 3)
    | FORD (ID: 11, ParentId: 3)
        | DIR4 (ID: 12, ParentId: 11)
    | RENAULT (ID: 6, ParentId: 3)
    | TOYOTA (ID: 4, ParentId: 3)

I need to display the ID's of all the leaves related to a given level along with this level as follows:

ID
Name
ID2
Name2

3
CARS
3

3
CARS
5
AUDI

3
CARS
9
DIR1

3
CARS
7
DIR2

3
CARS
8
DIR3

3
CARS
10
FIAT

3
CARS
11
FORD

3
CARS
12
DIR4

3
CARS
6
RENAULT

3
CARS
4
TOYOTA

5
AUDI
5

5
AUDI
9
DIR1

5
AUDI
7
DIR2

5
AUDI
8
DIR3

9
DIR1
9
DIR1

7
DIR2
7
DIR2

8
DIR3
8
DIR3

10
FIAT
10

11
FORD
11

11
FORD
12
DIR4

12
DIR4
12
DIR4

6
RENAULT
6

4
TOYOTA
4

This is a dynamic structure, users can delete and add leaves so I need a function or procedure.

I have created the following code but maybe there is a better, more elegant way to get the results:

DECLARE @T AS TABLE
              (
                  ID int,
                  Name varchar(255),
                  ParentId int,
                  Level int,
                  Leaf int
              )

INSERT INTO @T
VALUES (3, 'CARS', NULL, 1, 0),
       (4, 'TOYOTA', 3, 2, 1),
       (5, 'AUDI', 3, 2, 2),
       (6, 'RENAULT', 3, 2, 3),
       (7, 'DIR2', 5, 3, 1),
       (8, 'DIR3', 5, 3, 2),
       (9, 'DIR1', 5, 3, 3),
       (10, 'FIAT', 3, 2, 4),
       (11, 'FORD', 3, 2, 5),
       (12, 'DIR4', 11, 3, 1)

;WITH cte1 AS
(
    SELECT
        ID, Name, ParentId, Level, Leaf
    FROM
        @T
), cte2 AS
(
    SELECT
        ID, Name, ParentId, 1 AS [Level],
        CAST((RTRIM(LTRIM(STR(ID, 15, 0)))) AS VARCHAR(MAX)) AS Ids
    FROM
        @T t1
    WHERE
        ParentId IS NULL

    UNION ALL

    SELECT
        t2.ID, t2.Name, t2.ParentId, M.[level] + 1 AS [Level],
        CAST((M.Ids + ',' + RTRIM(LTRIM(STR(t2.ID, 15, 0)))) AS VARCHAR(MAX)) AS Ids
    FROM
        @T AS t2
    JOIN
        cte2 AS M ON t2.ParentId = M.ID
)
SELECT
    B.ID, B.Name AS Name,
    cte2.ID AS ID2, cte2.Name
FROM
    cte2
CROSS APPLY
    (SELECT Split.a.value('.', 'VARCHAR(1024)') AS gId
     FROM
         (SELECT
              CAST ('<M>' + REPLACE(Ids, ',', '</M><M>') + '</M>' AS XML) AS String) A
     CROSS APPLY
         String.nodes ('/M') AS Split(a)) AS A
CROSS APPLY
    (SELECT CAST(gId as int) AS G_ID) AS G_ID
INNER JOIN
    @T B ON B.Id = G_ID

Body:
Is it what you are after?

WITH cte AS (
    SELECT  ID, Name, ID id2, Name Name2, ParentId, 1 AS [Level]
      , CAST(STR(ID,15,0) AS VARCHAR(MAX)) AS Ids
    FROM    tbl
    UNION ALL

    SELECT  m.ID, m.Name, t2.id, t2.name,  t2.ParentId, M.[level] + 1
      , M.Ids + ',' + STR(t2.ID,15,0)
    FROM tbl AS t2
    JOIN cte AS M ON t2.ParentId = M.ID2
)
select ID, Name, id2, Name2, level, replace(ids, ' ', '')
from cte
order by id, ids;

All paths from a node.

db<>fiddle


问:
Odata Global PageSize
Can someone please explain why my EnableQueryAttribute filter is not firing when the client query does not include the Count=True in their query? My entire dataset is returned.

```<code>public class EnableQueryWithDefaultPageSizeAttribute : EnableQueryAttribute
{
    const int pageSizeDefault = 100;

    public override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)
    {
        int pagesize = pageSizeDefault;
        var result = queryOptions.ApplyTo(queryable, new ODataQuerySettings { PageSize = pagesize });
        return result;
    }
}
</code>```

The following query trigger the filter:

```<code>https://localhost:5001/api/teams?$count=true
</code>```

This query doesn't trigger the filter:

```<code>https://localhost:5001/api/teams
</code>```

The only way to solve it is to right now is to hard code my controller method with:

```<code> [EnableQuery(PageSize = 100)]
</code>```

My gold is to have a global filter that sets the page size for any Odata API request.  I've googled and read Microsoft documentation and still can't find a solution.  Any help will be appreciated.  I'm currently using .net core 6.0 and AspNetCoreOdata 8.0.6.

答:
Have you tried deliberately setting the property in the constructor? This has the added benefit of still allowing you to override the default page size at each endpoint.

```<code>public class EnableQueryWithDefaultPageSizeAttribute : EnableQueryAttribute
{
    public EnableQueryWithDefaultPageSizeAttribute()
    {
        this.PageSize = 100;
    }
}
</code>```

I think the issue in .Net 5/6 is the paging behaviour needs to be resolvable from the Edm, not from the individual Query, this is a breaking change from the .Net FX implementation when you couldmodify it on a per-request basis.

Title: Odata Global PageSize

Body:
Can someone please explain why my EnableQueryAttribute filter is not firing when the client query does not include the Count=True in their query? My entire dataset is returned.

public class EnableQueryWithDefaultPageSizeAttribute : EnableQueryAttribute
{
    const int pageSizeDefault = 100;

    public override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)
    {
        int pagesize = pageSizeDefault;
        var result = queryOptions.ApplyTo(queryable, new ODataQuerySettings { PageSize = pagesize });
        return result;
    }
}

The following query trigger the filter:

https://localhost:5001/api/teams?$count=true

This query doesn't trigger the filter:

https://localhost:5001/api/teams

The only way to solve it is to right now is to hard code my controller method with:

 [EnableQuery(PageSize = 100)]

My gold is to have a global filter that sets the page size for any Odata API request.  I've googled and read Microsoft documentation and still can't find a solution.  Any help will be appreciated.  I'm currently using .net core 6.0 and AspNetCoreOdata 8.0.6.

Body:
Have you tried deliberately setting the property in the constructor? This has the added benefit of still allowing you to override the default page size at each endpoint.

public class EnableQueryWithDefaultPageSizeAttribute : EnableQueryAttribute
{
    public EnableQueryWithDefaultPageSizeAttribute()
    {
        this.PageSize = 100;
    }
}

I think the issue in .Net 5/6 is the paging behaviour needs to be resolvable from the Edm, not from the individual Query, this is a breaking change from the .Net FX implementation when you couldmodify it on a per-request basis.


问:
How do i stop pause a task in c# .net
I have tried but it is not working i want to stop and pause this task:: code below

```<code>private void checkingTimer()
        {
            System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(startPollingAwaitingURLs);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
            dispatcherTimer.Start();
        }

        private static object _lock_CrawlingSync = new object();
        private static bool blBeingProcessed = false;
        private static List<Task> lstCrawlingTasks = new List<Task>();
        private static List<string> lstCurrentlyCrawlingUrls = new List<string>();
        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            using (WebCrawlerEntities1 db = new WebCrawlerEntities1())
            {
                db.tblMainUrls.RemoveRange(db.tblMainUrls);
                db.SaveChanges();
            }
        }

        private void clearDBandStart(object sender, RoutedEventArgs e)
        {
            dtStartDate = DateTime.Now;

            crawlPage(urlTextbox.Text.normalizeUrl(), 0, urlTextbox.Text.normalizeUrl(), DateTime.Now);
            checkingTimer();
        }

        private void startPollingAwaitingURLs(object sender, EventArgs e)
        {
            lock (UserLogs)
            {
                string srPerMinCrawlingspeed = (irCrawledUrlCount.ToDouble() / (DateTime.Now - dtStartDate).TotalMinutes).ToString("N2");

                string srPerMinDiscoveredLinkSpeed = (irDiscoveredUrlCount.ToDouble() / (DateTime.Now - dtStartDate).TotalMinutes).ToString("N2");

                string srPassedTime = (DateTime.Now - dtStartDate).TotalMinutes.ToString("N2");

                UserLogs.Insert(0, $"{DateTime.Now} polling awaiting urls \t processing: {blBeingProcessed} \t number of crawling tasks: {lstCrawlingTasks.Count}");

                UserLogs.Insert(0, $"Total Time: {srPassedTime} Minutes \t Total Crawled Links Count: {irCrawledUrlCount.ToString("N0")} \t Crawling Speed Per Minute: {srPerMinCrawlingspeed} \t Total Discovered Links : {irDiscoveredUrlCount.ToString("N0")} \t Discovered Url Speed: {srPerMinDiscoveredLinkSpeed} ");
            }

            logMesssage($"polling awaiting urls \t processing: {blBeingProcessed} \t number of crawling tasks: {lstCrawlingTasks.Count}");

            if (blBeingProcessed)
                return;

            lock (_lock_CrawlingSync)
            {

                blBeingProcessed = true;

                lstCrawlingTasks = lstCrawlingTasks.Where(pr => pr.Status != TaskStatus.RanToCompletion && pr.Status != TaskStatus.Faulted).ToList();

                int irTasksCountToStart = _irNumberOfTotalConcurrentCrawling - lstCrawlingTasks.Count;

                if (irTasksCountToStart > 0)
                    using (WebCrawlerEntities1 db = new WebCrawlerEntities1())
                    {
                        var vrReturnedList = db.tblMainUrls.Where(x => x.isCrawled == false && x.CrawlTryCounter < _irMaximumTryCount)
                                  .OrderBy(pr => pr.DiscoverDate)
                            .Select(x => new
                            {
                                x.Url,
                                x.LinkDepthLevel
                            }).Take(irTasksCountToStart * 2).ToList();

                        logMesssage(string.Join(" , ", vrReturnedList.Select(pr => pr.Url)));

                        foreach (var vrPerReturned in vrReturnedList)
                        {
                            var vrUrlToCrawl = vrPerReturned.Url;
                            int irDepth = vrPerReturned.LinkDepthLevel;
                            lock (lstCurrentlyCrawlingUrls)
                            {
                                if (lstCurrentlyCrawlingUrls.Contains(vrUrlToCrawl))
                                {
                                    logMesssage($"bypass url since already crawling: \t {vrUrlToCrawl}");
                                    continue;
                                }
                                lstCurrentlyCrawlingUrls.Add(vrUrlToCrawl);
                            }

                            logMesssage($"starting crawling url: \t {vrUrlToCrawl}");

                            lock (UserLogs)
                            {
                                UserLogs.Insert(0, $"{DateTime.Now} starting crawling url: \t {vrUrlToCrawl}");
                            }

                            var vrStartedTask = Task.Factory.StartNew(() => { crawlPage(vrUrlToCrawl, irDepth, null, DateTime.MinValue); }).ContinueWith((pr) =>
                            {

                                lock (lstCurrentlyCrawlingUrls)
                                {
                                    lstCurrentlyCrawlingUrls.Remove(vrUrlToCrawl);
                                    logMesssage($"removing url from list since task completed: \t {vrUrlToCrawl}");
                                }

                            });
                            lstCrawlingTasks.Add(vrStartedTask);

                            if (lstCrawlingTasks.Count > _irNumberOfTotalConcurrentCrawling)
                                break;
                        }
                    }

                blBeingProcessed = false;
            }
        }
</code>```

so is there a way to stop my task up ahead and pause should i mre.set() or .Set()

my application is a web crawler that get links from any website.

so when pressing on a button web crawling task pause or stop and restart ... any methods to do or changes

答:
Try :

Thread.Sleep() to pause your task.

Thread.Interrupt() to stop your sleeping task.

Title: How do i stop pause a task in c# .net

Body:
I have tried but it is not working i want to stop and pause this task:: code below

private void checkingTimer()
        {
            System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(startPollingAwaitingURLs);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
            dispatcherTimer.Start();
        }

        private static object _lock_CrawlingSync = new object();
        private static bool blBeingProcessed = false;
        private static List<Task> lstCrawlingTasks = new List<Task>();
        private static List<string> lstCurrentlyCrawlingUrls = new List<string>();
        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            using (WebCrawlerEntities1 db = new WebCrawlerEntities1())
            {
                db.tblMainUrls.RemoveRange(db.tblMainUrls);
                db.SaveChanges();
            }
        }

        private void clearDBandStart(object sender, RoutedEventArgs e)
        {
            dtStartDate = DateTime.Now;

            crawlPage(urlTextbox.Text.normalizeUrl(), 0, urlTextbox.Text.normalizeUrl(), DateTime.Now);
            checkingTimer();
        }

        private void startPollingAwaitingURLs(object sender, EventArgs e)
        {
            lock (UserLogs)
            {
                string srPerMinCrawlingspeed = (irCrawledUrlCount.ToDouble() / (DateTime.Now - dtStartDate).TotalMinutes).ToString("N2");

                string srPerMinDiscoveredLinkSpeed = (irDiscoveredUrlCount.ToDouble() / (DateTime.Now - dtStartDate).TotalMinutes).ToString("N2");

                string srPassedTime = (DateTime.Now - dtStartDate).TotalMinutes.ToString("N2");

                UserLogs.Insert(0, $"{DateTime.Now} polling awaiting urls \t processing: {blBeingProcessed} \t number of crawling tasks: {lstCrawlingTasks.Count}");

                UserLogs.Insert(0, $"Total Time: {srPassedTime} Minutes \t Total Crawled Links Count: {irCrawledUrlCount.ToString("N0")} \t Crawling Speed Per Minute: {srPerMinCrawlingspeed} \t Total Discovered Links : {irDiscoveredUrlCount.ToString("N0")} \t Discovered Url Speed: {srPerMinDiscoveredLinkSpeed} ");
            }

            logMesssage($"polling awaiting urls \t processing: {blBeingProcessed} \t number of crawling tasks: {lstCrawlingTasks.Count}");

            if (blBeingProcessed)
                return;

            lock (_lock_CrawlingSync)
            {

                blBeingProcessed = true;

                lstCrawlingTasks = lstCrawlingTasks.Where(pr => pr.Status != TaskStatus.RanToCompletion && pr.Status != TaskStatus.Faulted).ToList();

                int irTasksCountToStart = _irNumberOfTotalConcurrentCrawling - lstCrawlingTasks.Count;

                if (irTasksCountToStart > 0)
                    using (WebCrawlerEntities1 db = new WebCrawlerEntities1())
                    {
                        var vrReturnedList = db.tblMainUrls.Where(x => x.isCrawled == false && x.CrawlTryCounter < _irMaximumTryCount)
                                  .OrderBy(pr => pr.DiscoverDate)
                            .Select(x => new
                            {
                                x.Url,
                                x.LinkDepthLevel
                            }).Take(irTasksCountToStart * 2).ToList();

                        logMesssage(string.Join(" , ", vrReturnedList.Select(pr => pr.Url)));

                        foreach (var vrPerReturned in vrReturnedList)
                        {
                            var vrUrlToCrawl = vrPerReturned.Url;
                            int irDepth = vrPerReturned.LinkDepthLevel;
                            lock (lstCurrentlyCrawlingUrls)
                            {
                                if (lstCurrentlyCrawlingUrls.Contains(vrUrlToCrawl))
                                {
                                    logMesssage($"bypass url since already crawling: \t {vrUrlToCrawl}");
                                    continue;
                                }
                                lstCurrentlyCrawlingUrls.Add(vrUrlToCrawl);
                            }

                            logMesssage($"starting crawling url: \t {vrUrlToCrawl}");

                            lock (UserLogs)
                            {
                                UserLogs.Insert(0, $"{DateTime.Now} starting crawling url: \t {vrUrlToCrawl}");
                            }

                            var vrStartedTask = Task.Factory.StartNew(() => { crawlPage(vrUrlToCrawl, irDepth, null, DateTime.MinValue); }).ContinueWith((pr) =>
                            {

                                lock (lstCurrentlyCrawlingUrls)
                                {
                                    lstCurrentlyCrawlingUrls.Remove(vrUrlToCrawl);
                                    logMesssage($"removing url from list since task completed: \t {vrUrlToCrawl}");
                                }

                            });
                            lstCrawlingTasks.Add(vrStartedTask);

                            if (lstCrawlingTasks.Count > _irNumberOfTotalConcurrentCrawling)
                                break;
                        }
                    }

                blBeingProcessed = false;
            }
        }

so is there a way to stop my task up ahead and pause should i mre.set() or .Set()

my application is a web crawler that get links from any website.

so when pressing on a button web crawling task pause or stop and restart ... any methods to do or changes


问:
Testing Django model throws TypeError
I am trying to test my REST API and am currently testing my models. I am very new at Django and testing in particular.

While testing my models I keep getting this error:

```<code>TypeError: Field 'id' expected a number but got datetime.datetime(2022, ...)
</code>```

I get this error for every model and view so far.

Why is this error occurring? How can I get my tests for this model to run?
Am I even testing properly?

This is one of my models:

```<code>class Tag(models.Model):
    name = models.CharField(max_length=256)
    language = models.CharField(max_length=256)

    objects = models.Manager()

    def __str__(self):
        """Return a human readable representation of the model instance."""
        return self.name or ''

    @property
    def tags(self):
        tags = self.tagging.values('tag')
        return tags.values('tag_id', 'tag__name', 'tag__language')

</code>```

And this is the corresponding test suite for this model:

```<code>class TagTests(TestCase):
    def setUp(self):
        self.tag_name = "name of the tag"
        self.tag_language = "language of tag"
        self.tag = Tag.objects.create(name=self.tag_name, language=self.tag_language)

    def test_name_label(self):
        tag = Tag.objects.get(id=1)
        field_label = tag._meta.get_field('name').verbose_name()
        self.assertEqual(field_label, 'name')

    def test_tag_size(self):
        tag = Tag.objects.get(id=1)
        max_length = tag._meta.get_field('name').max_length
        self.assertEqual(max_length, 256)

    def test_str(self):
        """Test for string representation"""
        tag = Tag().objects.get(id=1)
        self.assertEqual(str(tag), tag.name)

    def test_model_can_create_tag(self):
        """Test the tagging model can create a tag instance"""
        old_count = Tag.objects.count()
        self.tag.save()
        new_count = Tag.objects.count()
        self.assertNotEqual(old_count, new_count)
</code>```

答:
I can't see a spot that you pass datetime object as an id.

But...

I've spotted some crucial mistakes:

```<code>tag = Tag().objects.get(id=1)
</code>```

You are creating Tag object with ().

Another thing. If you create self.tag = Tag.objects.create() in SetUp, then the model is created for every test in TestCase. It means that you cannot get object with seeking (id=1) because the database is the same, but in SetUp it creates new object with new id. So, instead of:

```<code>def test_str(self):
    tag = Tag.objects.get(id=1)
    self.assertEqual(str(tag), tag.name)
</code>```

You should simply use much safier approach:

```<code>def test_str(self):
    self.assertEqual(str(self.tag), self.tag.name)
</code>```

Try to "hardcode" as little, as you can in tests.

Title: Testing Django model throws TypeError

Body:
I am trying to test my REST API and am currently testing my models. I am very new at Django and testing in particular.

While testing my models I keep getting this error:

TypeError: Field 'id' expected a number but got datetime.datetime(2022, ...)

I get this error for every model and view so far.

Why is this error occurring? How can I get my tests for this model to run?
Am I even testing properly?

This is one of my models:

class Tag(models.Model):
    name = models.CharField(max_length=256)
    language = models.CharField(max_length=256)

    objects = models.Manager()

    def __str__(self):
        """Return a human readable representation of the model instance."""
        return self.name or ''

    @property
    def tags(self):
        tags = self.tagging.values('tag')
        return tags.values('tag_id', 'tag__name', 'tag__language')

And this is the corresponding test suite for this model:

class TagTests(TestCase):
    def setUp(self):
        self.tag_name = "name of the tag"
        self.tag_language = "language of tag"
        self.tag = Tag.objects.create(name=self.tag_name, language=self.tag_language)

    def test_name_label(self):
        tag = Tag.objects.get(id=1)
        field_label = tag._meta.get_field('name').verbose_name()
        self.assertEqual(field_label, 'name')

    def test_tag_size(self):
        tag = Tag.objects.get(id=1)
        max_length = tag._meta.get_field('name').max_length
        self.assertEqual(max_length, 256)

    def test_str(self):
        """Test for string representation"""
        tag = Tag().objects.get(id=1)
        self.assertEqual(str(tag), tag.name)

    def test_model_can_create_tag(self):
        """Test the tagging model can create a tag instance"""
        old_count = Tag.objects.count()
        self.tag.save()
        new_count = Tag.objects.count()
        self.assertNotEqual(old_count, new_count)

Body:
I can't see a spot that you pass datetime object as an id.

But...

I've spotted some crucial mistakes:

tag = Tag().objects.get(id=1)

You are creating Tag object with ().

Another thing. If you create self.tag = Tag.objects.create() in SetUp, then the model is created for every test in TestCase. It means that you cannot get object with seeking (id=1) because the database is the same, but in SetUp it creates new object with new id. So, instead of:

def test_str(self):
    tag = Tag.objects.get(id=1)
    self.assertEqual(str(tag), tag.name)

You should simply use much safier approach:

def test_str(self):
    self.assertEqual(str(self.tag), self.tag.name)

Try to "hardcode" as little, as you can in tests.


问:
c# read serial in hex
I am using the SDS011 laser dust sensor and want to read the data in a Windows forms Application.
I get Hex Data. Example: AA C0 D4 04 3A 0A A1 60 1D AB
now the fourth and the third pair represent the PM2.5 value, in this example: 04D4 -> 1236 -> 123,6 ug/m^3
Could you please help me write a code for reading in the hex data and calculating the PM2.5 value?
Thanks.</p>

答:
If the data is coming as a string then it's simple as:</p>
```<code>string inputData = "AA C0 D4 04 3A 0A A1 60 1D AB";
var inputDataSplit = inputData.Split(' ');
// Concatenate the fourth and the third string, and convert it to integer with base 16 (hex)
int pmValue = Convert.ToInt32(inputDataSplit[3] + inputDataSplit[2], 16);

// 1236
Console.Write(pmValue);
</code>```

Title: c# read serial in hex

Body:
If the data is coming as a string then it's simple as:

string inputData = "AA C0 D4 04 3A 0A A1 60 1D AB";
var inputDataSplit = inputData.Split(' ');
// Concatenate the fourth and the third string, and convert it to integer with base 16 (hex)
int pmValue = Convert.ToInt32(inputDataSplit[3] + inputDataSplit[2], 16);

// 1236
Console.Write(pmValue);


问:
Scrollbar in canvas
I want to put a scrollbar in a canvas inside a Frame with tkinter. I can see my scrollbar but she don't work. I don't anderstant why, here is my code.

```<code>    labelBlesser = tk.Label(self.fen, text='Rajouter', font=fontLabel)
    labelBlesser.configure(background='white')
    labelBlesser.place(relx=0.7, rely=0.40, anchor='center')

    frameBlesser = tk.Frame(self.fen)

    vbar = tk.Scrollbar(frameBlesser, orient='vertical')
    vbar.pack(side='right', fill='y')
    canvasBlesser = tk.Canvas(frameBlesser)
    vbar.config(command=canvasBlesser.yview)

    frameBlesser.place(relx=0.7, rely=0.65, anchor='center')

    for _ in range(3):
        self.listeBlesser.append(tk.Label(canvasBlesser, text='Blesse {}:'.format(self.nombreBlesserAjouter + 1)))
        self.listeBlesser.append(tk.Entry(canvasBlesser, font=fontEntry))

    self.refreshListeBlesser()
    canvasBlesser.pack()

def refreshListeBlesser(self):
    for i, lab in enumerate(self.listeBlesser):
        lab.place(x=10, y=i*70+13)
</code>```

thank you for your help :)

答:
You need to bind the canvas and the scrollbar together. Also, you need to create a frame inside of the canvas using canvasBlesser.create_window so that you can place stuff inside the frame as usual.

frameBlesser = tk.Frame(self.fen)
vbar = tk.Scrollbar(frameBlesser, orient='vertical')
vbar.pack(side='right', fill='y')
canvasBlesser = tk.Canvas(frameBlesser)
# adding the side and fill for packing canvas in the frame
canvasBlesser.pack(side='left', fill='both')

# connecting the canvas and scrollbar together
vbar.config(command=canvasBlesser.yview)
canvasBlesser.configure(yscrollcommand=vbar.set)

# placing a frame inside the canvas as a parent to other widgets in it
inner_frame = tk.Frame(canvasBlesser)
canvasBlesser.create_window((0,0), window=inner_frame, anchor="nw")
```

Use this inner_frame as a parent to place the widgets just as usual to be seen in the canvas.

The line canvasBlesser.configure(yscrollcommand=vbar.set) makes it so that whenever the view of the canvas is changed, it updates the scrollbar's value.

Title: Scrollbar in canvas

Body:
I want to put a scrollbar in a canvas inside a Frame with tkinter. I can see my scrollbar but she don't work. I don't anderstant why, here is my code.

    labelBlesser = tk.Label(self.fen, text='Rajouter', font=fontLabel)
    labelBlesser.configure(background='white')
    labelBlesser.place(relx=0.7, rely=0.40, anchor='center')

    frameBlesser = tk.Frame(self.fen)

    vbar = tk.Scrollbar(frameBlesser, orient='vertical')
    vbar.pack(side='right', fill='y')
    canvasBlesser = tk.Canvas(frameBlesser)
    vbar.config(command=canvasBlesser.yview)

    frameBlesser.place(relx=0.7, rely=0.65, anchor='center')

    for _ in range(3):
        self.listeBlesser.append(tk.Label(canvasBlesser, text='Blesse {}:'.format(self.nombreBlesserAjouter + 1)))
        self.listeBlesser.append(tk.Entry(canvasBlesser, font=fontEntry))

    self.refreshListeBlesser()
    canvasBlesser.pack()

def refreshListeBlesser(self):
    for i, lab in enumerate(self.listeBlesser):
        lab.place(x=10, y=i*70+13)

thank you for your help :)

Body:
You need to bind the canvas and the scrollbar together. Also, you need to create a frame inside of the canvas using canvasBlesser.create_window so that you can place stuff inside the frame as usual.

frameBlesser = tk.Frame(self.fen)
vbar = tk.Scrollbar(frameBlesser, orient='vertical')
vbar.pack(side='right', fill='y')
canvasBlesser = tk.Canvas(frameBlesser)
# adding the side and fill for packing canvas in the frame
canvasBlesser.pack(side='left', fill='both')

# connecting the canvas and scrollbar together
vbar.config(command=canvasBlesser.yview)
canvasBlesser.configure(yscrollcommand=vbar.set)

# placing a frame inside the canvas as a parent to other widgets in it
inner_frame = tk.Frame(canvasBlesser)
canvasBlesser.create_window((0,0), window=inner_frame, anchor="nw")

Use this inner_frame as a parent to place the widgets just as usual to be seen in the canvas.

The line canvasBlesser.configure(yscrollcommand=vbar.set) makes it so that whenever the view of the canvas is changed, it updates the scrollbar's value.


问:
Maximum number of subarrays having equal sum
I was asked this question in one of my interview. Given an array of integers (with both positive and negative values) we need to find the maximum number of disjoint subarrays having equal sum.

Example :

Input : [1, 2, 3]
Output : 2 {since we have at most 2 subarrays with sum = 3 i.e. [1, 2],[3]}

Input: [2 2 2 -2]
Output : 2 {two subarrays each with sum = 2 i.e. [2],[2, 2, -2]}

My Approach

First approach that came to my mind was to find the prefix sum array and then taking each element (prefix[i]) as target finding the number of subarrays with sum = prefix[i] .

But this failed in the case of negative numbers. How to handle the negative cases?

EDIT Complete array must be covered with these subarrays. That is why in example 2 we get 2 as output and not 3 ([2],[2],[2]).

答:
First, assuming that they can be non-consecutive elements

Probably there is not efficient algorithm (if so, P=NP), then, simply check all possible combinations (partitions).

If partitions is a function returning all partitions given a set, then your problem is solved with:

```<code>static Optional<List<List<Integer>>> maximumSubarraysEqSum(List<Integer> xs) {
  return
    // all indexes partitions
    partitions(IntStream.range(0, xs.size()).mapToObj(x -> x).collect(toList()))
    // with all groups with same sum
    .stream().filter(zs -> zs.stream().mapToInt(ys -> ys.stream().mapToInt(xs::get).sum()).distinct().count() == 1L)
    // sorting by size desc
    .sorted((zs, ys) -> Integer.compare(ys.size(), zs.size()))
    // first (or all with same size if you want, ...)
    .findFirst()
    // map indexes to values
    .map(zs -> zs.stream().map(ys -> ys.stream().map(xs::get).collect(toList())).collect(toList()));
}
</code>```

running

```<code>public static void main(String... args) {
    System.out.println("    " + maximumSubarraysEqSum(List.of(1, 2, 3)));
    System.out.println("    " + maximumSubarraysEqSum(List.of(2, 2, 2, -2)));
    System.out.println("    " + maximumSubarraysEqSum(List.of(3, 4)));
}
</code>```

the output is

```<code>Optional[[[1, 2], [3]]]
Optional[[[2, 2, -2], [2]]]
Optional[[[3, 4]]]
</code>```

Second, assuming they must be consecutive elements

The first subarray set what sum is possible, then for every possible "first sum" we check the number of groups

```<code>static int maxSubarrayEqSum(List<Integer> xs) {
    // possible sizes for the first subarray
    return IntStream.range(1, xs.size() + 1)
            // with that sum count (if exists) how many subarrays match
            .map(sz -> countMaxSubArrayEqSum(0, xs, xs.stream().limit(sz).mapToInt(x -> x).sum()))
            // get the maximum number
            .max()
            .getAsInt();
}
</code>```

counting the maximum subarrays is get the first possible sum

```<code>static int countMaxSubArrayEqSum(int from, List<Integer> xs, int sz) {
    int acc = 0;
    for(int i = from; i < xs.size(); i++) {
        acc += xs.get(i);
        if(acc == sz) {
            if(i == xs.size() - 1)
                return 1;
            int count = countMaxSubArrayEqSum(i + 1, xs, sz);
            if(count > 0)
                return count + 1;
        }
    }
    return 0;
}
</code>```

Optimal solution for consecutive sequences O(n^2)

Instead backtracking, we can get the maxSplit value (maximum of groups) checking if xs can be divided by |xs|, |xs|-1, |xs|-2, ..., 1 groups.

```<code>static int maxSplit(int [] xs) {

    // sum all
    int S = 0;
    for(int i = 0; i < xs.length; i++)
        S += xs[i];

    // try every possible number of groups
    for(int i = xs.length; i > 1; i--)
        if(S % i == 0 && maxSplitFit(xs, i, S / i))
            return i;

    return 1;
}
</code>```

xs can be divided into k groups if we can use a voracious strategy

```<code>static boolean maxSplitFit(int [] xs, int k, int s) {

    int groupsCount = 1;
    int acc = 0;

    // look for (not final) groups summing S/k
    int i = 0;
    while(i < xs.length - 1 && groupsCount < k) {
        acc += xs[i];
        if ((s == 0 && acc == 0) // divide by 0
         || (s != 0 && s * groupsCount == acc)) // S/k
            groupsCount++;
        i++;
    }

    // if there are not enough groups then it is not possible
    if(groupsCount != k)
        return false;

    // the last group must contains all remaining elements
    while(i < xs.length)
        acc += xs[i++];

    // S/k for every group
    return s * k == acc;
}
</code>```

Aside

A possible function to get all partitions could be

```<code>static <T> List<List<List<T>>> partitions(List<T> set) {
    // last element
    T element = set.get(set.size() - 1);

    if (set.size() == 1)
        return singletonList(singletonList(singletonList(element)));

    List<List<List<T>>> current = new ArrayList<>();

    // it could be in any of previous groups or in a new one

    // add on every previous
    for (List<List<T>> p : partitions(set.subList(0, set.size() - 1))) {
        // every candidate group to place
        for (int i = 0; i < p.size(); i++) {
            List<List<T>> b = new ArrayList<>(p);
            b.add(i, new ArrayList<>(b.remove(i)));
            b.get(i).add(element);
            current.add(b);
        }
        // add singleton
        List<List<T>> b = new ArrayList<>(p);
        b.add(singletonList(element));
        current.add(b);
    }

    return current;
}
</code>```

Body:
First, assuming that they can be non-consecutive elements

Probably there is not efficient algorithm (if so, P=NP), then, simply check all possible combinations (partitions).

If partitions is a function returning all partitions given a set, then your problem is solved with:

static Optional<List<List<Integer>>> maximumSubarraysEqSum(List<Integer> xs) {
  return
    // all indexes partitions
    partitions(IntStream.range(0, xs.size()).mapToObj(x -> x).collect(toList()))
    // with all groups with same sum
    .stream().filter(zs -> zs.stream().mapToInt(ys -> ys.stream().mapToInt(xs::get).sum()).distinct().count() == 1L)
    // sorting by size desc
    .sorted((zs, ys) -> Integer.compare(ys.size(), zs.size()))
    // first (or all with same size if you want, ...)
    .findFirst()
    // map indexes to values
    .map(zs -> zs.stream().map(ys -> ys.stream().map(xs::get).collect(toList())).collect(toList()));
}

running

public static void main(String... args) {
    System.out.println("    " + maximumSubarraysEqSum(List.of(1, 2, 3)));
    System.out.println("    " + maximumSubarraysEqSum(List.of(2, 2, 2, -2)));
    System.out.println("    " + maximumSubarraysEqSum(List.of(3, 4)));
}

the output is

Optional[[[1, 2], [3]]]
Optional[[[2, 2, -2], [2]]]
Optional[[[3, 4]]]

Second, assuming they must be consecutive elements

The first subarray set what sum is possible, then for every possible "first sum" we check the number of groups

static int maxSubarrayEqSum(List<Integer> xs) {
    // possible sizes for the first subarray
    return IntStream.range(1, xs.size() + 1)
            // with that sum count (if exists) how many subarrays match
            .map(sz -> countMaxSubArrayEqSum(0, xs, xs.stream().limit(sz).mapToInt(x -> x).sum()))
            // get the maximum number
            .max()
            .getAsInt();
}

counting the maximum subarrays is get the first possible sum

static int countMaxSubArrayEqSum(int from, List<Integer> xs, int sz) {
    int acc = 0;
    for(int i = from; i < xs.size(); i++) {
        acc += xs.get(i);
        if(acc == sz) {
            if(i == xs.size() - 1)
                return 1;
            int count = countMaxSubArrayEqSum(i + 1, xs, sz);
            if(count > 0)
                return count + 1;
        }
    }
    return 0;
}

Optimal solution for consecutive sequences O(n^2)

Instead backtracking, we can get the maxSplit value (maximum of groups) checking if xs can be divided by |xs|, |xs|-1, |xs|-2, ..., 1 groups.

static int maxSplit(int [] xs) {

    // sum all
    int S = 0;
    for(int i = 0; i < xs.length; i++)
        S += xs[i];

    // try every possible number of groups
    for(int i = xs.length; i > 1; i--)
        if(S % i == 0 && maxSplitFit(xs, i, S / i))
            return i;

    return 1;
}

xs can be divided into k groups if we can use a voracious strategy

static boolean maxSplitFit(int [] xs, int k, int s) {

    int groupsCount = 1;
    int acc = 0;

    // look for (not final) groups summing S/k
    int i = 0;
    while(i < xs.length - 1 && groupsCount < k) {
        acc += xs[i];
        if ((s == 0 && acc == 0) // divide by 0
         || (s != 0 && s * groupsCount == acc)) // S/k
            groupsCount++;
        i++;
    }

    // if there are not enough groups then it is not possible
    if(groupsCount != k)
        return false;

    // the last group must contains all remaining elements
    while(i < xs.length)
        acc += xs[i++];

    // S/k for every group
    return s * k == acc;
}

Aside

A possible function to get all partitions could be

static <T> List<List<List<T>>> partitions(List<T> set) {
    // last element
    T element = set.get(set.size() - 1);

    if (set.size() == 1)
        return singletonList(singletonList(singletonList(element)));

    List<List<List<T>>> current = new ArrayList<>();

    // it could be in any of previous groups or in a new one

    // add on every previous
    for (List<List<T>> p : partitions(set.subList(0, set.size() - 1))) {
        // every candidate group to place
        for (int i = 0; i < p.size(); i++) {
            List<List<T>> b = new ArrayList<>(p);
            b.add(i, new ArrayList<>(b.remove(i)));
            b.get(i).add(element);
            current.add(b);
        }
        // add singleton
        List<List<T>> b = new ArrayList<>(p);
        b.add(singletonList(element));
        current.add(b);
    }

    return current;
}


问:
How does cassandra handle update request under the hood?
I am trying to understand the storage mechanism of cassandra under the hood

From reading the official doc it seems like

write request write to mutable memtable

when memtable gets too large, its written to sstable

so I have the following question

is memtable durable?

if there is heavy update qps does it mean that there is going to be multiple versions of stale data in both memtable and sstable such that read latency can increase? how does cassandra get the latest data? and how is multiple version of data stored?

if there is heavy update qps does this mean there is alot of tombstone?

答:
is memtable durable?

There is the memtable which is flushed to disk based on size / a few other settings, but at the point the write is accepted - it is not durable in the memtable.
There is also an entry placed in the commitlog which by default will flush every 10 seconds. (so on RF 3, you would expect a flush every 3.33 seconds). The flushing of the commitlog makes it durable to that specific node. To entirely lose the write before this flush has occurred would require all replicas to have failed before any of them had performed a commit log flush. As long as 1 of them flushed, it would be durable.

if there is heavy update qps does it mean that there is going to be multiple versions of stale data in both memtable and sstable such that read latency can increase?

In terms of the memtable, no there will not be stale data. In terms of the SSTables on disk, yes, there can be multiple versions of a record as it is updated over time which would lead to an increase in read latencies. A good metric to look at is the SSTablesPerRead metric which will give you the histogram of how many SSTables are being accessed per DB Table for the queries you run. The p95 or higher is the main value to look at, these will be the scenarios that will be causing slowness.

how does cassandra get the latest data? and how is multiple version of data stored?

During the read of the data, it will use the read path (bloom filters, partition summary etc) and read all versions of the row - and discard the parts which are not needed, before returning the records to the calling application. The multiple versions of the row is a facet of it existing in more than 1 sstable.

Part of the role of compaction is to manage this scenario and to bring together the multiple copies, older and newer versions of a record, and writing out new SStables which only retain the newer version. (and the SSTables it compacted together are removed).

if there is heavy update qps does this mean there is alot of tombstone?

This depends on the type of update, for most normal updates - no, this does not generate tombstones. Updates on list collection types though can and will generate tombstones. If you are issuing deletions, then yes, it will generate tombstones.

If you are going to be running a scenario of heavy updates, then I would recommend considering LeveledCompactionStrategy instead of a default SizeTieredCompactionStrategy - it is likely to provide you better read performance, but at a higher compaction IO cost.


问:
Syntax Error: unexpected $end when using if/else if?
I'm getting an error from one of my controller classes and I can't figure out why.  The error is:

```<code>SyntaxError in TermsController#show, syntax error, unexpected $end, expecting keyword_end
</code>```

Here is terms_controller.rb:

```<code>class TermsController < ApplicationController

    def show
        @term = Term.find(params[:id])
        if @term.id == 1
            @title = "Fall"
        else if @term.id == 2
            @title = "Winter"
        else if @term.id == 3
            @title = "Spring"
        else if @term.id == 4
            @title = "Summer"
        end
    end
end
</code>```

My show page currently just consists of:

```<code><h1> <%= @title %> </h1>
</code>```

It's probably something small that I'm just missing - thanks for your help!

答:
The issue that there are not enough end keywords and it found $end (the token representing the end of the file) before it could find what it was looking for -- another end. (The parser token for the end keyword is either "keyword_end" or "Kend", depending upon ruby version.)

Each if expression requires a matching end keyword.

To get around this, use elsif instead of else if. It is part of the same if construct and does not require a matching end (only the if requires the matching end).

```<code>   if x == 1
     "1"
   elsif x == 2
     "2"
   else
     "else"
   end
</code>```

Another option is case which works well if all branches check the same conditional operand (x in this case):

```<code>   case x
     when 1 then "1"
     when 2 then "2"
     else "else"
   end
</code>```

If you do want to use else if (remember, each if starts a new if conditional construct) then make sure close each block that a if opens. I have indented the code to show this point better.

```<code>   if x == 1
     "1"
   else
     if x == 2
       "2"
     else
       "else"
     end
   end
</code>```

Happy coding.

For the pedantic: there is also another form of if, which is expr if cond, which doesn't have a matching end as part of the syntax and the rules talked about above do not apply to it.

In addition, if and case are just expressions in Ruby, so it might be more idiomatically written like this

```<code>@term = Term.find(params[:id])
@title = case @term.id
   when 1 then "Fall"
   when 2 then "Winter"
   when 3 then "Spring"
   when 4 then "Summer"
   else "Invalid Term"
end
</code>```

The if/elsif/end syntax can be used in the same way, but using case avoids the repeated mentioning of @term.id. Another option is to use a Hash to perform this sort of simple mapping -- or the mapping can be encapsulated in a separate method -- but that is covered elsewhere ;-)

Body:
I'm getting an error from one of my controller classes and I can't figure out why.  The error is:

SyntaxError in TermsController#show, syntax error, unexpected $end, expecting keyword_end

Here is terms_controller.rb:

class TermsController < ApplicationController

    def show
        @term = Term.find(params[:id])
        if @term.id == 1
            @title = "Fall"
        else if @term.id == 2
            @title = "Winter"
        else if @term.id == 3
            @title = "Spring"
        else if @term.id == 4
            @title = "Summer"
        end
    end
end

My show page currently just consists of:

 <%= @title %>

It's probably something small that I'm just missing - thanks for your help!

Body:
The issue that there are not enough end keywords and it found $end (the token representing the end of the file) before it could find what it was looking for -- another end. (The parser token for the end keyword is either "keyword_end" or "Kend", depending upon ruby version.)

Each if expression requires a matching end keyword.

To get around this, use elsif instead of else if. It is part of the same if construct and does not require a matching end (only the if requires the matching end).

   if x == 1
     "1"
   elsif x == 2
     "2"
   else
     "else"
   end

Another option is case which works well if all branches check the same conditional operand (x in this case):

   case x
     when 1 then "1"
     when 2 then "2"
     else "else"
   end

If you do want to use else if (remember, each if starts a new if conditional construct) then make sure close each block that a if opens. I have indented the code to show this point better.

   if x == 1
     "1"
   else
     if x == 2
       "2"
     else
       "else"
     end
   end

Happy coding.

For the pedantic: there is also another form of if, which is expr if cond, which doesn't have a matching end as part of the syntax and the rules talked about above do not apply to it.

In addition, if and case are just expressions in Ruby, so it might be more idiomatically written like this

@term = Term.find(params[:id])
@title = case @term.id
   when 1 then "Fall"
   when 2 then "Winter"
   when 3 then "Spring"
   when 4 then "Summer"
   else "Invalid Term"
end

The if/elsif/end syntax can be used in the same way, but using case avoids the repeated mentioning of @term.id. Another option is to use a Hash to perform this sort of simple mapping -- or the mapping can be encapsulated in a separate method -- but that is covered elsewhere ;-)


问:
nested array object property return undefined typeError in react redux
i want to show the post detail in frontend. my api is showing the postdetail like below captured in postman:

```<code>"message": "Posts fetched successfully!",
    "posts": {
        "_id": "61f05f676793d49f466e7aaa",
        "title": "Liberal Arts Student Sample",
        "content": "The three-page.",
        "creator": {
            "_id": "61cd99efa0b8d616a7a53ce1",
            "createdAt": "2021-12-30T11:37:19.041Z",
            "updatedAt": "2022-01-06T14:35:48.801Z",
            "__v": 0,
            "bio": "user bio",
            "name": "username"
        },
        "Comments": [],
        "created": "2022-01-25T20:36:55.095Z",
        "createdAt": "2022-01-25T20:36:55.096Z",
        "updatedAt": "2022-01-25T20:36:55.096Z",
        "__v": 0
    }
}
</code>```

i want to exhibit this post detail in frontend and here is the code:

```<code>export default function PostDetail() {
    const { postId } = useParams();
    const post = useSelector((state) => state.post)
    const dispatch = useDispatch();
    const { title, content,creator, created } = post;
    const fetchPostDetail = async (id) => {
        const response = await axios.get(`http://localhost:5000/api/articles/post/${id}`, { post })
            .catch(err => {
                console.log(err);
            })
        dispatch(selectedPost(response.data.posts));
              }

    useEffect(() => {
        fetchPostDetail(postId)
    }, [])

    return (
        <div>
            <h1>Post Detail</h1>
            <div>
                <h2>{title}</h2>
                <i>posted in {created}</i>
                 <li>Created by {creator.map((m,i)=>(
<b key={i}>{m.name}</b>
                 ))}</li>
                <p>{content}</p>
            </div>
        </div>
    );
}
</code>```

There are three errors:

Uncaught TypeError: creator is undefined

The above error occurred in the  component:

Uncaught TypeError: creator is undefined

if i mute the

Created by {creator.map((m,i)=>(
{m.name}
                 ))}
 then it shows the post detail without post author name. but i want to show the author name.

how can i solve that?
thank you in advance

答:
For the first time when the component will mount, the value of the creator will be undefined. You need to add a check before getting the nested value.

```<code><div>
  <h1>Post Detail </h1>
  <div>
    <h2>{title} </h2>
    <i> posted in {created} </i>
    {creator && <li> Created by :{creator.name}</li>}
    <p> {content} </p>
  </div>
</div>
</code>```

Note: One thing more, Creator is not an array. it is an Object. So you cant map the object. In case it is an array, You have to make above check in that case too.

Body:
i want to show the post detail in frontend. my api is showing the postdetail like below captured in postman:

"message": "Posts fetched successfully!",
    "posts": {
        "_id": "61f05f676793d49f466e7aaa",
        "title": "Liberal Arts Student Sample",
        "content": "The three-page.",
        "creator": {
            "_id": "61cd99efa0b8d616a7a53ce1",
            "createdAt": "2021-12-30T11:37:19.041Z",
            "updatedAt": "2022-01-06T14:35:48.801Z",
            "__v": 0,
            "bio": "user bio",
            "name": "username"
        },
        "Comments": [],
        "created": "2022-01-25T20:36:55.095Z",
        "createdAt": "2022-01-25T20:36:55.096Z",
        "updatedAt": "2022-01-25T20:36:55.096Z",
        "__v": 0
    }
}

i want to exhibit this post detail in frontend and here is the code:

export default function PostDetail() {
    const { postId } = useParams();
    const post = useSelector((state) => state.post)
    const dispatch = useDispatch();
    const { title, content,creator, created } = post;
    const fetchPostDetail = async (id) => {
        const response = await axios.get(`http://localhost:5000/api/articles/post/${id}`, { post })
            .catch(err => {
                console.log(err);
            })
        dispatch(selectedPost(response.data.posts));
              }

    useEffect(() => {
        fetchPostDetail(postId)
    }, [])

    return (

Post Detail

{title}

                posted in {created}

Created by {creator.map((m,i)=>(
{m.name}
                 ))}

{content}

    );
}

There are three errors:

Uncaught TypeError: creator is undefined

The above error occurred in the  component:

Uncaught TypeError: creator is undefined

if i mute the

Created by {creator.map((m,i)=>(
{m.name}
                 ))}
 then it shows the post detail without post author name. but i want to show the author name.

how can i solve that?
thank you in advance

Body:
For the first time when the component will mount, the value of the creator will be undefined. You need to add a check before getting the nested value.

<div>
  <h1>Post Detail </h1>
  <div>
    <h2>{title} </h2>
    <i> posted in {created} </i>
    {creator && <li> Created by :{creator.name}</li>}
    <p> {content} </p>
  </div>
</div>

Note: One thing more, Creator is not an array. it is an Object. So you cant map the object. In case it is an array, You have to make above check in that case too.


问:
Access Laravel HTTP client status code in catch block
I need to be able to access the status code and response time in my catch block as not every error from the HTTP client results in no status code.

I've tried the following:

/**
* HTTP type
*
* @return object
*/
public function checkWithHttp($url, $timeout)
{
    try {
        $startResponseTime = microtime(true);
        $response = Http::withHeaders([
            'User-Agent' => 'Mozilla/5.0+(compatible; DomainMonitor/2.0; https://domain-monitor.io/)'
        ])->timeout($timeout)->get($url);
        $stopResponseTime = microtime(true);

        $responseTime = ($stopResponseTime - $startResponseTime) * 1000;

        return [
            'response_time' => round($responseTime),
            'code' => $response->getStatusCode(),
            'ok' => $response->ok(),
            'json' => $response->json(),
            'headers' => $response->headers()
        ];
    } catch (\Exception $e) {
        return [
            'response_time' => round($responseTime),
            'code' => $response->getStatusCode(),
            'ok' => false,
            'json' => null,
            'headers' => null
        ];
    }
}
```

But the results in $responseTime being undefined.

答:
Try this way

try {
    $startResponseTime = microtime(true);
    $response = Http::withHeaders([
        'User-Agent' => 'Mozilla/5.0+(compatible; DomainMonitor/2.0; https://domain-monitor.io/)'
    ])->timeout($timeout)->get($url);
    $stopResponseTime = microtime(true);

    $responseTime = ($stopResponseTime - $startResponseTime) * 1000;

    if($response->successful()){
        return [
            'response_time' => round($responseTime),
            'code' => $response->getStatusCode(),
            'ok' => $response->ok(),
            'json' => $response->json(),
            'headers' => $response->headers()
        ];

    }else{

        return [
            'response_time' => round($responseTime),
            'code' => $response->getStatusCode(),
            'ok' => false,
            'json' => null,
            'headers' => null
        ];

    }

} catch (\Exception $e) {
    return [
        'response_time' => 0,
        'code' => 0,
        'ok' => false,
        'json' => null,
        'headers' => null,
        'message' => $e->getMessage(), //get exception message
    ];
}
```

Body:
I need to be able to access the status code and response time in my catch block as not every error from the HTTP client results in no status code.

I've tried the following:

/**
* HTTP type
*
* @return object
*/
public function checkWithHttp($url, $timeout)
{
    try {
        $startResponseTime = microtime(true);
        $response = Http::withHeaders([
            'User-Agent' => 'Mozilla/5.0+(compatible; DomainMonitor/2.0; https://domain-monitor.io/)'
        ])->timeout($timeout)->get($url);
        $stopResponseTime = microtime(true);

        $responseTime = ($stopResponseTime - $startResponseTime) * 1000;

        return [
            'response_time' => round($responseTime),
            'code' => $response->getStatusCode(),
            'ok' => $response->ok(),
            'json' => $response->json(),
            'headers' => $response->headers()
        ];
    } catch (\Exception $e) {
        return [
            'response_time' => round($responseTime),
            'code' => $response->getStatusCode(),
            'ok' => false,
            'json' => null,
            'headers' => null
        ];
    }
}

But the results in $responseTime being undefined.


问:
Get how object is named from the object
Is is posible to get how you named object from the object

For example:

```<code>public static void Main(string[] args)
{
    Test testVariable = new Test();
}
</code>```
```<code>class Test
{
    public Test()
    {
         Console.WriteLine(GetName());
    }
}
</code>```

would be testVariable

答:
From your code example, it looks like you want the name of the assigned variable. This is not possible without specific requirements on the caller.

There is no real robust solution in C# for this.

The best you can do is using the nameof expression:

```<code>public static void Main(string[] args)
{
    Test testVariable = new Test(nameof(testVariable));
}

class Test
{
    public Test(string variableName)
    {
        Console.WriteLine(variableName);
    }
}
</code>```

However, this will add little benefit. As you can see, it is a 'static' solution in that it requires to pass in the name of the variable at compile time. Using nameof makes this 'refactor friendly' and gives you basic compile time checking:

```<code>public static void Main(string[] args)
{
    Test testVariable = new Test(nameof(tstVariable)); // compiler error
}
</code>```

It opens scenarios like this:

```<code>public static void Main(string[] args)
{
    Test testVariable1 = new Test(nameof(testVariable1));
    Test testVariable2 = new Test(nameof(testVariable2));
}
</code>```

But as mentioned, this doesn't add very much value, and it's still error prone. For example, nothing stops you from doing something like this:

```<code>public static void Main(string[] args)
{
    Test testVariable1 = new Test(nameof(testVariable1));
    Test testVariable2 = new Test(nameof(testVariable1)); // oops, should be testVariable2
}
</code>```

Also, as @derpirscher points out, it doesn't stop you from things like this:

```<code>Test testVariable1 = new Test(nameof(testVariable1));
Test testVariable2 = testVariable1;
testVariable2.Test(); // still outputs "testVariable1"

</code>```

Title: Get how object is named from the object

Body:
Is is posible to get how you named object from the object

For example:

public static void Main(string[] args)
{
    Test testVariable = new Test();
}

class Test
{
    public Test()
    {
         Console.WriteLine(GetName());
    }
}

would be testVariable

Body:
From your code example, it looks like you want the name of the assigned variable. This is not possible without specific requirements on the caller.

There is no real robust solution in C# for this.

The best you can do is using the nameof expression:

public static void Main(string[] args)
{
    Test testVariable = new Test(nameof(testVariable));
}

class Test
{
    public Test(string variableName)
    {
        Console.WriteLine(variableName);
    }
}

However, this will add little benefit. As you can see, it is a 'static' solution in that it requires to pass in the name of the variable at compile time. Using nameof makes this 'refactor friendly' and gives you basic compile time checking:

public static void Main(string[] args)
{
    Test testVariable = new Test(nameof(tstVariable)); // compiler error
}

It opens scenarios like this:

public static void Main(string[] args)
{
    Test testVariable1 = new Test(nameof(testVariable1));
    Test testVariable2 = new Test(nameof(testVariable2));
}

But as mentioned, this doesn't add very much value, and it's still error prone. For example, nothing stops you from doing something like this:

public static void Main(string[] args)
{
    Test testVariable1 = new Test(nameof(testVariable1));
    Test testVariable2 = new Test(nameof(testVariable1)); // oops, should be testVariable2
}

Also, as @derpirscher points out, it doesn't stop you from things like this:

Test testVariable1 = new Test(nameof(testVariable1));
Test testVariable2 = testVariable1;
testVariable2.Test(); // still outputs "testVariable1"


问:
How can I attach a SQLite ID to a Spinner object in android?
I want to pull a couple columns from a database and add those to the spinner, but I want the _id of the row to be hidden in there somewhere too.  Take partial sample code below for example:

```<code>    public void fillProfileSpinner()
    {
        String query = "SELECT _id,fruit_type,weight,colour FROM fruits;";
        SQLiteDatabase profileDatabase = fruitCakes.database.getReadableDatabase();
        Cursor cursor = profileDatabase.rawQuery(query, null);
        startManagingCursor(cursor);
        try {
            cursor.moveToFirst();
            do
            {
                String fruitType = cursor.getString(cursor.getColumnIndex("fruit_type"));
                double weight = cursor.getString(cursor.getColumnIndex("weight"));
                String colour = cursor.getInt(cursor.getColumnIndex("colour"));
                fruitAdapter.add(colour + " " + weight + " " + fruit_type);
            }
            while(cursor.moveToNext());
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        cursor.deactivate();
        cursor.close();
        profileDatabase.close();
}
</code>```

I believe this is what I'm looking for, however I find it very confusing:
Android Spinners, say I pull spinner selections from SQL, can I also add their SQL _id's to the spinner values?

How can I get the _id column in there somewhere, so that is accessible from some method in the spinner object?

答:
I cannot think of a scenario where your _ID value is not already directly available to you or derivable via the position:

In onListItemClick() of a ListActivity, it is the id parameter

In onItemClick() of a OnItemClickListener, it is the id parameter

Anywhere else that you have a position (e.g., getView() of a ListAdapter), call moveToPosition() on your Cursor and retrieve your _ID that way

Body:
I want to pull a couple columns from a database and add those to the spinner, but I want the _id of the row to be hidden in there somewhere too.  Take partial sample code below for example:

    public void fillProfileSpinner()
    {
        String query = "SELECT _id,fruit_type,weight,colour FROM fruits;";
        SQLiteDatabase profileDatabase = fruitCakes.database.getReadableDatabase();
        Cursor cursor = profileDatabase.rawQuery(query, null);
        startManagingCursor(cursor);
        try {
            cursor.moveToFirst();
            do
            {
                String fruitType = cursor.getString(cursor.getColumnIndex("fruit_type"));
                double weight = cursor.getString(cursor.getColumnIndex("weight"));
                String colour = cursor.getInt(cursor.getColumnIndex("colour"));
                fruitAdapter.add(colour + " " + weight + " " + fruit_type);
            }
            while(cursor.moveToNext());
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        cursor.deactivate();
        cursor.close();
        profileDatabase.close();
}

I believe this is what I'm looking for, however I find it very confusing:
Android Spinners, say I pull spinner selections from SQL, can I also add their SQL _id's to the spinner values?

How can I get the _id column in there somewhere, so that is accessible from some method in the spinner object?


问:
React router not working //Even after following the documentation
So i was trying react for first time, i followed the documentation and at router dom i got stuck
When i use Switch is says "export 'Switch' (imported as 'Switch') was not found in 'react-router-dom'" So in short my router isn't working and i want a way to make it work, also it is the latest version of react as i just made this project yesterday</p>
```<code>import logo from './logo.svg';
import './App.css';
import Navbar from './components/Navbar';
import Form from './components/Form';
import Sus from './components/Sus';
import React from "react";
import {
  BrowserRouter as Router,
  // Switch,
  Routes,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (
    <Router>
    <div className="">
      <Navbar title="Sus" main="SusHome" about="SusAbout"/>
      <div className="container my-5">

      <Routes>
          <Route path="/" component={Form}/>
          <Route path="/sus" component={Sus} />
        </Routes>
      </div>
    </div>
    </Router>
  );
}

export default App;
</code>```

答:
To render your components you have to pass like this:

```<code><Route path="/" element={<Form/>}/>
<Route path="/sus" element={<Sus/>} />
</code>```

The documentation react-router-dom  version 6 is this.

Body:
So i was trying react for first time, i followed the documentation and at router dom i got stuck
When i use Switch is says "export 'Switch' (imported as 'Switch') was not found in 'react-router-dom'" So in short my router isn't working and i want a way to make it work, also it is the latest version of react as i just made this project yesterday

import logo from './logo.svg';
import './App.css';
import Navbar from './components/Navbar';
import Form from './components/Form';
import Sus from './components/Sus';
import React from "react";
import {
  BrowserRouter as Router,
  // Switch,
  Routes,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (
    <Router>

      <Navbar title="Sus" main="SusHome" about="SusAbout"/>

      <Routes>
          <Route path="/" component={Form}/>
          <Route path="/sus" component={Sus} />
        </Routes>

    </Router>
  );
}

export default App;

Body:
To render your components you have to pass like this:

<Route path="/" element={<Form/>}/>
<Route path="/sus" element={<Sus/>} />

The documentation react-router-dom  version 6 is this.


问:
Limited number of break lines in text in PHP
Assume a string is like

```<code>Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks)

Section 4 (after 4 line breaks)

Section 5 (after 1 line break)

</code>```

My intention is to only allow N number of breaks and replace the other ones with SPACE in PHP. For example, if N=3 then the text above would be outputed like:

```<code>Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks) Section 4 (after 4 line breaks) Section 5 (after 1 line break)
</code>```

My code is below but I am looking for a better way:

```<code>function limitedBreaks($str = '', $n = 5)
{
    $str = nl2br($str);
    $chars = str_split($str);
    $counter = 0;
    foreach ($chars as $key => $char) {
        if ($char == "<br/>")
            if ($counter > $n) {
                $chars[$key] = ' ';
            } else {
                $counter += 1;
            }
    }

    return implode($chars, ' ');

}
</code>```

答:
This really is a job better suited for regex than exploding and iterating.

```<code>$str = preg_replace('~\v+~', "\n\n", $str);
</code>```

Here \v+ matches any number of vertical spaces, substituted with two \n newlines. You will get a standard one line gap between your content (non-linebreak-only) lines. This results in:

```<code>Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks)

Section 4 (after 4 line breaks)

Section 5 (after 1 line break)
</code>```

If you want to only target more than N breaks, use e.g. \v{4,}, assuming EOL is \n, to normalize all instances of 4 or more newlines. If your file uses Windows EOL (\r\n), be aware that you need to double it up, or use (\r\n|\n){4,}, since \r and \n each are one match of \v.

That's the basic idea. Seeing as you want to replace 4+ newlines with horizontal space, merging the lines instead of normalizing line break quantity, you would simply:

```<code>$str = preg_replace('~(\r\n|\n){4,}~', " ", $str);
</code>```

This would give you:

```<code>Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks) Section 4 (after 4 line breaks)

Section 5 (after 1 line break)
</code>```

Here the gap with 4 or more EOLs was substituted with space and merged with the preceding line. The rest of the "acceptably spaced" lines are still in their places.

However it seems that you want to merge all subsequent rows into a single line after any gap of 4+ EOLs. Is that really the requirement? The first example I posted is a fairly standard operation for normalizing content with irregular linebreaks; especially "level items" like section headings!

OP: thanks for explaining your use case, makes sense. This can be regex-ed without loops:

```<code>$str = preg_replace_callback('~(\r\n|\n){4,}(?<therest>.+)~s', function($match) {
    return ' ' . preg_replace('~\v+~', ' ', $match['therest']);
}, $str);
</code>```

Here we capture (as named group therest) all the content that follows four or more linebreaks using preg_replace_callback, and inside the callback we preg_replace all vertical spaces in "the rest" with a single horizontal space. This results in:

```<code>Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks) Section 4 (after 4 line breaks) Section 5 (after 1 line break) Section 17 after a hundred bundred line breaks"
</code>```

For convenience, here's the regex above wrapped in a function:

```<code>function fuse_breaks(string $str): string {
    $str = preg_replace_callback('~(\r\n|\n){4,}(?<therest>.+)~s', function($match) {
        return ' ' . preg_replace('~\v+~', ' ', $match['therest']);
    }, $str);
    return $str;
}

// Usage:
$fused_text = fuse_breaks($source_text);
</code>```

Body:
Assume a string is like

Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks)

Section 4 (after 4 line breaks)

Section 5 (after 1 line break)

My intention is to only allow N number of breaks and replace the other ones with SPACE in PHP. For example, if N=3 then the text above would be outputed like:

Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks) Section 4 (after 4 line breaks) Section 5 (after 1 line break)

My code is below but I am looking for a better way:

function limitedBreaks($str = '', $n = 5)
{
    $str = nl2br($str);
    $chars = str_split($str);
    $counter = 0;
    foreach ($chars as $key => $char) {
        if ($char == "
")
            if ($counter > $n) {
                $chars[$key] = ' ';
            } else {
                $counter += 1;
            }
    }

    return implode($chars, ' ');

}

Body:
This really is a job better suited for regex than exploding and iterating.

$str = preg_replace('~\v+~', "\n\n", $str);

Here \v+ matches any number of vertical spaces, substituted with two \n newlines. You will get a standard one line gap between your content (non-linebreak-only) lines. This results in:

Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks)

Section 4 (after 4 line breaks)

Section 5 (after 1 line break)

If you want to only target more than N breaks, use e.g. \v{4,}, assuming EOL is \n, to normalize all instances of 4 or more newlines. If your file uses Windows EOL (\r\n), be aware that you need to double it up, or use (\r\n|\n){4,}, since \r and \n each are one match of \v.

That's the basic idea. Seeing as you want to replace 4+ newlines with horizontal space, merging the lines instead of normalizing line break quantity, you would simply:

$str = preg_replace('~(\r\n|\n){4,}~', " ", $str);

This would give you:

Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks) Section 4 (after 4 line breaks)

Section 5 (after 1 line break)

Here the gap with 4 or more EOLs was substituted with space and merged with the preceding line. The rest of the "acceptably spaced" lines are still in their places.

However it seems that you want to merge all subsequent rows into a single line after any gap of 4+ EOLs. Is that really the requirement? The first example I posted is a fairly standard operation for normalizing content with irregular linebreaks; especially "level items" like section headings!

OP: thanks for explaining your use case, makes sense. This can be regex-ed without loops:

$str = preg_replace_callback('~(\r\n|\n){4,}(?<therest>.+)~s', function($match) {
    return ' ' . preg_replace('~\v+~', ' ', $match['therest']);
}, $str);

Here we capture (as named group therest) all the content that follows four or more linebreaks using preg_replace_callback, and inside the callback we preg_replace all vertical spaces in "the rest" with a single horizontal space. This results in:

Section 1

Section 2 (after 1 line break)

Section 3 (after 2 line breaks) Section 4 (after 4 line breaks) Section 5 (after 1 line break) Section 17 after a hundred bundred line breaks"

For convenience, here's the regex above wrapped in a function:

function fuse_breaks(string $str): string {
    $str = preg_replace_callback('~(\r\n|\n){4,}(?<therest>.+)~s', function($match) {
        return ' ' . preg_replace('~\v+~', ' ', $match['therest']);
    }, $str);
    return $str;
}

// Usage:
$fused_text = fuse_breaks($source_text);


问:
Does app server use jwt id token for user identification or is the jwt id token meant to be sent to resource server to be able to identify the user?
Oauth can be used for authentication, authorization and delegation. The Oauth flow eventually results in the the app server receives an access token (and refresh token) and a jwt ID token (openidconnect).

The app server can use the access token to pass it to the resource server to access resources on behalf of the user (delegation).

Does the app server pass the Jwt id token to the resource server to inform the resource server about who the current user is? Or does the app server use the jwt id token to authenticate the user to allow the app server to know who the current user is?

答:
The ID token only proves that the user is authenticated and provides the user 's profile data.  It does not contains any information that can prove that the user really confirms the resource server is allowed to do certain actions on his resource (i.e no OAuth2 scope).

So just passing the ID token to the resource server cannot help it to make the authorisation decision. Even though the resource server may use the ID token to find out what the user is , and then find out what permission does he has , but it still cannot prove the the user really confirm to delegate the app server to do certain actions on his resource. (i.e. I have permission to do something does not mean that I agree you to do it on behalf of me.)

So always pass the access token to the resource server for making authorization decision.

You can also refer to this blog post which also answer your question.


问:
Cannot find module '@nestjs/core' or its corresponding type declarations
Couple of weeks ago I installed NestJS globally on my computer.
Now I'm coming back to that, to start learning.

So I created new project with comand:

```<code>nest new ./
</code>```

It generated all the files, but when I try to run this application with command:

```<code>nest start
</code>```

I expected this template project to start but there are errors with importing paths?
Is this due to version of my installed Nest or something?

Errors on the screen:

Version of my Nest:
7.5.6

Package.json:

```<code>  "dependencies": {
    "@nestjs/common": "^7.6.13",
    "@nestjs/core": "^7.6.13",
    "@nestjs/platform-express": "^7.6.13",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^6.6.6"
  },
  "devDependencies": {
    "@nestjs/cli": "^7.5.6",
    "@nestjs/schematics": "^7.2.7",
    "@nestjs/testing": "^7.6.13",
    "@types/express": "^4.17.11",
    "@types/jest": "^26.0.20",
    "@types/node": "^14.14.31",
    "@types/supertest": "^2.0.10",
    "@typescript-eslint/eslint-plugin": "^4.15.2",
    "@typescript-eslint/parser": "^4.15.2",
    "eslint": "^7.20.0",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-prettier": "^3.3.1",
    "jest": "^26.6.3",
    "prettier": "^2.2.1",
    "supertest": "^6.1.3",
    "ts-jest": "^26.5.2",
    "ts-loader": "^8.0.17",
    "ts-node": "^9.1.1",
    "tsconfig-paths": "^3.9.0",
    "typescript": "^4.1.5"
  },
</code>```

答:
I had the same issue. The following two commands fixed it:

```<code>npm install @nestjs/common
npm install @nestjs/core
</code>```

These commands make sure you are using the lastest versions of those packages.

Sometimes you may also get error: Cannot find module '@nestjs/mapped-types' or its corresponding type declarations.

In that case, do:

```<code>npm install @nestjs/mapped-types
</code>```

Body:
Couple of weeks ago I installed NestJS globally on my computer.
Now I'm coming back to that, to start learning.

So I created new project with comand:

nest new ./

It generated all the files, but when I try to run this application with command:

nest start

I expected this template project to start but there are errors with importing paths?
Is this due to version of my installed Nest or something?

Errors on the screen:

Version of my Nest:
7.5.6

Package.json:

  "dependencies": {
    "@nestjs/common": "^7.6.13",
    "@nestjs/core": "^7.6.13",
    "@nestjs/platform-express": "^7.6.13",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^6.6.6"
  },
  "devDependencies": {
    "@nestjs/cli": "^7.5.6",
    "@nestjs/schematics": "^7.2.7",
    "@nestjs/testing": "^7.6.13",
    "@types/express": "^4.17.11",
    "@types/jest": "^26.0.20",
    "@types/node": "^14.14.31",
    "@types/supertest": "^2.0.10",
    "@typescript-eslint/eslint-plugin": "^4.15.2",
    "@typescript-eslint/parser": "^4.15.2",
    "eslint": "^7.20.0",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-prettier": "^3.3.1",
    "jest": "^26.6.3",
    "prettier": "^2.2.1",
    "supertest": "^6.1.3",
    "ts-jest": "^26.5.2",
    "ts-loader": "^8.0.17",
    "ts-node": "^9.1.1",
    "tsconfig-paths": "^3.9.0",
    "typescript": "^4.1.5"
  },

Body:
I had the same issue. The following two commands fixed it:

npm install @nestjs/common
npm install @nestjs/core

These commands make sure you are using the lastest versions of those packages.

Sometimes you may also get error: Cannot find module '@nestjs/mapped-types' or its corresponding type declarations.

In that case, do:

npm install @nestjs/mapped-types


问:
How to make a box to shrink first and when it reaches a specific size, it drops down to another line of a row?
I have a problem I can't solve which I want to reproduce a behaviour.

This behaviour consists in, per example:

Two divs(div1 and div2) in a flexbox row with flex-wrap, where the div2 shrinks(while you're changing window size) until it reaches a specific width, and only after that, I want it to drop down(or wrap it) from div1.

The only thing I can do to happen is:

when I change window size from the right, it instantly drops below div1 and after that it starts to shrink.

```<code><body>
    <div id="container">
        <div class="item" id="pri"></div>
        <div class="item" id="seg"></div>
    </div>
</body>

/* CSS */

#container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

.item {
    width: 300px;
    height: 200px;
}

.item#pri {
    background-color: red;
}

.item#seg {
    background-color: green;
    width: 600px;
    flex-shrink: 3;
    margin-right: 20px;
}
</code>```

答:
I just learned with your answers. Though I didn't expose my real problem. I have a label with words on it, and next to it I have an input.

What I want to reproduce is the label staying in a specific size, and then the input with a width of 600px shrinking while window browser is getting small, and when it reaches a specific size, it drops under the label.

```<code><label class="item" for="allwords">all these words: </label>
<input class="item" type="text" name="q">
</code>```

I've running so many tests that my css file is all messed up. I've tried to put label and input inside of divs individually, and those divs inside of one div and playing with flexbox(parent / child).

Body:
I have a problem I can't solve which I want to reproduce a behaviour.

This behaviour consists in, per example:

Two divs(div1 and div2) in a flexbox row with flex-wrap, where the div2 shrinks(while you're changing window size) until it reaches a specific width, and only after that, I want it to drop down(or wrap it) from div1.

The only thing I can do to happen is:

when I change window size from the right, it instantly drops below div1 and after that it starts to shrink.

/* CSS */

#container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

.item {
    width: 300px;
    height: 200px;
}

.item#pri {
    background-color: red;
}

.item#seg {
    background-color: green;
    width: 600px;
    flex-shrink: 3;
    margin-right: 20px;
}

Body:
I just learned with your answers. Though I didn't expose my real problem. I have a label with words on it, and next to it I have an input.

What I want to reproduce is the label staying in a specific size, and then the input with a width of 600px shrinking while window browser is getting small, and when it reaches a specific size, it drops under the label.

<label class="item" for="allwords">all these words: </label>
<input class="item" type="text" name="q">

I've running so many tests that my css file is all messed up. I've tried to put label and input inside of divs individually, and those divs inside of one div and playing with flexbox(parent / child).