问:
Delete value from array then resize
For reference, here is the whole code.

```<code>  Sub CalculateOutliers()

                Dim n As Long
                Dim mean As Double
                Dim SD As Double
                Dim k As Long
                Dim DataSet As Variant
                Dim LowConf As Double
                Dim HighConf As Double

            '--------------------------------------------------------
                DataSet = Selection.Value
            'Copies highlighted data into DataSet variable
            'Cell A1 is (1,1) Because it starts at 0 which is out of range
            '--------------------------------------------------------

            '--------------------------------------------------------
                n = Selection.CountLarge
            'Counts number of entries
            '--------------------------------------------------------

            '--------------------------------------------------------
             'DEFINES 95(LowConf) AND 99(HighConf) PERCENT CONFIDENCES BASED ON
             'SAMPLE SIZE

                If n <= 5 Then
                        LowConf = 1.72
                        HighConf = 1.76
                End If

                If n = 6 Then
                        LowConf = 1.89
                        HighConf = 1.97
                End If

                If n = 7 Then
                        LowConf = 2.02
                        HighConf = 2.14
                End If

                If n = 8 Then
                        LowConf = 2.13
                        HighConf = 2.28
                End If

                If n = 9 Then
                        LowConf = 2.21
                        HighConf = 2.39
                End If

                If n = 10 Then
                        LowConf = 2.29
                        HighConf = 2.48
                End If

                If n = 11 Then
                        LowConf = 2.36
                        HighConf = 2.56
                End If

                If n = 12 Then
                        LowConf = 2.41
                        HighConf = 2.64
                End If

                If n = 13 Then
                        LowConf = 2.46
                        HighConf = 2.7
                End If

                If n = 14 Then
                        LowConf = 2.51
                        HighConf = 2.75
                End If

                If n = 15 Then
                        LowConf = 2.55
                        HighConf = 2.81
                End If

                If n = 16 Then
                        LowConf = 2.59
                        HighConf = 2.85
                End If

                If n = 17 Then
                        LowConf = 2.62
                        HighConf = 2.9
                End If

                If n = 18 Then
                        LowConf = 2.65
                        HighConf = 2.93
                End If

                If n = 19 Then
                        LowConf = 2.68
                        HighConf = 2.97
                End If

                If n = 20 Then
                        LowConf = 2.71
                        HighConf = 3
                End If

                If n = 21 Then
                        LowConf = 2.73
                        HighConf = 3.03
                End If

                If n = 22 Then
                        LowConf = 2.76
                        HighConf = 3.06
                End If

                If n = 23 Then
                        LowConf = 2.78
                        HighConf = 3.08
                End If

                If n = 24 Then
                        LowConf = 2.8
                        HighConf = 3.11
                End If

                If n = 25 Then
                        LowConf = 2.82
                        HighConf = 3.14
                End If

                If n = 26 Then
                        LowConf = 2.84
                        HighConf = 3.16
                End If

                If n = 27 Then
                        LowConf = 2.86
                        HighConf = 3.18
                End If

                If n = 28 Then
                        LowConf = 2.88
                        HighConf = 3.2
                End If

                If n = 29 Then
                        LowConf = 2.89
                        HighConf = 3.22
                End If

                If n = 30 Then
                        LowConf = 2.91
                        HighConf = 3.24
                End If

                If n <= 35 And n > 30 Then
                        LowConf = 2.98
                        HighConf = 3.32
                End If

                If n <= 40 And n > 35 Then
                        LowConf = 3.04
                        HighConf = 3.38
                End If

                If n <= 45 And n > 40 Then
                        LowConf = 3.09
                        HighConf = 3.44
                End If

                If n <= 50 And n > 45 Then
                        LowConf = 3.13
                        HighConf = 3.48
                End If

                If n <= 60 And n > 50 Then
                        LowConf = 3.2
                        HighConf = 3.56
                End If

                If n <= 70 And n > 60 Then
                        LowConf = 3.26
                        HighConf = 3.62
                End If

                If n <= 80 And n > 70 Then
                        LowConf = 3.31
                        HighConf = 3.67
                End If

                If n <= 90 And n > 80 Then
                        LowConf = 3.35
                        HighConf = 3.72
                End If

                If n <= 100 And n > 90 Then
                        LowConf = 3.38
                        HighConf = 3.75
                End If

                If n <= 150 And n > 100 Then
                        LowConf = 3.52
                        HighConf = 3.89
                End If

                If n <= 200 And n > 150 Then
                        LowConf = 3.61
                        HighConf = 3.98
                End If

                If n <= 300 And n > 200 Then
                        LowConf = 3.72
                        HighConf = 4.09
                End If

                If n <= 400 And n > 300 Then
                        LowConf = 3.8
                        HighConf = 4.17
                End If

                If n <= 500 And n > 400 Then
                        LowConf = 3.86
                        HighConf = 4.32
                End If

                If n > 500 Then
                        MsgBox "Sample size cannot exceed 500."
                End If
            '--------------------------------------------------------

            '--------------------------------------------------------
                If n < 50 Then
                    k = Int(n / 10)
                Else
                    k = 5
                End If
            'determines k = number of possible outliers
            '--------------------------------------------------------

            Dim i As Long

            For i = 1 To k
            '--------------------------------------------------------
                mean = Application.WorksheetFunction.Average(DataSet)
            'Calculates mean of Data Set
            '--------------------------------------------------------

            '--------------------------------------------------------
                SD = Application.WorksheetFunction.StDev(DataSet)
            'Calculates Standard Deviation of Data Set
            '--------------------------------------------------------

            '--------------------------------------------------------
                Dim Suspect As Double

                If (Abs(Application.WorksheetFunction.Max(DataSet) - mean)) > (Abs(Application.WorksheetFunction.Min(DataSet) - mean)) Then

                    Suspect = Application.WorksheetFunction.Max(DataSet)

                End If

                If (Abs(Application.WorksheetFunction.Max(DataSet) - mean)) < (Abs(Application.WorksheetFunction.Min(DataSet) - mean)) Then

                    Suspect = Application.WorksheetFunction.Min(DataSet)

                End If
            'Defines what the most outlying value is
            '--------------------------------------------------------

            '--------------------------------------------------------
                Dim Retest As Boolean

                If (Abs(Suspect - mean) / SD) > LowConf Then
                    MsgBox "95% outlier: " & Suspect
                    Retest = True
                End If

                If (Abs(Suspect - mean) / SD) > HighConf Then
                    MsgBox "99% outlier: " & Suspect
                    Retest = True
                End If

                If Retest = True Then

            '--------------------------------------------------------
            Next i

            End Sub
</code>```

Talking about this chunk of code, I need to delete Suspect from DataSet then shrink DataSet by 1 but I am not sure how to go about this. Is there a function that will delete the Max or Min value and is there a way to resize DataSet given that it is a variant?

```<code>                        Dim Retest As Boolean

                        If (Abs(Suspect - mean) / SD) > LowConf Then

                            MsgBox "95% outlier: " & Suspect
                            Retest = True

                    End If

                        If (Abs(Suspect - mean) / SD) > HighConf Then

                            MsgBox "99% outlier: " & Suspect
                            Retest = True

                    End If

                        If Retest = True Then
</code>```

答:
One approach is to sort the data, either in excel before reading it into the vba routine, or in vba see for example Chip Pearson. With sorted data, you can remove outliers by changing array bounds, e.g. DataSet(3) to DataSet(n-5) has removed 2 outliers on the low side and 5 on the high side.

Hope that helps

Title: Delete value from array then resize

Body:
For reference, here is the whole code.

  Sub CalculateOutliers()

                Dim n As Long
                Dim mean As Double
                Dim SD As Double
                Dim k As Long
                Dim DataSet As Variant
                Dim LowConf As Double
                Dim HighConf As Double

            '--------------------------------------------------------
                DataSet = Selection.Value
            'Copies highlighted data into DataSet variable
            'Cell A1 is (1,1) Because it starts at 0 which is out of range
            '--------------------------------------------------------

            '--------------------------------------------------------
                n = Selection.CountLarge
            'Counts number of entries
            '--------------------------------------------------------

            '--------------------------------------------------------
             'DEFINES 95(LowConf) AND 99(HighConf) PERCENT CONFIDENCES BASED ON
             'SAMPLE SIZE

                If n <= 5 Then
                        LowConf = 1.72
                        HighConf = 1.76
                End If

                If n = 6 Then
                        LowConf = 1.89
                        HighConf = 1.97
                End If

                If n = 7 Then
                        LowConf = 2.02
                        HighConf = 2.14
                End If

                If n = 8 Then
                        LowConf = 2.13
                        HighConf = 2.28
                End If

                If n = 9 Then
                        LowConf = 2.21
                        HighConf = 2.39
                End If

                If n = 10 Then
                        LowConf = 2.29
                        HighConf = 2.48
                End If

                If n = 11 Then
                        LowConf = 2.36
                        HighConf = 2.56
                End If

                If n = 12 Then
                        LowConf = 2.41
                        HighConf = 2.64
                End If

                If n = 13 Then
                        LowConf = 2.46
                        HighConf = 2.7
                End If

                If n = 14 Then
                        LowConf = 2.51
                        HighConf = 2.75
                End If

                If n = 15 Then
                        LowConf = 2.55
                        HighConf = 2.81
                End If

                If n = 16 Then
                        LowConf = 2.59
                        HighConf = 2.85
                End If

                If n = 17 Then
                        LowConf = 2.62
                        HighConf = 2.9
                End If

                If n = 18 Then
                        LowConf = 2.65
                        HighConf = 2.93
                End If

                If n = 19 Then
                        LowConf = 2.68
                        HighConf = 2.97
                End If

                If n = 20 Then
                        LowConf = 2.71
                        HighConf = 3
                End If

                If n = 21 Then
                        LowConf = 2.73
                        HighConf = 3.03
                End If

                If n = 22 Then
                        LowConf = 2.76
                        HighConf = 3.06
                End If

                If n = 23 Then
                        LowConf = 2.78
                        HighConf = 3.08
                End If

                If n = 24 Then
                        LowConf = 2.8
                        HighConf = 3.11
                End If

                If n = 25 Then
                        LowConf = 2.82
                        HighConf = 3.14
                End If

                If n = 26 Then
                        LowConf = 2.84
                        HighConf = 3.16
                End If

                If n = 27 Then
                        LowConf = 2.86
                        HighConf = 3.18
                End If

                If n = 28 Then
                        LowConf = 2.88
                        HighConf = 3.2
                End If

                If n = 29 Then
                        LowConf = 2.89
                        HighConf = 3.22
                End If

                If n = 30 Then
                        LowConf = 2.91
                        HighConf = 3.24
                End If

                If n <= 35 And n > 30 Then
                        LowConf = 2.98
                        HighConf = 3.32
                End If

                If n <= 40 And n > 35 Then
                        LowConf = 3.04
                        HighConf = 3.38
                End If

                If n <= 45 And n > 40 Then
                        LowConf = 3.09
                        HighConf = 3.44
                End If

                If n <= 50 And n > 45 Then
                        LowConf = 3.13
                        HighConf = 3.48
                End If

                If n <= 60 And n > 50 Then
                        LowConf = 3.2
                        HighConf = 3.56
                End If

                If n <= 70 And n > 60 Then
                        LowConf = 3.26
                        HighConf = 3.62
                End If

                If n <= 80 And n > 70 Then
                        LowConf = 3.31
                        HighConf = 3.67
                End If

                If n <= 90 And n > 80 Then
                        LowConf = 3.35
                        HighConf = 3.72
                End If

                If n <= 100 And n > 90 Then
                        LowConf = 3.38
                        HighConf = 3.75
                End If

                If n <= 150 And n > 100 Then
                        LowConf = 3.52
                        HighConf = 3.89
                End If

                If n <= 200 And n > 150 Then
                        LowConf = 3.61
                        HighConf = 3.98
                End If

                If n <= 300 And n > 200 Then
                        LowConf = 3.72
                        HighConf = 4.09
                End If

                If n <= 400 And n > 300 Then
                        LowConf = 3.8
                        HighConf = 4.17
                End If

                If n <= 500 And n > 400 Then
                        LowConf = 3.86
                        HighConf = 4.32
                End If

                If n > 500 Then
                        MsgBox "Sample size cannot exceed 500."
                End If
            '--------------------------------------------------------

            '--------------------------------------------------------
                If n < 50 Then
                    k = Int(n / 10)
                Else
                    k = 5
                End If
            'determines k = number of possible outliers
            '--------------------------------------------------------

            Dim i As Long

            For i = 1 To k
            '--------------------------------------------------------
                mean = Application.WorksheetFunction.Average(DataSet)
            'Calculates mean of Data Set
            '--------------------------------------------------------

            '--------------------------------------------------------
                SD = Application.WorksheetFunction.StDev(DataSet)
            'Calculates Standard Deviation of Data Set
            '--------------------------------------------------------

            '--------------------------------------------------------
                Dim Suspect As Double

                If (Abs(Application.WorksheetFunction.Max(DataSet) - mean)) > (Abs(Application.WorksheetFunction.Min(DataSet) - mean)) Then

                    Suspect = Application.WorksheetFunction.Max(DataSet)

                End If

                If (Abs(Application.WorksheetFunction.Max(DataSet) - mean)) < (Abs(Application.WorksheetFunction.Min(DataSet) - mean)) Then

                    Suspect = Application.WorksheetFunction.Min(DataSet)

                End If
            'Defines what the most outlying value is
            '--------------------------------------------------------

            '--------------------------------------------------------
                Dim Retest As Boolean

                If (Abs(Suspect - mean) / SD) > LowConf Then
                    MsgBox "95% outlier: " & Suspect
                    Retest = True
                End If

                If (Abs(Suspect - mean) / SD) > HighConf Then
                    MsgBox "99% outlier: " & Suspect
                    Retest = True
                End If

                If Retest = True Then

            '--------------------------------------------------------
            Next i

            End Sub

