问:
Cross Origin amazon S3 not working using chrome
Our website is having a problem, with chrome, loading images from amazon S3 with crossOrigin attribute setted on "Anonymous".

Our S3 server is setted with:

`

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <ExposeHeader>x-amz-server-side-encryption</ExposeHeader>
        <ExposeHeader>x-amz-request-id</ExposeHeader>
        <ExposeHeader>x-amz-id-2</ExposeHeader>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
</code>```

`

I'm using canvg.js in order to create a canvas from an SVG having remote images (on amazon S3 server) but chrome browser returns me "No 'Access-Control-Allow-Origin' header is present on the requested resource." error after executed this code:

```<code> this.img = document.createElement('img');
            var self = this;
            this.img.onload = function() { self.loaded = true; }
            this.img.onerror = function() { if (typeof(console) != 'undefined')
            console.log('ERROR: image "' + href + '" not found'); self.loaded = true; } }
            if (svg.opts['useCORS'] == true) {
                                this.img.crossOrigin = 'Anonymous'; }
            this.img.src = href;
</code>```

In firefox and IE this doesn't cause any issue.

答:
This is an issue with Chrome caching requests. Here is a discussion on the topic.

Simply add the following to all HTML tags where you are trying to access resources from a different domain crossorigin="anonymous" as documented by MDN here.

Body:
Our website is having a problem, with chrome, loading images from amazon S3 with crossOrigin attribute setted on "Anonymous".

Our S3 server is setted with:

`

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <ExposeHeader>x-amz-server-side-encryption</ExposeHeader>
        <ExposeHeader>x-amz-request-id</ExposeHeader>
        <ExposeHeader>x-amz-id-2</ExposeHeader>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

`

I'm using canvg.js in order to create a canvas from an SVG having remote images (on amazon S3 server) but chrome browser returns me "No 'Access-Control-Allow-Origin' header is present on the requested resource." error after executed this code:

 this.img = document.createElement('img');
            var self = this;
            this.img.onload = function() { self.loaded = true; }
            this.img.onerror = function() { if (typeof(console) != 'undefined')
            console.log('ERROR: image "' + href + '" not found'); self.loaded = true; } }
            if (svg.opts['useCORS'] == true) {
                                this.img.crossOrigin = 'Anonymous'; }
            this.img.src = href;

In firefox and IE this doesn't cause any issue.


来源: stackexchange

问:
Possible side effect of Stream.peek changing state and why not use it like this
A solution that I came up on another Stackoverflow question that is using Stream.peek operation works but still seems like is not right because it mutates state in the Stream.peek method.

While researching (here and here) on Stream.peek usage whether it is ok to mutate state I am still not fully convinced that Stream.peek should not mutate state (including state of collection that is source of the Stream).

Here is what Javadoc says:

This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:

And then:

Parameters: action - a non-interfering action to perform on the
  elements as they are consumed from the stream.

For well-behaved non-interfering
  stream sources, the source can be modified before the terminal
  operation commences and those modifications will be reflected in the
  covered elements.All the streams returned from JDK collections, and
  most other JDK classes, are well-behaved in this manner.

Seems like non-interfering action does includes changing the state of collection in the stream.

Here is the code that uses Stream.peek.

```<code>Map< String, List<Test> > userTests = new HashMap<>();

Map< String, List<Test> > filtered  = userTests.entrySet().stream()
        .peek( e -> e.setValue( modifyListAndReturnIt( e.getValue() ) ) )
        .filter( e -> !e.getValue().isEmpty() ) //check if modified list in peek has been emptied
        .collect( Collectors.toMap(p -> p.getKey(), p -> p.getValue() ) );

    public static List<Test> modifyListAndReturnIt(List<Test> list){
        if (somecondition) list.clear();
        return list;
    }
</code>```

1) Can the above code have any side effect?

2) Why not use peek in such a way. The Javadoc does not seem to not allow it?

答:
What you seem to do looks harmless as Brian Goetz states in comment here.

Now the problem with peek is that if you do side effects inside it - you would expect these side effects to actually happen. So, suppose you would want to alter some property of some object like this:

```<code>myUserList.stream()
          .peek(u -> u.upperCaseName())
          .count()
</code>```

In java-8 your peek would be indeed called, in 9 - it is not - there is no need to call peek here since the size can be computed without it anyway.

While being on the same path, imagine that your terminal operation is a short-circuit one, like findFirst or findAny - you are not going to process all elements of the source - you might get just a few of them through the pipeline.

Things might get even stranger if your peek would rely on a encounter order even if your terminal operation would not be a short-circuit one. The intermediate operations for parallel processing do not have an encounter order, while the terminal ones - do. Imagine the surprises you might be facing.

ContentLicense: CC BY-SA 3.0

Body:
A solution that I came up on another Stackoverflow question that is using Stream.peek operation works but still seems like is not right because it mutates state in the Stream.peek method.

While researching (here and here) on Stream.peek usage whether it is ok to mutate state I am still not fully convinced that Stream.peek should not mutate state (including state of collection that is source of the Stream).

Here is what Javadoc says:

This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:

And then:

Parameters: action - a non-interfering action to perform on the
  elements as they are consumed from the stream.

For well-behaved non-interfering
  stream sources, the source can be modified before the terminal
  operation commences and those modifications will be reflected in the
  covered elements.All the streams returned from JDK collections, and
  most other JDK classes, are well-behaved in this manner.

Seems like non-interfering action does includes changing the state of collection in the stream.

Here is the code that uses Stream.peek.

Map< String, List<Test> > userTests = new HashMap<>();

Map< String, List<Test> > filtered  = userTests.entrySet().stream()
        .peek( e -> e.setValue( modifyListAndReturnIt( e.getValue() ) ) )
        .filter( e -> !e.getValue().isEmpty() ) //check if modified list in peek has been emptied
        .collect( Collectors.toMap(p -> p.getKey(), p -> p.getValue() ) );

    public static List<Test> modifyListAndReturnIt(List<Test> list){
        if (somecondition) list.clear();
        return list;
    }

1) Can the above code have any side effect?

2) Why not use peek in such a way. The Javadoc does not seem to not allow it?

Body:
What you seem to do looks harmless as Brian Goetz states in comment here.

Now the problem with peek is that if you do side effects inside it - you would expect these side effects to actually happen. So, suppose you would want to alter some property of some object like this:

myUserList.stream()
          .peek(u -> u.upperCaseName())
          .count()

In java-8 your peek would be indeed called, in 9 - it is not - there is no need to call peek here since the size can be computed without it anyway.

While being on the same path, imagine that your terminal operation is a short-circuit one, like findFirst or findAny - you are not going to process all elements of the source - you might get just a few of them through the pipeline.

Things might get even stranger if your peek would rely on a encounter order even if your terminal operation would not be a short-circuit one. The intermediate operations for parallel processing do not have an encounter order, while the terminal ones - do. Imagine the surprises you might be facing.


问:
In Kubernetes, how can I wait for updated code to be deployed in a cluster?
I have a working Kubernetes cluster hosted in the Google Kubernetes Engine. I can apply new code to the cluster by building a Docker image with the new code, pushing the image (with a new tag) to the Google Container Registry, and then kubectl apply-ing an updated manifest (using the new tag) to the cluster.

I have a manual step (specifically, rails db:migrate to apply new migrations to the database) that I want to happen once the new code has been deployed. I can execute this command just fine as a kubectl exec command. But there's a problem: I need to run it against the new image, not the old image. Running it against the old image will succeed, in the sense that the exit code will be 0, but it will not apply the new migrations, which are only present in the new image.

My question: How can I wait for new code to be live in a cluster before I run a kubectl exec command against it?

Note that I can't do a kubectl run using the new image, because the container by itself can't access the database; it needs the "sidecar" CloudSQL proxy container running in the same pod.

One more constraint: I need to do this in a scripting environment (e.g. bash), so repeatedly running a command and examining the output manually isn't an option. Doing an automatic, scripted loop until some condition is met does count as a solution, but I'd really prefer something that doesn't require me to poll in my script.

A sleep of some duration could sort of solve this problem, but there are problems with that approach:

The sleep time might not be long enough for everything to finish (and the time that takes is variable and difficult to predict).

If I sleep longer than I need to, the Rails app will refuse to work because it will recognize that there are database migrations that haven't been applied—which should be considered downtime for the app.

答:
If I have understood the problem correctly then I think init containers will solve your problem fairly well. Init containers allow you to do certain tasks before a pod is started.

So in your case, something to tunes of the following will serve the purpose (Code copied from the link above):

apiVersion: v1
kind: Pod
metadata:
  name: rails-app
  labels:
    app: myapp
  annotations:
    pod.beta.kubernetes.io/init-containers: '[
        {
            "name": "init-myservice",
            "image": "new-image",
            "command": ["sh", "-c", "rails db:migrate"]
        }
    ]'
spec:
  containers:
  - name: myapp-rails-app
    image: new-image

Let's run over how this will work:

You will build and push the new image of the app to registry. You will have to modify the pod definition to have init containers as above of course.

You will apply the new version via kubectl to deployment

The init container uses same image as that your app uses, but is used only for the execution of rails DB migration.

After that actual app starts.

Even if you have N replicas of the the pod with a deployment or replication controller object - then the migration might run N times (Once for each pod). It is not intended or best path but wont have any issues as the first pod that comes up would have done migration anyway.


问:
Unable to launch EC2 with IAM role as a member of Administrators group
On AWS member of Administrators group is unable to launch EC2 instances with IAM role. The same user can create IAM roles and even manage users in IAM console. </p>

<p>User seems to have all possible permissions. What could be missing? </p>

答:
The documentation states you need ec2:RunInstances, ec2:AssociateIamInstanceProfile, ec2:ReplaceIamInstanceProfileAssociation and iam:PassRole. Do they have all of those?

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
         "ec2:RunInstances",
         "ec2:AssociateIamInstanceProfile",
         "ec2:ReplaceIamInstanceProfileAssociation"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "*"
    }
  ]
}
</code>```

Body:
On AWS member of Administrators group is unable to launch EC2 instances with IAM role. The same user can create IAM roles and even manage users in IAM console.

User seems to have all possible permissions. What could be missing?

Body:
The documentation states you need ec2:RunInstances, ec2:AssociateIamInstanceProfile, ec2:ReplaceIamInstanceProfileAssociation and iam:PassRole. Do they have all of those?

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
         "ec2:RunInstances",
         "ec2:AssociateIamInstanceProfile",
         "ec2:ReplaceIamInstanceProfileAssociation"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "*"
    }
  ]
}


