问:
How to get mean directly from a csv row range in R?

Following is my code to read more than 1000 csv files, where each file has over 1000 rows and 4 columns. Each csv file has only 4 columns, such as ID, values, param1, param2. My current code snippet reads each file separately with their respective file names into a data frame. It's pretty clean frame per se. Because it's already implemented, I am only looking for a code that can be integrated to my function.

e.g. input

```<code>200 4.864 ne15 hx1
201 4.872 ne12 hx3
202 4.898 ne10 hx9
203 4.815 ne23 hx1
204 4.699 ne14 hx3
...
212 4.813 ne20 hx2
213 4.763 ne18 hx8
...
</code>```

Output :
e.g.

```<code>index  row#.   value     filename
# mean should be the value for row 2 to 20
# it needs to be output in R under row 202
154    202.0   4.337     1wq.csv
164    225.0   4.358     1wq.csv
174    250.0   4.421     1wq.csv
184    275.0   4.498     1wq.csv
194    300.0   4.513     1wq.csv
</code>```

Instead of getting 2 to 20 conseuctive values from csv file row (18 values) in that column, I want to get the mean value corresponding to values from row 2 to 20. How can I do that?

```<code>#set working directly to the folder where csv files are located
files <- list.files(pattern='.csv')
m = data.frame()
 for (k in 1:length(files)){
    csv = read.csv(files[k], header = FALSE)

    #picking up 2:20 consecutive values, value for row 50,120,150 so on
    data = csv[c(2:20, 50, 120, 150, 175, 200), c(1,2)]

    #-pivot transform col/row- data <- as.data.frame(t(data))
    #but that line screwed up the data
    #when those selected values are with NA/blanks
    data$file = files[k]

    m = rbind(m, data)
 }
</code>```

With thanks to both the answers, I managed the following:
I will try AdamQuek's answer separately again to improve mine.
For now, I am closing this question as solved.

```<code>m = data.frame()
for (k in 1:length(files)) {
  csv = read.csv(files[k], header = FALSE)
  data = csv[c(2:20, 225, 250, 275, 300, 325, 350), c(1,2)]
  data[1,] <- mean(data[c(2:19),c(2)], na.rm=T)
  data <- data[-2:-19,]
  data[c(1),c(1)] = 200
  data$file = files[k]
  data <- as.data.frame(t(data))
  m = rbind(m, data)
}
</code>```

答:
Is something like this what you are trying to accomplish?</p>

```<code># Insert the mean of rows 2:20 into row 202
csv[202,"value"] <- mean(csv[2:20,"value])

# Drop rows 2:20 from the dataframe
csv <- csv[-2:-20,]
</code>```

Body:
Following is my code to read more than 1000 csv files, where each file has over 1000 rows and 4 columns. Each csv file has only 4 columns, such as ID, values, param1, param2. My current code snippet reads each file separately with their respective file names into a data frame. It's pretty clean frame per se. Because it's already implemented, I am only looking for a code that can be integrated to my function.

e.g. input

200 4.864 ne15 hx1
201 4.872 ne12 hx3
202 4.898 ne10 hx9
203 4.815 ne23 hx1
204 4.699 ne14 hx3
...
212 4.813 ne20 hx2
213 4.763 ne18 hx8
...

Output :
e.g.

index  row#.   value     filename
# mean should be the value for row 2 to 20
# it needs to be output in R under row 202
154    202.0   4.337     1wq.csv
164    225.0   4.358     1wq.csv
174    250.0   4.421     1wq.csv
184    275.0   4.498     1wq.csv
194    300.0   4.513     1wq.csv

Instead of getting 2 to 20 conseuctive values from csv file row (18 values) in that column, I want to get the mean value corresponding to values from row 2 to 20. How can I do that?

#set working directly to the folder where csv files are located
files <- list.files(pattern='.csv')
m = data.frame()
 for (k in 1:length(files)){
    csv = read.csv(files[k], header = FALSE)

    #picking up 2:20 consecutive values, value for row 50,120,150 so on
    data = csv[c(2:20, 50, 120, 150, 175, 200), c(1,2)]

    #-pivot transform col/row- data <- as.data.frame(t(data))
    #but that line screwed up the data
    #when those selected values are with NA/blanks
    data$file = files[k]

    m = rbind(m, data)
 }

With thanks to both the answers, I managed the following:
I will try AdamQuek's answer separately again to improve mine.
For now, I am closing this question as solved.

m = data.frame()
for (k in 1:length(files)) {
  csv = read.csv(files[k], header = FALSE)
  data = csv[c(2:20, 225, 250, 275, 300, 325, 350), c(1,2)]
  data[1,] <- mean(data[c(2:19),c(2)], na.rm=T)
  data <- data[-2:-19,]
  data[c(1),c(1)] = 200
  data$file = files[k]
  data <- as.data.frame(t(data))
  m = rbind(m, data)
}

Body:
Is something like this what you are trying to accomplish?

