问:
Have only hours and minutes in durationfield Django
I would like to have a duration field expressed just as hours and minutes.
I post you my code:

views.py

```<code>    log_entry = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q(
        student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft))

    total_flight_hours = log_entry_dual.aggregate(eet=Sum(ExpressionWrapper(
        F('ata') - F('etd'), output_field=IntegerField()), output_field=DurationField()))['eet']
</code>```

Now, total_flight_hours is printed in my template as (for example) 03:00:00 which states for 3 hours.
Since I just need hours and minutes and I don't care about seconds, is there a way to get rid of the seconds?
Thank you very much in advance

答:
I'm not sure how your template is structured and where the hours and minutes are used. If a string would be accepted in your template that django passes to I think this would work:

```<code>from datetime import timedelta

def timedelta_to_hm(td: timedelta) -> str:
    if td.seconds % 60 > 29:
        td += timedelta(seconds=30)
    a = str(td)
    b = a[-8:].lstrip(' ')
    return b[:-3]

timedelta_to_hm(timedelta(days=1, hours=2,minutes=20, seconds=0)) #  '2:20'
timedelta_to_hm(timedelta(hours=26,minutes=20, seconds=0)) #  '2:20'
timedelta_to_hm(timedelta(hours=21,minutes=20, seconds=31)) #  '21:21'
timedelta_to_hm(timedelta(hours=1,minutes=20, seconds=29)) #  '1:20'
timedelta_to_hm(timedelta(hours=1,minutes=20, seconds=31)) #  '1:21'
timedelta_to_hm(timedelta(hours=1,minutes=20, seconds=39)) #  '1:21'
timedelta_to_hm(timedelta(minutes=0, seconds=39)) #  '0:01'
</code>```

Here I'm thinking something like this in your html template, where ctxt is the context with parametrized template data.

```<code><p>We start at
   <time datetime={{ctxt.hours_minutes}}>{{ctxt.hours_minutes}}</time>
   sharp.
</p>
</code>```

Note this drops leading 0s in the hours. If you want a leading 0 you can add one in cases where needed in the function. Also, I'm rounding up at 30 seconds. The default behavior without the round would be to always round down (analogous to integer division).
This also assumes the hours and minutes are going into your template and you're not doing any other calculation on the hours and minutes.

If you want to do other calculations then it's best not to convert to a string and to proceed with calculations to extract the hours and minutes directly. Perhaps using one of the approaches described in another question here.

Body:
I would like to have a duration field expressed just as hours and minutes.
I post you my code:

views.py

    log_entry = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q(
        student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft))

    total_flight_hours = log_entry_dual.aggregate(eet=Sum(ExpressionWrapper(
        F('ata') - F('etd'), output_field=IntegerField()), output_field=DurationField()))['eet']

Now, total_flight_hours is printed in my template as (for example) 03:00:00 which states for 3 hours.
Since I just need hours and minutes and I don't care about seconds, is there a way to get rid of the seconds?
Thank you very much in advance

Body:
I'm not sure how your template is structured and where the hours and minutes are used. If a string would be accepted in your template that django passes to I think this would work:

from datetime import timedelta

def timedelta_to_hm(td: timedelta) -> str:
    if td.seconds % 60 > 29:
        td += timedelta(seconds=30)
    a = str(td)
    b = a[-8:].lstrip(' ')
    return b[:-3]

timedelta_to_hm(timedelta(days=1, hours=2,minutes=20, seconds=0)) #  '2:20'
timedelta_to_hm(timedelta(hours=26,minutes=20, seconds=0)) #  '2:20'
timedelta_to_hm(timedelta(hours=21,minutes=20, seconds=31)) #  '21:21'
timedelta_to_hm(timedelta(hours=1,minutes=20, seconds=29)) #  '1:20'
timedelta_to_hm(timedelta(hours=1,minutes=20, seconds=31)) #  '1:21'
timedelta_to_hm(timedelta(hours=1,minutes=20, seconds=39)) #  '1:21'
timedelta_to_hm(timedelta(minutes=0, seconds=39)) #  '0:01'

Here I'm thinking something like this in your html template, where ctxt is the context with parametrized template data.

<p>We start at
   <time datetime={{ctxt.hours_minutes}}>{{ctxt.hours_minutes}}</time>
   sharp.
</p>

Note this drops leading 0s in the hours. If you want a leading 0 you can add one in cases where needed in the function. Also, I'm rounding up at 30 seconds. The default behavior without the round would be to always round down (analogous to integer division).
This also assumes the hours and minutes are going into your template and you're not doing any other calculation on the hours and minutes.

If you want to do other calculations then it's best not to convert to a string and to proceed with calculations to extract the hours and minutes directly. Perhaps using one of the approaches described in another question here.


来源: stackexchange

问:
Is if(A | B) always faster than if(A || B)?
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

```<code>void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}
</code>```

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

答:
The expression A | B might be faster in a loop that the compiler can optimize to a bitwise or of two vectors.  Another case where | might be slightly more optimized is when the compiler would want to optimize away a branch by combining the two operands with bitmasks.  If the operand on the right is something that might have visible side-effects, the compiler must instead insert a branch to guarantee the correct short-circuiting.

In other situations I can think of, A || B will be as fast or faster, including just about all the ones I can think of where you’re comparing a single pair of operands rather than a vector.  However, those are almost never critical to performance.

ContentLicense: CC BY-SA 4.0

Body:
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?


问:
Clarification on overloading
When the parent class have an add method with 2 parameters, If we add new add method with 3 parameters in child class, shall we call this as over loading?

Thanks in advance.

答:
yep... it is overloading method even if the method is located in the same class.

ps: i assume the new method with three parameters has identical name and return type

ContentLicense: CC BY-SA 3.0

Title: Clarification on overloading


问:
Using bash script to remove from sentence words longer than [x] characters
I have a sentence (array) and I would like to remove from it all words longer than 8 characters.

Example sentence:

var="one two three four giberish-giberish five giberish-giberish six"
```
<p>I would like to get:</p>
<pre class="lang-bash prettyprint-override"><code>var="one two three four five six"
</code>```

So far I'm using this:

echo $var | tr ' ' '\n' | awk 'length($1) <= 6 { print $1 }' | tr '\n ' ' ' ```
Solution above works fine but as you can see I'm replacing space with newline then filtering words and then replacing back newline with space.

I'm pretty sure there must be better and more "elegant" solution without swapping space/newline.
</code>```

答:
This might work for you (GNU sed):

```<code><<<"$var" sed -E 'y/ /\n/;s/..{8}.*\n//mg;y/\n/ /'
</code>```

Translate spaces to newlines.

Remove all lines that are more than 8 characters long.

Translate newlines to spaces.

Body:
I have a sentence (array) and I would like to remove from it all words longer than 8 characters.

Example sentence:

var="one two three four giberish-giberish five giberish-giberish six"

I would like to get:

var="one two three four five six"

So far I'm using this:

echo $var | tr ' ' '\n' | awk 'length($1) <= 6 { print $1 }' | tr '\n ' ' ' ```
Solution above works fine but as you can see I'm replacing space with newline then filtering words and then replacing back newline with space.

I'm pretty sure there must be better and more "elegant" solution without swapping space/newline.

Body:
This might work for you (GNU sed):

<<<"$var" sed -E 'y/ /\n/;s/..{8}.*\n//mg;y/\n/ /'

Translate spaces to newlines.

Remove all lines that are more than 8 characters long.

Translate newlines to spaces.


问:
Visualizing repetitive tasks in Gantt Chart in Google Sheets
I'm trying to make a chart (either with lines or bars) to show periods of time in certain Stages. Using the data below, the closest I've gotten is to try to get a Gantt chart and turn off the color for the start date, only showing the duration. Rather than the duration in days on the x-axis, I'd like it just to be dates (months or years).

(screenshot - Gantt chart example - note the multiple appearances of "Cultivate")

It's close to what I want, but the stage can be reentered multiple times. So I would like those separate Cultivate periods/bars on one line. Something like this:

Data:

STAGE
START
END

Cultivate
4/25/2008
3/29/2012

Qualify
3/30/2012
7/18/2012

Cultivate
7/19/2012
2/22/2015

Open
2/23/2015
4/17/2020

Cultivate
4/18/2020
6/24/2020

Steward
6/25/2020
3/31/2022

答:
Unfortunately, it's not possible to do it by the default chart creator.

A workaround would be building your Spreadsheet with the Gantt Chart in cells and apply conditional formatting for repeating tasks.

You can check it on this spreadsheet https://docs.google.com/spreadsheets/d/1VOxoDlL5auzigm1FSt2gmbjSSmkoRMhVlQiLsKwN4Kk/edit#gid=1539711303

The idea comes from https://infoinspired.com/google-docs/spreadsheet/split-a-task-in-gantt-chart-in-google-sheets/

I tested it out and it works well, but I think that it only accepts one repetitive task


问:
regression model into table
I have a summary regression model I want to put into a table. However, it keeps coming up with an error. Not sure what I am doing wrong here. I have included a reproducible data and steps I have taken below.

```<code>library(sjPlot)
library(sjmisc)
library(sjlabelled)
library(webshot)

x<-rnorm(1:20)

y<-(1:20)/10+x

m1<-lm(y~x)

summary(m1)

test<-tab_model(m1, file="test.html")

webshot("test.html","test.png")

Could not load  file:///C:/Users/AB/Documents/test.html
Error in webshot("test.html", "test.png") :
  webshot.js returned failure value: 1
</code>```

I'm not sure what the problem is. I have even changed my working directory - just to be sure. Is there any other better way than what I am currently doing?
Any help will be appreciated.

答:
You shouldn't assign the output of tab_model() to a variable - that prevents it from writing the HTML file. If you just run tab_model() without assigning it to test you'll be fine.

The following works for me:

library(sjPlot)
library(sjmisc)
library(sjlabelled)
library(webshot)

x<-rnorm(1:20)

y<-(1:20)/10+x

m1<-lm(y~x)

summary(m1)

tab_model(m1, file="test.html")

webshot("test.html","test.png")
```

Title: regression model into table

Body:
I have a summary regression model I want to put into a table. However, it keeps coming up with an error. Not sure what I am doing wrong here. I have included a reproducible data and steps I have taken below.

library(sjPlot)
library(sjmisc)
library(sjlabelled)
library(webshot)

x<-rnorm(1:20)

y<-(1:20)/10+x

