问:
The ForeignKeyAttribute on property "[Model name]" on type "[Project name]" is not valid
So i tried to add a foreign key by following this tutorial. But now im getting an error i have looked for an anwser but couldn't find any. these are my model classes

Movie class

```<code>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    [Table("Movie")]
    public class Movie
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int MovieId { get; set; }
        public string Name { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? DateCreated { get; set; }

        public int? CustomerId { get; set; }
        [ForeignKey("Customer")]
        public Customer customer { get; set; }
    }
}
</code>```

Customer class

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    [Table("Customer")]
    public class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustomerId { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public bool IsCreated { get; set; }
        public int MaxMovies { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime Created { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? LastEdited { get; set; }

        public ICollection<Movie> BorrowingMovies { get; set; }
    }
}
</code>```

I hope someone can help me with my problem.

答:
You must have property's name with pascal-case :

```<code>public Customer Customer { get; set; }
</code>```

Also, there is no need to use data-annotation in this case.
Furthermore, the types of CustomerId are different in Movie and Customer. It could not be nullable in Movie. Your foreign key must be defined like this:

```<code>public int CustomerId { get; set; }
</code>```

Body:
So i tried to add a foreign key by following this tutorial. But now im getting an error i have looked for an anwser but couldn't find any. these are my model classes

Movie class

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    [Table("Movie")]
    public class Movie
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int MovieId { get; set; }
        public string Name { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? DateCreated { get; set; }

        public int? CustomerId { get; set; }
        [ForeignKey("Customer")]
        public Customer customer { get; set; }
    }
}

Customer class

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    [Table("Customer")]
    public class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustomerId { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public bool IsCreated { get; set; }
        public int MaxMovies { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime Created { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? LastEdited { get; set; }

        public ICollection<Movie> BorrowingMovies { get; set; }
    }
}

I hope someone can help me with my problem.

Body:
You must have property's name with pascal-case :

public Customer Customer { get; set; }

Also, there is no need to use data-annotation in this case.
Furthermore, the types of CustomerId are different in Movie and Customer. It could not be nullable in Movie. Your foreign key must be defined like this:

public int CustomerId { get; set; }


来源: stackexchange

问:
Regex / JavaScript: Split string to separate lines by max characters per line with looking n chars backwards for a possible whitespace?
This is similar question to How to split a string at every n characters or to nearest previous space, however, on the contrary to what I was expecting based on the title, that solution does not work if there is just one long word without any whitespace.

So I need a Regex which splits a string to separate lines (multiple times if needed) by max characters per line, and looking backwards n characters for a possible whitespace (break there if found, otherwise at max length)?

Edit 1: For example, with max line length 30 characters with 15 characters backwards whitespace lookup:

Loremipsumissimplydummytextofthe printing and typesetting industry.

That sentence's first word has a length of 32 characters. So the output should be:

```<code>Loremipsumissimplydummytextoft  # Line has length of 30 char
he printing and typesetting     # Cut before the word at otherwise 30 char
industry.
</code>```

So the first word should be force-cut after 30th character, as there was no whitespace.

The remaining string has a length of 28 (or 29 with the dash) before word 'industry', so at the place of 30th character there's a word, so the solution looks up for the previous whitespace within 15 characters range. That line is broken before 'industry' word.

Edit 2: Second example of text:

Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry. Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry.

Should output:

Loremipsumissimplydummytextoft
he printing and typesetting
industry. Loremipsumis simply
dummytext ofthe printing and
typesetting industry.
Loremipsumissimplydummytextoft
he printing and typesetting
industry. Loremipsumis simply
dummytext ofthe printing and
typesetting industry.
```

<p><strong>Use case for this regex is to format a long string into readable text with max line length enforced and lines starting with a character and not a whitespace.</strong></p>

<p><strong>Optional requirement:</strong> When after initial posting I added that example in Edit 1, I also added an optional requirement for adding a dash '-' character at start of the next line, if a word was cut at max line length. I'm removing that from the example now and adding it as a separate optional requirement here.</p>

<p>So an optional requirement: If a line is broken mid-word at max-length and not at a whitespace, then a dash should be appended at the end of that line (and not at start of the next line, as I had originally described).</p>

```Loremipsumissimplydummytextoft-  # Line length 30+1 char with an appended a dash
he printing and typesetting     # Cut before the word at otherwise 30 char
industry.
```

答:
Final answer:

(\S[\s\S]{1,30}$|\S[\s\S]{1,29}(?:\s+)|\S{30})

evolution:

([\s\S]{1,15}(?!\S)|\S{15,})

you just have to modify the answer in the link by an 'or' statement that adds your additional requirement: |\S{15,}

responding to your edits, here is my modified regex:
([\s\S]{1,15}(?!\S)|\S{15})

you can replace the 15s with 30 or the character cutoff of your choice

adjusting for your further clarifications:
(\S[\s\S]{1,14}(?:\s*)|\S{15})

Now the string has to start with a none-whitespace and it matches but does not capture additional white space after the first 15 characters. Again you need to change the 15 and the 14 to the lengths you want.

(\S[\s\S]{1,30}$|\S[\s\S]{1,29}(?:\s+)|\S{30})
Adding another condition in the multiple 'or' statement at the beginning which captures the end of the string if it ends in a none-whitespace character. If it ended in a whitespace character, the second part of the 'or' statement captures it.

ContentLicense: CC BY-SA 4.0

Body:
This is similar question to How to split a string at every n characters or to nearest previous space, however, on the contrary to what I was expecting based on the title, that solution does not work if there is just one long word without any whitespace.

So I need a Regex which splits a string to separate lines (multiple times if needed) by max characters per line, and looking backwards n characters for a possible whitespace (break there if found, otherwise at max length)?

Edit 1: For example, with max line length 30 characters with 15 characters backwards whitespace lookup:

Loremipsumissimplydummytextofthe printing and typesetting industry.

That sentence's first word has a length of 32 characters. So the output should be:

Loremipsumissimplydummytextoft  # Line has length of 30 char
he printing and typesetting     # Cut before the word at otherwise 30 char
industry.

So the first word should be force-cut after 30th character, as there was no whitespace.

The remaining string has a length of 28 (or 29 with the dash) before word 'industry', so at the place of 30th character there's a word, so the solution looks up for the previous whitespace within 15 characters range. That line is broken before 'industry' word.

Edit 2: Second example of text:

Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry. Loremipsumissimplydummytextofthe printing and typesetting industry. Loremipsumis simply dummytext ofthe printing and typesetting industry.

Should output:

Loremipsumissimplydummytextoft
he printing and typesetting
industry. Loremipsumis simply
dummytext ofthe printing and
typesetting industry.
Loremipsumissimplydummytextoft
he printing and typesetting
industry. Loremipsumis simply
dummytext ofthe printing and
typesetting industry.

Use case for this regex is to format a long string into readable text with max line length enforced and lines starting with a character and not a whitespace.

Optional requirement: When after initial posting I added that example in Edit 1, I also added an optional requirement for adding a dash '-' character at start of the next line, if a word was cut at max line length. I'm removing that from the example now and adding it as a separate optional requirement here.

So an optional requirement: If a line is broken mid-word at max-length and not at a whitespace, then a dash should be appended at the end of that line (and not at start of the next line, as I had originally described).

Loremipsumissimplydummytextoft-  # Line length 30+1 char with an appended a dash
he printing and typesetting     # Cut before the word at otherwise 30 char
industry.


问:
NSHTTPURLResponse Status Code 200 in Airplane Mode
I have an interesting problem: when my device is in Airplane Mode, the HTTP Status Code that the NSHHTPURLResponse provides is 200 "OK".

Shouldn't it fail with an error, or at least not respond that it has a valid connection with code 200?

Here is a snipit of my code:

```<code>let url = NSURL(string: "http://apple.com");

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    if(error == nil){
        let statusCode = (response as! NSHTTPURLResponse).statusCode;
        if(statusCode == 200){
            println("All Good");
        }
    }
}
task.resume();
</code>```

In Airplane Mode, "All Good" is printed

答:
Seems you may be getting an cached response. Check this article out.

```<code>.reloadIgnoringLocalCacheData
</code>```

should solve your issue if this is the cause.

cachepolicy

ContentLicense: CC BY-SA 3.0

Body:
I have an interesting problem: when my device is in Airplane Mode, the HTTP Status Code that the NSHHTPURLResponse provides is 200 "OK".

Shouldn't it fail with an error, or at least not respond that it has a valid connection with code 200?

Here is a snipit of my code:

let url = NSURL(string: "http://apple.com");

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    if(error == nil){
        let statusCode = (response as! NSHTTPURLResponse).statusCode;
        if(statusCode == 200){
            println("All Good");
        }
    }
}
task.resume();

In Airplane Mode, "All Good" is printed

Body:
Seems you may be getting an cached response. Check this article out.

.reloadIgnoringLocalCacheData

should solve your issue if this is the cause.

cachepolicy


问:
To get the xy coordinates of dropped element on svg:image in d3
Here I'm working with an example where I need to get X and Y value of the dropped element (using Jquery drag & drop) from the svg:image element. Please check out my codepen. In the codepen, you can see an rss icon, which is the draggable element and the main big image is used as the droppable element. The main big image is added using d3 svg:image. While dropping the rss icon to the main big image, on the dropped point an rss icon should be appended. So in the drop function (JQuery), I added the d3 code to append the rss icon to main big image.

