问:
Return result using if statement with for loop in r
I would like to return the result in a vector based on the results of an if statement. My default value in the column would be "blank" and if both conditions are met ==FALSE I would like the vector/cell to have "some text". Here is what I have so far:

```<code>COMP30$Test_3<-"blank"
matches<-list(c(COMP30$PMPI_Has_Plan,COMP30$PMPI_Is_Eligible,COMP30$Test_3))
for (match in matches){if (match[1]==FALSE & match[2]==FALSE){match[3]<-"some text"}}
</code>```

After running, I am showing only "blank" even though there are instances of ==FALSE & ==FALSE. Basically, either the condition is not evaluating or the result is not being returned. Just started learning R so I am not sure what I am missing. Thanks!

答:
From what I can guess about your dataset. Please provide your data using dput.

Using vectorisation:

```<code>COMP30$Test_3<-"blank"
matches <- cbind(COMP30$PMPI_Has_Plan, COMP30$PMPI_Is_Eligible, COMP30$Test_3)
matches[!matches[,1] & !matches[,2],3] <- "Some text"
</code>```

Or with a for loop:

```<code>matches <- cbind(COMP30$PMPI_Has_Plan, COMP30$PMPI_Is_Eligible, COMP30$Test_3)
for (k in 1:nrow(matches)){
  if (!matches[k, 1] & !matches[k, 2]){
    matches[k, 3] <- "some text"
  }
}
</code>```

Body:
I would like to return the result in a vector based on the results of an if statement. My default value in the column would be "blank" and if both conditions are met ==FALSE I would like the vector/cell to have "some text". Here is what I have so far:

COMP30$Test_3<-"blank"
matches<-list(c(COMP30$PMPI_Has_Plan,COMP30$PMPI_Is_Eligible,COMP30$Test_3))
for (match in matches){if (match[1]==FALSE & match[2]==FALSE){match[3]<-"some text"}}

After running, I am showing only "blank" even though there are instances of ==FALSE & ==FALSE. Basically, either the condition is not evaluating or the result is not being returned. Just started learning R so I am not sure what I am missing. Thanks!

Body:
From what I can guess about your dataset. Please provide your data using dput.

Using vectorisation:

COMP30$Test_3<-"blank"
matches <- cbind(COMP30$PMPI_Has_Plan, COMP30$PMPI_Is_Eligible, COMP30$Test_3)
matches[!matches[,1] & !matches[,2],3] <- "Some text"

Or with a for loop:

matches <- cbind(COMP30$PMPI_Has_Plan, COMP30$PMPI_Is_Eligible, COMP30$Test_3)
for (k in 1:nrow(matches)){
  if (!matches[k, 1] & !matches[k, 2]){
    matches[k, 3] <- "some text"
  }
}


来源: stackexchange

问:
tensorflow js model (converted from Keras) has 3 outputs. How can I extract them?
I have trained a yolov3 model in Keras, and it has 3 outputs (3D tensors). No problem there.
Then I converted this model into tfjs to run it in a browser.
I can easily get the content of each one of the outputs if I truncate the model to this specific output. But I cannot get the full (3 outputs) at once. I am wondering if that is even possible?

Here's what I'd like to do (it does not work, it hangs):

```<code>const myTracker = await tf.loadLayersModel(v3_model);
const prediction = tf.tidy(() => {

      // prepare inputs tensor
      const inputs = tf.browser.fromPixels(canvas, 3).expandDims(0).toFloat().div(tf.scalar(255));
      console.log("============ inputs tensor shape:" + inputs.shape);  //--> 1,416,416,3

      // get all 3 outputs
      const outputs = myTracker.predict(inputs).arraySync();
      outputs.print();
      return outputs;
});
</code>```

And here's what works if I am only interested in 1 output, after identifying the 3 outputs names.

```<code>const myTracker = await tf.loadLayersModel(v3_model);
const prediction = tf.tidy(() => {

      // prepare inputs tensor
      const inputs = tf.browser.fromPixels(canvas, 3).expandDims(0).toFloat().div(tf.scalar(255));
      console.log("============ inputs tensor shape:" + inputs.shape);  //--> 1,416,416,3

      // get the full object of interesting layers
      const layer3 = myTracker.getLayer('conv2d_3');
      const layer8 = myTracker.getLayer('conv2d_8');
      const layer13= myTracker.getLayer('conv2d_13');

      // get 1 specific output from a new model build from the original
      const myTracker_truncated = tf.model({inputs: myTracker.inputs, outputs: layer3.output});
      const outputs = myTracker_truncated.predict(inputs).arraySync();
      return outputs;
});
</code>```

If I inpect (console.log(myTracker)) I get this structure for my outputs:

```<code>outputNames: (3) […]
0: "conv2d_3
1: "conv2d_8"
2: "conv2d_13"
length: 3

outputs: (3) […]
0: Object { dtype: "float32", id: 662, originalName: "conv2d_3/conv2d_3", … }
1: Object { dtype: "float32", id: 665, originalName: "conv2d_8/conv2d_8", … }
2: Object { dtype: "float32", id: 668, originalName: "conv2d_13/conv2d_13", … }
length: 3
</code>```

Would anybody know if what I am trying to achieve is feasible (short of concatenating the 3 outputs into 1 in the original keras model) ?

答:
The thee outputs can be obtained by using an array of outputs when creating the model with tf.model

```<code>tf.model({inputs: myTracker.inputs, outputs: [layer3.output, layer8.output, layer13.output, ...]});

prediction = myTracker_truncated.predict(inputs).arraySync()
</code>```

now prediction will be an array of three values respectively to the layers defined in outputs

ContentLicense: CC BY-SA 4.0

Body:
I have trained a yolov3 model in Keras, and it has 3 outputs (3D tensors). No problem there.
Then I converted this model into tfjs to run it in a browser.
I can easily get the content of each one of the outputs if I truncate the model to this specific output. But I cannot get the full (3 outputs) at once. I am wondering if that is even possible?

Here's what I'd like to do (it does not work, it hangs):

const myTracker = await tf.loadLayersModel(v3_model);
const prediction = tf.tidy(() => {

      // prepare inputs tensor
      const inputs = tf.browser.fromPixels(canvas, 3).expandDims(0).toFloat().div(tf.scalar(255));
      console.log("============ inputs tensor shape:" + inputs.shape);  //--> 1,416,416,3

      // get all 3 outputs
      const outputs = myTracker.predict(inputs).arraySync();
      outputs.print();
      return outputs;
});

And here's what works if I am only interested in 1 output, after identifying the 3 outputs names.

const myTracker = await tf.loadLayersModel(v3_model);
const prediction = tf.tidy(() => {

      // prepare inputs tensor
      const inputs = tf.browser.fromPixels(canvas, 3).expandDims(0).toFloat().div(tf.scalar(255));
      console.log("============ inputs tensor shape:" + inputs.shape);  //--> 1,416,416,3

      // get the full object of interesting layers
      const layer3 = myTracker.getLayer('conv2d_3');
      const layer8 = myTracker.getLayer('conv2d_8');
      const layer13= myTracker.getLayer('conv2d_13');

      // get 1 specific output from a new model build from the original
      const myTracker_truncated = tf.model({inputs: myTracker.inputs, outputs: layer3.output});
      const outputs = myTracker_truncated.predict(inputs).arraySync();
      return outputs;
});

If I inpect (console.log(myTracker)) I get this structure for my outputs:

outputNames: (3) […]
0: "conv2d_3
1: "conv2d_8"
2: "conv2d_13"
length: 3

outputs: (3) […]
0: Object { dtype: "float32", id: 662, originalName: "conv2d_3/conv2d_3", … }
1: Object { dtype: "float32", id: 665, originalName: "conv2d_8/conv2d_8", … }
2: Object { dtype: "float32", id: 668, originalName: "conv2d_13/conv2d_13", … }
length: 3

Would anybody know if what I am trying to achieve is feasible (short of concatenating the 3 outputs into 1 in the original keras model) ?

Body:
The thee outputs can be obtained by using an array of outputs when creating the model with tf.model

tf.model({inputs: myTracker.inputs, outputs: [layer3.output, layer8.output, layer13.output, ...]});

prediction = myTracker_truncated.predict(inputs).arraySync()

now prediction will be an array of three values respectively to the layers defined in outputs


问:
How to store & retrieve an object as a value in option of select element?
How to store & retrieve an object as a value for option of select element?</p>

```<code><select>
  <option value = "{}" selected>lorem</option>
</select>
</code>```

答:
agree with KiaiFighter. create an array of objects. and populate/create your options from it. then use the filter function to retrieve the selected object. run the snippet below for an example

const myarray = [
  {value: 'one', text: 'one', otherstuff: 'A'},
  {value: 'two', text: 'two', otherstuff: 'B'},
  {value: 'three', text: 'three', otherstuff: 'C'},
  {value: 'four', text: 'four', otherstuff: 'D'},
]

const options = myarray.map(x => `<option value="${x.value}">${x.text}</option>`);
$('#myselect').append(options);

// find elements
$('#mybutton').click(()=> console.log(myarray.filter(x => x.value == $('#myselect').val())[0]));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id = "myselect">
 </select>

<button id="mybutton">
submit
</button></code>```

Body:
How to store & retrieve an object as a value for option of select element?

<select>
  <option value = "{}" selected>lorem</option>
</select>

Body:
agree with KiaiFighter. create an array of objects. and populate/create your options from it. then use the filter function to retrieve the selected object. run the snippet below for an example

const myarray = [
  {value: 'one', text: 'one', otherstuff: 'A'},
  {value: 'two', text: 'two', otherstuff: 'B'},
  {value: 'three', text: 'three', otherstuff: 'C'},
  {value: 'four', text: 'four', otherstuff: 'D'},
]

const options = myarray.map(x => `<option value="${x.value}">${x.text}</option>`);
$('#myselect').append(options);

// find elements
$('#mybutton').click(()=> console.log(myarray.filter(x => x.value == $('#myselect').val())[0]));

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id = "myselect">
 </select>

<button id="mybutton">
submit
</button>


问:
How to change the uinavigationbar title's position?
I've managed to change the navigationbar height by using my own navigationbar, but the title is still centered. I want it to be at the 72px position from the left.

```<code>override func sizeThatFits(size: CGSize) -> CGSize {
   return CGSizeMake(UIScreen.mainScreen().bounds.width, 56)
}
</code>```

I used this to change the height but I didn't find a way to change the position of all the items.
I tried to set the frame but I can't. I can't change the position of the button too.

i wanna look like this

答:
Setting custom view with left align.

Setting custom view as leftBarButtonItem is not conveniently, because we will have a problems with back button.

Setting custom view as subview of navigationBar is not conveniently because:

we can't to easy control width of custom view when right buttons are set. We can get overlapping custom view and right buttons

we need to add custom navTitleView and remove it every viewWillAppear and viewWillDissapear. This is additional, not clean code.

So?
I've just added width constraint to the customTitleView.

Inside of CustomTitleView class:

```<code>  private func layoutViewsConfig() {
    // Width constraint needed to align view to left
    let widthConstraint = NSLayoutConstraint.init(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: UIScreen.main.bounds.width)
    widthConstraint.priority = .init(748)
    let heightConstraint = NSLayoutConstraint.init(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)
   self.addConstraint(widthConstraint)
   self.addConstraint(heightConstraint)
  }