Talking about this chunk of code, I need to delete Suspect from DataSet then shrink DataSet by 1 but I am not sure how to go about this. Is there a function that will delete the Max or Min value and is there a way to resize DataSet given that it is a variant?

                        Dim Retest As Boolean

                        If (Abs(Suspect - mean) / SD) > LowConf Then

                            MsgBox "95% outlier: " & Suspect
                            Retest = True

                    End If

                        If (Abs(Suspect - mean) / SD) > HighConf Then

                            MsgBox "99% outlier: " & Suspect
                            Retest = True

                    End If

                        If Retest = True Then


来源: stackexchange

问:
Multiple Imputation Exercise
I am reviewing multiple imputations methods in R, and I came across a fundamental yet important question. In the script below, what purpose does the number 7 serve in data[4:10, 3] <- rep(NA, 7)? Is it telling R to repeat NA seven times?

```<code>library(mice)
library(Amelia)
library(mi)
library(missForest)
library(Hmisc)
library(mi)

data <- airquality
data[4:10, 3] <- rep(NA, 7) # rows 4 through 10, third column, make it NA
data[1:5, 4] <- NA # rows 1 through 5, fourth column, make it NA
</code>```

答:
Yes.</p>

```<code> > rep(NA, 3)
 # [1] NA NA NA
 >rep(NA, 7)
 # [1] NA NA NA NA NA NA NA
</code>```

ContentLicense: CC BY-SA 3.0

Title: Multiple Imputation Exercise

Body:
I am reviewing multiple imputations methods in R, and I came across a fundamental yet important question. In the script below, what purpose does the number 7 serve in data[4:10, 3] <- rep(NA, 7)? Is it telling R to repeat NA seven times?

library(mice)
library(Amelia)
library(mi)
library(missForest)
library(Hmisc)
library(mi)

data <- airquality
data[4:10, 3] <- rep(NA, 7) # rows 4 through 10, third column, make it NA
data[1:5, 4] <- NA # rows 1 through 5, fourth column, make it NA

Body:
Yes.

 > rep(NA, 3)
 # [1] NA NA NA
 >rep(NA, 7)
 # [1] NA NA NA NA NA NA NA


问:
'JPA/Hibernate: Change primitive Datatype(double) to Wrapper (Double)
I want to change primitiv (double) to Wrapper (Double) in JPA.

Data already exists in Database with the primitive data type (double).

```<code>Current Status:
private double item;

What i want:
private Double item;
</code>```

If i change double to Double i get an error : ---> Column 'item' cannot be null.
Its because primitiv Datatypes does not except null. But before i have changed my Model to the Wrapper Double.

So i think JPA does not update Datatable Schema, to allow null for 'item'.

I have already set update property for Hibernate.

```<code><property name="hibernate.hbm2ddl.auto" value="update" />
</code>```

Any Idea how to deal with this ?

答:
Maybe you could add nullable = true to your item column, this will allow null value and regenerate your schema

ex:

```<code>@Column(name = "ITEM", nullable=true)
private Double item;
</code>```

Or

just initialize your wrapper type with 0

Body:
I want to change primitiv (double) to Wrapper (Double) in JPA.

Data already exists in Database with the primitive data type (double).

Current Status:
private double item;

What i want:
private Double item;

If i change double to Double i get an error : ---> Column 'item' cannot be null.
Its because primitiv Datatypes does not except null. But before i have changed my Model to the Wrapper Double.

So i think JPA does not update Datatable Schema, to allow null for 'item'.

I have already set update property for Hibernate.

<property name="hibernate.hbm2ddl.auto" value="update" />

Any Idea how to deal with this ?

Body:
Maybe you could add nullable = true to your item column, this will allow null value and regenerate your schema

ex:

@Column(name = "ITEM", nullable=true)
private Double item;

Or

just initialize your wrapper type with 0


问:
AntiForgeryConfig.UniqueClaimTypeIdentifier in ASP.NET Core
In earlier versions of ASP.NET we usally used a property named AntiForgeryConfig.UniqueClaimTypeIdentifier for claims-based authorization to set the claim type from the identity that was used to uniquely identify the user.

How is this done in ASP.NET Core?

答:
As near as I can tell what you are looking for is to set up a SignInManager in the Startup.cs class's ConfigureServices method like so:

```<code>services.AddScoped<SignInManager<ApplicationUser>, AvantiaSignInManager<ApplicationUser>>();
</code>```

Then you can implement your own SignInManager like the following:

```<code>public class AvantiaSignInManager<TUser> : SignInManager<TUser> where TUser : class
</code>```

You will have to implement the CreateUserPrincipalAsync method like the following:

```<code>public override async Task<ClaimsPrincipal> CreateUserPrincipalAsync(TUser user) {
  var Principal = await base.CreateUserPrincipalAsync(user);
  var Identity = (ClaimsIdentity)Principal.Identity;

  // How To: Here is where you can add Custom/On the fly Claims
  // They would not be persisted in the database but are within the Cookie

  var Employee = _dataContext.Employees
    .Include(x => x.Tenant)
    .ThenInclude(x => x.Subscriber)
    .Where(x => x.Email == Identity.Name)
    .SingleOrDefault();

  // See if there are any Claims linked to this user
  var MyClaims = _dataContext.EmployeeRoleClaims
    .Where(x => x.EmployeeID == Employee.ID)
    .Select(x => x.RoleClaim)
    .ToList();

  if (Employee != null) {
    // Add common Claims for every user, but the values are unique to them
    Identity.AddClaim(new Claim(Constants.Claims.Employee.ID, Employee.ID.ToString()));
    Identity.AddClaim(new Claim(Constants.Claims.Employee.Number, Employee.Number));
    Identity.AddClaim(new Claim(Constants.Claims.Tenant.ID, Employee.TenantID.ToString()));
    Identity.AddClaim(new Claim(Constants.Claims.Tenant.Name, Employee?.Tenant.Name));
    Identity.AddClaim(new Claim(Constants.Claims.Subscriber.ID, Employee?.Tenant.SubscriberID.ToString()));
    Identity.AddClaim(new Claim(Constants.Claims.Subscriber.Name, Employee?.Tenant?.Subscriber.Name));

    // Add any special Claims - May not be necessary within your application
    foreach (var rc in MyClaims) {
      Identity.AddClaim(rc.ToClaim()); // Add the Claim normally

      if ((rc.ClaimType == Constants.Claims.Subscriber.Administrator) ||
        (rc.ClaimType == Constants.Claims.Subscriber.TimeSheetAdmin) ||
        (rc.ClaimType == Constants.Claims.Subscriber.TimeSheetReview)) {
        var myTenants = _dataContext.Tenants.Where(x => x.SubscriberID == Convert.ToInt64(rc.ClaimValue)).ToList();

        foreach (var t in myTenants) {
          if (rc.ClaimType == Constants.Claims.Subscriber.Administrator)
            Identity.AddClaim(new Claim(Constants.Claims.Tenant.Administrator, t.ID.ToString()));
          else if (rc.ClaimType == Constants.Claims.Subscriber.TimeSheetAdmin)
            Identity.AddClaim(new Claim(Constants.Claims.Tenant.TimeSheetAdmin, t.ID.ToString()));
          else if (rc.ClaimType == Constants.Claims.Subscriber.TimeSheetReview)
            Identity.AddClaim(new Claim(Constants.Claims.Tenant.TimeSheetReview, t.ID.ToString()));
        } // foreach of the Tenants within the Subscription
      } // if I am the Administrator of a Subscription, I should also get the Tenants as well
    } // foreach of the Claims that have been specifically assinged to me

    // Add Claims for each of the Projects I am a Manager of or a Member of
    var PM = _dataContext.ProjectRoles.Where(x => x.Name == "Project Manager").FirstOrDefault();

    if (PM != null) {
      // Get the Projects where I am the Project Manager
      var MyPMProjects = _dataContext.ProjectProjectRoleEmployees.Where(x => x.EmployeeID == Employee.ID && x.ProjectRoleID == PM.ID).ToList();

      foreach(var Project in MyPMProjects)
        Identity.AddClaim(new Claim(Constants.Claims.Project.ManagerOf, Project.ProjectID.ToString()));

      // Get the Projects that I am ON but am NOT the Project Manager
      var MyProjects = _dataContext.ProjectProjectRoleEmployees.Where(x => x.EmployeeID == Employee.ID && x.ProjectRoleID != PM.ID).ToList();

      foreach (var Project in MyProjects)
        Identity.AddClaim(new Claim(Constants.Claims.Project.MemberOf, Project.ProjectID.ToString()));
    } // if we found the Project Manager Role
  } // if we found the associated Employee record

  return Principal;
}
</code>```