m1<-lm(y~x)

summary(m1)

test<-tab_model(m1, file="test.html")

webshot("test.html","test.png")

Could not load  file:///C:/Users/AB/Documents/test.html
Error in webshot("test.html", "test.png") :
  webshot.js returned failure value: 1

I'm not sure what the problem is. I have even changed my working directory - just to be sure. Is there any other better way than what I am currently doing?
Any help will be appreciated.


答:
If you're using MySQL version that supports window function then probably:

```<code>SELECT id,
       SUM(CASE WHEN rn <= 20 THEN vals ELSE 0 END) AS 'SumOf1st20',
       SUM(CASE WHEN rn > 20 THEN vals ELSE 0 END) AS 'SumOFOthers'
FROM
(SELECT SUM(value) AS vals, id, DATE_FORMAT(date,'%Y-%m-%d') AS dt,
       ROW_NUMBER() OVER (PARTITION BY id ORDER BY dt DESC) AS rn
FROM test_table
GROUP BY id, dt) v
GROUP BY id;
</code>```

But I wonder if this is exactly what you want since your sample data seems to be a result of your original query.

Here's a sample fiddle for reference.

This here is a way to replicate ROW_NUMBER() function in older MySQL version:

```<code>SELECT t1.*,
       CASE WHEN id=@idx THEN @rnk := @rnk+1
        ELSE @rnk := 1 END AS rn,
        @idx := id
 FROM (SELECT id,
          SUM(value) AS vals, DATE_FORMAT(date,"%Y-%m-%d") AS dt
   FROM test_table
   GROUP BY id, dt)t1
 CROSS JOIN (SELECT @rnk := 0, @idx := NULL) r
 ORDER BY id, dt DESC
</code>```

Fiddle

Although, (in rare occasions) I had experience where this doesn't perform as I expect it to be: the row numbering sometimes gets messed up.

With further testing, that "rare occasion" seems to be happening here. Since your original query include aggregation, I took that and compare it against the v8 compatible ROW_NUMBER() and I got different results. Upon observation, the row numbers were assigned before the ORDER BY xxx DESC occur. So, visually it does sort by date descending accordingly but the rn column "incorrectly" generated. The workaround I found was to perform the aggregation in subquery first then only attempt to generate the custom row numbering. See my updated query and fiddle above.

Title: How to sum value by DATE_FORMAT(date,'%Y-%m-%d') limit 20, and sum remaining value if greater than 20?

Body:
How to sum value by DATE_FORMAT(date,'%Y-%m-%d') and id the first 20 rows of data, and sum the remaining value if greater than 20 else 0? supposed I have below data with below SQL, how to do it? thanks so much for any advice.

SELECT SUM(value), id, DATE_FORMAT(date,'%Y-%m-%d')
FROM test_table
GROUP BY id, DATE_FORMAT(date,'%Y-%m-%d')

sum(value)  id  DATE_FORMAT(date,'%Y-%m-%d')
--------------------------------------------
64.98   123456  2021-01-01
64.98   123456  2021-01-02
64.98   123456  2021-01-03
64.98   123456  2021-01-04
64.98   123456  2021-01-05
64.98   123456  2021-01-06
72.34   123456  2021-01-07
64.98   123456  2021-01-08
64.98   123456  2021-01-09
103.80  123456  2021-01-10
64.98   123456  2021-01-11
64.98   123456  2021-01-12
64.98   123456  2021-01-13
64.98   123456  2021-01-14
64.98   123456  2021-01-15
64.98   123456  2021-01-16
64.98   123456  2021-01-17
64.98   123456  2021-01-18
64.98   123456  2021-01-19
64.98   123456  2021-01-20
64.98   123456  2021-01-21
64.98   123456  2021-01-22
64.98   123456  2021-01-23
64.98   123456  2021-01-24
144.98  123456  2021-01-25
64.98   123456  2021-01-26
64.98   123456  2021-01-27
64.98   123456  2021-01-28
64.98   123456  2021-01-29
64.98   123456  2021-01-30
64.98   123456  2021-01-31
64.98   123456  2021-02-01
64.98   123456  2021-02-02
64.98   123456  2021-02-03
64.98   123456  2021-02-04
720.92  123456  2021-02-05
66.98   123456  2021-02-06
66.98   123456  2021-02-07
66.98   123456  2021-02-08
64.98   123456  2021-02-09
64.98   123456  2021-02-10
64.98   123456  2021-02-11
64.98   123456  2021-02-12
64.98   123456  2021-02-13
64.98   123456  2021-02-14
64.98   123456  2021-02-15
64.98   123456  2021-02-16
64.98   123456  2021-02-17
64.98   123456  2021-02-18
64.98   123456  2021-02-19
64.98   123456  2021-02-20
64.98   223456  2021-01-20
54.98   223456  2021-01-21

...................................

Body:
If you're using MySQL version that supports window function then probably:

SELECT id,
       SUM(CASE WHEN rn <= 20 THEN vals ELSE 0 END) AS 'SumOf1st20',
       SUM(CASE WHEN rn > 20 THEN vals ELSE 0 END) AS 'SumOFOthers'
FROM
(SELECT SUM(value) AS vals, id, DATE_FORMAT(date,'%Y-%m-%d') AS dt,
       ROW_NUMBER() OVER (PARTITION BY id ORDER BY dt DESC) AS rn
FROM test_table
GROUP BY id, dt) v
GROUP BY id;

But I wonder if this is exactly what you want since your sample data seems to be a result of your original query.

Here's a sample fiddle for reference.

This here is a way to replicate ROW_NUMBER() function in older MySQL version:

SELECT t1.*,
       CASE WHEN id=@idx THEN @rnk := @rnk+1
        ELSE @rnk := 1 END AS rn,
        @idx := id
 FROM (SELECT id,
          SUM(value) AS vals, DATE_FORMAT(date,"%Y-%m-%d") AS dt
   FROM test_table
   GROUP BY id, dt)t1
 CROSS JOIN (SELECT @rnk := 0, @idx := NULL) r
 ORDER BY id, dt DESC

Fiddle

Although, (in rare occasions) I had experience where this doesn't perform as I expect it to be: the row numbering sometimes gets messed up.

With further testing, that "rare occasion" seems to be happening here. Since your original query include aggregation, I took that and compare it against the v8 compatible ROW_NUMBER() and I got different results. Upon observation, the row numbers were assigned before the ORDER BY xxx DESC occur. So, visually it does sort by date descending accordingly but the rn column "incorrectly" generated. The workaround I found was to perform the aggregation in subquery first then only attempt to generate the custom row numbering. See my updated query and fiddle above.


问:
substring-before the last occurrence of any non-word character xslt 2.0 3.0
Similar to this question, but in XSLT 2.0 or 3.0, and I want to break on the last non-word character (like the regex \W)

Finding the last occurrence of a string xslt 1.0

The input is REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX

The desired output is:

```<code>REMOVE-THIS-IS-A-TEST-LINE,XXX,

</code>```

This works for one delimiter at a time, but I need to break on at least commas, spaces and dashes.

```<code>substring('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX',1,index-of(string-to-codepoints('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX'),string-to-codepoints(' '))[last()])
</code>```

I am using oxygen with saxon 9.9EE and antenna house.

答:
You could split out the string based on tokenize() and then use [] indexing or subsequence(), and then join() it back together, but the most concise approach is probably to do it all in the string realm using regex...

This XPath, based on , separators,

```<code>replace('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX', '(.*,).+', '$1')
</code>```

or this XPath, based on the \W non-word-character,

```<code>replace('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX', '(.*\W).+', '$1')
</code>```

will return

```<code>REMOVE-THIS-IS-A-TEST-LINE,XXX,
</code>```

as requested.

Body:
Similar to this question, but in XSLT 2.0 or 3.0, and I want to break on the last non-word character (like the regex \W)

Finding the last occurrence of a string xslt 1.0

The input is REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX

The desired output is:

REMOVE-THIS-IS-A-TEST-LINE,XXX,

This works for one delimiter at a time, but I need to break on at least commas, spaces and dashes.

substring('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX',1,index-of(string-to-codepoints('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX'),string-to-codepoints(' '))[last()])

I am using oxygen with saxon 9.9EE and antenna house.

Body:
You could split out the string based on tokenize() and then use [] indexing or subsequence(), and then join() it back together, but the most concise approach is probably to do it all in the string realm using regex...

This XPath, based on , separators,

replace('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX', '(.*,).+', '$1')

or this XPath, based on the \W non-word-character,

replace('REMOVE-THIS-IS-A-TEST-LINE,XXX,XXXXX', '(.*\W).+', '$1')

will return

REMOVE-THIS-IS-A-TEST-LINE,XXX,

as requested.


问:
The relationship could not be changed because one or more of the foreign-key properties is non-nullable
I am getting this error when I GetById() on an entity and then set the collection of child entities to my new list which comes from the MVC view.

The operation failed: The
  relationship could not be changed
  because one or more of the foreign-key
  properties is non-nullable. When a
  change is made to a relationship, the
  related foreign-key property is set to
  a null value. If the foreign-key does
  not support null values, a new
  relationship must be defined, the
  foreign-key property must be assigned
  another non-null value, or the
  unrelated object must be deleted.

I don't quite understand this line:

The relationship could not be changed
  because one or more of the foreign-key
  properties is non-nullable.

Why would I change the relationship between 2 entities? It should remain the same throughout the lifetime of the whole application.

The code the exception occurs on is simple assigning modified child classes in a collection to the existing parent class.  This would hopefully cater for removal of child classes, addition of new ones and modifications.  I would have thought Entity Framework handles this.

The lines of code can be distilled to:

```<code>var thisParent = _repo.GetById(1);
thisParent.ChildItems = modifiedParent.ChildItems();
_repo.Save();
</code>```

答:
I had the same issue when I was trying to modify the scalar property of the targeted entity and realized I have accidentally referenced the target entity's parent:

```<code>entity.GetDbContextFromEntity().Entry(entity).Reference(i => i.ParentEntity).Query().Where(p => p.ID == 1).Load();
</code>```

Just an advice by making sure the target entity does not reference any parent.

ContentLicense: CC BY-SA 2.5

Body:
I am getting this error when I GetById() on an entity and then set the collection of child entities to my new list which comes from the MVC view.