</code>```

Then, inside of your ViewController:

```<code>var navigationTitleView = NavigationSubtitleView()
self.navigationItem.titleView = navigationTitleView
</code>```

And we have:

ContentLicense: CC BY-SA 3.0

Body:
I've managed to change the navigationbar height by using my own navigationbar, but the title is still centered. I want it to be at the 72px position from the left.

override func sizeThatFits(size: CGSize) -> CGSize {
   return CGSizeMake(UIScreen.mainScreen().bounds.width, 56)
}

I used this to change the height but I didn't find a way to change the position of all the items.
I tried to set the frame but I can't. I can't change the position of the button too.

i wanna look like this

Body:
Setting custom view with left align.

Setting custom view as leftBarButtonItem is not conveniently, because we will have a problems with back button.

Setting custom view as subview of navigationBar is not conveniently because:

we can't to easy control width of custom view when right buttons are set. We can get overlapping custom view and right buttons

we need to add custom navTitleView and remove it every viewWillAppear and viewWillDissapear. This is additional, not clean code.

So?
I've just added width constraint to the customTitleView.

Inside of CustomTitleView class:

  private func layoutViewsConfig() {
    // Width constraint needed to align view to left
    let widthConstraint = NSLayoutConstraint.init(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: UIScreen.main.bounds.width)
    widthConstraint.priority = .init(748)
    let heightConstraint = NSLayoutConstraint.init(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)
   self.addConstraint(widthConstraint)
   self.addConstraint(heightConstraint)
  }

Then, inside of your ViewController:

var navigationTitleView = NavigationSubtitleView()
self.navigationItem.titleView = navigationTitleView

And we have:


问:
How can I extract the values of the last aggregation date in sql
I have the following table.

```<code>id  user    time_stamp
1   Mike    2020-02-13 00:00:00 UTC
2   John    2020-02-13 00:00:00 UTC
3   Levy    2020-02-12 00:00:00 UTC
4   Sam     2020-02-12 00:00:00 UTC
5   Frodo   2020-02-11 00:00:00 UTC
</code>```

Let's say 2020-02-13 00:00:00 UTC is the last day and I would like to query this table to only display last days results? I want to create a view in Bigquery so that I only and always get the last day's results?

So that in the end I get something like this (For last day which is 2020-02-13 00:00:00 UTC )

```<code>id  user    time_stamp
1   Mike    2020-02-13 00:00:00 UTC
2   John    2020-02-13 00:00:00 UTC
</code>```

答:
You can use window functions:

```<code>select t.* except (seqnum)
from (select t.*,
             dense_rank() over (order by time_stamp) as seqnum
      from t
     ) t
where seqnum = 1;
</code>```

This may not work well on a large amount of data -- because of the way that BQ implements window functions with no partitioning.  So, you might find that this works better (especially if the above runs out of resources):

```<code>select t.*
from t join
     (select max(time_stamp) as max_time_stamp
      from t
     ) tt
     on t.time_stamp = max_time_stamp;
</code>```

Also, if the timestamps actually have date components, then you will want to convert to a date or remove the time component somehow.

Body:
I have the following table.

id  user    time_stamp
1   Mike    2020-02-13 00:00:00 UTC
2   John    2020-02-13 00:00:00 UTC
3   Levy    2020-02-12 00:00:00 UTC
4   Sam     2020-02-12 00:00:00 UTC
5   Frodo   2020-02-11 00:00:00 UTC

Let's say 2020-02-13 00:00:00 UTC is the last day and I would like to query this table to only display last days results? I want to create a view in Bigquery so that I only and always get the last day's results?

So that in the end I get something like this (For last day which is 2020-02-13 00:00:00 UTC )

id  user    time_stamp
1   Mike    2020-02-13 00:00:00 UTC
2   John    2020-02-13 00:00:00 UTC

Body:
You can use window functions:

select t.* except (seqnum)
from (select t.*,
             dense_rank() over (order by time_stamp) as seqnum
      from t
     ) t
where seqnum = 1;

This may not work well on a large amount of data -- because of the way that BQ implements window functions with no partitioning.  So, you might find that this works better (especially if the above runs out of resources):

select t.*
from t join
     (select max(time_stamp) as max_time_stamp
      from t
     ) tt
     on t.time_stamp = max_time_stamp;

Also, if the timestamps actually have date components, then you will want to convert to a date or remove the time component somehow.


问:
Injecting jQuery css via a bookmarklet
This will be a very dummy question, but... I want to add some css styles to a page, when browsing it, simply by clicking on a bookmarklet. It will save me some time :)

For instance, this code works :

```<code>javascript:void( jQuery( ".fancybox-overlay-fixed").css("background-color","black" ) );
</code>```

But how come this one doesnt? It returns to me an error because of ";" before the second jquery.

```<code>javascript:void( jQuery( ".fancybox-overlay-fixed").css("background-color","black" ); jQuery( ".fancybox-close").css({ "display":"none"}); );
</code>```

Any idea of how to adapt it, in order to add styles to more than 1 element?
Thanks !

答:
You can try this code :

```<code>$( ".fancybox-overlay-fixed").css("background-color","black" );
$( ".fancybox-close").css({ "display":"none"});
</code>```

https://codepen.io/yakupov112/pen/LYVRdxp

Title: Injecting jQuery css via a bookmarklet

Body:
This will be a very dummy question, but... I want to add some css styles to a page, when browsing it, simply by clicking on a bookmarklet. It will save me some time :)

For instance, this code works :

javascript:void( jQuery( ".fancybox-overlay-fixed").css("background-color","black" ) );

But how come this one doesnt? It returns to me an error because of ";" before the second jquery.

javascript:void( jQuery( ".fancybox-overlay-fixed").css("background-color","black" ); jQuery( ".fancybox-close").css({ "display":"none"}); );

Any idea of how to adapt it, in order to add styles to more than 1 element?
Thanks !

Body:
You can try this code :

$( ".fancybox-overlay-fixed").css("background-color","black" );
$( ".fancybox-close").css({ "display":"none"});

https://codepen.io/yakupov112/pen/LYVRdxp


问:
Config Nanoc in Docker Error facing "Nanoc::Core::ConfigLoader::NoConfigFileFoundError: No configuration file found"
I try to create nanoc Markdown Documentation page deployment using docker.

Docker container was created successfully.

While running the container i am getting the nanoc configuration error and container stopped.

I have mentioned the steps followed for implementation.

Followed Steps

Step 1

Docker file

```<code>FROM ruby:latest

# Create app directory

WORKDIR /usr/src/app

COPY Gemfile .

# Copy the files
COPY . ./docs

RUN bundler install
RUN apt update

# Start the development/staging server
EXPOSE 3000
CMD ["bundler","exec","nanoc","view" ]
</code>```

Step 2

```<code>docker build -t nanoc:latest .
</code>```

Step 3

```<code>docker run -p 0.0.0.0:3000:3000 --name nanoc-latest -t -d nanoc:latest
</code>```

Docker Logs container ID

答:
Docker file update:

```<code>FROM ruby:2.3
RUN mkdir -p /user/src/app
COPY . /usr/src/app
WORKDIR /usr/src/app/docs

RUN bundle install
RUN bundle exec nanoc
EXPOSE 3000
CMD bundle exec nanoc view
</code>```

This configuration will sole the above error.

Body:
I try to create nanoc Markdown Documentation page deployment using docker.

Docker container was created successfully.

While running the container i am getting the nanoc configuration error and container stopped.

I have mentioned the steps followed for implementation.

Followed Steps

Step 1

Docker file

FROM ruby:latest

# Create app directory

WORKDIR /usr/src/app

COPY Gemfile .

# Copy the files
COPY . ./docs

RUN bundler install
RUN apt update

# Start the development/staging server
EXPOSE 3000
CMD ["bundler","exec","nanoc","view" ]

Step 2

docker build -t nanoc:latest .

Step 3

docker run -p 0.0.0.0:3000:3000 --name nanoc-latest -t -d nanoc:latest

Docker Logs container ID

Body:
Docker file update:

FROM ruby:2.3
RUN mkdir -p /user/src/app
COPY . /usr/src/app
WORKDIR /usr/src/app/docs

RUN bundle install
RUN bundle exec nanoc
EXPOSE 3000
CMD bundle exec nanoc view

This configuration will sole the above error.


问:
Find conflicted date intervals using SQL
Suppose I have following table in Sql Server 2008:

```<code>ItemId StartDate   EndDate
1      NULL        2011-01-15
2      2011-01-16  2011-01-25
3      2011-01-26  NULL
</code>```

As you can see, this table has StartDate and EndDate columns. I want to validate data in these columns. Intervals cannot conflict with each other. So, the table above is valid, but the next table is invalid, becase first row has End Date greater than StartDate in the second row.

```<code>ItemId StartDate   EndDate
1      NULL        2011-01-17
2      2011-01-16  2011-01-25
3      2011-01-26  NULL
</code>```

NULL means infinity here.

Could you help me to write a script for data validation?

[The second task]

Thanks for the answers.
I have a complication. Let's assume, I have such table:

```<code>ItemId  IntervalId StartDate   EndDate
1       1          NULL        2011-01-15
2       1          2011-01-16  2011-01-25
3       1          2011-01-26  NULL
4       2          NULL        2011-01-17
5       2          2011-01-16  2011-01-25
6       2          2011-01-26  NULL
</code>```

Here I want to validate intervals within a groups of IntervalId, but not within the whole table. So, Interval 1 will be valid, but Interval 2 will be invalid.

And also. Is it possible to add a constraint to the table in order to avoid such invalid records?

[Final Solution]

I created function to check if interval is conflicted:

```<code>CREATE FUNCTION [dbo].[fnIntervalConflict]
(
    @intervalId INT,
    @originalItemId INT,
    @startDate DATETIME,
    @endDate DATETIME
)
RETURNS BIT
AS
BEGIN

    SET @startDate = ISNULL(@startDate,'1/1/1753 12:00:00 AM')
    SET @endDate = ISNULL(@endDate,'12/31/9999 11:59:59 PM')

    DECLARE @conflict BIT = 0

    SELECT TOP 1 @conflict = 1
    FROM Items
    WHERE IntervalId = @intervalId
    AND ItemId <> @originalItemId
    AND (
    (ISNULL(StartDate,'1/1/1753 12:00:00 AM') >= @startDate
     AND ISNULL(StartDate,'1/1/1753 12:00:00 AM') <= @endDate)
     OR (ISNULL(EndDate,'12/31/9999 11:59:59 PM') >= @startDate
     AND ISNULL(EndDate,'12/31/9999 11:59:59 PM') <= @endDate)
    )

    RETURN @conflict
