问:
SUM of offset cells from an offset results
I need to sum the results of the one highlighted in red which I got from the startRange.Offset(counter, 0) = Application.WorksheetFunction.CountIf(countRange, Cities(city))

The results from the code does not have a fixed location as the listed cities in Column C is different everyday and in every sheet.

The 1st Results of total is from the code:

```<code>Public Sub count()

Dim lastCell As String
Range("C2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(1, 0).Select
ActiveCell.Value = "=counta(C2:" + lastCell + ")"
End Sub
</code>```

The 2nd results of total is from the code:
citiesCount = countRange.Rows.Count .
The problem with this code is that if a city is not listed in my array, it will still count it.

Here is the full code.

```<code>Public Sub B1_Manual_CountLocations()

Dim wb As Workbook
Dim ws As Worksheet
Dim lastCell As String
Dim countRange As Range

count 'Call the function to count the total of cities

Set wb = ThisWorkbook
Set ws = wb.ActiveSheet 'Change as appropriate

Set countRange = ws.Range(Cells(2, "C"),Cells(ws.Range("C2").End(xlDown).Row, "C"))

Dim Cities()
Cities = Array("Armonk", "Bratislava", "Bangalore", "Hong Kong", "Mumbai", Zurich")
Dim city As Long
Dim counter As Long
Dim startRange As Range

Set startRange = ws.Cells(ws.Range("C2").End(xlDown).Row, "C").Offset(2, 0)

counter = 2

Dim citiesCount As Long
citiesCount = ((countRange.Rows.count) - 1) 'new line to hold total number of cities

For city = LBound(Cities) To UBound(Cities)

  If Application.WorksheetFunction.CountIf(countRange, Cities(city)) > 0 Then
startRange.Offset(counter, -1) = Application.WorksheetFunction.CountIf(countRange, Cities(city)) / citiesCount 'new line to calculate proportion of total
startRange.Offset(counter, 0) = Application.WorksheetFunction.CountIf(countRange, Cities(city))
startRange.Offset(counter, 1) = Cities(city)

counter = counter + 1

  End If

Next city
startRange.Offset(counter + 1, 0) = "Total:" & citiesCount 'count the total number of city

End Sub
</code>```

I already checked SUM of offset cells that contain a value but this is not clear to me.

答:
You would need to add perhaps a function to check if the values in the count range exist in your array, if it does then for each match add 1 to your total cities count.

Using a function by Jimmy Pena you would have something like the following:

```<code>Option Explicit

Public Sub B1_Manual_CountLocations()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim countRange As Range
    Dim cell As Range

    Set wb = ThisWorkbook
    Set ws = wb.ActiveSheet                      'Change as appropriate

    Set countRange = ws.Range(ws.Cells(2, "C"), ws.Cells(ws.Range("C2").End(xlDown).Row, "C")) 'explicit worksheet reference

    Dim Cities()
    Cities = Array("Armonk", "Bratislava", "Bangalore", "Hong Kong", "Mumbai", "Zurich")
    Dim city As Long
    Dim counter As Long
    Dim startRange As Range
    Dim citiesCount As Long

    citiesCount = 0

    For Each cell In countRange

        If IsInArray(cell.Value, Cities) Then
            citiesCount = citiesCount + 1
        End If

    Next cell

    Set startRange = ws.Cells(ws.Range("C2").End(xlDown).Row, "C").Offset(2, 0)
    counter = 2

    For city = LBound(Cities) To UBound(Cities)

        If Application.WorksheetFunction.CountIf(countRange, Cities(city)) > 0 Then

            startRange.Offset(counter, -1) = Application.WorksheetFunction.CountIf(countRange, Cities(city)) / citiesCount 'new line to calculate proportion of total
            startRange.Offset(counter, 0) = Application.WorksheetFunction.CountIf(countRange, Cities(city))
            startRange.Offset(counter, 1) = Cities(city)

            counter = counter + 1

        End If

    Next city

    startRange.Offset(counter + 1, 0) = "Total:" & citiesCount 'count the total number of city

End Sub

'https://stackoverflow.com/questions/11109832/how-to-find-if-an-array-contains-a-string

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
</code>```

Body:
I need to sum the results of the one highlighted in red which I got from the startRange.Offset(counter, 0) = Application.WorksheetFunction.CountIf(countRange, Cities(city))

The results from the code does not have a fixed location as the listed cities in Column C is different everyday and in every sheet.

The 1st Results of total is from the code:

Public Sub count()