I have used 4 methods to retrieve the X & Y value of the point which the rss icon is dropped. In the code pen you can see that:

First method to extract xy positon:

```<code> var currentPos = ui.helper.position();
 var parentOffset = $(this).parent().offset();
 var x1 = event.pageX - parentOffset.left;
 var y1 = event.pageY - parentOffset.top;
</code>```

Second method to extract xy positon:

```<code>var dropPositionX = event.pageX - $(this).offset().left;
var dropPositionY = event.pageY - $(this).offset().top;
// Get mouse offset relative to dragged item:
var dragItemOffsetX = event.offsetX;
var dragItemOffsetY = event.offsetY;
// Get position of dragged item relative to drop target:
var x2 = dropPositionX-dragItemOffsetX;
var y2 = dropPositionY-dragItemOffsetY;
</code>```

Third method to extract xy positon:

```<code> var x3 = ui.offset.left - $(this).offset().left;
 var y3 = ui.offset.top - $(this).offset().top;
</code>```

Fourth method to extract xy positon:

```<code>    var elem = document.getElementById("floor")
    var rect = elem.getBoundingClientRect();
            var scrollTop = document.documentElement.scrollTop?
                            document.documentElement.scrollTop:document.body.scrollTop;
            var scrollLeft = document.documentElement.scrollLeft?
                            document.documentElement.scrollLeft:document.body.scrollLeft;
            var elementLeft = rect.left+scrollLeft;
            var elementTop = rect.top+scrollTop;

            var x4 = event.pageX-elementLeft;
            var y4 = event.pageY-elementTop;
</code>```

Appending dropped icon to the main big image:

```<code>svg.append("svg:image")
      .attr('xlink:href', 'http://icons.webpatashala.com/icons/Blueberry-Basic-Icons/Png/rss-icon.PNG')
      .attr('x', x1)  //x2, x3, x4, x5
      .attr('y', y1);  //x2, x3, x4, x5
</code>```

But using all the methods, rss icon is not append on the exact point in which it is dropped. How to retrieve the exact X & Y value?

答:
I think I figured out what you're looking for. There are some things to consider with this problem:

ViewBox Scaling

This is the main item to consider. Since you are using the viewBox property on your svg element and you are not using width / height, then whatever the browser window size is will change the scale of the svg's viewable canvas. This is important to consider when dropping the cloned image because you cannot use absolute top / left coordinates. It might look OK at 0, 0, but when you start moving away from it you'll notice that the image is not dropped where you think it should be.

The way around this is to use d3.scaleLinear() (docs here). This will help translate the droppable coordinates to the coordinates of your svg. The way I put it together is that for the X scale, the domain is from the SVG's left property to the left + width properties and the range is set to your SVG's viewbox x-min and width values. A similar approach is used for the Y scale (see code).

Where the SVG is on your page

This is the next thing to consider. It goes along with the previous item about the viewbox. If the SVG has some margins, for example, then you'll need to consider this when setting up the d3.scaleLinear() scale. The way to do is to use getBoundingClientRectangle() like this:

const clientRect = document.getElementById('floor').getBoundingClientRect();
```

<p><strong>If the window is resized</strong></p>

<p>If the window is resized, you will need to reset the scales.</p>

<p><strong>Where you grab the image from the draggable element</strong></p>

<p>This can add some work if you want to figure out how to get the x,y offset of where you grabbed the image from when you first grab it with the mouse. Instead, I use the <code>cursorAt</code> property on the <code>draggable()</code> method's configuration and set it to <code>{ left: 0, top: 0 }</code> so when you drag the image, the user will see the cursor at the top left of the image. This saves you from doing the work of figuring out the offset of where they grabbed the image.</p>

<p>Here is the code I used in the end (pen here) (also, I had to use a different icon because the one you were using wasn't loading for me).</p>

<pre class="lang-js prettyprint-override"><code>let scaleX = getScaleX();
let scaleY = getScaleY();

function getScaleX() {
  const clientRect = document.getElementById('floor').getBoundingClientRect();
  return d3.scaleLinear()
    .domain([clientRect.left, clientRect.left + clientRect.width])
    .range([0, 1500])
}

function getScaleY() {
  const clientRect = document.getElementById('floor').getBoundingClientRect();
  return d3.scaleLinear()
    .domain([clientRect.top, clientRect.top + clientRect.height])
    .range([0, 800])
}

window.onresize = function() {
  scaleX = getScaleX();
  scaleY = getScaleY();
};

var svg = d3.select('#floor');

svg.append("svg:image")
  .attr('xlink:href', 'https://wallpapershome.com/images/pages/pic_h/241.jpg')
  .style('width', "100%");

$(function() {
  $("#draggable" ).draggable({
      helper: "clone",
    cursor: 'move',
    containment: "document",
    cursorAt: { top: 0, left: 0 }
  });

  $( "#droppable" ).droppable({
    drop: function( event, ui ) {
      $( this ).addClass( "ui-state-highlight" );

      svg.append("svg:image")
        .attr('xlink:href', 'https://i2.wp.com/icons.iconarchive.com/icons/cornmanthe3rd/plex/512/Communication-RSS-icon.png')
        .attr('x', scaleX(event.pageX))
        .attr('y', scaleY(event.pageY))
        .attr('width', '50px');
    }
  });
});
</code>```

Body:
Here I'm working with an example where I need to get X and Y value of the dropped element (using Jquery drag & drop) from the svg:image element. Please check out my codepen. In the codepen, you can see an rss icon, which is the draggable element and the main big image is used as the droppable element. The main big image is added using d3 svg:image. While dropping the rss icon to the main big image, on the dropped point an rss icon should be appended. So in the drop function (JQuery), I added the d3 code to append the rss icon to main big image.

I have used 4 methods to retrieve the X & Y value of the point which the rss icon is dropped. In the code pen you can see that:

First method to extract xy positon:

 var currentPos = ui.helper.position();
 var parentOffset = $(this).parent().offset();
 var x1 = event.pageX - parentOffset.left;
 var y1 = event.pageY - parentOffset.top;

Second method to extract xy positon:

var dropPositionX = event.pageX - $(this).offset().left;
var dropPositionY = event.pageY - $(this).offset().top;
// Get mouse offset relative to dragged item:
var dragItemOffsetX = event.offsetX;
var dragItemOffsetY = event.offsetY;
// Get position of dragged item relative to drop target:
var x2 = dropPositionX-dragItemOffsetX;
var y2 = dropPositionY-dragItemOffsetY;

Third method to extract xy positon:

 var x3 = ui.offset.left - $(this).offset().left;
 var y3 = ui.offset.top - $(this).offset().top;

Fourth method to extract xy positon:

    var elem = document.getElementById("floor")
    var rect = elem.getBoundingClientRect();
            var scrollTop = document.documentElement.scrollTop?
                            document.documentElement.scrollTop:document.body.scrollTop;
            var scrollLeft = document.documentElement.scrollLeft?
                            document.documentElement.scrollLeft:document.body.scrollLeft;
            var elementLeft = rect.left+scrollLeft;
            var elementTop = rect.top+scrollTop;

            var x4 = event.pageX-elementLeft;
            var y4 = event.pageY-elementTop;

Appending dropped icon to the main big image:

svg.append("svg:image")
      .attr('xlink:href', 'http://icons.webpatashala.com/icons/Blueberry-Basic-Icons/Png/rss-icon.PNG')
      .attr('x', x1)  //x2, x3, x4, x5
      .attr('y', y1);  //x2, x3, x4, x5

But using all the methods, rss icon is not append on the exact point in which it is dropped. How to retrieve the exact X & Y value?

Body:
I think I figured out what you're looking for. There are some things to consider with this problem:

ViewBox Scaling

This is the main item to consider. Since you are using the viewBox property on your svg element and you are not using width / height, then whatever the browser window size is will change the scale of the svg's viewable canvas. This is important to consider when dropping the cloned image because you cannot use absolute top / left coordinates. It might look OK at 0, 0, but when you start moving away from it you'll notice that the image is not dropped where you think it should be.

The way around this is to use d3.scaleLinear() (docs here). This will help translate the droppable coordinates to the coordinates of your svg. The way I put it together is that for the X scale, the domain is from the SVG's left property to the left + width properties and the range is set to your SVG's viewbox x-min and width values. A similar approach is used for the Y scale (see code).

Where the SVG is on your page

This is the next thing to consider. It goes along with the previous item about the viewbox. If the SVG has some margins, for example, then you'll need to consider this when setting up the d3.scaleLinear() scale. The way to do is to use getBoundingClientRectangle() like this:

const clientRect = document.getElementById('floor').getBoundingClientRect();

If the window is resized

If the window is resized, you will need to reset the scales.

Where you grab the image from the draggable element

This can add some work if you want to figure out how to get the x,y offset of where you grabbed the image from when you first grab it with the mouse. Instead, I use the cursorAt property on the draggable() method's configuration and set it to { left: 0, top: 0 } so when you drag the image, the user will see the cursor at the top left of the image. This saves you from doing the work of figuring out the offset of where they grabbed the image.