END
</code>```

And then I added 2 constraints to my table:

```<code>ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_Dates CHECK (StartDate IS NULL OR EndDate IS NULL OR StartDate <= EndDate)

GO
</code>```

and

```<code>ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_ValidInterval CHECK (([dbo].[fnIntervalConflict]([IntervalId], ItemId,[StartDate],[EndDate])=(0)))

GO
</code>```

I know, the second constraint slows insert and update operations, but it is not very important for my application.
And also, now I can call function fnIntervalConflict from my application code before inserts and updates of data in the table.

Body:
Suppose I have following table in Sql Server 2008:

ItemId StartDate   EndDate
1      NULL        2011-01-15
2      2011-01-16  2011-01-25
3      2011-01-26  NULL

As you can see, this table has StartDate and EndDate columns. I want to validate data in these columns. Intervals cannot conflict with each other. So, the table above is valid, but the next table is invalid, becase first row has End Date greater than StartDate in the second row.

ItemId StartDate   EndDate
1      NULL        2011-01-17
2      2011-01-16  2011-01-25
3      2011-01-26  NULL

NULL means infinity here.

Could you help me to write a script for data validation?

[The second task]

Thanks for the answers.
I have a complication. Let's assume, I have such table:

ItemId  IntervalId StartDate   EndDate
1       1          NULL        2011-01-15
2       1          2011-01-16  2011-01-25
3       1          2011-01-26  NULL
4       2          NULL        2011-01-17
5       2          2011-01-16  2011-01-25
6       2          2011-01-26  NULL

Here I want to validate intervals within a groups of IntervalId, but not within the whole table. So, Interval 1 will be valid, but Interval 2 will be invalid.

And also. Is it possible to add a constraint to the table in order to avoid such invalid records?

[Final Solution]

I created function to check if interval is conflicted:

CREATE FUNCTION [dbo].[fnIntervalConflict]
(
    @intervalId INT,
    @originalItemId INT,
    @startDate DATETIME,
    @endDate DATETIME
)
RETURNS BIT
AS
BEGIN

    SET @startDate = ISNULL(@startDate,'1/1/1753 12:00:00 AM')
    SET @endDate = ISNULL(@endDate,'12/31/9999 11:59:59 PM')

    DECLARE @conflict BIT = 0

    SELECT TOP 1 @conflict = 1
    FROM Items
    WHERE IntervalId = @intervalId
    AND ItemId <> @originalItemId
    AND (
    (ISNULL(StartDate,'1/1/1753 12:00:00 AM') >= @startDate
     AND ISNULL(StartDate,'1/1/1753 12:00:00 AM') <= @endDate)
     OR (ISNULL(EndDate,'12/31/9999 11:59:59 PM') >= @startDate
     AND ISNULL(EndDate,'12/31/9999 11:59:59 PM') <= @endDate)
    )

    RETURN @conflict
END

And then I added 2 constraints to my table:

ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_Dates CHECK (StartDate IS NULL OR EndDate IS NULL OR StartDate <= EndDate)

GO

and

ALTER TABLE dbo.Items ADD CONSTRAINT
    CK_Items_ValidInterval CHECK (([dbo].[fnIntervalConflict]([IntervalId], ItemId,[StartDate],[EndDate])=(0)))

GO

I know, the second constraint slows insert and update operations, but it is not very important for my application.
And also, now I can call function fnIntervalConflict from my application code before inserts and updates of data in the table.

Body:
declare @T table (ItemId int, IntervalID int, StartDate datetime,   EndDate datetime)

insert into @T
select 1, 1,  NULL,        '2011-01-15' union all
select 2, 1, '2011-01-16', '2011-01-25' union all
select 3, 1, '2011-01-26',  NULL        union all
select 4, 2,  NULL,        '2011-01-17' union all
select 5, 2, '2011-01-16', '2011-01-25' union all
select 6, 2, '2011-01-26',  NULL

select T1.*
from @T as T1
  inner join @T as T2
    on coalesce(T1.StartDate, '1753-01-01') < coalesce(T2.EndDate, '9999-12-31') and
       coalesce(T1.EndDate, '9999-12-31') > coalesce(T2.StartDate, '1753-01-01') and
       T1.IntervalID = T2.IntervalID and
       T1.ItemId <> T2.ItemId

Result:

ItemId      IntervalID  StartDate               EndDate
----------- ----------- ----------------------- -----------------------
5           2           2011-01-16 00:00:00.000 2011-01-25 00:00:00.000
4           2           NULL                    2011-01-17 00:00:00.000


问:
Cannot find setter for field - using Kotlin with Room database
I'm integrating with the Room persistence library. I have a data class in Kotlin like:

```<code>@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        val by: String,
        val descendants: Int,
        val score: Int,
        val time: Long,
        val title: String,
        val type: String,
        val url: String
)
</code>```

The @Entity and @PrimaryKey annotations are for the Room library. When I try to build, it is failing with error:

```<code>Error:Cannot find setter for field.
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
</code>```

I also tried providing a default constructor:

```<code>@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        val by: String,
        val descendants: Int,
        val score: Int,
        val time: Long,
        val title: String,
        val type: String,
        val url: String
) {
    constructor() : this(0, "", 0, 0, 0, "", "", "")
}
</code>```

But this doesn't work as well. A thing to note is that it works if I convert this Kotlin class into a Java class with getters and setters. Any help is appreciated!

答:
Just use var instead of val and if you are using private keyword, make it public.</p>

```<code>@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        var by: String,
        var descendants: Int,
        var score: Int,
        var time: Long,
        var title: String,
        var type: String,
        var url: String
)
</code>```

Body:
I'm integrating with the Room persistence library. I have a data class in Kotlin like:

@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        val by: String,
        val descendants: Int,
        val score: Int,
        val time: Long,
        val title: String,
        val type: String,
        val url: String
)

The @Entity and @PrimaryKey annotations are for the Room library. When I try to build, it is failing with error:

Error:Cannot find setter for field.
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

I also tried providing a default constructor:

@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        val by: String,
        val descendants: Int,
        val score: Int,
        val time: Long,
        val title: String,
        val type: String,
        val url: String
) {
    constructor() : this(0, "", 0, 0, 0, "", "", "")
}

But this doesn't work as well. A thing to note is that it works if I convert this Kotlin class into a Java class with getters and setters. Any help is appreciated!

Body:
Just use var instead of val and if you are using private keyword, make it public.

@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        var by: String,
        var descendants: Int,
        var score: Int,
        var time: Long,
        var title: String,
        var type: String,
        var url: String
)


问:
Running Esper in ARM Cortex-M4
Is it possible to run Esper CEP in an LPC4088 microcontroller with a 120 MHz ARM Cortex-M4 core?

I wonder if it is possible to it under JVM or using Nesper for .NET.

答: Esper needs a 1.8 or higher JVM. As long as that hardware can run a JVM you should be ok. Nesper needs a certain minimum .NET CLR, same there.</p>

Title: Running Esper in ARM Cortex-M4


问:
The toggle in the script isn't working for me
I'm using this code that I found online, but it's not working completely the way I want it to.

Basically I am wanting check boxes to hide divs based on the users selection.
I am building an allergens advice page for a restaurant. When a guest selects the allergens they have I want it to hide the dishes that they cannot have.

The above code works perfectly if the guest has one allergen. It hides the div. If they select more than one then the box will reappear.

$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
    var inputValue = $(this).attr("value");
    $("." + inputValue).toggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="selectt Eggs Gluten">
    <strong>Dough Balls</strong><br/>
    Cheese dough balls served with chipotle butter.
</div>
<ul>
    <li>
        <input type="checkbox" id="checkboxThree" value="Eggs">
        <label for="checkboxThree"> Eggs</label>
    </li>
</ul></code>```

I'm guessing it's doing it because the code is toggling, but I don't know of any other code to prevent that.
Your help would be greatly appreciated.

答:
I've rewritten the code without jQuery, as it doesn't seem to need it...

Here is the pen: https://codepen.io/paulmartin91/pen/ExjgQBJ?editors=1011

JS

```<code>    //object containing each allergen. Add them to this object when adding them to the list - always set to false as default
let choices = {
    Eggs: false,
    Gluten: false
  }

let clickedBox  = (input) => {
  //mark the selected allergen as checked
  choices[input.value] = input.checked
  //returns an array of classes for each element with the selected allergen
  let selected = document.getElementsByClassName(input.value)
  //iterates though array of elements with selected allergen
  for (let i = 0; i < selected.length; i++) {
    //creates an array of classes for each element
    var classList = selected[i].className.split(' ')
    var counter = 0
    classList.forEach(x=>{
      //if the element contains a class that is checked, hide it
      if (choices[x]) {selected[i].style.display = 'none'} else{
        //count the number of classes that aren't checked
        counter++
        //if the element has no classes that are checked, show it
        if (counter == classList.length) {selected[i].style.display = 'block'}
      };
    })
  }
  };
</code>```

HTML

```<code><div class=" Eggs Gluten">
        <strong>Eggs Gluten</strong>
</div>
<div class="Eggs ">
        <strong>Eggs</strong>
</div>
<div class="Gluten ">
        <strong>Gluten</strong>
</div>

<li>
  <input
         onclick = 'clickedBox(this)'
         type="checkbox"
         id="checkboxOne"
         value="Eggs">
  <label for="checkboxOne"> Eggs</label>
  <input
         onclick = 'clickedBox(this)'
         type="checkbox"
         id="checkboxTwo"
         value="Gluten">
  <label for="checkboxTwo"> Gluten</label>

</li>
</code>```

It now iterates through all the elements that match the class and hide/show them based on the condition of the checked box.

Hope this helps!

Edit: fixed code, should work now!

Body:
I'm using this code that I found online, but it's not working completely the way I want it to.

Basically I am wanting check boxes to hide divs based on the users selection.
I am building an allergens advice page for a restaurant. When a guest selects the allergens they have I want it to hide the dishes that they cannot have.