Dim lastCell As String
Range("C2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(1, 0).Select
ActiveCell.Value = "=counta(C2:" + lastCell + ")"
End Sub

The 2nd results of total is from the code:
citiesCount = countRange.Rows.Count .
The problem with this code is that if a city is not listed in my array, it will still count it.

Here is the full code.

Public Sub B1_Manual_CountLocations()

Dim wb As Workbook
Dim ws As Worksheet
Dim lastCell As String
Dim countRange As Range

count 'Call the function to count the total of cities

Set wb = ThisWorkbook
Set ws = wb.ActiveSheet 'Change as appropriate

Set countRange = ws.Range(Cells(2, "C"),Cells(ws.Range("C2").End(xlDown).Row, "C"))

Dim Cities()
Cities = Array("Armonk", "Bratislava", "Bangalore", "Hong Kong", "Mumbai", Zurich")
Dim city As Long
Dim counter As Long
Dim startRange As Range

Set startRange = ws.Cells(ws.Range("C2").End(xlDown).Row, "C").Offset(2, 0)

counter = 2

Dim citiesCount As Long
citiesCount = ((countRange.Rows.count) - 1) 'new line to hold total number of cities

For city = LBound(Cities) To UBound(Cities)

  If Application.WorksheetFunction.CountIf(countRange, Cities(city)) > 0 Then
startRange.Offset(counter, -1) = Application.WorksheetFunction.CountIf(countRange, Cities(city)) / citiesCount 'new line to calculate proportion of total
startRange.Offset(counter, 0) = Application.WorksheetFunction.CountIf(countRange, Cities(city))
startRange.Offset(counter, 1) = Cities(city)

counter = counter + 1

  End If

Next city
startRange.Offset(counter + 1, 0) = "Total:" & citiesCount 'count the total number of city

End Sub

I already checked SUM of offset cells that contain a value but this is not clear to me.

Body:
You would need to add perhaps a function to check if the values in the count range exist in your array, if it does then for each match add 1 to your total cities count.

Using a function by Jimmy Pena you would have something like the following:

Option Explicit

Public Sub B1_Manual_CountLocations()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim countRange As Range
    Dim cell As Range

    Set wb = ThisWorkbook
    Set ws = wb.ActiveSheet                      'Change as appropriate

    Set countRange = ws.Range(ws.Cells(2, "C"), ws.Cells(ws.Range("C2").End(xlDown).Row, "C")) 'explicit worksheet reference

    Dim Cities()
    Cities = Array("Armonk", "Bratislava", "Bangalore", "Hong Kong", "Mumbai", "Zurich")
    Dim city As Long
    Dim counter As Long
    Dim startRange As Range
    Dim citiesCount As Long

    citiesCount = 0

    For Each cell In countRange

        If IsInArray(cell.Value, Cities) Then
            citiesCount = citiesCount + 1
        End If

    Next cell

    Set startRange = ws.Cells(ws.Range("C2").End(xlDown).Row, "C").Offset(2, 0)
    counter = 2

    For city = LBound(Cities) To UBound(Cities)

        If Application.WorksheetFunction.CountIf(countRange, Cities(city)) > 0 Then

            startRange.Offset(counter, -1) = Application.WorksheetFunction.CountIf(countRange, Cities(city)) / citiesCount 'new line to calculate proportion of total
            startRange.Offset(counter, 0) = Application.WorksheetFunction.CountIf(countRange, Cities(city))
            startRange.Offset(counter, 1) = Cities(city)

            counter = counter + 1

        End If

    Next city

    startRange.Offset(counter + 1, 0) = "Total:" & citiesCount 'count the total number of city

End Sub

'https://stackoverflow.com/questions/11109832/how-to-find-if-an-array-contains-a-string

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function


来源: stackexchange

问:
Error Returning Value From Switch Case?
after coding a custom event in AS3, i've come across a curious problem:

```<code>override public function toString():String
    {
    switch  (type)
            {
            case CHANGE:    return formatToString("HistoryEvent", "type", "action", "name", "data");
            case ABILITY:   return formatToString("HistoryEvent", "type", "undoable", "redoable");
            }
    }
</code>```

the above code returns the following compile-time error:

1170: Function does not return a
  value.

i can remedy the problem easily by adding return null; at the end of the function, but that's redundant and it annoys me that it seems to be the only solution.

why is returning a value from a switch case not seen by the compiler?  is this an issue specific to the AS3 compiler or am i actually attempting something here that is so completely dangerous and adverse that it shadows counterculturists the world over.

答: You have to add default block to your switch statement.Then the compiler won't complain to return value</p>

ContentLicense: CC BY-SA 2.5

Title: Error Returning Value From Switch Case?

Body:
after coding a custom event in AS3, i've come across a curious problem:

override public function toString():String
    {
    switch  (type)
            {
            case CHANGE:    return formatToString("HistoryEvent", "type", "action", "name", "data");
            case ABILITY:   return formatToString("HistoryEvent", "type", "undoable", "redoable");
            }
    }

the above code returns the following compile-time error:

1170: Function does not return a
  value.

i can remedy the problem easily by adding return null; at the end of the function, but that's redundant and it annoys me that it seems to be the only solution.

why is returning a value from a switch case not seen by the compiler?  is this an issue specific to the AS3 compiler or am i actually attempting something here that is so completely dangerous and adverse that it shadows counterculturists the world over.


问:
Is decision logic a client or server side responsibility?
I had some debate with a colleague regard how the logic of add/delete entries should work.

So the problem is that an object has following properties

```<code>{
   foo: []
}
</code>```

When adding more to the foo list, user can click save

Wherein a REST method is called to add the new entries in the foo property.

So next time the object looks like following

```<code>{
   foo: [1, 2, 3]
}
</code>```

User this time delete 1 and then re-adds it. And click save.
Nothing should happen.

The actual call to REST method occurs when save is clicked.

My colleague, says to simplify things on client side, it should only need to call the REST method which does add. And the REST method should add all the entries again. So he wants the add method to basically remove every entries related to that object and re-add all of them again.

I'm against this because it does unneeded work. I could write logic to check which entry is new. However since this is a business class of application I don't think putting that logic on server side is a good idea because of cost. Instead I think it should be resolved on the client side.

So that the REST method to add does what it does, it adds new entries, and not do two things which are delete all entries and then add all entries.

Examples on call to REST method

```<code>Add
POST: REST/{objectId}?entries=1,2,3
</code>```

Result entries = [1,2,3]

```<code>Remove
DELETE: REST/{objectId}?entries=1
</code>```

Result entries = [2,3]

答:
".. I think it should be resolved on the client side.."

I disagree. The REST service should be a black box and the client doesn't have to be aware of the logic to add or remove items, it's server's responsibility.

ContentLicense: CC BY-SA 3.0

Body:
I had some debate with a colleague regard how the logic of add/delete entries should work.

So the problem is that an object has following properties

{
   foo: []
}

When adding more to the foo list, user can click save

Wherein a REST method is called to add the new entries in the foo property.

So next time the object looks like following

{
   foo: [1, 2, 3]
}

User this time delete 1 and then re-adds it. And click save.
Nothing should happen.

The actual call to REST method occurs when save is clicked.

My colleague, says to simplify things on client side, it should only need to call the REST method which does add. And the REST method should add all the entries again. So he wants the add method to basically remove every entries related to that object and re-add all of them again.

I'm against this because it does unneeded work. I could write logic to check which entry is new. However since this is a business class of application I don't think putting that logic on server side is a good idea because of cost. Instead I think it should be resolved on the client side.

So that the REST method to add does what it does, it adds new entries, and not do two things which are delete all entries and then add all entries.

Examples on call to REST method

Add
POST: REST/{objectId}?entries=1,2,3

Result entries = [1,2,3]

Remove
DELETE: REST/{objectId}?entries=1

Result entries = [2,3]


问:
How to create a class extension in asp.net core?
I want to create my custom service via using userManager. But I don't know how to access to dbContext.

```<code>public static class UserManagerExtensions
{
    public static async Task<IdentityResult> AddProfileAsync(this UserManager<ApplicationUser> userManager, UserProfileModel model)
    {

        // how to access to dbContext here???

        if (await dbContext.SaveChangesAsync() > 0)
        {
            return IdentityResult.Success;
        }

        return IdentityResult.Failed();
    }
}
</code>```

Usage:

```<code>public class UserController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public UserController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IActionResult> Update(UserProfileModel model)
    {
        await _userManager.AddProfileAsync(model);

        return View();
    }
}
</code>```

How to access DbContext class inside a static class?

Thank you!

答:
You should inject it into your controller and then pass it to your method:

```<code>public class UserController : Controller
{
    private readonly DbContext _dbContext;
    private readonly UserManager<ApplicationUser> _userManager;

    public UserController(DbContext dbContext, UserManager<ApplicationUser> userManager)
    {
        _dbContext = dbContext;
        _userManager = userManager;
    }

    public async Task<IActionResult> Update(UserProfileModel model)
    {
        await _userManager.AddProfileAsync(_dbContext, model);

        return View();
    }
}
</code>```

That way, you have full control over where there database context comes from and with what kind of lifetime it exists.

If your goal is to actually create a service as you say, you should do so and not work with extension methods at all. You could do this:

```<code>public class UserController : Controller
{
    private readonly ProfileService _profileService;

    public UserController(ProfileService profileService)
    {
        _profileService = profileService;
    }

    public async Task<IActionResult> Update(UserProfileModel model)
    {
        await _profileService.AddProfileAsync(model);
        return View();
    }
}

public class ProfileService
{
    private readonly DbContext _dbContext;
    private readonly UserManager<ApplicationUser> _userManager;

    public ProfileService(DbContext dbContext, UserManager<ApplicationUser> userManager)
    {
        _dbContext = dbContext;
        _userManager = userManager;
    }

    public async Task<IdentityResult> AddProfileAsync(UserProfileModel model)
    {
        // do stuff
        if (await dbContext.SaveChangesAsync() > 0)
        {
            return IdentityResult.Success;
        }
        return IdentityResult.Failed();
    }
}
</code>```

And don’t forget to register your service in Startup.ConfigureServices using:

```<code>services.AddTransient<ProfileService>();
</code>```

That way, you now have an actual service which has clear dependencies and which you can test properly, and you are also moving more logic out of your controllers which makes it easier to reason about it.

Body:
I want to create my custom service via using userManager. But I don't know how to access to dbContext.

public static class UserManagerExtensions
{
    public static async Task<IdentityResult> AddProfileAsync(this UserManager<ApplicationUser> userManager, UserProfileModel model)
    {

        // how to access to dbContext here???

        if (await dbContext.SaveChangesAsync() > 0)
        {
            return IdentityResult.Success;
        }

        return IdentityResult.Failed();
    }
}

Usage:

public class UserController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public UserController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IActionResult> Update(UserProfileModel model)
    {
        await _userManager.AddProfileAsync(model);

        return View();
    }
}

How to access DbContext class inside a static class?

Thank you!

Body:
You should inject it into your controller and then pass it to your method:

public class UserController : Controller
{
    private readonly DbContext _dbContext;
    private readonly UserManager<ApplicationUser> _userManager;

    public UserController(DbContext dbContext, UserManager<ApplicationUser> userManager)
    {
        _dbContext = dbContext;
        _userManager = userManager;
    }

    public async Task<IActionResult> Update(UserProfileModel model)
    {
        await _userManager.AddProfileAsync(_dbContext, model);

        return View();
    }
}

That way, you have full control over where there database context comes from and with what kind of lifetime it exists.

If your goal is to actually create a service as you say, you should do so and not work with extension methods at all. You could do this:

public class UserController : Controller
{
    private readonly ProfileService _profileService;

    public UserController(ProfileService profileService)
    {
        _profileService = profileService;
    }

    public async Task<IActionResult> Update(UserProfileModel model)
    {
        await _profileService.AddProfileAsync(model);
        return View();
    }
}

public class ProfileService
{
    private readonly DbContext _dbContext;
    private readonly UserManager<ApplicationUser> _userManager;

    public ProfileService(DbContext dbContext, UserManager<ApplicationUser> userManager)
    {
        _dbContext = dbContext;
        _userManager = userManager;
    }

    public async Task<IdentityResult> AddProfileAsync(UserProfileModel model)
    {
        // do stuff
        if (await dbContext.SaveChangesAsync() > 0)
        {
            return IdentityResult.Success;
        }
        return IdentityResult.Failed();
    }
}

And don’t forget to register your service in Startup.ConfigureServices using:

services.AddTransient<ProfileService>();

That way, you now have an actual service which has clear dependencies and which you can test properly, and you are also moving more logic out of your controllers which makes it easier to reason about it.


问:
Can't create ReplicationController for Nginx in Kubernetes
Want to create a ingress controller for k8s. Use nginx ingress sample to do it.

Follow this created nginx-rc.yaml file:

https://github.com/kubernetes/contrib/blob/master/ingress/controllers/nginx/examples/proxy-protocol/nginx-rc.yaml

```<code>apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx-ingress-controller
  labels:
    k8s-app: nginx-ingress-lb
spec:
  replicas: 1
  selector:
    k8s-app: nginx-ingress-lb
  template:
    metadata:
      labels:
        k8s-app: nginx-ingress-lb
        name: nginx-ingress-lb
    spec:
      terminationGracePeriodSeconds: 60
      containers:
      - image: gcr.io/google_containers/nginx-ingress-controller:0.8.3
        name: nginx-ingress-lb
        imagePullPolicy: Always
        readinessProbe:
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
        livenessProbe:
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
          initialDelaySeconds: 10
          timeoutSeconds: 1
        # use downward API
        env:
          - name: POD_NAME
            valueFrom:
              fieldRef:
                fieldPath: metadata.name
          - name: POD_NAMESPACE
            valueFrom:
              fieldRef:
                fieldPath: metadata.namespace
        ports:
        - containerPort: 80
        - containerPort: 443
        args:
        - /nginx-ingress-controller
        - --default-backend-service=$(POD_NAMESPACE)/default-http-backend
        - --nginx-configmap=$(POD_NAMESPACE)/nginx-ingress-controller
</code>```

After created it then k8s shows:

Check from console:

```<code>$ kubectl describe pod nginx-ingress-controller-5wxch
Name:           nginx-ingress-controller-5wxch
Namespace:      default
Node:           minikube/192.168.99.100
Start Time:     Fri, 17 Nov 2017 15:50:33 +0900
Labels:         k8s-app=nginx-ingress-lb
                name=nginx-ingress-lb
Annotations:    kubernetes.io/created-by={"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"ReplicationController","namespace":"default","name":"nginx-ingress-controller","uid":"9c1aba15-cb63-11e7-9...
Status:         Running
IP:             172.17.0.15
Created By:     ReplicationController/nginx-ingress-controller
Controlled By:  ReplicationController/nginx-ingress-controller
Containers:
  nginx-ingress-lb:
    Container ID:  docker://9fabc8d7f74b442c35ac5f443e7f35117b183e61aa37851dfdb5847d90252672
    Image:         gcr.io/google_containers/nginx-ingress-controller:0.8.3
    Image ID:      docker-pullable://gcr.io/google_containers/nginx-ingress-controller@sha256:820c338dc22eda7ab6331001da3cccd43b1b7dcd179049d33a62ad6deaef8daf
    Ports:         80/TCP, 443/TCP
    Args:
      /nginx-ingress-controller
      --default-backend-service=$(POD_NAMESPACE)/default-http-backend
      --nginx-configmap=$(POD_NAMESPACE)/nginx-ingress-controller
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    255
      Started:      Fri, 17 Nov 2017 15:52:43 +0900
      Finished:     Fri, 17 Nov 2017 15:52:43 +0900
    Ready:          False
    Restart Count:  4
    Liveness:       http-get http://:10254/healthz delay=10s timeout=1s period=10s #success=1 #failure=3
    Readiness:      http-get http://:10254/healthz delay=0s timeout=1s period=10s #success=1 #failure=3
    Environment:
      POD_NAME:       nginx-ingress-controller-5wxch (v1:metadata.name)
      POD_NAMESPACE:  default (v1:metadata.namespace)
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-0nlh9 (ro)
Conditions:
  Type           Status
  Initialized    True
  Ready          False
  PodScheduled   True
Volumes:
  default-token-0nlh9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-0nlh9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     <none>
Events:
  Type     Reason                 Age               From               Message
  ----     ------                 ----              ----               -------
  Normal   Scheduled              3m                default-scheduler  Successfully assigned nginx-ingress-controller-5wxch to minikube
  Normal   SuccessfulMountVolume  3m                kubelet, minikube  MountVolume.SetUp succeeded for volume "default-token-0nlh9"
  Warning  Unhealthy              2m                kubelet, minikube  Readiness probe failed: Get http://172.17.0.15:10254/healthz: dial tcp 172.17.0.15:10254: getsockopt: connection refused
  Normal   Pulling                1m (x5 over 3m)   kubelet, minikube  pulling image "gcr.io/google_containers/nginx-ingress-controller:0.8.3"
  Normal   Pulled                 1m (x5 over 2m)   kubelet, minikube  Successfully pulled image "gcr.io/google_containers/nginx-ingress-controller:0.8.3"
  Normal   Created                1m (x5 over 2m)   kubelet, minikube  Created container
  Normal   Started                1m (x5 over 2m)   kubelet, minikube  Started container
  Warning  BackOff                0s (x17 over 2m)  kubelet, minikube  Back-off restarting failed container
  Warning  FailedSync             0s (x17 over 2m)  kubelet, minikube  Error syncing pod
</code>```

Now using minikube on Mac. The kubernetes version is:

```<code>$ kubectl version
Client Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.2", GitCommit:"bdaeafa71f6c7c04636251031f93464384d54963", GitTreeState:"clean", BuildDate:"2017-10-24T19:48:57Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"7", GitVersion:"v1.7.5", GitCommit:"17d7182a7ccbb167074be7a87f0a68bd00d58d97", GitTreeState:"clean", BuildDate:"2017-10-06T20:53:14Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}
</code>```

So what's the reason? Does this version can't support the config file, or the config file has outdated?

答:
You can get information with kubectl describe pod xxx, as you did.
And more information with kubectl get pod xxx -o yaml (this pretty much gives you everything the cluster knows about the pod).
And finally, check the pod's logs with kubect logs xxx.

When I reproduce with your manifest yaml file, kubectl get pod xxx shows:

kubectl logs nginx-ingress-controller-test-4mgw7

I1117 08:44:11.650301       1 main.go:94] Using build: https://github.com/bprashanth/contrib.git - git-92b2bac
F1117 08:44:11.703533       1 main.go:121] no service with name default/default-http-backend found: services "default-http-backend" not found