The operation failed: The
  relationship could not be changed
  because one or more of the foreign-key
  properties is non-nullable. When a
  change is made to a relationship, the
  related foreign-key property is set to
  a null value. If the foreign-key does
  not support null values, a new
  relationship must be defined, the
  foreign-key property must be assigned
  another non-null value, or the
  unrelated object must be deleted.

I don't quite understand this line:

The relationship could not be changed
  because one or more of the foreign-key
  properties is non-nullable.

Why would I change the relationship between 2 entities? It should remain the same throughout the lifetime of the whole application.

The code the exception occurs on is simple assigning modified child classes in a collection to the existing parent class.  This would hopefully cater for removal of child classes, addition of new ones and modifications.  I would have thought Entity Framework handles this.

The lines of code can be distilled to:

var thisParent = _repo.GetById(1);
thisParent.ChildItems = modifiedParent.ChildItems();
_repo.Save();

Body:
I had the same issue when I was trying to modify the scalar property of the targeted entity and realized I have accidentally referenced the target entity's parent:

entity.GetDbContextFromEntity().Entry(entity).Reference(i => i.ParentEntity).Query().Where(p => p.ID == 1).Load();

Just an advice by making sure the target entity does not reference any parent.


问:
How to assign text to the rich textbox control when mouse pointer pointing on the image using wpf?
I have images. When the mouse pointer is pointing/over that image, the image description should be visible on rich text box? How?

Please, any one have idea? Please revert me ASAP

Thanks in Advance.

答: You can add a Trigger to the image that sets the RichTextBox's content when the property (IsMouseOver) is set to true. Check out this link for more information


问:
How to setup accessibility containers so that gestures work properly?
I have a view controller with this layout (note that yellow and table views are siblings):

I want the yellow view to act as a container, so I'm doing this in viewDidLoad:

```<code>yellowView.isAccessibilityElement = true
view.accessibilityElements = [yellowView!, tableView!]
</code>```

When in Voice Over, I select "Containers" from the accessibility rotor and expect to be able to swipe up and down to move from the yellow view to the table view and back again:

Yellow (swipe down) → TableView (swipe down) → Tabbar (swipe up) → tableView (swipe up) → Yellow

However, this is not the case - after the tableView gains focus, swiping up does not move focus to the yellow view, it just stops there. Swiping down, moves to the tabbar - it seems that my custom view is ignored as container.

I have experimented with many combinations of adding superviews and setting isAccessibilityElement = false to them, but nothing seems to work.

Does anybody know how to solve this?

答:
Did you set an accessibilityLabel on the yellowView or try changing the accessibilityContainerType = .semantic?

I think VoiceOver is not finding yellowView because the rotor is looking for UIAccessibilityContainer but the default container type is .none for UIView. However, a UITableView has a default container type of .semantic.

Body:
I have a view controller with this layout (note that yellow and table views are siblings):

I want the yellow view to act as a container, so I'm doing this in viewDidLoad:

yellowView.isAccessibilityElement = true
view.accessibilityElements = [yellowView!, tableView!]

When in Voice Over, I select "Containers" from the accessibility rotor and expect to be able to swipe up and down to move from the yellow view to the table view and back again:

Yellow (swipe down) → TableView (swipe down) → Tabbar (swipe up) → tableView (swipe up) → Yellow

However, this is not the case - after the tableView gains focus, swiping up does not move focus to the yellow view, it just stops there. Swiping down, moves to the tabbar - it seems that my custom view is ignored as container.

I have experimented with many combinations of adding superviews and setting isAccessibilityElement = false to them, but nothing seems to work.

Does anybody know how to solve this?


问:
AsyncTask kill task when back button pressed
I am having a little problems with AsyncTask.

I have it implemented as follows

```<code> private class MakeConnection extends AsyncTask<String, Void, String> implements OnDismissListener{

    Context context;
    ProgressDialog myDialog;
    public MakeConnection(Context conetext)
    {
        this.context = conetext;
        myDialog = new ProgressDialog(this.context);
        myDialog.setCancelable(true);
        myDialog.setOnDismissListener(this);
    }

    @Override
    protected String doInBackground(String... urls) {
        //do stuff
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            myDialog.dismiss();
            success(result);
        }catch(JSONException e)
        {
            data = e.toString();
        }
    }

    @Override
      protected void onProgressUpdate(Void... values) {
            myDialog = ProgressDialog.show(context, "Please wait...", "Loading the data", true);
       }

    @Override
    public void onDismiss(DialogInterface dialog) {

        this.cancel(true);
    }
}
</code>```

But when ever I press the back button nothing happens, it just completes the task as if I didn't press the back button

Any idea why?

答:
This fixes my problem</p>

```<code>@Override
protected void onPreExecute(){
    myDialog = ProgressDialog.show(
            context,
            "Please wait...",
            "Loading the data",
            true,
            true,
            new DialogInterface.OnCancelListener(){
                @Override
                public void onCancel(DialogInterface dialog) {
                    MakeConnection.this.cancel(true);
                }
            }
    );
}
</code>```

Body:
I am having a little problems with AsyncTask.

I have it implemented as follows

 private class MakeConnection extends AsyncTask<String, Void, String> implements OnDismissListener{

    Context context;
    ProgressDialog myDialog;
    public MakeConnection(Context conetext)
    {
        this.context = conetext;
        myDialog = new ProgressDialog(this.context);
        myDialog.setCancelable(true);
        myDialog.setOnDismissListener(this);
    }

    @Override
    protected String doInBackground(String... urls) {
        //do stuff
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            myDialog.dismiss();
            success(result);
        }catch(JSONException e)
        {
            data = e.toString();
        }
    }

    @Override
      protected void onProgressUpdate(Void... values) {
            myDialog = ProgressDialog.show(context, "Please wait...", "Loading the data", true);
       }

    @Override
    public void onDismiss(DialogInterface dialog) {

        this.cancel(true);
    }
}

But when ever I press the back button nothing happens, it just completes the task as if I didn't press the back button

Any idea why?

Body:
This fixes my problem

@Override
protected void onPreExecute(){
    myDialog = ProgressDialog.show(
            context,
            "Please wait...",
            "Loading the data",
            true,
            true,
            new DialogInterface.OnCancelListener(){
                @Override
                public void onCancel(DialogInterface dialog) {
                    MakeConnection.this.cancel(true);
                }
            }
    );
}


问:
Compare two column values and validate it to through error
I have interactive grid with some columns and one button as Match in my page, here i want to compare two column values and through error

Ex: one column as Outstanding which have value from table another column is Match_value here user will enter the match value amount

--> When i click on match button the below example should allow to proceed further

Outstanding     Match value

1000            1000

--> When i click on match button the below example should allow to proceed further

Outstanding     Match value

1000            900

--> When i click on match button the below example should not allow to proceed further it should through error as match_value should not greater than outstanding
Outstanding     Match value

1000            1500

答:
You need to test the values and raise an exception if they don't match your criteria:</p>
```<code>  CREATE OR REPLACE PROCEDURE validate_match (
      p_match         IN INTEGER
    , p_outstanding   IN INTEGER)
  AS
  BEGIN
      IF p_match > p_outstanding
      THEN
          raise_application_error (
              -20001
            ,    'match value '
              || TO_CHAR (p_match, '999,999,999')
              || ' must be less than or equal to oustanding value '
              || TO_CHAR (p_outstanding, '999,999,999'));
      END IF;
  END validate_match;
</code>```

Body:
You need to test the values and raise an exception if they don't match your criteria:

  CREATE OR REPLACE PROCEDURE validate_match (
      p_match         IN INTEGER
    , p_outstanding   IN INTEGER)
  AS
  BEGIN
      IF p_match > p_outstanding
      THEN
          raise_application_error (
              -20001
            ,    'match value '
              || TO_CHAR (p_match, '999,999,999')
              || ' must be less than or equal to oustanding value '
              || TO_CHAR (p_outstanding, '999,999,999'));
      END IF;
  END validate_match;


问:
Python OpenCV: Crop image to contents, and make background transparent
I have the following image:

I want to crop the image to the actual contents, and then make the background (the white space behind) transparent. I have seen the following question: How to crop image based on contents (Python & OpenCV)?, and after looking at the answer, and trying it, I got the following code:

img = cv.imread("tmp/"+img+".png")
mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

rect = (55,55,110,110)
cv.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv.GC_INIT_WITH_RECT)

mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]

plt.imshow(img),plt.colorbar(),plt.show()
```

But when I try this code, I get the following result:

Which isn't really the result I'm searching for, expected result:

答:
Given that the background to be converted to transparent has its BGR channels white (like in your image), you can do:

```<code>import cv2
import numpy as np

img = cv2.imread("cat.png")
img[np.where(np.all(img == 255, -1))] = 0
img_transparent = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
img_transparent[np.where(np.all(img == 0, -1))] = 0

cv2.imshow("transparent.png", img_transparent)
</code>```

Input image:

Output image:

We can tell the second image is transparent by clicking on it; the transparent background will show up a grey (in Firefox, at least).

Body:
I have the following image:

I want to crop the image to the actual contents, and then make the background (the white space behind) transparent. I have seen the following question: How to crop image based on contents (Python & OpenCV)?, and after looking at the answer, and trying it, I got the following code:

img = cv.imread("tmp/"+img+".png")
mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

rect = (55,55,110,110)
cv.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv.GC_INIT_WITH_RECT)

mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]

plt.imshow(img),plt.colorbar(),plt.show()

But when I try this code, I get the following result:

Which isn't really the result I'm searching for, expected result:

Body:
Given that the background to be converted to transparent has its BGR channels white (like in your image), you can do:

import cv2
import numpy as np

img = cv2.imread("cat.png")
img[np.where(np.all(img == 255, -1))] = 0
img_transparent = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
img_transparent[np.where(np.all(img == 0, -1))] = 0

cv2.imshow("transparent.png", img_transparent)

Input image:

Output image:

We can tell the second image is transparent by clicking on it; the transparent background will show up a grey (in Firefox, at least).


问:
How to add icon to autocomplete in PrimeVue
I've run into this issue. There is a feature request for this at the moment.
I've provided my workaround in the answer below.</p>

答:
Anyone looking for alternatives can either add a placeholder value to the Autocomplete with emojis as 'icons'

Option 1

<AutoComplete
  class="inputSearch"
  id="artist"
  v-model="selectedArtist"
  :suggestions="filteredArtists"
  @complete="searchArtist($event)"
  placeholder=" Search Artist"
>
</AutoComplete>
```
<h2>Option 2 (better)</h2>
<p>OR use this method where you add icons as a background image and indent the text away from it. You can remove the focus from the example if you want to keep the icon.</p>
<p>If you have primeicons imported, you can put the path to your desired icon in the url section of background-image. Additionally, you can add</p>
<pre class="lang-css prettyprint-override"><code>background-size: 0.8em;
background-position: left;
</code>```

under the input in the CSS with your desired values to position and size the icon.

Final CSS in my case looks like this:

.inputSearch input {
  background-image: url("../../node_modules/primeicons/raw-svg/search.svg");
  background-size: 0.8em;
  background-position: left;
  background-repeat: no-repeat;
  text-indent: 20px;
}
```

