问:
How to serialize interface default property?
This question is resurrected, because I was wrong in comment "My bad".
This issue is there, or I miss something. For popular demand here is a minimal reproducable example:

minimal reproducable example

I have an interface with a default property:

```<code>public interface INotification
{
    // ...
    Severity Severity { get; set; } // Severity is an Enum
    // ...
    public string SeverityName => Severity.ToString().ToLower();
}
</code>```

I have an implementation class

```<code>public class Notification : INotification
{
    // ...
    public Severity Severity { get; set; }
    // ...
    // This class does not override default implementation of SeverityName
}
</code>```

Question

The Notification class does not have a SeverityName property... this was surprising, but I can live with that, accessing to the notification instance via the INotification interface.

However, I would like to serialize this class with System.Text.Json. How can I serialize SeverityName property too?

答:
This is not possible with System.Text.Json in .NET Core 3.1 other than by writing a custom JsonConverter for Notification. The serializer serializes the public properties of a type, but default interface properties are not implemented as class properties, instead they're implemented through some sort of extension mechanism. See the spec: default interface methods

Add support for virtual extension methods - methods in interfaces with concrete implementations. .

Only when the default interface property is overridden does an instance property actually get added to the implementing concrete type, and thereby become serializable.

For confirmation, if we modify the classes from your fiddle as follows:

```<code>public interface INotification
{
    Severity Severity { get; set; }
    string Message { get; set; }

    static string MakeDefaultSeverityName<TNotification>(TNotification notification) where TNotification : INotification => notification?.Severity.ToString().ToLower();

    public string SeverityName => MakeDefaultSeverityName(this);
}

public class Notification : INotification
{
    public Severity Severity { get; set; }
    public string Message { get; set; }
}

public class NotificationWithOverride : Notification
{
    public string SeverityName => INotification.MakeDefaultSeverityName(this);
}
</code>```

And print out the properties and methods of both types using reflection:

```<code>Console.WriteLine("Properties of {0}: {1}", typeof(TNotification).Name, string.Join(", ", typeof(TNotification).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Select(p => p.Name)));
Console.WriteLine("Methods of {0}: {1}", typeof(TNotification).Name, string.Join(", ", typeof(TNotification).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Select(p => p.Name)));
</code>```

We get the following results for Notification:

Properties of Notification: Severity, Message
Methods of Notification: get_Severity, set_Severity, get_Message, set_Message, GetType, MemberwiseClone, Finalize, ToString, Equals, GetHashCode
```

<p>And for <code>NotificationWithOverride</code>:</p>

<pre class="lang-none prettyprint-override"><code>Properties of NotificationWithOverride: SeverityName, Severity, Message
Methods of NotificationWithOverride: get_SeverityName, get_Severity, set_Severity, get_Message, set_Message, GetType, MemberwiseClone, Finalize, ToString, Equals, GetHashCode
</code>```

Notice there's just no instance property or method corresponding to SeverityName in Notification -- but there is in NotificationWithOverride.  Lacking a property to serialize, the serializer does not output a SeverityName value.

Notes:

System.Text.Json is consistent with other serializers in this respect; both it and Json.NET generate exactly the same JSON:

{"Severity":0,"Message":"Message"} for Notification.

{"SeverityName":"info","Severity":0,"Message":"Message"} for NotificationWithOverride.

With Json.NET it might be possible to create a custom contract resolver that automatically adds in the missing default properties, but System.Text.Json does not have public access to its contract resolver; for confirmation see the question System.Text.Json API is there something like IContractResolver to which the answer is, not currently.

In c# 8.0 it is not possible for to override a default interface method in a concrete class and call the base interface method.  See How can I call the default method instead of the concrete implementation, Making member virtual prevents calling default interface implementation and causes StackOverflowException in C# 8 and Default interface implementations and base() calls for details.

To work around this I added a static interface method to INotification that encapsulates the default logic, then called it from both the default interface instance method and the override class method.

A demo fiddle that shows the above can be found here.

Body:
This question is resurrected, because I was wrong in comment "My bad".
This issue is there, or I miss something. For popular demand here is a minimal reproducable example:

minimal reproducable example

I have an interface with a default property:

public interface INotification
{
    // ...
    Severity Severity { get; set; } // Severity is an Enum
    // ...
    public string SeverityName => Severity.ToString().ToLower();
}

I have an implementation class

public class Notification : INotification
{
    // ...
    public Severity Severity { get; set; }
    // ...
    // This class does not override default implementation of SeverityName
}

Question

The Notification class does not have a SeverityName property... this was surprising, but I can live with that, accessing to the notification instance via the INotification interface.

However, I would like to serialize this class with System.Text.Json. How can I serialize SeverityName property too?

Body:
This is not possible with System.Text.Json in .NET Core 3.1 other than by writing a custom JsonConverter for Notification. The serializer serializes the public properties of a type, but default interface properties are not implemented as class properties, instead they're implemented through some sort of extension mechanism. See the spec: default interface methods

Add support for virtual extension methods - methods in interfaces with concrete implementations. .

Only when the default interface property is overridden does an instance property actually get added to the implementing concrete type, and thereby become serializable.

For confirmation, if we modify the classes from your fiddle as follows:

public interface INotification
{
    Severity Severity { get; set; }
    string Message { get; set; }

    static string MakeDefaultSeverityName<TNotification>(TNotification notification) where TNotification : INotification => notification?.Severity.ToString().ToLower();

    public string SeverityName => MakeDefaultSeverityName(this);
}

public class Notification : INotification
{
    public Severity Severity { get; set; }
    public string Message { get; set; }
}

public class NotificationWithOverride : Notification
{
    public string SeverityName => INotification.MakeDefaultSeverityName(this);
}

And print out the properties and methods of both types using reflection:

Console.WriteLine("Properties of {0}: {1}", typeof(TNotification).Name, string.Join(", ", typeof(TNotification).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Select(p => p.Name)));
Console.WriteLine("Methods of {0}: {1}", typeof(TNotification).Name, string.Join(", ", typeof(TNotification).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Select(p => p.Name)));

We get the following results for Notification:

Properties of Notification: Severity, Message
Methods of Notification: get_Severity, set_Severity, get_Message, set_Message, GetType, MemberwiseClone, Finalize, ToString, Equals, GetHashCode

And for NotificationWithOverride:

Properties of NotificationWithOverride: SeverityName, Severity, Message
Methods of NotificationWithOverride: get_SeverityName, get_Severity, set_Severity, get_Message, set_Message, GetType, MemberwiseClone, Finalize, ToString, Equals, GetHashCode

Notice there's just no instance property or method corresponding to SeverityName in Notification -- but there is in NotificationWithOverride.  Lacking a property to serialize, the serializer does not output a SeverityName value.

Notes:

System.Text.Json is consistent with other serializers in this respect; both it and Json.NET generate exactly the same JSON:

{"Severity":0,"Message":"Message"} for Notification.

{"SeverityName":"info","Severity":0,"Message":"Message"} for NotificationWithOverride.

With Json.NET it might be possible to create a custom contract resolver that automatically adds in the missing default properties, but System.Text.Json does not have public access to its contract resolver; for confirmation see the question System.Text.Json API is there something like IContractResolver to which the answer is, not currently.

In c# 8.0 it is not possible for to override a default interface method in a concrete class and call the base interface method.  See How can I call the default method instead of the concrete implementation, Making member virtual prevents calling default interface implementation and causes StackOverflowException in C# 8 and Default interface implementations and base() calls for details.

To work around this I added a static interface method to INotification that encapsulates the default logic, then called it from both the default interface instance method and the override class method.

A demo fiddle that shows the above can be found here.


来源: stackexchange

问:
error getting interface index using SIOCGIFINDEX
Hi i am trying to do packet injection using raw sockets, i have a problem in getting the interface index using SIOCGIFINDEX command of the ioctl. I am using ubuntu 12.04 as my OS. Please help the code is:</p>

```<code>int BindRawSocketToInterface(char *device, int rawsock, int protocol)
{
struct sockaddr_ll sll;
struct ifreq ifr;
bzero(&sll, sizeof(sll));
bzero(&ifr, sizeof(ifr));

/* First Get the Interface Index */

strncpy ((char*) ifr.ifr_name, device, IFNAMSIZ);
if ((ioctl(rawsock, SIOCGIFINDEX, &ifr))== -1)
{
printf ("Error getting interface index!\n");
exit(-1);
}

/* Bind our rawsocket to this interface */

sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons(protocol);

if ((bind(rawsock, (struct sockaddr*)&sll,sizeof(sll)))== -1)
{
perror("Error binding raw socket to interface \n");
exit(-1);
}
return 1;
}
</code>```

答:
As a reminder for anyone searching for such a function, i've seen many variants of this function and many of them have the following bug, so its probably a copy paste bug to be warned of:

```<code>strncpy ((char*) ifr.ifr_name, device, IFNAMSIZ);
</code>```

This line has an OBOE (off-by-one error) and an unnecessary cast to char *.

```<code>strncpy (ifr.ifr_name, device, sizeof ifr.ifr_name - 1);
</code>```

should be used instead.

ContentLicense: CC BY-SA 3.0

Body:
Hi i am trying to do packet injection using raw sockets, i have a problem in getting the interface index using SIOCGIFINDEX command of the ioctl. I am using ubuntu 12.04 as my OS. Please help the code is:

int BindRawSocketToInterface(char *device, int rawsock, int protocol)
{
struct sockaddr_ll sll;
struct ifreq ifr;
bzero(&sll, sizeof(sll));
bzero(&ifr, sizeof(ifr));

/* First Get the Interface Index */

strncpy ((char*) ifr.ifr_name, device, IFNAMSIZ);
if ((ioctl(rawsock, SIOCGIFINDEX, &ifr))== -1)
{
printf ("Error getting interface index!\n");
exit(-1);
}

/* Bind our rawsocket to this interface */

sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons(protocol);

if ((bind(rawsock, (struct sockaddr*)&sll,sizeof(sll)))== -1)
{
perror("Error binding raw socket to interface \n");
exit(-1);
}
return 1;
}