So there you go, you're missing a backend service.

Tip: an easier way to install the ingress nginx controler could be:

helm install ing-nginx-ctrl stable/nginx-ingress

There's an helm chart for it.

Body:
Want to create a ingress controller for k8s. Use nginx ingress sample to do it.

Follow this created nginx-rc.yaml file:

https://github.com/kubernetes/contrib/blob/master/ingress/controllers/nginx/examples/proxy-protocol/nginx-rc.yaml

apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx-ingress-controller
  labels:
    k8s-app: nginx-ingress-lb
spec:
  replicas: 1
  selector:
    k8s-app: nginx-ingress-lb
  template:
    metadata:
      labels:
        k8s-app: nginx-ingress-lb
        name: nginx-ingress-lb
    spec:
      terminationGracePeriodSeconds: 60
      containers:
      - image: gcr.io/google_containers/nginx-ingress-controller:0.8.3
        name: nginx-ingress-lb
        imagePullPolicy: Always
        readinessProbe:
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
        livenessProbe:
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
          initialDelaySeconds: 10
          timeoutSeconds: 1
        # use downward API
        env:
          - name: POD_NAME
            valueFrom:
              fieldRef:
                fieldPath: metadata.name
          - name: POD_NAMESPACE
            valueFrom:
              fieldRef:
                fieldPath: metadata.namespace
        ports:
        - containerPort: 80
        - containerPort: 443
        args:
        - /nginx-ingress-controller
        - --default-backend-service=$(POD_NAMESPACE)/default-http-backend
        - --nginx-configmap=$(POD_NAMESPACE)/nginx-ingress-controller

After created it then k8s shows:

Check from console:

$ kubectl describe pod nginx-ingress-controller-5wxch
Name:           nginx-ingress-controller-5wxch
Namespace:      default
Node:           minikube/192.168.99.100
Start Time:     Fri, 17 Nov 2017 15:50:33 +0900
Labels:         k8s-app=nginx-ingress-lb
                name=nginx-ingress-lb