Here is the code I used in the end (pen here) (also, I had to use a different icon because the one you were using wasn't loading for me).

let scaleX = getScaleX();
let scaleY = getScaleY();

function getScaleX() {
  const clientRect = document.getElementById('floor').getBoundingClientRect();
  return d3.scaleLinear()
    .domain([clientRect.left, clientRect.left + clientRect.width])
    .range([0, 1500])
}

function getScaleY() {
  const clientRect = document.getElementById('floor').getBoundingClientRect();
  return d3.scaleLinear()
    .domain([clientRect.top, clientRect.top + clientRect.height])
    .range([0, 800])
}

window.onresize = function() {
  scaleX = getScaleX();
  scaleY = getScaleY();
};

var svg = d3.select('#floor');

svg.append("svg:image")
  .attr('xlink:href', 'https://wallpapershome.com/images/pages/pic_h/241.jpg')
  .style('width', "100%");

$(function() {
  $("#draggable" ).draggable({
      helper: "clone",
    cursor: 'move',
    containment: "document",
    cursorAt: { top: 0, left: 0 }
  });

  $( "#droppable" ).droppable({
    drop: function( event, ui ) {
      $( this ).addClass( "ui-state-highlight" );

      svg.append("svg:image")
        .attr('xlink:href', 'https://i2.wp.com/icons.iconarchive.com/icons/cornmanthe3rd/plex/512/Communication-RSS-icon.png')
        .attr('x', scaleX(event.pageX))
        .attr('y', scaleY(event.pageY))
        .attr('width', '50px');
    }
  });
});


问:
How to properly type a Redux connect call?
I am trying to use a Redux state store in combination with TypeScript. I am trying to use the official Typings of Redux and want to make the entire call on the connect method (which connects the mapStatetoProps and mapDispatchToProps with a component) type safe.

I usually see approaches where the methods mapStatetoProps and mapDispatchToProps are just custom typed and return a partial of the component props, such as the following:

```<code>function mapStateToProps(state: IStateStore, ownProps: Partial<IComponentProps>)
  : Partial<IProjectEditorProps> {}
function mapDispatchToProps (dispatch: Dispatch, ownProps: Partial<IComponentProps>)
  : Partial<IProjectEditorProps> {}
</code>```

This is typed and works, but not really safe because it is possible to instantiate a component which misses props, as the usage of the Partial interface allows incomplete definitions. However, the Partial interface is required here because you may want to define some props in mapStateToProps and some in mapDispatchToProps, and not all in one function. So this is why I want to avoid this style.

What I am currently trying to use is directly embedding the functions in the connect call and typing the connect call with the generic typing supplied by redux:

```<code>connect<IComponentProps, any, any, IStateStore>(
  (state, ownProps) => ({
    /* some props supplied by redux state */
  }),
  dispatch => ({
    /* some more props supplied by dispatch calls */
  })
)(Component);
</code>```

However, this also throws the error that the embedded  mapStatetoProps and mapDispatchToProps calls to not define all Props each as both only require a subset of them, but together defining all Props.

How can I properly type the connect call so that the  mapStatetoProps and mapDispatchToProps calls are really type safe and typing checks if the combined values defined by both methods supply all required props without one of the methods required to define all props at once? Is this somehow possible with my approach?

答:
Really like @NSjonas's splitting approach, but I'd borrow something from his second approach as well to have a balance among practicality, not letting the implementation completely define your interface and not being extremely verbose in typing your dispatch actions;</p>

```<code>import * as React from 'react';
import { connect, Dispatch } from 'react-redux'
import { IStateStore } from '@src/reducers';
import { fooAction } from '@src/actions';

interface IComponentOwnProps {
  foo: string;
}

interface IComponentStoreProps {
  bar: string;
}

interface IComponentDispatchProps {
  doFoo: (...args: Parameters<typeof fooAction>) => void;
}

type IComponentProps = IComponentOwnProps & IComponentStoreProps & IComponentDispatchProps

class IComponent extends React.Component<IComponentProps, never> {
  public render() {
    return (
      <div>
        foo: {this.props.foo}
        bar: {this.props.bar}
        <button onClick={this.props.doFoo}>Do Foo</button>
      </div>
    );
  }
}

export default connect<IComponentStoreProps, IComponentDispatchProps, IComponentOwnProps, IStateStore>(
  (state, ownProps): IComponentStoreProps => {
    return {
      bar: state.bar + ownProps.foo
    };
  },
  {
      doFoo: fooAction
  }
)(IComponent);

</code>```

Body:
I am trying to use a Redux state store in combination with TypeScript. I am trying to use the official Typings of Redux and want to make the entire call on the connect method (which connects the mapStatetoProps and mapDispatchToProps with a component) type safe.

I usually see approaches where the methods mapStatetoProps and mapDispatchToProps are just custom typed and return a partial of the component props, such as the following:

function mapStateToProps(state: IStateStore, ownProps: Partial<IComponentProps>)
  : Partial<IProjectEditorProps> {}
function mapDispatchToProps (dispatch: Dispatch, ownProps: Partial<IComponentProps>)
  : Partial<IProjectEditorProps> {}

This is typed and works, but not really safe because it is possible to instantiate a component which misses props, as the usage of the Partial interface allows incomplete definitions. However, the Partial interface is required here because you may want to define some props in mapStateToProps and some in mapDispatchToProps, and not all in one function. So this is why I want to avoid this style.

What I am currently trying to use is directly embedding the functions in the connect call and typing the connect call with the generic typing supplied by redux:

connect<IComponentProps, any, any, IStateStore>(
  (state, ownProps) => ({
    /* some props supplied by redux state */
  }),
  dispatch => ({
    /* some more props supplied by dispatch calls */
  })
)(Component);

However, this also throws the error that the embedded  mapStatetoProps and mapDispatchToProps calls to not define all Props each as both only require a subset of them, but together defining all Props.

How can I properly type the connect call so that the  mapStatetoProps and mapDispatchToProps calls are really type safe and typing checks if the combined values defined by both methods supply all required props without one of the methods required to define all props at once? Is this somehow possible with my approach?

Body:
Really like @NSjonas's splitting approach, but I'd borrow something from his second approach as well to have a balance among practicality, not letting the implementation completely define your interface and not being extremely verbose in typing your dispatch actions;

import * as React from 'react';
import { connect, Dispatch } from 'react-redux'
import { IStateStore } from '@src/reducers';
import { fooAction } from '@src/actions';

interface IComponentOwnProps {
  foo: string;
}

interface IComponentStoreProps {
  bar: string;
}

interface IComponentDispatchProps {
  doFoo: (...args: Parameters<typeof fooAction>) => void;
}

type IComponentProps = IComponentOwnProps & IComponentStoreProps & IComponentDispatchProps

class IComponent extends React.Component<IComponentProps, never> {
  public render() {
    return (
      <div>
        foo: {this.props.foo}
        bar: {this.props.bar}
        <button onClick={this.props.doFoo}>Do Foo</button>
      </div>
    );
  }
}

export default connect<IComponentStoreProps, IComponentDispatchProps, IComponentOwnProps, IStateStore>(
  (state, ownProps): IComponentStoreProps => {
    return {
      bar: state.bar + ownProps.foo
    };
  },
  {
      doFoo: fooAction
  }
)(IComponent);


问:
CSC : error CS7038: Failed to emit module
After installing Visual Studio 2015 and building my project I receive the error

"CSC : error CS7038: Failed to emit module".

However my solution is building fine in Visual Studio 2013.

It is an ASP.NET webforms project .NET 4.0

Anyone?

UPDATE: it looks like the problem has to do with Red Gate Smart Assembly in combination with method parameters with default values.

UPDATE: Smart Assembly 6.9 fixes the error for me.

答:
Adding to the list of possible causes, in VS2019 with C# 8, I got the "Failed to emit module" message when doing something like:

```<code>_ = someBool ? SomeVoid() : default;
</code>```

I filed a bug report about it here: https://github.com/dotnet/roslyn/issues/41741

Body:
Adding to the list of possible causes, in VS2019 with C# 8, I got the "Failed to emit module" message when doing something like:

_ = someBool ? SomeVoid() : default;

I filed a bug report about it here: https://github.com/dotnet/roslyn/issues/41741


问:
Can video containing malware be cleaned through format conversion?
I'm trying to find out if video containing malware can be cleaned by converting the video to a different format. Similar to how images containing malware can be cleaned by converting them to .BMP.

I expect it's not that simple due to the complexity of video formats, but I haven't been able to find a definitive answer by Googling many reworded questions, so I'm hoping someone here may have an answer :).

Thanks.

答:
I don't think you will find a definitive answer to this as it will depend on the particular malware attack.

For example (with fictitious example attacks):

if the malware relies on a particular set of bytes in a data stream to trigger the attack, then transcoding and repackaging from one format to another will most likely change the bytes and hence defeat the attack.

if the malware is triggered by the user clicking a link in the video or by scanning an image for a barcode etc then transcoding will not impact the attack.

Looking at the first point - a given frame might be transported 'wrapped' in multiple layers:

raw pixels bitmap

raw pixels encoded (e.g. h.264, h.265 encoded)

encoded video stream packaged into container with audio streams, subtitles etc (e.g. mp4, avi container)

container broken into 'chunks' or segments for streaming (e.g. HLS or DASH streaming format).

If we look at transcoding from one codec to another as an example of changing the format, then, if your malware is in a particular byte sequence in the raw pixels then this transformation will change the bytes and presumably remove it. If the sequence of bytes was in the container or the streaming protocol, for example in one of the container metadata fields, then the malware would survive.

Similarly if you changed the container from mp4 to avi, but kept the codec the same, then the malware would survive if it was in the encoded video.

If you want to make sure everything has changed you would need to change the codec, the container and the streaming protocol and additionally probably remove all metadata and text as this would likely stay the same even when changing containers.

Note that the streams can be encrypted also which may help depending on where the vulnerable component is - i.e. if it is a router or firewall, but be aware many encryption schemes only partially encrypt video streams, for efficiency and to allow the metadata be read in some cases.


问:
How can i use Firebase App distribution without google account?
I am a Fabric user it works flawless for app distribution purpose. Recently I migrated my Fabric app to Firebase platform (as Google is removing Fabric) for app distribution with my testers. I followed their doc https://firebase.google.com/docs/app-distribution/ios/distribute-console and got email for app setup, but when I process it shows sign in with Google button. This is really useless how can my tester sign in without his google account as he only has our office domain email address?

I am unable to download with my domain email and can not share with our testers. How can I fix this?

Thanks,

答:
You need to create google account with with google domain.

http://google.com/accounts/NewAccount


问:
How to simplify user input
How can I simplify this code?

I check every input for an error, but in the way that I do, the code is duplicated.

```<code>long houseNumberOfFloors;
while (true) {
  System.out.print("Enter valid house number of floors: ");
  try {
    houseNumberOfFloors = Long.parseLong(br.readLine());
  } catch (NumberFormatException e) {
    continue;
  }
  if (FlatAttrValidator.checkHouseNumberOfFloors(houseNumberOfFloors)) {
    break;
  }
}

Integer houseNumberOfLifts;
while (true) {
  System.out.print("Enter valid house number of lifts: ");
  try {
    houseNumberOfLifts = Integer.parseInt(br.readLine());
  } catch (NumberFormatException e) {
    continue;
  }
  if (FlatAttrValidator.checkHouseNumberOfLifts(houseNumberOfLifts)) {
    break;
  }
}
</code>```

答:
I created the following solution for you, using functional interfaces:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class IReader {
    public static void main(String args[]) {
        InputStreamReader in= new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);

      Integer houseNumberOfFloors = getNumber(br, "Enter valid house number of floors: ", (i) -> FlatAttrValidator.checkHouseNumberOfFloors(i));
      Integer houseNumberOfLifts = getNumber(br, "Enter valid house number of lifts: ", (i) -> FlatAttrValidator.checkHouseNumberOfLifts(i));
      System.out.println("" + houseNumberOfFloors +"-" +houseNumberOfLifts);
    }

    public interface Checker {
        boolean check(Integer i);
    }

    private static Integer getNumber(BufferedReader br, String query, Checker checker) {

        Integer number;
        while (true) {
          System.out.println(query);
          try {
            number = Integer.parseInt(br.readLine());
          } catch (NumberFormatException|IOException e) {
            continue;
          }
          if (checker.check(number)) {
            break;
          }
        }
        return number;
    }

    private static class FlatAttrValidator {
        static boolean checkHouseNumberOfFloors(Integer i) {
            return i>0;
        }
        static boolean checkHouseNumberOfLifts(Integer i) {
            return i>0;
        }
    }
}
</code>```

It runs on https://www.jdoodle.com/online-java-compiler/.

Title: How to simplify user input

Body:
How can I simplify this code?

I check every input for an error, but in the way that I do, the code is duplicated.

long houseNumberOfFloors;
while (true) {
  System.out.print("Enter valid house number of floors: ");
  try {
    houseNumberOfFloors = Long.parseLong(br.readLine());
  } catch (NumberFormatException e) {
    continue;
  }
  if (FlatAttrValidator.checkHouseNumberOfFloors(houseNumberOfFloors)) {
    break;
  }
}

Integer houseNumberOfLifts;
while (true) {
  System.out.print("Enter valid house number of lifts: ");
  try {
    houseNumberOfLifts = Integer.parseInt(br.readLine());
  } catch (NumberFormatException e) {
    continue;
  }
  if (FlatAttrValidator.checkHouseNumberOfLifts(houseNumberOfLifts)) {
    break;
  }
}

Body:
I created the following solution for you, using functional interfaces:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class IReader {
    public static void main(String args[]) {
        InputStreamReader in= new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);

      Integer houseNumberOfFloors = getNumber(br, "Enter valid house number of floors: ", (i) -> FlatAttrValidator.checkHouseNumberOfFloors(i));
      Integer houseNumberOfLifts = getNumber(br, "Enter valid house number of lifts: ", (i) -> FlatAttrValidator.checkHouseNumberOfLifts(i));
      System.out.println("" + houseNumberOfFloors +"-" +houseNumberOfLifts);
    }

    public interface Checker {
        boolean check(Integer i);
    }

    private static Integer getNumber(BufferedReader br, String query, Checker checker) {

        Integer number;
        while (true) {
          System.out.println(query);
          try {
            number = Integer.parseInt(br.readLine());
          } catch (NumberFormatException|IOException e) {
            continue;
          }
          if (checker.check(number)) {
            break;
          }
        }
        return number;
    }

    private static class FlatAttrValidator {
        static boolean checkHouseNumberOfFloors(Integer i) {
            return i>0;
        }
        static boolean checkHouseNumberOfLifts(Integer i) {
            return i>0;
        }
    }
}

It runs on https://www.jdoodle.com/online-java-compiler/.


问:
ASP.NET :- Deleting records from two tables using single view
I want to delete data from 2 tables. I am using entity framework.

Here is the class .

```<code>[HttpPost]
        public ActionResult Delete(int employeeId)
        {
            int id = employeeId;
            MvcWebApp.DbModel.profile profile = dbContext.profiles.Find(employeeId);
            dbContext.profiles.Remove(profile);
            dbContext.SaveChanges();
            regi regi = dbContext.regis.Find(id);
            dbContext.regis.Remove(regi);
            dbContext.SaveChanges();
            return RedirectToAction("Index");
        }