问:
Where do I find the workflow id of an automation in Mailchimp?
I would like to use Mailchimp Api 3.0 to add a subscriber to an automation workflow, but I can't find where the workflow_id or workflow_email_id are located... this is from the documentation:

POST /automations/{workflow_id}/emails/{workflow_email_id}/queue   Add a subscriber to a workflow email

http://developer.mailchimp.com/documentation/mailchimp/reference/automations/emails/queue/

Can anyone tell me to find it? It's probably somewhere really obvious. I mean the list_id is well covered, but I can't find any info about this.

答:
I found this confusing as well. Here is how I got the answer:

Send a GET request to https://us9.api.mailchimp.com/3.0/automations to find the workflow_id

With the workflow_id, send a GET request to https://us9.api.mailchimp.com/3.0/automations/<workflow_id>/emails to find the workflow_email_id. The workflow_email_id will be the "id" in the array that's returned.

From there you can make POST requests to https://us9.api.mailchimp.com/3.0/automations/<workflow_id>/emails/<workflow_email_id>/queue

Keep in mind you might need to subscribe an email address to a list first for the post request to work. To subscribe you can use: https://us9.api.mailchimp.com/3.0/lists/<list_id> with your data:

```<code>{
  "members": [{
        "email_address" : "emailaddress@whatever.com",
        "status": "subscribed"
  }]
}
</code>```

Body:
I found this confusing as well. Here is how I got the answer:

Send a GET request to https://us9.api.mailchimp.com/3.0/automations to find the workflow_id

With the workflow_id, send a GET request to https://us9.api.mailchimp.com/3.0/automations/<workflow_id>/emails to find the workflow_email_id. The workflow_email_id will be the "id" in the array that's returned.

From there you can make POST requests to https://us9.api.mailchimp.com/3.0/automations/<workflow_id>/emails/<workflow_email_id>/queue

Keep in mind you might need to subscribe an email address to a list first for the post request to work. To subscribe you can use: https://us9.api.mailchimp.com/3.0/lists/<list_id> with your data:

{
  "members": [{
        "email_address" : "emailaddress@whatever.com",
        "status": "subscribed"
  }]
}


问:
Angular Autocomplete Error Messages (without floating label)
I'm looking to add validation error messages for an Angular Autocomplete component.  I followed an example I found in How to add validation attributes to md-autocomplete angular material directive, but I do not want to use a floating label.  How can I achieve this?  Here's my HTML:

<md-autocomplete md-input-id="person"
                 md-input-name="person"
                 md-item-text="item.displayName"
                 md-items="item in getPeople(searchText)"
                 md-search-text="searchText"
                 md-selected-item="model.person"
                 md-selected-item-change="form.person.$setValidity('itemInList', !!item)"
                 md-min-length="0"
                 placeholder="Enter a person"
                 md-select-on-focus
                 class="output"
                 required>
    <md-item-template>
        {{item.displayName}}
    </md-item-template>
    <md-not-found>
        No matches found.
    </md-not-found>
</md-autocomplete>

Person is required

Person was not selected from the list

```

答:
I found that adding the "md-no-float" attribute fixed my problem.  Here's an updated snippet:

    <md-autocomplete md-input-id="person"
                     md-input-name="person"
                     md-item-text="item.displayName"
                     md-items="item in getPeople(searchText)"
                     md-search-text="searchText"
                     md-selected-item="model.person"
                     md-selected-item-change="form.person.$setValidity('itemInList', !!item)"
                     md-min-length="0"
                     placeholder="Enter a person"
                     md-select-on-focus
                     class="output"
      md-no-float
                     required>```


问:
Expose GRPC server through Ingress on Google Cloud
I'm trying to expose a GRPC Java service thought an Ingress to outside world from my GKE cluster.

The problem is that GKE's default implementation creates a health check that expect 200 response code on curling "/". It is expected and documented here.

Unfortunately this seems not to work with grpc-java implementation since it's not handling "/" GET requests.

GRPC itself defines a health checking protocol. But it's not supported either.

I wonder if there is a similar secret annotation like "kubernetes.io/ingress.global-static-ip-name" but for disabling health checks at least(ideally overriding them).

答:
The health check can be changed by defining custom liveness/readiness probes. In this way, you can define custom endpoints to hit for the health check. Here's a sample from the documentation:

```<code> livenessProbe:
  httpGet:
    path: /healthz
    port: 8080
    httpHeaders:
    - name: X-Custom-Header
      value: Awesome
  initialDelaySeconds: 3
  periodSeconds: 3
</code>```

If you need something more powerful than a simple HTTP check, you can construct a probe with 'exec' instead of 'httpGet'. With exec, you can use Linux commands or a custom CLI script in your container to query your API or otherwise verify the state of your system. If the command/script returns 0, the pod is seen as healthy. This sample will view the pod as alive if a file exists at /tmp/healthy:

```<code>livenessProbe:
  exec:
    command:
    - cat
    - /tmp/healthy
  initialDelaySeconds: 5
  periodSeconds: 5
</code>```

Body:
The health check can be changed by defining custom liveness/readiness probes. In this way, you can define custom endpoints to hit for the health check. Here's a sample from the documentation:

 livenessProbe:
  httpGet:
    path: /healthz
    port: 8080
    httpHeaders:
    - name: X-Custom-Header
      value: Awesome
  initialDelaySeconds: 3
  periodSeconds: 3

If you need something more powerful than a simple HTTP check, you can construct a probe with 'exec' instead of 'httpGet'. With exec, you can use Linux commands or a custom CLI script in your container to query your API or otherwise verify the state of your system. If the command/script returns 0, the pod is seen as healthy. This sample will view the pod as alive if a file exists at /tmp/healthy:

livenessProbe:
  exec:
    command:
    - cat
    - /tmp/healthy
  initialDelaySeconds: 5
  periodSeconds: 5


问:
"URLize" string in ruby
I'm getting some strings on human readable format, and those are gonna be titles of my wordpress posts. So, for generate the url for that post, I would like to know if there's some method for "urlize" a string in ruby. For example, if I have the string "Doing some test on my áccented string ", I would like to get "doing-some-test-on-my-accented-string" or do I have to write my own? Thanks in advance!</p>

答:
Won't give you as pretty results, but

```<code>require 'uri'
URI.escape(string.gsub(/\s+/, ?-)
</code>```

For your example that gives

```<code>"Doing-some-test-on-my-%C3%A1ccented-string"
</code>```

Title: "URLize" string in ruby

Body:
Won't give you as pretty results, but