Annotations:    kubernetes.io/created-by={"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"ReplicationController","namespace":"default","name":"nginx-ingress-controller","uid":"9c1aba15-cb63-11e7-9...
Status:         Running
IP:             172.17.0.15
Created By:     ReplicationController/nginx-ingress-controller
Controlled By:  ReplicationController/nginx-ingress-controller
Containers:
  nginx-ingress-lb:
    Container ID:  docker://9fabc8d7f74b442c35ac5f443e7f35117b183e61aa37851dfdb5847d90252672
    Image:         gcr.io/google_containers/nginx-ingress-controller:0.8.3
    Image ID:      docker-pullable://gcr.io/google_containers/nginx-ingress-controller@sha256:820c338dc22eda7ab6331001da3cccd43b1b7dcd179049d33a62ad6deaef8daf
    Ports:         80/TCP, 443/TCP
    Args:
      /nginx-ingress-controller
      --default-backend-service=$(POD_NAMESPACE)/default-http-backend
      --nginx-configmap=$(POD_NAMESPACE)/nginx-ingress-controller
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    255
      Started:      Fri, 17 Nov 2017 15:52:43 +0900
      Finished:     Fri, 17 Nov 2017 15:52:43 +0900
    Ready:          False
    Restart Count:  4
    Liveness:       http-get http://:10254/healthz delay=10s timeout=1s period=10s #success=1 #failure=3
    Readiness:      http-get http://:10254/healthz delay=0s timeout=1s period=10s #success=1 #failure=3
    Environment:
      POD_NAME:       nginx-ingress-controller-5wxch (v1:metadata.name)
      POD_NAMESPACE:  default (v1:metadata.namespace)
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-0nlh9 (ro)
Conditions:
  Type           Status
  Initialized    True
  Ready          False
  PodScheduled   True
Volumes:
  default-token-0nlh9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-0nlh9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     <none>
Events:
  Type     Reason                 Age               From               Message
  ----     ------                 ----              ----               -------
  Normal   Scheduled              3m                default-scheduler  Successfully assigned nginx-ingress-controller-5wxch to minikube
  Normal   SuccessfulMountVolume  3m                kubelet, minikube  MountVolume.SetUp succeeded for volume "default-token-0nlh9"
  Warning  Unhealthy              2m                kubelet, minikube  Readiness probe failed: Get http://172.17.0.15:10254/healthz: dial tcp 172.17.0.15:10254: getsockopt: connection refused
  Normal   Pulling                1m (x5 over 3m)   kubelet, minikube  pulling image "gcr.io/google_containers/nginx-ingress-controller:0.8.3"
  Normal   Pulled                 1m (x5 over 2m)   kubelet, minikube  Successfully pulled image "gcr.io/google_containers/nginx-ingress-controller:0.8.3"
  Normal   Created                1m (x5 over 2m)   kubelet, minikube  Created container
  Normal   Started                1m (x5 over 2m)   kubelet, minikube  Started container
  Warning  BackOff                0s (x17 over 2m)  kubelet, minikube  Back-off restarting failed container
  Warning  FailedSync             0s (x17 over 2m)  kubelet, minikube  Error syncing pod

Now using minikube on Mac. The kubernetes version is:

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.2", GitCommit:"bdaeafa71f6c7c04636251031f93464384d54963", GitTreeState:"clean", BuildDate:"2017-10-24T19:48:57Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"7", GitVersion:"v1.7.5", GitCommit:"17d7182a7ccbb167074be7a87f0a68bd00d58d97", GitTreeState:"clean", BuildDate:"2017-10-06T20:53:14Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}

So what's the reason? Does this version can't support the config file, or the config file has outdated?


问:
Test string with a string list
I have a list of Id contained in an array :

```<code>var listId: string[] = [];
var newId: boolean;
for (let i in data.chunk) {
    listId.push(data.chunk[i].aliases[0]);
}
</code>```

I then want to test my new Id with this whole list. If my new Id is in the list I want to return a false, and if it is not returned a true.

```<code>for(let i of listId) {
    if(member.userId !== listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }
</code>```

I do not see how to do it .. My proposed solution does not work

答:
Try this</p>

```<code>    if(listId.indexOf(member.userId) !== -1)
     {
      newId = false;
     }else
      {
       newid = true;
      }
</code>```

Title: Test string with a string list

Body:
I have a list of Id contained in an array :

var listId: string[] = [];
var newId: boolean;
for (let i in data.chunk) {
    listId.push(data.chunk[i].aliases[0]);
}

I then want to test my new Id with this whole list. If my new Id is in the list I want to return a false, and if it is not returned a true.

for(let i of listId) {
    if(member.userId !== listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }

I do not see how to do it .. My proposed solution does not work

Body:
Try this

    if(listId.indexOf(member.userId) !== -1)
     {
      newId = false;
     }else
      {
       newid = true;
      }


问:
Do a count and group by weeks or months
I have an object array like this:

```<code>[ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ]
</code>```

Using the momentJS library and pure javascript only (no lodash _groupBy etc), how can I group the results and add together the 'count' to be like this:

Week Grouping: (Monday is start of week)

```<code>[ { date: '2017-11-13', count: 104 }, { date: '2017-11-06', count: 22 }, { date: '2017-10-02', count: 66 } ]
</code>```

Month Grouping: (1st of month is start of month)

```<code>[ { date: '2017-11-01', count: 26 }, { date: '2017-10-01', count: 66 } ]
</code>```

Thank You.

答:
The below code groups by weeks. Get inspired to group by month:

var datas = [ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ];
var groupedByWeek = datas.reduce((m, o) => {
    var monday = getMonday(new Date(o.date));
    var mondayYMD = monday.toISOString().slice(0,10);
    var found = m.find(e => e.date === mondayYMD);
    if (found) {
        found.count += o.count;
    } else {
        o.date = mondayYMD;
        m.push(o);
    }
    return m;
}, []);

console.log(groupedByWeek);

function getMonday(d) {
    var day = d.getDay();
    var diff = d.getDate() - day + (day === 0 ? -6 : 1);
    return new Date(d.setDate(diff));
}```

Title: Do a count and group by weeks or months

Body:
I have an object array like this:

[ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ]

Using the momentJS library and pure javascript only (no lodash _groupBy etc), how can I group the results and add together the 'count' to be like this:

Week Grouping: (Monday is start of week)

[ { date: '2017-11-13', count: 104 }, { date: '2017-11-06', count: 22 }, { date: '2017-10-02', count: 66 } ]

Month Grouping: (1st of month is start of month)

[ { date: '2017-11-01', count: 26 }, { date: '2017-10-01', count: 66 } ]

Thank You.


问:
string split using regex and get data on both side
I am trying to parse  a string as below but not able to get expected output
In value pair there can be {} or [] or () and they may contain \n and = both

Please check key 4

3=dkjashd\n4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA}\n5=112

here output has to be

3=dkjashd

4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA}

5=112

As above key gives wrong result with "\h*\R\s*(?=\d*=)" and \s+(?=\d{1,2}=) both

```<code>        String req="1=A  \n2=B\n3={AAAAAA}\n4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA} \n5=AAAAAA \n6=[10]\n7=[]\n8=[10,11]\n99=0";

        String []str=req.split("\\d{1,2}=");
        Arrays.stream(str).forEach(data-> System.out.println("Data :"+ data));
</code>```

Result:

Data : Data :A

Data :B

Data :{AAAAAA}

Data :{AAAAAA

  Data :45=45  AAAAAA    AAAAAA}

Data :AAAAAA

Data :[10]

Data :[]

Data :[10,11]

Data :0

Expected :

Data :1=A

Data :2=B

Data :3={AAAAAA}

Data :4={AAAAAA 45=45  AAAAAA    AAAAAA}

Data :5=AAAAAA

Data :6=[10]

Data :7=[]

Data :8=[10,11]

Data :99=0

Can anyone help over it.

答:
You can use pattern/matcher to extract the required parts:

```<code>String req="1=A  \n2=B\n3={AAAAAA}\n4={AAAAAA \n AAAAAA  \n AAAAAA} \n5=AAAAAA \n6=[10]\n7=[]\n8=[10,11]\n99=0";
Pattern pattern = Pattern.compile("(\\d+=.*?)\\s");
Matcher matcher = pattern.matcher(req);

while (matcher.find()) {
    System.out.println("Data :"+ matcher.group(1));
}
</code>```

OUTPUT

```<code>Data :1=A
Data :2=B
Data :3={AAAAAA}
Data :4={AAAAAA
Data :5=AAAAAA
Data :6=[10]
Data :7=[]
Data :8=[10,11]
</code>```

Body:
I am trying to parse  a string as below but not able to get expected output
In value pair there can be {} or [] or () and they may contain \n and = both

Please check key 4

3=dkjashd\n4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA}\n5=112

here output has to be

3=dkjashd

4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA}

5=112

As above key gives wrong result with "\h*\R\s*(?=\d*=)" and \s+(?=\d{1,2}=) both

        String req="1=A  \n2=B\n3={AAAAAA}\n4={AAAAAA \n45=45\n AAAAAA  \n AAAAAA} \n5=AAAAAA \n6=[10]\n7=[]\n8=[10,11]\n99=0";

        String []str=req.split("\\d{1,2}=");
        Arrays.stream(str).forEach(data-> System.out.println("Data :"+ data));

Result:

Data : Data :A

Data :B

Data :{AAAAAA}

Data :{AAAAAA

  Data :45=45  AAAAAA    AAAAAA}

Data :AAAAAA

Data :[10]

Data :[]

Data :[10,11]

Data :0

Expected :

Data :1=A

Data :2=B

Data :3={AAAAAA}

Data :4={AAAAAA 45=45  AAAAAA    AAAAAA}

Data :5=AAAAAA

Data :6=[10]

Data :7=[]

Data :8=[10,11]

Data :99=0

Can anyone help over it.

Body:
You can use pattern/matcher to extract the required parts:

String req="1=A  \n2=B\n3={AAAAAA}\n4={AAAAAA \n AAAAAA  \n AAAAAA} \n5=AAAAAA \n6=[10]\n7=[]\n8=[10,11]\n99=0";
Pattern pattern = Pattern.compile("(\\d+=.*?)\\s");
Matcher matcher = pattern.matcher(req);

while (matcher.find()) {
    System.out.println("Data :"+ matcher.group(1));
}

OUTPUT

Data :1=A
Data :2=B
Data :3={AAAAAA}
Data :4={AAAAAA
Data :5=AAAAAA
Data :6=[10]
Data :7=[]
Data :8=[10,11]


问:
How to call external javascript function in angular 5?
I have downloaded a theme from this link. I have to define script and CSS in index.html file.

index.html (body section)

```<code><body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/main.85741bff.js"></script>
  <script type="text/javascript" src="./assets/js/common.js"></script>
</body>
</code>```

I have defind my function in common.js and call it from main.85741bff.js file.

common.js (function)

```<code>document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});
</code>```

The issue is that I am able to call the function while page reloads but can't call the function while content load.

Can anyone help me to resolve this issue? Any help would be appreciated.

答:
In Angular4, 5 project folder, there is .angular-cli.json file.

In file, you will see

```<code>"apps": [
  {
    "scripts": []
  }
]
</code>```

push your external js file path in the array.

ContentLicense: CC BY-SA 4.0

Body:
I have downloaded a theme from this link. I have to define script and CSS in index.html file.

index.html (body section)

  <app-root></app-root>

I have defind my function in common.js and call it from main.85741bff.js file.

common.js (function)

document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});

The issue is that I am able to call the function while page reloads but can't call the function while content load.

Can anyone help me to resolve this issue? Any help would be appreciated.

Body:
In Angular4, 5 project folder, there is .angular-cli.json file.

In file, you will see

"apps": [
  {
    "scripts": []
  }
]

push your external js file path in the array.


问:
Changing the view within the Android Tab Widget
So I have my tab layout working as demonstrated in the Android example:

```<code>super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost();  // The activity TabHost
TabHost.TabSpec spec;  // Resusable TabSpec for each tab
Intent intent;  // Reusable Intent for each tab

// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, ArtistActivity.class);

// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("artists").setIndicator("Artists", res.getDrawable(R.drawable.ic_tab_artists)).setContent(intent);
tabHost.addTab(spec);

// Do the same for the other tabs
intent = new Intent().setClass(this, AlbumsActivity.class);
spec = tabHost.newTabSpec("albums").setIndicator("Albums", res.getDrawable(R.drawable.ic_tab_artists)).setContent(intent);
tabHost.addTab(spec);

intent = new Intent().setClass(this, SongsActivity.class);
spec = tabHost.newTabSpec("songs").setIndicator("Songs", res.getDrawable(R.drawable.ic_tab_artists)).setContent(intent);
tabHost.addTab(spec);
</code>```

Now, in one of the tab's activities I've declared a button and would like to bring in a new view. If I create a new intent it will push a new view and the tabs are gone. Is it possible to switch the currently selected view with a new view?

答:
Yes it is very much possible .. You have to use ActivityGroup for this purpose..

Instead of Adding a activity to a TabHost.. You have to add ActivityGroup..
Each Activity Group is having its Activity..

THis is simple to implement

I have the same issue but got it totaly RESOLVED Check The Following Link

http://ericharlow.blogspot.com/2010/09/experience-multiple-android-activities.html

Its The Solution For Me . Hope It will Help You as Well

Body:
So I have my tab layout working as demonstrated in the Android example:

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost();  // The activity TabHost
TabHost.TabSpec spec;  // Resusable TabSpec for each tab
Intent intent;  // Reusable Intent for each tab

// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, ArtistActivity.class);

// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("artists").setIndicator("Artists", res.getDrawable(R.drawable.ic_tab_artists)).setContent(intent);
tabHost.addTab(spec);

// Do the same for the other tabs
intent = new Intent().setClass(this, AlbumsActivity.class);
spec = tabHost.newTabSpec("albums").setIndicator("Albums", res.getDrawable(R.drawable.ic_tab_artists)).setContent(intent);
tabHost.addTab(spec);

intent = new Intent().setClass(this, SongsActivity.class);
spec = tabHost.newTabSpec("songs").setIndicator("Songs", res.getDrawable(R.drawable.ic_tab_artists)).setContent(intent);
tabHost.addTab(spec);

Now, in one of the tab's activities I've declared a button and would like to bring in a new view. If I create a new intent it will push a new view and the tabs are gone. Is it possible to switch the currently selected view with a new view?


问:
Reference regex when using find and replace in Notepad++
I use this regex ^.*?\K\d+\.\d+\.\d+ to search for the first date on every line in notepad++. It seems to work just fine.

The text I work with looks something like this:

Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

  Nå skal folk få fred, iTromsø, 09.09.2017,  Martin Lægland 31.12.2017 Publisert på nett.

  Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

The search gives me every 09.09.2017, but not 31.12.2017 on the second line. Which is exactly what I want. I then want to replace all the 09.09.2017s so they becomes *09.09.2017*.

How do I reference ^.*?\K\d+\.\d+\.\d+ in the replace field in notepad++? Earlier I have been able to do this with *\1* in the replace field, where \1 references the regex I've used, but that doesn't seem to work now.

答: you could use "$&" instead of \1</p>

Body: you could use "$&" instead of \1


问:
pyyaml load number as decimal
yaml.load loads numbers as Python floats. I cannot find a straightforward way to override this.

Compare json.load, which allows parse_float=Decimal if you want to parse floating point numbers as decimal.Decimals.

Is there any way to accomplish this with PyYAML? Or is this inadvisable by some property of the YAML spec?

答:
You can do something like:

```<code>def decimal_constructor(loader, node):
    value = loader.construct_scalar(node)
    return Decimal(value)

yaml.add_constructor(u'!decimal', decimal_constructor)
</code>```

This allows you to load decimals, but only if they are prefixed with the !decimal tag in the YAML document. However, you can use a custom Resolver to resolve all numbers to !decimal:

```<code>class MyResolver(BaseResolver):
    pass

MyResolver.add_implicit_resolver(
        '!decimal',
        re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
                    |\.[0-9_]+(?:[eE][-+][0-9]+)?
                    |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
                    |[-+]?\.(?:inf|Inf|INF)
                    |\.(?:nan|NaN|NAN))$''', re.X),
        list('-+0123456789.'))
</code>```

You should copy the other implicit resolvers over from the default resolver. Then, you need to define a Loader that uses your resolver.

```<code>class MyLoader(Reader, Scanner, Parser, Composer, SafeConstructor, MyResolver):
    def __init__(self, stream):
        Reader.__init__(self, stream)
        Scanner.__init__(self)
        Parser.__init__(self)
        Composer.__init__(self)
        SafeConstructor.__init__(self)
        MyResolver.__init__(self)
</code>```

Above, we added your constructor to the default loader. Change that line to:

```<code>yaml.add_constructor(u'!decimal', decimal_constructor, MyLoader)
</code>```

Finally, load the YAML using

```<code>yaml.load(stream, MyLoader)
</code>```

Title: pyyaml load number as decimal

Body:
You can do something like:

def decimal_constructor(loader, node):
    value = loader.construct_scalar(node)
    return Decimal(value)

yaml.add_constructor(u'!decimal', decimal_constructor)

This allows you to load decimals, but only if they are prefixed with the !decimal tag in the YAML document. However, you can use a custom Resolver to resolve all numbers to !decimal:

class MyResolver(BaseResolver):
    pass

MyResolver.add_implicit_resolver(
        '!decimal',
        re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?
                    |\.[0-9_]+(?:[eE][-+][0-9]+)?
                    |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
                    |[-+]?\.(?:inf|Inf|INF)
                    |\.(?:nan|NaN|NAN))$''', re.X),
        list('-+0123456789.'))