The above code works perfectly if the guest has one allergen. It hides the div. If they select more than one then the box will reappear.

$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
    var inputValue = $(this).attr("value");
    $("." + inputValue).toggle();
});

    Dough Balls

    Cheese dough balls served with chipotle butter.

        <input type="checkbox" id="checkboxThree" value="Eggs">
         Eggs

I'm guessing it's doing it because the code is toggling, but I don't know of any other code to prevent that.
Your help would be greatly appreciated.

Body:
I've rewritten the code without jQuery, as it doesn't seem to need it...

Here is the pen: https://codepen.io/paulmartin91/pen/ExjgQBJ?editors=1011

JS

    //object containing each allergen. Add them to this object when adding them to the list - always set to false as default
let choices = {
    Eggs: false,
    Gluten: false
  }

let clickedBox  = (input) => {
  //mark the selected allergen as checked
  choices[input.value] = input.checked
  //returns an array of classes for each element with the selected allergen
  let selected = document.getElementsByClassName(input.value)
  //iterates though array of elements with selected allergen
  for (let i = 0; i < selected.length; i++) {
    //creates an array of classes for each element
    var classList = selected[i].className.split(' ')
    var counter = 0
    classList.forEach(x=>{
      //if the element contains a class that is checked, hide it
      if (choices[x]) {selected[i].style.display = 'none'} else{
        //count the number of classes that aren't checked
        counter++
        //if the element has no classes that are checked, show it
        if (counter == classList.length) {selected[i].style.display = 'block'}
      };
    })
  }
  };

HTML

<div class=" Eggs Gluten">
        <strong>Eggs Gluten</strong>
</div>
<div class="Eggs ">
        <strong>Eggs</strong>
</div>
<div class="Gluten ">
        <strong>Gluten</strong>
</div>

<li>
  <input
         onclick = 'clickedBox(this)'
         type="checkbox"
         id="checkboxOne"
         value="Eggs">
  <label for="checkboxOne"> Eggs</label>
  <input
         onclick = 'clickedBox(this)'
         type="checkbox"
         id="checkboxTwo"
         value="Gluten">
  <label for="checkboxTwo"> Gluten</label>

</li>

It now iterates through all the elements that match the class and hide/show them based on the condition of the checked box.

Hope this helps!

Edit: fixed code, should work now!


问:
Reading class properties inside from javascript code
Is it possible to read the class values of the style's part from script part in vue?

e.g I have:

```<code>.node-output02 {
    bottom: #{-2+$portSize/-2}px;
    left: #{$nodeWidth/3}px;
  }
</code>```

in script I want to do:

```<code>const left = .node-output02.left
</code>```

答:
This is less of a Vue issue and more of a general JS issue.

Using this code (for obtaining the CSS text from a stylesheet), you can parse the CSS into a query-able object.

It's not fool-proof, but it's a start.

console.log('left =', getStyleObject('.node-output02')['left']); // 420px

function getStyleText(className) {
  let classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules,
      styleText = '';
  Array.from(classes).forEach(clazz => {
    if (clazz.selectorText == className) {
      styleText += clazz.cssText || clazz.style.cssText;
    }
  });
  return styleText;
}

function getStyleObject(className) {
  let styleText = getStyleText(className);
  if (styleText.length > 0) {
    let leftBraceIndex = styleText.indexOf('{'),
        rightBraceIndex = styleText.lastIndexOf('}'),
        selector = styleText.substring(0, leftBraceIndex).trim(),
        ruleText = styleText.substring(leftBraceIndex + 1, rightBraceIndex).trim();
    return Object.fromEntries(ruleText.split(/\s*;\s*/g)
      .filter(v => v.length > 0) // filter out empty (if there is a trailing semi-colon)
      .map(v => v.split(/\s*:\s*/g)));
  }
  return null;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.node-output02 {
  bottom: 360px;
  left: 420px;
}</code>```

Multiple style rules...

In the example below, everything is merged top-to-bottom, but !important is ignored, a reducer might be a better option.

console.log('left =', getStyleObject('.node-output02')['left']); // 100%;

function getStyleText(className) {
  let classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules,
      styles = [];
  Array.from(classes).forEach(clazz => {
    if (clazz.selectorText == className) {
      let styleText = clazz.cssText || clazz.style.cssText,
          leftBraceIndex = styleText.indexOf('{'),
          rightBraceIndex = styleText.lastIndexOf('}'),
          selector = styleText.substring(0, leftBraceIndex).trim(),
          ruleText = styleText.substring(leftBraceIndex + 1, rightBraceIndex).trim();
      styles.push(ruleText);
    }
  });
  return styles;
}

function getStyleObject(className) {
  return Object.assign.apply({}, getStyleText(className).map(ruleText => {
    return Object.fromEntries(ruleText.split(/\s*;\s*/g)
      .filter(v => v.length > 0)
      .map(v => v.split(/\s*:\s*/g)));
  }));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.node-output02 {
  bottom: 360px;
  left: 420px;
}

.node-output02 {
  left: 5em !important; /* This should precedence... */
}

.node-output02 {
  left: 100%; /* This will be the returned value. */
}</code>```

Reducer

If you want to maintain precedence, you can identify !important exceptions.

Again, this is not fool-proof, because selector specificity is not maintained either. But it is more robust than the code above.

console.log('left =', getStyleObject('.node-output02')['left']); // 5em

function getStyleText(className) {
  let classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules,
      styles = [];
  Array.from(classes).forEach(clazz => {
    if (clazz.selectorText == className) {
      let styleText = clazz.cssText || clazz.style.cssText,
          leftBraceIndex = styleText.indexOf('{'),
          rightBraceIndex = styleText.lastIndexOf('}'),
          selector = styleText.substring(0, leftBraceIndex).trim(),
          ruleText = styleText.substring(leftBraceIndex + 1, rightBraceIndex).trim();
      styles.push(ruleText);
    }
  });
  return styles;
}

function getStyleObject(className) {
  return cleanupValues(getStyleText(className).reduce((result, ruleText) => {
    let css = parseRuleText(ruleText);
    for (let [prop, value] of Object.entries(css)) {
      if (result.hasOwnProperty(prop) &&
          result[prop].includes('!important') &&
          !value.includes('!important')) {
        continue; // ignore...
      }
      result[prop] = value;
    }
    return result;
  }, {}));
}

function parseRuleText(ruleText) {
  return Object.fromEntries(ruleText.split(/\s*;\s*/g)
    .filter(v => v.length > 0)
    .map(v => v.split(/\s*:\s*/g)));
}

function cleanupValues(css) {
  for (let [prop, value] of Object.entries(css)) {
    if (value.includes('!important')) {
      css[prop] = value.replace(/\s*!important/, '');
    }
  }
  return css;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.node-output02 {
  bottom: 360px;
  left: 420px;
}

.node-output02 {
  left: 5em !important; /* This will be the returned value. */
}

.node-output02 {
  left: 100%; /* Not as important as the preceeding rule. */
}</code>```

Body:
Is it possible to read the class values of the style's part from script part in vue?

e.g I have:

.node-output02 {
    bottom: #{-2+$portSize/-2}px;
    left: #{$nodeWidth/3}px;
  }

in script I want to do:

const left = .node-output02.left

Body:
This is less of a Vue issue and more of a general JS issue.

Using this code (for obtaining the CSS text from a stylesheet), you can parse the CSS into a query-able object.

It's not fool-proof, but it's a start.

console.log('left =', getStyleObject('.node-output02')['left']); // 420px

function getStyleText(className) {
  let classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules,
      styleText = '';
  Array.from(classes).forEach(clazz => {
    if (clazz.selectorText == className) {
      styleText += clazz.cssText || clazz.style.cssText;
    }
  });
  return styleText;
}

function getStyleObject(className) {
  let styleText = getStyleText(className);
  if (styleText.length > 0) {
    let leftBraceIndex = styleText.indexOf('{'),
        rightBraceIndex = styleText.lastIndexOf('}'),
        selector = styleText.substring(0, leftBraceIndex).trim(),
        ruleText = styleText.substring(leftBraceIndex + 1, rightBraceIndex).trim();
    return Object.fromEntries(ruleText.split(/\s*;\s*/g)
      .filter(v => v.length > 0) // filter out empty (if there is a trailing semi-colon)
      .map(v => v.split(/\s*:\s*/g)));
  }
  return null;
}

.node-output02 {
  bottom: 360px;
  left: 420px;
}

Multiple style rules...

In the example below, everything is merged top-to-bottom, but !important is ignored, a reducer might be a better option.

console.log('left =', getStyleObject('.node-output02')['left']); // 100%;

function getStyleText(className) {
  let classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules,
      styles = [];
  Array.from(classes).forEach(clazz => {
    if (clazz.selectorText == className) {
      let styleText = clazz.cssText || clazz.style.cssText,
          leftBraceIndex = styleText.indexOf('{'),
          rightBraceIndex = styleText.lastIndexOf('}'),
          selector = styleText.substring(0, leftBraceIndex).trim(),
          ruleText = styleText.substring(leftBraceIndex + 1, rightBraceIndex).trim();
      styles.push(ruleText);
    }
  });
  return styles;
}

function getStyleObject(className) {
  return Object.assign.apply({}, getStyleText(className).map(ruleText => {
    return Object.fromEntries(ruleText.split(/\s*;\s*/g)
      .filter(v => v.length > 0)
      .map(v => v.split(/\s*:\s*/g)));
  }));
}

.node-output02 {
  bottom: 360px;
  left: 420px;
}

.node-output02 {
  left: 5em !important; /* This should precedence... */
}

.node-output02 {
  left: 100%; /* This will be the returned value. */
}

Reducer

If you want to maintain precedence, you can identify !important exceptions.

Again, this is not fool-proof, because selector specificity is not maintained either. But it is more robust than the code above.

console.log('left =', getStyleObject('.node-output02')['left']); // 5em

function getStyleText(className) {
  let classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules,
      styles = [];
  Array.from(classes).forEach(clazz => {
    if (clazz.selectorText == className) {
      let styleText = clazz.cssText || clazz.style.cssText,
          leftBraceIndex = styleText.indexOf('{'),
          rightBraceIndex = styleText.lastIndexOf('}'),
          selector = styleText.substring(0, leftBraceIndex).trim(),
          ruleText = styleText.substring(leftBraceIndex + 1, rightBraceIndex).trim();
      styles.push(ruleText);
    }
  });
  return styles;
}

function getStyleObject(className) {
  return cleanupValues(getStyleText(className).reduce((result, ruleText) => {
    let css = parseRuleText(ruleText);
    for (let [prop, value] of Object.entries(css)) {
      if (result.hasOwnProperty(prop) &&
          result[prop].includes('!important') &&
          !value.includes('!important')) {
        continue; // ignore...
      }
      result[prop] = value;
    }
    return result;
  }, {}));
}

function parseRuleText(ruleText) {
  return Object.fromEntries(ruleText.split(/\s*;\s*/g)
    .filter(v => v.length > 0)
    .map(v => v.split(/\s*:\s*/g)));
}

function cleanupValues(css) {
  for (let [prop, value] of Object.entries(css)) {
    if (value.includes('!important')) {
      css[prop] = value.replace(/\s*!important/, '');
    }
  }
  return css;
}

.node-output02 {
  bottom: 360px;
  left: 420px;
}

.node-output02 {
  left: 5em !important; /* This will be the returned value. */
}

.node-output02 {
  left: 100%; /* Not as important as the preceeding rule. */
}


问:
Error while building angular 8 ssr application
I am working on an angular 8 project and trying to build it for production but every time I run the build command, it shows

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

I am unable to figure out the error as the application is working fine on development mode.

npm log file:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node',
1 verbose cli   '/usr/bin/npm',
1 verbose cli   'run',
1 verbose cli   'build:client-and-server-bundles' ]
2 info using npm@6.13.4
3 info using node@v10.19.0
4 verbose run-script [ 'prebuild:client-and-server-bundles',
4 verbose run-script   'build:client-and-server-bundles',
4 verbose run-script   'postbuild:client-and-server-bundles' ]
5 info lifecycle angularproject@1.0.0~prebuild:client-and-server-bundles: angularproject@1.0.0
6 info lifecycle angularproject@1.0.0~build:client-and-server-bundles: angularproject@1.0.0
7 verbose lifecycle angularproject@1.0.0~build:client-and-server-bundles: unsafe-perm in lifecycle true
8 verbose lifecycle angularproject@1.0.0~build:client-and-server-bundles: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/ekodev/angular_b2b/node_modules/.bin:/usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/ekodev/angular_b2b/node_modules/.bin:/home/ekodev/bin:/home/ekodev/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle angularproject@1.0.0~build:client-and-server-bundles: CWD: /home/ekodev/angular_b2b
10 silly lifecycle angularproject@1.0.0~build:client-and-server-bundles: Args: [ '-c',
10 silly lifecycle   'node --max_old_space_size=32276 node_modules/@angular/cli/bin/ng build --prod --aot --output-hashing=all && ng run angularproject:server:production' ]
11 silly lifecycle angularproject@1.0.0~build:client-and-server-bundles: Returned: code: 134  signal: null
12 info lifecycle angularproject@1.0.0~build:client-and-server-bundles: Failed to exec build:client-and-server-bundles script
13 verbose stack Error: angularproject@1.0.0 build:client-and-server-bundles: `node --max_old_space_size=32276 node_modules/@angular/cli/bin/ng build --prod --aot --output-hashing=all && ng run angularproject:server:production`
13 verbose stack Exit status 134
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:198:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:198:13)
13 verbose stack     at maybeClose (internal/child_process.js:982:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid angularproject@1.0.0
15 verbose cwd /home/ekodev/angular_b2b
16 verbose Linux 4.4.0-169-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "build:client-and-server-bundles"
18 verbose node v10.19.0
19 verbose npm  v6.13.4
20 error code ELIFECYCLE
21 error errno 134
22 error angularproject@1.0.0 build:client-and-server-bundles: `node --max_old_space_size=32276 node_modules/@angular/cli/bin/ng build --prod --aot --output-hashing=all && ng run angularproject:server:production`
22 error Exit status 134
23 error Failed at the angularproject@1.0.0 build:client-and-server-bundles script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 134, true ]
</code>```

I tried searching for the issue but unable to find anything.

答: Fixed the issue by updating the node version to v12.16.1. Not sure if this is the right way but at least it fixed my issue for now. </p>

Body:
I am working on an angular 8 project and trying to build it for production but every time I run the build command, it shows

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

I am unable to figure out the error as the application is working fine on development mode.

npm log file:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node',
1 verbose cli   '/usr/bin/npm',
1 verbose cli   'run',
1 verbose cli   'build:client-and-server-bundles' ]
2 info using npm@6.13.4
3 info using node@v10.19.0
4 verbose run-script [ 'prebuild:client-and-server-bundles',
4 verbose run-script   'build:client-and-server-bundles',
4 verbose run-script   'postbuild:client-and-server-bundles' ]
5 info lifecycle angularproject@1.0.0~prebuild:client-and-server-bundles: angularproject@1.0.0
6 info lifecycle angularproject@1.0.0~build:client-and-server-bundles: angularproject@1.0.0
7 verbose lifecycle angularproject@1.0.0~build:client-and-server-bundles: unsafe-perm in lifecycle true
8 verbose lifecycle angularproject@1.0.0~build:client-and-server-bundles: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/ekodev/angular_b2b/node_modules/.bin:/usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/ekodev/angular_b2b/node_modules/.bin:/home/ekodev/bin:/home/ekodev/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle angularproject@1.0.0~build:client-and-server-bundles: CWD: /home/ekodev/angular_b2b
10 silly lifecycle angularproject@1.0.0~build:client-and-server-bundles: Args: [ '-c',
10 silly lifecycle   'node --max_old_space_size=32276 node_modules/@angular/cli/bin/ng build --prod --aot --output-hashing=all && ng run angularproject:server:production' ]
11 silly lifecycle angularproject@1.0.0~build:client-and-server-bundles: Returned: code: 134  signal: null
12 info lifecycle angularproject@1.0.0~build:client-and-server-bundles: Failed to exec build:client-and-server-bundles script
13 verbose stack Error: angularproject@1.0.0 build:client-and-server-bundles: `node --max_old_space_size=32276 node_modules/@angular/cli/bin/ng build --prod --aot --output-hashing=all && ng run angularproject:server:production`
13 verbose stack Exit status 134
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:198:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:198:13)
13 verbose stack     at maybeClose (internal/child_process.js:982:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid angularproject@1.0.0
15 verbose cwd /home/ekodev/angular_b2b
16 verbose Linux 4.4.0-169-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "build:client-and-server-bundles"
18 verbose node v10.19.0
19 verbose npm  v6.13.4
20 error code ELIFECYCLE
21 error errno 134
22 error angularproject@1.0.0 build:client-and-server-bundles: `node --max_old_space_size=32276 node_modules/@angular/cli/bin/ng build --prod --aot --output-hashing=all && ng run angularproject:server:production`
22 error Exit status 134
23 error Failed at the angularproject@1.0.0 build:client-and-server-bundles script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 134, true ]