If you inspect the Autocomplete in a browser, you'll see an input wrapped in a span. That's why this works. I may copy those icons to my public folder later on. Not ideal, but a workaround for now.

Body:
Anyone looking for alternatives can either add a placeholder value to the Autocomplete with emojis as 'icons'

Option 1

<AutoComplete
  class="inputSearch"
  id="artist"
  v-model="selectedArtist"
  :suggestions="filteredArtists"
  @complete="searchArtist($event)"
  placeholder=" Search Artist"
>
</AutoComplete>

Option 2 (better)

OR use this method where you add icons as a background image and indent the text away from it. You can remove the focus from the example if you want to keep the icon.

If you have primeicons imported, you can put the path to your desired icon in the url section of background-image. Additionally, you can add

background-size: 0.8em;
background-position: left;

under the input in the CSS with your desired values to position and size the icon.

Final CSS in my case looks like this:

.inputSearch input {
  background-image: url("../../node_modules/primeicons/raw-svg/search.svg");
  background-size: 0.8em;
  background-position: left;
  background-repeat: no-repeat;
  text-indent: 20px;
}

If you inspect the Autocomplete in a browser, you'll see an input wrapped in a span. That's why this works. I may copy those icons to my public folder later on. Not ideal, but a workaround for now.


问:
Convert from String to either LocalDateTime or ZonedDateTime
Hi I want to convert String value 2020-12-16T19:20:30+01:00 UTC to either LocalDateTime or ZonedDateTime in java

I tried solution:

```<code>DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-DDThh:mm:ssTZD", Locale.ENGLISH);
final String responseTimeStamp = "2020-12-16T19:20:30+01:00 UTC";
ZonedDateTime zdt = ZonedDateTime.parse(responseTimeStamp, dtf);
</code>```

Which gives me the error

Exception in thread "main" java.lang.IllegalArgumentException: Unknown pattern letter: T at java.base/java.time.format.DateTimeFormatterBuilder.parsePattern(DateTimeFormatterBuilder.java:1815) at java.base/java.time.format.DateTimeFormatterBuilder.appendPattern(DateTimeFormatterBuilder.java:1712) at java.base/java.time.format.DateTimeFormatter.ofPattern(DateTimeFormatter.java:588) at learning/learning.SpringDemo.main(SpringDemo.java:21)

答:
There are a few things wrong with your code. I suggest you to take a look at the DateTimeFormatter documentation.

YYYY -> This means week-based-year, you can have a look here to see the difference between year-of-era. So you should be using yyyy.

DD -> This means day-of-year, so December 16 is equal to 350. In your case you want to use dd, day-of-month.

T -> There isn't a pattern for T, so you can put it like a text to formmat you date 'T'

TZD -> I don't know what you are trying to use here and I couldn't find the patter +03:00 UTC, you can try to use O

So your final pattern should be "yyyy-MM-dd'T'HH:mm:ssO". It doens't work for UTC and I couldn't find it on ZoneId list, maybe because UTC is +00:00 already, so UTC+01:00 is equal to +01:00.

After a lot of working understanding the pattern, I found out that you are looking for ISO_ZONED_DATE_TIME, so you could just change your code like below:

```<code>DateTimeFormatter dtf = DateTimeFormatter.ISO_ZONED_DATE_TIME;
final String responseTimeStamp = "2020-12-16T19:20:30+01:00";
ZonedDateTime zdt = ZonedDateTime.parse(responseTimeStamp, dtf);
</code>```

Body:
Hi I want to convert String value 2020-12-16T19:20:30+01:00 UTC to either LocalDateTime or ZonedDateTime in java

I tried solution:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-DDThh:mm:ssTZD", Locale.ENGLISH);
final String responseTimeStamp = "2020-12-16T19:20:30+01:00 UTC";
ZonedDateTime zdt = ZonedDateTime.parse(responseTimeStamp, dtf);

Which gives me the error

Exception in thread "main" java.lang.IllegalArgumentException: Unknown pattern letter: T at java.base/java.time.format.DateTimeFormatterBuilder.parsePattern(DateTimeFormatterBuilder.java:1815) at java.base/java.time.format.DateTimeFormatterBuilder.appendPattern(DateTimeFormatterBuilder.java:1712) at java.base/java.time.format.DateTimeFormatter.ofPattern(DateTimeFormatter.java:588) at learning/learning.SpringDemo.main(SpringDemo.java:21)

Body:
There are a few things wrong with your code. I suggest you to take a look at the DateTimeFormatter documentation.

YYYY -> This means week-based-year, you can have a look here to see the difference between year-of-era. So you should be using yyyy.

DD -> This means day-of-year, so December 16 is equal to 350. In your case you want to use dd, day-of-month.

T -> There isn't a pattern for T, so you can put it like a text to formmat you date 'T'

TZD -> I don't know what you are trying to use here and I couldn't find the patter +03:00 UTC, you can try to use O

So your final pattern should be "yyyy-MM-dd'T'HH:mm:ssO". It doens't work for UTC and I couldn't find it on ZoneId list, maybe because UTC is +00:00 already, so UTC+01:00 is equal to +01:00.

After a lot of working understanding the pattern, I found out that you are looking for ISO_ZONED_DATE_TIME, so you could just change your code like below:

DateTimeFormatter dtf = DateTimeFormatter.ISO_ZONED_DATE_TIME;
final String responseTimeStamp = "2020-12-16T19:20:30+01:00";
ZonedDateTime zdt = ZonedDateTime.parse(responseTimeStamp, dtf);


问:
Discord Delete Message Prank
So basically in discord.py I wanted to try to prank one of my friends by deleting every message they send. I thought the code would of been simple enough to make but apparently not.</p>
```<code> if message.author.id == ("198562028556648448"):
     await message.delete()
</code>```

答:
According to the Discord API Reference, the message author ID is of type int.

It's likely this is the issue, because you can easily demonstrate the non-equivalence of an integer with its string representation in the Python shell:

```<code>>>> 198562028556648448 == "198562028556648448"
False
</code>```

You should therefore perform your test as follows:

```<code>if message.author.id == 198562028556648448:
</code>```

Happy pranking.

Title: Discord Delete Message Prank

Body:
So basically in discord.py I wanted to try to prank one of my friends by deleting every message they send. I thought the code would of been simple enough to make but apparently not.

 if message.author.id == ("198562028556648448"):
     await message.delete()

Body:
According to the Discord API Reference, the message author ID is of type int.

It's likely this is the issue, because you can easily demonstrate the non-equivalence of an integer with its string representation in the Python shell:

>>> 198562028556648448 == "198562028556648448"
False

You should therefore perform your test as follows:

if message.author.id == 198562028556648448:

Happy pranking.


问:
Superclass meant only to be extended, not directly instanciated
i am coding an OOP application in PHP. I want to have a Superclass from which other classes will inherit from.

Is there a way i can make sure the class itself can't be instantiated directly?

like:

```<code>class Mother {}
class Child extends Mother{}
$child = new Child();//no problemo
$mother = new Mother();//throws exception or dies
</code>```

答:
You can use abstract classes which only define methods but not their implementation.

```<code>abstract class Mother
{
    public function doSomething();
}

class Child implements Mother
{
    public function doSomething()
    {
        echo 'Hello world';
    }
}

$mother = new Mother(); // won't work
$child = new Child(); // works
$child->doSomething(); // echoes hello world
</code>```

Alternatively, if you need to implement the method implementation (functions do something but they can be overloaded) then you can use protected constructor.

```<code>class Mother
{
    protected function __construct()
    {
        echo "Hello World!";
    }
}

class Child extends Mother
{
    public function __construct()
    {
        parent::__construct();
    }
}

$mother = new Mother(); // won't work, you're trying to access protected method
$child = new Child(); // it'll work echoing "Hello World!"
</code>```

Body:
i am coding an OOP application in PHP. I want to have a Superclass from which other classes will inherit from.

Is there a way i can make sure the class itself can't be instantiated directly?

like:

class Mother {}
class Child extends Mother{}
$child = new Child();//no problemo
$mother = new Mother();//throws exception or dies

Body:
You can use abstract classes which only define methods but not their implementation.

abstract class Mother
{
    public function doSomething();
}

class Child implements Mother
{
    public function doSomething()
    {
        echo 'Hello world';
    }
}

$mother = new Mother(); // won't work
$child = new Child(); // works
$child->doSomething(); // echoes hello world

Alternatively, if you need to implement the method implementation (functions do something but they can be overloaded) then you can use protected constructor.

class Mother
{
    protected function __construct()
    {
        echo "Hello World!";
    }
}

class Child extends Mother
{
    public function __construct()
    {
        parent::__construct();
    }
}

$mother = new Mother(); // won't work, you're trying to access protected method
$child = new Child(); // it'll work echoing "Hello World!"


问:
How to call a function inside another function in VBA?
I'm trying to call a function inside another function but the result I'm getting is 0

```<code>Function DepositRate(Deposit):
    If Deposit > 100000 Then
        Rtaxa = 0.078
    ElseIf Deposit <= 100000 And Deposit > 10000 Then
        Rtaxa = 0.073
    ElseIf Deposit <= 10000 And Deposit > 1000 Then
        Rtaxa = 0.063
    ElseIf Deposit <= 1000 And Deposit > 0 Then
        Rtaxa = 0.055
    Else
        Rtaxa = "Negative Value"
    End If

    DepositRate = Rtaxa

End Function

Function NewDFV(Value, Year):
    Call DepositRate(Value)
    ValorFuturo = Deposit * (1 + Rtaxa) ^ (Year)
    NewDFV = ValorFuturo

End Function
</code>```

So,  Where I'm doing wrong here ?

答:
Unless Rtaxa is declared as a module or global variable, you will need to assign the return value of DepositRate to Rtaxa within function NewDFV