Body:
As a reminder for anyone searching for such a function, i've seen many variants of this function and many of them have the following bug, so its probably a copy paste bug to be warned of:

strncpy ((char*) ifr.ifr_name, device, IFNAMSIZ);

This line has an OBOE (off-by-one error) and an unnecessary cast to char *.

strncpy (ifr.ifr_name, device, sizeof ifr.ifr_name - 1);

should be used instead.

ContentLicense: CC BY-SA 4.0


问:
How to change the tab text colour for com.google.android.material.tabs.TabItem
Hello im using this tab layout com.google.android.material.tabs.TabItem and im trying to change the colour of the text from black to white but im not sure how to change tab text colours in general.

xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/gradient"
tools:context=".GuestTab">

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabMode"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    >

    <com.google.android.material.tabs.TabItem
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/Tab1"
        android:text="@string/tab_text_1"
        />

    <com.google.android.material.tabs.TabItem
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/Tab2"
        android:text="@string/tab_text_2"
        />

    <com.google.android.material.tabs.TabItem
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/Tab3"
        android:text="@string/tab_text_3"
        />
</com.google.android.material.tabs.TabLayout>

<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewpager"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
</androidx.viewpager.widget.ViewPager>

</LinearLayout>
</code>```

This is what the text colour looks like at the moment:
tabs

答:
Try something like this.

```<code>  <com.google.android.material.tabs.TabLayout
        app:tabTextColor="@color/white"
</code>```

the tab layout is transparent so you might just mess with the background(of the View Pager) to get your desired effect.

If you want to change the indicator color, try this:

```<code>        app:tabIndicatorColor="@color/white"
</code>```

Body:
Hello im using this tab layout com.google.android.material.tabs.TabItem and im trying to change the colour of the text from black to white but im not sure how to change tab text colours in general.

xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/gradient"
tools:context=".GuestTab">

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabMode"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    >

    <com.google.android.material.tabs.TabItem
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/Tab1"
        android:text="@string/tab_text_1"
        />

    <com.google.android.material.tabs.TabItem
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/Tab2"
        android:text="@string/tab_text_2"
        />

    <com.google.android.material.tabs.TabItem
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/Tab3"
        android:text="@string/tab_text_3"
        />
</com.google.android.material.tabs.TabLayout>

<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewpager"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
</androidx.viewpager.widget.ViewPager>

</LinearLayout>

This is what the text colour looks like at the moment:
tabs

Body:
Try something like this.

  <com.google.android.material.tabs.TabLayout
        app:tabTextColor="@color/white"

the tab layout is transparent so you might just mess with the background(of the View Pager) to get your desired effect.

If you want to change the indicator color, try this:

        app:tabIndicatorColor="@color/white"


问:
How to determine number Saturdays and Sundays comes between two dates in java script
I have requirement as follows
I have two dates i need to find how may saturdays and sundays will come in between

Date1: 02/06/2011

Date2: 02/07/2011

10 days are weekends

Thanks
Srini

答:
Edited to count number of weekend days instead of number of weekends. http://jsfiddle.net/bRgUq/3/</p>

```<code>function CalculateWeekendDays(fromDate, toDate){
    var weekendDayCount = 0;

    while(fromDate < toDate){
        fromDate.setDate(fromDate.getDate() + 1);
        if(fromDate.getDay() === 0 || fromDate.getDay() == 6){
            ++weekendDayCount ;
        }
    }

    return weekendDayCount ;
}

console.log(CalculateWeekendDays(new Date(2011, 6, 2), new Date(2011, 7, 2)));
</code>```

Body:
Edited to count number of weekend days instead of number of weekends. http://jsfiddle.net/bRgUq/3/

function CalculateWeekendDays(fromDate, toDate){
    var weekendDayCount = 0;

    while(fromDate < toDate){
        fromDate.setDate(fromDate.getDate() + 1);
        if(fromDate.getDay() === 0 || fromDate.getDay() == 6){
            ++weekendDayCount ;
        }
    }

    return weekendDayCount ;
}

console.log(CalculateWeekendDays(new Date(2011, 6, 2), new Date(2011, 7, 2)));


问:
Autofill clear background trick stopped working?
I had this piece of CSS implemented to have a transparent autofill background. But something has recently changed that it stopped working?

```<code>@-webkit-keyframes autofill {
    to {
        color: white;
        background: transparent;

    }
}

input:-webkit-autofill {
    -webkit-animation-name: autofill;
    -webkit-animation-fill-mode: both;
}
</code>```

Is there a fix to this?

  form {
  background-color: red;
}

div {
  margin: 15px 0;
  position: relative;
  width: 360px;
  color: red;
  background-color: red;
}

textarea,
select,
input {
  height: 30px;
  line-height: 30px;
  border-radius: 5px;
  border: 1px solid #000;
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  color: red;
  background-color: red;
}

textarea {
  height: 200px;
  color: red;
  background-color: red;
}

textarea+label {
  width: calc(100% - 2px) !important;
  top: 1px;
  box-sizing: border-box;
  border-radius: 5px 5px 0 0;
  text-align: center;
  color: red;
}

textarea:invalid,
select:invalid,
input:invalid {
  box-shadow: none;
  color: red;
}

textarea:invalid+label,
select:invalid+label,
input:invalid+label {
  padding: 0 10px;
  max-width: 360px;
  color: red;
}

textarea:focus+label,
select:focus+label,
input:focus+label,
label {
  position: absolute;
  background: #a4a290;
  max-width: 0;
  padding: 0;
  overflow: hidden;
  left: 1px;
  top: 1px;
  height: 28px;
  font: 14px/28px sans-serif;
  -webkit-transition: all 0.25s;
  -o-transition: all 0.25s;
  transition: all 0.25s;
  color: red;
  border-radius: 5px 0 0 5px;
}

textarea:focus+label {
  height: 0;
  color: red;
  @-webkit-keyframes autofill {
    to {
      color: white;
      background: transparent;
    }
  }
  input:-webkit-autofill {
    -webkit-animation-name: autofill;
    -webkit-animation-fill-mode: both;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <div>
    <input type="text" id="firstname" required/>
    <label for="firstname">First Name</label>
  </div>
  <div>
    <input type="text" id="secondname" required/>
    <label for="secondname">Second Name</label>
  </div>
  <div>
    <select id="type" required>
      <option value=""></option>
      <option value="1">Type 1</option>
      <option value="2">Type 2</option>
      <option value="3">Type 3</option>
      <option value="4">Type 4</option>
    </select>
    <label for="type">Select type...</label>
  </div>
  <div>
    <textarea id="comment" required/></textarea>
    <label for="comment">Comment</label>
  </div>
</form></code>```

答:
https://jsbin.com/zofuqunavo/

```<code>@keyframes autofill {
    to {
        color: white;
        background: green;
    }
}

input:focus {
    animation-name: autofill;
    animation-fill-mode: both;
}
</code>```

Using input:focus selector instead of input:autofill seem fix your issue.

Autofill is a bit unstable feature, the behaviour is changed multiple times and each browser has own implementation.

Body:
I had this piece of CSS implemented to have a transparent autofill background. But something has recently changed that it stopped working?

@-webkit-keyframes autofill {
    to {
        color: white;
        background: transparent;

    }
}

input:-webkit-autofill {
    -webkit-animation-name: autofill;
    -webkit-animation-fill-mode: both;
}

Is there a fix to this?

  form {
  background-color: red;
}

div {
  margin: 15px 0;
  position: relative;
  width: 360px;
  color: red;
  background-color: red;
}

textarea,
select,
input {
  height: 30px;
  line-height: 30px;
  border-radius: 5px;
  border: 1px solid #000;
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  color: red;
  background-color: red;
}

textarea {
  height: 200px;
  color: red;
  background-color: red;
}

textarea+label {
  width: calc(100% - 2px) !important;
  top: 1px;
  box-sizing: border-box;
  border-radius: 5px 5px 0 0;
  text-align: center;
  color: red;
}

textarea:invalid,
select:invalid,
input:invalid {
  box-shadow: none;
  color: red;
}

textarea:invalid+label,
select:invalid+label,
input:invalid+label {
  padding: 0 10px;
  max-width: 360px;
  color: red;
}

textarea:focus+label,
select:focus+label,
input:focus+label,
label {
  position: absolute;
  background: #a4a290;
  max-width: 0;
  padding: 0;
  overflow: hidden;
  left: 1px;
  top: 1px;
  height: 28px;
  font: 14px/28px sans-serif;
  -webkit-transition: all 0.25s;
  -o-transition: all 0.25s;
  transition: all 0.25s;
  color: red;
  border-radius: 5px 0 0 5px;
}