I tried searching for the issue but unable to find anything.


问:
Can't get textarea value
I'm trying to get the textarea value from a HTML form with Go, but it always returns as  blank/null.

HTML form:

```<code><form method="POST" action="/tickets/" name="ticketForm">
 <textarea rows="3" cols="50" class="form-control" name="ticketDescription" id="ticketDescription" form="ticketForm" required> </textarea>
   </form>
</code>```

Golang method to capture form data:

```<code>inputDescription := r.PostFormValue("ticketDescription")
</code>```

If I choose ' input="text" ', for example, it gives me the value. It's just from textarea that goes with blank/null. I've used "fmt.Println(inputDescription)" just to see if Go is retrieving the value, and it goes as a blank value too.

答:
The form attribute of <textarea> must be the id attribute of a <form>, not name. Also, form is not necessary if the <textarea> is inside the <form>.

Since in your example your <form> has no id attribute and you provided form for your <textarea>, its value will not be sent when the form is submitted.

So do it like this:

```<code><form method="POST" action="/tickets/" name="ticketForm">
  <textarea name="ticketDescription" id="ticketDescription" required> </textarea>
</form>
</code>```

Or:

```<code><form method="POST" action="/tickets/" id="ticketForm">
</form>

<textarea name="ticketDescription" id="ticketDescription"
    form="ticketForm" required> </textarea>
</code>```

Also don't forget that in your handler you must call Request.ParseForm() before you can access form values (Request.Form), or use Request.FormValue() or Request.PostFormValue() (which call Request.Parseform() if necessary).

Title: Can't get textarea value

Body:
I'm trying to get the textarea value from a HTML form with Go, but it always returns as  blank/null.

HTML form:

<form method="POST" action="/tickets/" name="ticketForm">
 <textarea rows="3" cols="50" class="form-control" name="ticketDescription" id="ticketDescription" form="ticketForm" required> </textarea>
   </form>

Golang method to capture form data:

inputDescription := r.PostFormValue("ticketDescription")

If I choose ' input="text" ', for example, it gives me the value. It's just from textarea that goes with blank/null. I've used "fmt.Println(inputDescription)" just to see if Go is retrieving the value, and it goes as a blank value too.

Body:
The form attribute of <textarea> must be the id attribute of a <form>, not name. Also, form is not necessary if the <textarea> is inside the <form>.

Since in your example your <form> has no id attribute and you provided form for your <textarea>, its value will not be sent when the form is submitted.

So do it like this:

<form method="POST" action="/tickets/" name="ticketForm">
  <textarea name="ticketDescription" id="ticketDescription" required> </textarea>
</form>

Or:

<form method="POST" action="/tickets/" id="ticketForm">
</form>

<textarea name="ticketDescription" id="ticketDescription"
    form="ticketForm" required> </textarea>

Also don't forget that in your handler you must call Request.ParseForm() before you can access form values (Request.Form), or use Request.FormValue() or Request.PostFormValue() (which call Request.Parseform() if necessary).


问:
Using QSlider in window to change background volume
I have a MainWindow and then a SecondWindow class that opens when a button is clicked in MainWindow. There is a slider in this SecondWindow class I want to control the music in both the MainWindow and SecondWindow classes.

my main function:

```<code>int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;
    w.show();

    SecondWindow s;

    //this connects MainWindow to SecondWindow to open
    QObject::connect(...);

    //plays background music
    Music m;
    QObject::connect(&s, SIGNAL(Volume(int)), &m, SLOT(setVol(int)));

    return a.exec();
}
</code>```

I have a music object that plays a function defined as such:

```<code>class Music
{
public:
    Music();

public slots:
    void setVol(int value);
private:
    QMediaPlayer* music;
};
</code>```

my SecondWindow is defined as such:

```<code>class SecondWindow: public QMainWindow
{
    Q_OBJECT
public:
    explicit SecondWindo(QWidget *parent = nullptr);
    ~SecondWindow();
signals:
    void VolumeChange(int value);
    void Volume(int value);

public slots:
    void ShowSettingsWindow();
    void changeVolume(int value);

private:
    void Connections();

    int volume; //holds the volume value based on the music_slider
    QSlider* music_slider;

};
</code>```