You should copy the other implicit resolvers over from the default resolver. Then, you need to define a Loader that uses your resolver.

class MyLoader(Reader, Scanner, Parser, Composer, SafeConstructor, MyResolver):
    def __init__(self, stream):
        Reader.__init__(self, stream)
        Scanner.__init__(self)
        Parser.__init__(self)
        Composer.__init__(self)
        SafeConstructor.__init__(self)
        MyResolver.__init__(self)

Above, we added your constructor to the default loader. Change that line to:

yaml.add_constructor(u'!decimal', decimal_constructor, MyLoader)

Finally, load the YAML using

yaml.load(stream, MyLoader)


问:
How to conform a class to a protocol in Swift and can protocol methods be overridden?
Is it necessary to use delegates to conform to a protocol? If yes, can anyone write an example code to show the same? Suppose I have a protocol ABC and I want to create a class for mocking the methods of ABC, how can this be done? I don't have very clear concepts of protocols and delegates. Please explain that too.</p>

答:
Delegates are a design pattern that allows one object to send messages to another object when a specific event happens.

ObjectA does not need to know the exact type of object B. It is
  sufficient for Object A to know just know that object B conforms to
  the FooDelegateProtocol

Comment from Alexander.

Imagine an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action, this can be achieved with the help of delegates!

Mark Moykens explains delegation really good.

Mark Moykens Delegation

For Protocols you can look in the swift documentation, there are plenty of good examples.

Swift Docs Protocols

For your ABC example:

```<code>protocol ABC {
  func exampleFunctionA()
  func examplefunctionB()
}

class ExampleClass: ABC {
  func exampleFunctionA() {
    // your code here
  }

  func examplefunctionB() {
    // your code here
  }

}
</code>```

Body:
Delegates are a design pattern that allows one object to send messages to another object when a specific event happens.

ObjectA does not need to know the exact type of object B. It is
  sufficient for Object A to know just know that object B conforms to
  the FooDelegateProtocol

Comment from Alexander.

Imagine an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action, this can be achieved with the help of delegates!

Mark Moykens explains delegation really good.

Mark Moykens Delegation

For Protocols you can look in the swift documentation, there are plenty of good examples.

Swift Docs Protocols

For your ABC example:

protocol ABC {
  func exampleFunctionA()
  func examplefunctionB()
}

class ExampleClass: ABC {
  func exampleFunctionA() {
    // your code here
  }

  func examplefunctionB() {
    // your code here
  }

}


问:
Why people use the following pattern instead of singleton
I heard that singleton is useful and popular ,but the fact is that I seldom see it appears in open source projects.

Instead,I always see people to use static method.

The following one is an example
link

```<code>public final class IoUtils {

private IoUtils() {
    }

public static boolean copyStream(InputStream is, OutputStream os, CopyListener
......
}

}
</code>```

Singleton Pattern says that just"define a class that has only one instance and provides a global point of access to it".

I think Utils class is suitable to use Singleton because all other classes share to use it.

But Why people nerve use it ?

答:
Singleton design pattern is used when a single object is required to instantiate and all requested object access goes through this particular instance. This object can maintain state if desired.
This type of object is required in logger, printing, etc. functionality because they need to maintain state.

Static Utility class is used when you have a class that is just stateless utility functions. It does not maintain state. An instance of the object is never instantiated.

Body:
I heard that singleton is useful and popular ,but the fact is that I seldom see it appears in open source projects.

Instead,I always see people to use static method.

The following one is an example
link

public final class IoUtils {

private IoUtils() {
    }

public static boolean copyStream(InputStream is, OutputStream os, CopyListener
......
}

}

Singleton Pattern says that just"define a class that has only one instance and provides a global point of access to it".

I think Utils class is suitable to use Singleton because all other classes share to use it.

But Why people nerve use it ?


问:
How to retrieve numeric data as string
This kind question may be asked before, but I can't get my head around it, so I'll appreciate any help.

I have a message box where a type of error that i'm receiving by modbus communication is stored.

```<code>MessageBox.Show(String.Format("Error uploading: {0}", e.ReceivedData[0]));
</code>```

e.ReceivedData[0] is holding the data that I want to show on the message box.
So, it might be 1 2 3 4 5 6 7. Those numbers represent type of operation failure.

However, I want to show the exact error message

```<code>1 - "UR_NOT_ACTIVE",
2 - "UR_OUT_OF_BOUND",
3 - "UR_INVALID_COMMAND"
</code>```

and so on.

My plan was to store it in an enum, but I have no previous experience with c#, so it it more confusing than I thought.

答:
Yes, use an enum:

```<code>public enum OperationFailureType
{
    UR_NOT_ACTIVE = 1,
    UR_OUT_OF_BOUND = 2,
    UR_INVALID_COMMAND = 3
}
</code>```

Now you can use enumValue.ToString to get the text and you can cast it to int to get the number.

```<code>MessageBox.Show($"Error uploading: {e.ReceivedData[0].ToString()}");
</code>```

Presuming ReceivedData is now an array of this enum. If it's just an int[] and you can't change it you can cast it to the OperationFailureType:

```<code>OperationFailureType failureType = (OperationFailureType) e.ReceivedData[0];
MessageBox.Show($"Error uploading: {failureType.ToString()}");
</code>```

Title: How to retrieve numeric data as string

Body:
This kind question may be asked before, but I can't get my head around it, so I'll appreciate any help.

I have a message box where a type of error that i'm receiving by modbus communication is stored.

MessageBox.Show(String.Format("Error uploading: {0}", e.ReceivedData[0]));

e.ReceivedData[0] is holding the data that I want to show on the message box.
So, it might be 1 2 3 4 5 6 7. Those numbers represent type of operation failure.

However, I want to show the exact error message

1 - "UR_NOT_ACTIVE",
2 - "UR_OUT_OF_BOUND",
3 - "UR_INVALID_COMMAND"

and so on.

My plan was to store it in an enum, but I have no previous experience with c#, so it it more confusing than I thought.

Body:
Yes, use an enum:

public enum OperationFailureType
{
    UR_NOT_ACTIVE = 1,
    UR_OUT_OF_BOUND = 2,
    UR_INVALID_COMMAND = 3
}

Now you can use enumValue.ToString to get the text and you can cast it to int to get the number.

MessageBox.Show($"Error uploading: {e.ReceivedData[0].ToString()}");

Presuming ReceivedData is now an array of this enum. If it's just an int[] and you can't change it you can cast it to the OperationFailureType:

OperationFailureType failureType = (OperationFailureType) e.ReceivedData[0];
MessageBox.Show($"Error uploading: {failureType.ToString()}");


问:
Bigcommerce - disable add to cart redirection
how "Add To Cart" looks on a Category page

The following code in "templates\components\products\card.html" leads customer to his Cart after he clicked on a "Add to Cart" button on chosen product on Category Page.