I then created a BaseController that overrides the default Controller class as such:

```<code>public class BaseController : Controller {

  internal ILogger logger;

  public string UsersLoginName => User.Identity.Name;
  public long UsersEmployeeID => User.HasClaim(x => x.Type == Constants.Claims.Employee.ID) ? Convert.ToInt64(User.FindFirst(Constants.Claims.Employee.ID).Value) : 0;
  public long UsersTenantID => User.HasClaim(x => x.Type == Constants.Claims.Tenant.ID) ? Convert.ToInt64(User.FindFirst(Constants.Claims.Tenant.ID).Value) : 0;
  public long UsersSubscriberID => User.HasClaim(x => x.Type == Constants.Claims.Subscriber.ID) ? Convert.ToInt64(User.FindFirst(Constants.Claims.Subscriber.ID).Value) : 0;

}
</code>```

This would allow me to, from any xxxController inheriting from my BaseController to do things like:

```<code>model.EmployeeID = UsersEmployeeID;
</code>```

I realize it has been months since you asked this question, but for you and anyone coming to this after the fact, hope it helps out.

Body:
As near as I can tell what you are looking for is to set up a SignInManager in the Startup.cs class's ConfigureServices method like so:

services.AddScoped<SignInManager<ApplicationUser>, AvantiaSignInManager<ApplicationUser>>();

Then you can implement your own SignInManager like the following:

public class AvantiaSignInManager<TUser> : SignInManager<TUser> where TUser : class

You will have to implement the CreateUserPrincipalAsync method like the following:

public override async Task<ClaimsPrincipal> CreateUserPrincipalAsync(TUser user) {
  var Principal = await base.CreateUserPrincipalAsync(user);
  var Identity = (ClaimsIdentity)Principal.Identity;

  // How To: Here is where you can add Custom/On the fly Claims
  // They would not be persisted in the database but are within the Cookie

  var Employee = _dataContext.Employees
    .Include(x => x.Tenant)
    .ThenInclude(x => x.Subscriber)
    .Where(x => x.Email == Identity.Name)
    .SingleOrDefault();

  // See if there are any Claims linked to this user
  var MyClaims = _dataContext.EmployeeRoleClaims
    .Where(x => x.EmployeeID == Employee.ID)
    .Select(x => x.RoleClaim)
    .ToList();

  if (Employee != null) {
    // Add common Claims for every user, but the values are unique to them
    Identity.AddClaim(new Claim(Constants.Claims.Employee.ID, Employee.ID.ToString()));
    Identity.AddClaim(new Claim(Constants.Claims.Employee.Number, Employee.Number));
    Identity.AddClaim(new Claim(Constants.Claims.Tenant.ID, Employee.TenantID.ToString()));
    Identity.AddClaim(new Claim(Constants.Claims.Tenant.Name, Employee?.Tenant.Name));
    Identity.AddClaim(new Claim(Constants.Claims.Subscriber.ID, Employee?.Tenant.SubscriberID.ToString()));
    Identity.AddClaim(new Claim(Constants.Claims.Subscriber.Name, Employee?.Tenant?.Subscriber.Name));

    // Add any special Claims - May not be necessary within your application
    foreach (var rc in MyClaims) {
      Identity.AddClaim(rc.ToClaim()); // Add the Claim normally

      if ((rc.ClaimType == Constants.Claims.Subscriber.Administrator) ||
        (rc.ClaimType == Constants.Claims.Subscriber.TimeSheetAdmin) ||
        (rc.ClaimType == Constants.Claims.Subscriber.TimeSheetReview)) {
        var myTenants = _dataContext.Tenants.Where(x => x.SubscriberID == Convert.ToInt64(rc.ClaimValue)).ToList();

        foreach (var t in myTenants) {
          if (rc.ClaimType == Constants.Claims.Subscriber.Administrator)
            Identity.AddClaim(new Claim(Constants.Claims.Tenant.Administrator, t.ID.ToString()));
          else if (rc.ClaimType == Constants.Claims.Subscriber.TimeSheetAdmin)
            Identity.AddClaim(new Claim(Constants.Claims.Tenant.TimeSheetAdmin, t.ID.ToString()));
          else if (rc.ClaimType == Constants.Claims.Subscriber.TimeSheetReview)
            Identity.AddClaim(new Claim(Constants.Claims.Tenant.TimeSheetReview, t.ID.ToString()));
        } // foreach of the Tenants within the Subscription
      } // if I am the Administrator of a Subscription, I should also get the Tenants as well
    } // foreach of the Claims that have been specifically assinged to me

    // Add Claims for each of the Projects I am a Manager of or a Member of
    var PM = _dataContext.ProjectRoles.Where(x => x.Name == "Project Manager").FirstOrDefault();

    if (PM != null) {
      // Get the Projects where I am the Project Manager
      var MyPMProjects = _dataContext.ProjectProjectRoleEmployees.Where(x => x.EmployeeID == Employee.ID && x.ProjectRoleID == PM.ID).ToList();

      foreach(var Project in MyPMProjects)
        Identity.AddClaim(new Claim(Constants.Claims.Project.ManagerOf, Project.ProjectID.ToString()));

      // Get the Projects that I am ON but am NOT the Project Manager
      var MyProjects = _dataContext.ProjectProjectRoleEmployees.Where(x => x.EmployeeID == Employee.ID && x.ProjectRoleID != PM.ID).ToList();

      foreach (var Project in MyProjects)
        Identity.AddClaim(new Claim(Constants.Claims.Project.MemberOf, Project.ProjectID.ToString()));
    } // if we found the Project Manager Role
  } // if we found the associated Employee record

  return Principal;
}

I then created a BaseController that overrides the default Controller class as such:

public class BaseController : Controller {

  internal ILogger logger;

  public string UsersLoginName => User.Identity.Name;
  public long UsersEmployeeID => User.HasClaim(x => x.Type == Constants.Claims.Employee.ID) ? Convert.ToInt64(User.FindFirst(Constants.Claims.Employee.ID).Value) : 0;
  public long UsersTenantID => User.HasClaim(x => x.Type == Constants.Claims.Tenant.ID) ? Convert.ToInt64(User.FindFirst(Constants.Claims.Tenant.ID).Value) : 0;
  public long UsersSubscriberID => User.HasClaim(x => x.Type == Constants.Claims.Subscriber.ID) ? Convert.ToInt64(User.FindFirst(Constants.Claims.Subscriber.ID).Value) : 0;

}

This would allow me to, from any xxxController inheriting from my BaseController to do things like:

model.EmployeeID = UsersEmployeeID;

I realize it has been months since you asked this question, but for you and anyone coming to this after the fact, hope it helps out.


问:
I'm getting warning on LineRenderer SetWidth that it's obsolete how should i fix it?
```<code>lineRenderer.SetWidth(startWidth, endWidth);
lineRenderer.SetVertexCount(linePoints.Count);
</code>```

On both lines same warning:

'LineRenderer.SetVertexCount(int)' is obsolete: 'SetVertexCount has been deprecated. Please use the numPositions property instead.'

And

'LineRenderer.SetWidth(float, float)' is obsolete: 'SetWidth has been deprecated. Please use the startWidth, endWidth, or widthCurve properties instead.'

I tried this then:

```<code>lineRenderer.startWidth(startWidth, endWidth);
</code>```

But then getting error on startWidth property:

'LineRenderer.startWidth' cannot be used like a method.

答:
Some of the LineRenderer functions has been changed to properties and also renamed to avoid confusion. You set properties not call it as a function. For lineRenderer.SetVertexCount, you use lineRenderer.positionCount to set that.

```<code>lineRenderer.startWidth = startWidth;
lineRenderer.endWidth = endWidth;
lineRenderer.positionCount = linePoints.Count;
</code>```

Body:
lineRenderer.SetWidth(startWidth, endWidth);
lineRenderer.SetVertexCount(linePoints.Count);

On both lines same warning:

'LineRenderer.SetVertexCount(int)' is obsolete: 'SetVertexCount has been deprecated. Please use the numPositions property instead.'

And

'LineRenderer.SetWidth(float, float)' is obsolete: 'SetWidth has been deprecated. Please use the startWidth, endWidth, or widthCurve properties instead.'

I tried this then:

lineRenderer.startWidth(startWidth, endWidth);

But then getting error on startWidth property:

'LineRenderer.startWidth' cannot be used like a method.

Body:
Some of the LineRenderer functions has been changed to properties and also renamed to avoid confusion. You set properties not call it as a function. For lineRenderer.SetVertexCount, you use lineRenderer.positionCount to set that.

lineRenderer.startWidth = startWidth;
lineRenderer.endWidth = endWidth;
lineRenderer.positionCount = linePoints.Count;


问:
Foreign key constraint exception in basic table design
I'm using Entity Framework Core and have a simple 5 table design, but get an error and can't figure out why. What am I missing?

Exception:

Introducing FOREIGN KEY constraint
  'FK_GraphicItems_GraphicUploadTemplateItems_GraphicUploadTemplateItemId'
  on table 'GraphicItems' may cause cycles or multiple cascade paths.
  Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other
  FOREIGN KEY constraints.

Base:

```<code>public abstract class Base
{
    public int Id { get; set; }
    public DateTime DateCreated { get; set; } = DateTime.Now;
}
</code>```

Client:

```<code>public class Client : Base
{
    public Guid Key { get; set; }
    public string Name { get; set; }
}
</code>```

Graphic:

```<code>public class Graphic : Base
{
    public int ClientId { get; set; }
    public virtual Client Client { get; set; }
    public ICollection<GraphicItem> Items { get; set; } = new HashSet<GraphicItem>();
    public ICollection<Tag> Tags { get; set; } = new HashSet<Tag>();
}
</code>```

GraphicItem: (the property GraphicUploadTemplateId causes the exception)

```<code>public class GraphicItem : Base
{
    public int GraphicId { get; set; }
    public virtual Graphic Graphic { get; set; }
    public int GraphicUploadTemplateItemId { get; set; }
    public virtual GraphicUploadTemplateItem UploadTemplateItem { get; set; }
}
</code>```

GraphicUploadTemplate:

```<code>public class GraphicUploadTemplate : Base
{
    public int ClientId { get; set; }
    public virtual Client client { get; set; }
    public ICollection<GraphicUploadTemplateItem> Items { get; set; }
}
</code>```

GraphicUploadTemplateItem:

```<code>public class GraphicUploadTemplateItem : Base
{
    public int GraphicUploadTemplateId { get; set; }
    public virtual GraphicUploadTemplate UploadTemplate { get; set; }
}
</code>```

答:
Fixed the problem by setting the property type to nullable</p>

```<code>public class GraphicItem : Base
{
    public int GraphicId { get; set; }
    public virtual Graphic Graphic { get; set; }
    public int? GraphicUploadTemplateItemId { get; set; }
    public virtual GraphicUploadTemplateItem UploadTemplate { get; set; }
}
</code>```

Body:
I'm using Entity Framework Core and have a simple 5 table design, but get an error and can't figure out why. What am I missing?

Exception:

Introducing FOREIGN KEY constraint
  'FK_GraphicItems_GraphicUploadTemplateItems_GraphicUploadTemplateItemId'
  on table 'GraphicItems' may cause cycles or multiple cascade paths.
  Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other
  FOREIGN KEY constraints.

Base:

public abstract class Base
{
    public int Id { get; set; }
    public DateTime DateCreated { get; set; } = DateTime.Now;
}

Client:

public class Client : Base
{
    public Guid Key { get; set; }
    public string Name { get; set; }
}

Graphic:

public class Graphic : Base
{
    public int ClientId { get; set; }
    public virtual Client Client { get; set; }
    public ICollection<GraphicItem> Items { get; set; } = new HashSet<GraphicItem>();
    public ICollection<Tag> Tags { get; set; } = new HashSet<Tag>();
}

GraphicItem: (the property GraphicUploadTemplateId causes the exception)

public class GraphicItem : Base
{
    public int GraphicId { get; set; }
    public virtual Graphic Graphic { get; set; }
    public int GraphicUploadTemplateItemId { get; set; }
    public virtual GraphicUploadTemplateItem UploadTemplateItem { get; set; }
}

GraphicUploadTemplate:

public class GraphicUploadTemplate : Base
{
    public int ClientId { get; set; }
    public virtual Client client { get; set; }
    public ICollection<GraphicUploadTemplateItem> Items { get; set; }
}

GraphicUploadTemplateItem:

public class GraphicUploadTemplateItem : Base
{
    public int GraphicUploadTemplateId { get; set; }
    public virtual GraphicUploadTemplate UploadTemplate { get; set; }
}

Body:
Fixed the problem by setting the property type to nullable

public class GraphicItem : Base
{
    public int GraphicId { get; set; }
    public virtual Graphic Graphic { get; set; }
    public int? GraphicUploadTemplateItemId { get; set; }
    public virtual GraphicUploadTemplateItem UploadTemplate { get; set; }
}


问:
call multiple functions nodejs
I just started with nodejs and I basically have two functions I want to execute and based on the success of each of those functions, or error of those functions, I want the wrapper function to generate an overall status code.  I looked at the async package and I got it working in the happy path where everything succeeds and my last callback gets a success.  But what if one fails?  I see that the error gets sent to the last callback of async.waterfall, but the second function never gets run since there was an error and I do want to know the results of both functions.  I've tried, series, parallel, and waterfall, and from what I can tell, they all call the final callback once an error is hit.  Is there an idiomatic way to do this in Node? </p>

答:
Given a generic asynchronous function ...

```<code>const double = (x, k) =>
  k (x * 2)

double (1, console.log)
// 1 * 2
// => 2
</code>```

compk

We can compose two asynchronous functions using compk

const double = (x, k) =>
  k (x * 2)

const compk = f => g =>
  (x, k) =>
    f (x, y => g (y, k))

compk (double) (double) (1, console.log)
// (1 * 2) * 2
// 2 * 2
// =>  4```
</div>
</div>
</p>

<p><strong>composek</strong></p>

<p>We can compose N asynchronous functions using <code>composek</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const double = (x, k) =>
  k (x * 2)

const compk = f => g =>
  (x, k) =>
    f (x, y => g (y, k))

const composek = (f, ...fs) =>
  (x, k) =>
    f === undefined
      ? k (x)
      : compk (composek (...fs)) (f) (x, k)

composek (double, double, double, double, double) (1, console.log)
// ((((1 * 2) * 2) * 2) * 2) * 2
// (((2 * 2) * 2) * 2) * 2
// ((4 * 2) * 2) * 2
// (8 * 2) * 2
// 16 * 2
// => 32</code>```

node-style continuation passing style

Node.JS has a convention where it uses error-first continuation passing style. If we want compose node-style cps functions and properly bubble the errors, a little more care needs to be applied

const nodedouble = (x, k) =>
  x > 10
    ? k (Error('cannot double numbers over 10'))
    : k (null, x * 2)

const nodedebug = (err, x) => {
  if (err)
    console.error('Error', err.message)
  else
    console.log(x)
}

nodedouble (2, nodedebug)
// 2 * 2
// => 4

nodedouble (12, nodedebug)
// 12 * 2
// => Error: cannot double numbers over 10```
</div>
</div>
</p>

<p><strong>nodecompk</strong></p>

<p>We can compose two node-style cps functions using <code>nodecompk</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const nodedouble = (x, k) =>
  x > 10
    ? k (Error('cannot double numbers over 10'))
    : k (null, x * 2)

const nodedebug = (err, x) => {
  if (err)
    console.error('Error', err.message)
  else
    console.log(x)
}

const nodecompk = f => g =>
  (x, k) =>
    f (x, (err, y) =>
      err ? k (err) : g (y, (err, z) =>
        err ? k (err) : k (null, z)))

nodecompk (nodedouble) (nodedouble) (1, nodedebug)
// (1 * 2) * 2
// 2 * 2
// => 4

nodecompk (nodedouble) (nodedouble) (6, nodedebug)
// (6 * 2) * 2
// 12 * 2
// => Error: cannot double numbers over 10</code>```

nodecomposek

We can compose N node-style cps functions using nodecomposek

const nodedouble = (x, k) =>
  x > 10
    ? k (Error('cannot double numbers over 10'))
    : k (null, x * 2)

const nodedebug = (err, x) => {
  if (err)
    console.error('Error', err.message)
  else
    console.log(x)
}

const nodecompk = f => g =>
  (x, k) =>
    f (x, (err, y) =>
      err ? k (err) : g (y, (err, z) =>
        err ? k (err) : k (null, z)))

const nodecomposek = (f,...fs) =>
  (x, k) =>
    f === undefined
      ? k (null, x)
      : nodecompk (nodecomposek (...fs)) (f) (x, k)

nodecomposek (nodedouble, nodedouble, nodedouble) (2, nodedebug)
// ((2 * 2) * 2) * 2
// (4 * 2) * 2
// 8 * 2
// => 16

nodecomposek (nodedouble, nodedouble, nodedouble) (8, nodedebug)
// ((8 * 2) * 2) * 2
// (16 * 2) * 12
// => Error cannot double numbers over 10```

Title: call multiple functions nodejs

Body:
Given a generic asynchronous function ...

const double = (x, k) =>
  k (x * 2)

double (1, console.log)
// 1 * 2
// => 2

compk

We can compose two asynchronous functions using compk

const double = (x, k) =>
  k (x * 2)

const compk = f => g =>
  (x, k) =>
    f (x, y => g (y, k))

compk (double) (double) (1, console.log)
// (1 * 2) * 2
// 2 * 2
// =>  4

composek

We can compose N asynchronous functions using composek

const double = (x, k) =>
  k (x * 2)

const compk = f => g =>
  (x, k) =>
    f (x, y => g (y, k))

const composek = (f, ...fs) =>
  (x, k) =>
    f === undefined
      ? k (x)
      : compk (composek (...fs)) (f) (x, k)

composek (double, double, double, double, double) (1, console.log)
// ((((1 * 2) * 2) * 2) * 2) * 2
// (((2 * 2) * 2) * 2) * 2
// ((4 * 2) * 2) * 2
// (8 * 2) * 2
// 16 * 2
// => 32

node-style continuation passing style

Node.JS has a convention where it uses error-first continuation passing style. If we want compose node-style cps functions and properly bubble the errors, a little more care needs to be applied

const nodedouble = (x, k) =>
  x > 10
    ? k (Error('cannot double numbers over 10'))
    : k (null, x * 2)

const nodedebug = (err, x) => {
  if (err)
    console.error('Error', err.message)
  else
    console.log(x)
}

nodedouble (2, nodedebug)
// 2 * 2
// => 4

nodedouble (12, nodedebug)
// 12 * 2
// => Error: cannot double numbers over 10

nodecompk

We can compose two node-style cps functions using nodecompk

const nodedouble = (x, k) =>
  x > 10
    ? k (Error('cannot double numbers over 10'))
    : k (null, x * 2)

const nodedebug = (err, x) => {
  if (err)
    console.error('Error', err.message)
  else
    console.log(x)
}

const nodecompk = f => g =>
  (x, k) =>
    f (x, (err, y) =>
      err ? k (err) : g (y, (err, z) =>
        err ? k (err) : k (null, z)))

nodecompk (nodedouble) (nodedouble) (1, nodedebug)
// (1 * 2) * 2
// 2 * 2
// => 4

nodecompk (nodedouble) (nodedouble) (6, nodedebug)
// (6 * 2) * 2
// 12 * 2
// => Error: cannot double numbers over 10

nodecomposek

We can compose N node-style cps functions using nodecomposek

const nodedouble = (x, k) =>
  x > 10
    ? k (Error('cannot double numbers over 10'))
    : k (null, x * 2)

const nodedebug = (err, x) => {
  if (err)
    console.error('Error', err.message)
  else
    console.log(x)
}

const nodecompk = f => g =>
  (x, k) =>
    f (x, (err, y) =>
      err ? k (err) : g (y, (err, z) =>
        err ? k (err) : k (null, z)))

const nodecomposek = (f,...fs) =>
  (x, k) =>
    f === undefined
      ? k (null, x)
      : nodecompk (nodecomposek (...fs)) (f) (x, k)

nodecomposek (nodedouble, nodedouble, nodedouble) (2, nodedebug)
// ((2 * 2) * 2) * 2
// (4 * 2) * 2
// 8 * 2
// => 16

nodecomposek (nodedouble, nodedouble, nodedouble) (8, nodedebug)
// ((8 * 2) * 2) * 2
// (16 * 2) * 12
// => Error cannot double numbers over 10


问:
nodejs app receive data from post and render to html
I'm just starting to use node.js and I can't quite understand few things. So please don't be mean. I tried to search the web without much results.

I want one webpage to go on wait for a post and then render the data received.
so far I was have the following app.js