</code>```

Where employeeId is the Column name of child table and Id is column name of parent table .

MvcWebApp.DbModel.profile This is fully qualified name of class.

I am getting profile object null.

答:
Need to include child table in parent object.</p>

```<code> [HttpPost]
         public ActionResult Delete(int id)
         {
            var parent = dbContext.regis.Include(p => p.profiles).SingleOrDefault(p => p.id == id);
            foreach(var child in parent.profiles.ToList())
            {
                dbContext.profiles.Remove(child);
                dbContext.SaveChanges();
            }
             return RedirectToAction("Index");
         }
</code>```

Body:
I want to delete data from 2 tables. I am using entity framework.

Here is the class .

[HttpPost]
        public ActionResult Delete(int employeeId)
        {
            int id = employeeId;
            MvcWebApp.DbModel.profile profile = dbContext.profiles.Find(employeeId);
            dbContext.profiles.Remove(profile);
            dbContext.SaveChanges();
            regi regi = dbContext.regis.Find(id);
            dbContext.regis.Remove(regi);
            dbContext.SaveChanges();
            return RedirectToAction("Index");
        }

Where employeeId is the Column name of child table and Id is column name of parent table .

MvcWebApp.DbModel.profile This is fully qualified name of class.

I am getting profile object null.

Body:
Need to include child table in parent object.

 [HttpPost]
         public ActionResult Delete(int id)
         {
            var parent = dbContext.regis.Include(p => p.profiles).SingleOrDefault(p => p.id == id);
            foreach(var child in parent.profiles.ToList())
            {
                dbContext.profiles.Remove(child);
                dbContext.SaveChanges();
            }
             return RedirectToAction("Index");
         }


问:
SetLockoutEndDateAsync not updating value in db
I have an ajax form that posts back when a user clicks a checkbox to lock a user out.  When I check the LockoutEndDateUtc column for said user remains NULL.

Here is my Json Method.

```<code>    [Authorize]
    [HttpPost]
    public JsonResult AjaxUpdateUserLockout(string userId)
    {
        string message = "";

        if (string.IsNullOrEmpty(userId)) message = "Unable to find user!";

        try
        {
            var result = UpdateLockoutDate(userId);
            message = "Success";
        }
        catch (Exception ex)
        {
            NLogger.Error(ex);
            message = "Error updating user!";
        }

        return new JsonResult()
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            Data = new { result = message }
        };
    }
</code>```

And here is the method I have which sets the lockout date

```<code>    private async Task<IdentityResult> UpdateLockoutDate(string userId)
    {
        var user = ApplicationUserManager.FindById(userId, new AFFirst2Entities());

        if (user.LockoutEndDateUtc != null && user.LockoutEndDateUtc != DateTime.MinValue)
        {
            return await ApplicationUserManager.SetLockoutEndDateAsync(userId, DateTimeOffset.MinValue);
        }
        else
        {
            return await ApplicationUserManager.SetLockoutEndDateAsync(userId, DateTimeOffset.MaxValue);
        }
    }