textarea:focus+label {
  height: 0;
  color: red;
  @-webkit-keyframes autofill {
    to {
      color: white;
      background: transparent;
    }
  }
  input:-webkit-autofill {
    -webkit-animation-name: autofill;
    -webkit-animation-fill-mode: both;
  }

<form>

    <input type="text" id="firstname" required/>
    First Name

    <input type="text" id="secondname" required/>
    Second Name

    <select id="type" required>
      <option value=""></option>
      <option value="1">Type 1</option>
      <option value="2">Type 2</option>
      <option value="3">Type 3</option>
      <option value="4">Type 4</option>
    </select>
    Select type...

    <textarea id="comment" required/></textarea>
    Comment

</form>

Body:
https://jsbin.com/zofuqunavo/

@keyframes autofill {
    to {
        color: white;
        background: green;
    }
}

input:focus {
    animation-name: autofill;
    animation-fill-mode: both;
}

Using input:focus selector instead of input:autofill seem fix your issue.

Autofill is a bit unstable feature, the behaviour is changed multiple times and each browser has own implementation.


问:
The canvas has been tainted by cross-origin data with computedStyleMap().get("background-image")

background-image with this

```

<pre class="lang-css prettyprint-override"><code>#img3 {
  background-image: url("../icons/we-flow.png");
}
</code>```

var img = img3.computedStyleMap().get("background-image");
//img=img1;
var canvas=document.createElement('canvas');
img.crossOrigin="Anonymous";
var ctx=canvas.getContext('2d');
try {
  ctx.drawImage(img, 0, 0);
  var data=ctx.getImageData(0, 0, canvas.width, canvas.height).data;
}catch (error) {
  console.log('refresh page will get this', img.toString(), {error, img});
}
```

<p>run this code with chrome 83, first time load the code, everything is ok, but when I refresh the page in browser, I got the console.log: </p>

```DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
```

why and how can i fix it?

答:
In the current Chromium implementation, CSSImageValue::WouldTaintOrigin is set to return true, always.

https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/css/cssom/css_style_image_value.h#L32

```<code> bool WouldTaintOrigin() const final { return true; }
</code>```

If you are able to get the canvas data after you painted such an image source on the canvas, then please file a bug to chromium's team right away as it would be a security issue. (But I can't reproduce this on my own Chrome 83 nor any other branches).

Note that currently HTML specs still don't include CSSImageValue as a potential source, but the plan is that it will fall in the HTMLOrSVGImageElement branch of is-origin-clean algo. So CSSImageValue should only taint the canvas in case of cross-origin request, but given the youth of the APIs and the difficulty it would be to store that information in all these often changing interfaces, implementers just erred on the side of safety by simply marking it as unsafe all the time, as they are allowed to do with any source they consider unsafe.

Body:
background-image with this

#img3 {
  background-image: url("../icons/we-flow.png");
}

var img = img3.computedStyleMap().get("background-image");
//img=img1;
var canvas=document.createElement('canvas');
img.crossOrigin="Anonymous";
var ctx=canvas.getContext('2d');
try {
  ctx.drawImage(img, 0, 0);
  var data=ctx.getImageData(0, 0, canvas.width, canvas.height).data;
}catch (error) {
  console.log('refresh page will get this', img.toString(), {error, img});
}

run this code with chrome 83, first time load the code, everything is ok, but when I refresh the page in browser, I got the console.log:

DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

why and how can i fix it?

Body:
In the current Chromium implementation, CSSImageValue::WouldTaintOrigin is set to return true, always.

https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/css/cssom/css_style_image_value.h#L32

 bool WouldTaintOrigin() const final { return true; }

If you are able to get the canvas data after you painted such an image source on the canvas, then please file a bug to chromium's team right away as it would be a security issue. (But I can't reproduce this on my own Chrome 83 nor any other branches).

Note that currently HTML specs still don't include CSSImageValue as a potential source, but the plan is that it will fall in the HTMLOrSVGImageElement branch of is-origin-clean algo. So CSSImageValue should only taint the canvas in case of cross-origin request, but given the youth of the APIs and the difficulty it would be to store that information in all these often changing interfaces, implementers just erred on the side of safety by simply marking it as unsafe all the time, as they are allowed to do with any source they consider unsafe.


问:
Unselecting an item on a SwiftUI list crashes the app
I’m having an issue with SwiftUI with optional bindings, basically it’s a List on macOS, where I add a DetailView once an item is selected, if not selected just add a Text.

When I open the app it’s fine, the Text appears, then I add some items and select it, also works fine, DetailView appears, but once I click outside the table, unselecting it, it crashes. Even tough I have a conditional checking for nil, that’s why it works the first time.

I guess the DetailView is keeping a reference to the selectedItem and crashing once it’s set to nil, but I thought the entire body should be refreshed once a State property is changed, which would remove the previous DetailView from memory and not call a new one, right?

Here's the code:

import SwiftUI

struct DetailView: View {
    @Binding var text: String

    var body: some View {
        TextField("123", text: self.$text)
    }
}

struct ContentView: View {
    @State var text = ""
    @State var items = [String]()
    @State var selectedItem: String? = nil

    var body: some View {
        VStack {
            HStack {
                VStack(alignment: .leading, spacing: 0) {
                    List(selection: $selectedItem) {
                        ForEach(items, id: \.self) { item in
                            Text(item)
                        }
                    }
                    HStack(spacing: 0) {
                        Button(action: {
                            self.items.append(UUID().uuidString)
                        }, label: {
                            Text("Add")
                        })
                        Button(action: {
                            if let item = self.selectedItem {
                                self.items.remove(at: self.items.firstIndex(of: item)!)
                            }
                            self.selectedItem = nil
                        }, label: {
                            Text("Remove")
                        }).disabled(selectedItem == nil)
                    }
                }
                if selectedItem != nil {
                    DetailView(text: Binding($selectedItem)!)
                } else {
                    Text("Add an item")
                }
            }
            .tabItem {
                Text("Test")
            }
        }.frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

```

答:
I guess the DetailView is keeping a reference to the selectedItem and
  crashing once it’s set to nil, but I thought the entire body should be
  refreshed once a State property is changed, which would remove the
  previous DetailView from memory and not call a new one, right?

The order of update is not defined, so I would answer no on above.

Here is a solution. Tested with Xcode 11.4 / iOS 13.4

```<code>if selectedItem != nil {
    DetailView(text: Binding(get: {self.selectedItem ?? ""},
                             set: {self.selectedItem = $0}))
} else {
    Text("Add an item")
}
</code>```

Body:
I guess the DetailView is keeping a reference to the selectedItem and
  crashing once it’s set to nil, but I thought the entire body should be
  refreshed once a State property is changed, which would remove the
  previous DetailView from memory and not call a new one, right?

The order of update is not defined, so I would answer no on above.

Here is a solution. Tested with Xcode 11.4 / iOS 13.4

if selectedItem != nil {
    DetailView(text: Binding(get: {self.selectedItem ?? ""},
                             set: {self.selectedItem = $0}))
} else {
    Text("Add an item")
}


问:
How to setup a time series multiplot configuration with matplolib
I'm trying to make two subplots on the same figure with several sets of time series. In the representation below, I would like that the upper sub-plot has only the series called "original", and the rest below. However, my code groups them all in the subplot below. You can see how it looks now:

The implemented code is the following one:

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.holtwinters import ExponentialSmoothing
# Data loading

data = pd.read_csv('setpoints.csv', parse_dates=['date'], index_col=['date'])

df_data = pd.DataFrame(data, columns=['Data'])

df_matric['Data'].index.freq = 'MS'
train, test = df_data['Data'], df_data['Data']
model = ExponentialSmoothing(train, trend='mul', seasonal='add', seasonal_periods=12).fit()
period = ['Jan-12', 'Dec-14']
pred = model.predict(start=period[0], end=period[1])
print(pred)

df_data['Data'].plot(label='Train')
test.plot(label='Test')
pred.plot(label='Holt-Winters')
plt.legend(loc='best')
plt.show()

fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Submissions data')
ax1.set_ylim(0, 300000)
ax1.set_ylabel('Submissions')
ax1 = df_data['Data'].plot(label='Original', color = 'blue')
ax1.legend()
ax2 = df_data['Data'].plot(label='Train')
ax2 = test.plot(label='Test')
ax2 = pred.plot(label='Holt-Winters')
ax2.set_xlabel('Date')
ax2.set_ylabel('Submissions')
ax2.legend()
plt.show()
</code>```

And the data set is the following one:

```<code>date,Data

Jan-12,153046

Feb-12,161874

Mar-12,226134

Apr-12,171871

May-12,191416

Jun-12,230926

Jul-12,147518

Aug-12,107449

Sep-12,170645

Oct-12,176492

Nov-12,180005

Dec-12,193372

Jan-13,156846

Feb-13,168893

Mar-13,231103

Apr-13,187390

May-13,191702

Jun-13,252216

Jul-13,175392

Aug-13,150390

Sep-13,148750

Oct-13,173798

Nov-13,171611

Dec-13,165390

Jan-14,155079

Feb-14,172438

Mar-14,225818

Apr-14,188195

May-14,193948

Jun-14,230964

Jul-14,172225

Aug-14,129257

Sep-14,173443

Oct-14,188987

Nov-14,172731

Dec-14,211194
</code>```

Does anyone now how can I solve it? Or a better way to do it

答:
I believe the problem with your code is that you are calling plt.show() twice in your python session. I would suggest you call it once at the end of your script. I think it will solve your problem.

The way plt.show() work is that it looks for all the currently active figure objects, and opens interactive windows that display your results. Calling it multiple times one session can lead to unpredictable behaviour and it mostly should be avoided.

Body:
I'm trying to make two subplots on the same figure with several sets of time series. In the representation below, I would like that the upper sub-plot has only the series called "original", and the rest below. However, my code groups them all in the subplot below. You can see how it looks now:

The implemented code is the following one:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.holtwinters import ExponentialSmoothing
# Data loading

data = pd.read_csv('setpoints.csv', parse_dates=['date'], index_col=['date'])

df_data = pd.DataFrame(data, columns=['Data'])

df_matric['Data'].index.freq = 'MS'
train, test = df_data['Data'], df_data['Data']
model = ExponentialSmoothing(train, trend='mul', seasonal='add', seasonal_periods=12).fit()
period = ['Jan-12', 'Dec-14']
pred = model.predict(start=period[0], end=period[1])
print(pred)

df_data['Data'].plot(label='Train')
test.plot(label='Test')
pred.plot(label='Holt-Winters')
plt.legend(loc='best')
plt.show()

fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Submissions data')
ax1.set_ylim(0, 300000)
ax1.set_ylabel('Submissions')
ax1 = df_data['Data'].plot(label='Original', color = 'blue')
ax1.legend()
ax2 = df_data['Data'].plot(label='Train')
ax2 = test.plot(label='Test')
ax2 = pred.plot(label='Holt-Winters')
ax2.set_xlabel('Date')
ax2.set_ylabel('Submissions')
ax2.legend()
plt.show()

And the data set is the following one:

date,Data

Jan-12,153046

Feb-12,161874

Mar-12,226134

Apr-12,171871

May-12,191416

Jun-12,230926

Jul-12,147518

Aug-12,107449

Sep-12,170645

Oct-12,176492

Nov-12,180005

Dec-12,193372

Jan-13,156846

Feb-13,168893

Mar-13,231103

Apr-13,187390

May-13,191702

Jun-13,252216

Jul-13,175392

Aug-13,150390

Sep-13,148750

Oct-13,173798

Nov-13,171611

Dec-13,165390

Jan-14,155079

Feb-14,172438

Mar-14,225818

Apr-14,188195

May-14,193948

Jun-14,230964

Jul-14,172225

Aug-14,129257

Sep-14,173443

Oct-14,188987

Nov-14,172731

Dec-14,211194

Does anyone now how can I solve it? Or a better way to do it


问:
C# Entity Framework Inheritance: Automatic Mapping a Property To Children Property
I was wondering if we can automatically map a property into children property when retrieving from database.

Example :

```<code>public class Account
{
    [Key]
    [Index(IsUnique = true)]
    public Guid ID { get; set; } = Guid.NewGuid();

    [Required]
    [Index(IsUnique = true)]
    [StringLength(50)]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }

    public string Hash { get; set; }

    public ICollection<Role> Roles { get; set; }

    [ForeignKey("AccountProfile")]
    public Guid? AccountProfileId { get; set; }

    public virtual AccountProfile AccountProfile { get; set; }
}