# Insert the mean of rows 2:20 into row 202
csv[202,"value"] <- mean(csv[2:20,"value])

# Drop rows 2:20 from the dataframe
csv <- csv[-2:-20,]


来源: stackexchange

问:
share objects between controllers using services
I have to controllers the first controller is "cockpitController"and the other one  "idCardSupplierWarnController" .In the first controller i set my objects and i checked if the set work and it work i can see all my objects but when i want to get my objects in the other controller then all my objects are null .

PS: I checked this solution it's working for the case that the controller is in the same Window of the navigator but in my case it's in new window using $window.open(url).

Le service idCardSupplierWarnService :

```<code>var app = angular.module('idCardSupplierWarn');

app.service('idCardSupplierWarnService', function () {

    this.idRefNum = "";
    this.idSupNum = "";
    this.codeSuppNum = "";

    this.setParam = function (paramSet) {

        console.log(paramSet);

        this.idRefNum = paramSet.designRefPart;
        this.idSupNum = paramSet.idSuppNumber;
        this.codeSuppNum = paramSet.codeSupp;

    };

    this.getParamSupNum = function () {

        return this.idSupNum;

    };

    this.getParamCodeSupNum = function () {

        return this.codeSuppNum;

    };

    this.getParamIdRefNum = function () {

        return this.idRefNum;

    };

});
</code>```

Le controller cockpitController :

```<code>    (function () {
        angular
            .module("cockpit", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
            .controller('cockpitController', ['$scope', '$translate', 'serviceCockpit','idCardSupplierWarnService', '$window', function ($scope, $translate, serviceCockpit,idCardSupplierWarnService,$window) {

                var urlSuppliersWarning = 'rest/suppliers/warnings';
                var urlSuppliersWarningByRefForDetails = 'rest/suppliers/warnings/supplier/ref/search';

                var self = this;

                serviceCockpit.loadData([urlSuppliersWarning]).then(function (results) {
                    self.suppliersWarning = results[0].data;
                });

                this.change = function () {

                    if (this.openWindow) {
                        this.openWindow = false;
                    }
                    else {
                        this.openWindow = true;
                    }

                };

                $scope.openNewWindowRef = function (url, params) {
                    console.log(params);
                    idCardSupplierWarnService.setParam(params);
                    console.log(idCardSupplierWarnService.getParams());
                    $window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
                };

                $scope.openNewWindowSupp = function (url, params) {
                    idCardSupplierWarnService.setParam(params);
                    console.log(idCardSupplierWarnService);
                    $window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
                };

                this.process = function (items) {

                    if (items.origin == 'reference' || items.origin == 'suppliers' || items.origin == 'supplierAccounts' || items.origin == 'supplierAddressCodes' || items.origin == 'reset') {

                        serviceCockpit.loadData([urlSuppliersWarningByRefForDetails], items).then(function (results) {
                            self.suppliersWarningDetails = results[0].data;
                        });
                    }

                    serviceCockpit.loadData([urlSuppliersWarning], items).then(function (results) {
                        self.suppliersWarning = results[0].data;
                    });
                }

            }]);
    })();
</code>```

Le controller **idCardSupplierWarnController :**

```<code> (function () {
    angular
        .module("idCardSupplierWarn", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
        .controller('idCardSupplierWarnController', ['$translate', '$scope', 'serviceCockpit','idCardSupplierWarnService', function ($translate, $scope, serviceCockpit,idCardSupplierWarnService) {

            var urlSupplierWarningByRefDetail = 'rest/suppliers/warnings/supplier/details';

            var self = this;

             var params = {} ;

             params.idRefNum = idCardSupplierWarnService.getParamIdRefNum();
             params.idSupNum = idCardSupplierWarnService.getParamSupNum();
             params.codeSuppNum = idCardSupplierWarnService.getParamCodeSupNum();
                      console.log(params.codeSuppNum);

            serviceCockpit.loadData([urlSupplierWarningByRefDetail], params).then(function (results) {
                self.suppliersWarningsList = results[0].data;
            });

        }]);
})();
</code>```

答:
You need to inject idCardSupplierWarn module into cockpit module, to access the service.

```<code>angular.module("cockpit", ['mm.foundation', 'security', 'message', `isteven-multi-select`, `idCardSupplierWarn`])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have to controllers the first controller is "cockpitController"and the other one  "idCardSupplierWarnController" .In the first controller i set my objects and i checked if the set work and it work i can see all my objects but when i want to get my objects in the other controller then all my objects are null .

PS: I checked this solution it's working for the case that the controller is in the same Window of the navigator but in my case it's in new window using $window.open(url).

Le service idCardSupplierWarnService :

var app = angular.module('idCardSupplierWarn');

app.service('idCardSupplierWarnService', function () {

    this.idRefNum = "";
    this.idSupNum = "";
    this.codeSuppNum = "";

    this.setParam = function (paramSet) {

        console.log(paramSet);

        this.idRefNum = paramSet.designRefPart;
        this.idSupNum = paramSet.idSuppNumber;
        this.codeSuppNum = paramSet.codeSupp;

    };

    this.getParamSupNum = function () {

        return this.idSupNum;

    };

    this.getParamCodeSupNum = function () {

        return this.codeSuppNum;

    };

    this.getParamIdRefNum = function () {

        return this.idRefNum;

    };

});

Le controller cockpitController :

    (function () {
        angular
            .module("cockpit", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
            .controller('cockpitController', ['$scope', '$translate', 'serviceCockpit','idCardSupplierWarnService', '$window', function ($scope, $translate, serviceCockpit,idCardSupplierWarnService,$window) {

                var urlSuppliersWarning = 'rest/suppliers/warnings';
                var urlSuppliersWarningByRefForDetails = 'rest/suppliers/warnings/supplier/ref/search';

                var self = this;

                serviceCockpit.loadData([urlSuppliersWarning]).then(function (results) {
                    self.suppliersWarning = results[0].data;
                });

                this.change = function () {

                    if (this.openWindow) {
                        this.openWindow = false;
                    }
                    else {
                        this.openWindow = true;
                    }

                };

                $scope.openNewWindowRef = function (url, params) {
                    console.log(params);
                    idCardSupplierWarnService.setParam(params);
                    console.log(idCardSupplierWarnService.getParams());
                    $window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
                };

                $scope.openNewWindowSupp = function (url, params) {
                    idCardSupplierWarnService.setParam(params);
                    console.log(idCardSupplierWarnService);
                    $window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
                };

                this.process = function (items) {

                    if (items.origin == 'reference' || items.origin == 'suppliers' || items.origin == 'supplierAccounts' || items.origin == 'supplierAddressCodes' || items.origin == 'reset') {

                        serviceCockpit.loadData([urlSuppliersWarningByRefForDetails], items).then(function (results) {
                            self.suppliersWarningDetails = results[0].data;
                        });
                    }

                    serviceCockpit.loadData([urlSuppliersWarning], items).then(function (results) {
                        self.suppliersWarning = results[0].data;
                    });
                }

            }]);
    })();

Le controller **idCardSupplierWarnController :**

 (function () {
    angular
        .module("idCardSupplierWarn", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
        .controller('idCardSupplierWarnController', ['$translate', '$scope', 'serviceCockpit','idCardSupplierWarnService', function ($translate, $scope, serviceCockpit,idCardSupplierWarnService) {

            var urlSupplierWarningByRefDetail = 'rest/suppliers/warnings/supplier/details';

            var self = this;

             var params = {} ;

             params.idRefNum = idCardSupplierWarnService.getParamIdRefNum();
             params.idSupNum = idCardSupplierWarnService.getParamSupNum();
             params.codeSuppNum = idCardSupplierWarnService.getParamCodeSupNum();
                      console.log(params.codeSuppNum);

            serviceCockpit.loadData([urlSupplierWarningByRefDetail], params).then(function (results) {
                self.suppliersWarningsList = results[0].data;
            });

        }]);
})();

Body:
You need to inject idCardSupplierWarn module into cockpit module, to access the service.

angular.module("cockpit", ['mm.foundation', 'security', 'message', `isteven-multi-select`, `idCardSupplierWarn`])


问:
$q.all of AngularJS only works for one result
I am working on function that calculates a distance from a given object to a number of other places with the help of Google Distance Matrix which is of course async therefore I'm dealing with promises.

When the number of places is one, everything works great. But once I have more than one promise, $q.all doesn't do anything : it neither resolves in a success nor in error. Though I have checked in the console that the calls to the Google distance matrix do happen and return a correct result. Any clue what can be at play here?

I am using AngularJS 1.6.4. Let me know should you need any more details. Thanks!

```<code>var requests = [];
for (var i = 0; i < ctrl.places.length; i += 1) {
    var deferred = $q.defer();
    requests.push(deferred.promise);
    var destination = ctrl.places[i].latLng;
    service.getDistanceMatrix({
        origins: [ctrl.origin],
        destinations: [destination[0] + "," + destination[1]],
        travelMode: 'DRIVING'
    }, function(response, status) {
        if (status === 'OK') {
            deferred.resolve(response.rows[0].elements[0].distance.text);
        }
    });
}

$q.all(requests).then(function(result) {
    ctrl.distances = result;
});
</code>```

答:
Your problem is that var is not block-scoped, so the value of deferred will always belong to the final iteration of your loop by the time any of your callbacks are invoked. A consequence of this will that the earlier deferred will never be resolved and the $q.all will appear to hang.

The simplest way to resolve this is to change your use of var to let to take advantage of block scoping:

```<code>let deferred = $q.defer();
</code>```

Body:
I am working on function that calculates a distance from a given object to a number of other places with the help of Google Distance Matrix which is of course async therefore I'm dealing with promises.

When the number of places is one, everything works great. But once I have more than one promise, $q.all doesn't do anything : it neither resolves in a success nor in error. Though I have checked in the console that the calls to the Google distance matrix do happen and return a correct result. Any clue what can be at play here?

I am using AngularJS 1.6.4. Let me know should you need any more details. Thanks!

var requests = [];
for (var i = 0; i < ctrl.places.length; i += 1) {
    var deferred = $q.defer();
    requests.push(deferred.promise);
    var destination = ctrl.places[i].latLng;
    service.getDistanceMatrix({
        origins: [ctrl.origin],
        destinations: [destination[0] + "," + destination[1]],
        travelMode: 'DRIVING'
    }, function(response, status) {
        if (status === 'OK') {
            deferred.resolve(response.rows[0].elements[0].distance.text);
        }
    });
}

$q.all(requests).then(function(result) {
    ctrl.distances = result;
});

Body:
Your problem is that var is not block-scoped, so the value of deferred will always belong to the final iteration of your loop by the time any of your callbacks are invoked. A consequence of this will that the earlier deferred will never be resolved and the $q.all will appear to hang.

The simplest way to resolve this is to change your use of var to let to take advantage of block scoping:

let deferred = $q.defer();


问:
c++ How could I properly predefined array of char*?
I am doing it that way:

```<code>int argc = 9;
char* argv[argc];

argv[0] = "c:/prog.exe";
</code>```

but I get notice, that it is deprecated. What is better way?

答:
Let analyze what you are doing here:

```<code>// Create an int with value 9.
int argc = 9;

// Create an array of char* pointers of size 9
char* argv[argc];

// Assign the the first pointer to the global data string "C:\prog.exe"
argv[0] = "c:/prog.exe";
</code>```

My guess is that you are not trying to do what I've described above. Try something like this:

```<code>// create an array of characters
char argv[] = "C:/prog.exe";

// argc in now the length of the string
int argc = sizeof argv;
</code>```

-or -

```<code>// create an array of strings
char* argv[] = {"C:/prog.exe"};
// argc is now the number of strings in the array
int argc = 1;
</code>```

Body:
I am doing it that way:

int argc = 9;
char* argv[argc];

argv[0] = "c:/prog.exe";

but I get notice, that it is deprecated. What is better way?

Body:
Let analyze what you are doing here:

// Create an int with value 9.
int argc = 9;

// Create an array of char* pointers of size 9
char* argv[argc];

// Assign the the first pointer to the global data string "C:\prog.exe"
argv[0] = "c:/prog.exe";

My guess is that you are not trying to do what I've described above. Try something like this:

// create an array of characters
char argv[] = "C:/prog.exe";

// argc in now the length of the string
int argc = sizeof argv;

-or -

// create an array of strings
char* argv[] = {"C:/prog.exe"};
// argc is now the number of strings in the array
int argc = 1;

ContentLicense: CC BY-SA 2.5


问:
C Printfs are expecting a Type Specifier
Trying to figure out what I'm doing wrong with my C code here. The last two printf calls are asking for a type specifier and I don't know what to give it. The other lines don't have this issue. Any help is appreciated!

Edit The program does multiple math functions and the two print lines in question are supposed to print the results of two of these equations. The first one is supposed to print the remainder of the two numbers the user enters, the second printf is supposed to print out the answer of adding the two numbers together, multiplying that by the first number, and dividing it by the second number. Both of these printf lines give me the error of E0079, expected a type specifier.

Edit 2: Solved this issue by changing my SDK pack for the project, and also putting the calculations after asking the user for the numbers. Jimmy's formatting tips also helped fix it. Thank you so much to all of you who helped.

```<code>#include <stdio.h>
#include <stdlib.h>

main(void) {

    int digit1; //First digit user gives
    int digit2; //Second digit user gives.
    int product; //The result of the two user given numbers multiplied.
    int cube; //The result of cubing the second number.
    int remainder; //The remainder of dividing the two given numbers.
    int tooManySteps; //The result of adding the two given numbers together, multiplying it by the first given number, dividing by the second number.

    product = digit1 * digit2;
    cube = digit2 * digit2 * digit2;
    remainder = digit1 % digit2;
    tooManySteps = (digit1 + digit2) * digit1 / digit2;

    printf("Hi there, want me to do some cool math for you? Great! Just give me a number please.");
    scanf("%d", &digit1);

    printf("Cool! Now just give me one number.");
    scanf("%d", &digit2);

    printf("Your numbers multiplied together give you %d \n", product);

    printf("Now the cube of the second number you gave is %d \n", cube);

    printf("If you were to divide your two numbers together your remainder would be %d\n", remainder);

    printf("Now we'll get really crazy, if you were to add your two numbers, multiply them by the first number you gave and divide by the second number you gave, you would get %d\n", tooManySteps);
}
</code>```

答:
I really think it's a bad question. But I still correct the code for you.</p>

```<code>int main(void)
{
    int digit1; //First digit user gives
    int digit2; //Second digit user gives.
    int product; //The result of the two user given numbers multiplied.
    int cube; //The result of cubing the second number.
    int remainder; //The remainder of dividing the two given numbers.
    int tooManySteps; //The result of adding the two given numbers together,
                      //multiplying it by the first given number,
                      //dividing by the second number.

    printf("Hi there, want me to do some cool math for you? Great! "
           "Just give me a number please.");
    scanf("%d", &digit1);

    printf("Cool! Now just give me one number.");
    scanf("%d", &digit2);

    product = digit1 * digit2;
    cube = digit2 * digit2 * digit2;
    remainder = digit1 % digit2;
    tooManySteps = (digit1 + digit2) * digit1 / digit2;

    printf("Your numbers multiplied together give you %d \n", product);

    printf("Now the cube of the second number you gave is %d \n", cube);

    printf("If you were to divide your two numbers together your "
           "remainder would be %d\n", remainder);

    printf("Now we'll get really crazy, if you were to add your two numbers, "
           "multiply them by the first number you gave and divide by the second"
           " number you gave, you would get %d\n",
           tooManySteps);
    return 0;
}
</code>```

Body:
Trying to figure out what I'm doing wrong with my C code here. The last two printf calls are asking for a type specifier and I don't know what to give it. The other lines don't have this issue. Any help is appreciated!

Edit The program does multiple math functions and the two print lines in question are supposed to print the results of two of these equations. The first one is supposed to print the remainder of the two numbers the user enters, the second printf is supposed to print out the answer of adding the two numbers together, multiplying that by the first number, and dividing it by the second number. Both of these printf lines give me the error of E0079, expected a type specifier.

Edit 2: Solved this issue by changing my SDK pack for the project, and also putting the calculations after asking the user for the numbers. Jimmy's formatting tips also helped fix it. Thank you so much to all of you who helped.

#include <stdio.h>
#include <stdlib.h>

main(void) {

    int digit1; //First digit user gives
    int digit2; //Second digit user gives.
    int product; //The result of the two user given numbers multiplied.
    int cube; //The result of cubing the second number.
    int remainder; //The remainder of dividing the two given numbers.
    int tooManySteps; //The result of adding the two given numbers together, multiplying it by the first given number, dividing by the second number.

    product = digit1 * digit2;
    cube = digit2 * digit2 * digit2;
    remainder = digit1 % digit2;
    tooManySteps = (digit1 + digit2) * digit1 / digit2;

    printf("Hi there, want me to do some cool math for you? Great! Just give me a number please.");
    scanf("%d", &digit1);

    printf("Cool! Now just give me one number.");
    scanf("%d", &digit2);

    printf("Your numbers multiplied together give you %d \n", product);

    printf("Now the cube of the second number you gave is %d \n", cube);

    printf("If you were to divide your two numbers together your remainder would be %d\n", remainder);

    printf("Now we'll get really crazy, if you were to add your two numbers, multiply them by the first number you gave and divide by the second number you gave, you would get %d\n", tooManySteps);
}

Body:
I really think it's a bad question. But I still correct the code for you.

int main(void)
{
    int digit1; //First digit user gives
    int digit2; //Second digit user gives.
    int product; //The result of the two user given numbers multiplied.
    int cube; //The result of cubing the second number.
    int remainder; //The remainder of dividing the two given numbers.
    int tooManySteps; //The result of adding the two given numbers together,
                      //multiplying it by the first given number,
                      //dividing by the second number.

    printf("Hi there, want me to do some cool math for you? Great! "
           "Just give me a number please.");
    scanf("%d", &digit1);

    printf("Cool! Now just give me one number.");
    scanf("%d", &digit2);

    product = digit1 * digit2;
    cube = digit2 * digit2 * digit2;
    remainder = digit1 % digit2;
    tooManySteps = (digit1 + digit2) * digit1 / digit2;

    printf("Your numbers multiplied together give you %d \n", product);

    printf("Now the cube of the second number you gave is %d \n", cube);

    printf("If you were to divide your two numbers together your "
           "remainder would be %d\n", remainder);

    printf("Now we'll get really crazy, if you were to add your two numbers, "
           "multiply them by the first number you gave and divide by the second"
           " number you gave, you would get %d\n",
           tooManySteps);
    return 0;
}


问:
Jenkins cannot execute webpack from ant script
I am trying to execute an Ant script through jenkins but it fails when it attempts to use webpack...

The ant script's execution task is the following:

```<code><exec executable="webpack.cmd" failonerror="true">
    <env key="PROD_ENV" value="true"/>
</exec>
</code>```

where webpack.cmd has been installed as a global npm module. The module directory has been included in the Path variable and I have even made sure that Jenkins is actually able to see it by doing a trial run inside a Execute windows batch command build step. However when it attempts to execute it via Ant it fails. Could it be a problem with the Ant plugin and its version?

The error i'm getting is the following:

Execute failed: java.io.IOException: Cannot run program "webpack.cmd": CreateProcess error=2, The system cannot find the file specified

答:
webpack.cmd needs to run in a command shell. Try...

```<code><exec executable="cmd" failonerror="true">
    <env key="PROD_ENV" value="true"/>
    <arg value="/c"/>
    <arg value="webpack.cmd"/>
</exec>
</code>```

You may need to provide the full absolute path to webpack.cmd so cmd.exe can find it.

Body:
I am trying to execute an Ant script through jenkins but it fails when it attempts to use webpack...

The ant script's execution task is the following:

<exec executable="webpack.cmd" failonerror="true">
    <env key="PROD_ENV" value="true"/>
</exec>

where webpack.cmd has been installed as a global npm module. The module directory has been included in the Path variable and I have even made sure that Jenkins is actually able to see it by doing a trial run inside a Execute windows batch command build step. However when it attempts to execute it via Ant it fails. Could it be a problem with the Ant plugin and its version?

The error i'm getting is the following:

Execute failed: java.io.IOException: Cannot run program "webpack.cmd": CreateProcess error=2, The system cannot find the file specified

Body:
webpack.cmd needs to run in a command shell. Try...

<exec executable="cmd" failonerror="true">
    <env key="PROD_ENV" value="true"/>
    <arg value="/c"/>
    <arg value="webpack.cmd"/>
</exec>

You may need to provide the full absolute path to webpack.cmd so cmd.exe can find it.


问:
WooCommerce remove product from loop by id
I'm trying to hide woocommerce products from the loop if any of the variation are out of stock.

What I have tried so far

1: Get the current logged in users "region"
2: Get a list of all product variation which are regions to check against the user region.
3: Run a check and if matches hide the product
4: Exclude the product from the loop

Any incite would be greatly appreciated.

```<code>function tm_remove_product_stock_region($query) {

    $product_variable = new WC_Product_Variable();
    $product_variations = $product_variable->get_available_variations();

/** Get users region. */
    $user_region = tm_get_user_region();

    $post__in = array();

    foreach ( $product_variations as $variation ) {

        /** Get products regions. */
        $product_region = $variation['attributes']['attribute_pa_regions'];

        if ($user_region === $product_region && !$variation->is_in_stock()) {

          $post__in[] = $variation['product_id'];

          add_filter('woocommerce_product_is_visible', function($is_visible, $id) {
                $is_visible = false;
                return $is_visible;
            }, 10,2);

        } else if ($user_region === $product_region && $variation->is_in_stock()) {

          $post__in[] = $variation['product_id'];

            add_filter('woocommerce_product_is_visible', function($is_visible, $id) {
                $is_visible = true;
                return $is_visible;
            }, 10,2);

        }

    }

    if(is_array($post__in) && $post__in != null){
        $query->set('post__in', $post__in);
    }

    return $query;

 }

 add_action('pre_get_posts', 'tm_remove_product_stock_region', 10, 2);
</code>```

Update 2:

I update the above and got it to work, BUT woocommerce_product_is_visible filter only works on category archive pages, Noting gets filtered for search page or when WP_Query is used on a custom page which is a real shame. Also is their a reason why $is_visible for woocommerce wont work with pre_get_posts

```<code>Function tm_remove_product_stock_region($is_visible, $id) {

    $product = wc_get_product(get_the_ID());

    $product_variable = new WC_Product_Variable(get_the_ID());
    $product_variations = $product_variable->get_available_variations();

    /** Get users region. */
    $user_region = tm_get_user_region();

    foreach ($product_variations as $variation) {

       /** Get products regions. */
        $product_region = $variation['attributes']['attribute_pa_regions'];

       if (!$product->is_in_stock() && $user_region === $product_region) {

            $is_visible = false;
            return $is_visible;

       }

       else if ($product->is_in_stock() && $user_region === $product_region) {

            $is_visible = true;
            return $is_visible;

       }
    }

}

add_filter('woocommerce_product_is_visible', 'tm_remove_product_stock_region', 10,2);
</code>```

Update 3:

After more hours of fiddling about I just noticed that $product_variable in both functions returns a different set of results ie with "woocommerce_product_is_visible" the products parent ID get returned but with "pre_get_posts" it's the variation ID.

So I don't get the result I wanted and pre_get_posts fails which is what  I actually need to work, I still have not solved this.

答:
Maybe something like this is what you are looking for:</p>

```<code>$has_items_in_stock = false;
foreach ($product_variations as $variation) {

    /** Get products regions. */
    $product_region = $variation['attributes']['attribute_pa_regions'];

    if ( $user_region === $product_region && $variation['is_in_stock'] ) {
        $has_items_in_stock = true;
        break;
    }
}

if($has_items_in_stock ) {
    //show product
    //show variations
    //..
}
</code>```

Body:
I'm trying to hide woocommerce products from the loop if any of the variation are out of stock.

What I have tried so far

1: Get the current logged in users "region"
2: Get a list of all product variation which are regions to check against the user region.
3: Run a check and if matches hide the product
4: Exclude the product from the loop

Any incite would be greatly appreciated.

function tm_remove_product_stock_region($query) {

    $product_variable = new WC_Product_Variable();
    $product_variations = $product_variable->get_available_variations();

/** Get users region. */
    $user_region = tm_get_user_region();

    $post__in = array();

    foreach ( $product_variations as $variation ) {

        /** Get products regions. */
        $product_region = $variation['attributes']['attribute_pa_regions'];

        if ($user_region === $product_region && !$variation->is_in_stock()) {

          $post__in[] = $variation['product_id'];

          add_filter('woocommerce_product_is_visible', function($is_visible, $id) {
                $is_visible = false;
                return $is_visible;
            }, 10,2);

        } else if ($user_region === $product_region && $variation->is_in_stock()) {

          $post__in[] = $variation['product_id'];

            add_filter('woocommerce_product_is_visible', function($is_visible, $id) {
                $is_visible = true;
                return $is_visible;
            }, 10,2);

        }

    }

    if(is_array($post__in) && $post__in != null){
        $query->set('post__in', $post__in);
    }

    return $query;

 }

 add_action('pre_get_posts', 'tm_remove_product_stock_region', 10, 2);

Update 2:

I update the above and got it to work, BUT woocommerce_product_is_visible filter only works on category archive pages, Noting gets filtered for search page or when WP_Query is used on a custom page which is a real shame. Also is their a reason why $is_visible for woocommerce wont work with pre_get_posts

Function tm_remove_product_stock_region($is_visible, $id) {

    $product = wc_get_product(get_the_ID());

    $product_variable = new WC_Product_Variable(get_the_ID());
    $product_variations = $product_variable->get_available_variations();

    /** Get users region. */
    $user_region = tm_get_user_region();

    foreach ($product_variations as $variation) {

       /** Get products regions. */
        $product_region = $variation['attributes']['attribute_pa_regions'];

       if (!$product->is_in_stock() && $user_region === $product_region) {

            $is_visible = false;
            return $is_visible;

       }

       else if ($product->is_in_stock() && $user_region === $product_region) {

            $is_visible = true;
            return $is_visible;

       }
    }

}

add_filter('woocommerce_product_is_visible', 'tm_remove_product_stock_region', 10,2);

Update 3:

After more hours of fiddling about I just noticed that $product_variable in both functions returns a different set of results ie with "woocommerce_product_is_visible" the products parent ID get returned but with "pre_get_posts" it's the variation ID.

So I don't get the result I wanted and pre_get_posts fails which is what  I actually need to work, I still have not solved this.

Body:
Maybe something like this is what you are looking for:

$has_items_in_stock = false;
foreach ($product_variations as $variation) {

    /** Get products regions. */
    $product_region = $variation['attributes']['attribute_pa_regions'];

    if ( $user_region === $product_region && $variation['is_in_stock'] ) {
        $has_items_in_stock = true;
        break;
    }
}

if($has_items_in_stock ) {
    //show product
    //show variations
    //..
}


问:
Angular2 - What folder for custom CSS / JS files?
I have to include a set of CSS and JS files in my angular2 application.

What is the correct folder in order to have them included when I do the build?

Should I have to put them inside SRC\Assets or under SRC\myFolder ?

Once defined it, how do I have to include them inside my app.component.html and how to configure <base href="/"> properly?

Thanks to support

答:
If you are asking where to put the styles the official angular style guide says:

https://angular.io/styleguide#!#05-04

it is a recommended way, but as the comment bellow you can put them in the order that makes better sense for you.


问:
Using a regex in Java
I need to build a regular expression for all nonempty sequences of letters other than : file, for,from.

So I should end up getting all the values from my text input excluding the above 3 words.

Is this a correct way to represent it?

```<code>^(?:(?!file|for|from).)*$
</code>```

Also I was trying to use this regex pattern in my java program and assumed it should work. But it does not.

My sample code is as follows:

```<code>Pattern p = Pattern.compile("^(?:(?!file|for|from).)*$");

// Split input with the pattern

String[] result =

         p.split("file is not there from for this time for this test");

for (int i=0; i<result.length; i++)

    System.out.println(result[i]);
</code>```

Is there an error in my regex or is there some error with the way I am using regex in java?

Please advise.

Thank you.

答:
Unless your question learning RegEx, like Isac, I believe you are much better of simply splitting the string using a simple splitting algorithm and manually filtering away whatever entries you do not wish to find. String.split() is our friend. If the list of words to be ignored is large, consider keeping them in a HashTable and check each extracted word against this table. This will  transform your algorithm from O(N^2) to O(N).

Not only will you be dealing with faster code that is easier to read, write and maintain (actually you haven't managed to get a working solution by now I guess).

My personal experience is, that most often your regular expression becomes very complex, hard to read and slow to evaluate due to the many unforseen backtracks due to the useg of .

Title: Using a regex in Java

Body:
I need to build a regular expression for all nonempty sequences of letters other than : file, for,from.

So I should end up getting all the values from my text input excluding the above 3 words.

Is this a correct way to represent it?

^(?:(?!file|for|from).)*$

Also I was trying to use this regex pattern in my java program and assumed it should work. But it does not.

My sample code is as follows:

Pattern p = Pattern.compile("^(?:(?!file|for|from).)*$");

// Split input with the pattern

String[] result =

         p.split("file is not there from for this time for this test");

for (int i=0; i<result.length; i++)

    System.out.println(result[i]);

Is there an error in my regex or is there some error with the way I am using regex in java?

Please advise.

Thank you.


问:
Versionize HTTP methods web api2
Which is the best way to versionize http methods web api2? Each version of web api called from different version of upgrated application.</p>

答:
Versioning an API can be complex. The way that I typically do it is to setup versioned routes and controllers.

This makes my routes look like this

```<code>https://api.example.com/api/v1/
https://api.example.com/api/v2/
https://api.example.com/api/v3/
</code>```

Then I include a "baseUrl" and "version" in the client. So it knows how to assemble that into a complete Uri. This means my project structure looks something like

```<code>|- Controllers
|-----\VersionController.cs
|-----\v1
|----------\HomeController.cs
|----------\AuthController.cs
|-----\v2
|----------\HomeController.cs
|----------\AuthController.cs
</code>```

Additionally, I provide an endpoint that never changes form and only provides the available API versions.

```<code>https://api.example.com/api/version
</code>```

And this returns a value that looks something like:

```<code>{
    "currentVersion": 3,
    "minVersion": 1
}
</code>```

This way, clients can know when their API version is deprecated and no longer available. Instead of just throwing a 404.

Title: Versionize HTTP methods web api2

Body:
Versioning an API can be complex. The way that I typically do it is to setup versioned routes and controllers.

This makes my routes look like this

https://api.example.com/api/v1/
https://api.example.com/api/v2/
https://api.example.com/api/v3/

Then I include a "baseUrl" and "version" in the client. So it knows how to assemble that into a complete Uri. This means my project structure looks something like

|- Controllers
|-----\VersionController.cs
|-----\v1
|----------\HomeController.cs
|----------\AuthController.cs
|-----\v2
|----------\HomeController.cs
|----------\AuthController.cs

Additionally, I provide an endpoint that never changes form and only provides the available API versions.

https://api.example.com/api/version

And this returns a value that looks something like:

{
    "currentVersion": 3,
    "minVersion": 1
}

This way, clients can know when their API version is deprecated and no longer available. Instead of just throwing a 404.


问:
find command error in shell script
I have a file "log_data.txt" which contains various log files and the mtime next to the names with a space. Contents of the file are as shown below,

```<code>Log1 2
Log2 6
Log3 5
Log4 7
Log5 3
</code>```

The intent here is my script shown below has to assign itself the log filename and delete the files as per the mtime next to it.

```<code>IFS=''
while read line
do
find /opt/tmp/log/ -name `$line | awk '{print $1}'`*.log -mtime `$line | awk '{print $2}'` -exec rm -rf {} \;
echo ---------
done < log_data.txt
</code>```

If I assign an integer next to mtime in the script, it works fine, but, it throws the below error, if I put "$line | awk '{print $2}'" in the find command.

```<code>---------
./log_clear_script.sh: line 4: Log1      2: not found
./log_clear_script.sh: line 4: Log1      2: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log2     6: not found
./log_clear_script.sh: line 4: Log2     6: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log3       5: not found
./log_clear_script.sh: line 4: Log3       5: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log4  7: not found
./log_clear_script.sh: line 4: Log4  7: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log5        3: not found
./log_clear_script.sh: line 4: Log5        3: not found
find: invalid argument `-exec' to `-mtime'
</code>```

Please help me resolve it. All responses are much appreciated. - Thank you.

答:
the variable
    $line
is not a command. it's just a string.

try to substitute

```<code>`$line | awk '{print $1}'`
</code>```

with

```<code>`echo -n $line | awk '{print $1}'`
</code>```

and

```<code>`$line | awk '{print $2}'`
</code>```

with

```<code>`echo -n $line | awk '{print $2}'`
</code>```

Title: find command error in shell script

Body:
I have a file "log_data.txt" which contains various log files and the mtime next to the names with a space. Contents of the file are as shown below,

Log1 2
Log2 6
Log3 5
Log4 7
Log5 3

The intent here is my script shown below has to assign itself the log filename and delete the files as per the mtime next to it.

IFS=''
while read line
do
find /opt/tmp/log/ -name `$line | awk '{print $1}'`*.log -mtime `$line | awk '{print $2}'` -exec rm -rf {} \;
echo ---------
done < log_data.txt

If I assign an integer next to mtime in the script, it works fine, but, it throws the below error, if I put "$line | awk '{print $2}'" in the find command.

---------
./log_clear_script.sh: line 4: Log1      2: not found
./log_clear_script.sh: line 4: Log1      2: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log2     6: not found
./log_clear_script.sh: line 4: Log2     6: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log3       5: not found
./log_clear_script.sh: line 4: Log3       5: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log4  7: not found
./log_clear_script.sh: line 4: Log4  7: not found
find: invalid argument `-exec' to `-mtime'
---------
./log_clear_script.sh: line 4: Log5        3: not found
./log_clear_script.sh: line 4: Log5        3: not found
find: invalid argument `-exec' to `-mtime'

Please help me resolve it. All responses are much appreciated. - Thank you.

Body:
the variable
    $line
is not a command. it's just a string.

try to substitute

`$line | awk '{print $1}'`

with

`echo -n $line | awk '{print $1}'`

and

`$line | awk '{print $2}'`

with

`echo -n $line | awk '{print $2}'`


问:
Continuously Generating Random Coordinates in a Text File Using Python
Is there a way to continuously add random coordinates to a text file using python? (UPDATED)</p>

```<code>import random
import threading

#Open a file named numbersmake.txt.
outfile = open('new.txt', 'w')

def coordinate():
    threading.Timer(0.0000000000001, coordinate).start ()
    x = random.randint(0,10000)
    y = random.randint(0,10000)
    outfile.write("{},{}\n".format(x, y))

coordinate()

#Close the file.
outfile.close()
print('The data is now the the new.txt file')
</code>```

答:
Based on your code it looks like you are just trying to generate 12,000 random coordinates in one shot and exit. If this is the case why would you want to thread it? You would only need to thread if you plan to do something else with your program while the thread is dealing with collecting coordinates.

Maybe if your coordinate generation were triggered by some external, unpredictable event it might make sense. Otherwise, if you are really just generating a finite set of coordinates as quickly as possible, I think your range solution is fine.

More detail on what you are really trying to do would help craft a better solution.

Body:
Is there a way to continuously add random coordinates to a text file using python? (UPDATED)

import random
import threading

#Open a file named numbersmake.txt.
outfile = open('new.txt', 'w')

def coordinate():
    threading.Timer(0.0000000000001, coordinate).start ()
    x = random.randint(0,10000)
    y = random.randint(0,10000)
    outfile.write("{},{}\n".format(x, y))

coordinate()

#Close the file.
outfile.close()
print('The data is now the the new.txt file')


问:
Docker run does not deploy
So we followed the Docker get started tutorial
(https://docs.docker.com/get-started/part2/). The build works, the command

```<code>docker run -p 4000:80 friendlyhello
</code>```

works but when we go to http://localhost:4000, nothing is reached. We just followed the tutorial step by step but don't see anything.

Yes we also went to localhost:4001.
Is this perhaps something that has to do witht the message "system pool is not available on windows"?

Here's a screenshot of our docker output

答:
Firstly talking about the issue that you've pointed out yourself, this is identified as an issue that can't be fixed for Windows.

Please try downgrading to version 1.12.x so that these warnings do not pop-up anymore. This solution is found working for most of us.

```<code>level-info msg="Unable to use system certificate pool: crypto/x509: system root pool is not available on Windows"
</code>```

Coming to the main issue that you're facing, which is as follows:

```<code>Error response from daemon: driver failed programming external connectivity on endpoint objective_joliot
</code>```

This says that the port 4000 is already in use on Docker VM or possibly on your system. You can either stop whatever is running on that port or change the port used in your Docker command.

To change to the external port 8080, use:

```<code>docker run -d -p 8080:80 --name objective_joliot nginx
</code>```

Hope this helps!!!

Title: Docker run does not deploy

Body:
So we followed the Docker get started tutorial
(https://docs.docker.com/get-started/part2/). The build works, the command

docker run -p 4000:80 friendlyhello

works but when we go to http://localhost:4000, nothing is reached. We just followed the tutorial step by step but don't see anything.

Yes we also went to localhost:4001.
Is this perhaps something that has to do witht the message "system pool is not available on windows"?

Here's a screenshot of our docker output

Body:
Firstly talking about the issue that you've pointed out yourself, this is identified as an issue that can't be fixed for Windows.

Please try downgrading to version 1.12.x so that these warnings do not pop-up anymore. This solution is found working for most of us.

level-info msg="Unable to use system certificate pool: crypto/x509: system root pool is not available on Windows"

Coming to the main issue that you're facing, which is as follows:

Error response from daemon: driver failed programming external connectivity on endpoint objective_joliot

This says that the port 4000 is already in use on Docker VM or possibly on your system. You can either stop whatever is running on that port or change the port used in your Docker command.

To change to the external port 8080, use:

docker run -d -p 8080:80 --name objective_joliot nginx

Hope this helps!!!


问:
userform always ontop after add new workbook excel vba
I got one userform with a commandbutton on it, this button is use to create a new workbook. I want this userform on top of the new created workbook after click the button. Any idea?(For excel 2007, userform is always on top, but not for excel 2016)

```<code>Private Sub CommandButton1_Click()
Workbooks.Add

End Sub
</code>```

答:
Try placing the following snippet on top of the userform's code module.

```<code>Option Explicit
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal clsName As String, ByVal wndName As String) As Long
Private Declare PtrSafe Function SetParent Lib "user32" (ByVal hChild As Long, ByVal hParent As Long) As Long

Private Sub CommandButton1_Click()
  Static h As Long
  If h <= 0 Then h = FindWindow("ThunderDFrame", Me.Caption)
  If h <= 0 Then Exit Sub
  Dim wb As Workbook: Set wb = Workbooks.Add
  SetParent h, Application.Windows(wb.Name).hwnd
  wb.Activate
End Sub
</code>```

This will make the new workbook the Parent of the user-form. It implies that the form will unload when you close the new workbook. If your goal is to keep the form alive for whatever workbook or worksheet is active, some other techniques can be used, maybe the easiest of which is by handling the Workbook_SheetActivate event.

Body:
I got one userform with a commandbutton on it, this button is use to create a new workbook. I want this userform on top of the new created workbook after click the button. Any idea?(For excel 2007, userform is always on top, but not for excel 2016)

Private Sub CommandButton1_Click()
Workbooks.Add

End Sub

Body:
Try placing the following snippet on top of the userform's code module.

Option Explicit
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal clsName As String, ByVal wndName As String) As Long
Private Declare PtrSafe Function SetParent Lib "user32" (ByVal hChild As Long, ByVal hParent As Long) As Long

Private Sub CommandButton1_Click()
  Static h As Long
  If h <= 0 Then h = FindWindow("ThunderDFrame", Me.Caption)
  If h <= 0 Then Exit Sub
  Dim wb As Workbook: Set wb = Workbooks.Add
  SetParent h, Application.Windows(wb.Name).hwnd
  wb.Activate
End Sub

This will make the new workbook the Parent of the user-form. It implies that the form will unload when you close the new workbook. If your goal is to keep the form alive for whatever workbook or worksheet is active, some other techniques can be used, maybe the easiest of which is by handling the Workbook_SheetActivate event.


问:
XOR-Encryption works on Code blocks not on Visual Studio 2017
so I would like to encrypt my data when write into .txt file so I choose XOR-Encryption from this code:
Github
So when I run in code blocks it runs and shows this result:

```<code>Encrypted: :=.43*-:8m2$.a
Decrypted:kylewbanks.com0

Process returned 0 (0x0)   execution time : 0.025 s
Press any key to continue.
</code>```

But When I start use Visual Studio 2017 it shows this error:

```<code>Error (active)  E0059   function call is not allowed in a constant expression
</code>```

Which means I cant put variable when declaring an array, so is there any method for my encryption to work in VS2017.
I think the problems is when declare the variable using constant, anyway to force it or other encryption method that is easy to use, I wont need to be secure just to prevent plain text in file.
 Anyway this is the only code:

```<code>#include <stdio.h>
#include <string.h>

void encryptDecrypt(char *input, char *output) {
    char key[] = {'K', 'C', 'Q'}; //Can be any chars, and any size array

    int i;
    for(i = 0; i < strlen(input); i++) {
        output[i] = input[i] ^ key[i % (sizeof(key)/sizeof(char))];
    }
}

int main () {
    char baseStr[] = "kylewbanks.com";

    char encrypted[strlen(baseStr)];
    encryptDecrypt(baseStr, encrypted);
    printf("Encrypted:%s\n", encrypted);

    char decrypted[strlen(baseStr)];
    encryptDecrypt(encrypted, decrypted);
    printf("Decrypted:%s\n", decrypted);
}
</code>```

答:
MSVC does not support Variable Length Arrays. One way round is to allocate the memory.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void encryptDecrypt(char *input, char *output) {
    char key[] = {'K', 'C', 'Q'}; //Can be any chars, and any size array
    size_t i;
    for(i = 0; i < strlen(input); i++) {
        output[i] = input[i] ^ key[i % (sizeof(key)/sizeof(char))];
    }
    output[i] = '\0';               // terminate
}

int main () {
    char baseStr[] = "kylewbanks.com";
    size_t len = strlen(baseStr) + 1;

    char *encrypted = malloc(len);
    if(encrypted == NULL) {
        // error handling
    }
    encryptDecrypt(baseStr, encrypted);
    printf("Encrypted:%s\n", encrypted);

    char *decrypted = malloc(len);
    if(decrypted == NULL) {
        // error handling
    }
    encryptDecrypt(encrypted, decrypted);
    printf("Decrypted:%s\n", decrypted);

    free(decrypted);
    free(encrypted);
}
</code>```

Please note that an extra byte is needed for the string terminator - and the string should be terminated.

Body:
so I would like to encrypt my data when write into .txt file so I choose XOR-Encryption from this code:
Github
So when I run in code blocks it runs and shows this result:

Encrypted: :=.43*-:8m2$.a
Decrypted:kylewbanks.com0

Process returned 0 (0x0)   execution time : 0.025 s
Press any key to continue.

But When I start use Visual Studio 2017 it shows this error:

Error (active)  E0059   function call is not allowed in a constant expression

Which means I cant put variable when declaring an array, so is there any method for my encryption to work in VS2017.
I think the problems is when declare the variable using constant, anyway to force it or other encryption method that is easy to use, I wont need to be secure just to prevent plain text in file.
 Anyway this is the only code:

#include <stdio.h>
#include <string.h>

void encryptDecrypt(char *input, char *output) {
    char key[] = {'K', 'C', 'Q'}; //Can be any chars, and any size array

    int i;
    for(i = 0; i < strlen(input); i++) {
        output[i] = input[i] ^ key[i % (sizeof(key)/sizeof(char))];
    }
}

int main () {
    char baseStr[] = "kylewbanks.com";

    char encrypted[strlen(baseStr)];
    encryptDecrypt(baseStr, encrypted);
    printf("Encrypted:%s\n", encrypted);

    char decrypted[strlen(baseStr)];
    encryptDecrypt(encrypted, decrypted);
    printf("Decrypted:%s\n", decrypted);
}

Body:
MSVC does not support Variable Length Arrays. One way round is to allocate the memory.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void encryptDecrypt(char *input, char *output) {
    char key[] = {'K', 'C', 'Q'}; //Can be any chars, and any size array
    size_t i;
    for(i = 0; i < strlen(input); i++) {
        output[i] = input[i] ^ key[i % (sizeof(key)/sizeof(char))];
    }
    output[i] = '\0';               // terminate
}

int main () {
    char baseStr[] = "kylewbanks.com";
    size_t len = strlen(baseStr) + 1;

    char *encrypted = malloc(len);
    if(encrypted == NULL) {
        // error handling
    }
    encryptDecrypt(baseStr, encrypted);
    printf("Encrypted:%s\n", encrypted);

    char *decrypted = malloc(len);
    if(decrypted == NULL) {
        // error handling
    }
    encryptDecrypt(encrypted, decrypted);
    printf("Decrypted:%s\n", decrypted);

    free(decrypted);
    free(encrypted);
}

Please note that an extra byte is needed for the string terminator - and the string should be terminated.


问:
Cloning and Adding Hyper-V VM to Domain
I have a standalone (not clustered, but in the domain) Windows Server 2016 with Hyper-V role installed.
I need to clone VMs on a daily basis, so I wrote a few small "things" using C# and PowerShell.

Parallel Copy of VHD

public static void Main(string[] args) {
    var sourceFile = args[0];
    var distanationDir = args[1];
    int numOfCopies = Int32.Parse(args[2]);

    //var sourceFile = $@"C:\temp\123.VHD";
    //var distanationDir = $@"C:\temp\vhds\";
    //int numOfCopies = 15;

    StartJob(sourceFile, distanationDir, numOfCopies, random);
}

private static void StartJob(string sourcefile, string distanationdir, int numOfCopies, Random random) {
    int count = 0;
    Parallel.For(0, numOfCopies, i => {
        Console.WriteLine("i = {0}, thread = {1}", i, Thread.CurrentThread.ManagedThreadId);

        try {
            string atrib = Path.GetExtension(sourcefile);
            string guid = Guid.NewGuid().ToString("N");
            var copyNew = Path.GetFileNameWithoutExtension(sourcefile) + guid + atrib;
            File.Copy(sourcefile, Path.Combine(distanationdir + '\\', copyNew));
            Console.WriteLine(@"Started{copyNew}");
        } catch (IOException copyError) {
            Console.WriteLine(copyError.Message);
        }
    }
}
```</li>
<li><p>The second step is to create VMs with this PowerShell script that creates a VM with existing VHDX.</p>

<pre class="lang-bsh prettyprint-override"><code>$from = 81
$howmany = 30

$files = Get-ChildItem -Path "E:\Hyper-v" -Filter *.vhdx
if ($files) {
    Write-Host "variable is not null"
    try {
        $vmIndex = $from
        for ($i = 0; $i -lt $howmany; $i++) {
            Write-Host "Start  "
            New-Vm -Name "AUT-TA$vmIndex" -Path "E:\Hyper-v\Virtual Machines" -MemoryStartupBytes 4294967296 -VHDPath $files[$i].FullName -SwitchName "Broadcom NetXtreme Gigabit Ethernet #4 - Virtual Switch"
            Write-Host "Vm created " + "AUT-TA$vmIndex"
            $vmIndex++
            Write-Host "End"
        }
        exit
    } catch {
        [System.Exception]"caught a system exception"
    }
} else {
    Write-Host "No such files"
    exit
}
</code>```

Last I need join them to the domain but I need some script that will be running for each VM on this host and adding it to the domain.

答:
Since you should be able to use PowerShell Direct, you can just get the VM's you want to execute on, then Invoke-Command -VMName the Add-Computer command. Your comment implies that you want to save the password in the script. Just remember the security implications of that.

```<code>$domain = "myDomain"
$password = "myPassword!" | ConvertTo-SecureString -asPlainText -Force
$username = "$domain\myUserAccount"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
Get-VM | ForEach-Object { Invoke-Command -VMName $_.name -ScriptBlock {Add-Computer -DomainName $using:domain -Credential $using:credentia}}
</code>```

Title: Cloning and Adding Hyper-V VM to Domain

Body:
I have a standalone (not clustered, but in the domain) Windows Server 2016 with Hyper-V role installed.
I need to clone VMs on a daily basis, so I wrote a few small "things" using C# and PowerShell.

Parallel Copy of VHD

public static void Main(string[] args) {
    var sourceFile = args[0];
    var distanationDir = args[1];
    int numOfCopies = Int32.Parse(args[2]);

    //var sourceFile = $@"C:\temp\123.VHD";
    //var distanationDir = $@"C:\temp\vhds\";
    //int numOfCopies = 15;

    StartJob(sourceFile, distanationDir, numOfCopies, random);
}

private static void StartJob(string sourcefile, string distanationdir, int numOfCopies, Random random) {
    int count = 0;
    Parallel.For(0, numOfCopies, i => {
        Console.WriteLine("i = {0}, thread = {1}", i, Thread.CurrentThread.ManagedThreadId);

        try {
            string atrib = Path.GetExtension(sourcefile);
            string guid = Guid.NewGuid().ToString("N");
            var copyNew = Path.GetFileNameWithoutExtension(sourcefile) + guid + atrib;
            File.Copy(sourcefile, Path.Combine(distanationdir + '\\', copyNew));
            Console.WriteLine(@"Started{copyNew}");
        } catch (IOException copyError) {
            Console.WriteLine(copyError.Message);
        }
    }
}

The second step is to create VMs with this PowerShell script that creates a VM with existing VHDX.

$from = 81
$howmany = 30

$files = Get-ChildItem -Path "E:\Hyper-v" -Filter *.vhdx
if ($files) {
    Write-Host "variable is not null"
    try {
        $vmIndex = $from
        for ($i = 0; $i -lt $howmany; $i++) {
            Write-Host "Start  "
            New-Vm -Name "AUT-TA$vmIndex" -Path "E:\Hyper-v\Virtual Machines" -MemoryStartupBytes 4294967296 -VHDPath $files[$i].FullName -SwitchName "Broadcom NetXtreme Gigabit Ethernet #4 - Virtual Switch"
            Write-Host "Vm created " + "AUT-TA$vmIndex"
            $vmIndex++
            Write-Host "End"
        }
        exit
    } catch {
        [System.Exception]"caught a system exception"
    }
} else {
    Write-Host "No such files"
    exit
}

Last I need join them to the domain but I need some script that will be running for each VM on this host and adding it to the domain.

Body:
Since you should be able to use PowerShell Direct, you can just get the VM's you want to execute on, then Invoke-Command -VMName the Add-Computer command. Your comment implies that you want to save the password in the script. Just remember the security implications of that.

$domain = "myDomain"
$password = "myPassword!" | ConvertTo-SecureString -asPlainText -Force
$username = "$domain\myUserAccount"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
Get-VM | ForEach-Object { Invoke-Command -VMName $_.name -ScriptBlock {Add-Computer -DomainName $using:domain -Credential $using:credentia}}


问:
Sockets vs web service .NET (file updater)
I'm going to make a program (c# .NET) that downloads files from a server (basically a file updater) and I'll have around 1,000 clients downloading files ( from 1 to 10 each client) this files are small ( from 100k to 2.5 MB). So what kind of communication would you recommend? sockets? web service? WSE 3 MTOM? or prob another suggestion? thanks</p>

答: Another option is the HttpListener class, which is quite approachable.  But if I were expecting 1,000 clients hitting me on a regular basis, I'd set up a real Web server, as others have suggested.</p>


问:
how to visualize weights between layer convolution?
I have a small deep learning problem. Here I built my network (CNN) with the bookstore Keras. I am interested in visualizing the weights of my CNN. My architecture is AlexNet type and my color images (RGB) are divided into 72 classes. For the first convolution which has 96 filters whose filter kernel is 11 by 11 I recover a 4 dimensional tensor at the output [11] [11] [3] [96]. So each filter has 3 matrix 11 by 11 which we will call kernel.

At this level for the visualization of my weights I took an image I split it in 3 channels. For a given filter each channel was convoluted with a kernel. Each result of these convolutions operations has been gathered to give a resulting image.

Now the second convolution that takes input the output of the first is set with 383 filters whose filter kernel is 5 * 5. The output of this second convolution gives me a tensor 4d of size [5] [5] [96] [383]. This means that for a given filter it has 96 filters (at least that's what I understand). So there for a given filter I'm still with my famous image splitted on these 3 channels facing 96 filters.

I do not know if it is a problem of understanding but I block total because on the output of the second convolution I do not know interpreted the 96 kernels for each filter.

I would like to from my weights reconstitute the filters a convolution layer.

I am really novice in deep learning it is an interesting science but full of mystery for me. If anyone had the kindness to enlighten me I would thank him.

答:
In this paper : “Visualizing and Understanding Convolutional Neural Networks” , Zeiler and Fergus discussed the idea that this renewed interest in CNNs is due to the accessibility of large training sets and increased computational power with the usage of GPUs. They found and also talked about the interesting ways of visualizing feature maps and weights. It is one of the best and prevalent papers in the field of Deep Learning. Writers also emphasized about the limited knowledge that researchers had on inner mechanisms of these models.

Saying that without this insight, the “development of better models
  is reduced to trial and error”.

They also use AlexNet like model in their paper. This model which was named as ZFNET was the winner of  ILSVRC 2013 .I am sure by reading this paper you will have better understanding about overall DL concept and possible solutions to your question.


问:
Delete unused records from oracle table
DB version : 11.2.0.4
OS Solaris 5.10

REQUIREMENT : Delete unused records from table only after finding if the record is being accessed or not.

We have a table employee, which has 100,000 records, if anyone select a particular record/records from employee table then, the respective record's STATUS column should get updated to 'ACTIVE' value.

This is required for auditing purpose, 60 days later we will delete all the records from employee table whose STATUS column value is is NULL. how can this be achieved?

My understanding so far, correct me if I am wrong:

1) Trigger can't be used as there is no SELECT event, we only have UPDATE, INSERT, DELETE event.
2) Oracle FGA (Fine grain auditing) may not solve the purpose. or may be I am not aware, is it doable with FGA?

Table:

```<code>CREATE TABLE EMPLOYEE
(
  EMPID   NUMBER,
  NAME    VARCHAR2(20 BYTE),
  SALARY  NUMBER,
  DEPART  VARCHAR2(100 BYTE),
  STATUS  VARCHAR2(100 BYTE)
)
</code>```

sample records:

```<code>     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH
</code>```

Example:

If any one issue below statements

query 1: SELECT * from EMPLOYEE where name='MESSI';

the auditing should update the STATUS='ACTIVE' of empid=105

```<code>     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH
</code>```

query 2: SELECT * from EMPLOYEE where DEPART='TECH';

The auditing should update the STATUS='ACTIVE' for empid=105,106,107,108

```<code>     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH                 'ACTIVE'
       107 TERI                  5000 TECH                 'ACTIVE'
       108 ROBERT                5000 TECH                 'ACTIVE'
</code>```

答:
You may try FGA ( fine-grained Audit ) using the DBMS_FGA Package. Try Running the code block below in your schema. If it executes successfully , check if audits are lodged periodically in the  DBA_COMMON_AUDIT_TRAIL  or DBA_AUDIT_STATEMENT table ( check documentation ) while running a select query. Schedule a program that runs periodically to check the audit table and update the status column accordingly. I have never tried anything like this, However!.</p>

```<code>BEGIN
                   dbms_fga.Add_policy(object_schema => 'HR', object_name => 'EMPLOYEE',
                   policy_name => 'STATUS_UPDATE', audit_condition => 'SELECT',
                   audit_column => 'NAME ,DEPART', handler_schema => NULL,
                   handler_module => NULL,
                   ENABLE => TRUE);
               END;

               /
</code>```

Title: Delete unused records from oracle table

Body:
DB version : 11.2.0.4
OS Solaris 5.10

REQUIREMENT : Delete unused records from table only after finding if the record is being accessed or not.

We have a table employee, which has 100,000 records, if anyone select a particular record/records from employee table then, the respective record's STATUS column should get updated to 'ACTIVE' value.

This is required for auditing purpose, 60 days later we will delete all the records from employee table whose STATUS column value is is NULL. how can this be achieved?

My understanding so far, correct me if I am wrong:

1) Trigger can't be used as there is no SELECT event, we only have UPDATE, INSERT, DELETE event.
2) Oracle FGA (Fine grain auditing) may not solve the purpose. or may be I am not aware, is it doable with FGA?

Table:

CREATE TABLE EMPLOYEE
(
  EMPID   NUMBER,
  NAME    VARCHAR2(20 BYTE),
  SALARY  NUMBER,
  DEPART  VARCHAR2(100 BYTE),
  STATUS  VARCHAR2(100 BYTE)
)

sample records:

     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH

Example:

If any one issue below statements

query 1: SELECT * from EMPLOYEE where name='MESSI';

the auditing should update the STATUS='ACTIVE' of empid=105

     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH

query 2: SELECT * from EMPLOYEE where DEPART='TECH';

The auditing should update the STATUS='ACTIVE' for empid=105,106,107,108

     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH                 'ACTIVE'
       107 TERI                  5000 TECH                 'ACTIVE'
       108 ROBERT                5000 TECH                 'ACTIVE'

Body:
You may try FGA ( fine-grained Audit ) using the DBMS_FGA Package. Try Running the code block below in your schema. If it executes successfully , check if audits are lodged periodically in the  DBA_COMMON_AUDIT_TRAIL  or DBA_AUDIT_STATEMENT table ( check documentation ) while running a select query. Schedule a program that runs periodically to check the audit table and update the status column accordingly. I have never tried anything like this, However!.

BEGIN
                   dbms_fga.Add_policy(object_schema => 'HR', object_name => 'EMPLOYEE',
                   policy_name => 'STATUS_UPDATE', audit_condition => 'SELECT',
                   audit_column => 'NAME ,DEPART', handler_schema => NULL,
                   handler_module => NULL,
                   ENABLE => TRUE);
               END;

               /


问:
MSSQL - OVER, ROW_NUMBER() and ORDER BY error
I'm trying to make a query that outputs a list with the company data and the number of Products and Discounts of each Company and order by product_count.
Also i need to limit the output to groups of 30 rows

```<code>SELECT * FROM (
    SELECT *, (
        SELECT COUNT(*) FROM Products WHERE Product_Comp_id = Comp_id
    ) as product_count, (
        SELECT COUNT(*) FROM Discount WHERE Disc_Comp_id = Comp_id
    ) as discount_count , ROW_NUMBER() OVER (
        ORDER BY product_count ASC
    ) AS RowNum FROM Company
) AS finalTable WHERE finalTable.RowNum BETWEEN 0 AND 30
</code>```

But i get this error

Invalid column name 'product_count'.

Table Structure

```<code>Products
    |-Product_id
    |-Product_Name
    |-Product_Description
    |-Product_Comp_id

Discount
    |-Disc_id
    |-Disc_Name
    |-Disc_Comp_id
    |-Disc_Ammount

Company
    |-Comp_id
    |-Comp_Name
    |-Comp_Address
</code>```

答:
You need an additional level of subquery to give you product_count.</p>

```<code>SELECT * FROM (
    SELECT * , ROW_NUMBER() OVER (ORDER BY product_count ASC) AS RowNum
    FROM
    (
        SELECT *, (SELECT COUNT(*) FROM Products WHERE Product_Comp_id = Comp_id) as product_count,
        (SELECT COUNT(*) FROM Discount WHERE Disc_Comp_id = Comp_id) as discount_count
        FROM Company
    ) C
) AS finalTable WHERE finalTable.RowNum BETWEEN 0 AND 30
</code>```

Body:
I'm trying to make a query that outputs a list with the company data and the number of Products and Discounts of each Company and order by product_count.
Also i need to limit the output to groups of 30 rows

SELECT * FROM (
    SELECT *, (
        SELECT COUNT(*) FROM Products WHERE Product_Comp_id = Comp_id
    ) as product_count, (
        SELECT COUNT(*) FROM Discount WHERE Disc_Comp_id = Comp_id
    ) as discount_count , ROW_NUMBER() OVER (
        ORDER BY product_count ASC
    ) AS RowNum FROM Company
) AS finalTable WHERE finalTable.RowNum BETWEEN 0 AND 30

But i get this error

Invalid column name 'product_count'.

Table Structure

Products
    |-Product_id
    |-Product_Name
    |-Product_Description
    |-Product_Comp_id

Discount
    |-Disc_id
    |-Disc_Name
    |-Disc_Comp_id
    |-Disc_Ammount

Company
    |-Comp_id
    |-Comp_Name
    |-Comp_Address

Body:
You need an additional level of subquery to give you product_count.

SELECT * FROM (
    SELECT * , ROW_NUMBER() OVER (ORDER BY product_count ASC) AS RowNum
    FROM
    (
        SELECT *, (SELECT COUNT(*) FROM Products WHERE Product_Comp_id = Comp_id) as product_count,
        (SELECT COUNT(*) FROM Discount WHERE Disc_Comp_id = Comp_id) as discount_count
        FROM Company
    ) C
) AS finalTable WHERE finalTable.RowNum BETWEEN 0 AND 30


问:
Spring Boot - Angularjs $stateProvider with Security
As you know, we can set permissions for specific URLs with spring security. for example

```<code>.antmatchers("/assets/**").permitall ()
</code>```

My problem is:
I am using the $stateProvider with AngularJS in the project.

So the URL path Localhost/#/home, localhost/#/userList.

For example, using Security, I want to log in to the /#/userList with the "ADMIN" authority.

```<code>.antmatchers("/#/userList").hasauthority("ADMIN")
</code>```

I guess that's not possible. How can we solve this?

答:
You can't do this, because the anchor is a client-side concept, see RFC 1630:

A reference to a particular part of a document may, including the
   fragment identifier, look like

   http://www.myu.edu/org/admin/people#andy
```

in which case the string "#andy" is not sent to the server, but is
    retained by the client and used when the whole object had been
    retrieved.

Body:
As you know, we can set permissions for specific URLs with spring security. for example

.antmatchers("/assets/**").permitall ()

My problem is:
I am using the $stateProvider with AngularJS in the project.

So the URL path Localhost/#/home, localhost/#/userList.

For example, using Security, I want to log in to the /#/userList with the "ADMIN" authority.

.antmatchers("/#/userList").hasauthority("ADMIN")

I guess that's not possible. How can we solve this?

Body:
You can't do this, because the anchor is a client-side concept, see RFC 1630:

A reference to a particular part of a document may, including the
   fragment identifier, look like

   http://www.myu.edu/org/admin/people#andy

in which case the string "#andy" is not sent to the server, but is
    retained by the client and used when the whole object had been
    retrieved.


问:
Loading map marker issue in take print
I am able to point the marker on the map and it is visible on the browser. But when I print the same, the marker isn't visible on the map. Please help.

```<code><button class="map-print" ng-click="mapprint();">print</button>
[enter image description here][1]<script>
function mapprint(){
    var content = document.getElementById('map_div'); //has to be first.
    content.style.position = "relative";
    content.style.height = contents.firstChild.offsetHeight + "px";
    content.style.width = contents.firstChild.offsetWidth + "px";
    var win = window.open();
    win.document.write(content.innerHTML);
    win.print();
    win.close();
}
</code>```

I got print of the map. But canot load the map marker

this is my web view

This is my Map print view

答:
The printing is not supported by Google Maps JavaScript API. Have a look at the following answer in the official FAQ

https://developers.google.com/maps/faq#print

Printing from the JavaScript API is not supported. This is because printing support is inconsistent across commonly used browsers. We recommend using the Static Maps API for printing purposes.

Title: Loading map marker issue in take print

Body:
I am able to point the marker on the map and it is visible on the browser. But when I print the same, the marker isn't visible on the map. Please help.

<button class="map-print" ng-click="mapprint();">print</button>
[enter image description here][1]


问:
Force Umbraco to use https for back office and http for all other requests
I am trying to configure Umbraco so all requests to the back office (www.mydomain.com/umbraco) get redirected to https and all non-backoffice requests are forwarded to http.

I can easily get the back office to use SSL by setting this web config appsetting key:

```<code><add key="umbracoUseSSL" value="false" />
</code>```

However, I am struggling to get all other pages to force http. The certificate is self signed so I don't want end users getting SSL errors. I have tried this rewrite rule in the web.config, but it has no impact.

```<code><rule name="No-https" enabled="true" stopProcessing="true">
   <match url=".*" negate="false" />
   <conditions>
      <add input="{HTTPS}" pattern="on" />
      <add input="{URL}" pattern="umbraco" negate="true" />
   </conditions>
   <action type="Redirect" url="http://{HTTP_HOST}{REQUEST_URI}" />
</rule>
</code>```

My aim is that any request to https://www.mydomain.com is redirected to http://www.mydomain.com unless it matches the folder /umbraco.

If I have this rule, all http requests are redirected to https:

```<code><rule name="Redirect to HTTPS" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
      <add input="{HTTPS}" pattern="^OFF$" />
   </conditions>
   <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</code>```

But when I negate the rule, it no longer has any effect?

```<code><rule name="Redirect to HTTP" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
      <add input="{HTTPS}" pattern="^OFF$" negate="true" />
   </conditions>
   <action type="Redirect" url="http://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</code>```

Update. It looks like it isn't possible to process the redirect because the browser is giving the https error before the rewrite rule runs? Redirect from https to http when the SSL cert is no longer valid. Is there any way to redirect to http when using a self signed certificate?

答:
Try amending your rule to only match on the Umbraco path, something like this:

```<code>  <rule name="Force SSL" stopProcessing="true">
    <match url="^umbraco/(.*)" />
    <conditions>
      <add input="{HTTPS}" pattern="OFF" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:0}" />
  </rule>
</code>```

That way http requests for anywhere other than the umbraco path will not be redirected. For https > http requests try the following (untested)

```<code>  <rule name="Force Http" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
      <add input="{HTTPS}" pattern="ON" />
      <add input="{PATH_INFO}" pattern="^umbraco/(.*)" negate="true" />
    </conditions>
    <action type="Redirect" url="http://{HTTP_HOST}/{R:0}" />
  </rule>
</code>```

Body:
I am trying to configure Umbraco so all requests to the back office (www.mydomain.com/umbraco) get redirected to https and all non-backoffice requests are forwarded to http.

I can easily get the back office to use SSL by setting this web config appsetting key:

<add key="umbracoUseSSL" value="false" />

However, I am struggling to get all other pages to force http. The certificate is self signed so I don't want end users getting SSL errors. I have tried this rewrite rule in the web.config, but it has no impact.

<rule name="No-https" enabled="true" stopProcessing="true">
   <match url=".*" negate="false" />
   <conditions>
      <add input="{HTTPS}" pattern="on" />
      <add input="{URL}" pattern="umbraco" negate="true" />
   </conditions>
   <action type="Redirect" url="http://{HTTP_HOST}{REQUEST_URI}" />
</rule>

My aim is that any request to https://www.mydomain.com is redirected to http://www.mydomain.com unless it matches the folder /umbraco.

If I have this rule, all http requests are redirected to https:

<rule name="Redirect to HTTPS" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
      <add input="{HTTPS}" pattern="^OFF$" />
   </conditions>
   <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>

But when I negate the rule, it no longer has any effect?

<rule name="Redirect to HTTP" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
      <add input="{HTTPS}" pattern="^OFF$" negate="true" />
   </conditions>
   <action type="Redirect" url="http://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>

Update. It looks like it isn't possible to process the redirect because the browser is giving the https error before the rewrite rule runs? Redirect from https to http when the SSL cert is no longer valid. Is there any way to redirect to http when using a self signed certificate?

Body:
Try amending your rule to only match on the Umbraco path, something like this:

  <rule name="Force SSL" stopProcessing="true">
    <match url="^umbraco/(.*)" />
    <conditions>
      <add input="{HTTPS}" pattern="OFF" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:0}" />
  </rule>

That way http requests for anywhere other than the umbraco path will not be redirected. For https > http requests try the following (untested)

  <rule name="Force Http" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
      <add input="{HTTPS}" pattern="ON" />
      <add input="{PATH_INFO}" pattern="^umbraco/(.*)" negate="true" />
    </conditions>
    <action type="Redirect" url="http://{HTTP_HOST}/{R:0}" />
  </rule>


问:
How to detect mouse moving while left button down?
I would like to detect mouse movement while the left button is pressed.

I'm simply creating a drawing application. I can detect mouse movement without any mouse being pressed. But I want to detect it WITH left mouse pressed.

I don't think there's a listener for this. So, what is the idea to do that?

答:
I think there might be some sort of mouse drag listener, but if not...

Capture the mouse button down and up events.  In those events, set a boolean such as leftButtonIsDown = true (unless there's already some easy way to query that) and then in the mouse movement events use a block like if (leftButtonIsDown)

ContentLicense: CC BY-SA 4.0


问:
ggplot pie chart labeling
I am struggling with getting the pie chart labels correct. Looked around and thought that I could easily implement what mathematicalCoffee did. So far I have this code:

```<code>ltr = LETTERS[seq( from = 1, to = 26)]

wght = runif(length(ltr))
wght = wght/sum(wght)
wght = round(wght, digits = 2)

alloc = as.data.frame(cbind(ltr, wght))
alloc$wght = as.numeric(as.character(alloc$wght))

ggpie <- function (dat, by, totals) {
  ggplot(dat, aes_string(x=factor(1), y=totals, fill=by)) +
    geom_bar(stat='identity', color='black') +
    guides(fill=guide_legend(override.aes=list(colour=NA))) +
    coord_polar(theta='y') +
    theme(axis.ticks=element_blank(),
          axis.text.y=element_blank(),
          axis.text.x=element_text(colour='black'),
          axis.title=element_blank()) +
    ## scale_fill_brewer(palette = "GnBu") +
    scale_y_continuous(breaks=cumsum(dat[[totals]]) - dat[[totals]] / 2, labels=paste(dat[[by]], ":", dat[[totals]]))
}

AA = ggpie(alloc, by = "ltr", totals = "wght") +
  ggtitle("Letter weights")

AA
</code>```

The resulting pie chart:

Is there any way to generate something like this, for example:

Update for suggested dup - I think that thread is more about alternatives to pie charts and why pie charts are bad. I would like to stick to pie charts and want to find a solution to handling labels correctly/user-friendly.

答:
We can make it work with ggplot2 and the ggrepel package.

Unfortunately geom_text_repel() does not support a position = argument, so we have to calculate the starting position of the line by hand.

With your data.frame:

```<code>alloc$pos = (cumsum(c(0, alloc$wght)) + c(alloc$wght / 2, .01))[1:nrow(alloc)]
</code>```

This calculates the mean point for each group (or obs, or whtvr you want to call it).

Plugging it in in the geom_text_repel's y aes gives a nice result:

```<code>library(ggplot2)
library(ggrepel)
ggplot(alloc, aes(1, wght, fill = ltr)) +
    geom_col(color = 'black',
             position = position_stack(reverse = TRUE),
             show.legend = FALSE) +
    geom_text_repel(aes(x = 1.4, y = pos, label = ltr),
                    nudge_x = .3,
                    segment.size = .7,
                    show.legend = FALSE) +
    coord_polar('y') +
    theme_void()
</code>```

I made some choices, as the use of text instead of label, the removal of the legend and the axes. Feel free to change them

Title: ggplot pie chart labeling

Body:
I am struggling with getting the pie chart labels correct. Looked around and thought that I could easily implement what mathematicalCoffee did. So far I have this code:

ltr = LETTERS[seq( from = 1, to = 26)]

wght = runif(length(ltr))
wght = wght/sum(wght)
wght = round(wght, digits = 2)

alloc = as.data.frame(cbind(ltr, wght))
alloc$wght = as.numeric(as.character(alloc$wght))

ggpie <- function (dat, by, totals) {
  ggplot(dat, aes_string(x=factor(1), y=totals, fill=by)) +
    geom_bar(stat='identity', color='black') +
    guides(fill=guide_legend(override.aes=list(colour=NA))) +
    coord_polar(theta='y') +
    theme(axis.ticks=element_blank(),
          axis.text.y=element_blank(),
          axis.text.x=element_text(colour='black'),
          axis.title=element_blank()) +
    ## scale_fill_brewer(palette = "GnBu") +
    scale_y_continuous(breaks=cumsum(dat[[totals]]) - dat[[totals]] / 2, labels=paste(dat[[by]], ":", dat[[totals]]))
}

AA = ggpie(alloc, by = "ltr", totals = "wght") +
  ggtitle("Letter weights")

AA

The resulting pie chart:

Is there any way to generate something like this, for example:

Update for suggested dup - I think that thread is more about alternatives to pie charts and why pie charts are bad. I would like to stick to pie charts and want to find a solution to handling labels correctly/user-friendly.

Body:
We can make it work with ggplot2 and the ggrepel package.

Unfortunately geom_text_repel() does not support a position = argument, so we have to calculate the starting position of the line by hand.

With your data.frame:

alloc$pos = (cumsum(c(0, alloc$wght)) + c(alloc$wght / 2, .01))[1:nrow(alloc)]

This calculates the mean point for each group (or obs, or whtvr you want to call it).

Plugging it in in the geom_text_repel's y aes gives a nice result:

library(ggplot2)
library(ggrepel)
ggplot(alloc, aes(1, wght, fill = ltr)) +
    geom_col(color = 'black',
             position = position_stack(reverse = TRUE),
             show.legend = FALSE) +
    geom_text_repel(aes(x = 1.4, y = pos, label = ltr),
                    nudge_x = .3,
                    segment.size = .7,
                    show.legend = FALSE) +
    coord_polar('y') +
    theme_void()

I made some choices, as the use of text instead of label, the removal of the legend and the axes. Feel free to change them


问:
Automating 'To' from Contacts List Gmail
When you compose an e-mail in Gmail, to send the email to people on your Contacts list you have to click 'To' which leads you to a pop-up box. Is there a way to automate the closing of this box? I'm using Selenium and C#.</p>

答:
I think you're likely running into problems because that modular window is within an iFrame, and you need to tell Selenium to specifically look into that iFrame before searching.

See handling-iframes-using-selenium-webdriver.

Unfortunately, Google seems to assign a new ID to this iframe every time it's created, so you can't rely on that, so you'll need to create an IWebElement for the iframe element and pass it into the .SwithTo().Frame() call.

Specifically, you could try this (I tested this out, and it worked for me).

```<code>//Get iFrame element and switch to it.
IWebElement selectContactFrame= driver.FindElement(By.CssSelector("iframe.KA-JQ"));
driver.SwitchTo().Frame(selectContactFrame);

//Find cancel button and click it.
IWebElement cancelButton = driver.FindElement(By.XPath("//div[text()='Cancel']"));
cancelButton.Click();
</code>```

Body:
I think you're likely running into problems because that modular window is within an iFrame, and you need to tell Selenium to specifically look into that iFrame before searching.

See handling-iframes-using-selenium-webdriver.

Unfortunately, Google seems to assign a new ID to this iframe every time it's created, so you can't rely on that, so you'll need to create an IWebElement for the iframe element and pass it into the .SwithTo().Frame() call.

Specifically, you could try this (I tested this out, and it worked for me).

//Get iFrame element and switch to it.
IWebElement selectContactFrame= driver.FindElement(By.CssSelector("iframe.KA-JQ"));
driver.SwitchTo().Frame(selectContactFrame);

//Find cancel button and click it.
IWebElement cancelButton = driver.FindElement(By.XPath("//div[text()='Cancel']"));
cancelButton.Click();


问:
Microservices: how to effectively deal with data dependencies between microservices
I am developing an application utilizing the microservices development approach with the mean stack.  I am running into a situation where data needs to be shared between multiple microservices.  For example, let's say I have user, video, message(sending/receiving,inbox, etc.) services.  Now the video and message records belong to an account record.  As users create video and send /receive message there is a foreign key(userId) that has to be associated with the video and message records they create. I have scenarios where I need to display the first, middle and last name associated with each video for example.  Let's now say on the front end a user is scrolling through a list of videos uploaded to the system, 50 at a time.  In the worst case scenario, I could see a situation where a pull of 50 occurs where each video is tied to a unique user.

There seems to be two approaches to this issue:

One, I make an api call to the user service and get each user tied to each video in the list.  This seems inefficient as it could get really chatty if I am making one call per video.  In the second of the api call scenario, I would get the list of video and send a distinct list of user foreign keys to query to get each user tied to each video.  This seems more efficient but still seems like I am losing performance putting everything back together to send out for display or however it needs to be manipulated.

Two, whenever a new user is created, the account service sends a message with the user information each other service needs to a fanout queue and then it is the responsibility of the individual services to add the new user to a table in it's own database thus maintaining loose coupling.  The extreme downside here would be the data duplication and having to have the fanout queue to handle when updates needs to be made to ensure eventual consistency.  Though, in the long run, this approach seems like it would be the most efficient from a performance perspective.

I am torn between these two approaches, as they both have their share of tradeoffs.  Which approach makes the most sense to implement and why?

答:
I'm also interested in this question.

First of all, scenario that you described is very common. Users, videos and messages definitely three different microservices. There is no issue in how you broke down system into pieces.

Secondly, there are multiple options, how to solve data sharing problem. Take a look at great article from auth0: https://auth0.com/blog/introduction-to-microservices-part-4-dependencies/


问:
Insert image into jsp page
I am sorry that I need to ask this but I already spent three days trying to do this. I am buidling Java Web application and I want to include image to JSP page. Project name is realestates and I have Files folder inside realestates folder.

My code is like this:

```<code><img alt="govno" src="<%=request.getContextPath() + "/Files/kurac.jpg"%>" style="width: 400px; height: 300px;">
</code>```

This is what gets generated on page after I open it in browser:

```<code><img alt="govno" src="/realestates/Files/kurac.jpg" style="width: 400px; height: 300px;">
</code>```

BUT, image is not dispayed, only alt "govno" is written. I have tried many many paths (relative, absolute, changed folder structure million times and whatever I could think of and find on internet but nothing helped). Who would say that such a thing will be so hard to do???

Folder structure on Tomcat server after deployment is:

```<code>webapps
 - realestates
   |- WEB-INF
   |- Files
     |- kurac.jpg
</code>```

Title: Insert image into jsp page

Body:
I am sorry that I need to ask this but I already spent three days trying to do this. I am buidling Java Web application and I want to include image to JSP page. Project name is realestates and I have Files folder inside realestates folder.

My code is like this:

<img alt="govno" src="<%=request.getContextPath() + "/Files/kurac.jpg"%>" style="width: 400px; height: 300px;">

This is what gets generated on page after I open it in browser:

BUT, image is not dispayed, only alt "govno" is written. I have tried many many paths (relative, absolute, changed folder structure million times and whatever I could think of and find on internet but nothing helped). Who would say that such a thing will be so hard to do???

Folder structure on Tomcat server after deployment is:

webapps
 - realestates
   |- WEB-INF
   |- Files
     |- kurac.jpg

Body: At first you must create image folder outside the WEB-INF directory and try that code <img src="${pageContext.request.contextPath}/Files/kurac.jpg"/>