</code>```

Am I missing something? The LockoutEnabled column is set to true for all users.

答: I fixed this by setting user.LockoutEndDateUtc = DateTime.UtcNow, instead of using the SetLockoutEndDateAsync method.

Body:
I have an ajax form that posts back when a user clicks a checkbox to lock a user out.  When I check the LockoutEndDateUtc column for said user remains NULL.

Here is my Json Method.

    [Authorize]
    [HttpPost]
    public JsonResult AjaxUpdateUserLockout(string userId)
    {
        string message = "";

        if (string.IsNullOrEmpty(userId)) message = "Unable to find user!";

        try
        {
            var result = UpdateLockoutDate(userId);
            message = "Success";
        }
        catch (Exception ex)
        {
            NLogger.Error(ex);
            message = "Error updating user!";
        }

        return new JsonResult()
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            Data = new { result = message }
        };
    }

And here is the method I have which sets the lockout date

    private async Task<IdentityResult> UpdateLockoutDate(string userId)
    {
        var user = ApplicationUserManager.FindById(userId, new AFFirst2Entities());

        if (user.LockoutEndDateUtc != null && user.LockoutEndDateUtc != DateTime.MinValue)
        {
            return await ApplicationUserManager.SetLockoutEndDateAsync(userId, DateTimeOffset.MinValue);
        }
        else
        {
            return await ApplicationUserManager.SetLockoutEndDateAsync(userId, DateTimeOffset.MaxValue);
        }
    }

Am I missing something? The LockoutEnabled column is set to true for all users.


问:
Store Flyway metadata table externally
So just exploring the possibility of using flyway to maintain my DDL statements against Amazon Athena using Athena provided JDBC driver, Athena supports only CREATE statements (hive DDL) and no INSERTS.

So if database metadata table is the only one that flyway creates and updates, Is there anyway I can externalize the creating, storing into a totally different database ?

答:
Currently this is not possible in flyway, as the schema history is read from/written to the database defined by the current jdbc connection. You can see this for yourself in the JDBCTableSchemaHistory file.

If you wish to add this support, you could create a pull request on the repo, or just add an issue detailing exactly what you want the behaviour to be.

Title: Store Flyway metadata table externally


问:
Changing color of image in fabric.js
Recently I started exploring fabric.js. I want to change the color of an image by selecting a color from color picker.

I started by this example. Exploring the documentation of fabric.js I deduced (I might be wrong) that fabric uses the HSL color model. The problem is everywhere I search, the range of hue is given between 0 to 360 degrees but the HueRotation filter in fabric expects values to be between -1 to 1. In order to solve this I calculated sin of hue to bring it between -1 and 1 but that changes the colour all together.

It would be great if somebody points out what I am missing. I am using this code to convert HEX to HSL. The only difference is I calculate sin of hue by Math.sin(h * Math.PI/180) to get it into range of -1 to 1.

答:
If this library expects a normalized range equivalent to [-180º, 180º] or [-π, π], you can't resolve it with sine or cosine. Both functions can give the same result for different angles (sin(45) == sin(135)) while those angles represent different hues (yellow and lime green).

You can convert your input to [-180º, 180º] range first:

```<code>hue = hue % 360; //handle inputs greater than 360 degrees
let displacedHue = (hue > 180) ? hue - 360 : hue
</code>```

Then you normalize it to [-1, 1]:

```<code>let normalizedHue = displacedHue/180
</code>```

Title: Changing color of image in fabric.js

Body:
If this library expects a normalized range equivalent to [-180º, 180º] or [-π, π], you can't resolve it with sine or cosine. Both functions can give the same result for different angles (sin(45) == sin(135)) while those angles represent different hues (yellow and lime green).

You can convert your input to [-180º, 180º] range first:

hue = hue % 360; //handle inputs greater than 360 degrees
let displacedHue = (hue > 180) ? hue - 360 : hue

Then you normalize it to [-1, 1]:

let normalizedHue = displacedHue/180


问:
The 'for' loop only prints the first element of my array
I have a problem that I want to go through an array with a for loop, but for some reason the loop doesn't go through it and just prints the first element of the array everywhere.

Here is my array with the days:

```<code>readonly days: WeekDayName[] = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
</code>```

And my functions is what it looks like now:

```<code>get dayName() {
  for (const { item, index } of this.days.map((item, index) => ({ item, index }))) {
    return (item);
  }
}
</code>```

How can I solve not just print the first item everywhere?

答: You are returning the item after one iteration. What you should do is to create an empty array/map and on each iteration you can add the item to it. Then return that array.</p>

Body:
I have a problem that I want to go through an array with a for loop, but for some reason the loop doesn't go through it and just prints the first element of the array everywhere.

Here is my array with the days:

readonly days: WeekDayName[] = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

And my functions is what it looks like now:

get dayName() {
  for (const { item, index } of this.days.map((item, index) => ({ item, index }))) {
    return (item);
  }
}

How can I solve not just print the first item everywhere?


问:
How do I auto delete all records/rows that are older than a week in NodeJs?
I have a requirement where i only need to keep all the data that are not older than 7 days. All the data older that should be auto deleted from the database. I want to do this in NodeJs in ExpressJs server.

I have read that i can use setInterval() function for this.

```<code>function intervalFunc() {
    //send DELETE request to delete rows older than 7 days.
}
setInterval(intervalFunc,604800000); //interval of 7 days
</code>```

I want to know how do i write the Delete request to delete only those records that are older than 7 days.
And, if there's a better a way to do this??

答:
You can schedule a cron job at the application level to delete the old records. But you can also use "Auto expire documents feature with MongoDB"  this feature is since MongoDB version 2.2. MongoDB uses TTL collection for this. TTL collections make it possible to store data in MongoDB and have the MongoDB automatically removing data after a specified number of seconds or at a specific clock time.
Read more here :

https://docs.mongodb.com/manual/core/index-ttl/

http://hassansin.github.io/working-with-mongodb-ttl-index

Using Cron job you will have more control over the process such as sending some sort of notification or perform some action once expired data is deleted.

Body:
I have a requirement where i only need to keep all the data that are not older than 7 days. All the data older that should be auto deleted from the database. I want to do this in NodeJs in ExpressJs server.

I have read that i can use setInterval() function for this.

function intervalFunc() {
    //send DELETE request to delete rows older than 7 days.
}
setInterval(intervalFunc,604800000); //interval of 7 days

I want to know how do i write the Delete request to delete only those records that are older than 7 days.
And, if there's a better a way to do this??


问:
Updating array with React hooks
I am fundamentally misunderstanding React hooks, especially the useState function. Why doesn't the code below update the index of the old array, and instead set the value of trick to 1? I understand how to push a new item onto an array with React hooks, but how do you update existing values?</p>

```<code>const [trick, modifyTrick] = useState([null, null, null, null]);

const identityTrick = () => {
    modifyTrick(oldTrick => oldTrick) //works
}

