问:
Error in tapply(var, y, mean, na.rm = TRUE) : arguments must have same length
Why am I attaining this error? what does tapply mean? I haven't even used that method?

Error occurs: naive_model <-naiveBayes(X_train,Y_train)

Error:

```<code>Error in tapply(var, y, mean, na.rm = TRUE) :
  arguments must have same length
</code>```

CODE:

```<code>  library(e1071)
  #Naive Bayes
  #Learn Time
  start.time <- Sys.time()
  naive_model <-naiveBayes(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Learnruntime[i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred = predict(naive_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Predictruntime [i]<- time.taken
</code>```

dataset

entire code

```<code>balance_data = read.table(file.choose(), sep=",")
attach(balance_data)
x <- balance_data[, c(2,3,4,5)]
y <- balance_data[,1]
X_train <-head(x,500)
Y_train <- head(y,100)
X_test <-tail(x,122)
str(X_train)
str(X_test)
str(Y_train)

decisionTree_Learnruntime = c()
svm_Learnruntime = c()
naivebayes_Learnruntime = c()
knn_Learnruntime = c()

decisionTree_Predictruntime = c()
svm_Predictruntime = c()
naivebayes_Predictruntime =c()
knn_Predictruntime = c()

for (i in 1:20){
  library(e1071)
  library(caret)
  #SVM Model
  start.time <- Sys.time()
  svm_model <- svm(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  svm_Learnruntime[i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred <- predict(svm_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  svm_Predictruntime[i]<- time.taken

  library(rpart)
  #Decision Tree
  #Learn Time
  start.time <- Sys.time()
  tree_model <- rpart(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  decisionTree_Learnruntime[i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred = predict(tree_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  decisionTree_Predictruntime[i] <- time.taken

  library(e1071)
  #Naive Bayes
  #Learn Time
  start.time <- Sys.time()
  naive_model <-naiveBayes(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Learnruntime[i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred = predict(naive_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Predictruntime [i]<- time.taken

}

svm_Learnruntime
svm_Predictruntime
decisionTree_Learnruntime
decisionTree_Predictruntime
naivebayes_Learnruntime
naivebayes_Predictruntime
</code>```

答:
The error indicates a difference in lengths of your naiveBayes() inputs (X_train and Y_train) which need to be the same (i.e., a corresponding y value for every row of your x data). From

```<code>X_train <- head(x,500)
Y_train <- head(y,100)
</code>```

we can see the inputs differ (1st 500 vs 1st 100 rows of balance_data).  Assigning the outcome data to Y_train from the corresponding rows of X_train will resolve this error message.  For example, you could use:

```<code>trainset <- 1:500  # to be similar to your 'head(x,500)'

# create train/test
X_train <- balance_data[trainset, -1]
Y_train <- balance_data[trainset, 1]
X_test <- balance_data[-trainset, -1]

# model and predict
naive_model <- naiveBayes(X_train, Y_train)
pred <- predict(naive_model, X_test)
</code>```

Body:
Why am I attaining this error? what does tapply mean? I haven't even used that method?

Error occurs: naive_model <-naiveBayes(X_train,Y_train)

Error:

Error in tapply(var, y, mean, na.rm = TRUE) :
  arguments must have same length