public class AccountProfile
{
    [Key]
    [Index(IsUnique = true)]
    public Guid ID { get; set; } = Guid.NewGuid();

    [Required]
    public string Name { get; set; }

    [Required]
    public string Phone { get; set; }

    public ICollection<AccountAddress> Addresses { get; set; }
}
</code>```

And then I make a view model:

```<code>[NotMapped]
public class AccountVM : Account
{
    public string Name { get; set; } //Map this into AccountProfile.Name
}
</code>```

I want to auto map the Name into base.AccountProfile.Name when retrieving the data from database:

```<code>List<AccountVM> models = db.Accounts.Include(m => m.Roles).Include(m => m.AccountProfile).ToList();
</code>```

This code will not work because I need to do Select(m => new AccountVM() {...}) which is not code efficient, because I have to assign each of the properties.

So is there a way to do this?

Updated

So I just figurred out a little change in my view model into:

```<code>[NotMapped]
public class AccountVM : Account
{
    public string Name { get { return base.AccountProfile.Name; } set { base.AccountProfile.Name = value; } }
}
</code>```

and my retriever:

```<code>List<AccountVM> models = db.Accounts.Include(m => m.Roles).Include(m => m.AccountProfile).Select(m => m as AccountVM).ToList();
</code>```

Then another error arise:

The 'TypeAs' expression with an input of type 'Yountrep.Models.Account' and a check of type 'Yountrep.ViewModels.AccountVM' is not supported. Only entity types and complex types are supported in LINQ to Entities queries.

I guess the problem is now how to typecast it into AccountVM

答:
Your view model should not be inheriting from an entity model.  You can create your view model like this to include any relational objects.

```<code>public class AccountVM
{
    public string Name { get; set; }
    public AccountProfile Profile { get; set; }

    public class AccountProfile
    {
        public string Name { get; set; }
    }
}
</code>```

You can than manually copy over the properties when building your LINQ query:

```<code>List<AccountVM> vm = db.Accounts.Select(a =>
{
    new AccountVM {
        Name= a.Name,
        Profile = new AccountProfile {
            Name = a.AccountProfile.Name
        }
    }
}).ToList();
</code>```

Another alternative is to use AutoMapper.  I use AutoMapper for several of my projects, and it reduces the need to have to manually translate every field.

AutoMapper

If you want to flatten properties:

```<code>    public class AccountVM
    {
        public string Name { get; set; }
        public string ProfileName { get; set; }
    }