```<code>    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    app.use(bodyParser.json()); // for parsing application/json
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing
    application/x-www-form-urlencoded

    app.set('view engine', 'pug');

    app.get('/', function (req, res) {
     res.render('index', {title: 'GET test',message : 'GET test'});
    });

    var data = "";

    app.post("/",function(req, res) {

    console.log(req.method);
    console.log(req.headers);
    console.log(req.url);
    data=req.body
    console.log(data);
    res.render('index', {title: 'POST test',message : 'POST test'});

    });

    app.listen(8081, function () {
      console.log('Example app listening on port 8081!');
    });
</code>```

in views/index.pug I have

```<code>    html
     head
      title = title
     body
      h1 = message
</code>```

And whenever I trigger curl --data "field=value" http://127.0.0.1:8081/
I can see the post received inside the terminal but I can't understend how to render this data in a page.

答:
It looks as if you're not passing data into the res.render method.

```<code>console.log(data);
res.render('index', {title: 'POST test',message : 'POST test', postData: data});

html
 head
  title = title
 body
  h1 = message
  span = postData.field
</code>```

^ This is under the assumption "field" is present in the post body, in practice you'd want to do this in a more dynamic fashion and make sure it exists.

Body:
I'm just starting to use node.js and I can't quite understand few things. So please don't be mean. I tried to search the web without much results.

I want one webpage to go on wait for a post and then render the data received.
so far I was have the following app.js

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    app.use(bodyParser.json()); // for parsing application/json
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing
    application/x-www-form-urlencoded

    app.set('view engine', 'pug');

    app.get('/', function (req, res) {
     res.render('index', {title: 'GET test',message : 'GET test'});
    });

    var data = "";

    app.post("/",function(req, res) {

    console.log(req.method);
    console.log(req.headers);
    console.log(req.url);
    data=req.body
    console.log(data);
    res.render('index', {title: 'POST test',message : 'POST test'});

    });

    app.listen(8081, function () {
      console.log('Example app listening on port 8081!');
    });

in views/index.pug I have

    html
     head
      title = title
     body
      h1 = message

And whenever I trigger curl --data "field=value" http://127.0.0.1:8081/
I can see the post received inside the terminal but I can't understend how to render this data in a page.

Body:
It looks as if you're not passing data into the res.render method.

console.log(data);
res.render('index', {title: 'POST test',message : 'POST test', postData: data});

html
 head
  title = title
 body
  h1 = message
  span = postData.field

^ This is under the assumption "field" is present in the post body, in practice you'd want to do this in a more dynamic fashion and make sure it exists.


问:
How do I adjust the transparency (alpha) of a button in Swift?
My button is flButton but when I try to set the alpha to 0, it gives me the error

Value of type '(Any) -> () has no member alpha".

Do I have to replace Any in the @IBAction line?

```<code>import UIKit

class FirstLaunchView: UIViewController {

    @IBOutlet weak var logo1: UIImageView!
    @IBOutlet weak var smiley1: UIImageView!
    @IBOutlet weak var subHapp1: UILabel!
    @IBOutlet weak var happ1: UILabel!
    @IBAction func flButton(_ sender: Any) {

        UserDefaults.standard.set(false, forKey: "name")
        //launchDetector = false

        performSegue(withIdentifier: "toMain", sender: self)
    }

    @IBOutlet weak var firstLaunch: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        logo1.alpha = 0
        smiley1.alpha = 0
        subHapp1.alpha = 0
        happ1.alpha = 0
        flButton.alpha = 0
    }
</code>```

答:
Most simple way is what Rashwan L suggested , create an outlet just like logo1,smiley1 like this.

```<code>@IBOutlet weak var flButton: UIButton!
</code>```

after that you can easily change your color by

```<code>flButton.alpha = 0
</code>```

Body:
My button is flButton but when I try to set the alpha to 0, it gives me the error

Value of type '(Any) -> () has no member alpha".

Do I have to replace Any in the @IBAction line?

import UIKit

class FirstLaunchView: UIViewController {

    @IBOutlet weak var logo1: UIImageView!
    @IBOutlet weak var smiley1: UIImageView!
    @IBOutlet weak var subHapp1: UILabel!
    @IBOutlet weak var happ1: UILabel!
    @IBAction func flButton(_ sender: Any) {

        UserDefaults.standard.set(false, forKey: "name")
        //launchDetector = false

        performSegue(withIdentifier: "toMain", sender: self)
    }

    @IBOutlet weak var firstLaunch: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        logo1.alpha = 0
        smiley1.alpha = 0
        subHapp1.alpha = 0
        happ1.alpha = 0
        flButton.alpha = 0
    }

Body:
Most simple way is what Rashwan L suggested , create an outlet just like logo1,smiley1 like this.

@IBOutlet weak var flButton: UIButton!

after that you can easily change your color by

flButton.alpha = 0


问:
How to pass the video id in main page to another page like youtube?
This is what in the main_page.html:

After clicked this image, the hidden form will be filled and use GET to video.php

```<code> <!-- hidden form -->
    <form id="openVideoPlayerForm" action="player.php" method="get">
        <input id="form-video-id" tpye="text" name="videoID" value="" hidden />
    </form>
</code>```

In video.php, I first make GET data into JSON and call initPage() -> js function to assign the video id attribute in youtube embed.

$video = $_GET['videoID'];

function initPage(){
  var videoID = <?php echo json_encode($videoID) ?>;
  var videoPath = 'https://www.youtube.com/embed/' + videoID + 'rel=0&showinfo=0';
  $('#video-player').attr('src' , videoPath);
}

The question is

1.

this is not work if I use php variable into js function (It is because I am using php 7.1 ?)

var videoID = <?php echo json_encode($videoID) ?>;

2.

I used this method to implement this "clone youtube" is it a best way?

Should I use ajax to implement this function?

If yes how to do.

image for description

答:
Here is a quick and basic layout of what you should have</p>

```<code><?php
$video = $_GET['videoID'];
?>
<!DOCTYPE html>
<html>
<body>
<script>
function initPage(){
  var videoID = ''+<?php echo $video ?>+'';
  var videoPath = 'https://www.youtube.com/embed/' + videoID + 'rel=0&showinfo=0';
  $('#video-player').attr('src' , videoPath);
}
</script>

..... your other content and code.....

</body>
</html>
</code>```

Body:
This is what in the main_page.html:

After clicked this image, the hidden form will be filled and use GET to video.php

    <form id="openVideoPlayerForm" action="player.php" method="get">
        <input id="form-video-id" tpye="text" name="videoID" value="" hidden />
    </form>

In video.php, I first make GET data into JSON and call initPage() -> js function to assign the video id attribute in youtube embed.

$video = $_GET['videoID'];

function initPage(){
  var videoID = <?php echo json_encode($videoID) ?>;
  var videoPath = 'https://www.youtube.com/embed/' + videoID + 'rel=0&showinfo=0';
  $('#video-player').attr('src' , videoPath);
}

The question is

1.

this is not work if I use php variable into js function (It is because I am using php 7.1 ?)

var videoID = <?php echo json_encode($videoID) ?>;

2.

I used this method to implement this "clone youtube" is it a best way?

Should I use ajax to implement this function?

If yes how to do.

image for description

Body:
Here is a quick and basic layout of what you should have

<?php
$video = $_GET['videoID'];
?>
<!DOCTYPE html>
<html>
<body>
<script>
function initPage(){
  var videoID = ''+<?php echo $video ?>+'';
  var videoPath = 'https://www.youtube.com/embed/' + videoID + 'rel=0&amp;showinfo=0';
  $('#video-player').attr('src' , videoPath);
}
</script>

..... your other content and code.....

</body>
</html>


问:
Android: How to perform Url Request via Wifi
is there a possiblity to explicitely use the wifi connection for doing Http Url requests?
In fact i just need to know if an internet connection (access to google.com for example) is possible via wifi.
(not via 2g / 3g / ..)</p>

答:
I havent done this, so i'm not sure, but I found this looking through the documentation.

```<code>public boolean wifiAvailable() {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connMgr.getActiveNetworkInfo();
        if((info.isAvailable() && info.isConnected() && (info.getType()==ConnectivityManager.TYPE_WIFI))) return true;
        return false;
    }
</code>```

Where you are going to fire a request, evaluate this method, if it returns true the system will automatically use WiFi, android will always use wifi over 3G/2G when available AFAIK.

ContentLicense: CC BY-SA 2.5

Body:
I havent done this, so i'm not sure, but I found this looking through the documentation.

public boolean wifiAvailable() {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connMgr.getActiveNetworkInfo();
        if((info.isAvailable() && info.isConnected() && (info.getType()==ConnectivityManager.TYPE_WIFI))) return true;
        return false;
    }

Where you are going to fire a request, evaluate this method, if it returns true the system will automatically use WiFi, android will always use wifi over 3G/2G when available AFAIK.


问:
Jquery toggle not working when toggling back
I am using jquery toggle, to show one image and then when the user clicks on an element, change to another image and if they click again show the original image. Like an open close kind of thing. It works when I first click, but nothing after that. Here is my jquery

```<code> $(".filterInventory").on("click", function () {

    $(".inventory-search").toggle();
    $(".filer-arrow.down").hide();
    $(".filer-arrow.up").show();

    return false;

});
</code>```

and here is the HTML

```<code><div class="container container-padding-top inventory-search-button">
        <div class="row">
            <div class="col-md-12">
                <a href="#" class="filterInventory">Filter <img src="~/Images/icons/down-arrow-white.png" class="filer-arrow down" alt="Filter Arrow" /><img src="~/Images/icons/up-arrow-white.png" class="filer-arrow up" alt="Filter Arrow" /></a>
            </div>
        </div>
    </div>
</code>```

CSS:

```<code>#communities a.filterInventory img.up {
    display: none;
}

#communities .filterInventory .filer-arrow {
    height: 10px;
}
</code>```

答:
Since one of your images is already hidden (assuming from your css you have a #communities element around the html) you can simply toggle them. Instead of targeting the img elements like another answer, this one selects all elements by class:</p>

```<code>$(".filterInventory").on("click", function () {

    $(".filer-arrow.down, .filer-arrow.up, .inventory-search").toggle();
    return false;
});
</code>```

Body:
I am using jquery toggle, to show one image and then when the user clicks on an element, change to another image and if they click again show the original image. Like an open close kind of thing. It works when I first click, but nothing after that. Here is my jquery

 $(".filterInventory").on("click", function () {

    $(".inventory-search").toggle();
    $(".filer-arrow.down").hide();
    $(".filer-arrow.up").show();

    return false;

});

and here is the HTML

                Filter

CSS:

#communities a.filterInventory img.up {
    display: none;
}

#communities .filterInventory .filer-arrow {
    height: 10px;
}