CODE:

  library(e1071)
  #Naive Bayes
  #Learn Time
  start.time <- Sys.time()
  naive_model <-naiveBayes(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Learnruntime[i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred = predict(naive_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Predictruntime [i]<- time.taken

dataset

entire code

balance_data = read.table(file.choose(), sep=",")
attach(balance_data)
x <- balance_data[, c(2,3,4,5)]
y <- balance_data[,1]
X_train <-head(x,500)
Y_train <- head(y,100)
X_test <-tail(x,122)
str(X_train)
str(X_test)
str(Y_train)

decisionTree_Learnruntime = c()
svm_Learnruntime = c()
naivebayes_Learnruntime = c()
knn_Learnruntime = c()

decisionTree_Predictruntime = c()
svm_Predictruntime = c()
naivebayes_Predictruntime =c()
knn_Predictruntime = c()

for (i in 1:20){
  library(e1071)
  library(caret)
  #SVM Model
  start.time <- Sys.time()
  svm_model <- svm(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  svm_Learnruntime[i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred <- predict(svm_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  svm_Predictruntime[i]<- time.taken

  library(rpart)
  #Decision Tree
  #Learn Time
  start.time <- Sys.time()
  tree_model <- rpart(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  decisionTree_Learnruntime[i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred = predict(tree_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  decisionTree_Predictruntime[i] <- time.taken

  library(e1071)
  #Naive Bayes
  #Learn Time
  start.time <- Sys.time()
  naive_model <-naiveBayes(X_train,Y_train)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Learnruntime[i]<- time.taken

  #Prediction Time
  start.time <- Sys.time()
  pred = predict(naive_model,X_test)
  end.time <- Sys.time()
  time.taken <- end.time - start.time
  naivebayes_Predictruntime [i]<- time.taken

}

svm_Learnruntime
svm_Predictruntime
decisionTree_Learnruntime
decisionTree_Predictruntime
naivebayes_Learnruntime
naivebayes_Predictruntime

Body:
The error indicates a difference in lengths of your naiveBayes() inputs (X_train and Y_train) which need to be the same (i.e., a corresponding y value for every row of your x data). From

X_train <- head(x,500)
Y_train <- head(y,100)

we can see the inputs differ (1st 500 vs 1st 100 rows of balance_data).  Assigning the outcome data to Y_train from the corresponding rows of X_train will resolve this error message.  For example, you could use:

trainset <- 1:500  # to be similar to your 'head(x,500)'

# create train/test
X_train <- balance_data[trainset, -1]
Y_train <- balance_data[trainset, 1]
X_test <- balance_data[-trainset, -1]

# model and predict
naive_model <- naiveBayes(X_train, Y_train)
pred <- predict(naive_model, X_test)


来源: stackexchange

问:
Printing image displayed in WPF picture box
I am trying to print the image that displayed in ImageBox. I found this solution but when I tried it I got the following error:

What am I missing?

Thanks in advance.

答:
The property on imagebox is Image, with an uppercase "I", not image.

See the documentation.

ContentLicense: CC BY-SA 3.0


问:
Non lazy loading
i have a model looks like this.

```<code>public class TradeModel
{
    public int id { get; set; }

    public BaseProductModel baseProduct { get; set; }

    public string productDescription { get; set; }
    public List<byte[]> images { get; set; }
    public int price { get; set; }
    // Date infos
    public DateTime estimatedShippingDate { get; set; }

}
</code>```

What i want to do is. when i call post request i want to send an id of an existing baseProduct not the entire baseProductForm and that being created.

ive tried

```<code>    [Required]
    public int baseProductId { get; set; }

    [ForeignKey("baseProductId")]
    public virtual BaseProductModel baseProduct { get; set; }
</code>```

something like this, but seems to be not working.

any possible solutions?

答:
Your model:

```<code>public class TradeModel
{
    public int id { get; set; }

    public int baseProductId { get; set; }
    public virtual BaseProductModel baseProduct { get; set; }

    public string productDescription { get; set; }
    public List<byte[]> images { get; set; }
    public int price { get; set; }
    // Date infos
    public DateTime estimatedShippingDate { get; set; }
}
</code>```

Your ViewModel:

```<code>public class TradeViewModel
{
    public int id { get; set; }

    public int baseProductId { get; set; }

    public string productDescription { get; set; }
    public List<byte[]> images { get; set; }
    public int price { get; set; }
    // Date infos
    public DateTime estimatedShippingDate { get; set; }
}
</code>```

Now you can pass only the baseProductId:

```<code>public IActionResult(TradeViewModel model)
{
    // Your form will contain only the id anyway so the method below should work.
    // Replace that with your actual context
    //dbcontext.Trades.Add(new TradeModel { ... });
}
</code>```

Title: Non lazy loading

Body:
i have a model looks like this.

public class TradeModel
{
    public int id { get; set; }

    public BaseProductModel baseProduct { get; set; }

    public string productDescription { get; set; }
    public List<byte[]> images { get; set; }
    public int price { get; set; }
    // Date infos
    public DateTime estimatedShippingDate { get; set; }

}

What i want to do is. when i call post request i want to send an id of an existing baseProduct not the entire baseProductForm and that being created.

ive tried

    [Required]
    public int baseProductId { get; set; }

    [ForeignKey("baseProductId")]
    public virtual BaseProductModel baseProduct { get; set; }

something like this, but seems to be not working.

any possible solutions?

Body:
Your model:

public class TradeModel
{
    public int id { get; set; }

    public int baseProductId { get; set; }
    public virtual BaseProductModel baseProduct { get; set; }

    public string productDescription { get; set; }
    public List<byte[]> images { get; set; }
    public int price { get; set; }
    // Date infos
    public DateTime estimatedShippingDate { get; set; }
}

Your ViewModel:

public class TradeViewModel
{
    public int id { get; set; }

    public int baseProductId { get; set; }

    public string productDescription { get; set; }
    public List<byte[]> images { get; set; }
    public int price { get; set; }
    // Date infos
    public DateTime estimatedShippingDate { get; set; }
}

Now you can pass only the baseProductId:

public IActionResult(TradeViewModel model)
{
    // Your form will contain only the id anyway so the method below should work.
    // Replace that with your actual context
    //dbcontext.Trades.Add(new TradeModel { ... });
}


问:
Generate a random matrix in R which the sum of each rows is equal to 1
I want to generate a matrix(4 rows and 30 columns) in R software, with random elements, by range of the elements between 0 and 1, which the sum of each rows equal to 1.</p>

答:
If you pick n numbers in [0,1] which sum to 1 you are in effect picking n-1 breakpoints. You can pick the breakpoints and then work backwards to the numbers:

```<code>rand.sum <- function(n){
  x <- sort(runif(n-1))
  c(x,1) - c(0,x)
}
</code>```

And then

```<code>t(replicate(4,rand.sum(30)))
</code>```

will be a 4x30 matrix of random numbers where eaxch row sums to 1.

Body:
If you pick n numbers in [0,1] which sum to 1 you are in effect picking n-1 breakpoints. You can pick the breakpoints and then work backwards to the numbers:

rand.sum <- function(n){
  x <- sort(runif(n-1))
  c(x,1) - c(0,x)
}

And then

t(replicate(4,rand.sum(30)))

will be a 4x30 matrix of random numbers where eaxch row sums to 1.


问:
Can't traverse the DOM with next
I have the following markup

```<code><a class="list-group-item" href="#">
    <div class='row'>
        <div class='col-xs-10 shows-submenu'>
            <h4 class="list-group-item-heading">A title</h4>
        </div>
    </div>
</a>

<div class='list-group-item hidden-group-item hide'>
    <div class="row">
        <div class="col-sm-12">
            <p class="list-group-item-text">
              Some text
            </p>
        </div>
    </div>
</div>
</code>```

I'd like to remove the 'hide' class in the 'hidden-group-item' when I click the 'shows-submenu'.
I was trying to do it with the following jQuery

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

    $('body').on('click', '.shows-submenu', function() {
      if ($(this).next('.hidden-group-item').hasClass('hide')) {
         $('.hidden-group-item').addClass('hide');
         $(this).next('.hidden-group-item').toggleClass('hide');
      }
      else {
         $(this).next('.hidden-group-item').toggleClass('hide');
      }
      $('.hidden-form-item').addClass('hide');
    });

});
</code>```

but I can't make it work. The next() method seems to work only if the 'shows-submenu' class is added to the whole a tag but not in the col-xs-10 div where I want it to be.

Could you figure out why is this not working?

Thanks

答:
Replace the following:

```<code>$(this).next('.hidden-group-item')
</code>```

with

```<code>$(this).closest('a').next('.hidden-group-item')
</code>```

and try again.

Explanation: next() get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
And hidden-group-item is not the sibling in your html.

Title: Can't traverse the DOM with next

Body:
I have the following markup

A title

              Some text

I'd like to remove the 'hide' class in the 'hidden-group-item' when I click the 'shows-submenu'.
I was trying to do it with the following jQuery

$(function(){

    $('body').on('click', '.shows-submenu', function() {
      if ($(this).next('.hidden-group-item').hasClass('hide')) {
         $('.hidden-group-item').addClass('hide');
         $(this).next('.hidden-group-item').toggleClass('hide');
      }
      else {
         $(this).next('.hidden-group-item').toggleClass('hide');
      }
      $('.hidden-form-item').addClass('hide');
    });

});

but I can't make it work. The next() method seems to work only if the 'shows-submenu' class is added to the whole a tag but not in the col-xs-10 div where I want it to be.

Could you figure out why is this not working?

Thanks

Body:
Replace the following:

$(this).next('.hidden-group-item')

with

$(this).closest('a').next('.hidden-group-item')

and try again.

Explanation: next() get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
And hidden-group-item is not the sibling in your html.


问:
Node.js/Express local disk caching
I have data from my firebase database. I want to cache it as json file so I don't need to query it every time the user access my web app.

This module is good https://www.npmjs.com/package/apicache but it doesn't cache it locally. It is good since it will check if the cache is already in there , if not , you can perform queries to the db. Can you recommend me good local caching. I dont need to put it in memory cos the json file is quite big.

答:
You can download and run redis which is, to quote from their site:

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker.

It's one of the best for the purpose of caching.

There's a popular npm package you can use redis with.

Title: Node.js/Express local disk caching


问:
Syntax errror in SQL code
I have sql code for inser test value to db:

```<code>INSERT INTO log (from, value) VALUES ('ABC', 'DEF')
</code>```

I have table log:

```<code>from | value
</code>```

from and value are varchar(255).

When I run my code I a getting error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

near 'from, value) VALUES ('ABC', 'DEF')' at line 1

I don't know why, can you give me advice? I have a syntax error in code? Or what?

答:
"from" is a reserved key word in SQL.
Its better to change the column name.
If you don't want to change the column name then use following query. it works fine.
The Query looks like.

insert into log(`from`,value) values ('abc','def').
I hope that helps you!!

Title: Syntax errror in SQL code

Body:
I have sql code for inser test value to db:

INSERT INTO log (from, value) VALUES ('ABC', 'DEF')

I have table log:

from | value

from and value are varchar(255).

When I run my code I a getting error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

near 'from, value) VALUES ('ABC', 'DEF')' at line 1

I don't know why, can you give me advice? I have a syntax error in code? Or what?


答:
div.hidden-group-item is not a sibling of .shows-submenu element thus .next() will not work.

You can use .closest() to traverse up ancestor and then use .next()

```<code> var hiddenDiv = $(this).closest('a.list-group-item').next('.hidden-group-item');
</code>```

You code can also be improved.

$(function() {
  $(document).on('click', '.shows-submenu', function() {
    var hiddenDiv = $(this).closest('a.list-group-item').next('.hidden-group-item');
    $('.hidden-form-item').not(this).addClass('hide');
    hiddenDiv.toggleClass('hide');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none
}</code>```

A title

        Some text

```

Title: Can't traverse the DOM with next

Body:
div.hidden-group-item is not a sibling of .shows-submenu element thus .next() will not work.

You can use .closest() to traverse up ancestor and then use .next()

 var hiddenDiv = $(this).closest('a.list-group-item').next('.hidden-group-item');

You code can also be improved.

$(function() {
  $(document).on('click', '.shows-submenu', function() {
    var hiddenDiv = $(this).closest('a.list-group-item').next('.hidden-group-item');
    $('.hidden-form-item').not(this).addClass('hide');
    hiddenDiv.toggleClass('hide');
  });
});

.hide {
  display: none
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="list-group-item" href="#">
  <div class='row'>
    <div class='col-xs-10 shows-submenu'>
      <h4 class="list-group-item-heading">A title</h4>
    </div>
  </div>
</a>

<div class='list-group-item hidden-group-item hide'>
  <div class="row">
    <div class="col-sm-12">
      <p class="list-group-item-text">
        Some text
      </p>
    </div>
  </div>
</div>


问:
Can I take a snapshot of a website from the command line?
I am writing documentation for a website  database interface. Is it possible to write a script that, when executed, takes the most recent snapshot of the website and saves it as an image file?

note: I am using the tags ruby, bash, and python since those are the languages used in our group (along with R and FORTRAN; for sport, I'll set a 100 point bounty If anyone can post a FORTRAN solution).

update: as @birryree notes, a previous question provides the answer. Considering the FORTRAN offer is just for sport, perhaps this is a duplicate?

答: You might find this useful -- an interesting Python project which processes a queue of URLs and exports the browser screenshots to your server. </p>

ContentLicense: CC BY-SA 2.5


问:
Regular Exp: Matcher: how to get last occurence in the group
I have table structure where I need to capture the Auth code. I have used  the regex and matcher method find(). However, there will be multiple codes generated and I need to get the recent one. I tried below code which captures only 1st occurrence. Please let me know How I can capture last occurrence of the code.

Code:

```<code>String mobilenumber="00955555555555";

//Date validate = null;

    {
    List<WebElement> rows = driver1.findElements(By.cssSelector("tr"));
    for (WebElement row : rows)
    {
        String text = row.getText();
        if (text.contains(mobilenumber))
        {
            String regex = ": (\\d+)"; //Your authentication code is
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);

            if (matcher.find())
                 {

                valueis = matcher.group(1);
                System.out.println(valueis);
</code>```

答:
There are (maybe not surprising) more ways to obtain this. Here are a couple.

One, keep matching until there are no more matches. The last match is — the last match.

```<code>        String valueis = null;
        while (matcher.find()) {
            valueis = matcher.group(1);
        }
        System.out.println(valueis);
</code>```

Two, alternatively in your regular expression first match as much of the string as you can before the colon and number:

```<code>        String regex = ".*: (\\d+)"; // Your authentication code is
</code>```

Since the * quantifier is greedy, this will match the last number first. For a simple test of the latter, try:

```<code>    String regex = ".*: (\\d+)";
    Pattern pattern = Pattern.compile(regex);

    String text = "00955555555555 auth: 44; auth: 77 end";
    Matcher matcher = pattern.matcher(text);
    if (matcher.find()) {
        String valueis = matcher.group(1);
        System.out.println(valueis);
    }
</code>```

This prints 77.

From the discussion I gather that there is only one authentication code (one regex match) in each table row (
 element), but the same mobile number may occur in more than one table row, and if so, you want the last (most recent) occurrence. This seems not to be a regular expression problem, but a problem of program logic. Here’s my attempt to solve it:

```<code>    String regex = ": (\\d+)"; // Your authentication code is
    Pattern pattern = Pattern.compile(regex);

    String valueis = null;
    for (WebElement row : rows) {
        String text = row.getText();
        if (text.contains(mobilenumber)) {
            Matcher matcher = pattern.matcher(text);

            if (matcher.find()) {
                valueis = matcher.group(1);
            }
        }
    }
    if (valueis == null) {
        System.out.println("Not found");
    } else {
        System.out.println("Last occurrence was " + valueis);
    }
</code>```

Body:
I have table structure where I need to capture the Auth code. I have used  the regex and matcher method find(). However, there will be multiple codes generated and I need to get the recent one. I tried below code which captures only 1st occurrence. Please let me know How I can capture last occurrence of the code.

Code:

String mobilenumber="00955555555555";

//Date validate = null;

    {
    List<WebElement> rows = driver1.findElements(By.cssSelector("tr"));
    for (WebElement row : rows)
    {
        String text = row.getText();
        if (text.contains(mobilenumber))
        {
            String regex = ": (\\d+)"; //Your authentication code is
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);

            if (matcher.find())
                 {

                valueis = matcher.group(1);
                System.out.println(valueis);

Body:
There are (maybe not surprising) more ways to obtain this. Here are a couple.

One, keep matching until there are no more matches. The last match is — the last match.

        String valueis = null;
        while (matcher.find()) {
            valueis = matcher.group(1);
        }
        System.out.println(valueis);

Two, alternatively in your regular expression first match as much of the string as you can before the colon and number:

        String regex = ".*: (\\d+)"; // Your authentication code is

Since the * quantifier is greedy, this will match the last number first. For a simple test of the latter, try:

    String regex = ".*: (\\d+)";
    Pattern pattern = Pattern.compile(regex);

    String text = "00955555555555 auth: 44; auth: 77 end";
    Matcher matcher = pattern.matcher(text);
    if (matcher.find()) {
        String valueis = matcher.group(1);
        System.out.println(valueis);
    }

This prints 77.

From the discussion I gather that there is only one authentication code (one regex match) in each table row (<tr> element), but the same mobile number may occur in more than one table row, and if so, you want the last (most recent) occurrence. This seems not to be a regular expression problem, but a problem of program logic. Here’s my attempt to solve it:

    String regex = ": (\\d+)"; // Your authentication code is
    Pattern pattern = Pattern.compile(regex);

    String valueis = null;
    for (WebElement row : rows) {
        String text = row.getText();
        if (text.contains(mobilenumber)) {
            Matcher matcher = pattern.matcher(text);

            if (matcher.find()) {
                valueis = matcher.group(1);
            }
        }
    }
    if (valueis == null) {
        System.out.println("Not found");
    } else {
        System.out.println("Last occurrence was " + valueis);
    }


问:
Is there a way of fixing a maximum value for an element in an array?
```<code>list = [5, 10, 20, 40, 50, 42, 35, 26, 18]
</code>```

So in this example, I don't want an element to exceed the value 40 and if it does, I want the element to have a value of 40, e.g. the element with the value 50 will become 40.

答:
```<code>list.map! { |i| i > 40 ? 40 : i }
 => [5, 10, 20, 40, 40, 40, 35, 26, 18]
</code>```

map method permits you to apply a transformation to all the elements of your collection so I think fits perfectly in this case.

Or, if you are populating your array one element at a time, you could insert the real value just if it's 40 or less, 40 otherwise.

Body:
list = [5, 10, 20, 40, 50, 42, 35, 26, 18]

So in this example, I don't want an element to exceed the value 40 and if it does, I want the element to have a value of 40, e.g. the element with the value 50 will become 40.

Body:
list.map! { |i| i > 40 ? 40 : i }
 => [5, 10, 20, 40, 40, 40, 35, 26, 18]

map method permits you to apply a transformation to all the elements of your collection so I think fits perfectly in this case.

Or, if you are populating your array one element at a time, you could insert the real value just if it's 40 or less, 40 otherwise.


问:
Can sprintf / formatted strings be passed directly to a function?
Is something like this allowed in C++? If so, how do I do it?

```<code>myFunction("User input: %s", a);
</code>```

Or is the only way to format it first and then pass it?

答: Yes, it's allowed. No, it is not a part of the standard library, so you have to implement it yourself. </p>

Body:
Is something like this allowed in C++? If so, how do I do it?

myFunction("User input: %s", a);

Or is the only way to format it first and then pass it?


答:
Try this:  </p>

```<code> $('body').on('click', '.shows-submenu', function() {
      if ($(this).closest(".list-group-item").next('.hidden-group-item').hasClass('hide')) ......
</code>```

Title: Can't traverse the DOM with next

Body:
Try this:

 $('body').on('click', '.shows-submenu', function() {
      if ($(this).closest(".list-group-item").next('.hidden-group-item').hasClass('hide')) ......


问:
Android Studio layout: match parent, wrap content and dp,
I use a layout with dp dimensions for my project, but if I change device also the layout change.
So is there a way to do an universal layout?
What can i do?</p>

答:
That is a very broad question and there is a lot of material available on the web to address it. To get you started, the Android developer site has an excellent introduction to the topic of "Supporting Multiple Screens". I think that this is what you are looking for.

Supporting Multiple Screens

Android runs on a variety of devices that offer different screen sizes and densities. For applications, the Android system provides a consistent development environment across devices and handles most of the work to adjust each application's user interface to the screen on which it is displayed. At the same time, the system provides APIs that allow you to control your application's UI for specific screen sizes and densities, in order to optimize your UI design for different screen configurations. For example, you might want a UI for tablets that's different from the UI for handsets.


问:
Rollup generates empty bundle
I would like to bundle a .js file with rollup that has only a class definition in it. But rollup creates only an empty bundle-file. This changes when I add some code outside the class Definition.
This creates an empty bundle:

```<code>class MyElement extends HTMLElement{
    constructor() {...}
    ...
}
</code>```

And this creates a filled bundle:

```<code>class MyElement extends HTMLElement{
    constructor() {...}
    ...
}

customElements.define('my-element', MyElement);
</code>```

But I don't want to have the ...define() in that file.
Is there a way to convice rollup.js to just bundle the class-definition?

答:
You have a module that defines a class in its local scope but doesn't do anything with it - neither export it nor use it to perform a side effect like passing it to define. It's dead code - and that will be stripped by rollup. You'll likely want to use

```<code>export default class MyElement extends HTMLElement { /*
^^^^^^^^^^^^^^ */
    constructor() { … }
    …
}
</code>```

which can be bundled to something that still exports the class so that it is usable elsewhere.

Title: Rollup generates empty bundle

Body:
I would like to bundle a .js file with rollup that has only a class definition in it. But rollup creates only an empty bundle-file. This changes when I add some code outside the class Definition.
This creates an empty bundle:

class MyElement extends HTMLElement{
    constructor() {...}
    ...
}

And this creates a filled bundle:

class MyElement extends HTMLElement{
    constructor() {...}
    ...
}

customElements.define('my-element', MyElement);

But I don't want to have the ...define() in that file.
Is there a way to convice rollup.js to just bundle the class-definition?

Body:
You have a module that defines a class in its local scope but doesn't do anything with it - neither export it nor use it to perform a side effect like passing it to define. It's dead code - and that will be stripped by rollup. You'll likely want to use

export default class MyElement extends HTMLElement { /*
^^^^^^^^^^^^^^ */
    constructor() { … }
    …
}

which can be bundled to something that still exports the class so that it is usable elsewhere.


问:
Add small change in two branches - git
I have two branches one master and other release branch. release branch is taken from master few days ago and has changes that are specific to release. master branch is used for active development.

Now i made one change in master branch. How should i copy this one change to release branch. Master branch has commits done by other team members too.

Please advise.

Thanks

答:
```<code> git checkout release-branch
 git fetch origin
 git rebase origin/master
</code>```

then push the release branch.

```<code>git push release-branch
</code>```

Title: Add small change in two branches - git

Body:
 git checkout release-branch
 git fetch origin
 git rebase origin/master

then push the release branch.

git push release-branch


答:
next() method will only work in siblings.

use find() method instead like this.

$.find('.hidden-group-item').toggleClass('hide');

Title: Can't traverse the DOM with next


问:
UWP - BackgroundTask and ContactManager
I am facing the problem that if I try to access the ContactManager from a BackgroundTask I get a System.IO.FileLoadException .

The same code works well when calling it from my main application:

```<code>    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
        test();
        deferral.Complete();

    }

    private async void test()
    {
        ContactStore contactStore = await ContactManager.RequestStoreAsync();
    }
</code>```

The BackgroundTasks starts normally, but as soon as I call "test" the exception is thrown.

答: try to change your async void test to async Task test</p>

Title: UWP - BackgroundTask and ContactManager

Body:
I am facing the problem that if I try to access the ContactManager from a BackgroundTask I get a System.IO.FileLoadException .

The same code works well when calling it from my main application:

    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
        test();
        deferral.Complete();

    }

    private async void test()
    {
        ContactStore contactStore = await ContactManager.RequestStoreAsync();
    }

The BackgroundTasks starts normally, but as soon as I call "test" the exception is thrown.


问:
Angularjs - sum object value in a controller in an array
I am trying to get cost sum from object array in controller. I got this array from mongo collection

```<code>vm.costs = CostsService.query();
</code>```

and then invoke a function to calculate cost sum

```<code>  vm.sum = function (items, prop) {
  console.log(items);
  return items.reduce(function (a, b) {
    return a + b[prop];
  }, 0);
};

vm.costTotal = vm.sum(vm.costs, 'costprice');
</code>```

I don't know why I got 0 value instead of real sum of costs.
I checked the items in a console in Chrome browser, but list is showing in proper way.

console.log() screenshot

There is one interesting thing, if I added in controller hardcoding array and then invoke the sum function everything looks good. I think that problem is in array from mongo, but I don't have any ideas how do this to get this cost sum.

My CostService method below:

// Costs service used to communicate Costs REST endpoints
(function () {
  'use strict';

  angular
    .module('costs')
    .factory('CostsService', CostsService);

  CostsService.$inject = ['$resource'];

  function CostsService($resource) {
    return $resource('api/costs/:costId', {
      costId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
}());```

答:
This could be because your CostsService might be returing a Promise resolving costs instead of costs array directly. To solve that, you need to call the vm.sum inside .then of your promise returning service call. Like this:

```<code>  vm.sum = function(items, prop) {
    console.log(items);
    return items.reduce(function(a, b) {
      return a + b[prop];
    }, 0);
  };

  CostsService.query().$promise.then(function(costs) {
    vm.costs = costs;
    vm.costTotal = vm.sum(costs, 'costprice');
  });
</code>```

Body:
I am trying to get cost sum from object array in controller. I got this array from mongo collection

vm.costs = CostsService.query();

and then invoke a function to calculate cost sum

  vm.sum = function (items, prop) {
  console.log(items);
  return items.reduce(function (a, b) {
    return a + b[prop];
  }, 0);
};

vm.costTotal = vm.sum(vm.costs, 'costprice');

I don't know why I got 0 value instead of real sum of costs.
I checked the items in a console in Chrome browser, but list is showing in proper way.

console.log() screenshot

There is one interesting thing, if I added in controller hardcoding array and then invoke the sum function everything looks good. I think that problem is in array from mongo, but I don't have any ideas how do this to get this cost sum.

My CostService method below:

// Costs service used to communicate Costs REST endpoints
(function () {
  'use strict';

  angular
    .module('costs')
    .factory('CostsService', CostsService);

  CostsService.$inject = ['$resource'];

  function CostsService($resource) {
    return $resource('api/costs/:costId', {
      costId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
}());

Body:
This could be because your CostsService might be returing a Promise resolving costs instead of costs array directly. To solve that, you need to call the vm.sum inside .then of your promise returning service call. Like this:

  vm.sum = function(items, prop) {
    console.log(items);
    return items.reduce(function(a, b) {
      return a + b[prop];
    }, 0);
  };

  CostsService.query().$promise.then(function(costs) {
    vm.costs = costs;
    vm.costTotal = vm.sum(costs, 'costprice');
  });


问:
Heap corruption when using delete/new in extra function
In the following code sample Visual Studio gives me the error "A heap has been corrupted". At first the for-loop seems to work fine, but after 1 or 2 iterations it just crashes.

I feel that my function myReAllocate facilitates some sort of memory leak where it shouldn't (because when I comment it out, everything works fine). What exactly is going on? It seems like a very subtle error.

```<code>#include <iostream>
using namespace std;

class myClass{};

void myReAllocate(myClass* c)
{
    delete c;
    c = new myClass();
}

int main(void)
{
    myClass *cc[10];

    for (int i = 0; i < 10; i++){
        cout << i << " attempt" << endl;
        cc[i] = new myClass();
        myReAllocate(cc[i]);
        delete cc[i];
    }

    return 0;
}
</code>```

I have tried adding a operator= but it didn't help either.

```<code>myClass operator=(myClass& right) {
    myClass temp = right;
    return *this;
}
</code>```

答:
myReAllocate gets the address of the myClass as parameter. You then free that address and allocate a new object and assign it to the local variable. This has no effect on the value of cc[i]. So when you then delete cc[i] you delete the already deleted object again.

If you want do to something like that then you need to pass the address of cc[i] (or reference to it) so you can change it:

```<code>void myReAllocate(myClass** c)
{
    delete *c;
    *c = new myClass();
}
</code>```

Body:
In the following code sample Visual Studio gives me the error "A heap has been corrupted". At first the for-loop seems to work fine, but after 1 or 2 iterations it just crashes.

I feel that my function myReAllocate facilitates some sort of memory leak where it shouldn't (because when I comment it out, everything works fine). What exactly is going on? It seems like a very subtle error.

#include <iostream>
using namespace std;

class myClass{};

void myReAllocate(myClass* c)
{
    delete c;
    c = new myClass();
}

int main(void)
{
    myClass *cc[10];

    for (int i = 0; i < 10; i++){
        cout << i << " attempt" << endl;
        cc[i] = new myClass();
        myReAllocate(cc[i]);
        delete cc[i];
    }

    return 0;
}

I have tried adding a operator= but it didn't help either.

myClass operator=(myClass& right) {
    myClass temp = right;
    return *this;
}

Body:
myReAllocate gets the address of the myClass as parameter. You then free that address and allocate a new object and assign it to the local variable. This has no effect on the value of cc[i]. So when you then delete cc[i] you delete the already deleted object again.

If you want do to something like that then you need to pass the address of cc[i] (or reference to it) so you can change it:

void myReAllocate(myClass** c)
{
    delete *c;
    *c = new myClass();
}


答:
If you want to write a function that takes variable parameters, the answer is yes, and here's how you declare such a function:

```<code>void myFunction(const char*, ...);
</code>```

Note the elipsis at the end.

But now that you know how to do this, I'll complicate things for you.  You should not do this.  The myFunction() declared above is type-unsafe, and completely sidesteps every means C++ has to protect you from mistakes.

There are other ways to accomplish something like this (vector comes to mind), but I have found that if you're needing a function that takes variable parameters, it's a code smell that indicates that there is somethign wrong with your design in the first place.  Take a closer look at why you need this.

EDIT:

If what you're trying to do is not pass variable parameters per se, but a formatted string (like your OP says), then you would need to do the string formatting yourself in your function.  There are ways to do this depending on your platform.  In Windows, you'd probably use vsprintf() or something similar.

But again, if you need to do this, there are better ways.  Personally I'm fond of using Boost format.

Title: Can sprintf / formatted strings be passed directly to a function?

Body:
If you want to write a function that takes variable parameters, the answer is yes, and here's how you declare such a function:

void myFunction(const char*, ...);

Note the elipsis at the end.

But now that you know how to do this, I'll complicate things for you.  You should not do this.  The myFunction() declared above is type-unsafe, and completely sidesteps every means C++ has to protect you from mistakes.

There are other ways to accomplish something like this (vector comes to mind), but I have found that if you're needing a function that takes variable parameters, it's a code smell that indicates that there is somethign wrong with your design in the first place.  Take a closer look at why you need this.

EDIT:

If what you're trying to do is not pass variable parameters per se, but a formatted string (like your OP says), then you would need to do the string formatting yourself in your function.  There are ways to do this depending on your platform.  In Windows, you'd probably use vsprintf() or something similar.

But again, if you need to do this, there are better ways.  Personally I'm fond of using Boost format.


答:
Use cherry-pick command to apply commit from one branch to another in the following way:

Find the hash of commit you wish to apply;

git checkout release-branch

git cherry-pick <commit-hash>

After that, I would suggest you to merge release-branch back to master to avoid conflicts in the future.

Title: Add small change in two branches - git

Body:
I have two branches one master and other release branch. release branch is taken from master few days ago and has changes that are specific to release. master branch is used for active development.

Now i made one change in master branch. How should i copy this one change to release branch. Master branch has commits done by other team members too.

Please advise.

Thanks


问:
Circular Queue Array
Hi everyone i am trying to implement a circular array, but something is not exactly right. I am not sure if is in the add method or display. When you run the debugger, the numbers are there but i cant get them in order. Please could you have a look and give me a feedback. Thank you.

```<code>public static void main (String[] args)
{
    Scanner input = new Scanner (System.in);
    Queue q1 = new Queue();
    int choice = 0;

    do
    {
        System.out.println ("Menu:");
        System.out.println ("1: Add");
        System.out.println ("2: Remove");
        System.out.println ("3: Display");
        System.out.println ("4: Exit");

        System.out.print ("\nChoice: ");
        choice = input.nextInt ();

        switch ( choice )
        {
            case 1:
                System.out.print ("\nEnter a number: ");
                int num = input.nextInt ();
                q1.add (num);
                break;
            case 2:
                q1.remove ();
                break;
            case 3:
                q1.display ();
                break;
            case 4:
                System.out.println ("Good Bye");
                break;
            default:
                System.out.println ("Wrong choice!");
                break;
        }

    } while ( choice != 4 );

}
</code>```

}

public class Queue
{

```<code>private final int SIZE;
private int first;
private int last;
private int[] q;

public Queue ()
{
    SIZE = 5;
    q = new int[ SIZE ];
    first = 0;
    last = 0;
}

public boolean isFull ()
{
    return last == SIZE;
}

public boolean isEmpty ()
{
    return last == first;
}

public void add (int x)
{
    if (  ! isFull () )
    {
        q[ ( first + last ) % q.length ] = x;
        last ++;
    } else
    {
        System.out.println ("\nThe queue is full!");
    }
}

int remove ()
{
    int x = 0;
    if (  ! isEmpty () )
    {
        x = q[ first ];
        first = ( first + 1 ) % q.length;
        last --;
    } else
    {
        System.out.println ("The queue is empy");
    }
    return x;

}

public void display ()
{
    if (  ! isEmpty () )
    {
        for ( int i = first; i < SIZE; i ++ )
        {
            System.out.println (q[ i ]);
        }

    } else
    {
        System.out.println ("The queue is emptry");
    }
}
</code>```

答: It worked pretty well. Can you be more specific about your error ?</p>

Title: Circular Queue Array

Body:
Hi everyone i am trying to implement a circular array, but something is not exactly right. I am not sure if is in the add method or display. When you run the debugger, the numbers are there but i cant get them in order. Please could you have a look and give me a feedback. Thank you.

public static void main (String[] args)
{
    Scanner input = new Scanner (System.in);
    Queue q1 = new Queue();
    int choice = 0;

    do
    {
        System.out.println ("Menu:");
        System.out.println ("1: Add");
        System.out.println ("2: Remove");
        System.out.println ("3: Display");
        System.out.println ("4: Exit");

        System.out.print ("\nChoice: ");
        choice = input.nextInt ();

        switch ( choice )
        {
            case 1:
                System.out.print ("\nEnter a number: ");
                int num = input.nextInt ();
                q1.add (num);
                break;
            case 2:
                q1.remove ();
                break;
            case 3:
                q1.display ();
                break;
            case 4:
                System.out.println ("Good Bye");
                break;
            default:
                System.out.println ("Wrong choice!");
                break;
        }

    } while ( choice != 4 );

}

}

public class Queue
{

private final int SIZE;
private int first;
private int last;
private int[] q;

public Queue ()
{
    SIZE = 5;
    q = new int[ SIZE ];
    first = 0;
    last = 0;
}

public boolean isFull ()
{
    return last == SIZE;
}

public boolean isEmpty ()
{
    return last == first;
}

public void add (int x)
{
    if (  ! isFull () )
    {
        q[ ( first + last ) % q.length ] = x;
        last ++;
    } else
    {
        System.out.println ("\nThe queue is full!");
    }
}

int remove ()
{
    int x = 0;
    if (  ! isEmpty () )
    {
        x = q[ first ];
        first = ( first + 1 ) % q.length;
        last --;
    } else
    {
        System.out.println ("The queue is empy");
    }
    return x;

}

public void display ()
{
    if (  ! isEmpty () )
    {
        for ( int i = first; i < SIZE; i ++ )
        {
            System.out.println (q[ i ]);
        }

    } else
    {
        System.out.println ("The queue is emptry");
    }
}


问:
Why I can't create an index on temporary table?
First I created a temporary table

```<code>CREATE GLOBAL TEMPORARY TABLE TMP ON COMMIT PRESERVE ROWS AS
SELECT *
FROM A
</code>```

then

```<code>INSERT INTO TMP
SELECT *
FROM B

COMMIT
</code>```

finally

```<code>CREATE INDEX IDX ON TMP (COLA, COLB, COLC);
</code>```

Upon creating the index, I got the following error

ORA-14452: attempt to create, alter or drop an index on temporary table already in use

I followd these steps in the same session.

What I want to do(with temporary table) is

Disable/Drop index

Insert large data

Enable/Create index

How can I acheive this?

答:
ORA-14452: attempt to create, alter or drop an index on temporary table already in use

This error occurs when it is tried to perform a DDL on a global temporary table with on commit preserve rows when the session trying to do the DDL has already made a DML on the table.
      In order to do a DDL, the table must first be either truncated or the session must be exited.

http://www.adp-gmbh.ch/ora/err/ora_14452.html

Body:
First I created a temporary table

CREATE GLOBAL TEMPORARY TABLE TMP ON COMMIT PRESERVE ROWS AS
SELECT *
FROM A

then

INSERT INTO TMP
SELECT *
FROM B

COMMIT

finally

CREATE INDEX IDX ON TMP (COLA, COLB, COLC);

Upon creating the index, I got the following error

ORA-14452: attempt to create, alter or drop an index on temporary table already in use

I followd these steps in the same session.

What I want to do(with temporary table) is

Disable/Drop index

Insert large data

Enable/Create index

How can I acheive this?


问:
How to achive swipe left and right on activity containg 2 fragments in android?
I have a activity that contain 2 fragments and both the fragments containing a recyclerview.
I need to implement a swipe gesture (when i swipe from one side to another the fragments need to be changed).
Previously i have added swipe gesture, but when i swipe the recycler view will scroll instead of change of fragments.

Can you help in implementing this..

Thanks

答: just use Android TabLayout with ViewPager and your problem will be solved :)</p>


答:
Would it be okay to take a snapshot of a web page and save it as an HTML file with images? Because that's trivial.

wget -m -p http://www.example.com/example.html

Title: Can I take a snapshot of a website from the command line?

Body:
I am writing documentation for a website  database interface. Is it possible to write a script that, when executed, takes the most recent snapshot of the website and saves it as an image file?

note: I am using the tags ruby, bash, and python since those are the languages used in our group (along with R and FORTRAN; for sport, I'll set a 100 point bounty If anyone can post a FORTRAN solution).

update: as @birryree notes, a previous question provides the answer. Considering the FORTRAN offer is just for sport, perhaps this is a duplicate?


问:
Using Shiny actionButton() function in onRender() function of htmlWidgets
I have a Shiny application in which a user can select black points in a Plotly scatterplot using the Plotly "box select" icon. The points the user selects will be highlighted in red. I have a MWE of this application below:

```<code>library(plotly)
library(htmlwidgets)
library(shiny)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot")
))

server <- shinyServer(function(input, output) {
  p <- ggplot(mtcars, aes(x = wt, y = mpg))  + xlim(10,40) +ylim(0,10)
  ggPS <- ggplotly(p)

  output$myPlot <- renderPlotly(ggPS %>%
    onRender("
       function(el, x, data) {

       var xArr = [];
       var yArr = [];
       for (a=0; a<data.wt.length; a++){
       xArr.push(data.wt[a])
       yArr.push(data.mpg[a])
       }

       Traces=[]
       var tracePoints = {
         x: yArr,
         y: xArr,
         hoverinfo: 'none',
         mode: 'markers',
         marker: {
           color: 'black',
           size: 4
         }
       };
       Traces.push(tracePoints);
       Plotly.addTraces(el.id, Traces);

       el.on('plotly_selected', function(e) {
       var numSel = e.points.length
       var xSel = [];
       var ySel = [];

       for (a=0; a<numSel; a++){
         xSel.push(e.points[a].x)
         ySel.push(e.points[a].y)
       }

       var trace = {
         x: xSel,
         y: ySel,
         mode: 'markers',
         marker: {
           color: 'red',
           size: 4
         },
         hoverinfo: 'none'
       };

       Traces.push(trace);
       Plotly.addTraces(el.id, Traces);
       })

       }
       ", data = list(dat= mtcars, wt=mtcars$wt, mpg=mtcars$mpg)))})

shinyApp(ui, server)
</code>```

I am now trying to update this Shiny application so that the selected black points do not automatically become red. Instead, after the user selects the black points, they can click on an action button with a label "Highlight selected points". If the user clicks that action button, then the selected points become red. Below is my attempt at getting this to work. Unfortunately, this application is not working, and actually loses its functionality of drawing the original black points and providing a box select icon in the first place .

```<code>library(plotly)
library(Shiny)
library(htmlwidgets)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot"),
  actionButton("highlight", "Highlight selected points")
))

server <- shinyServer(function(input, output) {

  highlight <- reactive(input$highlight)

  p <- ggplot(mtcars, aes(x = wt, y = mpg))  + xlim(10,40) +ylim(0,10)
  ggPS <- ggplotly(p)

  output$myPlot <- renderPlotly(ggPS %>%
onRender("
   function(el, x, data) {

   var xArr = [];
   var yArr = [];
   for (a=0; a<data.wt.length; a++){
   xArr.push(data.wt[a])
   yArr.push(data.mpg[a])
   }

   Traces=[]
   var tracePoints = {
   x: yArr,
   y: xArr,
   hoverinfo: 'none',
   mode: 'markers',
   marker: {
   color: 'black',
   size: 4
   }
   };
   Traces.push(tracePoints);
   Plotly.addTraces(el.id, Traces);

   el.on('plotly_selected', function(e) {

observeEvent(data.highlightS, {
   var numSel = e.points.length
   var xSel = [];
   var ySel = [];
   for (a=0; a<numSel; a++){
   xSel.push(e.points[a].x)
   ySel.push(e.points[a].y)
   }

   var trace = {
   x: xSel,
   y: ySel,
   mode: 'markers',
   marker: {
   color: 'red',
   size: 4
   },
   hoverinfo: 'none'
   };
   Traces.push(trace);
   Plotly.addTraces(el.id, Traces);
})
   })

   }
   ", data = list(dat= mtcars, wt=mtcars$wt, mpg=mtcars$mpg, highlightS=highlight())))})

shinyApp(ui, server)
</code>```

EDIT:

I wanted to include a picture to demonstrate what I am aiming for. Basically, if the user selects the 15 dots shown below, they remain black:

However, if the user selects the "Highlight the selected points" Shiny button, then the 15 dots will become red as shown below:

答:
Ok, this does what you want I think.

I had to take a different approach since I don't think you can add a plotly el.on event like that, but plotly has actually a Shiny event_data("plotly_selected") construct intended just for this kind of thing - so I used that instead.

The major changes I made:

stored the dataframe we are working with (m) in a reactiveValues so you could access it easily (without using <<-) from inside a reactive node.

added a reactive(event_data(.. to retreive the shiny selection data.

added a selected column to our working dataframe to keep track of what should be marked red.

added a reactive node (mvis) to process the selected data as it comes in and mark the new things as selected. Isolated the node from the reactiveValue event as well with isolate to avoid an endless reaction chain.

got rid of the el.on(plotly_selected because I don't see how that could work (although there is probably a way).

enabled the selection of the markers with a layout(dragmode="select") call

added a second trace one for black markers, one for selected ones

added a key variable so we could keep track of how the plotted markers correspond to our data rows.

and a few other miscellaneous small changes (xArr and yArr were reversed in the original traceBlock definition for example)

added a bootstrap toggle button to highlight the selectionr (as later requested). Note that it requires a double-click to toggle.

So here is the code:

```<code>library(plotly)
library(htmlwidgets)
library(shiny)
library(shinyBS)
library(ggplot2)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot"),
  bsButton("high","Highlight Selected Points",type="toggle")
))

server <- shinyServer(function(input, output) {

  m <- mtcars
  m$selected <- 0

  rv <- reactiveValues(m=m,high=FALSE)

  observeEvent(input$high,{req(input$high);rv$high <- !rv$high } )

  ggPS <- reactive(ggplotly(ggplot(m, aes(x = wt, y = mpg))))

  sel <- reactive(event_data("plotly_selected"))

  mvis <- reactive({
    rv$high
    sdatf <- sel()
    print(rv$high)
    isolate({
      rv$m$selected <- 0
      rv$m$selected[ sdatf$key ] <- 1  # now select the ones in sdatf
    })
    #  print(sdatf)  # debugging
    return(rv$m)
  })

  jscode <-
 "function(el, x, data) {
    Traces=[]
    var xArrNrm = [];
    var yArrNrm = [];
    var idxNrm = [];
    var xArrSel = [];
    var yArrSel = [];
    var idxSel = [];
    for (a=0; a<data.mvis.length; a++){
      if(data.mvis[a]['selected']===0){
        xArrNrm.push(data.mvis[a]['wt'])
        yArrNrm.push(data.mvis[a]['mpg'])
        idxNrm.push(a+1)
      } else {
        xArrSel.push(data.mvis[a]['wt'])
        yArrSel.push(data.mvis[a]['mpg'])
        idxSel.push(a+1)
      }
    }
    console.log(data.mvis.length)
    console.log(data)
    var tracePointsNrm = {
      x: xArrNrm,
      y: yArrNrm,
      key: idxNrm,
      hoverinfo: 'none',
      mode: 'markers',
      marker: {
        color: 'black',
        size: 4
      }
    };
    var tracePointsSel = {
      x: xArrSel,
      y: yArrSel,
      key: idxSel,
      hoverinfo: 'none',
      mode: 'markers',
      marker: {
        color: 'red',
        size: 6
      }
    };
    if (!data.high){
       tracePointsSel.marker.color = 'black'
    }
    //   console.log(tracePointsNrm) // debuging
    //   console.log(tracePointsSel)
    Traces.push(tracePointsNrm);
    Traces.push(tracePointsSel);
    Plotly.addTraces(el.id, Traces);
 }"
  output$myPlot <- renderPlotly({
                    ggPS() %>%  onRender(jscode,data=list(mvis=mvis(),high=rv$high)) %>%
                                layout(dragmode = "select")
                    })
})
shinyApp(ui, server)
</code>```

And here is a screen shot:

Note:

This seems overly complex, and it is. In theory this could be done without using onRender and any javascript, by adding traces with add_marker and setting the key attribute. Unfortunately  there seems to be a plotly bug in the R binding that scrambles the key values after selection when you do it that way. Too bad - it would be much shorter and easier to understand - maybe it will eventually get fixed.

Body:
I have a Shiny application in which a user can select black points in a Plotly scatterplot using the Plotly "box select" icon. The points the user selects will be highlighted in red. I have a MWE of this application below:

library(plotly)
library(htmlwidgets)
library(shiny)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot")
))

server <- shinyServer(function(input, output) {
  p <- ggplot(mtcars, aes(x = wt, y = mpg))  + xlim(10,40) +ylim(0,10)
  ggPS <- ggplotly(p)

  output$myPlot <- renderPlotly(ggPS %>%
    onRender("
       function(el, x, data) {

       var xArr = [];
       var yArr = [];
       for (a=0; a<data.wt.length; a++){
       xArr.push(data.wt[a])
       yArr.push(data.mpg[a])
       }

       Traces=[]
       var tracePoints = {
         x: yArr,
         y: xArr,
         hoverinfo: 'none',
         mode: 'markers',
         marker: {
           color: 'black',
           size: 4
         }
       };
       Traces.push(tracePoints);
       Plotly.addTraces(el.id, Traces);

       el.on('plotly_selected', function(e) {
       var numSel = e.points.length
       var xSel = [];
       var ySel = [];

       for (a=0; a<numSel; a++){
         xSel.push(e.points[a].x)
         ySel.push(e.points[a].y)
       }

       var trace = {
         x: xSel,
         y: ySel,
         mode: 'markers',
         marker: {
           color: 'red',
           size: 4
         },
         hoverinfo: 'none'
       };

       Traces.push(trace);
       Plotly.addTraces(el.id, Traces);
       })

       }
       ", data = list(dat= mtcars, wt=mtcars$wt, mpg=mtcars$mpg)))})

shinyApp(ui, server)

I am now trying to update this Shiny application so that the selected black points do not automatically become red. Instead, after the user selects the black points, they can click on an action button with a label "Highlight selected points". If the user clicks that action button, then the selected points become red. Below is my attempt at getting this to work. Unfortunately, this application is not working, and actually loses its functionality of drawing the original black points and providing a box select icon in the first place .

library(plotly)
library(Shiny)
library(htmlwidgets)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot"),
  actionButton("highlight", "Highlight selected points")
))

server <- shinyServer(function(input, output) {

  highlight <- reactive(input$highlight)

  p <- ggplot(mtcars, aes(x = wt, y = mpg))  + xlim(10,40) +ylim(0,10)
  ggPS <- ggplotly(p)

  output$myPlot <- renderPlotly(ggPS %>%
onRender("
   function(el, x, data) {

   var xArr = [];
   var yArr = [];
   for (a=0; a<data.wt.length; a++){
   xArr.push(data.wt[a])
   yArr.push(data.mpg[a])
   }

   Traces=[]
   var tracePoints = {
   x: yArr,
   y: xArr,
   hoverinfo: 'none',
   mode: 'markers',
   marker: {
   color: 'black',
   size: 4
   }
   };
   Traces.push(tracePoints);
   Plotly.addTraces(el.id, Traces);

   el.on('plotly_selected', function(e) {

observeEvent(data.highlightS, {
   var numSel = e.points.length
   var xSel = [];
   var ySel = [];
   for (a=0; a<numSel; a++){
   xSel.push(e.points[a].x)
   ySel.push(e.points[a].y)
   }

   var trace = {
   x: xSel,
   y: ySel,
   mode: 'markers',
   marker: {
   color: 'red',
   size: 4
   },
   hoverinfo: 'none'
   };
   Traces.push(trace);
   Plotly.addTraces(el.id, Traces);
})
   })

   }
   ", data = list(dat= mtcars, wt=mtcars$wt, mpg=mtcars$mpg, highlightS=highlight())))})

shinyApp(ui, server)

EDIT:

I wanted to include a picture to demonstrate what I am aiming for. Basically, if the user selects the 15 dots shown below, they remain black:

However, if the user selects the "Highlight the selected points" Shiny button, then the 15 dots will become red as shown below:

Body:
Ok, this does what you want I think.

I had to take a different approach since I don't think you can add a plotly el.on event like that, but plotly has actually a Shiny event_data("plotly_selected") construct intended just for this kind of thing - so I used that instead.

The major changes I made:

stored the dataframe we are working with (m) in a reactiveValues so you could access it easily (without using <<-) from inside a reactive node.

added a reactive(event_data(.. to retreive the shiny selection data.

added a selected column to our working dataframe to keep track of what should be marked red.

added a reactive node (mvis) to process the selected data as it comes in and mark the new things as selected. Isolated the node from the reactiveValue event as well with isolate to avoid an endless reaction chain.

got rid of the el.on(plotly_selected because I don't see how that could work (although there is probably a way).

enabled the selection of the markers with a layout(dragmode="select") call

added a second trace one for black markers, one for selected ones

added a key variable so we could keep track of how the plotted markers correspond to our data rows.

and a few other miscellaneous small changes (xArr and yArr were reversed in the original traceBlock definition for example)

added a bootstrap toggle button to highlight the selectionr (as later requested). Note that it requires a double-click to toggle.

So here is the code:

library(plotly)
library(htmlwidgets)
library(shiny)
library(shinyBS)
library(ggplot2)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot"),
  bsButton("high","Highlight Selected Points",type="toggle")
))

server <- shinyServer(function(input, output) {

  m <- mtcars
  m$selected <- 0

  rv <- reactiveValues(m=m,high=FALSE)

  observeEvent(input$high,{req(input$high);rv$high <- !rv$high } )

  ggPS <- reactive(ggplotly(ggplot(m, aes(x = wt, y = mpg))))

  sel <- reactive(event_data("plotly_selected"))

  mvis <- reactive({
    rv$high
    sdatf <- sel()
    print(rv$high)
    isolate({
      rv$m$selected <- 0
      rv$m$selected[ sdatf$key ] <- 1  # now select the ones in sdatf
    })
    #  print(sdatf)  # debugging
    return(rv$m)
  })

  jscode <-
 "function(el, x, data) {
    Traces=[]
    var xArrNrm = [];
    var yArrNrm = [];
    var idxNrm = [];
    var xArrSel = [];
    var yArrSel = [];
    var idxSel = [];
    for (a=0; a<data.mvis.length; a++){
      if(data.mvis[a]['selected']===0){
        xArrNrm.push(data.mvis[a]['wt'])
        yArrNrm.push(data.mvis[a]['mpg'])
        idxNrm.push(a+1)
      } else {
        xArrSel.push(data.mvis[a]['wt'])
        yArrSel.push(data.mvis[a]['mpg'])
        idxSel.push(a+1)
      }
    }
    console.log(data.mvis.length)
    console.log(data)
    var tracePointsNrm = {
      x: xArrNrm,
      y: yArrNrm,
      key: idxNrm,
      hoverinfo: 'none',
      mode: 'markers',
      marker: {
        color: 'black',
        size: 4
      }
    };
    var tracePointsSel = {
      x: xArrSel,
      y: yArrSel,
      key: idxSel,
      hoverinfo: 'none',
      mode: 'markers',
      marker: {
        color: 'red',
        size: 6
      }
    };
    if (!data.high){
       tracePointsSel.marker.color = 'black'
    }
    //   console.log(tracePointsNrm) // debuging
    //   console.log(tracePointsSel)
    Traces.push(tracePointsNrm);
    Traces.push(tracePointsSel);
    Plotly.addTraces(el.id, Traces);
 }"
  output$myPlot <- renderPlotly({
                    ggPS() %>%  onRender(jscode,data=list(mvis=mvis(),high=rv$high)) %>%
                                layout(dragmode = "select")
                    })
})
shinyApp(ui, server)

And here is a screen shot:

Note:

This seems overly complex, and it is. In theory this could be done without using onRender and any javascript, by adding traces with add_marker and setting the key attribute. Unfortunately  there seems to be a plotly bug in the R binding that scrambles the key values after selection when you do it that way. Too bad - it would be much shorter and easier to understand - maybe it will eventually get fixed.


问:
How do I use tensorflow with Visual Studio 2017 preview?
I have Python tools for visual studio 2017. I want to install tensorflow. I have already installed it using CMD with this command

```<code>pip3 install --upgrade tensorflow
</code>```

And the window said the installation as successful. However when I try to use tensorflow in a Python project in VS - the module is not found. What am I doing wrong here?

I found this menu in the solution to install python packages but none of them work for tensorflow and give me this error:

```<code>    ----- Installing 'tensorflow==1.0.1' -----
Collecting tensorflow==1.0.1
  Could not find a version that satisfies the requirement tensorflow==1.0.1 (from versions: )
No matching distribution found for tensorflow==1.0.1
----- Failed to install 'tensorflow==1.0.1' -----
</code>```

答:
The probably easiest way to do it is to first install VS 2017 Preview without Anaconda (uncheck the relevant checkbox before installation).

Then separately install Anaconda 4.2.0, which will bring you Python 3.5.2, on top of which you can install TensorFlow.

Make sure to set as default the new environment "Anaconda 4.2.0" which will appear in the Python Environments tab. Also you will need to hit the refresh  button for the new environment - this will bring the syntax highlight to your project. Note, the refresh may take a few minutes.

Body:
I have Python tools for visual studio 2017. I want to install tensorflow. I have already installed it using CMD with this command

pip3 install --upgrade tensorflow

And the window said the installation as successful. However when I try to use tensorflow in a Python project in VS - the module is not found. What am I doing wrong here?

I found this menu in the solution to install python packages but none of them work for tensorflow and give me this error:

    ----- Installing 'tensorflow==1.0.1' -----
Collecting tensorflow==1.0.1
  Could not find a version that satisfies the requirement tensorflow==1.0.1 (from versions: )
No matching distribution found for tensorflow==1.0.1
----- Failed to install 'tensorflow==1.0.1' -----


问:
Express - Send a page AND custom data to the browser in a single request?
How simultaneously to render a page and transmit my custom data to browser. As i understood it needs to send two layers: first with template and second with JSON data. I want to handle this data by backbone.

As i understood from tutorials express and bb app interact as follows:

res.render send a page to browser

when document.ready trigger jQuery.get to app.get('/post')

app.get('/post', post.allPosts) send data to page

This is three steps and how to do it by one?

```<code>var visitCard = {
  name: 'John Smit',
  phone: '+78503569987'
};

exports.index = function(req, res, next){
  res.render('index');
  res.send({data: visitCard});
};
</code>```

And how i should catch this variable on the page- document.card?

答:
My approach is to send a cookie with the information, and then use it from the client.

server.js

```<code>const visitCard = {
  name: 'John Smit',
  phone: '+78503569987'
};

router.get('/route', (req, res) => {
  res.cookie('data', JSON.stringify(pollsObj));
  res.render('index');
});
</code>```

client.js

```<code>const getCookie = (name) => {
  const value = "; " + document.cookie;
  const parts = value.split("; " + name + "=");
  if (parts.length === 2) return parts.pop().split(";").shift();
};

const deleteCookie = (name) => {
  document.cookie = name + '=; max-age=0;';
};

const parseObjectFromCookie = (cookie) => {
  const decodedCookie = decodeURIComponent(cookie);
  return JSON.parse(decodedCookie);
};

window.onload = () => {
  let dataCookie = getCookie('data');
  deleteCookie('data');

  if (dataCookie) {
    const data = parseObjectFromCookie(dataCookie);
    // work with data. `data` is equal to `visitCard` from the server

  } else {
    // handle data not found
  }
</code>```

Walkthrough

From the server, you send the cookie before rendering the page, so the cookie is available when the page is loaded.

Then, from the client, you get the cookie with the solution I found here and delete it. The content of the cookie is stored in our constant. If the cookie exists, you parse it as an object and use it. Note that inside the parseObjectFromCookie you first have to decode the content, and then parse the JSON to an object.

Notes:

If you're getting the data asynchronously, be careful to send the cookie before rendering. Otherwise, you will get an error because the res.render() ends the response. If the data fetching takes too long, you may use another solution that doesn't hold the rendering that long. An alternative could be to open a socket from the client and send the information that you were holding in the server. See here for that approach.

Probably data is not the best name for a cookie, as you could overwrite something. Use something more meaningful to your purpose.

I didn't find this solution anywhere else. I don't know if using cookies is not recommended for some reason I'm not aware of. I just thought it could work and checked it did, but I haven't used this in production.

Body:
How simultaneously to render a page and transmit my custom data to browser. As i understood it needs to send two layers: first with template and second with JSON data. I want to handle this data by backbone.

As i understood from tutorials express and bb app interact as follows:

res.render send a page to browser

when document.ready trigger jQuery.get to app.get('/post')

app.get('/post', post.allPosts) send data to page

This is three steps and how to do it by one?

var visitCard = {
  name: 'John Smit',
  phone: '+78503569987'
};

exports.index = function(req, res, next){
  res.render('index');
  res.send({data: visitCard});
};

And how i should catch this variable on the page- document.card?

Body:
My approach is to send a cookie with the information, and then use it from the client.

server.js

const visitCard = {
  name: 'John Smit',
  phone: '+78503569987'
};

router.get('/route', (req, res) => {
  res.cookie('data', JSON.stringify(pollsObj));
  res.render('index');
});

client.js

const getCookie = (name) => {
  const value = "; " + document.cookie;
  const parts = value.split("; " + name + "=");
  if (parts.length === 2) return parts.pop().split(";").shift();
};

const deleteCookie = (name) => {
  document.cookie = name + '=; max-age=0;';
};

const parseObjectFromCookie = (cookie) => {
  const decodedCookie = decodeURIComponent(cookie);
  return JSON.parse(decodedCookie);
};

window.onload = () => {
  let dataCookie = getCookie('data');
  deleteCookie('data');

  if (dataCookie) {
    const data = parseObjectFromCookie(dataCookie);
    // work with data. `data` is equal to `visitCard` from the server

  } else {
    // handle data not found
  }

Walkthrough

From the server, you send the cookie before rendering the page, so the cookie is available when the page is loaded.

Then, from the client, you get the cookie with the solution I found here and delete it. The content of the cookie is stored in our constant. If the cookie exists, you parse it as an object and use it. Note that inside the parseObjectFromCookie you first have to decode the content, and then parse the JSON to an object.

Notes:

If you're getting the data asynchronously, be careful to send the cookie before rendering. Otherwise, you will get an error because the res.render() ends the response. If the data fetching takes too long, you may use another solution that doesn't hold the rendering that long. An alternative could be to open a socket from the client and send the information that you were holding in the server. See here for that approach.

Probably data is not the best name for a cookie, as you could overwrite something. Use something more meaningful to your purpose.

I didn't find this solution anywhere else. I don't know if using cookies is not recommended for some reason I'm not aware of. I just thought it could work and checked it did, but I haven't used this in production.


问:
Spatial Clustering - associate cluster attribute (id) to the geometry that is part of the cluster
I'm having certain issues into associate a clustered set of geometries with their own proprieties.

Data

I've a table with a set of geometries,

```<code>buildings {
gid integer,
geom geometry(Multipoligon,4326)
}
</code>```

And I've run the function ST_ClusterWithin with a certain threshold over a the "buildings" table.
From that cluster analysis, I got a table that named "clusters",

```<code>clusters {
cid Integer,
geom geometry(GeometryCollection,4326)
}
</code>```

Question

I would love to extract into a table all geometry with associated its own cluster information.

```<code>clustered_building {
gid Integer
cid Integer
geom geometry(Multipoligon,4326)
}

 gid |    cid     |       geom            |
-----+------------+-----------------------+
  1  |     1      | multypoligon(...)     |
  2  |     1      | multypoligon(...)     |
  3  |     1      | multypoligon(...)     |
  4  |     2      | multypoligon(...)     |
  5  |     3      | multypoligon(...)     |
  6  |     3      | multypoligon(...)     |
</code>```

What I Did (but does not work)

I've been trying using the two function ST_GeometryN / ST_NumGeometries parse each MultyGeometry and extract the information of the cluster with this query that is derived from one of the Standard Example of the ST_Geometry manual page.

```<code>INSERT INTO  clustered_building (cid, c_item , geom)
SELECT sel.cid, n, ST_GeometryN(sel.geom, n) as singlegeom
FROM ( SELECT cid, geom, ST_NumGeometries(geom) as num
       FROM clusters") AS sel
       CROSS JOIN generate_series(1,sel.num) n
WHERE n <= ST_NumGeometries(sel.geom);
</code>```

The query, it takes few seconds if I force to use a series of 10.

```<code>CROSS JOIN generate_series(1,10)
</code>```

But it got stuck when I ask to generate a series according to the number of item in each GeometryCollection.
And also, this query does not allow me to link the single geometry to his own features into the building table because I'm losing the "gid"

could someone please help me,
thanks

Stefano

Body:
I'm having certain issues into associate a clustered set of geometries with their own proprieties.

Data

I've a table with a set of geometries,

buildings {
gid integer,
geom geometry(Multipoligon,4326)
}

And I've run the function ST_ClusterWithin with a certain threshold over a the "buildings" table.
From that cluster analysis, I got a table that named "clusters",

clusters {
cid Integer,
geom geometry(GeometryCollection,4326)
}

Question

I would love to extract into a table all geometry with associated its own cluster information.

clustered_building {
gid Integer
cid Integer
geom geometry(Multipoligon,4326)
}

 gid |    cid     |       geom            |
-----+------------+-----------------------+
  1  |     1      | multypoligon(...)     |
  2  |     1      | multypoligon(...)     |
  3  |     1      | multypoligon(...)     |
  4  |     2      | multypoligon(...)     |
  5  |     3      | multypoligon(...)     |
  6  |     3      | multypoligon(...)     |

What I Did (but does not work)

I've been trying using the two function ST_GeometryN / ST_NumGeometries parse each MultyGeometry and extract the information of the cluster with this query that is derived from one of the Standard Example of the ST_Geometry manual page.

INSERT INTO  clustered_building (cid, c_item , geom)
SELECT sel.cid, n, ST_GeometryN(sel.geom, n) as singlegeom
FROM ( SELECT cid, geom, ST_NumGeometries(geom) as num
       FROM clusters") AS sel
       CROSS JOIN generate_series(1,sel.num) n
WHERE n <= ST_NumGeometries(sel.geom);

The query, it takes few seconds if I force to use a series of 10.

CROSS JOIN generate_series(1,10)

But it got stuck when I ask to generate a series according to the number of item in each GeometryCollection.
And also, this query does not allow me to link the single geometry to his own features into the building table because I'm losing the "gid"

could someone please help me,
thanks

Stefano

Body:
I don't have you data, but using some dummy values, where ids 1, 2 and 3 intersect and 4 and 5, you can do something like the following:

WITH
  temp (id, geom) AS
    (VALUES (1, ST_Buffer(ST_Makepoint(0, 0), 2)),
    (2, ST_Buffer(ST_MakePoint(1, 1), 2)),
    (3, ST_Buffer(ST_MakePoint(2, 2), 2)),
    (4, ST_Buffer(ST_MakePoint(9, 9), 2)),
    (5, ST_Buffer(ST_MakePoint(10, 10), 2))),
  clusters(geom) as
    (SELECT
        ST_Makevalid(
          ST_CollectionExtract(
              unnest(ST_ClusterIntersecting(geom)), 3))
      FROM temp
    )
 SELECT array_agg(temp.id), cl.geom
   FROM clusters cl, temp
  WHERE ST_Intersects(cl.geom, temp.geom)
GROUP BY cl.geom;

If you wrap the final cl.geom is ST_AsText, you will see something like:

{1,2,3}   | MULTIPOLYGON(((2.81905966523328 0.180940334766718,2.66293922460509 -0.111140466039203,2.4142135623731 -0.414213562373094,2.11114046603921 -0.662939224605089,1.81905966523328 -0.819059665233282,1.84775906502257 -0.765366864730179,1.96157056080646 -0.390180644032256,2 0,2 3.08780778723872e-16,2 0,2.39018064403226 0.0384294391935396,2.76536686473018 0.152240934977427,2.81905966523328 0.180940334766718))......

{4,5}     | MULTIPOLYGON(((10.8190596652333 8.18094033476672,10.6629392246051 7.8888595339608,10.4142135623731 7.58578643762691,10.1111404660392 7.33706077539491,9.76536686473018 7.15224093497743,9.39018064403226 7.03842943919354,9 7,8.60981935596775 7.03842943919354,8.23463313526982 7.15224093497743,7.8888595339608 7.33706077539491,7.58578643762691 7.5857864376269,7.33706077539491 7.88885953396079,7.15224093497743 8.23463313526982

where you can see the ids 1,2,3, below to the first multipolygon, and 4,5 the other.

The general idea is you cluster the data, and then you intersect the returned clusters with the original data, using array_agg to group the ids together, so that the returned Multipolygons now contain the original ids.  The use of ST_CollectionExtract with 3 as the second paramter, in conjunction with unnest, which splits the geometry collection returned by ST_ClusterIntersecting back into rows, returns each contiguous cluster as a (Multi)Polygon. The ST_MakeValid is because sometimes when you intersect geometries with other related geometries, such as the original polygons with your clustered polygonss, you get strange rounding effects and GEOS error about non-noded intersections and the like.

I answered a similar question on gis.stackexchange recently that you might find useful.


问:
How to write to remote linux directory
How to expose a directory in remote ubuntu server so that I can read & write to that directory from remote machines.

Actually, I have a web application and I need to write to the AWS EC2 instance's directory and create directories using java program running in another server.

Note: I do not want to run a java program in AWS instance just for writing files.

Thanks in advance

答: I think you can use sftp from Java: https://www.example-code.com/java/sftp.asp or https://kodehelp.com/java-program-for-uploading-file-to-sftp-server</p>

Title: How to write to remote linux directory


问:
Cant redirect output to a file
```<code>tail -f /var/log/kern.log | sed 's/.* //'
</code>```

Gives me the output on the terminal but when i do

```<code> tail -f /var/log/kern.log | sed 's/.* //' >> logfile.txt
</code>```

i cant find anything in the file. From the kernel module i print the names of the executables. For eg if i run ls , kern.log has /bin/ls but with the timestamp etc. So im trying the above to extract only the path and it works as long as i run it without redirecting to an output file, i have also tried tee logfile.txt . Still nothing. Please help.

答: Sorry, but isn't only one ">" to put a content in file?</p>

Title: Cant redirect output to a file

Body:
tail -f /var/log/kern.log | sed 's/.* //'

Gives me the output on the terminal but when i do

 tail -f /var/log/kern.log | sed 's/.* //' >> logfile.txt

i cant find anything in the file. From the kernel module i print the names of the executables. For eg if i run ls , kern.log has /bin/ls but with the timestamp etc. So im trying the above to extract only the path and it works as long as i run it without redirecting to an output file, i have also tried tee logfile.txt . Still nothing. Please help.


问:
Storing and updating config files for my applications with kubernetes
My application uses a config file. How to push updates to it? How  they should be stored for convenient updates? In volumes?

The pipeline for the app is Git -> CI -> deb repo -> docker registry. So the updates to it is just to tell kubernetes to select a new image.

What to do for the config file? Maybe the same chain and then just spin up an container with NFS on it? Also, the app has to be notified about the parameters change via a SIGHUP. How to add that hook?

答:
You can use kubernetes configMaps for configs. Don't bake the configs inside the container image.

You can expose the configs as evironment variable or can be mounted as volumes inside pod.

ConfigMap can be generated from a file as well.

In your case it seems like you are reading from config file which is at specific location so you can use configMap and then mount this configMap at the same location from where your app will read, so you don't need to make any changes in your app.

And when you need to update the config just update the configMap and then the new pods that come up will start reading the config. I don't know how to update the config in running pod, what I have tried is scale up and then scale down.

configMaps: https://kubernetes.io/docs/user-guide/configmap/

HTH


问:
Redirect all traffic to https://www using a .conf file (httpd/Apache2)
I want the following addresses to redirect to https://www.foobar.com :

```<code> - http://www.foobar.com
 - http://foobar.com
 - https://foobar.com
</code>```

I've tried using this but it doesn't work:

etc/httpd/conf.d/ssl_rewrite.conf

```<code>RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

答:
```<code>RedirectMatch permanent ^(.*)$ https://www.foobar.com$1
</code>```

Body:
I want the following addresses to redirect to https://www.foobar.com :

 - http://www.foobar.com
 - http://foobar.com
 - https://foobar.com

I've tried using this but it doesn't work:

etc/httpd/conf.d/ssl_rewrite.conf

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


问:
Concurrency: Processes vs Threads
What are the main advantages of using a model for concurrency based on processes over one
based on threads and in what contexts is the latter appropriate?</p>

答:
In this case Processes are more independent of eachother, while Threads shares some resources e.g. memory. But in a general case Threads are more light-weight than Processes.

Erlang Processes is not the same thing as OS Processes. Erlang Processes are very light-weight and Erlang can have many Erlang Processes within the same OS Thread. See Technically why is processes in Erlang more efficient than OS threads?

Title: Concurrency: Processes vs Threads


问:
Quickblox: Unable to get push Notifications with FCM getting errr 401
I want to implement push notification in app by FCM.
The app is successfully getting FCM pushnotification but when i want to send from Quickblox admin pannel then that give me error like

error_description":"Unable to deliver notification 20860148, received error 401 (Unauthorized, check your App auth_key.)

This is log.json file :-

```<code>{"notification":{"registration_ids":["dA_lOjHQU2M:APA91bHB0zGuoalZoxtdcstBQ0dL0pPJA5HyUaoPVibD2iqnrUA51NLqrrmY5zrTZV7OaP55nUEber9NLkPs_ENkVtHLvbEAcHTrgh8wl_YoNhRsUNdyeIWt0mPDKk0tCDyLssXRuFu8"],"delay_while_idle":false,"data":{"message":"hii tesas","collapse_key":"event12616627"},"priority":"high","time_to_live":86400},"
</code>```

log":[{"device_token":null,"created_at":"2016-12-14T09:56:50Z","delivered_at":null,"failed_at":"2016-12-14T09:56:51Z","error_code":401,"error_description":"Unable to deliver notification 20860148, received error 401 (Unauthorized, check your App auth_key.)"}]}

答:
Because of GCM deprecate now so You are required to put Firebase Cloud Messaging (FCM) API Server key in your Quickblox Push notification panel go to setting and paste FCM Server key in Android-> Develpment or Production. Make sure you put Firebase Server Key there.

Follow these steps to get the server key:

Log into Firebase console https://console.firebase.google.com/
Add your project or select your project if you are already added
now click on setting icon go to project setting -> cloud messaging. there you can find your server key copy that key and paste in

There you should have your Server Key.
Hope this helps!

Body:
I want to implement push notification in app by FCM.
The app is successfully getting FCM pushnotification but when i want to send from Quickblox admin pannel then that give me error like

error_description":"Unable to deliver notification 20860148, received error 401 (Unauthorized, check your App auth_key.)

This is log.json file :-

{"notification":{"registration_ids":["dA_lOjHQU2M:APA91bHB0zGuoalZoxtdcstBQ0dL0pPJA5HyUaoPVibD2iqnrUA51NLqrrmY5zrTZV7OaP55nUEber9NLkPs_ENkVtHLvbEAcHTrgh8wl_YoNhRsUNdyeIWt0mPDKk0tCDyLssXRuFu8"],"delay_while_idle":false,"data":{"message":"hii tesas","collapse_key":"event12616627"},"priority":"high","time_to_live":86400},"

log":[{"device_token":null,"created_at":"2016-12-14T09:56:50Z","delivered_at":null,"failed_at":"2016-12-14T09:56:51Z","error_code":401,"error_description":"Unable to deliver notification 20860148, received error 401 (Unauthorized, check your App auth_key.)"}]}


问:
compiler error: is private within this context
I'm writing a class and when I compile, I get one error message that says, "is private within this context" and another that says, "invalid use of non-static data member".  But if I comment out everything before the addShipment function in my cpp file, it compiles just fine.  Can someone please explain to me what is different to sometimes cause an error and sometimes not, and if the two different types of errors are related.

Product.h:

```<code>#ifndef PRODUCT_H
#define PRODUCT_H

#include <iostream>

class Product {
    public:
        Product(int productID, std::string productName);
        std::string getDescription();
        void setDescription(std::string description);
        std::string getName();
        int getID();
        int getNumberSold();
        double getTotalPaid();
        int getInventoryCount();
        void addShipment(int shipmentQuantity, double shipmentCost);
        void reduceInventory(int purchaseQuantity);
        double getPrice();
    private:
        int productID;
        std::string name;
        std::string description;
        double totalPaid;
        int inventoryCount;
        int numSold;
};

#endif
</code>```

Product.cpp:

```<code>#include <iostream>
#include "Product.h"
using namespace std;

Product::Product(int productID, string productName) {
    Product::productID = productID;
    Product::name = productName;
}

string Product::getDescription() {
    return Product::description;
}

void Product::setDescription(string description) {
    Product::description = description;
}

string Product::getName() {
    return Product::name;
}

int Product::getID() {
    return Product::productID;
}

int Product::getNumberSold() {
    return Product::numSold;
}

double Product::getTotalPaid() {
    if(Product::totalPaid < 1) {
        totalPaid = 0;
    }
    return Product::totalPaid;
}

int Product::getInventoryCount() {
    Product::inventoryCount = 0;
    return Product::inventoryCount;
}

void addShipment(int shipmentQuantity, double shipmentCost) {
    Product::inventoryCount = Product::inventoryCount + shipmentQuantity;
    Product::totalPaid = Product::totalPaid + shipmentCost;
}

void reduceInventory(int purchaseQuantity) {
    Product::inventoryCount = Product::inventoryCount - purchaseQuantity;
    Product::numSold = Product::numSold + purchaseQuantity;
}

double getPrice() {
    int price = (Product::totalPaid / static_cast<double>(Product::inventoryCount + Product::numSold)) * 1.25;
    return price;
}
</code>```

答:
The "private within this context" error refers to the fact that the functions addShipment, reduceInventory and getPrice are not members or friends of the class Product, so they cannot use its private members.

The "invalid use of non-static data member" error refers to the fact that you are trying to access non-static data members by qualifying them using the syntax Class::member, which is how you access static data members, which are shared by all instances of a class. Non-static data members are accessed using the syntax object.member or pointer->member, as separate instances of each data member exist for each instance of a class.

And I assume that you mean the errors disappear if you comment out everything after (and including) the addShipment function, rather than everything before it. This is because both kinds of error refer to code within the non-member functions.

Body:
I'm writing a class and when I compile, I get one error message that says, "is private within this context" and another that says, "invalid use of non-static data member".  But if I comment out everything before the addShipment function in my cpp file, it compiles just fine.  Can someone please explain to me what is different to sometimes cause an error and sometimes not, and if the two different types of errors are related.

Product.h:

#ifndef PRODUCT_H
#define PRODUCT_H

#include <iostream>

class Product {
    public:
        Product(int productID, std::string productName);
        std::string getDescription();
        void setDescription(std::string description);
        std::string getName();
        int getID();
        int getNumberSold();
        double getTotalPaid();
        int getInventoryCount();
        void addShipment(int shipmentQuantity, double shipmentCost);
        void reduceInventory(int purchaseQuantity);
        double getPrice();
    private:
        int productID;
        std::string name;
        std::string description;
        double totalPaid;
        int inventoryCount;
        int numSold;
};

#endif

Product.cpp:

#include <iostream>
#include "Product.h"
using namespace std;

Product::Product(int productID, string productName) {
    Product::productID = productID;
    Product::name = productName;
}

string Product::getDescription() {
    return Product::description;
}

void Product::setDescription(string description) {
    Product::description = description;
}

string Product::getName() {
    return Product::name;
}

int Product::getID() {
    return Product::productID;
}

int Product::getNumberSold() {
    return Product::numSold;
}

double Product::getTotalPaid() {
    if(Product::totalPaid < 1) {
        totalPaid = 0;
    }
    return Product::totalPaid;
}

int Product::getInventoryCount() {
    Product::inventoryCount = 0;
    return Product::inventoryCount;
}

void addShipment(int shipmentQuantity, double shipmentCost) {
    Product::inventoryCount = Product::inventoryCount + shipmentQuantity;
    Product::totalPaid = Product::totalPaid + shipmentCost;
}

void reduceInventory(int purchaseQuantity) {
    Product::inventoryCount = Product::inventoryCount - purchaseQuantity;
    Product::numSold = Product::numSold + purchaseQuantity;
}

double getPrice() {
    int price = (Product::totalPaid / static_cast<double>(Product::inventoryCount + Product::numSold)) * 1.25;
    return price;
}


问:
Unregister uwp background task
I register a background task and I try to unregister it again when a certain setting is deactivated. But I only found information about register and scheduling tasks. Is there no way to this? </p>

答:
is this what you are looking for?</p>

```<code>var tasks = BackgroundTaskRegistration.AllTasks;
            foreach(var task in tasks)
            {
                // You can check here for the name
                string name = task.Value.Name;

                task.Value.Unregister(true);
            }
</code>```

Title: Unregister uwp background task

Body:
is this what you are looking for?

var tasks = BackgroundTaskRegistration.AllTasks;
            foreach(var task in tasks)
            {
                // You can check here for the name
                string name = task.Value.Name;

                task.Value.Unregister(true);
            }


问:
Numpy to reorder such that every nth row from the current row is appended to it
I want to reshape the Numpy array A, not by appending normal next row, but by appending every Nth row that comes after it.

Ex:

```<code>A = [[1  2  3  4]
[5  6  7  8]
[9  10 11 12]
[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]
</code>```

Now, I want to construct an array of size 2x12 like this from A

```<code> A = [[1 2 3 4 9 10 11 12 17 18 19 10]
 [5 6 7 8 13 14 15 16 21 22 23 24]]
</code>```

Here You can see that every 2nd row from the current row is appended to it and formed the new reshaped array.

Body:
I want to reshape the Numpy array A, not by appending normal next row, but by appending every Nth row that comes after it.

Ex:

A = [[1  2  3  4]
[5  6  7  8]
[9  10 11 12]
[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]

Now, I want to construct an array of size 2x12 like this from A

 A = [[1 2 3 4 9 10 11 12 17 18 19 10]
 [5 6 7 8 13 14 15 16 21 22 23 24]]

Here You can see that every 2nd row from the current row is appended to it and formed the new reshaped array.

Body:
How about this approach?

# extract alternative rows starting from 0th row (1st row)
In [18]: A[0::2]
Out[18]:
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12],
       [17, 18, 19, 20]])

# and then flatten to 1D array
In [19]: A[0::2].flatten()
Out[19]: array([ 1,  2,  3,  4,  9, 10, 11, 12, 17, 18, 19, 20])

# extract alternative rows starting from 2nd row
In [17]: A[1::2]
Out[17]:
array([[ 5,  6,  7,  8],
       [13, 14, 15, 16],
       [21, 22, 23, 24]])

# and then flatten to 1D array
In [20]: A[1::2].flatten()
Out[20]: array([ 5,  6,  7,  8, 13, 14, 15, 16, 21, 22, 23, 24])

# to get 2D, just put them in `np.vstack` (in the order you want the final array)
In [21]: np.vstack((A[0::2].flatten(), A[1::2].flatten()))
Out[21]:
array([[ 1,  2,  3,  4,  9, 10, 11, 12, 17, 18, 19, 20],
       [ 5,  6,  7,  8, 13, 14, 15, 16, 21, 22, 23, 24]])