At the bottom of my SecondWindow's default constructor I have the following connect statement, with the SLOT definition:

```<code>QObject::connect(music_slider, SIGNAL(valueChanged(int)), this, SLOT(VolumeChange(int)));

void SecondWindow::VolumeChange(int value){
    emit Volume(value);
}
</code>```

then music has the SLOT defined as such:

```<code>void Music::setVol(int value){
    music->setVolume(value);
}
</code>```

I am currently trying to make it so that everytime the slider changes value, VolumeChange is called for the value that the slider currently has. Then, the signal Volume is called causing music to call the function setVol and thus set the volume. But I recieve an error on the second connect statement in main saying it could not convert all argument types.
How an I fix these connect statements to work or is there a better way to do this?

答: According to your code, this connect QObject::connect(music_slider, SIGNAL(valueChanged(int)), this, SLOT(VolumeChange(int))); in the second window is invalid because it doesn't have a SLOT called VolumeChange. In fact, it's a SIGNAL. However, it has a SLOT called changeVolume, which I think you really mean.

Body:
I have a MainWindow and then a SecondWindow class that opens when a button is clicked in MainWindow. There is a slider in this SecondWindow class I want to control the music in both the MainWindow and SecondWindow classes.

my main function:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;
    w.show();

    SecondWindow s;

    //this connects MainWindow to SecondWindow to open
    QObject::connect(...);

    //plays background music
    Music m;
    QObject::connect(&s, SIGNAL(Volume(int)), &m, SLOT(setVol(int)));

    return a.exec();
}

I have a music object that plays a function defined as such:

class Music
{
public:
    Music();

public slots:
    void setVol(int value);
private:
    QMediaPlayer* music;
};

my SecondWindow is defined as such:

class SecondWindow: public QMainWindow
{
    Q_OBJECT
public:
    explicit SecondWindo(QWidget *parent = nullptr);
    ~SecondWindow();
signals:
    void VolumeChange(int value);
    void Volume(int value);

public slots:
    void ShowSettingsWindow();
    void changeVolume(int value);

private:
    void Connections();

    int volume; //holds the volume value based on the music_slider
    QSlider* music_slider;

};

At the bottom of my SecondWindow's default constructor I have the following connect statement, with the SLOT definition:

QObject::connect(music_slider, SIGNAL(valueChanged(int)), this, SLOT(VolumeChange(int)));

void SecondWindow::VolumeChange(int value){
    emit Volume(value);
}

then music has the SLOT defined as such:

void Music::setVol(int value){
    music->setVolume(value);
}

I am currently trying to make it so that everytime the slider changes value, VolumeChange is called for the value that the slider currently has. Then, the signal Volume is called causing music to call the function setVol and thus set the volume. But I recieve an error on the second connect statement in main saying it could not convert all argument types.
How an I fix these connect statements to work or is there a better way to do this?


问:
NaN is shown when a calculation has no value inside. How can "0" or "-" be displayed instead in SwiftUI?
If a calculation is performed in SwiftUI and no values are added to the TextField, it displays "-NaN" (Not a Number?) instead.

How can a value (for example "0", "-") be displayed until values are inserted?

I have tried adding @State private var display = 0 but it displayed both values...

Example code:

```<code> struct ContentView: View {
    @EnvironmentObject var userData: UserData

    var Brutto: Double {
        let price = Double(userData.BPrice) ?? 0
        let rent = Double(userData.Rent) ?? 0

        let Brutto = rent * 12 / price * 100

        return Brutto
    }

    var body: some View {
        VStack {
            Text ("\(Brutto, specifier: "%.1f")")
        }
</code>```

// The UserData File:

```<code>class UserData : ObservableObject {

  private static let userDefaultBPrice = "BPrice"
  private static let userDefaultRent = "Rent"

  @Published var BuyingPrice = UserDefaults.standard.string(forKey: UserData.userDefaultBPrice) ?? ""
  {
    didSet {
      UserDefaults.standard.set(self.BPrice, forKey: UserData.userDefaultBPrice)
    }
  }

  @Published var Rent = UserDefaults.standard.string(forKey: UserData.userDefaultRent) ?? "" {
    didSet {
      UserDefaults.standard.set(self.Rent, forKey: UserData.userDefaultRent)
    }
  }
  private var canc: AnyCancellable!

}
</code>```

Thanks

答:
Here is possible approach</p>

```<code>VStack {
    Text ("\(Brutto.isNaN ? 0 : Brutto, specifier: "%.1f")")
}
</code>```

Body:
If a calculation is performed in SwiftUI and no values are added to the TextField, it displays "-NaN" (Not a Number?) instead.

How can a value (for example "0", "-") be displayed until values are inserted?

I have tried adding @State private var display = 0 but it displayed both values...