Body:
Since one of your images is already hidden (assuming from your css you have a #communities element around the html) you can simply toggle them. Instead of targeting the img elements like another answer, this one selects all elements by class:

$(".filterInventory").on("click", function () {

    $(".filer-arrow.down, .filer-arrow.up, .inventory-search").toggle();
    return false;
});


问:
Unknown column in where clause with CASE
What is the wrong here, or missing?

```<code>SELECT CASE WHEN (f_username = '$username' AND table1.code = table2.code) THEN '1'
            ELSE '0'
             END as is_favorite
 FROM (
      SELECT *
        FROM favorites
       WHERE f_username='$username'
         AND code = table2.code
     ) table1
INNER JOIN (
       SELECT *
         FROM groups
        WHERE gname LIKE '%$text%'
     ) table2
</code>```

there error is

Unknown column 'table2.code' in 'where clause'

EDIT

I have two tables (groups / favorites)

groups structure is:
gname / code

favorites structure is:
code / f_username

What am looking for is I want to get list of groups in specific query and I want to loop for each group check the favorites based on username if he added as favorite or not.

答:
What's wrong or missing? You are referring to the table alias name table2 in your first subquery. That alias is not in scope in that subquery, because you only define it as an alias for your second subquery. This is the offending bit of SQL: AND code = table2.code.  The query parser didn't get to your SELECT clause because it tries to figure out what columns it has available first.

Your query has a strange structure. You probably should consider simply joining your tables like this.

```<code>SELECT whatever
  FROM favorites f
  JOIN groups g ON f.code = g.code
 WHERE f.f_username = '$username'
   AND g.gname LIKE '%$text%'
</code>```

But you didn't show any sample data or explain the result you want, so I'm guessing.

ContentLicense: CC BY-SA 4.0

Body:
What is the wrong here, or missing?

SELECT CASE WHEN (f_username = '$username' AND table1.code = table2.code) THEN '1'
            ELSE '0'
             END as is_favorite
 FROM (
      SELECT *
        FROM favorites
       WHERE f_username='$username'
         AND code = table2.code
     ) table1
INNER JOIN (
       SELECT *
         FROM groups
        WHERE gname LIKE '%$text%'
     ) table2

there error is

Unknown column 'table2.code' in 'where clause'

EDIT

I have two tables (groups / favorites)

groups structure is:
gname / code

favorites structure is:
code / f_username

What am looking for is I want to get list of groups in specific query and I want to loop for each group check the favorites based on username if he added as favorite or not.

Body:
What's wrong or missing? You are referring to the table alias name table2 in your first subquery. That alias is not in scope in that subquery, because you only define it as an alias for your second subquery. This is the offending bit of SQL: AND code = table2.code.  The query parser didn't get to your SELECT clause because it tries to figure out what columns it has available first.

Your query has a strange structure. You probably should consider simply joining your tables like this.

SELECT whatever
  FROM favorites f
  JOIN groups g ON f.code = g.code
 WHERE f.f_username = '$username'
   AND g.gname LIKE '%$text%'

But you didn't show any sample data or explain the result you want, so I'm guessing.


问:
How to get the runtime class of a generic type in Scala?
```<code>import scala.reflect.runtime.universe._
import scala.reflect.ClassTag
import scala.reflect.classTag

def getTypeTag[T: TypeTag](obj: T) = println(typeTag[T].tpe)

class Entity
{
    def greet = println("Hello!")
}

class Point[T : TypeTag](val x : T, val y :T) extends Entity

val p = new Point[Int](2,5)
val p2 = new Point[Float](1.0f,-5.0f)
val p3 = new Point[Double](4.0,-7.0)

val path = Array[Entity](p,p2,p3)

path.foreach(getTypeTag(_))
</code>```

This small code snippet writes to stdout

```<code>Helper.this.Entity
Helper.this.Entity
Helper.this.Entity
</code>```

I'd like it to write

```<code>Helper.this.Point[Int]
Helper.this.Point[Float]
Helper.this.Point[Double]
</code>```

I know there are already a lot of question about scala reflection, I read many of them but still haven't understand the difference between TypeTag, Manifest and ClassTag; nor I can get this very basic example to work. Any help would be greatly appreciated.

Thanks in advance

答:
Short, reasonable answer:

You can't. Don't do that. Why do you need that in the first place? You are probably doing it wrong...

Unsatisfactory answer:

```<code>def printType(a: Any) =
  a match {
    case p: Point[_] =>
      val clazz = p.getClass.getName
      val tname = p.x.getClass.getName
      println(s"$clazz[$tname]")
    case _ =>
      println("yolo")
  }

class Entity

class Point[T](val x: T, val y: T) extends Entity

val p = new Point[Int](2,5)
val p2 = new Point[Float](1.0f,-5.0f)
val p3 = new Point[Double](4.0,-7.0)

val path = Array[Entity](p, p2, p3)

path.foreach(printType)
</code>```

Actual answer:

Use shapeless Typeable.

```<code>import shapeless._

val path = p :: p2 :: p3 :: HNil

object printType extends Poly1 {
  implicit def case0[T](implicit t: Typeable[T]) =
    at[T](_ => t.describe)
}

path.map(printType).toList.foreach(println)
</code>```

Body:
import scala.reflect.runtime.universe._
import scala.reflect.ClassTag
import scala.reflect.classTag

def getTypeTag[T: TypeTag](obj: T) = println(typeTag[T].tpe)

class Entity
{
    def greet = println("Hello!")
}

class Point[T : TypeTag](val x : T, val y :T) extends Entity

val p = new Point[Int](2,5)
val p2 = new Point[Float](1.0f,-5.0f)
val p3 = new Point[Double](4.0,-7.0)

val path = Array[Entity](p,p2,p3)

path.foreach(getTypeTag(_))

This small code snippet writes to stdout

Helper.this.Entity
Helper.this.Entity
Helper.this.Entity

I'd like it to write

Helper.this.Point[Int]
Helper.this.Point[Float]
Helper.this.Point[Double]

I know there are already a lot of question about scala reflection, I read many of them but still haven't understand the difference between TypeTag, Manifest and ClassTag; nor I can get this very basic example to work. Any help would be greatly appreciated.

Thanks in advance

Body:
Short, reasonable answer:

You can't. Don't do that. Why do you need that in the first place? You are probably doing it wrong...

Unsatisfactory answer:

def printType(a: Any) =
  a match {
    case p: Point[_] =>
      val clazz = p.getClass.getName
      val tname = p.x.getClass.getName
      println(s"$clazz[$tname]")
    case _ =>
      println("yolo")
  }

class Entity

class Point[T](val x: T, val y: T) extends Entity

val p = new Point[Int](2,5)
val p2 = new Point[Float](1.0f,-5.0f)
val p3 = new Point[Double](4.0,-7.0)

val path = Array[Entity](p, p2, p3)

path.foreach(printType)

Actual answer:

Use shapeless Typeable.

import shapeless._

val path = p :: p2 :: p3 :: HNil

object printType extends Poly1 {
  implicit def case0[T](implicit t: Typeable[T]) =
    at[T](_ => t.describe)
}

path.map(printType).toList.foreach(println)


答:
Just do what the compiler is suggesting.

I.E.:

```<code>lineRenderer.startWidth = startWidth;
lineRenderer.endWidth = endWidth;
lineRenderer.positionCount = linePoints.Count;
</code>```

Title: I'm getting warning on LineRenderer SetWidth that it's obsolete how should i fix it?

Body:
lineRenderer.SetWidth(startWidth, endWidth);
lineRenderer.SetVertexCount(linePoints.Count);

On both lines same warning:

'LineRenderer.SetVertexCount(int)' is obsolete: 'SetVertexCount has been deprecated. Please use the numPositions property instead.'

And

'LineRenderer.SetWidth(float, float)' is obsolete: 'SetWidth has been deprecated. Please use the startWidth, endWidth, or widthCurve properties instead.'

I tried this then:

lineRenderer.startWidth(startWidth, endWidth);

But then getting error on startWidth property:

'LineRenderer.startWidth' cannot be used like a method.

Body:
Just do what the compiler is suggesting.

I.E.:

lineRenderer.startWidth = startWidth;
lineRenderer.endWidth = endWidth;
lineRenderer.positionCount = linePoints.Count;


问:
How to perform bulk insert into SQLServer from one machine to another?
i have running nifi instance in one machine and have SQL Server in another machine.

Here i can try to perform bulk insert operation with bulk insert Query in SQLserver. but i cannot able insert data from  one machine and move it into SQL Server in another machine.

If i run nifi and SQL Server in same machine then i can able to perform bulk insert operation easily.

i have configured GetFile->ReplaceText(BulkInsertQuery)-->PutSQL processors.

I have tried both nifi and sql server in single machine then bulk insert works but not works when both instances in different machines.

I need to get all data's from one machine and write a query to move that data into SQL runs in another machine.

Below query works when nifi and sql server in same machine

```<code>BULK INSERT BI FROM 'C:\Directory\input.csv' WITH (FIRSTROW = 1, ROWTERMINATOR = '\n', FIELDTERMINATOR = ',', ROWS_PER_BATCH = 10000)
</code>```

if i run that query in another machine then it says..,"FileNotFoundError" due to "input.csv" in Host1 machine but runs query in sql server machine (host2)

Can anyone give me suggestion to do this?

答:
The SQL query is being executed on the machine that hosts the SQL Server application. Because the query defines the incoming data with a file system path, the machine that attempts to resolve that path is the SQL machine. The data does not exist at that path, and thus, cannot be loaded. You have a couple options to handle this:

Use NiFi to move the data to a location on the SQL Server instance to be loaded during the SQL query execution. You can use GetFile/PutFTP, or ExecuteStreamCommand with RoboCopy (a Windows analog to rsync) -- this will avoid the cost of bringing the content into NiFi at all.

Use NiFi to ingest the data from the local system into the content repository and then craft a SQL insert statement that reads the actual data rather than providing a file system path.

Body:
i have running nifi instance in one machine and have SQL Server in another machine.

Here i can try to perform bulk insert operation with bulk insert Query in SQLserver. but i cannot able insert data from  one machine and move it into SQL Server in another machine.

If i run nifi and SQL Server in same machine then i can able to perform bulk insert operation easily.

i have configured GetFile->ReplaceText(BulkInsertQuery)-->PutSQL processors.

I have tried both nifi and sql server in single machine then bulk insert works but not works when both instances in different machines.

I need to get all data's from one machine and write a query to move that data into SQL runs in another machine.

Below query works when nifi and sql server in same machine

BULK INSERT BI FROM 'C:\Directory\input.csv' WITH (FIRSTROW = 1, ROWTERMINATOR = '\n', FIELDTERMINATOR = ',', ROWS_PER_BATCH = 10000)

if i run that query in another machine then it says..,"FileNotFoundError" due to "input.csv" in Host1 machine but runs query in sql server machine (host2)

Can anyone give me suggestion to do this?


问:
Angular Cli - How do I rebuild my project
How do I rebuild my project in Angular.  I build it first with ng build, yet cannot perform that command again as it wont let me change the folder.

I get this error message :
EPERM: operation not permitted, lstat

Is there another command such as ng build update ?

答: I faced similar problem in a Windows machine. You need admin privileges to run that command in Windows. Launch command prompt as administrator and rerun the command. It should work.</p>


问:
How can I dynamically divide columns based on n number of columns into different tables in SSRS
I have a query that returns data as below:

```<code>ID      Date            Date_flag
1       10-07/10/2016   1
1       1-06/10/2016    2
1       11-07/11/2016   3
1       12-07/13/2016   4
1       13-07/14/2016   5
2       10-07/10/2016   1
2       11-07/11/2016   2
2       12-07/13/2016   3
2       13-07/14/2016   4
2       14-07/15/2016   5
</code>```

I am creating a matrix in SSRS where Column group is based on Date and Row group is based on ID and data is to count # of rows. So here is my what my data looks like in a SSRS matrix:

```<code>H_Level 10-07/10/2016   1-06/10/2016    11-07/11/2016   12-07/13/2016   13-07/14/2016   14-07/15/2016
1       1               0               1               1               1               0
2       1               1               1               1               1               1
</code>```

Now the problem I am having is that I can only have three columns in one matrix at a time. So my matrix should split to two matrix (in this scenario). I need to make it dynamic because in future I can have more dates which means more columns. How do I make a dynamic matrix and have it break on every 3 columns? When the matrix break I want the header to display again. Is this possible in SSRS?

Body:
I have a query that returns data as below:

ID      Date            Date_flag
1       10-07/10/2016   1
1       1-06/10/2016    2
1       11-07/11/2016   3
1       12-07/13/2016   4
1       13-07/14/2016   5
2       10-07/10/2016   1
2       11-07/11/2016   2
2       12-07/13/2016   3
2       13-07/14/2016   4
2       14-07/15/2016   5

I am creating a matrix in SSRS where Column group is based on Date and Row group is based on ID and data is to count # of rows. So here is my what my data looks like in a SSRS matrix:

H_Level 10-07/10/2016   1-06/10/2016    11-07/11/2016   12-07/13/2016   13-07/14/2016   14-07/15/2016
1       1               0               1               1               1               0
2       1               1               1               1               1               1

Now the problem I am having is that I can only have three columns in one matrix at a time. So my matrix should split to two matrix (in this scenario). I need to make it dynamic because in future I can have more dates which means more columns. How do I make a dynamic matrix and have it break on every 3 columns? When the matrix break I want the header to display again. Is this possible in SSRS?

Body:
You can do pivot like below:

Select * from (
    Select Id, [Date], 1 as Val from YourDates ) a
    pivot (max([Val]) for [date] in ([10-07/10/2016],[1-06/10/2016 ],[11-07/11/2016],[12-07/13/2016],[13-07/14/2016],[14-07/15/2016]) ) p

For dynamic list of columns you can query as below:

declare @cols1 varchar(max)
declare @cols2 varchar(max)
declare @query nvarchar(max)

Select @cols1 = stuff((Select Distinct ','+QuoteName([Date]) from YourDates for xml path('')),1,1,'')
Select @cols2 = stuff((Select Distinct ','+'COALESCE('+QuoteName([Date])+', 0) as ' + QuoteName([Date])  from YourDates for xml path('')),1,1,'')

Select @Query = ' Select Id, ' + @cols2 + ' from (
    Select Id, [Date], 1 as Val from YourDates ) a
    pivot (max([Val]) for [date] in (' + @cols1 + ') ) p'