List<AccountVM> vm = db.Accounts.Select(a =>
{
    new AccountVM {
        Name= a.Name,
        ProfileName = (a.AccountProfile == null) ? "" : a.AccountProfile.Name
       }
    }
}).ToList();
</code>```

I also added a ternary expression to check for null.  This will avoid an exception error if profile does not exist.

Body:
I was wondering if we can automatically map a property into children property when retrieving from database.

Example :

public class Account
{
    [Key]
    [Index(IsUnique = true)]
    public Guid ID { get; set; } = Guid.NewGuid();

    [Required]
    [Index(IsUnique = true)]
    [StringLength(50)]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }

    public string Hash { get; set; }

    public ICollection<Role> Roles { get; set; }

    [ForeignKey("AccountProfile")]
    public Guid? AccountProfileId { get; set; }

    public virtual AccountProfile AccountProfile { get; set; }
}

public class AccountProfile
{
    [Key]
    [Index(IsUnique = true)]
    public Guid ID { get; set; } = Guid.NewGuid();

    [Required]
    public string Name { get; set; }

    [Required]
    public string Phone { get; set; }

    public ICollection<AccountAddress> Addresses { get; set; }
}

And then I make a view model:

[NotMapped]
public class AccountVM : Account
{
    public string Name { get; set; } //Map this into AccountProfile.Name
}

I want to auto map the Name into base.AccountProfile.Name when retrieving the data from database:

List<AccountVM> models = db.Accounts.Include(m => m.Roles).Include(m => m.AccountProfile).ToList();

This code will not work because I need to do Select(m => new AccountVM() {...}) which is not code efficient, because I have to assign each of the properties.

So is there a way to do this?

Updated

So I just figurred out a little change in my view model into:

[NotMapped]
public class AccountVM : Account
{
    public string Name { get { return base.AccountProfile.Name; } set { base.AccountProfile.Name = value; } }
}

and my retriever:

List<AccountVM> models = db.Accounts.Include(m => m.Roles).Include(m => m.AccountProfile).Select(m => m as AccountVM).ToList();

Then another error arise:

The 'TypeAs' expression with an input of type 'Yountrep.Models.Account' and a check of type 'Yountrep.ViewModels.AccountVM' is not supported. Only entity types and complex types are supported in LINQ to Entities queries.

I guess the problem is now how to typecast it into AccountVM

Body:
Your view model should not be inheriting from an entity model.  You can create your view model like this to include any relational objects.

public class AccountVM
{
    public string Name { get; set; }
    public AccountProfile Profile { get; set; }

    public class AccountProfile
    {
        public string Name { get; set; }
    }
}

You can than manually copy over the properties when building your LINQ query:

List<AccountVM> vm = db.Accounts.Select(a =>
{
    new AccountVM {
        Name= a.Name,
        Profile = new AccountProfile {
            Name = a.AccountProfile.Name
        }
    }
}).ToList();

Another alternative is to use AutoMapper.  I use AutoMapper for several of my projects, and it reduces the need to have to manually translate every field.

AutoMapper

If you want to flatten properties:

    public class AccountVM
    {
        public string Name { get; set; }
        public string ProfileName { get; set; }
    }

List<AccountVM> vm = db.Accounts.Select(a =>
{
    new AccountVM {
        Name= a.Name,
        ProfileName = (a.AccountProfile == null) ? "" : a.AccountProfile.Name
       }
    }
}).ToList();

I also added a ternary expression to check for null.  This will avoid an exception error if profile does not exist.


问:
Updating Database Value in windows forms
I am trying to do a function to update a value in a SQL database, this is my table

This is the function

```<code>private void UpdateGanToDB(float entrada, string Id)
        {
            string string_entrada = entrada.ToString();
            string conString = Properties.Settings.Default.LocalDataBaseConnectionString;
            string command_string = "UPDATE Gan SET Ganan = @GetGan WHERE Id = @GetId";
            SqlConnection connection = new SqlConnection(conString);
            SqlCommand cmd = new SqlCommand(command_string, connection);
            cmd.Parameters.AddWithValue("@GetGan", string_entrada);
            cmd.Parameters.AddWithValue("@GetId", Id);
            try
            {
                connection.Open();
                int row = cmd.ExecuteNonQuery();
                if (row > 0) {
                    MessageBox.Show("Upgrade successful");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                connection.Close();
            }
        }
</code>```

I am getting the message "upgrade successful" but when I check the database I can't see the changes. When I run the text in the command_string with known values I can see the changes but not with my function

Edit:
I added this code to the code above

```<code>int row = cmd.ExecuteNonQuery();
                if (row > 0) {
                    SqlCommand command = new SqlCommand("SELECT * FROM Gan ", connection);
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    System.Data.DataTable dataTable = new System.Data.DataTable();
                    adapter.Fill(dataTable);
                    MessageBox.Show(dataTable.Rows[0]["Ganan"].ToString());
                }
</code>```

To see if it is updating the value and I get the excepted 200 (Original value was 0) But When I close the application and see the values in the local database I see the original value 0 I don't know why the update is not saving

EDIT2:
I found another post with a work around for this problem: Can I commit changes to actual database while debugging C# in Visual Studio?

答:
I think your code is correct and there is no problem

If you created database via Add\NewItem\Service-Base Database

I'm not sure, but I think After running your project, one copy of your original database will be included in the debug folder in your project and the update operation and also other operations run on that, not your original database

so, if you want to see a result, you should connect to that via View\ServerExplorer

meantime, after Change your Code and rebuild your Project, your debug database will be deleted and again one copy of your original database will be included in the debug folder

Body:
I am trying to do a function to update a value in a SQL database, this is my table

This is the function

private void UpdateGanToDB(float entrada, string Id)
        {
            string string_entrada = entrada.ToString();
            string conString = Properties.Settings.Default.LocalDataBaseConnectionString;
            string command_string = "UPDATE Gan SET Ganan = @GetGan WHERE Id = @GetId";
            SqlConnection connection = new SqlConnection(conString);
            SqlCommand cmd = new SqlCommand(command_string, connection);
            cmd.Parameters.AddWithValue("@GetGan", string_entrada);
            cmd.Parameters.AddWithValue("@GetId", Id);
            try
            {
                connection.Open();
                int row = cmd.ExecuteNonQuery();
                if (row > 0) {
                    MessageBox.Show("Upgrade successful");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                connection.Close();
            }
        }

I am getting the message "upgrade successful" but when I check the database I can't see the changes. When I run the text in the command_string with known values I can see the changes but not with my function

Edit:
I added this code to the code above

int row = cmd.ExecuteNonQuery();
                if (row > 0) {
                    SqlCommand command = new SqlCommand("SELECT * FROM Gan ", connection);
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    System.Data.DataTable dataTable = new System.Data.DataTable();
                    adapter.Fill(dataTable);
                    MessageBox.Show(dataTable.Rows[0]["Ganan"].ToString());
                }

To see if it is updating the value and I get the excepted 200 (Original value was 0) But When I close the application and see the values in the local database I see the original value 0 I don't know why the update is not saving

EDIT2:
I found another post with a work around for this problem: Can I commit changes to actual database while debugging C# in Visual Studio?


问:
EC2 API Error validating access credential
I installed the ec2 api following the amazon guide. I setted up the access id and secret as environment variable.

Here it is my profile:

export AWS_ACCESS_KEY=XXXXX

export AWS_SECRET_KEY=XXXXXX

export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre

export EC2_HOME=/usr/local/ec2/ec2-api-tools-1.7.1.0

export PATH=$PATH:$EC2_HOME/bin

Everythings looks configured as asked, but i can't connect to aws.

Here the output of the command ec2-describe-regions in verbose mode:

```<code>Client.AuthFailure: AWS was not able to validate the provided access credentials
ubuntu@ip:~$ ec2dre -v
Setting User-Agent to [ec2-api-tools 1.7.1.0]
2014-07-14 19:10:34,898 [main] DEBUG org.apache.http.wire  - >> "POST / HTTP/1.1[\r][\n]"
2014-07-14 19:10:34,912 [main] DEBUG org.apache.http.wire  - >> "Host: ec2.amazonaws.com[\r][\n]"
2014-07-14 19:10:34,912 [main] DEBUG org.apache.http.wire  - >> "X-Amz-Date: 20140714T191033Z[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "Authorization: AWS4-HMAC-SHA256 Credential=AKIAIT64V5MH2HHF5QZQ/20140714/us-east-1/ec2/aws4_request, SignedHeaders=host;user-agent;x-amz-date, Signature=06920c7d37a24d8244feb630d87310238886294d3ae2ab40f68a362a799d9a62[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "User-Agent: ec2-api-tools 1.7.1.0, aws-sdk-java/unknown-version Linux/3.2.0-36-virtual OpenJDK_64-Bit_Server_VM/24.51-b03[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "Content-Type: application/x-www-form-urlencoded; charset=utf-8[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "Content-Length: 41[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "Connection: Keep-Alive[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "[\r][\n]"
2014-07-14 19:10:34,914 [main] DEBUG org.apache.http.wire  - >> "Action=DescribeRegions&Version=2014-06-15"
2014-07-14 19:10:34,984 [main] DEBUG org.apache.http.wire  - << "HTTP/1.1 401 Unauthorized[\r][\n]"
2014-07-14 19:10:35,002 [main] DEBUG org.apache.http.wire  - << "Transfer-Encoding: chunked[\r][\n]"
2014-07-14 19:10:35,003 [main] DEBUG org.apache.http.wire  - << "Date: Mon, 14 Jul 2014 19:18:34 GMT[\r][\n]"
2014-07-14 19:10:35,003 [main] DEBUG org.apache.http.wire  - << "Server: AmazonEC2[\r][\n]"
2014-07-14 19:10:35,010 [main] DEBUG org.apache.http.wire  - << "[\r][\n]"
2014-07-14 19:10:35,225 [main] DEBUG org.apache.http.wire  - << "fe[\r][\n]"
2014-07-14 19:10:35,225 [main] DEBUG org.apache.http.wire  - << "<?xml version="1.0" encoding="UTF-8"?>[\n]"
2014-07-14 19:10:35,225 [main] DEBUG org.apache.http.wire  - << "<Response><Errors><Error><Code>AuthFailure</Code><Message>AWS was not able to validate the provided access credentials</Message></Error></Errors><RequestID>cd2b128b-3d70-425b-a8a7-4856fd9a6b99</RequestID></Response>"
2014-07-14 19:10:35,278 [main] DEBUG org.apache.http.wire  - << "[\r][\n]"
2014-07-14 19:10:35,279 [main] DEBUG org.apache.http.wire  - << "0[\r][\n]"
2014-07-14 19:10:35,279 [main] DEBUG org.apache.http.wire  - << "[\r][\n]"
Client.AuthFailure: AWS was not able to validate the provided access credentials
Request ID: cd2b128b-3d70-425b-a8a7-4856fd9a6b99
</code>```

答:
For CentOS

```<code># install ntpdate
sudo yum install ntpdate

# install policy kit
sudo yum install polkit

# start ntpd service
sudo systemctl start ntpd.service

sudo ntpdate 0.amazon.pool.ntp.org

</code>```

You can also reconfigure aws credential again

```<code>aws configure
</code>```

Body:
I installed the ec2 api following the amazon guide. I setted up the access id and secret as environment variable.

Here it is my profile:

export AWS_ACCESS_KEY=XXXXX

export AWS_SECRET_KEY=XXXXXX

export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre

export EC2_HOME=/usr/local/ec2/ec2-api-tools-1.7.1.0

export PATH=$PATH:$EC2_HOME/bin

Everythings looks configured as asked, but i can't connect to aws.

Here the output of the command ec2-describe-regions in verbose mode:

Client.AuthFailure: AWS was not able to validate the provided access credentials
ubuntu@ip:~$ ec2dre -v
Setting User-Agent to [ec2-api-tools 1.7.1.0]
2014-07-14 19:10:34,898 [main] DEBUG org.apache.http.wire  - >> "POST / HTTP/1.1[\r][\n]"
2014-07-14 19:10:34,912 [main] DEBUG org.apache.http.wire  - >> "Host: ec2.amazonaws.com[\r][\n]"
2014-07-14 19:10:34,912 [main] DEBUG org.apache.http.wire  - >> "X-Amz-Date: 20140714T191033Z[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "Authorization: AWS4-HMAC-SHA256 Credential=AKIAIT64V5MH2HHF5QZQ/20140714/us-east-1/ec2/aws4_request, SignedHeaders=host;user-agent;x-amz-date, Signature=06920c7d37a24d8244feb630d87310238886294d3ae2ab40f68a362a799d9a62[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "User-Agent: ec2-api-tools 1.7.1.0, aws-sdk-java/unknown-version Linux/3.2.0-36-virtual OpenJDK_64-Bit_Server_VM/24.51-b03[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "Content-Type: application/x-www-form-urlencoded; charset=utf-8[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "Content-Length: 41[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "Connection: Keep-Alive[\r][\n]"
2014-07-14 19:10:34,913 [main] DEBUG org.apache.http.wire  - >> "[\r][\n]"
2014-07-14 19:10:34,914 [main] DEBUG org.apache.http.wire  - >> "Action=DescribeRegions&Version=2014-06-15"
2014-07-14 19:10:34,984 [main] DEBUG org.apache.http.wire  - << "HTTP/1.1 401 Unauthorized[\r][\n]"
2014-07-14 19:10:35,002 [main] DEBUG org.apache.http.wire  - << "Transfer-Encoding: chunked[\r][\n]"
2014-07-14 19:10:35,003 [main] DEBUG org.apache.http.wire  - << "Date: Mon, 14 Jul 2014 19:18:34 GMT[\r][\n]"
2014-07-14 19:10:35,003 [main] DEBUG org.apache.http.wire  - << "Server: AmazonEC2[\r][\n]"
2014-07-14 19:10:35,010 [main] DEBUG org.apache.http.wire  - << "[\r][\n]"
2014-07-14 19:10:35,225 [main] DEBUG org.apache.http.wire  - << "fe[\r][\n]"
2014-07-14 19:10:35,225 [main] DEBUG org.apache.http.wire  - << "<?xml version="1.0" encoding="UTF-8"?>[\n]"
2014-07-14 19:10:35,225 [main] DEBUG org.apache.http.wire  - << "<Response><Errors><Error>AuthFailure<Message>AWS was not able to validate the provided access credentials</Message></Error></Errors><RequestID>cd2b128b-3d70-425b-a8a7-4856fd9a6b99</RequestID></Response>"
2014-07-14 19:10:35,278 [main] DEBUG org.apache.http.wire  - << "[\r][\n]"
2014-07-14 19:10:35,279 [main] DEBUG org.apache.http.wire  - << "0[\r][\n]"
2014-07-14 19:10:35,279 [main] DEBUG org.apache.http.wire  - << "[\r][\n]"
Client.AuthFailure: AWS was not able to validate the provided access credentials
Request ID: cd2b128b-3d70-425b-a8a7-4856fd9a6b99

Body:
For CentOS

# install ntpdate
sudo yum install ntpdate

# install policy kit
sudo yum install polkit

# start ntpd service
sudo systemctl start ntpd.service

sudo ntpdate 0.amazon.pool.ntp.org

You can also reconfigure aws credential again

aws configure


问:
Python storing and plotting data
I am trying to categorize a csv data with 600000 rows and 2 columns into a few types of data. Is there any possible way that I could apply something like array in C so that I could use ply.scatter(x,y) , where x and y correspond to columns of each type, to plot them out?

The way I am currently using is to store them into different files and then open it with plt(float(row[0]), float(row[1])).

答:
check csv package in python standard library:
https://docs.python.org/3/library/csv.html

my sketched answer will be like

import csv
x, y = [], []

with open('your.csv', newline='') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        x.append(row[0])
        y.append(row[1])
```

Title: Python storing and plotting data


问:
How to use squid proxy server to modify html page before sending to client
I am looking to setup a proxy server and I want to run some python script(or any other language) to filter out some content on the html pages, the client requests through proxy server.

Is there a way to do that?

Thanks

答: Take a look at ICAP and ECAP: http://wiki.squid-cache.org/Features/ICAP and http://wiki.squid-cache.org/Features/eCAP. They accomplish the same goal - ICAP is via an external helper daemon (which you'd need to code on your own) and ECAP uses plugins.</p>


问:
python code number_list = [1, 239, 949, 0, 84, 0, 1] output: True number_list = [1, 239, 949, 0, 84, 0, 13] output: False
This function should return true if the value at the beginning and the end of the list are equal. False otherwise.

Example:

number_list = [1, 239, 949, 0, 84, 0, 1]
```

<p>output:</p>

<pre class="lang-py prettyprint-override"><code>True
</code>```

number_list = [1, 239, 949, 0, 84, 0, 13]
```

<p>output:</p>

<pre class="lang-py prettyprint-override"><code>False
</code>```

答:
@Ritika Gupta answered this question
But you can make it shorter by using

def check(l):
    return l[0] == l[-1]
```

Body:
This function should return true if the value at the beginning and the end of the list are equal. False otherwise.

Example:

number_list = [1, 239, 949, 0, 84, 0, 1]

output:

True

number_list = [1, 239, 949, 0, 84, 0, 13]

output:

False


问:
Unexpected Addition Behaviour of two Uint64
Problem

In the code below, I have a couple of Go-routines and the one I'm facing issues with is the "calculateMemoryUsage()" Go-routine, where the avg memory usage is to be calculated every half a second. For some reason, the total keeps giving me weird values. Here's the Print Logs:

```<code>Memory Usage: 162224
Average: 162224
Total: 162224
Iteration Count: 1

Memory Usage: 181200
Average: 171712
Total: 343424
Iteration Count: 2

Memory Usage: 187864
Average: 119858
Total: 359576
Iteration Count: 3
</code>```

As seen, from the third iteration, the average messes up because the total doesn't add right. After debugging, I see that the memory usage is read fine, but the total seems to give me issues. I suspected the GC, but during this problem the LastGC value is set to 0, meaning no GC is performed. Any suggestions would be highly appreciated! :)

Code

```<code>func main() {
    db, err := sql.Open("mysql", "<credentials_removed>@@tcp(127.0.0.1:3306)/rts")

    err = db.Ping()
    if err != nil {
        panic(err.Error()) // proper error handling instead of panic in your app
    }

    showStocksChannel := make(chan bool)
    showBestPerformingChannel := make(chan bool)

    go calculateMemoryUsage()
    go showStocks(showStocksChannel, db)
    go changeStockPrices(showStocksChannel, showBestPerformingChannel, db)
    go displayBestPerformingStocks(showBestPerformingChannel, db)

    showStocksChannel <- true

    select{}
}
func calculateMemoryUsage() {
    var averageMemoryUsage uint64 = 0
    var iterations uint64 = 0
    var usage uint64 = 0
    var total uint64 = 0

    for iterations <= 200 {
        var memoryStats runtime.MemStats
        runtime.ReadMemStats(&memoryStats)

        iterations = iterations + 1

        usage = memoryStats.Alloc
        total = (averageMemoryUsage + usage)
        averageMemoryUsage = total / iterations

        fmt.Printf("\nMemory Usage: %v\nAverage: %v\nTotal: %v\nIteration Count: %v\n\n", usage, averageMemoryUsage, total, iterations)

        time.Sleep(time.Millisecond * 1000)
        //fmt.Printf("\nLast GC: %v\nNext GC: %v\n\n", memoryStats.LastGC, memoryStats.NextGC)

    }

    fmt.Printf("\nAverage Memory Usage: %v bytes\n\n", averageMemoryUsage)
}
</code>```

答:
this line

```<code>total = (averageMemoryUsage + usage)
</code>```

should be

```<code>total = (total + usage)
</code>```

Body:
Problem

In the code below, I have a couple of Go-routines and the one I'm facing issues with is the "calculateMemoryUsage()" Go-routine, where the avg memory usage is to be calculated every half a second. For some reason, the total keeps giving me weird values. Here's the Print Logs:

Memory Usage: 162224
Average: 162224
Total: 162224
Iteration Count: 1

Memory Usage: 181200
Average: 171712
Total: 343424
Iteration Count: 2

Memory Usage: 187864
Average: 119858
Total: 359576
Iteration Count: 3

As seen, from the third iteration, the average messes up because the total doesn't add right. After debugging, I see that the memory usage is read fine, but the total seems to give me issues. I suspected the GC, but during this problem the LastGC value is set to 0, meaning no GC is performed. Any suggestions would be highly appreciated! :)

Code

func main() {
    db, err := sql.Open("mysql", "<credentials_removed>@@tcp(127.0.0.1:3306)/rts")

    err = db.Ping()
    if err != nil {
        panic(err.Error()) // proper error handling instead of panic in your app
    }

    showStocksChannel := make(chan bool)
    showBestPerformingChannel := make(chan bool)

    go calculateMemoryUsage()
    go showStocks(showStocksChannel, db)
    go changeStockPrices(showStocksChannel, showBestPerformingChannel, db)
    go displayBestPerformingStocks(showBestPerformingChannel, db)

    showStocksChannel <- true

    select{}
}
func calculateMemoryUsage() {
    var averageMemoryUsage uint64 = 0
    var iterations uint64 = 0
    var usage uint64 = 0
    var total uint64 = 0

    for iterations <= 200 {
        var memoryStats runtime.MemStats
        runtime.ReadMemStats(&memoryStats)

        iterations = iterations + 1

        usage = memoryStats.Alloc
        total = (averageMemoryUsage + usage)
        averageMemoryUsage = total / iterations

        fmt.Printf("\nMemory Usage: %v\nAverage: %v\nTotal: %v\nIteration Count: %v\n\n", usage, averageMemoryUsage, total, iterations)

        time.Sleep(time.Millisecond * 1000)
        //fmt.Printf("\nLast GC: %v\nNext GC: %v\n\n", memoryStats.LastGC, memoryStats.NextGC)

    }

    fmt.Printf("\nAverage Memory Usage: %v bytes\n\n", averageMemoryUsage)
}

Body:
this line

total = (averageMemoryUsage + usage)

should be

total = (total + usage)


问:
Mongodb: searching embedded documents by the '_id' field
If I have a data with a structure like this as a single document in a collection:

```<code>{
_id: ObjectId("firstid"),
"name": "sublimetest",
"child": {
        _id: ObjectId("childid"),
        "name": "materialtheme"
    }
}
</code>```

is there a way to search for the embedded document by the id "childid" ?
because mongo doesn't index the _id fields of embedded documents (correct me if I am wrong here),
as this query doesn't work :
db.collection.find({_id:"childid"});

Also please suggest me if there is any other document database that would be suitable for this kind of retreiving data that is structured as a tree, where the requirement is to :

query children without having to issue joins

find any node in the tree as fast as you would find the root node, as if all these nodes were stored as separate documents in a collection.

Why this is not a duplicate of question(s) suggested :
the potential-duplicate-question, queries document by using dot notation. But what if the document is nested 7 levels deep ? In such case it would not be suitable to write a query using dot notation. what I want is that, all documents, whether top level, or nested, if they have the _id field, should be in the bucket of _id indexes, so that when you search db.collection.find({_id: "asdf"}), it should take into account documents that are nested too that have the _id field matching "asdf". In short, it should be as if the inner document weren't nested, but present parallel to the outer one.

答:
You can use the dot notation:</p>

```<code>db.posts.find({"child._id": "childid"})
</code>```

Body:
If I have a data with a structure like this as a single document in a collection:

{
_id: ObjectId("firstid"),
"name": "sublimetest",
"child": {
        _id: ObjectId("childid"),
        "name": "materialtheme"
    }
}

is there a way to search for the embedded document by the id "childid" ?
because mongo doesn't index the _id fields of embedded documents (correct me if I am wrong here),
as this query doesn't work :
db.collection.find({_id:"childid"});

Also please suggest me if there is any other document database that would be suitable for this kind of retreiving data that is structured as a tree, where the requirement is to :

query children without having to issue joins

find any node in the tree as fast as you would find the root node, as if all these nodes were stored as separate documents in a collection.

Why this is not a duplicate of question(s) suggested :
the potential-duplicate-question, queries document by using dot notation. But what if the document is nested 7 levels deep ? In such case it would not be suitable to write a query using dot notation. what I want is that, all documents, whether top level, or nested, if they have the _id field, should be in the bucket of _id indexes, so that when you search db.collection.find({_id: "asdf"}), it should take into account documents that are nested too that have the _id field matching "asdf". In short, it should be as if the inner document weren't nested, but present parallel to the outer one.

Body:
You can use the dot notation:

db.posts.find({"child._id": "childid"})


问:
Package restore failed. Rolling back package changes
When I am trying to install any nuget package in VS2017 for asp.net core. it is constantly showing "Package restore failed. Rolling back package changes" for each package.</p>

答:
Update Nuget package
Microsoft.EntityFrameworkCore,
Microsoft.EntityFrameworkCore.SqlServer

**it will resolved because while we using scaffolding for new controller then DbContext class object is created that why correct package is required to update for EntityFrameworkCore **


问:
Clear previous output of widget every time it runs
I would like to clear the previous output when the widget is rerun.

for example

```<code>from IPython.display import display, clear_output

import ipywidgets as widgets
from datetime import datetime, timedelta
</code>```

```<code>button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):

    # DO SOMETHING #

    out = widgets.Output()
    out.clear_output(wait=True)
    out.append_stdout(f'Ran at {datetime.now()}')
    display(out)

button.on_click(on_button_clicked)
widgets.VBox([button])

</code>```

Every time i click on the RUN button it "appends" the print statement

I also tried this:

```<code>button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):

    # DO SOMETHING #

    out = widgets.Output()
    out.clear_output(wait=True)
    with out:
        print(f'Ran at {datetime.now()}')
    display(out)

button.on_click(on_button_clicked)
widgets.VBox([button])
</code>```

答:
Looks like you're running ipython 3.8... that's 5 years old. I strongly recommend upgrading to a later version, but totally understand that this is not always possible depending on time and resources.

Here's the documentation for the ipython 3.x display widget:

https://ipython.org/ipython-doc/3/api/generated/IPython.display.html#functions

Try this:

from IPython.display import clear_output
import ipywidgets as widgets
from datetime import datetime

button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):
    # DO SOMETHING #
    print(f'Ran at {datetime.now()}')

    # This will clear the cell output the NEXT time the button is pressed
    clear_output(wait=True)

button.on_click(on_button_clicked)
widgets.VBox([button])
```

There have been some reports of "shaking" in the notebook when print() is used. If you notice this, try using print('message', flush=True) instead.

Body:
I would like to clear the previous output when the widget is rerun.

for example

from IPython.display import display, clear_output

import ipywidgets as widgets
from datetime import datetime, timedelta

button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):

    # DO SOMETHING #

    out = widgets.Output()
    out.clear_output(wait=True)
    out.append_stdout(f'Ran at {datetime.now()}')
    display(out)

button.on_click(on_button_clicked)
widgets.VBox([button])

Every time i click on the RUN button it "appends" the print statement

I also tried this:

button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):

    # DO SOMETHING #

    out = widgets.Output()
    out.clear_output(wait=True)
    with out:
        print(f'Ran at {datetime.now()}')
    display(out)