Example code:

 struct ContentView: View {
    @EnvironmentObject var userData: UserData

    var Brutto: Double {
        let price = Double(userData.BPrice) ?? 0
        let rent = Double(userData.Rent) ?? 0

        let Brutto = rent * 12 / price * 100

        return Brutto
    }

    var body: some View {
        VStack {
            Text ("\(Brutto, specifier: "%.1f")")
        }

// The UserData File:

class UserData : ObservableObject {

  private static let userDefaultBPrice = "BPrice"
  private static let userDefaultRent = "Rent"

  @Published var BuyingPrice = UserDefaults.standard.string(forKey: UserData.userDefaultBPrice) ?? ""
  {
    didSet {
      UserDefaults.standard.set(self.BPrice, forKey: UserData.userDefaultBPrice)
    }
  }

  @Published var Rent = UserDefaults.standard.string(forKey: UserData.userDefaultRent) ?? "" {
    didSet {
      UserDefaults.standard.set(self.Rent, forKey: UserData.userDefaultRent)
    }
  }
  private var canc: AnyCancellable!

}

Thanks

Body:
Here is possible approach

VStack {
    Text ("\(Brutto.isNaN ? 0 : Brutto, specifier: "%.1f")")
}


问:
query returns nothing php
I attempt to get the result of a very simple query with the function query but nothing appears. If I execute the query in PHPMyAdmin, with the same data, I have a result.

There is my code :

```<code>$sql = "SELECT * FROM users WHERE email='$email'";

$response = $conn->query($conn, $sql);
</code>```

The $conn variable is correct, I did an Insert with that.

$response is null. I can do an echo and there is nothing.

What can I do to solve this problem ? What can I check ?

Thank you very much.

答:
You don't need to pass connection in query.

Solution:

```<code>$sql = "SELECT * FROM users WHERE email='$email'";
$response = $conn->query($sql);
while($res = $response->fetch_array()){
$name=$res['nameofuser']; //just an example
}
echo $name;
</code>```

Real solution (prepare stmt):

```<code>$sql = "SELECT * FROM users WHERE email=?";
$response = $conn->prepare($sql);
$response->bind_param('s',$email);
if(!$response->execute()){
echo "Error query: " . $response->error . ".";
}
$result=$response->get_result();
while($res = $result->fetch_array()){
$name=$res['nameofuser']; //just an example
}
echo $name;
</code>```

'Tips' add to real solution check if query is done.

Title: query returns nothing php

Body:
I attempt to get the result of a very simple query with the function query but nothing appears. If I execute the query in PHPMyAdmin, with the same data, I have a result.

There is my code :

$sql = "SELECT * FROM users WHERE email='$email'";

$response = $conn->query($conn, $sql);

The $conn variable is correct, I did an Insert with that.

$response is null. I can do an echo and there is nothing.

What can I do to solve this problem ? What can I check ?

Thank you very much.

Body:
You don't need to pass connection in query.

Solution:

$sql = "SELECT * FROM users WHERE email='$email'";
$response = $conn->query($sql);
while($res = $response->fetch_array()){
$name=$res['nameofuser']; //just an example
}
echo $name;

Real solution (prepare stmt):

$sql = "SELECT * FROM users WHERE email=?";
$response = $conn->prepare($sql);
$response->bind_param('s',$email);
if(!$response->execute()){
echo "Error query: " . $response->error . ".";
}
$result=$response->get_result();
while($res = $result->fetch_array()){
$name=$res['nameofuser']; //just an example
}
echo $name;

'Tips' add to real solution check if query is done.


问:
Javascript Accordian
I have a simple accordion working, except for one thing. I would like to be able to re-click the same accordion item again, and be able to set height to '0'.

Currently, the open accordion item closes when I click a different accordion item, which is exactly what I want to do — but I also want the ability to re-click the open accordion item and have that one close, when clicked. See working example below:

https://codepen.io/celli/pen/BaNLJWb

```<code>// set heights to 0
gsap.set('.content', {
  height: 0
});

// click function
$('.accordianItem').click(function() {

  if ($('.accordianItem').hasClass('on')) {
    gsap.to($('.content'), {
      duration: .25,
      height: 0
    });
    $('.accordianItem').removeClass('on');
  }

  gsap.to($(this).children('.content'), {
    duration: .25,
    height: "auto"
  });
  $(this).addClass('on');
});
</code>```

What code can I add to add this extra functionality?

答:
I have modified your code by adding another if that checks if the element clicked has 'on' class already. It should now work as you intended it to (hide when the user clicks on the already opened header).</p>

```<code>// set heights to 0
gsap.set('.content', {height:0});

// click function
$('.accordianItem').click(function() {
    if($(this).hasClass("on")){
       gsap.to($('.content'), {duration:.25, height:0});
       $('.accordianItem').removeClass('on');
    }
    else{
      if ($('.accordianItem').hasClass('on')) {
         gsap.to($('.content'), {duration:.25, height:0});
         $('.accordianItem').removeClass('on');
      }
      gsap.to($(this).children('.content'), {duration:.25, height:"auto"});
      $(this).addClass('on');
    }

});
</code>```

Title: Javascript Accordian

Body:
I have a simple accordion working, except for one thing. I would like to be able to re-click the same accordion item again, and be able to set height to '0'.

Currently, the open accordion item closes when I click a different accordion item, which is exactly what I want to do — but I also want the ability to re-click the open accordion item and have that one close, when clicked. See working example below:

https://codepen.io/celli/pen/BaNLJWb

// set heights to 0
gsap.set('.content', {
  height: 0
});

// click function
$('.accordianItem').click(function() {

  if ($('.accordianItem').hasClass('on')) {
    gsap.to($('.content'), {
      duration: .25,
      height: 0
    });
    $('.accordianItem').removeClass('on');
  }

  gsap.to($(this).children('.content'), {
    duration: .25,
    height: "auto"
  });
  $(this).addClass('on');
});

What code can I add to add this extra functionality?

Body:
I have modified your code by adding another if that checks if the element clicked has 'on' class already. It should now work as you intended it to (hide when the user clicks on the already opened header).

// set heights to 0
gsap.set('.content', {height:0});

// click function
$('.accordianItem').click(function() {
    if($(this).hasClass("on")){
       gsap.to($('.content'), {duration:.25, height:0});
       $('.accordianItem').removeClass('on');
    }
    else{
      if ($('.accordianItem').hasClass('on')) {
         gsap.to($('.content'), {duration:.25, height:0});
         $('.accordianItem').removeClass('on');
      }
      gsap.to($(this).children('.content'), {duration:.25, height:"auto"});
      $(this).addClass('on');
    }

});


问:
How to use Logical operator OR " || " in ASP .NET
I've followed this question How to use IF statement in asp.net using C#, but I really can make it out with my code.

```<code>if ((txtNome.Value == null) || (txtNome.Value == (""))
{

}
</code>```

Here is the error

The "||" operator cannot be applied a bool and string operands

I've tried all the possible solutions in the question above, but still not working. Some ideas?

Thank you

答:
Solution 1

```<code>if ((txtNome.Value == null) || (txtNome.Value == ""))
    {

    }
</code>```

Solution 2
The same as above but without the extra round brackets.
These are unnecessary for single logical statements.

```<code>if (txtNome.Value == null || txtNome.Value == "")
{

}
</code>```

Solution 3
Built in function for the above in C#

```<code>if (string.IsNullOrEmpty(txtNome.Value))
{

}
</code>```

Body:
I've followed this question How to use IF statement in asp.net using C#, but I really can make it out with my code.

if ((txtNome.Value == null) || (txtNome.Value == (""))
{

}

Here is the error

The "||" operator cannot be applied a bool and string operands

I've tried all the possible solutions in the question above, but still not working. Some ideas?

Thank you

Body:
Solution 1

if ((txtNome.Value == null) || (txtNome.Value == ""))
    {

    }

Solution 2
The same as above but without the extra round brackets.
These are unnecessary for single logical statements.

if (txtNome.Value == null || txtNome.Value == "")
{

}

Solution 3
Built in function for the above in C#

if (string.IsNullOrEmpty(txtNome.Value))
{

}


答:
After execute query . fetch the results</p>

```<code>   $stmt = $conn->prepare( "SELECT * FROM users WHERE email= ? ");

$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) exit('No rows');
while($row = $result->fetch_assoc()) {
// your code
}
</code>```

Title: query returns nothing php

Body:
After execute query . fetch the results

   $stmt = $conn->prepare( "SELECT * FROM users WHERE email= ? ");

$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) exit('No rows');
while($row = $result->fetch_assoc()) {
// your code
}


问:
Javascript regex to check if a value begins with a number followed by anything else
How would i go about doing a regex to see if it begins with a number and any character can follow after. My current expression is

```<code>var validaddress = /^[0-9][A-Za-z0-9]+$/;
</code>```

But this isn't the right way. Im new to this, help anyone?

答:
If you have a string of these values and you want to find each individually try this:

```<code>(^|(?<=\W))(\d\w*)
</code>```

You can then do a loop through each match.

Regexr example

Body:
How would i go about doing a regex to see if it begins with a number and any character can follow after. My current expression is

var validaddress = /^[0-9][A-Za-z0-9]+$/;

But this isn't the right way. Im new to this, help anyone?

Body:
If you have a string of these values and you want to find each individually try this:

(^|(?<=\W))(\d\w*)

You can then do a loop through each match.

Regexr example


问:
Can anyone suggest a faster method for creaing this array?
I am creating this array for my shader and this step is very slow as it constitutes a nested for loop. Currently this methos takes approx 1 sec to create this. Can anyone suggest any faster method for creating this array.</p>

```<code>import numpy as np

elems = []
b = 23503
a = 24

for i in range(0, a - 1):
    for j in range(0, b - 1):
        elems += [j + b * i, j + b * i + 1, j + b * (i + 1)]
        elems += [j + b * (i + 1), j + b * (i + 1) + 1, j + b * i + 1]

elems = np.array(elems, dtype=np.int32)
</code>```

答:
First I would recognise that there is a lot of repeated computation. The base term involving the iterator variables here is i*b+j, so let's have NumPy create an array that contains those values in the order they should appear:

ib_j = (np.arange(a-1)[:, None]*b + np.arange(b-1)).flatten()
```

<p>Next we compute the six different columns from this base, stack them horizontally, and flatten:</p>

<pre class="lang-py prettyprint-override"><code>def create_shader_array(a, b):
    ib_j = (np.arange(a-1)[:, None]*b + np.arange(b-1)).flatten()
    return np.column_stack((ib_j, ib_j+1, ib_j+b, ib_j+b, ib_j+b+1, ib_j+1)).flatten()
</code>```

Validation:

>>> all(create_shader_array(a, b) == AKS(a, b)) # AKS is your original implementation
True
```

<p>Timing:</p>

```>>> %timeit AKS(24, 23503)
1.02 s ± 8.25 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
>>> %timeit create_shader_array(24, 23503)
28.8 ms ± 364 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
```

Body:
I am creating this array for my shader and this step is very slow as it constitutes a nested for loop. Currently this methos takes approx 1 sec to create this. Can anyone suggest any faster method for creating this array.

import numpy as np

elems = []
b = 23503
a = 24

for i in range(0, a - 1):
    for j in range(0, b - 1):
        elems += [j + b * i, j + b * i + 1, j + b * (i + 1)]
        elems += [j + b * (i + 1), j + b * (i + 1) + 1, j + b * i + 1]

elems = np.array(elems, dtype=np.int32)

Body:
First I would recognise that there is a lot of repeated computation. The base term involving the iterator variables here is i*b+j, so let's have NumPy create an array that contains those values in the order they should appear:

ib_j = (np.arange(a-1)[:, None]*b + np.arange(b-1)).flatten()

Next we compute the six different columns from this base, stack them horizontally, and flatten:

def create_shader_array(a, b):
    ib_j = (np.arange(a-1)[:, None]*b + np.arange(b-1)).flatten()
    return np.column_stack((ib_j, ib_j+1, ib_j+b, ib_j+b, ib_j+b+1, ib_j+1)).flatten()

Validation:

>>> all(create_shader_array(a, b) == AKS(a, b)) # AKS is your original implementation
True

Timing:

>>> %timeit AKS(24, 23503)
1.02 s ± 8.25 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
>>> %timeit create_shader_array(24, 23503)
28.8 ms ± 364 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)


问:
ngClass directive to use with ngFor
I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding.

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

```<code><ul>
      <li *ngFor="let text of income; let i = index" [ngClass]="'strong'">{{text.text}}</li>
    </ul>
income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];
</code>```

答:
As other answers have identified, you need to split your text. My preference for this would be to create in interface that models the different parts of the income text.

```<code>export interface Income {
  amount: string;
  currencySymbol: string;
  text: string;
}
</code>```

In your component or service (wherever makes sense when it comes to reusing the interface), you would map the text to the interface. This is where the complexity lies. I will show a version of using it in the component for simplicity. In reality you would do this in your service for reusability.

```<code>incomes: Income[];

ngOnInit() {
  this.service.getIncomeTexts().subscribe((texts: string[]) => {
    this.incomes = texts.map(x => this.mapTextToIncome(x));
  });
}

private mapTextToIncome(text: string): Income {
  // this regex will match a string that ends with a dollar symbol
  // followed by numbers or commas
  // You could extend the possible currency symbols if required
  const parts: string[] = /^(.+)(\$)([\d+,]+)$/.exec(text);
  return {
    amount: parts[3],
    currencySymbol: parts[2],
    text: parts[1]
  };
}
</code>```

And then it becomes trivial to use in your HTML:

```<code><ul *ngIf="incomes">
  <li *ngFor="let income of incomes">
    <span>{{income.text}}</span>
    <span class="strong">{{income.currencySymbol}}</span>
    <span>{{income.amount}}</span>
  </li>
</ul>
</code>```

I have left amount as a string in my example, but you might want to parse it and treat it as a number so that you can apply your own formatting if you wish.

DEMO: https://stackblitz.com/edit/angular-do6joa

Regex demo: https://regex101.com/r/e4nLLO/2

Of course, the correct answer is that your API should return data in a better format :)

Title: ngClass directive to use with ngFor

Body:
I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding.

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

{{text.text}}

income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];

Body:
As other answers have identified, you need to split your text. My preference for this would be to create in interface that models the different parts of the income text.

export interface Income {
  amount: string;
  currencySymbol: string;
  text: string;
}

In your component or service (wherever makes sense when it comes to reusing the interface), you would map the text to the interface. This is where the complexity lies. I will show a version of using it in the component for simplicity. In reality you would do this in your service for reusability.

incomes: Income[];

ngOnInit() {
  this.service.getIncomeTexts().subscribe((texts: string[]) => {
    this.incomes = texts.map(x => this.mapTextToIncome(x));
  });
}

private mapTextToIncome(text: string): Income {
  // this regex will match a string that ends with a dollar symbol
  // followed by numbers or commas
  // You could extend the possible currency symbols if required
  const parts: string[] = /^(.+)(\$)([\d+,]+)$/.exec(text);
  return {
    amount: parts[3],
    currencySymbol: parts[2],
    text: parts[1]
  };
}

And then it becomes trivial to use in your HTML:

<ul *ngIf="incomes">
  <li *ngFor="let income of incomes">
    <span>{{income.text}}</span>
    <span class="strong">{{income.currencySymbol}}</span>
    <span>{{income.amount}}</span>
  </li>
</ul>

I have left amount as a string in my example, but you might want to parse it and treat it as a number so that you can apply your own formatting if you wish.

DEMO: https://stackblitz.com/edit/angular-do6joa

Regex demo: https://regex101.com/r/e4nLLO/2

Of course, the correct answer is that your API should return data in a better format :)


问:
Azure DevOps Server 2019 Retention Policy no longer working
Last week we have migrated from TFVC to Git on our ADS 2019.1 server.

On our validation pipeline we have an aggressive retention policy.
It is set to Keep for 2 days, 10 good builds with the branch filter * and all checkboxes cleared
ADS writes it as: +refs/heads/*

What we see is that since we migrated, none of the Git builds have been deleted. From the last 8 days we now have hundreds of builds with their multi-GB drop.

Is * the right branch filter to use ? This was the default setting entered by ADS, we do indeed want all builds for all branches to be deleted by this policy.

I also tried **, but that made no change, in the build results page i see all build are build off a temporary branch with a 4 digit number, which is probably the pull request number.

How can we ensure the builds are cleaned up as per the retention policies ?

The Build definition is not linked to a Release pipeline. The builds are triggered from the Pull Requests created by developers. The Pull requests are marked as Completed.

Another build definition, one with a CI trigger that runs after every commit, does still seem to delete builds based on the retention policy defined.

Picture of our TFS Retention policy settings. Master builds are cleaned up, pull request builds are not

List of the oldest builds in TFS after manual cleanup last week, these builds are now 4-5 days old, over the 2 day limit of the retention policy.
Also you can see there is no retain lock behind them.

Overview of the deleted builds. You can see 'master' builds in there that have been deleted by the retention policy.

Shows the master builds are deleted after the 2 day retention policy setting

答:
You may also try:

Tab "Retention"

Select a policy (in your case: "Keep for 2 days, […]")

Under "Branch filters", add another one

Type: "Include", Branch specification: "refs/pull/*"

Explaination:
If you open a terminal in the build agent's source folder (named s) and run git branch --all, you will see a lot of branches like refs/pull/1234 for each pull request (e.g. 1234) there. Also, if you compare your branch specification * to the path shown on the left (+refs/heads/*) you see that it does in fact not match all branches…


问:
How to render element in React.js from object map
I have a question about rendering components from object map. I have a structure like this:

```<code>const tabs = [
    'tab1': {
        name: 'Tab 1',
        renderComponent: () => <Tab1Component />
    },
    'tab2': {
        name: 'Tab 2',
        renderComponent: () => <Tab2Component />
    }
];
</code>```

I want to access the renderComponent property and render sub component.
Tried with function invocation, React.createElement(), doesn't work.

```<code>const MyComponent = ({tabs}) => {
    const activeTab = 'tab1';
    return (
        <>
        // How to render it?
        // function invocation?
        // createElement??
            tabs[activeTab].renderComponent();
        </>
    );
};
</code>```

答:
```<code>const MyComponent = () => {

const activeTab = 'tab2';

const tabs = [
{'tab1': {
    name: 'Tab 1',
    renderComponent: () => <Tab1Component />
}},
{'tab2':{
    name: 'Tab 2',
    renderComponent: () => <Tab2Component />
}}
</code>```

];

```<code>  return (
  <div>
    {tabs.map((el) => {
      if (el[activeTab]) {
        return el[activeTab].renderComponent()
      }
    })}
  </div>
</code>```

);
 }

Body:
I have a question about rendering components from object map. I have a structure like this:

const tabs = [
    'tab1': {
        name: 'Tab 1',
        renderComponent: () => <Tab1Component />
    },
    'tab2': {
        name: 'Tab 2',
        renderComponent: () => <Tab2Component />
    }
];

I want to access the renderComponent property and render sub component.
Tried with function invocation, React.createElement(), doesn't work.

const MyComponent = ({tabs}) => {
    const activeTab = 'tab1';
    return (
        <>
        // How to render it?
        // function invocation?
        // createElement??
            tabs[activeTab].renderComponent();
        </>
    );
};

Body:
const MyComponent = () => {

const activeTab = 'tab2';

const tabs = [
{'tab1': {
    name: 'Tab 1',
    renderComponent: () => <Tab1Component />
}},
{'tab2':{
    name: 'Tab 2',
    renderComponent: () => <Tab2Component />
}}

];

  return (
  <div>
    {tabs.map((el) => {
      if (el[activeTab]) {
        return el[activeTab].renderComponent()
      }
    })}
  </div>

);
 }


问:
setting color range in matplotlib patchcollection
I am plotting a PatchCollection in matplotlib with coords and patch color values read in from a file.

The problem is that matplotlib seems to automatically scale the color range to the min/max of the data values. How can I manually set the color range? E.g. if my data range is 10-30, but I want to scale this to a color range of 5-50 (e.g. to compare to another plot), how can I do this?

My plotting commands look much the same as in the api example code: patch_collection.py

```<code>colors = 100 * pylab.rand(len(patches))
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
p.set_array(pylab.array(colors))
ax.add_collection(p)
pylab.colorbar(p)

pylab.show()
</code>```

答:
Use p.set_clim([5, 50]) to set the color scaling minimums and maximums in the case of your example. Anything in matplotlib that has a colormap has the get_clim and set_clim methods.

As a full example:

```<code>import matplotlib
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Circle
import numpy as np

# (modified from one of the matplotlib gallery examples)
resolution = 50 # the number of vertices
N = 100
x       = np.random.random(N)
y       = np.random.random(N)
radii   = 0.1*np.random.random(N)
patches = []
for x1, y1, r in zip(x, y, radii):
    circle = Circle((x1, y1), r)
    patches.append(circle)

fig = plt.figure()
ax = fig.add_subplot(111)

colors = 100*np.random.random(N)
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
p.set_array(colors)
ax.add_collection(p)
fig.colorbar(p)

fig.show()
</code>```

Now, if we just add p.set_clim([5, 50]) (where p is the patch collection) somewhere before we call fig.show(...), we get this:

Body:
I am plotting a PatchCollection in matplotlib with coords and patch color values read in from a file.

The problem is that matplotlib seems to automatically scale the color range to the min/max of the data values. How can I manually set the color range? E.g. if my data range is 10-30, but I want to scale this to a color range of 5-50 (e.g. to compare to another plot), how can I do this?

My plotting commands look much the same as in the api example code: patch_collection.py

colors = 100 * pylab.rand(len(patches))
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
p.set_array(pylab.array(colors))
ax.add_collection(p)
pylab.colorbar(p)

pylab.show()

Body:
Use p.set_clim([5, 50]) to set the color scaling minimums and maximums in the case of your example. Anything in matplotlib that has a colormap has the get_clim and set_clim methods.

As a full example:

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Circle
import numpy as np

# (modified from one of the matplotlib gallery examples)
resolution = 50 # the number of vertices
N = 100
x       = np.random.random(N)
y       = np.random.random(N)
radii   = 0.1*np.random.random(N)
patches = []
for x1, y1, r in zip(x, y, radii):
    circle = Circle((x1, y1), r)
    patches.append(circle)

fig = plt.figure()
ax = fig.add_subplot(111)

colors = 100*np.random.random(N)
p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
p.set_array(colors)
ax.add_collection(p)
fig.colorbar(p)

fig.show()

Now, if we just add p.set_clim([5, 50]) (where p is the patch collection) somewhere before we call fig.show(...), we get this:


问:
Autoscroll highchart on new data only if user sees last data
I have highstock in react application. I've added historical data upload functionality. My problem is that I need to add both historical data and new data which could happen simultaneously. I need to understand where user on the chart currently. If chart was scrolled and user sees historical data I need to do nothing in case of new data was added. But if user sees latest data and chart got new data (not historical one) I need to autoscroll graph to show last data. Of course user can scroll graph back and forward.
I was trying to change extremes with next condition:

```<code>if ( extremes.userMax === oldMax && extremes.userMax < dataMax ) {
 e.target.xAxis[ 0 ].setExtremes(
    dataMax - ( userMax - userMin ),
    dataMax
 );
}
</code>```

but it doesn't work.

Is it possible to determine current user position on the chart?

Code above was added as event callback for redraw.

答:
Thank you for response.

Here is full code I use to automatically scroll chart:

if ( e.target.xAxis ) {
   const extremes = e.target.xAxis[ 0 ].getExtremes();
   const { userMax, userMin, oldMax, dataMax } = e.target.xAxis[ 0 ];
   if ( extremes.userMax === oldMax && extremes.userMax < dataMax ) {
   e.target.xAxis[ 0 ].setExtremes(
      dataMax - ( userMax - userMin ),
      dataMax
   );
}

```

<p>May be I need to clarify how I store and change data in redux. All chart data placed in array:</p>

<pre class="lang-js prettyprint-override"><code>[{
  open(pin):1
  high(pin):3
  low(pin):1
  close(pin):2
  volume(pin):10
  x(pin):1581850800000
}, ...
]
</code>```

So if I need to upload historical data from server I just add data to the beginning of array. In case I need to add new candle to chart I just push new element in the end of array. Chart component gets new series array through redux update.

UPD:

I finally solved my problem with next logic in redraw event:

```<code>            if ( dataMax - userMax < pointRange * 2 ) {
                e.target.xAxis[ 0 ].setExtremes(
                    dataMax - ( userMax - userMin ),
                    dataMax,
                    false
                );
            }
</code>```

The idea is to check how many candles out of user view and if there are more than 2 just do nothing otherwise move chart to show latest candles.
false in setExtremes needs to avoid endless redraw.

Body:
I have highstock in react application. I've added historical data upload functionality. My problem is that I need to add both historical data and new data which could happen simultaneously. I need to understand where user on the chart currently. If chart was scrolled and user sees historical data I need to do nothing in case of new data was added. But if user sees latest data and chart got new data (not historical one) I need to autoscroll graph to show last data. Of course user can scroll graph back and forward.
I was trying to change extremes with next condition:

if ( extremes.userMax === oldMax && extremes.userMax < dataMax ) {
 e.target.xAxis[ 0 ].setExtremes(
    dataMax - ( userMax - userMin ),
    dataMax
 );
}

but it doesn't work.

Is it possible to determine current user position on the chart?

Code above was added as event callback for redraw.

Body:
Thank you for response.

Here is full code I use to automatically scroll chart:

if ( e.target.xAxis ) {
   const extremes = e.target.xAxis[ 0 ].getExtremes();
   const { userMax, userMin, oldMax, dataMax } = e.target.xAxis[ 0 ];
   if ( extremes.userMax === oldMax && extremes.userMax < dataMax ) {
   e.target.xAxis[ 0 ].setExtremes(
      dataMax - ( userMax - userMin ),
      dataMax
   );
}

May be I need to clarify how I store and change data in redux. All chart data placed in array:

[{
  open(pin):1
  high(pin):3
  low(pin):1
  close(pin):2
  volume(pin):10
  x(pin):1581850800000
}, ...
]

So if I need to upload historical data from server I just add data to the beginning of array. In case I need to add new candle to chart I just push new element in the end of array. Chart component gets new series array through redux update.

UPD:

I finally solved my problem with next logic in redraw event:

            if ( dataMax - userMax < pointRange * 2 ) {
                e.target.xAxis[ 0 ].setExtremes(
                    dataMax - ( userMax - userMin ),
                    dataMax,
                    false
                );
            }

The idea is to check how many candles out of user view and if there are more than 2 just do nothing otherwise move chart to show latest candles.
false in setExtremes needs to avoid endless redraw.