const updatedTrick = () => {
    modifyTrick(oldTrick => oldTrick[0] = 1) //sets the entire value of trick to 1
}
</code>```

答:
If you provide modifyTrick a function, the return value will be the new value of trick.

The return value of your function is 1, so that's why trick is set to 1.

```<code>oldTrick[0] = 1 //this expression returns 1.
</code>```

Modify oldTrick array in your modifyTrick function, and than return it:

```<code>const updatedTrick = () => {
    modifyTrick(oldTrick => {
       oldTrick[0] = 1

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

Title: Updating array with React hooks

Body:
I am fundamentally misunderstanding React hooks, especially the useState function. Why doesn't the code below update the index of the old array, and instead set the value of trick to 1? I understand how to push a new item onto an array with React hooks, but how do you update existing values?

const [trick, modifyTrick] = useState([null, null, null, null]);

const identityTrick = () => {
    modifyTrick(oldTrick => oldTrick) //works
}

const updatedTrick = () => {
    modifyTrick(oldTrick => oldTrick[0] = 1) //sets the entire value of trick to 1
}

Body:
If you provide modifyTrick a function, the return value will be the new value of trick.

The return value of your function is 1, so that's why trick is set to 1.

oldTrick[0] = 1 //this expression returns 1.

Modify oldTrick array in your modifyTrick function, and than return it:

const updatedTrick = () => {
    modifyTrick(oldTrick => {
       oldTrick[0] = 1

       return oldTrick;
    });
};


问:
Getting "A potentially dangerous Request.Path value was detected from the client (&)"
I've got a legacy code issue that requires that I support random URLs as if they were requests for the home page. Some of the URLs have characters in them that generate the error "A potentially dangerous Request.Path value was detected from the client (&)". The site is written with ASP.Net MVC 3 (in C#) and is running on IIS 7.5.

Here's an example URL...

```<code>http://mywebsite.example/Test123/This_&_That
</code>```

Here's how I have my catch-all route setup (I have other routes to catch specific pages)...

```<code>routes.MapRoute(
    "Default", // Route name
    "{garb1}/{garb2}", // URL with parameters
    new { controller = "Website", action = "Home", garb1 = UrlParameter.Optional, garb2 = UrlParameter.Optional } // Parameter defaults
);
</code>```

I've added the following things to my web.config file...

```<code><configuration>
    <system.web>
        <pages validateRequest="false" />
        <httpRuntime requestValidationMode="2.0" />
    </system.web>
<configuration>
</code>```

I've also Added the ValidateInput attribute to the action that should be catching the urls...

```<code>public class WebsiteController : Controller
{
    [ValidateInput(false)]
    public ActionResult Home()
    {
        return View();
    }
}
</code>```

But I'm still getting the error. Any ideas why? Did I miss something? Right now I'm just running on my local dev server (I haven't tried these fixes in production yet).

答:
While you could try these settings in config file

```<code><system.web>
    <httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
    <pages validateRequest="false" />
</system.web>
</code>```

I would avoid using characters like '&' in URL path replacing them with underscores.

Body:
I've got a legacy code issue that requires that I support random URLs as if they were requests for the home page. Some of the URLs have characters in them that generate the error "A potentially dangerous Request.Path value was detected from the client (&)". The site is written with ASP.Net MVC 3 (in C#) and is running on IIS 7.5.

Here's an example URL...

http://mywebsite.example/Test123/This_&_That

Here's how I have my catch-all route setup (I have other routes to catch specific pages)...

routes.MapRoute(
    "Default", // Route name
    "{garb1}/{garb2}", // URL with parameters
    new { controller = "Website", action = "Home", garb1 = UrlParameter.Optional, garb2 = UrlParameter.Optional } // Parameter defaults
);

I've added the following things to my web.config file...

<configuration>
    <system.web>
        <pages validateRequest="false" />
        <httpRuntime requestValidationMode="2.0" />
    </system.web>
<configuration>

I've also Added the ValidateInput attribute to the action that should be catching the urls...

public class WebsiteController : Controller
{
    [ValidateInput(false)]
    public ActionResult Home()
    {
        return View();
    }
}

But I'm still getting the error. Any ideas why? Did I miss something? Right now I'm just running on my local dev server (I haven't tried these fixes in production yet).

Body:
While you could try these settings in config file

<system.web>
    <httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
    <pages validateRequest="false" />
</system.web>

I would avoid using characters like '&' in URL path replacing them with underscores.


问:
How to find the available colours for hi-ColorColumn in Vim
I need to set up a "colorcolumn" to indicate a length of 100 characters in vim (v7.4). Instead of using the default settings for "cterm", I would like to set a different colour.

Problem is, certain colour names I use, throw an error stating it is invalid.

```<code>E421: Color name or number not recognized: ctermbg=ivory guibg=blue
</code>```

How can I find the list of available colours for my terminal?

答:
Open vim and run the below command. It will list the available list of colours.

```<code>:so $VIMRUNTIME/syntax/colortest.vim
</code>```

I already have the below two lines added in my .vimrc file.

```<code>":set colorcolumn=100,80  (set multiple colorcolumn)

:set cc=100
:hi ColorColumn ctermbg=lightcyan guibg=blue
</code>```

For someone curious, I found useful information in the below documentation.

Vim Documentation Syntax

Body:
I need to set up a "colorcolumn" to indicate a length of 100 characters in vim (v7.4). Instead of using the default settings for "cterm", I would like to set a different colour.

Problem is, certain colour names I use, throw an error stating it is invalid.

E421: Color name or number not recognized: ctermbg=ivory guibg=blue

How can I find the list of available colours for my terminal?

Body:
Open vim and run the below command. It will list the available list of colours.

:so $VIMRUNTIME/syntax/colortest.vim

I already have the below two lines added in my .vimrc file.

":set colorcolumn=100,80  (set multiple colorcolumn)

:set cc=100
:hi ColorColumn ctermbg=lightcyan guibg=blue

For someone curious, I found useful information in the below documentation.

Vim Documentation Syntax


问:
How to get quantity of a WooCommerce subscription?
I am currently developing a WordPress project and I am using WooCommerce with WooCommerce Subscriptions plugin to offer subscriptions to my users. I need help on how to get the quantity of a subscription in PHP.

I am using this code to get subscription but I can not retrieve quantity:

```<code>$subscriptions = wcs_get_subscriptions( array(
    'customer_id'            => get_current_user_id(),
    'subscription_status'    => 'wc-active',
    'order_by'               => 'DESC',
    'subscriptions_per_page' => - 1
) );
</code>```

When a user purchases a subscription, the user can select the quantity of subscriptions. So I need to get the value of this field:

答:
Here is my working code try this

```<code>$current_user_id = get_current_user_id();
$customer_subscriptions = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(), // Or $user_id
    'post_type'   => 'shop_subscription', // WC orders post type
    'post_status' => 'wc-active' // Only orders with status "completed"
) );
</code>```

And if you want get all post_status subscription then use this

```<code>
$customer_subscriptions_for_other_cases = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(), // Or $user_id
    'post_type'   => 'shop_subscription', // WC orders post type
    'post_status' => array('wc-on-hold','wc-pending-cancel','wc-active') // Only orders with status "completed"
) );
</code>```

Thanks

Body:
I am currently developing a WordPress project and I am using WooCommerce with WooCommerce Subscriptions plugin to offer subscriptions to my users. I need help on how to get the quantity of a subscription in PHP.

I am using this code to get subscription but I can not retrieve quantity:

$subscriptions = wcs_get_subscriptions( array(
    'customer_id'            => get_current_user_id(),
    'subscription_status'    => 'wc-active',
    'order_by'               => 'DESC',
    'subscriptions_per_page' => - 1
) );

When a user purchases a subscription, the user can select the quantity of subscriptions. So I need to get the value of this field:

Body:
Here is my working code try this

$current_user_id = get_current_user_id();
$customer_subscriptions = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(), // Or $user_id
    'post_type'   => 'shop_subscription', // WC orders post type
    'post_status' => 'wc-active' // Only orders with status "completed"
) );

And if you want get all post_status subscription then use this

$customer_subscriptions_for_other_cases = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(), // Or $user_id
    'post_type'   => 'shop_subscription', // WC orders post type
    'post_status' => array('wc-on-hold','wc-pending-cancel','wc-active') // Only orders with status "completed"
) );

Thanks


问:
Showing results for a quiz app (Android Studio)
I have a quiz app that is working properly, but the thing is the user must answer all questions correctly in order to win the game(if the player gets it wrong the game will be over) .

What I wanted to do is have the questions answered and then at the end there will be an activity that will show how many the player has answered then there will be the options to retry and go back to menu

This is the code for the maingameactivity

```<code>public class MainGameActivity extends AppCompatActivity {
FButton buttonA, buttonB, buttonC, buttonD;
TextView questionText, triviaQuizText, timeText, resultText, coinText;
TriviaQuizHelper triviaQuizHelper;
TriviaQuestion currentQuestion;
List<TriviaQuestion> list;
int qid = 0;
int timeValue = 20;
int coinValue = 0;
CountDownTimer countDownTimer;
Typeface tb, sb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_main);

    //Initializing variables
    questionText = (TextView) findViewById(R.id.triviaQuestion);
    buttonA = (FButton) findViewById(R.id.buttonA);
    buttonB = (FButton) findViewById(R.id.buttonB);
    buttonC = (FButton) findViewById(R.id.buttonC);
    buttonD = (FButton) findViewById(R.id.buttonD);
    triviaQuizText = (TextView) findViewById(R.id.triviaQuizText);
    timeText = (TextView) findViewById(R.id.timeText);
    resultText = (TextView) findViewById(R.id.resultText);
    coinText = (TextView) findViewById(R.id.coinText);

    //Setting typefaces for textview and buttons - this will give stylish fonts on textview and button etc
    tb = Typeface.createFromAsset(getAssets(), "fonts/TitilliumWeb-Bold.ttf");
    sb = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
    triviaQuizText.setTypeface(sb);
    questionText.setTypeface(tb);
    buttonA.setTypeface(tb);
    buttonB.setTypeface(tb);
    buttonC.setTypeface(tb);
    buttonD.setTypeface(tb);
    timeText.setTypeface(tb);
    resultText.setTypeface(sb);
    coinText.setTypeface(tb);

    //Our database helper class
    triviaQuizHelper = new TriviaQuizHelper(this);
    //Make db writable
    triviaQuizHelper.getWritableDatabase();

    //It will check if the ques,options are already added in table or not
    //If they are not added then the getAllOfTheQuestions() will return a list of size zero
    if (triviaQuizHelper.getAllOfTheQuestions().size() == 0) {
        //If not added then add the ques,options in table
        triviaQuizHelper.allQuestion();
    }

    //This will return us a list of data type TriviaQuestion
    list = triviaQuizHelper.getAllOfTheQuestions();

    //Now we gonna shuffle the elements of the list so that we will get questions randomly
    Collections.shuffle(list);

    //currentQuestion will hold the que, 4 option and ans for particular id
    currentQuestion = list.get(qid);

    //countDownTimer
    countDownTimer = new CountDownTimer(22000, 1000) {
        public void onTick(long millisUntilFinished) {

            //here you can have your logic to set text to timeText
            timeText.setText(String.valueOf(timeValue) + "\"");

            //With each iteration decrement the time by 1 sec
            timeValue -= 1;

            //This means the user is out of time so onFinished will called after this iteration
            if (timeValue == -1) {

                //Since user is out of time setText as time up
                resultText.setText(getString(R.string.timeup));

                //Since user is out of time he won't be able to click any buttons
                //therefore we will disable all four options buttons using this method
                disableButton();
            }
        }

        //Now user is out of time
        public void onFinish() {
            //We will navigate him to the time up activity using below method
            timeUp();
        }
    }.start();

    //This method will set the que and four options
    updateQueAndOptions();

}

public void updateQueAndOptions() {

    //This method will setText for que and options
    questionText.setText(currentQuestion.getQuestion());
    buttonA.setText(currentQuestion.getOptA());
    buttonB.setText(currentQuestion.getOptB());
    buttonC.setText(currentQuestion.getOptC());
    buttonD.setText(currentQuestion.getOptD());

    timeValue = 20;

    //Now since the user has ans correct just reset timer back for another que- by cancel and start
    countDownTimer.cancel();
    countDownTimer.start();

    //set the value of coin text
    coinText.setText(String.valueOf(coinValue));
    //Now since user has ans correct increment the coinvalue
    coinValue++;

}

//Onclick listener for first button
public void buttonA(View view) {
    //compare the option with the ans if yes then make button color green
    if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
        buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
        //Check if user has not exceeds the que limit
        if (qid < list.size() - 1) {

            //Now disable all the option button since user ans is correct so
            //user won't be able to press another option button after pressing one button
            disableButton();

            //Show the dialog that ans is correct
            correctDialog();
        }
        //If user has exceeds the que limit just navigate him to GameWon activity
        else {

            gameWon();

        }
    }
    //User ans is wrong then just navigate him to the PlayAgain activity
    else {

        gameLostPlayAgain();

    }
}

//Onclick listener for sec button
public void buttonB(View view) {
    if (currentQuestion.getOptB().equals(currentQuestion.getAnswer())) {
        buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
        if (qid < list.size() - 1) {
            disableButton();
            correctDialog();
        } else {
            gameWon();
        }
    } else {
        gameLostPlayAgain();
    }
}

//Onclick listener for third button
public void buttonC(View view) {
    if (currentQuestion.getOptC().equals(currentQuestion.getAnswer())) {
        buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
        if (qid < list.size() - 1) {
            disableButton();
            correctDialog();
        } else {
            gameWon();
        }
    } else {

        gameLostPlayAgain();
    }
}

//Onclick listener for fourth button
public void buttonD(View view) {
    if (currentQuestion.getOptD().equals(currentQuestion.getAnswer())) {
        buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
        if (qid < list.size() - 1) {
            disableButton();
            correctDialog();
        } else {
            gameWon();
        }
    } else {
        gameLostPlayAgain();
    }
}

//This method will navigate from current activity to GameWon
public void gameWon() {
    Intent intent = new Intent(this, GameWon.class);
    startActivity(intent);
    finish();
}

//This method is called when user ans is wrong
//this method will navigate user to the activity PlayAgain
public void gameLostPlayAgain() {
    Intent intent = new Intent(this, PlayAgain.class);
    startActivity(intent);
    finish();
}

//This method is called when time is up
//this method will navigate user to the activity Time_Up
public void timeUp() {
    Intent intent = new Intent(this, Time_Up.class);
    startActivity(intent);
    finish();
}

//If user press home button and come in the game from memory then this
//method will continue the timer from the previous time it left
@Override
protected void onRestart() {
    super.onRestart();
    countDownTimer.start();
}

//When activity is destroyed then this will cancel the timer
@Override
protected void onStop() {
    super.onStop();
    countDownTimer.cancel();
}

//This will pause the time
@Override
protected void onPause() {
    super.onPause();
    countDownTimer.cancel();
}

//On BackPressed
@Override
public void onBackPressed() {
    Intent intent = new Intent(this, HomeScreen.class);
    startActivity(intent);
    finish();
}

//This dialog is show to the user after he ans correct
public void correctDialog() {
    final Dialog dialogCorrect = new Dialog(MainGameActivity.this);
    dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
    if (dialogCorrect.getWindow() != null) {
        ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
        dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
    }
    dialogCorrect.setContentView(R.layout.dialog_correct);
    dialogCorrect.setCancelable(false);
    dialogCorrect.show();

    //Since the dialog is show to user just pause the timer in background
    onPause();

    TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
    FButton buttonNext = (FButton) dialogCorrect.findViewById(R.id.dialogNext);

    //Setting type faces
    correctText.setTypeface(sb);
    buttonNext.setTypeface(sb);

    //OnCLick listener to go next que
    buttonNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //This will dismiss the dialog
            dialogCorrect.dismiss();
            //it will increment the question number
            qid++;
            //get the que and 4 option and store in the currentQuestion
            currentQuestion = list.get(qid);
            //Now this method will set the new que and 4 options
            updateQueAndOptions();
            //reset the color of buttons back to white
            resetColor();
            //Enable button - remember we had disable them when user ans was correct in there particular button methods
            enableButton();
        }
    });
}

//This method will make button color white again since our one button color was turned green
public void resetColor() {
    buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
    buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
    buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
    buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
}

//This method will disable all the option button
public void disableButton() {
    buttonA.setEnabled(false);
    buttonB.setEnabled(false);
    buttonC.setEnabled(false);
    buttonD.setEnabled(false);
}

//This method will all enable the option buttons
public void enableButton() {
    buttonA.setEnabled(true);
    buttonB.setEnabled(true);
    buttonC.setEnabled(true);
    buttonD.setEnabled(true);
    }

}
</code>```

答:
Edited

Just remove the wrapper if else inside all the buttons better to keep it as, don't repeat the code. I am assuming the screen that shows result is handled inside gameWon and you have implemented functionality for inCorrectDialog

```<code>public void buttonA(View view) {
 Button button = (Button) view;
 buttonPressed(button);
}
public void buttonB(View view) {
 Button button = (Button) view;
 buttonPressed(button);
}

public void buttonC(View view) {
 Button button = (Button) view;
 buttonPressed(button);
}

public void buttonD(View view) {
 Button button = (Button) view;
 buttonPressed(button);
}

public void buttonPressed(Button button) {

 button.setButtonColor(ContextCompat.getColor(getApplicationContext(), R.color.lightGreen));
 if (qid < list.size() - 1) {
  disableButton();
  if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
   correctDialog();
  } else {
   inCorrectDialog();
  }

 } else {
  gameWon();
 }

}
</code>```

Body:
I have a quiz app that is working properly, but the thing is the user must answer all questions correctly in order to win the game(if the player gets it wrong the game will be over) .

What I wanted to do is have the questions answered and then at the end there will be an activity that will show how many the player has answered then there will be the options to retry and go back to menu

This is the code for the maingameactivity

public class MainGameActivity extends AppCompatActivity {
FButton buttonA, buttonB, buttonC, buttonD;
TextView questionText, triviaQuizText, timeText, resultText, coinText;
TriviaQuizHelper triviaQuizHelper;
TriviaQuestion currentQuestion;
List<TriviaQuestion> list;
int qid = 0;
int timeValue = 20;
int coinValue = 0;
CountDownTimer countDownTimer;
Typeface tb, sb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_main);

    //Initializing variables
    questionText = (TextView) findViewById(R.id.triviaQuestion);
    buttonA = (FButton) findViewById(R.id.buttonA);
    buttonB = (FButton) findViewById(R.id.buttonB);
    buttonC = (FButton) findViewById(R.id.buttonC);
    buttonD = (FButton) findViewById(R.id.buttonD);
    triviaQuizText = (TextView) findViewById(R.id.triviaQuizText);
    timeText = (TextView) findViewById(R.id.timeText);
    resultText = (TextView) findViewById(R.id.resultText);
    coinText = (TextView) findViewById(R.id.coinText);

    //Setting typefaces for textview and buttons - this will give stylish fonts on textview and button etc
    tb = Typeface.createFromAsset(getAssets(), "fonts/TitilliumWeb-Bold.ttf");
    sb = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
    triviaQuizText.setTypeface(sb);
    questionText.setTypeface(tb);
    buttonA.setTypeface(tb);
    buttonB.setTypeface(tb);
    buttonC.setTypeface(tb);
    buttonD.setTypeface(tb);
    timeText.setTypeface(tb);
    resultText.setTypeface(sb);
    coinText.setTypeface(tb);

    //Our database helper class
    triviaQuizHelper = new TriviaQuizHelper(this);
    //Make db writable
    triviaQuizHelper.getWritableDatabase();

    //It will check if the ques,options are already added in table or not
    //If they are not added then the getAllOfTheQuestions() will return a list of size zero
    if (triviaQuizHelper.getAllOfTheQuestions().size() == 0) {
        //If not added then add the ques,options in table
        triviaQuizHelper.allQuestion();
    }

    //This will return us a list of data type TriviaQuestion
    list = triviaQuizHelper.getAllOfTheQuestions();

    //Now we gonna shuffle the elements of the list so that we will get questions randomly
    Collections.shuffle(list);

    //currentQuestion will hold the que, 4 option and ans for particular id
    currentQuestion = list.get(qid);

    //countDownTimer
    countDownTimer = new CountDownTimer(22000, 1000) {
        public void onTick(long millisUntilFinished) {

            //here you can have your logic to set text to timeText
            timeText.setText(String.valueOf(timeValue) + "\"");

            //With each iteration decrement the time by 1 sec
            timeValue -= 1;

            //This means the user is out of time so onFinished will called after this iteration
            if (timeValue == -1) {

                //Since user is out of time setText as time up
                resultText.setText(getString(R.string.timeup));

                //Since user is out of time he won't be able to click any buttons
                //therefore we will disable all four options buttons using this method
                disableButton();
            }
        }

        //Now user is out of time
        public void onFinish() {
            //We will navigate him to the time up activity using below method
            timeUp();
        }
    }.start();

    //This method will set the que and four options
    updateQueAndOptions();

}