```<code>Function NewDFV(Value, Year)
    Dim Rtaxa As Variant
    Rtaxa  = DepositRate(Value)
    ValorFuturo = Deposit * (1 + Rtaxa) ^ (Year)
    NewDFV = ValorFuturo

End Function
</code>```

Body:
I'm trying to call a function inside another function but the result I'm getting is 0

Function DepositRate(Deposit):
    If Deposit > 100000 Then
        Rtaxa = 0.078
    ElseIf Deposit <= 100000 And Deposit > 10000 Then
        Rtaxa = 0.073
    ElseIf Deposit <= 10000 And Deposit > 1000 Then
        Rtaxa = 0.063
    ElseIf Deposit <= 1000 And Deposit > 0 Then
        Rtaxa = 0.055
    Else
        Rtaxa = "Negative Value"
    End If

    DepositRate = Rtaxa

End Function

Function NewDFV(Value, Year):
    Call DepositRate(Value)
    ValorFuturo = Deposit * (1 + Rtaxa) ^ (Year)
    NewDFV = ValorFuturo

End Function

So,  Where I'm doing wrong here ?

Body:
Unless Rtaxa is declared as a module or global variable, you will need to assign the return value of DepositRate to Rtaxa within function NewDFV

Function NewDFV(Value, Year)
    Dim Rtaxa As Variant
    Rtaxa  = DepositRate(Value)
    ValorFuturo = Deposit * (1 + Rtaxa) ^ (Year)
    NewDFV = ValorFuturo

End Function


问:
C# Select XML Attributes
I want to select some Attributes out of a Node in XML with C#.
My XML Looks like this:

```<code><itemdata>
   <items>
      <item id="1" name="table">
         <cost>200</cost>
         <category>5</category>
         <type>2</type>
      </item>
      <item id="2" name="chair">
         <cost>100</cost>
         <category>4</category>
         <type>6</type>
      </item>
      <item id="3" name="lamp">
         <cost>700</cost>
         <category>2</category>
         <type>3</type>
      </item>
   </items>
</itemdata>
</code>```

And my Code in C# looks like this:

```<code>XmlDocument document = new XmlDocument();
document.Load("c:/dir/itemdata.xml");

foreach(XmlNode node in document.SelectNodes("//item/@name")) {
   string innerText = node.InnerText;
}
</code>```

How could I display for example the Attributes "cost" or "type" within the same foreach loop?

答:
Please try the following solution.

It is using LINQ to XML API, available in the .Net Framework since 2007. No need to use somewhat outdated XML API.

c#

```<code>void Main()
{
    const string filename = @"e:\Temp\itemdata.xml";

    XDocument xdoc = XDocument.Load(filename);

    var Item = xdoc.Descendants("item");

    foreach (var elem in Item.Elements())
    {
        Console.WriteLine($"{elem.Name}='{elem.Value}'");
    }
}
</code>```

Title: C# Select XML Attributes

Body:
I want to select some Attributes out of a Node in XML with C#.
My XML Looks like this:

<itemdata>
   <items>
      <item id="1" name="table">
         <cost>200</cost>
         <category>5</category>
         <type>2</type>
      </item>
      <item id="2" name="chair">
         <cost>100</cost>
         <category>4</category>
         <type>6</type>
      </item>
      <item id="3" name="lamp">
         <cost>700</cost>
         <category>2</category>
         <type>3</type>
      </item>
   </items>
</itemdata>

And my Code in C# looks like this:

XmlDocument document = new XmlDocument();
document.Load("c:/dir/itemdata.xml");

foreach(XmlNode node in document.SelectNodes("//item/@name")) {
   string innerText = node.InnerText;
}

How could I display for example the Attributes "cost" or "type" within the same foreach loop?

Body:
Please try the following solution.

It is using LINQ to XML API, available in the .Net Framework since 2007. No need to use somewhat outdated XML API.

c#

void Main()
{
    const string filename = @"e:\Temp\itemdata.xml";

    XDocument xdoc = XDocument.Load(filename);

    var Item = xdoc.Descendants("item");

    foreach (var elem in Item.Elements())
    {
        Console.WriteLine($"{elem.Name}='{elem.Value}'");
    }
}


问:
Vue 2 - render components from an ajax response
Is there a way to render components that come from an ajax response?
For example, I registered a component "Test" and in the ajax response I have:

```<code><p>dummy paragraph</p>
<test></test> <!-- vue component I want to render -->
<p>another dummy paragraph</p>
</code>```

My final goal is to make a shortcode that lets the user insert a router link in the content area.

I'm using Vue 2, vue router

Edit: here is a demo https://jsfiddle.net/Paulius_Krutkis/4mb1ypqs/

答:
Yes, there is way for doing this. Follow these steps:

Register the component (which will be sent as an ajax response) globally.

```<code>import Vue from 'vue'
import Test from './some/folder/Test.vue'

Vue.component('test', Test)
</code>```

Either add Vue to the window object or export it and import it wherever you need it. Here i will add it to the global window object so that i can easily access it within the browser console.

```<code>window.Vue = Vue
</code>```

When you get the ajax response with the uncompiled DOM element (<test></test>) you can decide if you want to insert it directly to your DOM and compile it afterwards or compile it first and then mount it to the DOM.
Lets say you inserted the component template directly to the DOM like in your example.
Notice the wrapper element.

```<code><p>dummy paragraph</p>
<div id="testapp">
  <test></test>
</div>
<p>another dummy paragraph</p>
</code>```

Create a new Vue instance and tell it where it should mount. Since your test component is already registered globally, vue knows how it looks like and will compile it once it sees it in the DOM. Alternatively, you can also add it here within your "components" property.

```<code>new window.Vue({
    el: '#testapp',
})
</code>```

Done!

Info: VueDevtools will not recognize your new compiled component If you have already a root vue instance mounted initially. To make it work you must tell the newly created instance that it belongs to a parent instance:

```<code>var vm = new Vue({
  el: '#app',
});

new window.Vue({
  el: '#testapp',
  parent: vm,
});
</code>```

Notice: The new vue instance will NOT share data with other instances. This approach is only "meaningful" (of course this whole procedure is not recommended) when you have independent components like for example a text-input component, that is only there to send data to the server independently.

Hope it helps someone out there!

Body:
Is there a way to render components that come from an ajax response?
For example, I registered a component "Test" and in the ajax response I have:

dummy paragraph

<test></test>

another dummy paragraph

My final goal is to make a shortcode that lets the user insert a router link in the content area.

I'm using Vue 2, vue router

Edit: here is a demo https://jsfiddle.net/Paulius_Krutkis/4mb1ypqs/

Body:
Yes, there is way for doing this. Follow these steps:

Register the component (which will be sent as an ajax response) globally.

import Vue from 'vue'
import Test from './some/folder/Test.vue'

Vue.component('test', Test)

Either add Vue to the window object or export it and import it wherever you need it. Here i will add it to the global window object so that i can easily access it within the browser console.

window.Vue = Vue

When you get the ajax response with the uncompiled DOM element (<test></test>) you can decide if you want to insert it directly to your DOM and compile it afterwards or compile it first and then mount it to the DOM.
Lets say you inserted the component template directly to the DOM like in your example.
Notice the wrapper element.

<p>dummy paragraph</p>
<div id="testapp">
  <test></test>
</div>
<p>another dummy paragraph</p>

Create a new Vue instance and tell it where it should mount. Since your test component is already registered globally, vue knows how it looks like and will compile it once it sees it in the DOM. Alternatively, you can also add it here within your "components" property.

new window.Vue({
    el: '#testapp',
})

Done!

Info: VueDevtools will not recognize your new compiled component If you have already a root vue instance mounted initially. To make it work you must tell the newly created instance that it belongs to a parent instance:

var vm = new Vue({
  el: '#app',
});

new window.Vue({
  el: '#testapp',
  parent: vm,
});

Notice: The new vue instance will NOT share data with other instances. This approach is only "meaningful" (of course this whole procedure is not recommended) when you have independent components like for example a text-input component, that is only there to send data to the server independently.

Hope it helps someone out there!


问:
Need a help with a jquery click count
So far I have got this JavaScript:

```<code>$(document).ready(function() {
    $("#flash").click(function() {
        $(this).html('<img src="http://ruh.kz/sites/default/files/ajax-loader.gif" />');
        $(this).load("http://ruh.kz/sites/all/themes/ruh/sunit.php");
        $('#counter').html(function(i, val) {
            return val * 1 + 1
        });
    });
});
</code>```

Accompanying this HTML:

```<code><div id="flash">
    <img src="http://ruh.kz/sites/default/files/sunit.jpg" />
</div>
<div id="counter">0</div>
</code>```

(Demo)

One problem is that it resets after the page refreshes... How can I save the count number?

In the example on jsfiddle.net, it works well. On my Drupal page however, it doesn't. When I press on the
 the counter "0" dissapears. What might be the problem here?

答:
you can post ajax request to save it or save it to cookies

DO you have #counter there?

Title: Need a help with a jquery click count

Body:
So far I have got this JavaScript:

$(document).ready(function() {
    $("#flash").click(function() {
        $(this).html('');
        $(this).load("http://ruh.kz/sites/all/themes/ruh/sunit.php");
        $('#counter').html(function(i, val) {
            return val * 1 + 1
        });
    });
});

Accompanying this HTML:

0

(Demo)

One problem is that it resets after the page refreshes... How can I save the count number?

In the example on jsfiddle.net, it works well. On my Drupal page however, it doesn't. When I press on the
 the counter "0" dissapears. What might be the problem here?


问:
Visual Studio Code React not showing error even after adding jsconfig
So I am building a REACT JS project, and after a while I noticed that it doesn't underline undefined functions nor wrong imports, for example if I does that:

```<code>import React, { useState } from 'reactaeasdfas';
</code>```

it wont say that reactaeasdfas is undefined.

After a bit of searching I found that people say that jsconfig.json should be initialized.

I found a basic one on the internet:

```<code>{
    "compilerOptions": {
      "module": "commonjs",
      "target": "es6",
      "jsx": "react"
    },
    "include": [
        "src"
    ]
}
</code>```

This code above does solve the problem that if I call an undefined function, it will underline it in red, but it still doesn't work if I include undefined import.

Note: I installed react project via create-react-app

答:
Install the ESLint extension for Visual Studio Code - https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

More details:

A standard create-react-app package is already using ESLint, so you shouldn't need to make any changes to the app. However, your editor needs to be set up to work with ESLint. For VS Code this is done by installing an extension/plugin. The CRA documentation has more information about setting up editors - https://create-react-app.dev/docs/setting-up-your-editor/

Body:
So I am building a REACT JS project, and after a while I noticed that it doesn't underline undefined functions nor wrong imports, for example if I does that:

import React, { useState } from 'reactaeasdfas';

it wont say that reactaeasdfas is undefined.

After a bit of searching I found that people say that jsconfig.json should be initialized.

I found a basic one on the internet:

{
    "compilerOptions": {
      "module": "commonjs",
      "target": "es6",
      "jsx": "react"
    },
    "include": [
        "src"
    ]
}

This code above does solve the problem that if I call an undefined function, it will underline it in red, but it still doesn't work if I include undefined import.

Note: I installed react project via create-react-app


问:
@Value for resource not working in Webflux
I have a Spring Boot Webflux app with:

```<code>@Value("classpath:file.json")
private Resource create;
</code>```

The file is in resources/file.json, but create is always coming up null in the debugger.

I have also tried:

new ClassPathLoader("file.json") through manual loading and its working fine.

Any ideas why @Value can't resolve?

答: Dependency injections happen after the initializers run on a class, that includes constructors. Dependencies are available as initialized within all instance methods as well as in a special lifecycle method marked @PostConstruct. Within a constructor, dependencies have their default values.

Body:
I have a Spring Boot Webflux app with:

@Value("classpath:file.json")
private Resource create;

The file is in resources/file.json, but create is always coming up null in the debugger.

I have also tried:

new ClassPathLoader("file.json") through manual loading and its working fine.

Any ideas why @Value can't resolve?


问:
can bash use kubectl get pods run a log watch sequentially?
Note: this is more a bash/shell script issue than Kubernetes.

So I have one replica of a pod, and so kubectl get pods will only return one active replica.

Conceptually what I want to do is simple.  I want to do a kubectl logs my-pod-nnn1 with a watcher, HOWEVER when that pod terminates I want to stream a message "my-pod-nnn1 terminated, now logging my-pod-nnn2", and then stream the new logs.  This is a fairly complex process (for me) and I'm wondering what approach I could take, and if this is possible (or perhaps not necessary) with multi-threading of some kind (which I have not done). Thanks

答:
as a rough outline for what you'll need to do, if I've read your needs right

slm-log-continue() {
  while true ; do
    PODLINE=$(kubectl get pod | grep regional-wkspce | grep Running | awk '/^regional-wkspce-.*/{print $1}')
    if [[ -z "$PODLINE" ]]; then
        echo no pod currently active, waiting 5 seconds ...
        sleep 5
    else
        echo "----- logging for $PODLINE -----"
        kubectl logs -f $PODLINE
        echo "----- pod $PODLINE disconnected -----"
    fi
  done
}
```

assuming kubectl logs terminates after the pod does and it's received the end of the logs ( I've not tested ), something like that should do what you need without any fancy multithreading. it will just find the current pod using whatever regex against the get pods output, extract the name and then spit out logs until it dies.

Body:
as a rough outline for what you'll need to do, if I've read your needs right

slm-log-continue() {
  while true ; do
    PODLINE=$(kubectl get pod | grep regional-wkspce | grep Running | awk '/^regional-wkspce-.*/{print $1}')
    if [[ -z "$PODLINE" ]]; then
        echo no pod currently active, waiting 5 seconds ...
        sleep 5
    else
        echo "----- logging for $PODLINE -----"
        kubectl logs -f $PODLINE
        echo "----- pod $PODLINE disconnected -----"
    fi
  done
}

assuming kubectl logs terminates after the pod does and it's received the end of the logs ( I've not tested ), something like that should do what you need without any fancy multithreading. it will just find the current pod using whatever regex against the get pods output, extract the name and then spit out logs until it dies.


问:
Barplot in R - How to divide the plot into separate parts by showing them in different colors
I am a newbie to R. I would like to create a barplot which is visually divided into different parts.

My data looks like the following:

```<code>"1.0";"0.0";"1.0";"2.0";"710";"12500"
</code>```

first four numbers give the number of parts that need to be ordered from the two parts list below. The fifth number gives the result sum of the first part, the sixth then the result sum of the second part.

```<code>part 1: 10;50;100;300
part 2: 500;1000;2000;5000;
</code>```

this is how it is calculated.

```<code>1 * 10 + 0 * 50 + 1 * 100 + 2 * 300 = 710 ;
1 * 500 + 0 * 1000 + 1 * 2000 + 2 * 5000 = 12500
</code>```

So what I now want to plot is for example the value 12500, but I want to visually divide this value into the different part (stacked bars) like two five thousands, then one two thousand then one five hundred -> the bar should consist of these parts which can visually be seen or marked with the value (would be nice to have different colors for each part in the part)

How can I do it? Folks, I did my homework, I searched a lot and did try it on my own, but couldn't achieve what I want.

答:
```<code>daten <- matrix(c(10,50,100,300,500,1000,2000,5000),ncol=2)
multiplier <- c(1,0,1,2)
barplot(daten*multiplier)
</code>```

To display bar segments in reverse order, you need to rearrange the rows in the daten*multiplier array:

```<code>barplot((daten*multiplier)[nrow(daten):1,])
</code>```

Body:
I am a newbie to R. I would like to create a barplot which is visually divided into different parts.

My data looks like the following:

"1.0";"0.0";"1.0";"2.0";"710";"12500"

first four numbers give the number of parts that need to be ordered from the two parts list below. The fifth number gives the result sum of the first part, the sixth then the result sum of the second part.

part 1: 10;50;100;300
part 2: 500;1000;2000;5000;

this is how it is calculated.

1 * 10 + 0 * 50 + 1 * 100 + 2 * 300 = 710 ;
1 * 500 + 0 * 1000 + 1 * 2000 + 2 * 5000 = 12500

So what I now want to plot is for example the value 12500, but I want to visually divide this value into the different part (stacked bars) like two five thousands, then one two thousand then one five hundred -> the bar should consist of these parts which can visually be seen or marked with the value (would be nice to have different colors for each part in the part)

How can I do it? Folks, I did my homework, I searched a lot and did try it on my own, but couldn't achieve what I want.

Body:
daten <- matrix(c(10,50,100,300,500,1000,2000,5000),ncol=2)
multiplier <- c(1,0,1,2)
barplot(daten*multiplier)

To display bar segments in reverse order, you need to rearrange the rows in the daten*multiplier array:

barplot((daten*multiplier)[nrow(daten):1,])


问:
Google Sheets How to Sortn/Filter/Query Top 10 across multiple ranges broken at the rows?
I have data in A1:C10, and then more in A14:C20.  So there are some subtotal rows in between.
How can I get the top 10 across these ranges?  I'm actually just trying to show the C column.  I know I'm supposed to use the Array {}, but not sure how to do that exactly (gives me errors).

I'd also be happy to pull from just one range if I could somehow get top 12 EXCLUDING top 2 (because the top 2 would be the larger sum rows).

Here's what the sortn formula is that's not working:

```<code>=sortn({c1:C10,c14:c20},10,1,{c1:c10,c14:c20},False)
</code>```

This formula works when I only have one range.  But for one Department, I need to pull from two ranges.

I'd also tried query:

```<code>=query({a1:c10,a14:c20},"Select C Order by C Desc Limit 10")
</code>```

but that didn't work.

This is on a work spreadsheet, so I can't share it without doing some anonymizing.

Body:
I have data in A1:C10, and then more in A14:C20.  So there are some subtotal rows in between.
How can I get the top 10 across these ranges?  I'm actually just trying to show the C column.  I know I'm supposed to use the Array {}, but not sure how to do that exactly (gives me errors).

I'd also be happy to pull from just one range if I could somehow get top 12 EXCLUDING top 2 (because the top 2 would be the larger sum rows).

Here's what the sortn formula is that's not working:

=sortn({c1:C10,c14:c20},10,1,{c1:c10,c14:c20},False)

This formula works when I only have one range.  But for one Department, I need to pull from two ranges.

I'd also tried query:

=query({a1:c10,a14:c20},"Select C Order by C Desc Limit 10")

but that didn't work.

This is on a work spreadsheet, so I can't share it without doing some anonymizing.

Body:
use:

=SORTN({C1:C10; C14:C20}, 10, 1, {C1:C10; C14:C20}, 0)


问:
Find all possible subarrays of an array and sum them
Let's suppose the array is A={1,2,3} , now get all subarrays for this array. For each sub-array find the minimum in that sub-array, also find the sum of items in that sub-array. Finally add all these values. The input cannot be sorted as I want all possible subarrays.

Example:

Possible sub-arrays are:

```<code>{1} - min = 1, sum = 1 => min* sum = 1
{1,2} - min = 1, sum = 3 => min* sum = 3
{1,2,3} - min = 1, sum = 6 => min* sum = 6
{2} - min = 2, sum = 2 => min* sum = 4
{2,3} - min = 2, sum = 5 => min* sum = 10
{3} - min = 3, sum = 3 => min* sum = 9
</code>```

Finally add all these values to get the result = 1 + 3 + 6 + 4 + 10 + 9 = 33.

constraints: array elements can range from 1 to 1000_000_000. Array size from 1 to 100_000. Return output as module 7+1000_000_000.

Here is my program with O(n^2). I want a better algorithm with lesser time complexity.

```<code>public int program(int[] A, int n) {
    int M = 7 + 1000_000_000;
    long total = 0;
    for (int i = 0; i < n; i++) {
        long sum = 0;
        int min = A[i];
        for (int j = i; j < n; j++) {
            int a = A[j];
            sum= (sum + a) % M;
            min = Math.min(min, a);
            total = (total + (min * sum) % M) % M;
        }
    }
    return (int) total;
}
</code>```

Input range:

```<code>n range is 1 to 10^6
elements in array range is 1 to 10^9
</code>```

答:
This problem can be solved in O(n log n).

Basic idea

In this explanation, a lot of off-by-one errors probably sneaked in, but it does not matter for the idea. Let m be the minimum of the array. Then any subarray that contains m would have m as a minimum, and every other sub-array would be either entirely before or entirely after m. Let n be the number of elements in the array, and let us treat m as an index. Then for every i < m let's count the subarrays that contain i'th element and have m'th element as a minimum. It is exactly i * (n - m), as there are i possible left edges before i and (n - m) possible edges after m. Each of such arrays would have A[m] as a minimum, and each element with i < m would contribute to the resulting sum with a factor of i * A[m] * (n - m). For i > m with similar reasoning we would get (n - i) * A[m] * m. Then we would update the array before m and after m recursively and then just loop over to get the result.

The problem is in the update. To add these i * A[m] * (n - m) to every possible i would result in a quadratic solution. But as one can notice, both sides are linear functions with respect to i, and this is an important property. Let's rewrite the function for the right side as i * -A[m] * m + n * A[m] * m. So we would use a * i + b expression for every index. If we have two linear functions a * i + b and c * i + d, their sum would, obviously, be (a + c) * i + (b + d) - also a linear function. To conclude this optimization we would use a recursive function with two parameters: subarray currently processed and linear function to apply to each element.

The last problem to solve is finding the minimum in the subarray, but that is known as RMQ problem and can be solved in O(n log n).

The function

To speed things up we would not create subarrays, of course, but pass indices. The pseudocode for what we would like to achieve:

//This uses inclusive l and exclusive r
public int program(int[] A, int l, int r, int a, int b) {
  if (r - l == 0) {
    //array of size 0 can appear in recursive calls
    //if smallest element is first or last in its subarray
    return 0;
  }
  if (r - l == 1) {
    //for size one array there exists only one possible subarray
    //we also need to add the linear function
    return A[l] * A[l] + A[l] * (a * l + b);
  }
  //This is the call to your RMQ data structure
  int m = findMinIdxInSubArray(A, l, r);
  int result = 0;

  //to the left function would be (i + 1 - l) * A[m] * (r - m) which expands to
  //i * A[m] * (r - m) + (1 - l) * A[m] * (r - m)
  result += program(A, l, i, a + A[m] * (r - m), b + (1 - l) * A[m] * (r - m));

  //to the right function would be (r - i) * A[m] * (m - l + 1) wich expands to
  //i * -A[m] * (m - l + 1) + r * A[m] * (m - l + 1)
  result += program(A, m + 1, r, a - A[m] * (m - l + 1), b + r * A[m] * (m - l + 1));

  //This is the case for the element m itself,
  //as it is not accounted in the previous calculations
  //the linear function also needs to be accounted here
  result += A[m] * (m - l + 1) * (r - m) + A[m] * (a * m + b);
  return result;
}
```
<p>Now your old function would be written like:</p>
<pre class="lang-java prettyprint-override"><code>public int program(int A[], int n) {
  //initialize your RMQ data structure here
  return program(A, 0, n, 0, 0);
}
</code>```

Note that this implementation lacks the findMinIdxInSubArray function, as i mentioned, any RMQ data structure can be used here. Feel free to use anything from Fenwick tree to sparse table.

Example
To explain this formulas a little bit better i would trace the execution of this program for an array A={3,2,1,4}

When the function is first called it has subarray from 0 inclusive to 4 not inclusive and no elements are accounted for now. The minimum of this subarray is element 1 at index 2, and m=2 therefore.

1 is minimum for all subarrays [i,j] such that i <= 2 and 2 <= j.

For element 4 to the right of 1 it appears in 3 arrays ([0,3], [1,3], [2,3]), and recursive call with function -3 * i + 12 would be called. In this function call it is the array of size one, so we would account for subarray {4} with 16 and as it is index 3, it's linear function value is -3 * 3 + 12 = 3, so we would also add 4 * 3 = 12 to account for the arrays from the first function call.

For element 1 itself, it appears in 6 arrays ([0,2],[0,3],[1,2],[1,3],[2,2] and [2,3]) and in the last formula would be added as 1 * 3 * 2 as expected, contributing 6 to the total sum.

Now for the harder array to the left. Element 3 appears in exactly 2 such arrays ([0,2] and [0,3]) and would contribute with a factor of 2 (2 arrays multiplied by minimum value 1 each) and element 2 appears in exactly 4 such arrays([0,2], [0,3], [1,2] and [1,3]). For these two elements, we would call a program with a linear function of 2*i+2, which, as one can see, matches their contribution.

In this recursive call, we would find that 2 at index 1 is the smallest element.
To the right of it, there are no elements, so the recursive call would return 0. 2 itself appears in two subarrays ([0,1] and [1,1]) and from them, it would contribute 8 (2 arrays value 2 in sum and 2 is minimum) to the total sum. But linear function mentions that we should also add 21+1=4 arrayminimums from the previous levels, which matches our computations previously with the contribution of 8. So for 2, we would add a total of 16 in this iteration.

To the left of the two, there is only one element, it is three, it appears in only one array, so its contribution factor should increase by 2 (one array, but minimum is two). The function passed recursively would be (2*i+2) + (2*i+2) = (4*i+4). When we would process the subarray of one element 3 we would add contribution of 9 from the subarray {3} and another 3*(4*0+4) to account for arrays on previous levels, and total contribution would be another 21.

Therefore, recursive function would yield a sum of 21+16+6+28=71. Now lets validate this result by hand:

```<code>{3} - min=3, sum=3, min*sum=9
{3,2} - min=2, sum=5, min*sum=10
{3,2,1} - min=1, sum=6, min*sum=6
{3,2,1,4} - min=1, sum=10, min*sum=10
{2} - min=2, sum=2, min*sum=4
{2,1} - min=1, sum=3, min*sum=3
{2,1,4} - min=1, sum=7, min*sum=7
{1} - min=1, sum=1, min*sum=1
{1,4} - min=1, sum=5, min*sum=5
{4} - min=4, sum=4, min*sum=16
</code>```

Total: 9+10+6+10+4+3+7+1+5+16=71

Edit

If making stack size bigger is not possible to make recursion work, here is the same idea, but without using recursion:

//This uses inclusive l and exclusive r
public int program(int[] A) {
  //for every possible l we would store all other call parameters
  //in the deepest call with this l
  int[] r = new int[A.length];
  int[] a = new int[A.length];
  int[] b = new int[A.length];
  r[0] = A.length;
  a[0] = 0;
  b[0] = 0;
  int result = 0;
  for (int l = 0; l  1) {
      int m = findMinIdxInSubArray(A, l, r[l]);

      //adding to center element
      r[m] = m + 1;
      //everything that was previously added to the result
      //should be stored in a and b
      a[m] = a[l];
      b[m] = b[l] + (m - l + 1) * (r - m);

      //right recursion step
      r[m + 1] = r[l];
      a[m + 1] = a[l] - A[m] * (m - l + 1);
      b[m + 1] = b[l] + r * A[m] * (m - l + 1);

      //left recursion step
      r[l] = m;
      a[l] = a[l] + A[m] * (r - m);
      b[l] = b[l] + (1 - l) * A[m] * (r - m)
    }
    result += A[l] * (a[l] * l + b[l]);
  }
```