--Select @Query
exec sp_executesql @Query

Output as below

+----+---------------+---------------+---------------+---------------+---------------+---------------+
| Id | 10-07/10/2016 | 1-06/10/2016  | 11-07/11/2016 | 12-07/13/2016 | 13-07/14/2016 | 14-07/15/2016 |
+----+---------------+---------------+---------------+---------------+---------------+---------------+
|  1 |             1 |             1 |             1 |             1 |             1 |             0 |
|  2 |             1 |             0 |             1 |             1 |             1 |             1 |
+----+---------------+---------------+---------------+---------------+---------------+---------------+


问:
why isn't the data from my bundle being sent to the new activity?
For reasons I cannot determine, the name string I am passing to the display activity will not be updated when I change it in the menu setting. I have omitted some excess code but hopefully the concepts are there. In particular, when DisplayName is started, I checked with the debugger and the extras put into the intent do not change from their default values (ie: "John Doe"). I note that when I use the options menu activity to change the name, this change is reflected every time I go back to the options menu. However, when I go to the display screen, the name continues to stay the same.

I am aware that these values are simple enough that they can be kept in static member variables and I wouldn't normally have to deal with the passing of bundles, however I still am curious as to why my code fails to function correctly.

I notice that if I use the menu option to set the name first, then click the display button, the change is reflected. However, after returning to the main screen and changing the name, the display screen continues to keep the same name. This leads me to think that since I press "Back" to return to the main screen from the display activity, then the activity is never killed so it would never change the displayed name. Is this guess correct?

```<code>public class MainScreen extends activity {
  private String mName;
  public static final String EXTRA_NAME = "android.intent.extra.NAME";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mName = "John Doe"

        Button button = (Button) findViewById(R.id.display_button);
        button.setOnClickListener(mDisplayButtonListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, SET_CONTACT_ID, 0, R.string.menu_setName);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case SET_CONTACT_ID:
                Intent intent = new Intent(MainScreen.this, ContactEdit.class);
                intent.putExtra(EXTRA_NAME, mName)
                startActivityForResult(intent, 1);
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            mName = data.getExtras().getString(EXTRA_NAME);
        }
    }

    private OnClickListener mDisplayButtonListener = new OnClickListener() {
      public void onClick(View v) {
        Intent intent = new Intent(MainScreen.this, DisplayName.class);
        intent.putExtra(EXTRA_NAME, mName);
        startActivity(intent);
      }
    };
}

public class ContactEdit extends Activity {
  private EditText mEditName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mEditName = (EditText) findViewById(R.id.editName);
    mEditName.setText(this.getIntent().getExtras().getString(MainScreen.EXTRA_NAME));

    Button button = (Button) findViewById(R.id.submit_select);
    button.setOnClickListener(mSubmitName);
  }

  private OnClickListener mSubmitName = new OnClickListener() {
    @Override
    public void onClick(View v) {
      Intent intent = new Intent();
      mName = mEditName.getText().toString();
      intent.putExtra(MainScreen.EXTRA_NAME, mName);
      setResult(RESULT_OK, intent);
      finish();
    }
  }
}

public class DisplayName extends Activity {
  private String mName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mName = getIntent.getExtras().getString(MainScreen.EXTRA_NAME)
    TextView view = (TextView) findViewById(R.id.name);
    view.setText(mName);
  }
}
</code>```

答:
the name string I am passing to the display activity will not be updated when I change it in the menu setting

In the ContactEdit class:

All you are doing is setting the text of the EditText to what you receive from MainScreen (which is "John Doe"). When you click the button mSubmitName, you send the value of mName (which is not even declared in your example).

To send whatever new value you have enter in the EditText, you will have to retrieve it first:

```<code>   public class ContactEdit extends Activity {
  private EditText mEditName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mEditName = (EditText) findViewById(R.id.editName);
    mEditName.setText(this.getIntent().getExtras().getString(MainScreen.EXTRA_NAME));

    Button button = (Button) findViewById(R.id.submit_select);
    button.setOnClickListener(mSubmitName);
  }

  private OnClickListener mSubmitName = new OnClickListener() {
    @Override
    public void onClick(View v) {
      Intent intent = new Intent();
      intent.putExtra(MainScreen.EXTRA_NAME, mEditName.getText()); // <-- Retrieve the value from the EditText
      setResult(RESULT_OK, intent);
      finish();
    }
  }
}
</code>```

Body:
For reasons I cannot determine, the name string I am passing to the display activity will not be updated when I change it in the menu setting. I have omitted some excess code but hopefully the concepts are there. In particular, when DisplayName is started, I checked with the debugger and the extras put into the intent do not change from their default values (ie: "John Doe"). I note that when I use the options menu activity to change the name, this change is reflected every time I go back to the options menu. However, when I go to the display screen, the name continues to stay the same.

I am aware that these values are simple enough that they can be kept in static member variables and I wouldn't normally have to deal with the passing of bundles, however I still am curious as to why my code fails to function correctly.

I notice that if I use the menu option to set the name first, then click the display button, the change is reflected. However, after returning to the main screen and changing the name, the display screen continues to keep the same name. This leads me to think that since I press "Back" to return to the main screen from the display activity, then the activity is never killed so it would never change the displayed name. Is this guess correct?

public class MainScreen extends activity {
  private String mName;
  public static final String EXTRA_NAME = "android.intent.extra.NAME";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mName = "John Doe"

        Button button = (Button) findViewById(R.id.display_button);
        button.setOnClickListener(mDisplayButtonListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, SET_CONTACT_ID, 0, R.string.menu_setName);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case SET_CONTACT_ID:
                Intent intent = new Intent(MainScreen.this, ContactEdit.class);
                intent.putExtra(EXTRA_NAME, mName)
                startActivityForResult(intent, 1);
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
        {
            mName = data.getExtras().getString(EXTRA_NAME);
        }
    }

    private OnClickListener mDisplayButtonListener = new OnClickListener() {
      public void onClick(View v) {
        Intent intent = new Intent(MainScreen.this, DisplayName.class);
        intent.putExtra(EXTRA_NAME, mName);
        startActivity(intent);
      }
    };
}

public class ContactEdit extends Activity {
  private EditText mEditName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mEditName = (EditText) findViewById(R.id.editName);
    mEditName.setText(this.getIntent().getExtras().getString(MainScreen.EXTRA_NAME));

    Button button = (Button) findViewById(R.id.submit_select);
    button.setOnClickListener(mSubmitName);
  }

  private OnClickListener mSubmitName = new OnClickListener() {
    @Override
    public void onClick(View v) {
      Intent intent = new Intent();
      mName = mEditName.getText().toString();
      intent.putExtra(MainScreen.EXTRA_NAME, mName);
      setResult(RESULT_OK, intent);
      finish();
    }
  }
}

public class DisplayName extends Activity {
  private String mName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mName = getIntent.getExtras().getString(MainScreen.EXTRA_NAME)
    TextView view = (TextView) findViewById(R.id.name);
    view.setText(mName);
  }
}

Body:
the name string I am passing to the display activity will not be updated when I change it in the menu setting

In the ContactEdit class:

All you are doing is setting the text of the EditText to what you receive from MainScreen (which is "John Doe"). When you click the button mSubmitName, you send the value of mName (which is not even declared in your example).

To send whatever new value you have enter in the EditText, you will have to retrieve it first:

   public class ContactEdit extends Activity {
  private EditText mEditName;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mEditName = (EditText) findViewById(R.id.editName);
    mEditName.setText(this.getIntent().getExtras().getString(MainScreen.EXTRA_NAME));

    Button button = (Button) findViewById(R.id.submit_select);
    button.setOnClickListener(mSubmitName);
  }

  private OnClickListener mSubmitName = new OnClickListener() {
    @Override
    public void onClick(View v) {
      Intent intent = new Intent();
      intent.putExtra(MainScreen.EXTRA_NAME, mEditName.getText()); // <-- Retrieve the value from the EditText
      setResult(RESULT_OK, intent);
      finish();
    }
  }
}