button.on_click(on_button_clicked)
widgets.VBox([button])

Body:
Looks like you're running ipython 3.8... that's 5 years old. I strongly recommend upgrading to a later version, but totally understand that this is not always possible depending on time and resources.

Here's the documentation for the ipython 3.x display widget:

https://ipython.org/ipython-doc/3/api/generated/IPython.display.html#functions

Try this:

from IPython.display import clear_output
import ipywidgets as widgets
from datetime import datetime

button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):
    # DO SOMETHING #
    print(f'Ran at {datetime.now()}')

    # This will clear the cell output the NEXT time the button is pressed
    clear_output(wait=True)

button.on_click(on_button_clicked)
widgets.VBox([button])

There have been some reports of "shaking" in the notebook when print() is used. If you notice this, try using print('message', flush=True) instead.


问:
DST transitions vs. iCalendar reminders vs. RFC 5545 duration spec
How should an RFC 5545 duration of less than 24 hours act when it crosses a Daylight Saving Time (DST) transition?

For example, assume DST ends at 2:00AM on a particular day, and assume that an event starts at the second 1:10AM on that day. (The first 1:10AM is one real-world hour earlier in Daylight Time, the second 1:10AM is in Standard Time).

If that event has a -PT15M (15 mins before) duration reminder, then how many real-world minutes before the start of the event should that reminder pop up?  Should it pop up 15 real-world minutes earlier at the first 1:55AM (in Daylight Time)?  Or should it pop up 75 real-world minutes earlier at 12:55AM Daylight Time?