Body:
Let's suppose the array is A={1,2,3} , now get all subarrays for this array. For each sub-array find the minimum in that sub-array, also find the sum of items in that sub-array. Finally add all these values. The input cannot be sorted as I want all possible subarrays.

Example:

Possible sub-arrays are:

{1} - min = 1, sum = 1 => min* sum = 1
{1,2} - min = 1, sum = 3 => min* sum = 3
{1,2,3} - min = 1, sum = 6 => min* sum = 6
{2} - min = 2, sum = 2 => min* sum = 4
{2,3} - min = 2, sum = 5 => min* sum = 10
{3} - min = 3, sum = 3 => min* sum = 9

Finally add all these values to get the result = 1 + 3 + 6 + 4 + 10 + 9 = 33.

constraints: array elements can range from 1 to 1000_000_000. Array size from 1 to 100_000. Return output as module 7+1000_000_000.

Here is my program with O(n^2). I want a better algorithm with lesser time complexity.

public int program(int[] A, int n) {
    int M = 7 + 1000_000_000;
    long total = 0;
    for (int i = 0; i < n; i++) {
        long sum = 0;
        int min = A[i];
        for (int j = i; j < n; j++) {
            int a = A[j];
            sum= (sum + a) % M;
            min = Math.min(min, a);
            total = (total + (min * sum) % M) % M;
        }
    }
    return (int) total;
}

Input range:

n range is 1 to 10^6
elements in array range is 1 to 10^9

Body:
This problem can be solved in O(n log n).

Basic idea

In this explanation, a lot of off-by-one errors probably sneaked in, but it does not matter for the idea. Let m be the minimum of the array. Then any subarray that contains m would have m as a minimum, and every other sub-array would be either entirely before or entirely after m. Let n be the number of elements in the array, and let us treat m as an index. Then for every i < m let's count the subarrays that contain i'th element and have m'th element as a minimum. It is exactly i * (n - m), as there are i possible left edges before i and (n - m) possible edges after m. Each of such arrays would have A[m] as a minimum, and each element with i < m would contribute to the resulting sum with a factor of i * A[m] * (n - m). For i > m with similar reasoning we would get (n - i) * A[m] * m. Then we would update the array before m and after m recursively and then just loop over to get the result.

The problem is in the update. To add these i * A[m] * (n - m) to every possible i would result in a quadratic solution. But as one can notice, both sides are linear functions with respect to i, and this is an important property. Let's rewrite the function for the right side as i * -A[m] * m + n * A[m] * m. So we would use a * i + b expression for every index. If we have two linear functions a * i + b and c * i + d, their sum would, obviously, be (a + c) * i + (b + d) - also a linear function. To conclude this optimization we would use a recursive function with two parameters: subarray currently processed and linear function to apply to each element.

The last problem to solve is finding the minimum in the subarray, but that is known as RMQ problem and can be solved in O(n log n).

The function

To speed things up we would not create subarrays, of course, but pass indices. The pseudocode for what we would like to achieve:

//This uses inclusive l and exclusive r
public int program(int[] A, int l, int r, int a, int b) {
  if (r - l == 0) {
    //array of size 0 can appear in recursive calls
    //if smallest element is first or last in its subarray
    return 0;
  }
  if (r - l == 1) {
    //for size one array there exists only one possible subarray
    //we also need to add the linear function
    return A[l] * A[l] + A[l] * (a * l + b);
  }
  //This is the call to your RMQ data structure
  int m = findMinIdxInSubArray(A, l, r);
  int result = 0;

  //to the left function would be (i + 1 - l) * A[m] * (r - m) which expands to
  //i * A[m] * (r - m) + (1 - l) * A[m] * (r - m)
  result += program(A, l, i, a + A[m] * (r - m), b + (1 - l) * A[m] * (r - m));

  //to the right function would be (r - i) * A[m] * (m - l + 1) wich expands to
  //i * -A[m] * (m - l + 1) + r * A[m] * (m - l + 1)
  result += program(A, m + 1, r, a - A[m] * (m - l + 1), b + r * A[m] * (m - l + 1));

  //This is the case for the element m itself,
  //as it is not accounted in the previous calculations
  //the linear function also needs to be accounted here
  result += A[m] * (m - l + 1) * (r - m) + A[m] * (a * m + b);
  return result;
}