问:
Permission denied when installing Tensorflow
I am trying to install TensorFlow by Anaconda(My Python is 3.5.2 edition).

When I run:

```<code>(tensorflow)C:> pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.0.1-cp35-cp35m-win_amd64.whl
</code>```

According to the guide in Tensorflow.org, the following tips emerge:

```<code>Exception:
Traceback (most recent call last):
File "C:\Users\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
File "C:\Users\Anaconda3\lib\site-packages\pip\commands\install.py", line 317, in run
prefix=options.prefix_path,
File "C:Anaconda3\lib\site-packages\pip\req\req_set.py", line 742, in install
**kwargs
File "C:\Users\Anaconda3\lib\site-packages\pip\req\req_install.py", line 831, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "C:\Users\Anaconda3\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
isolated=self.isolated,
File "C:\Users\Anaconda3\lib\site-packages\pip\wheel.py", line 346, in move_wheel_files
clobber(source, lib_dir, True)
File "C:\Users\Anaconda3\lib\site-packages\pip\wheel.py", line 324, in clobber
shutil.copyfile(srcfile, destfile)
File "C:\Users\Anaconda3\lib\shutil.py", line 115, in copyfile
with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Anaconda3\\Lib\\site-packages\\numpy\\core\\multiarray.cp35-win_amd64.pyd'
</code>```

I don't know what causes this error. Can someone help me with that?

答:
I had the same problem on several Windows machines (W7, W8.1 and W10). At last I solved the problem in the same way in all of them:

Uninstall Anaconda

Download Anaconda3-4.2.0 from Anaconda Installer Archive. This version of Anaconda includes Python 3.5.2. TensorFlow only supports version 3.5.x of Python on Windows.Although you can create an environment with version 3.5 of Python, I recommend installing Anaconda 4.2.0

Install Anaconda3-4.2.0 on a different drive than the Windows drive, for example in D:\Programdata\Anaconda3. Although installing on another drive is no longer necessary, better to select to install for all users.

Open an Anaconda Promp with administrator privileges and:

Create a environment named tensorflow by invoking the following command:

conda create -n tensorflow python=3.5

Activate the conda environment by issuing the following command:

activate tensorflow

Install TensorFlow:

conda install -c conda-forge tensorflow

Install Jupyter and Spyder at least, but surely you will need to install scipy too for example:

conda install spyder

conda install jupyter

After that you can check if all is correct by invoking python and trying the next program:

```<code>import tensorflow as tf
hail = tf.constant('Hello World')
session = tf.Session()
print(session.run(hail))
</code>```

Now you can check if Spyder works. Exit from Python, invoke Spyder from Anaconda prompt and try de program.

If you have any problem with iPython, install it on the tensorflow enviroment.

conda install ipython

If you want to update spyder write the following command:

conda update spyder

Remember to launch Spyder from the Anaconda prompt after you have activated the tensorflow enviroment.

I hope it works for you.

Edited: TensorFlow, since version 1.2.0, is compatible with Python 3.6, so you can already install the latest version of Anaconda (4.4.0 | Release Date: May 31, 2017), which incorporates Python 3.6.

Body:
I am trying to install TensorFlow by Anaconda(My Python is 3.5.2 edition).

When I run:

(tensorflow)C:> pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.0.1-cp35-cp35m-win_amd64.whl

According to the guide in Tensorflow.org, the following tips emerge:

Exception:
Traceback (most recent call last):
File "C:\Users\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
File "C:\Users\Anaconda3\lib\site-packages\pip\commands\install.py", line 317, in run
prefix=options.prefix_path,
File "C:Anaconda3\lib\site-packages\pip\req\req_set.py", line 742, in install
**kwargs
File "C:\Users\Anaconda3\lib\site-packages\pip\req\req_install.py", line 831, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "C:\Users\Anaconda3\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
isolated=self.isolated,
File "C:\Users\Anaconda3\lib\site-packages\pip\wheel.py", line 346, in move_wheel_files
clobber(source, lib_dir, True)
File "C:\Users\Anaconda3\lib\site-packages\pip\wheel.py", line 324, in clobber
shutil.copyfile(srcfile, destfile)
File "C:\Users\Anaconda3\lib\shutil.py", line 115, in copyfile
with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Anaconda3\\Lib\\site-packages\\numpy\\core\\multiarray.cp35-win_amd64.pyd'

I don't know what causes this error. Can someone help me with that?

Body:
I had the same problem on several Windows machines (W7, W8.1 and W10). At last I solved the problem in the same way in all of them:

Uninstall Anaconda

Download Anaconda3-4.2.0 from Anaconda Installer Archive. This version of Anaconda includes Python 3.5.2. TensorFlow only supports version 3.5.x of Python on Windows.Although you can create an environment with version 3.5 of Python, I recommend installing Anaconda 4.2.0

Install Anaconda3-4.2.0 on a different drive than the Windows drive, for example in D:\Programdata\Anaconda3. Although installing on another drive is no longer necessary, better to select to install for all users.

Open an Anaconda Promp with administrator privileges and:

Create a environment named tensorflow by invoking the following command:

conda create -n tensorflow python=3.5

Activate the conda environment by issuing the following command:

activate tensorflow

Install TensorFlow:

conda install -c conda-forge tensorflow

Install Jupyter and Spyder at least, but surely you will need to install scipy too for example:

conda install spyder

conda install jupyter

After that you can check if all is correct by invoking python and trying the next program:

import tensorflow as tf
hail = tf.constant('Hello World')
session = tf.Session()
print(session.run(hail))

Now you can check if Spyder works. Exit from Python, invoke Spyder from Anaconda prompt and try de program.

If you have any problem with iPython, install it on the tensorflow enviroment.

conda install ipython

If you want to update spyder write the following command:

conda update spyder

Remember to launch Spyder from the Anaconda prompt after you have activated the tensorflow enviroment.

I hope it works for you.

Edited: TensorFlow, since version 1.2.0, is compatible with Python 3.6, so you can already install the latest version of Anaconda (4.4.0 | Release Date: May 31, 2017), which incorporates Python 3.6.


问:
Vue.js templating and interpolation- not rendering data
I am trying to build a reviews page using Vue.js which will take an array of objects and insert a section on the page for each review in the array. It should also display the corresponding name, rating, review text, etc.

The following code is half-way working. The data is getting set correctly to the Vue and it's building out all the divs on the page, however the interpolation is not working. The divs are empty; the data is not being displayed.

HTML

```<code><div class="reviews-holder" id="review-holder">
    <div v-for="review of reviews" class="review-container">
        <div class="row border-bottom">
            <div class="col-sm-6 col-xs-12">
                <h5>{{ review.name }}</h5>
                <p>Reviewed on {{ review.time }}</p>
            </div>
            <div class="col-sm-6 col-xs-12">
                <div class="pull-right rating rating-header">
                    {{ review.rating }}
                </div>
            </div>
        </div>
        <h4>{{ review.title }}</h4>
        <span class="review-text">{{ review.review }}</span>
    </div>
</code>```

JS

```<code>$(document).ready(function() {
    $.post("/api/getReviews", dto, function(res){
        if (res.ok) {
            console.log("res.res", res.res);

        var reviewsVue = new Vue({
                el: '#review-holder',
                data: {
                  reviews: res.res
                },
                components: {
                  VPaginator: VuePaginator
                },
                methods: {
                  updateResource(data){
                    this.reviews = data
                  }
                }
            })
            console.log('reviewsVue', reviewsVue);
        } else {
            console.log(res);
        }
    });
});
</code>```

And the reviews item (res.res) has this structure(with real data, obviously):

```<code>[{name: , rating: , review: , time: , title:}, {name: , rating: , review: , time: , title:}]
</code>```

答:
The problem is that I'm using SWIG in this application and it uses the same interpolation syntax- {{}}. To avoid this issue, you can set your own custom syntax to the Vue object like so:

```<code>var reviewsVue = new Vue({
    el: '#review-holder',
    data: {
        reviews: reviews
    },
    delimiters: ["((","))"]
});
</code>```

And then the HTML looks like this:

```<code><div class="reviews-holder hidden" id="review-holder">
    <div v-for="review in reviews" class="review-container">
        <div class="row border-bottom">
            <div class="col-sm-6 col-xs-12">
                <h5>((review.name)) </h5>
                <p>Reviewed on ((review.time))</p>
            </div>
            <div class="col-sm-6 col-xs-12">
                <div v-for="star in review.stars"class="pull-right rating rating-header">
                    <span>((star))</span>
                </div>
            </div>
        </div>
        <h4>((review.title))</h4>
        <span class="review-text">((review.review))</span>
    </div>
</div>
</code>```

Body:
I am trying to build a reviews page using Vue.js which will take an array of objects and insert a section on the page for each review in the array. It should also display the corresponding name, rating, review text, etc.

The following code is half-way working. The data is getting set correctly to the Vue and it's building out all the divs on the page, however the interpolation is not working. The divs are empty; the data is not being displayed.

HTML

{{ review.name }}

Reviewed on {{ review.time }}

                    {{ review.rating }}

{{ review.title }}

        {{ review.review }}

JS

$(document).ready(function() {
    $.post("/api/getReviews", dto, function(res){
        if (res.ok) {
            console.log("res.res", res.res);

        var reviewsVue = new Vue({
                el: '#review-holder',
                data: {
                  reviews: res.res
                },
                components: {
                  VPaginator: VuePaginator
                },
                methods: {
                  updateResource(data){
                    this.reviews = data
                  }
                }
            })
            console.log('reviewsVue', reviewsVue);
        } else {
            console.log(res);
        }
    });
});

And the reviews item (res.res) has this structure(with real data, obviously):

[{name: , rating: , review: , time: , title:}, {name: , rating: , review: , time: , title:}]

Body:
The problem is that I'm using SWIG in this application and it uses the same interpolation syntax- {{}}. To avoid this issue, you can set your own custom syntax to the Vue object like so:

var reviewsVue = new Vue({
    el: '#review-holder',
    data: {
        reviews: reviews
    },
    delimiters: ["((","))"]
});

And then the HTML looks like this:

<div class="reviews-holder hidden" id="review-holder">
    <div v-for="review in reviews" class="review-container">
        <div class="row border-bottom">
            <div class="col-sm-6 col-xs-12">
                <h5>((review.name)) </h5>
                <p>Reviewed on ((review.time))</p>
            </div>
            <div class="col-sm-6 col-xs-12">
                <div v-for="star in review.stars"class="pull-right rating rating-header">
                    <span>((star))</span>
                </div>
            </div>
        </div>
        <h4>((review.title))</h4>
        <span class="review-text">((review.review))</span>
    </div>
</div>