```<code>{{#if add_to_cart_url }}
  <a href="{{add_to_cart_url}}"
    class="button button--small
    card-figcaption-button">
       {{lang 'products.add_to_cart'}}</a>
    {{/if}}
</code>```

"{{add_to_cart_url}}" == http://mystore.com/cart.php?action=add&product_id=15865.

How to NOT redirect customer to his Cart?
How to add item to a cart and stay on the same page?

For example on Product page, after customer add product, customer stays on the same page, and script opens modal confirmation window.

```<code>        <!-- from templates\components\products\product-view.html -->

        <form class="form" method="post" action="{{product.cart_url}}" enctype="multipart/form-data"
        data-cart-item-add>
        <input type="hidden" name="action" value="add">
        <input type="hidden" name="product_id" value="{{product.id}}"/>
    <div class="form-action">

      <input id="form-action-addToCart"
data-wait-message=
"{{lang 'products.adding_to_cart'}}"
class="button button--primary" type="submit"
 value="{{#if product.pre_order}}
{{lang 'products.pre_order'}}
{{else}}
{{lang 'products.add_to_cart'}}
{{/if}}">
</div>
</code>```

This Product page code works based on this script: assets\js\bundle.js

```<code> Product.prototype.addProductToCart = function addProductToCart(event, form) {
            var _this4 = this;

            var $addToCartBtn = (0, _jquery2.default)('#form-action-addToCart', (0, _jquery2.default)(event.target));
            var originalBtnVal = $addToCartBtn.val();
            var waitMessage = $addToCartBtn.data('waitMessage');

            // Do not do AJAX if browser doesn't support FormData
            if (window.FormData === undefined) {
                return;
            }

            // Prevent default
            event.preventDefault();

            $addToCartBtn.val(waitMessage).prop('disabled', true);

            // Add item to cart
            _stencilUtils2.default.api.cart.itemAdd(new FormData(form), function (err, response) {
                var errorMessage = err || response.data.error;

                $addToCartBtn.val(originalBtnVal).prop('disabled', false);

                // Guard statement
                if (errorMessage) {
                    // Strip the HTML from the error message
                    var tmp = document.createElement('DIV');
                    tmp.innerHTML = errorMessage;

                    alert(tmp.textContent || tmp.innerText);

                    return;
                }

                // Open preview modal and update content
                previewModal.open();

                _this4.updateCartContent(previewModal, response.data.cart_item.hash);
            });
        };
</code>```

UPDATE:
This is similar:
Adding item to cart with BigCommerce Stencil

He was able to use utils.api.cart.itemAdd()
I can't make it workable.

One of the hook examples in Stencil:
https://stencil.bigcommerce.com/docs/hook-example-2-cart-dialog

I need to add product to a cart from Category Page
(templates\components\products\card.html)

Prevent the page from redirecting.

Update Cart content.
All this does addProductToCart(event, form) function. How to use it?

Just prevent page from redirecting not enough, it gives issues with
updating Cart Content and quantity.

Difference between adding products to a cart on card.html(category page) and product-view.html(product page) also in options and quantity.
On card.html adding happens by link {{add_to_cart_url}}.
On product-view.html it happens by form submitting and hook from
addProductToCart(event, form).

答:
So looking at the theme (Cornerstone Light), I can see that this isn't any kind of bug, it's just the way this theme is set within the theme files. I tested this on a default version of the theme on my test store and it also automatically redirects to the cart if you hit the add to cart level on the home, brand, or category pages. I checked the built-in theme editor to find that there isn't a way to turn that off and the only way to allow for that would be to have a developer edit your theme files so that the cart pop up page appears in the home, category, and brand pages, not just the product one as them set to.

Alternative 1:   If you check the code of the file card.html there are two buttons one for quick view and one is add to cart, so we can make the behaviour of add to cart same like quick view so when user will click on the add to cart the pop up will come and then he can click to add to cart button and then continue shopping button as well. With the help of this, the user will not redirect to the checkout page. To achieve that just change the code on your card.html like below:

```<code>{{#if add_to_cart_url }}
<a href="{{add_to_cart_url}}" class="button button--small card-figcaption-button">{{lang 'products.add_to_cart'}}</a>
{{/if}}
</code>```

Replace above code with this one :

```<code>{{#unless hide_product_quick_view}}
     {{#if theme_settings.show_product_quick_view}}
        <a href="#" class="button button--small card-figcaption-button quickview" data-product-id="{{id}}">{{lang 'products.add_to_cart'}}</a>
    {{/if}}
 {{/unless}}
</code>```

and the result of this like quick view like this: https://prnt.sc/hbl06f

Alternative 2:  Got bigcommerce app marketplace and buy this app fly add to cart.  https://www.themevale.com/bigcommerce-add-ons-ajax-add-to-cart-with-fly-effect-stencil-ready-now-available/

Thanks

Body:
how "Add To Cart" looks on a Category page

The following code in "templates\components\products\card.html" leads customer to his Cart after he clicked on a "Add to Cart" button on chosen product on Category Page.