The spec seems to imply the latter behavior, but that behavior seems counter-intuitive to me. If I want a reminder 15 minutes beforehand, I really mean "15 minutes". However it is intuitive for longer reminders, e.g. -P1D should be 25 hours before the start of that event so that you get the reminder at the same local time on the previous day.

Anyway, how do most calendar apps deal with this unintuitive behavior?  Do they ignore the spec and always treat reminders <24 hours as exact without adjusting for DST? Or am I understanding the spec incorrectly and it's the -P1D case that will be unintuitive with the one-day reminder showing up at a different local time as the event start time?

Obviously this is somewhat of a corner case because few meetings start in the middle of the night. But there are cases where this could happen, e.g. late-night social events. And if I promise to meet you at the bar in 2 hours, I probably don't mean 1 hours or 3 hours on some nights!

Here's what the RFC 5545 spec says:

In the case of discontinuities in the time scale, such as the change from standard time to daylight time and back, the computation of the exact duration requires the subtraction or addition of the change of duration of the discontinuity.

To clarify further, according to https://standards.calconnect.org/csd/cc-51003.pdf, RFC 5545 has a concept of nominal durations (in local clock time) and exact durations (a real-world stopwatch that ignores DST). The language above is about how a nominal persisted duration should be converted to an exact duration.

This question isn't specific to a particular calendar implementation, but I'm tagging Google Calendar and Outlook here because developers using those APIs probably have the most context about these issues.

答:
The challenge here is to avoid ambiguity, not just with duration, but also with the event time.  See the first point in the summary of answers here Daylight saving time and time zone best practices

To avoid ambiguities and to accurately refer to the 'second' 1.10am one should use UTC timezone for those second instances.

Note: In the DATETIME part of the spec, under Form #3, https://www.rfc-editor.org/rfc/rfc5545#section-3.3.5 it clearly states that a local time with timezone always refers to the first instance.

Page 45 of the above doc says for recurrences it is always interpreted as above (first instance):

If the computed local start time of a recurrence instance does not
exist, or occurs more than once, for the specified time zone, the
time of the recurrence instance is interpreted in the same manner
as an explicit DATE-TIME value describing that date and time, as
specified in Section 3.3.5.

I take this to mean that the only way to refer to the second 1.10 am of your example would be using UTC time! (or another timezone not affected by that daylight saving change).

The summary of answers in the stack overflow link above does note that in some cases, one may need to store both local & UTC.  I suggest this may be exactly such a situation, where during the repeated cutover hour, the only truly accurate representation of times in that repeated daylight saving hour (the second hour), is the UTC time.


问:
C# How to get Audio Decibel values with time span
how can I get Decibel values of a wav/mp3 file I have every 1 second? using any audio library that works with C#..

something like:

```<code>Time: 0, DB: 0.213623
Time: 1, DB: 0.2692261
Time: 2, DB: 0.2355957
Time: 3, DB: 0.2363281
Time: 4, DB: 0.3799744
Time: 5, DB: 0.3580322
Time: 6, DB: 0.1331177
Time: 7, DB: 0.3091431
Time: 8, DB: 0.2984009
</code>```

I'd really appreciate your help :)

regards,

答:
I found a solution from examples given in NAudio Library.
since the solution I found is so big. I'm not gonna post it here.
so I'm just gonna give hints in case if anybody wanted to do the same thing..
NAudioDemo application -> AudioPlayBackDemo Folder ->  AudioPlayBackPanel.cs File...</p>

Body:
how can I get Decibel values of a wav/mp3 file I have every 1 second? using any audio library that works with C#..

something like:

Time: 0, DB: 0.213623
Time: 1, DB: 0.2692261
Time: 2, DB: 0.2355957
Time: 3, DB: 0.2363281
Time: 4, DB: 0.3799744
Time: 5, DB: 0.3580322
Time: 6, DB: 0.1331177
Time: 7, DB: 0.3091431
Time: 8, DB: 0.2984009

I'd really appreciate your help :)

regards,


问:
Strange C ++ behavior when i using a template in which need to calculate the address of an array cell
I created a matrix class and for example a simple cleanup function

```<code>template<typename T>
class matrix
{
public:
    matrix(int Lenght, int Height)
    {
        this->container = new T[this->lenght * this->height];

        this->lenght = Lenght;
        this->height = Height;
    }

    void Nulling()
    {
        size_t A = sizeof(T);
        for (int i = 0; i < (this->height * this->lenght); i++)
        {
           this->container)[i] = 0;
           //((T*)this->container)[i] = 0;    // same result
        }
    }

    T* container = nullptr;
    int lenght;
    int height;

};
</code>```

when i == 100226, debugging stops and an error occurs while writing ( i have 512*512 matrix so its 262144 elements)

I think problem is incorrect calculating adress with templates, i try this construction

```<code>size_t A = sizeof(T);
        for (int i = 0; i < (this->height * this->lenght); i++)
        {
            this->container[0] = 0;
            this->container += A;
        }
</code>```

its cause error on i == 12529

So i dont know what to do now.

答:
In your constructor, the statement

```<code>this->container = new T[this->lenght * this->height];
</code>```

Has undefined behavior, because you are using this->lenght and this->height before they have been assigned values, thus the size of the allocated array is indeterminate. You need to do those assignments first:

```<code>matrix(int Lenght, int Height)
{
    this->lenght = Lenght;
    this->height = Height;
    this->container = new T[this->lenght * this->height];
}
</code>```

Alternatively, use the input values instead of the class members when allocating the array:

```<code>matrix(int Lenght, int Height)
{
    this->container = new T[Lenght * Height];
    this->lenght = Lenght;
    this->height = Height;
}
</code>```

Body:
I created a matrix class and for example a simple cleanup function

template<typename T>
class matrix
{
public:
    matrix(int Lenght, int Height)
    {
        this->container = new T[this->lenght * this->height];

        this->lenght = Lenght;
        this->height = Height;
    }

    void Nulling()
    {
        size_t A = sizeof(T);
        for (int i = 0; i < (this->height * this->lenght); i++)
        {
           this->container)[i] = 0;
           //((T*)this->container)[i] = 0;    // same result
        }
    }

    T* container = nullptr;
    int lenght;
    int height;

};

when i == 100226, debugging stops and an error occurs while writing ( i have 512*512 matrix so its 262144 elements)

I think problem is incorrect calculating adress with templates, i try this construction

size_t A = sizeof(T);
        for (int i = 0; i < (this->height * this->lenght); i++)
        {
            this->container[0] = 0;
            this->container += A;
        }

its cause error on i == 12529

So i dont know what to do now.

Body:
In your constructor, the statement

this->container = new T[this->lenght * this->height];

Has undefined behavior, because you are using this->lenght and this->height before they have been assigned values, thus the size of the allocated array is indeterminate. You need to do those assignments first:

matrix(int Lenght, int Height)
{
    this->lenght = Lenght;
    this->height = Height;
    this->container = new T[this->lenght * this->height];
}

Alternatively, use the input values instead of the class members when allocating the array:

matrix(int Lenght, int Height)
{
    this->container = new T[Lenght * Height];
    this->lenght = Lenght;
    this->height = Height;
}


问:
Using CodePipeline to Deploy ElasticBeanstalk application in another AWS account
We have a setup with different AWS accounts for each environment(dev, test, prod) and then a shared build account which has a AWS CodePipeline that deploys into each of these environment by assuming a role in dev, test, prod.

This works fine for our Serverless applications using a Codebuild script.

Can we do something similar for the Elastic Beanstalk application that uses the deploy action provider? Or what is the best approach for Elastic Beanstalk