public void updateQueAndOptions() {

    //This method will setText for que and options
    questionText.setText(currentQuestion.getQuestion());
    buttonA.setText(currentQuestion.getOptA());
    buttonB.setText(currentQuestion.getOptB());
    buttonC.setText(currentQuestion.getOptC());
    buttonD.setText(currentQuestion.getOptD());

    timeValue = 20;

    //Now since the user has ans correct just reset timer back for another que- by cancel and start
    countDownTimer.cancel();
    countDownTimer.start();

    //set the value of coin text
    coinText.setText(String.valueOf(coinValue));
    //Now since user has ans correct increment the coinvalue
    coinValue++;

}

//Onclick listener for first button
public void buttonA(View view) {
    //compare the option with the ans if yes then make button color green
    if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
        buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
        //Check if user has not exceeds the que limit
        if (qid < list.size() - 1) {

            //Now disable all the option button since user ans is correct so
            //user won't be able to press another option button after pressing one button
            disableButton();

            //Show the dialog that ans is correct
            correctDialog();
        }
        //If user has exceeds the que limit just navigate him to GameWon activity
        else {

            gameWon();

        }
    }
    //User ans is wrong then just navigate him to the PlayAgain activity
    else {

        gameLostPlayAgain();

    }
}

//Onclick listener for sec button
public void buttonB(View view) {
    if (currentQuestion.getOptB().equals(currentQuestion.getAnswer())) {
        buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
        if (qid < list.size() - 1) {
            disableButton();
            correctDialog();
        } else {
            gameWon();
        }
    } else {
        gameLostPlayAgain();
    }
}