require 'uri'
URI.escape(string.gsub(/\s+/, ?-)

For your example that gives

"Doing-some-test-on-my-%C3%A1ccented-string"


问:
How to parse nested JSON array using SQL Server
I am currently able to parse most of a JSON file using SQL Server's OPENJSON WITH (... syntax.  However, this particular file contains nested arrays which I do not know how to handle.

Many of the examples I read reference JSON as a variable.  In this case I am calling a file:

select DEV_JSON.*
from OPENROWSET
(BULK 'C:\Users\Myuser\Documents\JSON_extract.json', SINGLE_CLOB) as my_datafile
 CROSS APPLY OPENJSON(BulkColumn)
WITH
  (DOC_ID           varchar(100)  '$.doc._id',
   DOC_REV          varchar(45)   '$.doc._rev',
   DELY_APPL_NAME   varchar(20)   '$.doc.delivery.application',
   DELY_SENT_BY     varchar(25)   '$.doc.delivery.sender.id',
   DELY_SENT_TYPO   varchar(20)   '$.doc.delivery.sender.type',
   .....
   ....
   ...
   ..) as DEV_JSON
```
<p>One of the attributes contains a nested array.  Below I have copied the 1st 5 attributes of my JSON, as well as the nested "recipients" array.</p>
<p>How do I structure my SQL to parse this section?</p>
<pre class="lang-json prettyprint-override"><code>"doc": {
    "_id": "049d4e4030afcdeefedaa90f640f91d4a2be93d7-bd_abcxyz@somemail.com",
    "_rev": "3-e119db13dae8d50ae0c4579ba9c87fc9",
    "delivery": {
        "application": "App_XYZ",
        "sender": {
            "id": "MABarrera@yahoo.com",
            "type": "user"
        },
        "recipients": [{
                "type": "email",
                "recipient": "\"Artzer, Daniel J\" <DJArtzer@emailaddr.com>",
                "sentTS": "2017-10-18T13:04:00.133Z"
            },
            {
                "type": "email",
                "recipient": "\"Higgins, Laura L\" <LLHiggins@emailaddr.com>",
                "sentTS": "2017-10-18T13:04:00.133Z"
            },
            {
                "type": "email",
                "recipient": "\"Friedman, Brian\" <BFriedman@emailaddr.com>",
                "sentTS": "2017-10-18T13:04:00.133Z"
            },
            {
                "type": "email",
                "recipient": "\"Garcia, Charlie M\" <CMGarcia@emailaddr.com>",
                "sentTS": "2017-10-18T13:04:00.133Z"
            }
        ]
    },
</code>```

答:
I just had the same problem, and I ended up solving it with multiple CROSS APPLY clauses.

Here's an example of my JSON:

```<code>DECLARE @PermsJSON NVARCHAR(MAX) =
N'[{
    "AppId": 1,
    "Perms":
    [{

        "Permission": ["AA", "BB"],
        "PermissionTypeID": 2
    },
    {
        "Permission": ["10"],
        "PermissionTypeID": 1
    }]
},
{
    "AppId": 2,
    "Perms":
    [{

        "Permission": ["IM", "NM"],
        "PermissionTypeID": 2
    },
    {
        "Permission": ["42"],
        "PermissionTypeID": 1
    }]
}]';
</code>```

And then I can parse it using the following query:

```<code>SELECT
    a.AppId
    ,[Permission] = c.Value
    ,b.PermissionTypeID
FROM
    OPENJSON(@PermsJSON)
    WITH
        (
            AppId INT N'$.AppId'
            ,Perms NVARCHAR(MAX) AS JSON
        ) AS a
CROSS APPLY
    OPENJSON(a.Perms)
    WITH
        (
            PermissionTypeID INT
            ,[Permission] NVARCHAR(MAX) AS JSON
        ) AS b
CROSS APPLY OPENJSON(b.Permission) AS c;
</code>```

The results then look like this:

```<code>AppId   Permission  PermissionTypeID
1       AA          2
1       BB          2
1       10          1
2       IM          2
2       NM          2
2       42          1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am currently able to parse most of a JSON file using SQL Server's OPENJSON WITH (... syntax.  However, this particular file contains nested arrays which I do not know how to handle.

Many of the examples I read reference JSON as a variable.  In this case I am calling a file:

select DEV_JSON.*
from OPENROWSET
(BULK 'C:\Users\Myuser\Documents\JSON_extract.json', SINGLE_CLOB) as my_datafile
 CROSS APPLY OPENJSON(BulkColumn)
WITH
  (DOC_ID           varchar(100)  '$.doc._id',
   DOC_REV          varchar(45)   '$.doc._rev',
   DELY_APPL_NAME   varchar(20)   '$.doc.delivery.application',
   DELY_SENT_BY     varchar(25)   '$.doc.delivery.sender.id',
   DELY_SENT_TYPO   varchar(20)   '$.doc.delivery.sender.type',
   .....
   ....
   ...
   ..) as DEV_JSON

One of the attributes contains a nested array.  Below I have copied the 1st 5 attributes of my JSON, as well as the nested "recipients" array.

How do I structure my SQL to parse this section?

"doc": {
    "_id": "049d4e4030afcdeefedaa90f640f91d4a2be93d7-bd_abcxyz@somemail.com",
    "_rev": "3-e119db13dae8d50ae0c4579ba9c87fc9",
    "delivery": {
        "application": "App_XYZ",
        "sender": {
            "id": "MABarrera@yahoo.com",
            "type": "user"
        },
        "recipients": [{
                "type": "email",
                "recipient": "\"Artzer, Daniel J\" <DJArtzer@emailaddr.com>",
                "sentTS": "2017-10-18T13:04:00.133Z"
            },
            {
                "type": "email",
                "recipient": "\"Higgins, Laura L\" <LLHiggins@emailaddr.com>",
                "sentTS": "2017-10-18T13:04:00.133Z"
            },
            {
                "type": "email",
                "recipient": "\"Friedman, Brian\" <BFriedman@emailaddr.com>",
                "sentTS": "2017-10-18T13:04:00.133Z"
            },
            {
                "type": "email",
                "recipient": "\"Garcia, Charlie M\" <CMGarcia@emailaddr.com>",
                "sentTS": "2017-10-18T13:04:00.133Z"
            }
        ]
    },

Body:
I just had the same problem, and I ended up solving it with multiple CROSS APPLY clauses.

Here's an example of my JSON:

DECLARE @PermsJSON NVARCHAR(MAX) =
N'[{
    "AppId": 1,
    "Perms":
    [{

        "Permission": ["AA", "BB"],
        "PermissionTypeID": 2
    },
    {
        "Permission": ["10"],
        "PermissionTypeID": 1
    }]
},
{
    "AppId": 2,
    "Perms":
    [{

        "Permission": ["IM", "NM"],
        "PermissionTypeID": 2
    },
    {
        "Permission": ["42"],
        "PermissionTypeID": 1
    }]
}]';

And then I can parse it using the following query:

SELECT
    a.AppId
    ,[Permission] = c.Value
    ,b.PermissionTypeID
FROM
    OPENJSON(@PermsJSON)
    WITH
        (
            AppId INT N'$.AppId'
            ,Perms NVARCHAR(MAX) AS JSON
        ) AS a
CROSS APPLY
    OPENJSON(a.Perms)
    WITH
        (
            PermissionTypeID INT
            ,[Permission] NVARCHAR(MAX) AS JSON
        ) AS b
CROSS APPLY OPENJSON(b.Permission) AS c;

The results then look like this:

AppId   Permission  PermissionTypeID
1       AA          2
1       BB          2
1       10          1
2       IM          2
2       NM          2
2       42          1


问:
Expanding %userprofile% within a Set Variable within an if Statement. Batch
I have something similar to the following...

```<code>set /p dir=Specify Path:
 if exist %dir% (
 echo ok
 ) else(
 echo not ok
)
</code>```

If the user enters a path or variable like %userprofile%

when %dir% is used %userprofile% is not expanded within.

for example

```<code>set dir=%userprofile%
echo %dir% :: this does not expand
call echo %dir% :: this does expand
cd %dir% :: does not expand
call cd %dir% :: expands
</code>```

but how would I have the path expand within a if statement.

Been banging my head on this one and i'm not really understanding DelayedExpansion.

Thanks.

答:
If the user enters an environmental variable as the path you can easily expand that variable by using the CALL command.  So your code will look like this.</p>

```<code>@ECHO OFF
set /p "dir=Specify Path:"

CALL set "dir=%dir%"

if exist "%dir%" (
    echo ok
) else (
    echo not ok
)
</code>```

Body:
I have something similar to the following...

set /p dir=Specify Path:
 if exist %dir% (
 echo ok
 ) else(
 echo not ok
)

If the user enters a path or variable like %userprofile%

when %dir% is used %userprofile% is not expanded within.

for example

set dir=%userprofile%
echo %dir% :: this does not expand
call echo %dir% :: this does expand
cd %dir% :: does not expand
call cd %dir% :: expands

but how would I have the path expand within a if statement.

Been banging my head on this one and i'm not really understanding DelayedExpansion.

Thanks.

Body:
If the user enters an environmental variable as the path you can easily expand that variable by using the CALL command.  So your code will look like this.

@ECHO OFF
set /p "dir=Specify Path:"

CALL set "dir=%dir%"

if exist "%dir%" (
    echo ok
) else (
    echo not ok
)


问:
Preventing classes from being instantiated on the stack or as data member
I'm starting to use shared pointers in C++ (Visual Studio 2010) and run into the following problem.

I am writing a new module which defines an interface that tells the module how to behave in certain conditions.  It's something like this (artifical example just to illustrate my problem):

```<code>// Interface that should be implemented by user of the module
class RingAlert
   {
   public:
      virtual void ring() = 0;
   };

// Module that does something important
class Module
   {
   public:
      Module (RingAlert &ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlert &m_ringAlert;
   };
</code>```

To make it easy for the users of the module, and because the RingAlert could be passed to other modules as well, I am now making this a shared pointer, like this:

```<code>typedef std::shared_ptr<RingAlert> RingAlertPtr;

class Module
   {
   public:
      Module (RingAlertPtr ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlertPtr m_ringAlert;
   };
</code>```

Now users of the module may create a new RingAlert instance and simply pass it to the module, without keeping it somewhere and deleting it at the end of the application.

The problem starts if the application does something like this:

```<code>class MyRingAlert : public RingAlert
   {
   public:
      virtual void ring() {std::cout << "ring ring" << std::endl;}
   };

class Application
   {
   public:
   private:
      MyRingAlert m_myRingAlert;
   };

// later, somewhere in application code
Module m(RingAlertPtr(&m_myRingAlert));
</code>```

In this example, the application takes the address of a data member and puts it in a shared pointer.
Later in the application, the destructor of the Module will delete the shared pointer, which will decrement the reference count, and which will then delete the ring alert, which mustn't be deleted because it is a data member of the Application class.

I found a way of preventing the shared pointer from deleting the instance by doing this (using lambda's but also have a slightly cleaner solution using a function):

```<code>Module m(RingAlertPtr(&m_myRingAlert,[](void *){});
</code>```

Although this solves my problem, I'm not completely happy with it because it will still give a problem if the Application class is destructed before the Module class.

The only good solution seems to be to force the rest of the application to new the instance of RingAlert (or actually the class that implements RingAlert).

Can this be done?
Is there a way to prevent code from instantiating subclasses of a base class on the stack or as datamember?
In other words: can we force subclasses of a base class being newed if they want to be instantiated?

答:
What I tend to do - and it's by no means the right way - or even the best way is as follows:

```<code>struct IType
{
    typedef shared_ptr<IType> Ptr;

    virtual DoSomething( ) = 0;

protected:
    virtual ~IType( ) { }
};

class Type : public IType
{
public:
    typedef shared_ptr<Type> Ptr;

    static Ptr New( )
    {
        return Ptr(
                   new Type( ),
                   &Type::Delete
                  );
    }

private:

    virtual void DoSomething( );

    Type( ); // Defined in the CPP file.

    static void Delete( Type* p )
    {
        delete ( p );
    }
};
</code>```

So you can only ever create an object of type Type::Ptr, You cannot delete the enclosed type through the .get() method.

Hope this helps.

ContentLicense: CC BY-SA 2.5

Body:
I'm starting to use shared pointers in C++ (Visual Studio 2010) and run into the following problem.

I am writing a new module which defines an interface that tells the module how to behave in certain conditions.  It's something like this (artifical example just to illustrate my problem):

// Interface that should be implemented by user of the module
class RingAlert
   {
   public:
      virtual void ring() = 0;
   };

// Module that does something important
class Module
   {
   public:
      Module (RingAlert &ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlert &m_ringAlert;
   };

To make it easy for the users of the module, and because the RingAlert could be passed to other modules as well, I am now making this a shared pointer, like this:

typedef std::shared_ptr<RingAlert> RingAlertPtr;

class Module
   {
   public:
      Module (RingAlertPtr ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlertPtr m_ringAlert;
   };

Now users of the module may create a new RingAlert instance and simply pass it to the module, without keeping it somewhere and deleting it at the end of the application.

The problem starts if the application does something like this:

class MyRingAlert : public RingAlert
   {
   public:
      virtual void ring() {std::cout << "ring ring" << std::endl;}
   };

class Application
   {
   public:
   private:
      MyRingAlert m_myRingAlert;
   };

// later, somewhere in application code
Module m(RingAlertPtr(&m_myRingAlert));

In this example, the application takes the address of a data member and puts it in a shared pointer.
Later in the application, the destructor of the Module will delete the shared pointer, which will decrement the reference count, and which will then delete the ring alert, which mustn't be deleted because it is a data member of the Application class.

I found a way of preventing the shared pointer from deleting the instance by doing this (using lambda's but also have a slightly cleaner solution using a function):

Module m(RingAlertPtr(&m_myRingAlert,[](void *){});

Although this solves my problem, I'm not completely happy with it because it will still give a problem if the Application class is destructed before the Module class.

The only good solution seems to be to force the rest of the application to new the instance of RingAlert (or actually the class that implements RingAlert).

Can this be done?
Is there a way to prevent code from instantiating subclasses of a base class on the stack or as datamember?
In other words: can we force subclasses of a base class being newed if they want to be instantiated?

Body:
What I tend to do - and it's by no means the right way - or even the best way is as follows:

struct IType
{
    typedef shared_ptr<IType> Ptr;

    virtual DoSomething( ) = 0;

protected:
    virtual ~IType( ) { }
};

class Type : public IType
{
public:
    typedef shared_ptr<Type> Ptr;

    static Ptr New( )
    {
        return Ptr(
                   new Type( ),
                   &Type::Delete
                  );
    }

private:

    virtual void DoSomething( );

    Type( ); // Defined in the CPP file.

    static void Delete( Type* p )
    {
        delete ( p );
    }
};

So you can only ever create an object of type Type::Ptr, You cannot delete the enclosed type through the .get() method.

Hope this helps.


问:
403 forbidden when use CGI in apache in mac os x
mac 10.12.6

The config of apache

```<code>LoadModule cgi_module libexec/apache2/mod_cgi.so

ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/cgi-bin/$1"

<Directory "/Library/WebServer/cgi-bin/">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
AddHandler cgi-script .cgi
</Directory>

AddHandler cgi-script .cgi
</code>```

and the file ls -l

```<code>user:cgi-bin root# ls -l
total 8
-rwxr-xr-x@ 1 user  wheel  60 Oct 27 21:57 server.cgi
</code>```

that's the test in command line

```<code>root# /library/webserver/cgi-bin/server.cgi
Content-type:text/plain
hello world
</code>```

and if I go to

http://localhost/cgi-bin/server.cgi

its response:

```<code>Forbidden

You don't have permission to access /cgi-bin/server.cgi on this server.
</code>```

I have try anything that I can do.

答:
Yaha I found the problem

it's a problem with Apache 2.4

You have to check allow and deny rules

Check out http://httpd.apache.org/docs/2.4/upgrading.html#access

In 2.2, access control based on client hostname, IP address, and other characteristics of client requests was done using the directives Order, Allow, Deny, and Satisfy.

In 2.4, such access control is done in the same way as other authorization checks, using the new module mod_authz_host.
The new directive is Require:

2.2 configuration:

```<code>Order allow,deny
Allow from all
</code>```

2.4 configuration:

```<code>Require all granted
</code>```

Body:
mac 10.12.6

The config of apache

LoadModule cgi_module libexec/apache2/mod_cgi.so

ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/cgi-bin/$1"

<Directory "/Library/WebServer/cgi-bin/">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
AddHandler cgi-script .cgi
</Directory>

AddHandler cgi-script .cgi

and the file ls -l

user:cgi-bin root# ls -l
total 8
-rwxr-xr-x@ 1 user  wheel  60 Oct 27 21:57 server.cgi

that's the test in command line

root# /library/webserver/cgi-bin/server.cgi
Content-type:text/plain
hello world

and if I go to

http://localhost/cgi-bin/server.cgi

its response:

Forbidden

You don't have permission to access /cgi-bin/server.cgi on this server.

I have try anything that I can do.

Body:
Yaha I found the problem

it's a problem with Apache 2.4

You have to check allow and deny rules

Check out http://httpd.apache.org/docs/2.4/upgrading.html#access

In 2.2, access control based on client hostname, IP address, and other characteristics of client requests was done using the directives Order, Allow, Deny, and Satisfy.

In 2.4, such access control is done in the same way as other authorization checks, using the new module mod_authz_host.
The new directive is Require:

2.2 configuration:

Order allow,deny
Allow from all

2.4 configuration:

Require all granted


问:
Confusing flow error when dealing with multiple promises and callbacks
I'm adding flow to a project, and I've run into an error I can't figure out. Here's some code that produces the same error:

```<code>type user = {
  id: string,
};

const thing = function(): Promise<user> {
  return new Promise(resolve => {
    var p1 = new Promise(innerResolve => {
      getData(data => {
        innerResolve(data);
      });
    });
    Promise.all([p1]).then(result => {
      resolve(result[0]);
    });
  });
};

const getData = function(callback) {
  setTimeout(() => {
    callback({});
  }, 1000);
};
</code>```

Link to this code on Try Flow, where you can read the error.

In my application, the getData function goes out to a database to get the object. And the type of what it returns in the callback can only be this specific:

```<code>{
  [key: string]: string,
}
</code>```

So it could be called with an empty object, like in the example. If you replace that line with:

```<code>callback({id: 'working'})
</code>```

there are no type errors. But I can't do that in my application.

Another strange thing is that I can remove this whole block:

```<code>Promise.all([p1]).then(result => {
  resolve(result[0]);
});
</code>```

and that also makes it pass the flow test.

And the one thing I'd think would fix this issue -- refinements -- don't resolve the issue.

```<code>    if (typeof data === 'object' && typeof data.id === 'string') {
      innerResolve(data);
    } else {
      throw new Error('bad db response');
    }
</code>```

I haven't been able to figure out any way to get flow to accept this code, without changing something that I can't actually change (like replacing the database code with a simple return).

Can anyone explain the error I'm seeing, and why I'm triggering it?

答:
you are explicitly setting the return type of thing function to Promise<user>, and that's why you get the error since your callback passes the parameter {} which is NOT a user

I don't know what your specific requirement is or why you are using a timeout but if the return type can be something that is NOT user, meaning any you can make the return type: you can set the return type to Promise<user|any>

You explicitly set the return type, so you have to return that return type.

Body:
I'm adding flow to a project, and I've run into an error I can't figure out. Here's some code that produces the same error:

type user = {
  id: string,
};

const thing = function(): Promise<user> {
  return new Promise(resolve => {
    var p1 = new Promise(innerResolve => {
      getData(data => {
        innerResolve(data);
      });
    });
    Promise.all([p1]).then(result => {
      resolve(result[0]);
    });
  });
};

const getData = function(callback) {
  setTimeout(() => {
    callback({});
  }, 1000);
};

Link to this code on Try Flow, where you can read the error.

In my application, the getData function goes out to a database to get the object. And the type of what it returns in the callback can only be this specific:

{
  [key: string]: string,
}

So it could be called with an empty object, like in the example. If you replace that line with:

callback({id: 'working'})

there are no type errors. But I can't do that in my application.

Another strange thing is that I can remove this whole block:

Promise.all([p1]).then(result => {
  resolve(result[0]);
});

and that also makes it pass the flow test.

And the one thing I'd think would fix this issue -- refinements -- don't resolve the issue.

    if (typeof data === 'object' && typeof data.id === 'string') {
      innerResolve(data);
    } else {
      throw new Error('bad db response');
    }

I haven't been able to figure out any way to get flow to accept this code, without changing something that I can't actually change (like replacing the database code with a simple return).

Can anyone explain the error I'm seeing, and why I'm triggering it?


问:
Shuffling array in multiple threads
I have an array of size N. I want to shuffle its elements in 2 threads (or more). Each thread should work with it's own part of the array.

Lets say, the first thread shuffles elements from 0 to K, and the second thread shuffles elements from K to N (where 0 < K < N). So, it can look like this:

```<code>//try-catch stuff is ommited
static void shuffle(int[] array) {
   Thread t1 = new ShufflingThread(array, 0, array.length / 2);
   Thread t2 = new ShufflingThread(array, array.length / 2, array.length);
   t1.start();
   t2.start();
   t1.join();
   t2.join();
}

public static void main(String[] args) {
   int array = generateBigSortedArray();
   shuffle(array);
}
</code>```

Are there any guaranties from JVM that I will see changes in the array from the main method after such shuffling?

How should I implement ShufflingThread (or, how should I run it, maybe within a synchronized block or whatever else) in order to get such guaranties?

答:
The join() calls are sufficient to ensure memory coherency: when t1.join() returns, the main thread "sees" whatever operations thread t1 did on the array.

Also, Java guarantees that there is no word-tearing on arrays: distinct threads may use distinct elements of the same array without needing synchronization.

Title: Shuffling array in multiple threads

Body:
I have an array of size N. I want to shuffle its elements in 2 threads (or more). Each thread should work with it's own part of the array.

Lets say, the first thread shuffles elements from 0 to K, and the second thread shuffles elements from K to N (where 0 < K < N). So, it can look like this:

//try-catch stuff is ommited
static void shuffle(int[] array) {
   Thread t1 = new ShufflingThread(array, 0, array.length / 2);
   Thread t2 = new ShufflingThread(array, array.length / 2, array.length);
   t1.start();
   t2.start();
   t1.join();
   t2.join();
}

public static void main(String[] args) {
   int array = generateBigSortedArray();
   shuffle(array);
}

Are there any guaranties from JVM that I will see changes in the array from the main method after such shuffling?

How should I implement ShufflingThread (or, how should I run it, maybe within a synchronized block or whatever else) in order to get such guaranties?


问:
Why does my Perf Mon Logical Disk Counters for C and D are the same?
I have been gathering performance counter of 1 of our busiest server and hopefully analyze it after a week long data gathering. To my dismay, when I reviewed all the Logical Disk Counters of drive C and D the where just the same.

Here is my data collector setup

Based on the definition of this counters there should be a big difference because the D is where the oracle database files reside, it should have a more activity spikes and more average values compared to drive C.

Drive C counters result

Drive D counters result

See the Avg. Disk Bytes / Write counter, both the same.

Can you please advice what I am missing here.

答:
Your Performance Monitor is showing the same details for both, i.e. the total across ALL drives and not just for the C: drive on one graph and the D: drive on the other. I have configured similar and got the same results.

What I have found is that if you add \LogicalDiks(C:)* to the data collector then you do not get the counters for the C: drive but the total across all drives. However if you add each of the individual Logical Disk Counters that you are interested in then you do get them for the selected drive, e.g.
\LogicalDisk(C:)\% Disk Read Time
\LogicalDisk(C:)\% Disk Time
\LogicalDisk(C:)\% Disk Write Time
\LogicalDisk(C:)\% Free Space
\LogicalDisk(C:)\% Idle Time
\LogicalDisk(C:)\Avg. Disk Bytes/Read
\LogicalDisk(C:)\Avg. Disk Bytes/Transfer
e.t.c

This is the same for the Physical Disk counters.


答:
indeed, an empty object is not of type user. Instead of returning an empty object when you have no match, is to return an empty array, and make your thing function return an array.

This changes the semantics: thing returns a promise of an empty array when there is no match, or an array with one element when there is.

```<code>const thing = function(): Promise<user[]> {
</code>```

... and the callback call should pass an array with zero or one elements:

```<code>callback([]);
</code>```

Your sample code could also be reduced to this, but I assume you have other code that made you write it like you did:

```<code>type user = {
  id: string,
};

const thing = function(): Promise<user[]> {
  return new Promise(getData);
};

const getData = function(callback) {
  setTimeout(() => {
    callback([]);
  }, 1000);
};
</code>```

On Try Flow

Title: Confusing flow error when dealing with multiple promises and callbacks

Body:
indeed, an empty object is not of type user. Instead of returning an empty object when you have no match, is to return an empty array, and make your thing function return an array.

This changes the semantics: thing returns a promise of an empty array when there is no match, or an array with one element when there is.

const thing = function(): Promise<user[]> {

... and the callback call should pass an array with zero or one elements:

callback([]);

Your sample code could also be reduced to this, but I assume you have other code that made you write it like you did:

type user = {
  id: string,
};

const thing = function(): Promise<user[]> {
  return new Promise(getData);
};

const getData = function(callback) {
  setTimeout(() => {
    callback([]);
  }, 1000);
};

On Try Flow


问:
C# .NET Entity Framework multi-tenant best practice
Consider the following code segment:

```<code>public class DatabaseContext : DbContext
{
   public DatabaseContext(String connectionString) : base(connectionString)
   {
   }
}

public class ContextNameDatabaseContext : DatabaseContext
{
   public ContextNameDatabaseContext(String connectionString) : base(connectionString)
   {
   }
}
</code>```

Would one say it is best practice when building the back-end for a multi-tenant solution where each client has its own database and maintain the data state until a user logs out / off?

Developer using these classes in this instance will need to be aware and careful as to when and how the classes are being used where the 'DatabaseContext' class acts as a base to the 'ContextNameDatabaseContext' class.

Please advise on any thoughts or suggestions.

答:
One approach is to keep all the database connection strings as parameters in the database. However you have to assure that its encrypted.

Then at your DB layer you can pass the connection as parameter in plain text after decrypting and constructing your connection string accordingly:

```<code>public class MyDatabase: DbContext
{
    public MyDatabase(string connString)
    {
        this.Database.Connection.ConnectionString = connString;
    }
    public DbSet<Order> Orders{ get; set; }
}
</code>```

You can also use IOptions if you are using .NET Core to inject the connection string as a dependency.

Body:
Consider the following code segment:

public class DatabaseContext : DbContext
{
   public DatabaseContext(String connectionString) : base(connectionString)
   {
   }
}

public class ContextNameDatabaseContext : DatabaseContext
{
   public ContextNameDatabaseContext(String connectionString) : base(connectionString)
   {
   }
}

Would one say it is best practice when building the back-end for a multi-tenant solution where each client has its own database and maintain the data state until a user logs out / off?

Developer using these classes in this instance will need to be aware and careful as to when and how the classes are being used where the 'DatabaseContext' class acts as a base to the 'ContextNameDatabaseContext' class.

Please advise on any thoughts or suggestions.

Body:
One approach is to keep all the database connection strings as parameters in the database. However you have to assure that its encrypted.

Then at your DB layer you can pass the connection as parameter in plain text after decrypting and constructing your connection string accordingly:

public class MyDatabase: DbContext
{
    public MyDatabase(string connString)
    {
        this.Database.Connection.ConnectionString = connString;
    }
    public DbSet<Order> Orders{ get; set; }
}

You can also use IOptions if you are using .NET Core to inject the connection string as a dependency.


问:
Getting a certain value out of a nested array
I have a json file with two arrays, one of them is nested. I need to get the numbers from the nested array and match them with a value (id) in the unnested array so that I can send the matched values in the unnested array to another function. I have been trying to figure this out for two straight days and haven't been able to figure out what it is I am doing wrong. Any pointers or help would be appreciated.

I have the data to my json here for reference.

```<code>{
  "videos": [
    {
      "id": 1,
      "title": "Lego!",
      "created": 1509804047011,
      "duration": 5,
      "poster": "./videos/small.png",
      "video": "./videos/small.mp4"
    },
    {
      "id": 2,
      "title": "Big Bunny",
      "created": 1507804047011,
      "duration": 62,
      "poster": "./videos/bunny.png",
      "video": "./videos/bunny.mp4"
    },
    {
      "id": 3,
      "title": "Prufu myndband",
      "created": 1505904047011,
      "duration": 3600,
      "poster": "./videos/16-9.png",
      "video": "./videos/bunny.mp4"
    },
    {
      "id": 4,
      "title": "Prufu myndband með löngum texta sem fer í tvær línur",
      "created": 1504904047011,
      "duration": 220,
      "poster": "./videos/16-9.png",
      "video": "./videos/bunny.mp4"
    }
  ],

  "categories": [
    {
      "title": "New videos",
      "videos": [1, 2]
    },
    {
      "title": "Amazing videos",
      "videos": [1, 3, 4]
    },
    {
      "title": "Funny videos",
      "videos": [2, 3, 4]
    }
  ]
}
</code>```

答:
Just iterate over the categories and find the videos:

```<code>for(const {title, videos} of data.categories){
  for(const id of videos){
    const video = data.videos.find(v => v.id === id);
    //do whatever with video
  }
}
</code>```

Alternatively if you just want to get the videos that are mentioned in the nested categories:

```<code>const ids = new Set( data.categories.reduce((res, videos) => res.concat(videos)) );

const result = data.videos.filter(v => ids.has(v.id));
</code>```

Body:
I have a json file with two arrays, one of them is nested. I need to get the numbers from the nested array and match them with a value (id) in the unnested array so that I can send the matched values in the unnested array to another function. I have been trying to figure this out for two straight days and haven't been able to figure out what it is I am doing wrong. Any pointers or help would be appreciated.

I have the data to my json here for reference.

{
  "videos": [
    {
      "id": 1,
      "title": "Lego!",
      "created": 1509804047011,
      "duration": 5,
      "poster": "./videos/small.png",
      "video": "./videos/small.mp4"
    },
    {
      "id": 2,
      "title": "Big Bunny",
      "created": 1507804047011,
      "duration": 62,
      "poster": "./videos/bunny.png",
      "video": "./videos/bunny.mp4"
    },
    {
      "id": 3,
      "title": "Prufu myndband",
      "created": 1505904047011,
      "duration": 3600,
      "poster": "./videos/16-9.png",
      "video": "./videos/bunny.mp4"
    },
    {
      "id": 4,
      "title": "Prufu myndband með löngum texta sem fer í tvær línur",
      "created": 1504904047011,
      "duration": 220,
      "poster": "./videos/16-9.png",
      "video": "./videos/bunny.mp4"
    }
  ],

  "categories": [
    {
      "title": "New videos",
      "videos": [1, 2]
    },
    {
      "title": "Amazing videos",
      "videos": [1, 3, 4]
    },
    {
      "title": "Funny videos",
      "videos": [2, 3, 4]
    }
  ]
}

Body:
Just iterate over the categories and find the videos:

for(const {title, videos} of data.categories){
  for(const id of videos){
    const video = data.videos.find(v => v.id === id);
    //do whatever with video
  }
}

Alternatively if you just want to get the videos that are mentioned in the nested categories:

const ids = new Set( data.categories.reduce((res, videos) => res.concat(videos)) );

const result = data.videos.filter(v => ids.has(v.id));


问:
Assign log depending user department change history
I have to create a select statement that get information from a MS SQL Server based on user printing. The problem is, each user has an specific department id and we have a changing history from that department. So my report must be smart enough to allocate printing from a specificperiod, like 1 month, and, if that user had it department changed, it will allocate those printing to the correct department. (for eg, the first 15 days his dept was IT and the other day it was changed to Development)...

Let me show my database:

USER

```<code>id       name              department_id

1        John Doe          2
</code>```

DEPARTMENT

```<code>id          name

1           T.I

2           Dev

3           R&D

4           FRONT

5           BACK
</code>```

USER_DEPARTMENT_HISTORY

```<code>id  user_id  department_id start_date   end_date

1   1        1             1900-01-01   2017-11-10

2   1        2             2017-11-10   2017-11-15

3   1        3             2017-11-15   2999-01-01
</code>```

LOG

```<code>id          user_id     pages       printed_on

1           1           5           2017-11-10 00:00:00.000

2           1           7           2017-10-12 00:00:00.000

3           1           3           2017-10-10 00:00:00.000

4           1           3           2017-09-10 00:00:00.000

5           1           3           2017-09-11 00:00:00.000
</code>```

It would be a nice approach IF we shouldn't consider it changing department history

答:
you can use joins  as follows

```<code>select  u.name as [user] ,d.name as department,l.pages,l.printed_on
from user u
inner join USER_DEPARTMENT_HISTORY dh on u.id = dh.[user_id]
inner join Department d on d.id = dh.department_id
inner join LOG l on l.[user_id] = u.id and printed_on>=[start_date] and printed_on <end_date
</code>```

Complete Script:

```<code>create table #user
( id int,
[name] varchar(25),
department_id int
)

insert into #user
values(1,'John Doe',2)

create table #Department
(
id int,
name varchar(25)
)

insert into #DEPARTMENT
values(1,'T.I'),
(2,'Dev'),
(3,'R&D'),
(4,'FRONT'),
(5,'BACK')

create table #USER_DEPARTMENT_HISTORY
(
id  int ,
[user_id]   int,
department_id int,
start_date   date,
end_date date
)

insert into #USER_DEPARTMENT_HISTORY
values(1,1,1,'1900-01-01','2017-11-10'),
(2,1,2,'2017-11-10','2017-11-15'),
(3,1,3,'2017-11-15','2999-01-01')

create table #LOG
(
id  int ,
[user_id]   int,
pages int,
printed_on   datetime
)

insert into #LOG
values(1,1,5,'2017-11-10 00:00:00.000'),
(2,1,7,'2017-10-12 00:00:00.000'),
(3,1,3,'2017-10-10 00:00:00.000'),
(4,1,3,'2017-09-10 00:00:00.000'),
(5,1,3,'2017-09-11 00:00:00.000')

select  u.name as [user] ,d.name as department,l.pages,l.printed_on
from #user u
inner join #USER_DEPARTMENT_HISTORY dh on u.id = dh.[user_id]
inner join #Department d on d.id = dh.department_id
inner join #LOG l on l.[user_id] = u.id and printed_on>=[start_date] and printed_on <end_date

drop table #user
drop table #USER_DEPARTMENT_HISTORY
drop table #Department
drop table #LOG
</code>```

Body:
I have to create a select statement that get information from a MS SQL Server based on user printing. The problem is, each user has an specific department id and we have a changing history from that department. So my report must be smart enough to allocate printing from a specificperiod, like 1 month, and, if that user had it department changed, it will allocate those printing to the correct department. (for eg, the first 15 days his dept was IT and the other day it was changed to Development)...

Let me show my database:

USER

id       name              department_id

1        John Doe          2

DEPARTMENT

id          name

1           T.I

2           Dev

3           R&D

4           FRONT

5           BACK

USER_DEPARTMENT_HISTORY

id  user_id  department_id start_date   end_date

1   1        1             1900-01-01   2017-11-10

2   1        2             2017-11-10   2017-11-15

3   1        3             2017-11-15   2999-01-01

LOG

id          user_id     pages       printed_on

1           1           5           2017-11-10 00:00:00.000

2           1           7           2017-10-12 00:00:00.000

3           1           3           2017-10-10 00:00:00.000

4           1           3           2017-09-10 00:00:00.000

5           1           3           2017-09-11 00:00:00.000

It would be a nice approach IF we shouldn't consider it changing department history

Body:
you can use joins  as follows

select  u.name as [user] ,d.name as department,l.pages,l.printed_on
from user u
inner join USER_DEPARTMENT_HISTORY dh on u.id = dh.[user_id]
inner join Department d on d.id = dh.department_id
inner join LOG l on l.[user_id] = u.id and printed_on>=[start_date] and printed_on <end_date

Complete Script:

create table #user
( id int,
[name] varchar(25),
department_id int
)

insert into #user
values(1,'John Doe',2)

create table #Department
(
id int,
name varchar(25)
)

insert into #DEPARTMENT
values(1,'T.I'),
(2,'Dev'),
(3,'R&D'),
(4,'FRONT'),
(5,'BACK')

create table #USER_DEPARTMENT_HISTORY
(
id  int ,
[user_id]   int,
department_id int,
start_date   date,
end_date date
)

insert into #USER_DEPARTMENT_HISTORY
values(1,1,1,'1900-01-01','2017-11-10'),
(2,1,2,'2017-11-10','2017-11-15'),
(3,1,3,'2017-11-15','2999-01-01')

create table #LOG
(
id  int ,
[user_id]   int,
pages int,
printed_on   datetime
)

insert into #LOG
values(1,1,5,'2017-11-10 00:00:00.000'),
(2,1,7,'2017-10-12 00:00:00.000'),
(3,1,3,'2017-10-10 00:00:00.000'),
(4,1,3,'2017-09-10 00:00:00.000'),
(5,1,3,'2017-09-11 00:00:00.000')

select  u.name as [user] ,d.name as department,l.pages,l.printed_on
from #user u
inner join #USER_DEPARTMENT_HISTORY dh on u.id = dh.[user_id]
inner join #Department d on d.id = dh.department_id
inner join #LOG l on l.[user_id] = u.id and printed_on>=[start_date] and printed_on <end_date

drop table #user
drop table #USER_DEPARTMENT_HISTORY
drop table #Department
drop table #LOG


问:
Linux rename files before directories
I have the following command that I run to lowercase files/directories, replace . with _ and various other manipulations.  The problem with it is that it seems to try to rename the directories first and then it cannot find the files below it. Is there a way to rename all files in a directory first then the directory itself recursively?  e.g.

directory1

file1

file2

directory1

file1

file2

directory2

file1

directory2

file1

file2

My code is

```<code>while IFS= read -rd '' entry; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      rename  'y/A-Z/a-z/; s/ /_/g; s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   else
      rename  'y/A-Z/a-z/; s/\.(?=.*\.)/_/g; s/ /_/g;  s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   fi
done < <(find . -iname '*' -print0)
</code>```

答:
I was thinking of something along this line:

```<code>find /path |awk -F/ '{print NF,$0}' |sort -r -n -k 1 |cut -f2- -d' ' |\
  while IFS= read -rd '' entry; do
    # ...
  done
</code>```

The idea is to prepend each line with the number of / and sort reversely according to this field:

4 /path/dir1/file1

  4 /path/dir2/file2

  3 /path/dir1

  3 /path/dir2

  2 /path

Then cut away the first column. This way you can work on the entries bottom up to avoid renaming issues.

Title: Linux rename files before directories

Body:
I have the following command that I run to lowercase files/directories, replace . with _ and various other manipulations.  The problem with it is that it seems to try to rename the directories first and then it cannot find the files below it. Is there a way to rename all files in a directory first then the directory itself recursively?  e.g.

directory1

file1

file2

directory1

file1

file2

directory2

file1

directory2

file1

file2

My code is

while IFS= read -rd '' entry; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      rename  'y/A-Z/a-z/; s/ /_/g; s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   else
      rename  'y/A-Z/a-z/; s/\.(?=.*\.)/_/g; s/ /_/g;  s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   fi
done < <(find . -iname '*' -print0)

Body:
I was thinking of something along this line:

find /path |awk -F/ '{print NF,$0}' |sort -r -n -k 1 |cut -f2- -d' ' |\
  while IFS= read -rd '' entry; do
    # ...
  done

The idea is to prepend each line with the number of / and sort reversely according to this field:

4 /path/dir1/file1

  4 /path/dir2/file2

  3 /path/dir1

  3 /path/dir2

  2 /path

Then cut away the first column. This way you can work on the entries bottom up to avoid renaming issues.


问:
Upload new object to CloudFront. Curl show the file changed but the browsers don't
I am trying to understand this weird behaviour.

I've a web distribution list on CloudFront which takes files from S3.

I've set in CF the

```<code>Minimum TTL: max-age=15
</code>```

and I can see the max age value also in the page header with curl

```
Content-Type: text/html
Content-Length: 851
Connection: keep-alive
Date: Thu, 16 Nov 2017 16:48:08 GMT
Last-Modified: Thu, 16 Nov 2017 16:48:01 GMT
ETag: "6f05a132c76b8e482f8f72f3cd2aa2b1"
Cache-Control: max-age=15
Accept-Ranges: bytes
Server: AmazonS3
X-Cache: RefreshHit from cloudfront
Via: 1.1 dba4881aee9ac99f5dba4dcd7e8175b1.cloudfront.net (CloudFront)
X-Amz-Cf-Id: 8Cwu-1UPFb2BL03mvu3exf17UzWqCZVrUGvNtc2xCeVg47G1UnqVjg==
```

Once I uploaded the new html page which contain my changes, if I curl the resource I can see the page changed.
If I open the page with Firefox/Chrome the page doesn't changed and the max-age value is not respected since the age value in the header is around 32000

```
date    : Thu, 16 Nov 2017 17:23:41 GMT
etag    :"8ad74acb5563f12bfd239683a3d96d75"
cache-control:15
server  :AmazonS3
age :31029
x-cache :Hit from cloudfront
via :1.1 1d3fdb2bba223d815ff2e40453…8.cloudfront.net (CloudFront)
x-amz-cf-id :ooeDeSw-_ZpMDR25_yN9VhfyJF2FeAgiklzE5QZusNRs_glDqobgcg==
```

What else I missed from or did I not consider?

答:
Changing an object in S3 does not push it to CloudFront if it's already cached there, as this one is... from 31029 seconds before you made the request.

```<code>age :31029
</code>```

To evict objects from the CloudFront cache (forcing CloudFront to make a new request from the origin the next time the object is requested) requires an invalidation.

Note also that Minimum TTL has no real meaning, here, since that is the minimum max-age or s-maxage that CloudFront will respect when it initially caches the object.  It only does anything when the object has a maximum lifetime that is shorter than the minimum, and it is most likely of no consequence once an object is cached.

Body:
I am trying to understand this weird behaviour.

I've a web distribution list on CloudFront which takes files from S3.

I've set in CF the

Minimum TTL: max-age=15

and I can see the max age value also in the page header with curl

Content-Type: text/html
Content-Length: 851
Connection: keep-alive
Date: Thu, 16 Nov 2017 16:48:08 GMT
Last-Modified: Thu, 16 Nov 2017 16:48:01 GMT
ETag: "6f05a132c76b8e482f8f72f3cd2aa2b1"
Cache-Control: max-age=15
Accept-Ranges: bytes
Server: AmazonS3
X-Cache: RefreshHit from cloudfront
Via: 1.1 dba4881aee9ac99f5dba4dcd7e8175b1.cloudfront.net (CloudFront)
X-Amz-Cf-Id: 8Cwu-1UPFb2BL03mvu3exf17UzWqCZVrUGvNtc2xCeVg47G1UnqVjg==

Once I uploaded the new html page which contain my changes, if I curl the resource I can see the page changed.
If I open the page with Firefox/Chrome the page doesn't changed and the max-age value is not respected since the age value in the header is around 32000

date    : Thu, 16 Nov 2017 17:23:41 GMT
etag    :"8ad74acb5563f12bfd239683a3d96d75"
cache-control:15
server  :AmazonS3
age :31029
x-cache :Hit from cloudfront
via :1.1 1d3fdb2bba223d815ff2e40453…8.cloudfront.net (CloudFront)
x-amz-cf-id :ooeDeSw-_ZpMDR25_yN9VhfyJF2FeAgiklzE5QZusNRs_glDqobgcg==

What else I missed from or did I not consider?

Body:
Changing an object in S3 does not push it to CloudFront if it's already cached there, as this one is... from 31029 seconds before you made the request.

age :31029

To evict objects from the CloudFront cache (forcing CloudFront to make a new request from the origin the next time the object is requested) requires an invalidation.

Note also that Minimum TTL has no real meaning, here, since that is the minimum max-age or s-maxage that CloudFront will respect when it initially caches the object.  It only does anything when the object has a maximum lifetime that is shorter than the minimum, and it is most likely of no consequence once an object is cached.


问:
Spring Data REST - Implementing user detail service
I am trying to implement the user detail service to include audit data for the entities.

The UserEntity class is as follows:

```<code>@Data
@Entity
@Audited
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true,updatable = false)
    private String uuid;

    private String username;

    private String firstName;

    private String lastName;
}
</code>```

I also have the following class which includes the audit meta data. This class will be extended by other entities.

```<code>@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Audited
public class Auditable {

    @CreatedDate
    private Long createdDate;

    @LastModifiedDate
    private Long lastModifiedDate;

    @CreatedBy
    private UserEntity createdBy;

    @LastModifiedBy
    private UserEntity modifiedBy;

}
</code>```

Here is my user detail service.

```<code>@Configuration
@EnableJpaAuditing
public class SpringSecurityAuditorAware implements AuditorAware<UserEntity> {

    @Autowired
    private AccessToken accessToken;

    @Autowired
    private UserEntityRepository userRepo;

    @Override
    public UserEntity getCurrentAuditor() {

        UserEntity user = userRepo.findByUuid(accessToken.getSubject());
        return user;
    }

}
</code>```

Now when I run the code I get the following error message.

```<code>Caused by: org.hibernate.MappingException: Could not determine type for: api.core.model.UserEntity, at table: business_entity, for columns: [org.hibernate.mapping.Column(created_by)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.configuration.internal.metadata.AuditMetadataGenerator.addValueInFirstPass(AuditMetadataGenerator.java:219) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.configuration.internal.metadata.AuditMetadataGenerator.addValue(AuditMetadataGenerator.java:345) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.configuration.internal.metadata.AuditMetadataGenerator.addProperties(AuditMetadataGenerator.java:371) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.configuration.internal.metadata.AuditMetadataGenerator.generateFirstPass(AuditMetadataGenerator.java:662) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.configuration.internal.EntitiesConfigurator.configure(EntitiesConfigurator.java:94) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.boot.internal.EnversServiceImpl.doInitialize(EnversServiceImpl.java:152) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.boot.internal.EnversServiceImpl.initialize(EnversServiceImpl.java:117) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.boot.internal.AdditionalJaxbMappingProducerImpl.produceAdditionalMappings(AdditionalJaxbMappingProducerImpl.java:99) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:288) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    ... 171 common frames omitted
</code>```

If I remove the UserEntity fields everything works fine and the audit data createdDate and lastModifiedDate are correctly recorded in the database.

I also included @ManyToOne annotation for UserEntity fields and the code runs fine but the database does not have the fields createdBy and modifiedBy. How do I fix this?

答: we should have table called Auditable_aud.</p>

Body:
I am trying to implement the user detail service to include audit data for the entities.

The UserEntity class is as follows:

@Data
@Entity
@Audited
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true,updatable = false)
    private String uuid;

    private String username;

    private String firstName;

    private String lastName;
}

I also have the following class which includes the audit meta data. This class will be extended by other entities.

@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Audited
public class Auditable {

    @CreatedDate
    private Long createdDate;

    @LastModifiedDate
    private Long lastModifiedDate;

    @CreatedBy
    private UserEntity createdBy;

    @LastModifiedBy
    private UserEntity modifiedBy;

}

Here is my user detail service.

@Configuration
@EnableJpaAuditing
public class SpringSecurityAuditorAware implements AuditorAware<UserEntity> {

    @Autowired
    private AccessToken accessToken;

    @Autowired
    private UserEntityRepository userRepo;

    @Override
    public UserEntity getCurrentAuditor() {

        UserEntity user = userRepo.findByUuid(accessToken.getSubject());
        return user;
    }

}

Now when I run the code I get the following error message.

Caused by: org.hibernate.MappingException: Could not determine type for: api.core.model.UserEntity, at table: business_entity, for columns: [org.hibernate.mapping.Column(created_by)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.configuration.internal.metadata.AuditMetadataGenerator.addValueInFirstPass(AuditMetadataGenerator.java:219) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.configuration.internal.metadata.AuditMetadataGenerator.addValue(AuditMetadataGenerator.java:345) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.configuration.internal.metadata.AuditMetadataGenerator.addProperties(AuditMetadataGenerator.java:371) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.configuration.internal.metadata.AuditMetadataGenerator.generateFirstPass(AuditMetadataGenerator.java:662) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.configuration.internal.EntitiesConfigurator.configure(EntitiesConfigurator.java:94) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.boot.internal.EnversServiceImpl.doInitialize(EnversServiceImpl.java:152) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.boot.internal.EnversServiceImpl.initialize(EnversServiceImpl.java:117) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.envers.boot.internal.AdditionalJaxbMappingProducerImpl.produceAdditionalMappings(AdditionalJaxbMappingProducerImpl.java:99) ~[hibernate-envers-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:288) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    ... 171 common frames omitted

If I remove the UserEntity fields everything works fine and the audit data createdDate and lastModifiedDate are correctly recorded in the database.

I also included @ManyToOne annotation for UserEntity fields and the code runs fine but the database does not have the fields createdBy and modifiedBy. How do I fix this?


问:
Ansible inside script command not found
Ansible:

```<code>-   name: Node package manager
    npm:
        name: pm2
        global: yes
    notify:
        - restart nginx

-   name: start the app
    script: ../files/common/pm2.sh app_name {{ user }}
    tags: test
</code>```

Script file:

```<code>#!/bin/bash
APP_NAME=$1
USER=$2

if [ "$USER" != "" ]; then
    PATH="/home/$USER/"
else
    PATH="/var/www/"
fi

pm2 describe ${APP_NAME} > /dev/null       # line no 11
RUNNING=$?

if [ "${RUNNING}" -ne 0 ]; then
  cd ${PATH}${APP_NAME}/ && pm2 start npm --name "${APP_NAME}" -- start
else
  pm2 restart ${APP_NAME}
fi;
</code>```

When I tried to run pm2 command on the remote machine, It's working. But, not running from ansible script file.

Error:

fatal: [webserver]: FAILED! => {"changed": true, "failed": true, "msg": "non-zero return code", "rc": 1, "stderr": "Shared connection to xx.xx.xx.xx closed.\r\n", "stdout": "/home/ronak/.ansible/tmp/ansible-tmp-1510939424.06-225768915266978/pm2.sh: line 11: pm2: command not found\r\n127\r\n", "stdout_lines": ["/home/ronak/.ansible/tmp/ansible-tmp-1510939424.06-225768915266978/pm2.sh: line 11: pm2: command not found", "127"]}

答:
You're overwriting the PATH environment variable in your script.  This is used to determine where executables are located (see https://en.wikipedia.org/wiki/PATH_(variable)).

Short answer is to use a different name for PATH in your script and use absolute paths for commands in your script.

Title: Ansible inside script command not found

Body:
Ansible:

-   name: Node package manager
    npm:
        name: pm2
        global: yes
    notify:
        - restart nginx

-   name: start the app
    script: ../files/common/pm2.sh app_name {{ user }}
    tags: test

Script file:

#!/bin/bash
APP_NAME=$1
USER=$2

if [ "$USER" != "" ]; then
    PATH="/home/$USER/"
else
    PATH="/var/www/"
fi

pm2 describe ${APP_NAME} > /dev/null       # line no 11
RUNNING=$?

if [ "${RUNNING}" -ne 0 ]; then
  cd ${PATH}${APP_NAME}/ && pm2 start npm --name "${APP_NAME}" -- start
else
  pm2 restart ${APP_NAME}
fi;

When I tried to run pm2 command on the remote machine, It's working. But, not running from ansible script file.

Error:

fatal: [webserver]: FAILED! => {"changed": true, "failed": true, "msg": "non-zero return code", "rc": 1, "stderr": "Shared connection to xx.xx.xx.xx closed.\r\n", "stdout": "/home/ronak/.ansible/tmp/ansible-tmp-1510939424.06-225768915266978/pm2.sh: line 11: pm2: command not found\r\n127\r\n", "stdout_lines": ["/home/ronak/.ansible/tmp/ansible-tmp-1510939424.06-225768915266978/pm2.sh: line 11: pm2: command not found", "127"]}


问:
Encode xml from structs
I'm new to go and trying to get the following piece of code to work with no luck. Looks like I don't have the struct of structs part correctly coded. Help!

```<code>package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

func main() {

    type Person struct {
        Email string `xml:"email"`
        Phone string `xml:"phone"`
    }

    type Host struct {
        Hostname string `xml:"hostname"`
        Address  string `xml:"address"`
    }

    type Asset struct {
        person Person
        host   Host
    }

    p := &Person{Email: "person@a.com", Phone: "1111"}
    h := &Host{Hostname: "boxen", Address: "1 Place St"}
    a := &Asset{person: *p, host: *h}

    enc := xml.NewEncoder(os.Stdout)
    enc.Indent(" ", " ")
    if err := enc.Encode(p); err != nil {
        fmt.Printf("error: %v\n", err)
    }
    if err := enc.Encode(h); err != nil {
        fmt.Printf("error: %v\n", err)
    }
    if err := enc.Encode(a); err != nil {
        fmt.Printf("error: %v\n", err)
    }
}
</code>```

Go playground here

Expected output. What I currently get is an empty Asset element.

```<code> <Asset>
   <Person>
    <email>person@a.com</email>
    <phone>1111</phone>
   </Person>
   <Host>
    <hostname>boxen</hostname>
    <address>1 Place St</address>
   </Host>
 </Asset>
</code>```

答:
As long as person and host are unexported, there is no way for enc.Encode to know about them. Exporting them will give your desired output.

```<code>package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

func main() {

    type Person struct {
        Email string `xml:"email"`
        Phone string `xml:"phone"`
    }

    type Host struct {
        Hostname string `xml:"hostname"`
        Address  string `xml:"address"`
    }

    type Asset struct {
        Person Person
        Host   Host
    }

    p := &Person{Email: "person@a.com", Phone: "1111"}
    h := &Host{Hostname: "boxen", Address: "1 Place St"}
    a := &Asset{Person: *p, Host: *h}

    enc := xml.NewEncoder(os.Stdout)
    enc.Indent(" ", " ")

    if err := enc.Encode(a); err != nil {
        fmt.Printf("error: %v\n", err)
    }
}
</code>```

Title: Encode xml from structs

Body:
I'm new to go and trying to get the following piece of code to work with no luck. Looks like I don't have the struct of structs part correctly coded. Help!

package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

func main() {

    type Person struct {
        Email string `xml:"email"`
        Phone string `xml:"phone"`
    }

    type Host struct {
        Hostname string `xml:"hostname"`
        Address  string `xml:"address"`
    }

    type Asset struct {
        person Person
        host   Host
    }

    p := &Person{Email: "person@a.com", Phone: "1111"}
    h := &Host{Hostname: "boxen", Address: "1 Place St"}
    a := &Asset{person: *p, host: *h}

    enc := xml.NewEncoder(os.Stdout)
    enc.Indent(" ", " ")
    if err := enc.Encode(p); err != nil {
        fmt.Printf("error: %v\n", err)
    }
    if err := enc.Encode(h); err != nil {
        fmt.Printf("error: %v\n", err)
    }
    if err := enc.Encode(a); err != nil {
        fmt.Printf("error: %v\n", err)
    }
}

Go playground here

Expected output. What I currently get is an empty Asset element.

 <Asset>
   <Person>
    <email>person@a.com</email>
    <phone>1111</phone>
   </Person>
   <Host>
    <hostname>boxen</hostname>
    <address>1 Place St</address>
   </Host>
 </Asset>

Body:
As long as person and host are unexported, there is no way for enc.Encode to know about them. Exporting them will give your desired output.

package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

func main() {

    type Person struct {
        Email string `xml:"email"`
        Phone string `xml:"phone"`
    }

    type Host struct {
        Hostname string `xml:"hostname"`
        Address  string `xml:"address"`
    }

    type Asset struct {
        Person Person
        Host   Host
    }

    p := &Person{Email: "person@a.com", Phone: "1111"}
    h := &Host{Hostname: "boxen", Address: "1 Place St"}
    a := &Asset{Person: *p, Host: *h}

    enc := xml.NewEncoder(os.Stdout)
    enc.Indent(" ", " ")

    if err := enc.Encode(a); err != nil {
        fmt.Printf("error: %v\n", err)
    }
}


问:
Can anyone tell me the import statement for Java's Combinations class?
I tried to import Combinations by

```<code>import java.lang.org.apache.commons.math3.util.Combinations;
</code>```

but I keep getting error when I use Combinations in my source code.

```<code>import java.util.*;
import java.org.apache.commons.math3.util.Combinations;

public class PowerSet{   //gets power set for a set containing first n integers

    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(args[0]);

        for(int i=0; i<=n; i++){
            Combinations c = new Combinations(n,i);
            Iterator iter = c.iterator();
            while(iter.hasNext()){
                int[] iarr = (int[])iter.next();
                System.out.print("{" + iarr[0]);
                for(int a=1; a<iarr.length; a++){
                    System.out.println(", " + iarr[a]);
                }
                System.out.print("}, ");
            }
        }
    }
}
</code>```

And the error I get clearly says the class does not exist. Am I getting the hierarchy wrong or the way I should have imported the class is wrong?

```<code>package java.org.apache.commons.math3.util does not exist
import java.org.apache.commons.math3.util.Combinations;
                                     ^
PowerSet.java:11: error: cannot find symbol
        Combinations c = new Combinations(n,i);
        ^
symbol:   class Combinations
location: class PowerSet
</code>```

答:
As you can see from your import statement </p>

```<code>java.lang.org.apache.commons.math3.util.Combinations;
</code>```

<p>is not in core java / jee package rather referring a 3rd party package repository. so you need to download that package and put that into your classpath or project lib directory or use your IDE or compile command to point that package somewhere in your system. however, now a days devs are using various build tool such as maven or gradle to manage such project dependencies overheads.  </p>

Body:
I tried to import Combinations by

import java.lang.org.apache.commons.math3.util.Combinations;

but I keep getting error when I use Combinations in my source code.

import java.util.*;
import java.org.apache.commons.math3.util.Combinations;

public class PowerSet{   //gets power set for a set containing first n integers

    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(args[0]);

        for(int i=0; i<=n; i++){
            Combinations c = new Combinations(n,i);
            Iterator iter = c.iterator();
            while(iter.hasNext()){
                int[] iarr = (int[])iter.next();
                System.out.print("{" + iarr[0]);
                for(int a=1; a<iarr.length; a++){
                    System.out.println(", " + iarr[a]);
                }
                System.out.print("}, ");
            }
        }
    }
}

And the error I get clearly says the class does not exist. Am I getting the hierarchy wrong or the way I should have imported the class is wrong?

package java.org.apache.commons.math3.util does not exist
import java.org.apache.commons.math3.util.Combinations;
                                     ^
PowerSet.java:11: error: cannot find symbol
        Combinations c = new Combinations(n,i);
        ^
symbol:   class Combinations
location: class PowerSet

Body:
As you can see from your import statement

java.lang.org.apache.commons.math3.util.Combinations;

is not in core java / jee package rather referring a 3rd party package repository. so you need to download that package and put that into your classpath or project lib directory or use your IDE or compile command to point that package somewhere in your system. however, now a days devs are using various build tool such as maven or gradle to manage such project dependencies overheads.


问:
POST versus Ajax call
Now that most modern browsers support AJAX and client-side requests without performing a POST, what is the role of POST (form post)?

Are there situations or general rules when a POST will always be preferred to a XmlHttpRequest?

All that POST is doing is placing variable key value pairs inside the server head. The advantages of POST I can think of are large amounts of data and mobile browsers. Are there many others I'm missing?

N.B. I know you can perform POSTs with AJAX calls, I'm talking primarily about with a <form> tag

答:
This question is a little tricky because it conflates two concepts.  The first is POSTing and the second is Ajax.  POSTing, as compared to GETting, is a different HTTP method with different implementation and semantics.  Ajax, or XmlHttpRequest, has its counterpart in normal requesting/navigation.  You can use POST or GET for both XmlHttpRequest and normal navigation and form submission (well, POST is always a "form submission").  The difference between XmlHttpRequest and normal requests is that a normal request replaces the page with a new page.

You could write just about any website using only Ajax to get data and change the DOM; that's mainly how Gmail works.  There are no "form submissions" in the traditional sense.  But there are still GETs and POSTs because the server and browsers interpret the results differently.  GET is supposed to be idempotent; POST is meant for operations that change the state on the server.  For example, an ecom transaction should be a POST.  This doesn't change when using Ajax because you want proxy servers to also understand that this is a POST and that they shouldn't try to cache the response.

There are also advantages and disadvantages to using GET vs POST.  You can't bookmark the results of a POST because the parameters are hidden.  You can't GET something with parameter values of unlimited length because IE only supports about 2000 chars.

Also there are disadvantages to using Ajax vs normal submissions; you can't bookmark the resulting page (because the page hasn't changed); the back button won't work as expected. But with Ajax you could minimize the data transfered and also provide convenient updates to a page (such as monitoring the status of a long process) without annoying flickering or refreshing.

In summary the two request types, Ajax and traditional form submission, can both be used with GETs and POSTs, and there are pros and cons for each.  Neither type can do everything the other can and so you can expect to see a mix for the foreseeable future.

OwnerDisplayName: Chris

Title: POST versus Ajax call

OwnerDisplayName: Mr. Shiny and New


问:
Is there a way to unit test ASP.NET MVC ViewBag properties set in the view?
Say I have a view with the following code at the top of the page:

```<code>@{
    ViewBag.Title = "About Us";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
</code>```

And I have a controller method:

```<code>    public ActionResult About()
    {
        return View();
    }
</code>```

How can I test that the ViewBag was set properly?

I have tried the following code.

```<code>[TestCase]
public void About()
{
    var controller = new AboutController();
    var ar = controller.About() as ViewResult;
    Assert.AreEqual("About Us", ar.ViewBag.Title);
}
</code>```

But I get the following result when I run the test:

```<code>Tests.Controllers.AboutControllerTests.About():
    Expected: "About Us"
    But was: null
</code>```

答:
The ViewResult returned by a controller has only a reference to the view that should be shown. The view is not even resolved at this time. The code there is never executed by your test.

What you should do is set ViewBag properties in the controller, not the view. Usually, the view will only read such values.

hope it helps

Body:
Say I have a view with the following code at the top of the page:

@{
    ViewBag.Title = "About Us";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

And I have a controller method:

    public ActionResult About()
    {
        return View();
    }

How can I test that the ViewBag was set properly?

I have tried the following code.

[TestCase]
public void About()
{
    var controller = new AboutController();
    var ar = controller.About() as ViewResult;
    Assert.AreEqual("About Us", ar.ViewBag.Title);
}

But I get the following result when I run the test:

Tests.Controllers.AboutControllerTests.About():
    Expected: "About Us"
    But was: null


问:
What Is the Cost of a Correctly Predicted Branch (On Any CPU)
Based from what I read, it seems like the cost might be 0 cycles. Is it really 0 cycles? If the cost is 0 cycles, does this include the jump instruction itself instead of just the possible flush in the CPU instruction cache? I appreciate answers on any CPU architecture.</p>

答: In general, when someone says that a correctly predicted conditional branch is "free", they don't mean that it magically happens instantaneously, they mean that it has the same cost as an unconditional jump, i.e. that the "conditional" is free, not the whole branch.</p>


问:
Are there any git commands that will explicitly destroy a commit?
Does Git ever truly destroy commits or just orphan them? I am aware that the git garbage collector will remove orphaned commits when run with git gc on whatever interval is set in git config. Are there any other cases that will delete a commit?

答: git-prune has the explicit mission statement of deleting orphaned objects.


问:
Rails 3 app will not match a route even though rake routes shows it
Here is a portion of my routes file:

resource :vendor do post 'modify_account' end

Running rake routes will generate the following line

```<code>           modify_account_vendor POST   /vendor/modify_account(.:format)                               {:action=>"modify_account", :controller=>"vendors"}
                          vendor POST   /vendor(.:format)                                              {:action=>"create", :controller=>"vendors"}
                      new_vendor GET    /vendor/new(.:format)                                          {:action=>"new", :controller=>"vendors"}
                     edit_vendor GET    /vendor/edit(.:format)                                         {:action=>"edit", :controller=>"vendors"}
                                 GET    /vendor(.:format)                                              {:action=>"show", :controller=>"vendors"}
                                 PUT    /vendor(.:format)                                              {:action=>"update", :controller=>"vendors"}
                                 DELETE /vendor(.:format)                                              {:action=>"destroy", :controller=>"vendors"}
                                        /vendor(.:format)                                              {:action=>"account", :controller=>"vendors"}
</code>```

I can load the form and verify the URL is correct in the form's action, but when I submit, the app throws an error:

No route matches "/vendor/modify_account"

Any suggestions as to what I can do to troubleshoot? Firebug verifies that the error page is of type POST.

答:
As it turns out, I believe the issue was with my choice of "action verb" - I should have been using PUT instead of POST. This is my new routes file, and the only thing I had to change was the _url helper method names.</p>

```<code>resource :vendor do put 'account', :action => 'modify_account' end
</code>```

Body:
Here is a portion of my routes file:

resource :vendor do post 'modify_account' end

Running rake routes will generate the following line

           modify_account_vendor POST   /vendor/modify_account(.:format)                               {:action=>"modify_account", :controller=>"vendors"}
                          vendor POST   /vendor(.:format)                                              {:action=>"create", :controller=>"vendors"}
                      new_vendor GET    /vendor/new(.:format)                                          {:action=>"new", :controller=>"vendors"}
                     edit_vendor GET    /vendor/edit(.:format)                                         {:action=>"edit", :controller=>"vendors"}
                                 GET    /vendor(.:format)                                              {:action=>"show", :controller=>"vendors"}
                                 PUT    /vendor(.:format)                                              {:action=>"update", :controller=>"vendors"}
                                 DELETE /vendor(.:format)                                              {:action=>"destroy", :controller=>"vendors"}
                                        /vendor(.:format)                                              {:action=>"account", :controller=>"vendors"}

I can load the form and verify the URL is correct in the form's action, but when I submit, the app throws an error:

No route matches "/vendor/modify_account"

Any suggestions as to what I can do to troubleshoot? Firebug verifies that the error page is of type POST.

Body:
As it turns out, I believe the issue was with my choice of "action verb" - I should have been using PUT instead of POST. This is my new routes file, and the only thing I had to change was the _url helper method names.

resource :vendor do put 'account', :action => 'modify_account' end