答:
We do this by using a CodeBuild job specified in each of the stage accounts (dev, test, prod) that uses the AWS CLI to deploy the CodePipeline artifact (available as CODEBUILD_SOURCE_VERSION in your build job's environment variables) to Elastic Beanstalk. We run this job as part of a CodePipeline in our shared build account.

These are the AWS CLI commands the CodeBuild deploy job runs:

```<code>aws elasticbeanstalk create-application-version --application-name ... --version-label ... --source-bundle S3Bucket="codepipeline-artifacts-us-east-1-123456789012",S3Key="application/deployable/XXXXXXX"
aws elasticbeanstalk update-environment --environment-name ... --version-label ...
</code>```

You can specify a CodeBuild job from another account in CodePipeline using the strategy outlined here: https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-create-cross-account.html. It involves setting up cross-account access to the role_arn used for the CodeBuild deploy job and a customer managed KMS key for the pipeline (with a cross-account access policy).

One deficiency with this approach is that the CodeBuild deploy job will complete as soon as the deployment starts and not wait until the ElasticBeanstalk deployment succeeds or fails, as the native CodePipeline EB deploy action does. You should be able to call aws elasticbeanstalk describe-environments in a loop from the job to replicate this behavior, but I have not yet attempted this. (Sample script here: https://blog.cyplo.net/posts/2018/04/wait-for-beanstalk/)

Body:
We do this by using a CodeBuild job specified in each of the stage accounts (dev, test, prod) that uses the AWS CLI to deploy the CodePipeline artifact (available as CODEBUILD_SOURCE_VERSION in your build job's environment variables) to Elastic Beanstalk. We run this job as part of a CodePipeline in our shared build account.

These are the AWS CLI commands the CodeBuild deploy job runs:

aws elasticbeanstalk create-application-version --application-name ... --version-label ... --source-bundle S3Bucket="codepipeline-artifacts-us-east-1-123456789012",S3Key="application/deployable/XXXXXXX"
aws elasticbeanstalk update-environment --environment-name ... --version-label ...

You can specify a CodeBuild job from another account in CodePipeline using the strategy outlined here: https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-create-cross-account.html. It involves setting up cross-account access to the role_arn used for the CodeBuild deploy job and a customer managed KMS key for the pipeline (with a cross-account access policy).

One deficiency with this approach is that the CodeBuild deploy job will complete as soon as the deployment starts and not wait until the ElasticBeanstalk deployment succeeds or fails, as the native CodePipeline EB deploy action does. You should be able to call aws elasticbeanstalk describe-environments in a loop from the job to replicate this behavior, but I have not yet attempted this. (Sample script here: https://blog.cyplo.net/posts/2018/04/wait-for-beanstalk/)


问:
Async Behavior in Javascript
The following function -

```<code>a = [1,2,3];
function f() {
    for(let i=0; i < a.length; i++){
        setTimeout(() => console.log(i),3000)
    }
}
</code>```

gives me output - 0,1,2 which is as expected.

However, the following function -

```<code>function f() {
    for(var i=0; i < a.length; i++){
        setTimeout((function(el){console.log(el)})(i),3000)
    }
}
</code>```

gives the following output -
0 and throws following error

```<code>Uncaught TypeError: Cannot read property '__wrapper_2__' of undefined
</code>```

However, in the last function if I remove setTimeout, I am getting expected behavior i.e. -

```<code>function f() {
    for(let i=0; i < a.length; i++){ (function(i){console.log(i)})(i);
    }
}
</code>```

I am getting the expected output - 0,1,2
So, Why setTimeout is giving me error with when defining new function, but not with arrow functions ?

答:
You're attempting to call the function in the argument list. It doesn't work for the same reason this doesn't:

```<code>function f() {
    for (let i = 0; i < a.length; i++) {
        setTimeout(console.log(i), 3000);
    }
}
f();

</code>```

The first argument of setTimeout is an uncalled function, like:

```<code>setTimeout(() => console.log(i), 1000);
</code>```

or

```<code>const method = () => console.log(i);
setTimeout(method, 1000)
</code>```

Edit: Also,

```<code>function f() {
    for (var i = 0; i < a.length; i++) {
        setTimeout(() => {
            (function (el) {
                console.log(el);
            })(i);
        }, 3000);
    }
}
let a = [1, 2, 3];
f();
</code>```

Will return 3, 3, 3 because after 3000ms the given function will be called with the global variable i as a parameter, and at that point i === 3;

However, in the following example, the value of i at the time is saved in the function. I believe that has something to do with closures, maybe someone else can follow up with a better explanation of that.

```<code>function f() {
    for (var i = 0; i < a.length; i++) {
        setTimeout(() => {
            console.log(i);
        }, 3000);
    }
}
let a = [1, 2, 3];
f();

</code>```

Title: Async Behavior in Javascript

Body:
The following function -

a = [1,2,3];
function f() {
    for(let i=0; i  console.log(i),3000)
    }
}

gives me output - 0,1,2 which is as expected.

However, the following function -

function f() {
    for(var i=0; i < a.length; i++){
        setTimeout((function(el){console.log(el)})(i),3000)
    }
}

gives the following output -
0 and throws following error

Uncaught TypeError: Cannot read property '__wrapper_2__' of undefined

However, in the last function if I remove setTimeout, I am getting expected behavior i.e. -

function f() {
    for(let i=0; i < a.length; i++){ (function(i){console.log(i)})(i);
    }
}

I am getting the expected output - 0,1,2
So, Why setTimeout is giving me error with when defining new function, but not with arrow functions ?

Body:
You're attempting to call the function in the argument list. It doesn't work for the same reason this doesn't:

function f() {
    for (let i = 0; i < a.length; i++) {
        setTimeout(console.log(i), 3000);
    }
}
f();

The first argument of setTimeout is an uncalled function, like:

setTimeout(() => console.log(i), 1000);

or

const method = () => console.log(i);
setTimeout(method, 1000)

Edit: Also,

function f() {
    for (var i = 0; i < a.length; i++) {
        setTimeout(() => {
            (function (el) {
                console.log(el);
            })(i);
        }, 3000);
    }
}
let a = [1, 2, 3];
f();

Will return 3, 3, 3 because after 3000ms the given function will be called with the global variable i as a parameter, and at that point i === 3;

However, in the following example, the value of i at the time is saved in the function. I believe that has something to do with closures, maybe someone else can follow up with a better explanation of that.

function f() {
    for (var i = 0; i < a.length; i++) {
        setTimeout(() => {
            console.log(i);
        }, 3000);
    }
}
let a = [1, 2, 3];
f();


问:
How to remove fingerprint authentication from Android KeyGaurd manager?
I've used keyguard manager inside my app to perform some action if and only if the user authenticates using his default device lock credentials, now what is happening is that my device has both fingerprint and pattern/pin lock enabled and when the keyguard manager checks the authentication using isKeyguardSecure method, it starts an activity for result and opens the intent using .createConfirmDeviceCredentialIntent...Now in this intent it asks for the fingerprint by default and gives an option for pin/pattern...I want to disable the fingerprint option in my app, and do not want to remove the fingerprint security from the device itself, just disable it for that particular app or intent.
This is my code:

```<code>KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
Intent screenLockIntent = keyguardManager.createConfirmDeviceCredentialIntent(title, description);
startActivityForResult(screenLockIntent, LOCK_REQUEST_CODE);
</code>```

Getting the result in this method

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
    if(LOCK_REQUEST_CODE == requestCode){
        if (resultCode == RESULT_OK) {
            //Authentication is successful
              My App works now
        } else {
            //Authentication failed
        }
    }
}
</code>```

Screenshot showing the fingerprint authentication which I want to remove

This all is working fine, I just want to remove the fingerprint authentication for this particular app and just use the pin/password option...
Thanks in advance ;-)

答:
You can't do that if you are using createConfirmDeviceCredentialIntent(), as this is a system intent and you can't change it. Generally, the screen lock is manged by the OS and will support whatever has been set up (face, fingerprint, iris, PIN, etc.)

You could implement a custom PIN only screen in your app, but that's tricky to do and generally less secure than the one provided by the OS.

Body:
I've used keyguard manager inside my app to perform some action if and only if the user authenticates using his default device lock credentials, now what is happening is that my device has both fingerprint and pattern/pin lock enabled and when the keyguard manager checks the authentication using isKeyguardSecure method, it starts an activity for result and opens the intent using .createConfirmDeviceCredentialIntent...Now in this intent it asks for the fingerprint by default and gives an option for pin/pattern...I want to disable the fingerprint option in my app, and do not want to remove the fingerprint security from the device itself, just disable it for that particular app or intent.
This is my code:

KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
Intent screenLockIntent = keyguardManager.createConfirmDeviceCredentialIntent(title, description);
startActivityForResult(screenLockIntent, LOCK_REQUEST_CODE);

Getting the result in this method

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
    if(LOCK_REQUEST_CODE == requestCode){
        if (resultCode == RESULT_OK) {
            //Authentication is successful
              My App works now
        } else {
            //Authentication failed
        }
    }
}

Screenshot showing the fingerprint authentication which I want to remove

This all is working fine, I just want to remove the fingerprint authentication for this particular app and just use the pin/password option...
Thanks in advance ;-)


问:
Reformatting a string and placing parts of it in separate variables
I'm trying to format a string that is entered by a user, and then want to place parts of that string in three separate variables.

```<code>//This is the text the user enters
rgbInputTextField.text == "253, 254, 255" //(Or variations like "53 54 55" or "3,4,5")

//I'd like to place that string in three variables such that:
R == 253
G == 254
G == 255
</code>```

Am I approaching this completely wrong? The goal is to register the RGB input string from the user and convert it to a Hex value.

I'm able to convert to Hex once I have the R, G and B variables, but can't figure out how to place the rgbInputTextField String into those three separate variables. I've found many UIColor extensions that can convert a hex string to UIColor, but nothing that converts an rgb string (with variations) to hex/UIColor.

Appreciate any help!

答:
Find a way to parse the string and after each comma, store the variable of R, G, and B. For this, you could create a regular expression using NSRegularExpression.

https://developer.apple.com/documentation/foundation/nsregularexpression

If I were you, I would just make three separate textFields and read in values from the inputs.

Body:
I'm trying to format a string that is entered by a user, and then want to place parts of that string in three separate variables.

//This is the text the user enters
rgbInputTextField.text == "253, 254, 255" //(Or variations like "53 54 55" or "3,4,5")

//I'd like to place that string in three variables such that:
R == 253
G == 254
G == 255

Am I approaching this completely wrong? The goal is to register the RGB input string from the user and convert it to a Hex value.

I'm able to convert to Hex once I have the R, G and B variables, but can't figure out how to place the rgbInputTextField String into those three separate variables. I've found many UIColor extensions that can convert a hex string to UIColor, but nothing that converts an rgb string (with variations) to hex/UIColor.

Appreciate any help!