{{#if add_to_cart_url }}

       {{lang 'products.add_to_cart'}}
    {{/if}}

"{{add_to_cart_url}}" == http://mystore.com/cart.php?action=add&product_id=15865.

How to NOT redirect customer to his Cart?
How to add item to a cart and stay on the same page?

For example on Product page, after customer add product, customer stays on the same page, and script opens modal confirmation window.

        <form class="form" method="post" action="{{product.cart_url}}" enctype="multipart/form-data"
        data-cart-item-add>
        <input type="hidden" name="action" value="add">
        <input type="hidden" name="product_id" value="{{product.id}}"/>

      <input id="form-action-addToCart"
data-wait-message=
"{{lang 'products.adding_to_cart'}}"
class="button button--primary" type="submit"
 value="{{#if product.pre_order}}
{{lang 'products.pre_order'}}
{{else}}
{{lang 'products.add_to_cart'}}
{{/if}}">

This Product page code works based on this script: assets\js\bundle.js

 Product.prototype.addProductToCart = function addProductToCart(event, form) {
            var _this4 = this;

            var $addToCartBtn = (0, _jquery2.default)('#form-action-addToCart', (0, _jquery2.default)(event.target));
            var originalBtnVal = $addToCartBtn.val();
            var waitMessage = $addToCartBtn.data('waitMessage');

            // Do not do AJAX if browser doesn't support FormData
            if (window.FormData === undefined) {
                return;
            }

            // Prevent default
            event.preventDefault();

            $addToCartBtn.val(waitMessage).prop('disabled', true);

            // Add item to cart
            _stencilUtils2.default.api.cart.itemAdd(new FormData(form), function (err, response) {
                var errorMessage = err || response.data.error;

                $addToCartBtn.val(originalBtnVal).prop('disabled', false);

                // Guard statement
                if (errorMessage) {
                    // Strip the HTML from the error message
                    var tmp = document.createElement('DIV');
                    tmp.innerHTML = errorMessage;

                    alert(tmp.textContent || tmp.innerText);

                    return;
                }

                // Open preview modal and update content
                previewModal.open();

                _this4.updateCartContent(previewModal, response.data.cart_item.hash);
            });
        };

UPDATE:
This is similar:
Adding item to cart with BigCommerce Stencil

He was able to use utils.api.cart.itemAdd()
I can't make it workable.

One of the hook examples in Stencil:
https://stencil.bigcommerce.com/docs/hook-example-2-cart-dialog

I need to add product to a cart from Category Page
(templates\components\products\card.html)

Prevent the page from redirecting.

Update Cart content.
All this does addProductToCart(event, form) function. How to use it?

Just prevent page from redirecting not enough, it gives issues with
updating Cart Content and quantity.

Difference between adding products to a cart on card.html(category page) and product-view.html(product page) also in options and quantity.
On card.html adding happens by link {{add_to_cart_url}}.
On product-view.html it happens by form submitting and hook from
addProductToCart(event, form).

Body:
So looking at the theme (Cornerstone Light), I can see that this isn't any kind of bug, it's just the way this theme is set within the theme files. I tested this on a default version of the theme on my test store and it also automatically redirects to the cart if you hit the add to cart level on the home, brand, or category pages. I checked the built-in theme editor to find that there isn't a way to turn that off and the only way to allow for that would be to have a developer edit your theme files so that the cart pop up page appears in the home, category, and brand pages, not just the product one as them set to.

Alternative 1:   If you check the code of the file card.html there are two buttons one for quick view and one is add to cart, so we can make the behaviour of add to cart same like quick view so when user will click on the add to cart the pop up will come and then he can click to add to cart button and then continue shopping button as well. With the help of this, the user will not redirect to the checkout page. To achieve that just change the code on your card.html like below:

{{#if add_to_cart_url }}
<a href="{{add_to_cart_url}}" class="button button--small card-figcaption-button">{{lang 'products.add_to_cart'}}</a>
{{/if}}

Replace above code with this one :

{{#unless hide_product_quick_view}}
     {{#if theme_settings.show_product_quick_view}}
        <a href="#" class="button button--small card-figcaption-button quickview" data-product-id="{{id}}">{{lang 'products.add_to_cart'}}</a>
    {{/if}}
 {{/unless}}

and the result of this like quick view like this: https://prnt.sc/hbl06f

Alternative 2:  Got bigcommerce app marketplace and buy this app fly add to cart.  https://www.themevale.com/bigcommerce-add-ons-ajax-add-to-cart-with-fly-effect-stencil-ready-now-available/

Thanks


问:
Rank numbers by comparing two matrices
Having a matrix A like:

```<code>      [,1] [,2]  [,3]  [,4]
[1,]     1    4     7     6
[2,]     2    5     8     1
[3,]     5    1     7     8
</code>```

and a matrix B like:

```<code>      [,1]
[1,]     8
[2,]     6
[3,]     1
[4,]     7
[5,]     5
[6,]     2
[7,]     3
[8,]     4
</code>```

I want to get create a matrix C similar to A replacing A values with the rank of A values in matrix B. The result should be:

```<code>matrix C
      [,1] [,2]  [,3]  [,4]
[1,]     3    8     4     2
[2,]     6    5     1     3
[3,]     5    3     4     1
</code>```

Title: Rank numbers by comparing two matrices

Body:
Having a matrix A like:

      [,1] [,2]  [,3]  [,4]
[1,]     1    4     7     6
[2,]     2    5     8     1
[3,]     5    1     7     8

and a matrix B like:

      [,1]
[1,]     8
[2,]     6
[3,]     1
[4,]     7
[5,]     5
[6,]     2
[7,]     3
[8,]     4

I want to get create a matrix C similar to A replacing A values with the rank of A values in matrix B. The result should be:

matrix C
      [,1] [,2]  [,3]  [,4]
[1,]     3    8     4     2
[2,]     6    5     1     3
[3,]     5    3     4     1

Body:
You can use match and adjust the dimensions:

C <- match(A, B)
dim(C) <- dim(A)

--

Example:

> set.seed(123)
> (A <- matrix(sample(1:8), ncol = 4))
     [,1] [,2] [,3] [,4]
[1,]    3    8    4    2
[2,]    6    5    1    7
> (B <- matrix(sample(1:8), ncol= 1))
     [,1]
[1,]    5
[2,]    4
[3,]    6
[4,]    3
[5,]    8
[6,]    2
[7,]    1
[8,]    7
> (C <- match(A, B))
[1] 4 3 5 1 2 7 6 8
> (dim(C) <- dim(A))
[1] 2 4
> C
     [,1] [,2] [,3] [,4]
[1,]    4    5    2    6
[2,]    3    1    7    8


问:
Retrieve inserted row ID in SQL
How do I retrieve the ID of an inserted row in SQL?

Users Table:

```<code>Column  | Type
--------|--------------------------------
ID      | * Auto-incrementing primary key
Name    |
Age     |
</code>```

Query Sample:

```<code>insert into users (Name, Age) values ('charuka',12)
</code>```

答:
In MySQL:

```<code>SELECT LAST_INSERT_ID();
</code>```

In SQL Server:

```<code>SELECT SCOPE_IDENTITY();
</code>```

In Oracle:

```<code>SELECT SEQNAME.CURRVAL FROM DUAL;
</code>```

In PostgreSQL:

```<code>SELECT lastval();
</code>```

(edited: lastval is any, currval requires a named sequence)
Note: lastval() returns the latest sequence value assigned by your session, independently of what is happening in other sessions.

Title: Retrieve inserted row ID in SQL

Body:
How do I retrieve the ID of an inserted row in SQL?

Users Table:

Column  | Type
--------|--------------------------------
ID      | * Auto-incrementing primary key
Name    |
Age     |

Query Sample:

insert into users (Name, Age) values ('charuka',12)

Body:
In MySQL:

SELECT LAST_INSERT_ID();

In SQL Server:

SELECT SCOPE_IDENTITY();

In Oracle:

SELECT SEQNAME.CURRVAL FROM DUAL;

In PostgreSQL:

SELECT lastval();

(edited: lastval is any, currval requires a named sequence)
Note: lastval() returns the latest sequence value assigned by your session, independently of what is happening in other sessions.


问:
nginx SSI call - how to execute a script via proxy pass?
I'm trying to work out how to get this going in my HTML page:

```<code><!--# exec cgi="/cgi-bin/links/track_ssi.cgi" -->
</code>```

I see this in the log file:

```<code>invalid SSI command: "exec" while sending response to client
</code>```

We have a proxy pass from nginx to Apache2.4:

```<code>    location ~ \.cgi$ {
        gzip off;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8181;
    }
</code>```

As far as I can see though, its not even getting that far. What am I doing wrong?

Thanks!

答:
There is no exec cgi SSI command, please see Nginx documentation on SSI.

Correct SSI fragment will be

```<code><!--#include virtual="/cgi-bin/links/track_ssi.cgi" -->
</code>```

(assuming everything else is correctly configured)

Body:
I'm trying to work out how to get this going in my HTML page:

I see this in the log file:

invalid SSI command: "exec" while sending response to client

We have a proxy pass from nginx to Apache2.4:

    location ~ \.cgi$ {
        gzip off;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8181;
    }

As far as I can see though, its not even getting that far. What am I doing wrong?

Thanks!

Body:
There is no exec cgi SSI command, please see Nginx documentation on SSI.

Correct SSI fragment will be

<!--#include virtual="/cgi-bin/links/track_ssi.cgi" -->

(assuming everything else is correctly configured)


问:
Webdriver: ExpectedConditions.invisibilityOf is not working. Always throws an exception
I'm using ExpectedConditions.invisibilityOf to check the invisibility of one of the element, but every time it throws the timeout exception for :

```<code>wait.until(ExpectedConditions.invisibilityOf(elementTobeInvisible));
</code>```

Error Message:

```<code>org.openqa.selenium.TimeoutException: Expected condition failed: waiting for invisibility of Proxy element for: DefaultElementLocator 'By.xpath: //button[text()='button text']' (tried for 30 second(s) with 500 MILLISECONDS interval)
</code>```

I've checked visibility of same element using element.isDisplayed() it returns 'false' correctly.

Recently I upgraded selenium from 2.53.0

Webdriver: 3.7.1 or 3.6.0

Chrome:  62.0.3202.94 (Official Build) (64-bit)

OS: Windows 7

答:
You can try using the below line of code instead of that -

```<code>wait.until(ExpectedConditions.invisibilityOfElementLocated(elementTobeInvisible));
</code>```

Or you can simply call the method like this -

```<code>//Wait until Invisibility of element is completed
public void waitForInvisibility(By byElement){
try{
WebDriverWait wait = new WebDriverWait(driver, 120);
wait.until(ExpectedConditions.invisibilityOfElementLocated(byElement));
//May apply thread sleep for 1 or 2 seconds
}catch(Exception e){}}
</code>```

Before call this method, declare the param By element like below -

```<code>By byElement = By.cssSelector("Use the element's css selector here");
</code>```

//or

```<code>By byElement = By.xpath("Use the element's XPath here");
</code>```

Body:
I'm using ExpectedConditions.invisibilityOf to check the invisibility of one of the element, but every time it throws the timeout exception for :

wait.until(ExpectedConditions.invisibilityOf(elementTobeInvisible));

Error Message:

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for invisibility of Proxy element for: DefaultElementLocator 'By.xpath: //button[text()='button text']' (tried for 30 second(s) with 500 MILLISECONDS interval)

I've checked visibility of same element using element.isDisplayed() it returns 'false' correctly.

Recently I upgraded selenium from 2.53.0

Webdriver: 3.7.1 or 3.6.0

Chrome:  62.0.3202.94 (Official Build) (64-bit)

OS: Windows 7

Body:
You can try using the below line of code instead of that -

wait.until(ExpectedConditions.invisibilityOfElementLocated(elementTobeInvisible));

Or you can simply call the method like this -

//Wait until Invisibility of element is completed
public void waitForInvisibility(By byElement){
try{
WebDriverWait wait = new WebDriverWait(driver, 120);
wait.until(ExpectedConditions.invisibilityOfElementLocated(byElement));
//May apply thread sleep for 1 or 2 seconds
}catch(Exception e){}}

Before call this method, declare the param By element like below -

By byElement = By.cssSelector("Use the element's css selector here");

//or

By byElement = By.xpath("Use the element's XPath here");


问:
Microcharts in Listview Using Xamarin
I'm using xamarin.forms and I need to create graphs inside of listview, how to create graphs inside of listview using microcharts.

This is my code in xaml:

```<code>            <ListView.ItemTemplate>

                <DataTemplate>

                    <ViewCell>

                        <StackLayout Orientation="Vertical">

                            <!--<StackLayout.GestureRecognizers>
                                <TapGestureRecognizer
                                    Tapped="TargetList_Tapped"/>
                            </StackLayout.GestureRecognizers>-->
                            <Grid
                                  HeightRequest="10"/>
                            <customRenderer:CustomFrame HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BackgroundColor="White" HeightRequest="30" Padding="15">

                                <StackLayout Orientation="Vertical" >
                                    <!--<Image x:Name="sam"/>-->

                                    <Label Text="{Binding AreaNo}"
                                       TextColor="Black"
                                       Font="Bold"/>

                                    <StackLayout Margin="0, -5, 0, 0" Orientation="Horizontal">
                                        <forms:ChartView x:Name="Chart1" HeightRequest="150"/>
                                        <Label Text="Last Covered On:"
                                           TextColor="Black"
                                           Font="10"
                                           FontAttributes="Bold"
                                           Opacity="0.6"/>

                                        <Label Text="{Binding DateCovered}"
                                           TextColor="Black"
                                           Font="10"
                                           FontAttributes="Bold"
                                           Opacity="0.6"/>
                                    </StackLayout>

                                </StackLayout>

                            </customRenderer:CustomFrame>
                            <customRenderer:CustomFrame Padding="0" Margin="0, -10, 0, 0">
                                <Image x:Name="sampleImage" Source="Rectangle_Inactive.png" HorizontalOptions="FillAndExpand" Aspect="AspectFill"/>
                            </customRenderer:CustomFrame>

                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

This is my code in xaml.cs:

```<code>namespace PrismUnityApp6.Views
{
public partial class MainPage : ContentPage
{

    List<Entry> entries = new List<Entry>
    {
        new Entry(200)
        {
            Color = SKColor.Parse("#008000"),
        },
        new Entry(400)
        {
            Color = SKColor.Parse("#FFFFFF")
        }

    };

    public MainPage()
    {

        InitializeComponent();

        Chart1.Chart = new RadialGaugeChart { Entries = entries };

    }
}
</code>```

}

I tried this code but I can't get the name of the chart in xaml.cs file while using listview.

Any suggestion will be appreciated. Thank you.

答:
You have chart inside ItemTemplate. Possibly there could many charts and they can't have same name. Correct approach is to use binding inside ItemTemplate.

Similar issue is discussed here.

This example is just for demonstration how it could possibly work. After you try this demo make sure you learn MVVM pattern and use it in your project.

The MainPage.xaml

```<code><ContentPage.Content>
    <ListView
       x:Name="MyListview">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout>
                        <microcharts:ChartView Chart="{Binding ChartData}" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>
</code>```

MainPage.xaml.cs

```<code>public partial class MainPage : ContentPage
{
    List<MyChart> MyCharts;

    public MainPage()
    {
        InitializeComponent();
        MyCharts = new List<MyChart>();
        PopulateCharts();
    }

    private void PopulateCharts()
    {
        MyCharts.Add(new MyChart() { ChartData = Chart1 });
        MyCharts.Add(new MyChart() { ChartData = Chart2 });
        MyListview.ItemsSource = MyCharts;
    }

    public class MyChart
    {
        public Chart ChartData { get; set; }
    }

    public Chart Chart1 => new BarChart()
    {
        Entries = new[]
        {
             new Microcharts.Entry(128)
             {
                 Label = "iOS",
                 ValueLabel = "128",
                 Color = SKColor.Parse("#b455b6")
             },
             new Microcharts.Entry(514)
             {
                 Label = "Shared",
                 ValueLabel = "514",
                 Color = SKColor.Parse("#3498db")
        }},
        BackgroundColor = SKColors.White
    };

    public Chart Chart2 => new BarChart()
    {
        Entries = new[]
        {
             new Microcharts.Entry(128)
             {
                 Label = "Android",
                 ValueLabel = "128",
                 Color = SKColor.Parse("#b455b6")
             },
             new Microcharts.Entry(514)
             {
                 Label = "UWP",
                 ValueLabel = "514",
                 Color = SKColor.Parse("#3498db")
        }},
        BackgroundColor = SKColors.Yellow
    };
}
</code>```

Also in the blog post that I mentioned there is a nice example using MVVM pattern here on this link.

Title: Microcharts in Listview Using Xamarin

Body:
I'm using xamarin.forms and I need to create graphs inside of listview, how to create graphs inside of listview using microcharts.

This is my code in xaml:

            <ListView.ItemTemplate>

                <DataTemplate>

                    <ViewCell>

                        <StackLayout Orientation="Vertical">

                            <Grid
                                  HeightRequest="10"/>
                            <customRenderer:CustomFrame HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BackgroundColor="White" HeightRequest="30" Padding="15">

                                <StackLayout Orientation="Vertical" >

                                    <StackLayout Margin="0, -5, 0, 0" Orientation="Horizontal">
                                        <forms:ChartView x:Name="Chart1" HeightRequest="150"/>

                                    </StackLayout>

                                </StackLayout>

                            </customRenderer:CustomFrame>
                            <customRenderer:CustomFrame Padding="0" Margin="0, -10, 0, 0">
                                <Image x:Name="sampleImage" Source="Rectangle_Inactive.png" HorizontalOptions="FillAndExpand" Aspect="AspectFill"/>
                            </customRenderer:CustomFrame>

                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

This is my code in xaml.cs:

namespace PrismUnityApp6.Views
{
public partial class MainPage : ContentPage
{

    List<Entry> entries = new List<Entry>
    {
        new Entry(200)
        {
            Color = SKColor.Parse("#008000"),
        },
        new Entry(400)
        {
            Color = SKColor.Parse("#FFFFFF")
        }

    };

    public MainPage()
    {

        InitializeComponent();

        Chart1.Chart = new RadialGaugeChart { Entries = entries };

    }
}

}

I tried this code but I can't get the name of the chart in xaml.cs file while using listview.

Any suggestion will be appreciated. Thank you.

Body:
You have chart inside ItemTemplate. Possibly there could many charts and they can't have same name. Correct approach is to use binding inside ItemTemplate.

Similar issue is discussed here.

This example is just for demonstration how it could possibly work. After you try this demo make sure you learn MVVM pattern and use it in your project.

The MainPage.xaml

<ContentPage.Content>
    <ListView
       x:Name="MyListview">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout>
                        <microcharts:ChartView Chart="{Binding ChartData}" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>

MainPage.xaml.cs

public partial class MainPage : ContentPage
{
    List<MyChart> MyCharts;

    public MainPage()
    {
        InitializeComponent();
        MyCharts = new List<MyChart>();
        PopulateCharts();
    }

    private void PopulateCharts()
    {
        MyCharts.Add(new MyChart() { ChartData = Chart1 });
        MyCharts.Add(new MyChart() { ChartData = Chart2 });
        MyListview.ItemsSource = MyCharts;
    }

    public class MyChart
    {
        public Chart ChartData { get; set; }
    }

    public Chart Chart1 => new BarChart()
    {
        Entries = new[]
        {
             new Microcharts.Entry(128)
             {
                 Label = "iOS",
                 ValueLabel = "128",
                 Color = SKColor.Parse("#b455b6")
             },
             new Microcharts.Entry(514)
             {
                 Label = "Shared",
                 ValueLabel = "514",
                 Color = SKColor.Parse("#3498db")
        }},
        BackgroundColor = SKColors.White
    };

    public Chart Chart2 => new BarChart()
    {
        Entries = new[]
        {
             new Microcharts.Entry(128)
             {
                 Label = "Android",
                 ValueLabel = "128",
                 Color = SKColor.Parse("#b455b6")
             },
             new Microcharts.Entry(514)
             {
                 Label = "UWP",
                 ValueLabel = "514",
                 Color = SKColor.Parse("#3498db")
        }},
        BackgroundColor = SKColors.Yellow
    };
}

Also in the blog post that I mentioned there is a nice example using MVVM pattern here on this link.


问:
How to get root node attributes on java
I have an xml file like down below. I want to get pharmacies nodes' latitude and longitude attributes.I can get chilnodes attributes but couldnt get root node attributes. I am new on java and xml. I could not find a solution how to do.

```<code><pharmacies Acc="4" latitude="36.8673380" longitude="30.6346640" address="Ayujkila">
        <pharmacy name="sadde" owner="" address="dedes" distance="327.000555668" phone="342343" lat="36.8644" long="30.6345" accuracy="8"/>
        <pharmacy name="Sun " owner="" address="degerse" distance="364.450016586" phone="45623" lat="36.8641" long="30.6353" accuracy="8"/>
        <pharmacy name="lara" owner="" address="freacde" distance="927.262190129" phone="564667" lat="36.8731" long="30.6422" accuracy="8"
    <end/>
    </pharmacies>
</code>```

This is my part of code. I get xml file from a url address.

```<code>                    DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                 DocumentBuilder db = dbf.newDocumentBuilder();
                 Document doc = db.parse(new InputSource(url.openStream()));
                 doc.getDocumentElement().normalize();
                    NodeList nodeList =doc.getElementsByTagName("pharmacy");
                 for (int i = 0; i < nodeList.getLength(); i++){
                      Node node =nodeList.item(i);
                      Element fstElmnt = (Element) node;
                      NodeList pharmacyList = fstElmnt.getElementsByTagName("pharmacy");
                      Element pharmacyElement = (Element) pharmacyList.item(0);
              Element pharmacyElement = (Element) pharmacyList.item(0);

              HashMap<String,String>map=new HashMap<String,String>();
              map.put("name", pharmacyElement.getAttribute("name"));
              map.put("distance", pharmacyElement.getAttribute("phone"));
              list.add(map);

              latt.add(pharmacyElement.getAttribute("lat"));

                    ....
</code>```

答:
You need to use pharmacies instead of pharmacy if you need to get attributes for root node pharmacies.And use getAttributes method instead.You can see lot of examples at this site.
http://java.sun.com/developer/codesamples/xml.html#dom</p>

Title: How to get root node attributes on java

Body:
I have an xml file like down below. I want to get pharmacies nodes' latitude and longitude attributes.I can get chilnodes attributes but couldnt get root node attributes. I am new on java and xml. I could not find a solution how to do.

<pharmacies Acc="4" latitude="36.8673380" longitude="30.6346640" address="Ayujkila">
        <pharmacy name="sadde" owner="" address="dedes" distance="327.000555668" phone="342343" lat="36.8644" long="30.6345" accuracy="8"/>
        <pharmacy name="Sun " owner="" address="degerse" distance="364.450016586" phone="45623" lat="36.8641" long="30.6353" accuracy="8"/>
        <pharmacy name="lara" owner="" address="freacde" distance="927.262190129" phone="564667" lat="36.8731" long="30.6422" accuracy="8"
    <end/>
    </pharmacies>

This is my part of code. I get xml file from a url address.

                    DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                 DocumentBuilder db = dbf.newDocumentBuilder();
                 Document doc = db.parse(new InputSource(url.openStream()));
                 doc.getDocumentElement().normalize();
                    NodeList nodeList =doc.getElementsByTagName("pharmacy");
                 for (int i = 0; i < nodeList.getLength(); i++){
                      Node node =nodeList.item(i);
                      Element fstElmnt = (Element) node;
                      NodeList pharmacyList = fstElmnt.getElementsByTagName("pharmacy");
                      Element pharmacyElement = (Element) pharmacyList.item(0);
              Element pharmacyElement = (Element) pharmacyList.item(0);

              HashMap<String,String>map=new HashMap<String,String>();
              map.put("name", pharmacyElement.getAttribute("name"));
              map.put("distance", pharmacyElement.getAttribute("phone"));
              list.add(map);

              latt.add(pharmacyElement.getAttribute("lat"));

                    ....


问:
How to check if two tables are structurally same?
I have two tables in a SQL Server database. I want to check if these two tables are structurally same. I used UNION/ EXCEPT operator to check this and found that these two tables are not identical.

Here are my questions:

How do we know if two tables are the same in structure?

If they are not same, how do we get the details of differences? If a column is missing in one table how do we get the name of the missing column?

If there is a data type mismatch between a column in these two tables, can we get the name of the column with different data type?

答:
In SSDT you can use schema compare to see if there is any differences in columns, tables, datatypes and so forth.

Schema Compare SSDT

If you want to code your way out of it. You can query information_schema catalog

System Information Schema