Now your old function would be written like:

public int program(int A[], int n) {
  //initialize your RMQ data structure here
  return program(A, 0, n, 0, 0);
}

Note that this implementation lacks the findMinIdxInSubArray function, as i mentioned, any RMQ data structure can be used here. Feel free to use anything from Fenwick tree to sparse table.

Example
To explain this formulas a little bit better i would trace the execution of this program for an array A={3,2,1,4}

When the function is first called it has subarray from 0 inclusive to 4 not inclusive and no elements are accounted for now. The minimum of this subarray is element 1 at index 2, and m=2 therefore.

1 is minimum for all subarrays [i,j] such that i <= 2 and 2 <= j.

For element 4 to the right of 1 it appears in 3 arrays ([0,3], [1,3], [2,3]), and recursive call with function -3 * i + 12 would be called. In this function call it is the array of size one, so we would account for subarray {4} with 16 and as it is index 3, it's linear function value is -3 * 3 + 12 = 3, so we would also add 4 * 3 = 12 to account for the arrays from the first function call.

For element 1 itself, it appears in 6 arrays ([0,2],[0,3],[1,2],[1,3],[2,2] and [2,3]) and in the last formula would be added as 1 * 3 * 2 as expected, contributing 6 to the total sum.

Now for the harder array to the left. Element 3 appears in exactly 2 such arrays ([0,2] and [0,3]) and would contribute with a factor of 2 (2 arrays multiplied by minimum value 1 each) and element 2 appears in exactly 4 such arrays([0,2], [0,3], [1,2] and [1,3]). For these two elements, we would call a program with a linear function of 2*i+2, which, as one can see, matches their contribution.

In this recursive call, we would find that 2 at index 1 is the smallest element.
To the right of it, there are no elements, so the recursive call would return 0. 2 itself appears in two subarrays ([0,1] and [1,1]) and from them, it would contribute 8 (2 arrays value 2 in sum and 2 is minimum) to the total sum. But linear function mentions that we should also add 21+1=4 arrayminimums from the previous levels, which matches our computations previously with the contribution of 8. So for 2, we would add a total of 16 in this iteration.

To the left of the two, there is only one element, it is three, it appears in only one array, so its contribution factor should increase by 2 (one array, but minimum is two). The function passed recursively would be (2*i+2) + (2*i+2) = (4*i+4). When we would process the subarray of one element 3 we would add contribution of 9 from the subarray {3} and another 3*(4*0+4) to account for arrays on previous levels, and total contribution would be another 21.

Therefore, recursive function would yield a sum of 21+16+6+28=71. Now lets validate this result by hand:

{3} - min=3, sum=3, min*sum=9
{3,2} - min=2, sum=5, min*sum=10
{3,2,1} - min=1, sum=6, min*sum=6
{3,2,1,4} - min=1, sum=10, min*sum=10
{2} - min=2, sum=2, min*sum=4
{2,1} - min=1, sum=3, min*sum=3
{2,1,4} - min=1, sum=7, min*sum=7
{1} - min=1, sum=1, min*sum=1
{1,4} - min=1, sum=5, min*sum=5
{4} - min=4, sum=4, min*sum=16

Total: 9+10+6+10+4+3+7+1+5+16=71

Edit

If making stack size bigger is not possible to make recursion work, here is the same idea, but without using recursion:

//This uses inclusive l and exclusive r
public int program(int[] A) {
  //for every possible l we would store all other call parameters
  //in the deepest call with this l
  int[] r = new int[A.length];
  int[] a = new int[A.length];
  int[] b = new int[A.length];
  r[0] = A.length;
  a[0] = 0;
  b[0] = 0;
  int result = 0;
  for (int l = 0; l < A.length; ++l) {
    //this loop would go down recursive calls to
    //the deepest call with the same l
    while (r[l] - l > 1) {
      int m = findMinIdxInSubArray(A, l, r[l]);

      //adding to center element
      r[m] = m + 1;
      //everything that was previously added to the result
      //should be stored in a and b
      a[m] = a[l];
      b[m] = b[l] + (m - l + 1) * (r - m);

      //right recursion step
      r[m + 1] = r[l];
      a[m + 1] = a[l] - A[m] * (m - l + 1);
      b[m + 1] = b[l] + r * A[m] * (m - l + 1);

      //left recursion step
      r[l] = m;
      a[l] = a[l] + A[m] * (r - m);
      b[l] = b[l] + (1 - l) * A[m] * (r - m)
    }
    result += A[l] * (a[l] * l + b[l]);
  }


问:
How to get file name from download link in firebase storage?
I have image view which loads image using Glide using download link. Code is given below :

How can I get the file name stored in fire base storage from the download url ?

Glide.with(ct)
  .load(downloadurllink)
  .centerCrop();

placeholder(R.drawable.common_icon_dark)
  .into(holder.image);
```

答:
If you want to delete a file having the url, you can do this:</p>
```<code>final httpsReference = FirebaseStorage.instance.refFromURL(url);

await FirebaseStorageService.deleteFile(httpsReference.fullPath);
</code>```

Body:
If you want to delete a file having the url, you can do this:

final httpsReference = FirebaseStorage.instance.refFromURL(url);

await FirebaseStorageService.deleteFile(httpsReference.fullPath);


问:
Passing parameters from external PHP service to CakePHP controller actions
Asking this question here because in CakePHP google group got no answer.I have the following pipeline:
There is a CakePHP based application.It has a controller with an action called save_results.
The action is a method accepting 3 arguments.So it looks like this:

```<code>function save_results($data,$rawdataset,$status){

 ///stub///
   return "all the data received";
}
</code>```

Besides CakePHP app I have a WebOrb(PHP) which I use to communicate with Flash application using AMF format.The flash application sends data to WebOrb service which then sends it to the action I described above in Cake.So I receive from the Flash app 3 objects to match the params I pass into the cake method (save_results) :
data -of type array of objects.
rawdataset-of type string containing xml object.
status-unsigned integer 0 or 1.
In the WebOrb service the data received from the Flash is ok.But when I try to send it further into CakePHP it doesn't pass through.
I do it this way (In The WebOrb class):

```<code>public function sendToCake($data,$rawdataset,$status){

    $encodedData=urlencode($data);
    $encodedRawData=urlencode($rawdataset);

    $destinationURL="http://localhost/mycakeapp/resultscontroller/save_results  /".$encodedData."/". $encodedRawData."/".$status;

   return file_get_contents( $destinationURL);

}
</code>```

I found that a parameter passed into url for cake can not have spaces between characters.SO I use urlencode().It works for simple strings like "Hello world".But once I pass more complex strings like xml strings ($rawdataset object) the cake doesn't receive such a call.I tried also rawurlencode() and still no results.Is it possible that cake doesn't know how to treat xml structured strings when passed via http call? Any help or advice on this issue will be highly appreciated.

答:
For your WebOrb class, change it so it uses HttpRequest instead:

```<code>public function sendToCake($data,$rawdataset,$status){
    $url = 'http://localhost/mycakeapp/resultscontroller/save_results';
    $r = new HttpRequest($url, HttpRequest::METH_GET);
    $r->addQueryData(array('data' => $data, 'rawdata' => $rawdata, 'status' => $status));

    try {
        $r->send();
        return $r->getResponseData();
    } catch (HttpException $ex) {
        return $ex;
    }
}
</code>```

^^ You may have to tweak it around a bit to return exactly what you want.
For your CakePHP Controller / Action, inside it you can access the get request via the Parameters Attribute.

```<code>function save_results(){
    $data = $this->params[];
    //do stuff to my data;
    return $data;
}
</code>```

Hope that helps!

Body:
Asking this question here because in CakePHP google group got no answer.I have the following pipeline:
There is a CakePHP based application.It has a controller with an action called save_results.
The action is a method accepting 3 arguments.So it looks like this:

function save_results($data,$rawdataset,$status){

 ///stub///
   return "all the data received";
}

Besides CakePHP app I have a WebOrb(PHP) which I use to communicate with Flash application using AMF format.The flash application sends data to WebOrb service which then sends it to the action I described above in Cake.So I receive from the Flash app 3 objects to match the params I pass into the cake method (save_results) :
data -of type array of objects.
rawdataset-of type string containing xml object.
status-unsigned integer 0 or 1.
In the WebOrb service the data received from the Flash is ok.But when I try to send it further into CakePHP it doesn't pass through.
I do it this way (In The WebOrb class):

public function sendToCake($data,$rawdataset,$status){

    $encodedData=urlencode($data);
    $encodedRawData=urlencode($rawdataset);

    $destinationURL="http://localhost/mycakeapp/resultscontroller/save_results  /".$encodedData."/". $encodedRawData."/".$status;

   return file_get_contents( $destinationURL);

}

I found that a parameter passed into url for cake can not have spaces between characters.SO I use urlencode().It works for simple strings like "Hello world".But once I pass more complex strings like xml strings ($rawdataset object) the cake doesn't receive such a call.I tried also rawurlencode() and still no results.Is it possible that cake doesn't know how to treat xml structured strings when passed via http call? Any help or advice on this issue will be highly appreciated.

Body:
For your WebOrb class, change it so it uses HttpRequest instead:

public function sendToCake($data,$rawdataset,$status){
    $url = 'http://localhost/mycakeapp/resultscontroller/save_results';
    $r = new HttpRequest($url, HttpRequest::METH_GET);
    $r->addQueryData(array('data' => $data, 'rawdata' => $rawdata, 'status' => $status));

    try {
        $r->send();
        return $r->getResponseData();
    } catch (HttpException $ex) {
        return $ex;
    }
}

^^ You may have to tweak it around a bit to return exactly what you want.
For your CakePHP Controller / Action, inside it you can access the get request via the Parameters Attribute.

function save_results(){
    $data = $this->params[];
    //do stuff to my data;
    return $data;
}

Hope that helps!