//Onclick listener for third button
public void buttonC(View view) {
    if (currentQuestion.getOptC().equals(currentQuestion.getAnswer())) {
        buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
        if (qid < list.size() - 1) {
            disableButton();
            correctDialog();
        } else {
            gameWon();
        }
    } else {

        gameLostPlayAgain();
    }
}

//Onclick listener for fourth button
public void buttonD(View view) {
    if (currentQuestion.getOptD().equals(currentQuestion.getAnswer())) {
        buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
        if (qid < list.size() - 1) {
            disableButton();
            correctDialog();
        } else {
            gameWon();
        }
    } else {
        gameLostPlayAgain();
    }
}

//This method will navigate from current activity to GameWon
public void gameWon() {
    Intent intent = new Intent(this, GameWon.class);
    startActivity(intent);
    finish();
}

//This method is called when user ans is wrong
//this method will navigate user to the activity PlayAgain
public void gameLostPlayAgain() {
    Intent intent = new Intent(this, PlayAgain.class);
    startActivity(intent);
    finish();
}

//This method is called when time is up
//this method will navigate user to the activity Time_Up
public void timeUp() {
    Intent intent = new Intent(this, Time_Up.class);
    startActivity(intent);
    finish();
}

//If user press home button and come in the game from memory then this
//method will continue the timer from the previous time it left
@Override
protected void onRestart() {
    super.onRestart();
    countDownTimer.start();
}

//When activity is destroyed then this will cancel the timer
@Override
protected void onStop() {
    super.onStop();
    countDownTimer.cancel();
}

//This will pause the time
@Override
protected void onPause() {
    super.onPause();
    countDownTimer.cancel();
}

//On BackPressed
@Override
public void onBackPressed() {
    Intent intent = new Intent(this, HomeScreen.class);
    startActivity(intent);
    finish();
}

//This dialog is show to the user after he ans correct
public void correctDialog() {
    final Dialog dialogCorrect = new Dialog(MainGameActivity.this);
    dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
    if (dialogCorrect.getWindow() != null) {
        ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
        dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
    }
    dialogCorrect.setContentView(R.layout.dialog_correct);
    dialogCorrect.setCancelable(false);
    dialogCorrect.show();

    //Since the dialog is show to user just pause the timer in background
    onPause();

    TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
    FButton buttonNext = (FButton) dialogCorrect.findViewById(R.id.dialogNext);

    //Setting type faces
    correctText.setTypeface(sb);
    buttonNext.setTypeface(sb);

    //OnCLick listener to go next que
    buttonNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //This will dismiss the dialog
            dialogCorrect.dismiss();
            //it will increment the question number
            qid++;
            //get the que and 4 option and store in the currentQuestion
            currentQuestion = list.get(qid);
            //Now this method will set the new que and 4 options
            updateQueAndOptions();
            //reset the color of buttons back to white
            resetColor();
            //Enable button - remember we had disable them when user ans was correct in there particular button methods
            enableButton();
        }
    });
}

//This method will make button color white again since our one button color was turned green
public void resetColor() {
    buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
    buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
    buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
    buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
}

//This method will disable all the option button
public void disableButton() {
    buttonA.setEnabled(false);
    buttonB.setEnabled(false);
    buttonC.setEnabled(false);
    buttonD.setEnabled(false);
}

//This method will all enable the option buttons
public void enableButton() {
    buttonA.setEnabled(true);
    buttonB.setEnabled(true);
    buttonC.setEnabled(true);
    buttonD.setEnabled(true);
    }

}

Body:
Edited

Just remove the wrapper if else inside all the buttons better to keep it as, don't repeat the code. I am assuming the screen that shows result is handled inside gameWon and you have implemented functionality for inCorrectDialog

public void buttonA(View view) {
 Button button = (Button) view;
 buttonPressed(button);
}
public void buttonB(View view) {
 Button button = (Button) view;
 buttonPressed(button);
}

public void buttonC(View view) {
 Button button = (Button) view;
 buttonPressed(button);
}

public void buttonD(View view) {
 Button button = (Button) view;
 buttonPressed(button);
}

public void buttonPressed(Button button) {

 button.setButtonColor(ContextCompat.getColor(getApplicationContext(), R.color.lightGreen));
 if (qid < list.size() - 1) {
  disableButton();
  if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
   correctDialog();
  } else {
   inCorrectDialog();
  }

 } else {
  gameWon();
 }

}


问:
Launching a Python watchdog in an Azure Devops Release pipeline
I have a situation where I would like to start up two Python watchdogs consecutively in an Azure Release stage and then continue with the following tasks.

As I understand, the subprocess.Popen is the way to go if you want to create a "fire & forget" behavior like this
When I run something like subprocess.Popen(["python", "mywatchdog1.py"])outside of Azure it behaves as I expect, it "fires & forgets", but when running that same call from a task (tried with both "Powershell" and "Run a Python Script") in Azure Devops, the task stops and waits for the watchdog process to finish.

Here's an example:

```<code># mywatchdog1.py

import time
import os
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

class MyWatchdogEventHandler(LoggingEventHandler):

    def dispatch(self, event):
        print(f"A new dog was created")

if __name__ == "__main__":
    dog_file_path = "c:\\dogs"
    event_handler = MyWatchdogEventHandler()
    observer = Observer()
    observer.schedule(event_handler, dog_file_path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
</code>```

This is what I'm trying to launch using something like:

```<code>import subprocess as sp

if __name__ == "__main__":
    sp.Popen(["python", "C:\\scripts\\mywatchdog01.py"])
</code>```

So, how do I make subprocess.Popen behave the same way regardless if you run locally or on an Azure Windows 2016 agent? Any help would be greatly appreciated.

/Niklas

答:
So, how do I make subprocess.Popen behave the same way regardless if
  you run locally or on an Azure Windows 2016 agent?

Sorry but I'm afraid this is not supported scenario for now. Azure Devops pipeline executes the tasks one by one, it won't finish current task until it finishes all the job to be done within it.

That's why it hangs in your Powershell or Run a Python Script task cause the watchdog is always listening to inputs. You can refer to this document for more details. And it's by design that the task won't finish if there's something like watchdog within the task keeping monitoring the file explorer changes.

Hope my answer helps to resolve your puzzle :)

Body:
I have a situation where I would like to start up two Python watchdogs consecutively in an Azure Release stage and then continue with the following tasks.

As I understand, the subprocess.Popen is the way to go if you want to create a "fire & forget" behavior like this
When I run something like subprocess.Popen(["python", "mywatchdog1.py"])outside of Azure it behaves as I expect, it "fires & forgets", but when running that same call from a task (tried with both "Powershell" and "Run a Python Script") in Azure Devops, the task stops and waits for the watchdog process to finish.

Here's an example:

# mywatchdog1.py

import time
import os
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

class MyWatchdogEventHandler(LoggingEventHandler):

    def dispatch(self, event):
        print(f"A new dog was created")

if __name__ == "__main__":
    dog_file_path = "c:\\dogs"
    event_handler = MyWatchdogEventHandler()
    observer = Observer()
    observer.schedule(event_handler, dog_file_path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

This is what I'm trying to launch using something like:

import subprocess as sp

if __name__ == "__main__":
    sp.Popen(["python", "C:\\scripts\\mywatchdog01.py"])

So, how do I make subprocess.Popen behave the same way regardless if you run locally or on an Azure Windows 2016 agent? Any help would be greatly appreciated.

/Niklas


问:
js-cookie not setting cookies when secure flag is enabled
I have this simple function that sets a cookie

Cookies.set('accesstoken', res.data.accesstoken);

I wanted to make it secure but whenever I put

Cookies.set('accesstoken', res.data.accesstoken, { secure: true });

The cookie is not set

答:
As per the js-cookie documentation:

secure

Either true or false, indicating if the cookie transmission requires a
    secure protocol (https).

Default: No secure protocol requirement.

You need to use https in order to set the cookie using {secure:ture}