问:
Execute command does not fire in resource dictionary code behind
I have created resource dictionary and code behind file for it.
In XAML I have defined command binding and added Executed handler:

```<code><Button Grid.Row="2" Width="100" >
  <CommandBinding Command="Search" Executed="CommandBinding_Executed" />
</Button>
</code>```

Here is code behind:

```<code>partial class StyleResources : ResourceDictionary {

        public StyleResources() {
            InitializeComponent();
        }
        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
            //this is never executed
        }
    }
</code>```

I don't know why is command not executing when button is clicked, and also, why is button enabled when I didn't set CanExecute to true. I have also tried to set it to true, but CanExecute event didn't fire as well.
Here is how I am using the resource dictionary:

```<code>public partial class MyWindow : Window {
        public MyWindow() {
            InitializeComponent();
            Uri uri = new Uri("/WPFLibs;component/Resources/StyleResources.xaml", UriKind.Relative);
            ResourceDictionary Dict = Application.LoadComponent(uri) as ResourceDictionary;
            this.Style = Dict["WindowTemplate"] as Style;
        }
    }
</code>```

答:
This is not how you bind commands to buttons. It should look something like this:

```<code><Grid>
  <Grid.CommandBindings>
    <CommandBinding Command="Search"
                    Executed="Search_Executed"
                    CanExecute="Search_CanExecute" />
  </Grid.CommandBindings>
  ...
  <Button Grid.Row="2" Width="100" Command="Search" />
  ...
</Grid>
</code>```

And in codebehind:

```<code>private void Search_Executed(object sender, ExecutedRoutedEventArgs e) {
    // do something
}

private void Search_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
    e.CanExecute = ...; // set to true or false
}
</code>```

Body:
I have created resource dictionary and code behind file for it.
In XAML I have defined command binding and added Executed handler:

<Button Grid.Row="2" Width="100" >
  <CommandBinding Command="Search" Executed="CommandBinding_Executed" />
</Button>

Here is code behind:

partial class StyleResources : ResourceDictionary {

        public StyleResources() {
            InitializeComponent();
        }
        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
            //this is never executed
        }
    }

I don't know why is command not executing when button is clicked, and also, why is button enabled when I didn't set CanExecute to true. I have also tried to set it to true, but CanExecute event didn't fire as well.
Here is how I am using the resource dictionary:

public partial class MyWindow : Window {
        public MyWindow() {
            InitializeComponent();
            Uri uri = new Uri("/WPFLibs;component/Resources/StyleResources.xaml", UriKind.Relative);
            ResourceDictionary Dict = Application.LoadComponent(uri) as ResourceDictionary;
            this.Style = Dict["WindowTemplate"] as Style;
        }
    }

Body:
This is not how you bind commands to buttons. It should look something like this:

<Grid>
  <Grid.CommandBindings>
    <CommandBinding Command="Search"
                    Executed="Search_Executed"
                    CanExecute="Search_CanExecute" />
  </Grid.CommandBindings>
  ...
  <Button Grid.Row="2" Width="100" Command="Search" />
  ...
</Grid>

And in codebehind:

private void Search_Executed(object sender, ExecutedRoutedEventArgs e) {
    // do something
}

private void Search_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
    e.CanExecute = ...; // set to true or false
}


来源: stackexchange

问:
Specify custom Date format for colClasses argument in read.table/read.csv

Question:

Is there a way to specify the Date format when using the colClasses argument in read.table/read.csv?

(I realise I can convert after importing, but with many date columns like this, it would be easier to do it in the import step)

Example:

I have a .csv with date columns in the format %d/%m/%Y.

```<code>dataImport <- read.csv("data.csv", colClasses = c("factor","factor","Date"))
</code>```

This gets the conversion wrong. For example, 15/07/2008 becomes 0015-07-20.

Reproducible code:

```<code>data <-
structure(list(func_loc = structure(c(1L, 2L, 3L, 3L, 3L, 3L,
3L, 4L, 4L, 5L), .Label = c("3076WAG0003", "3076WAG0004", "3076WAG0007",
"3076WAG0009", "3076WAG0010"), class = "factor"), order_type = structure(c(3L,
3L, 1L, 1L, 1L, 1L, 2L, 2L, 3L, 1L), .Label = c("PM01", "PM02",
"PM03"), class = "factor"), actual_finish = structure(c(4L, 6L,
1L, 2L, 3L, 7L, 1L, 8L, 1L, 5L), .Label = c("", "11/03/2008",
"14/08/2008", "15/07/2008", "17/03/2008", "19/01/2009", "22/09/2008",
"6/09/2007"), class = "factor")), .Names = c("func_loc", "order_type",
"actual_finish"), row.names = c(NA, 10L), class = "data.frame")

write.csv(data,"data.csv", row.names = F)

dataImport <- read.csv("data.csv")
str(dataImport)
dataImport

dataImport <- read.csv("data.csv", colClasses = c("factor","factor","Date"))
str(dataImport)
dataImport
</code>```

And here's what the output looks like:

答:
A long time ago, in the meantime the problem has been solved by Hadley Wickham. So nowadays the solution is reduced to a oneliner:

```<code>library(readr)
data <- read_csv("data.csv",
                  col_types = cols(actual_finish = col_datetime(format = "%d/%m/%Y")))
</code>```

Maybe we want even to get rid of unnecessary stuff:

```<code>data <- as.data.frame(data)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Question:

Is there a way to specify the Date format when using the colClasses argument in read.table/read.csv?

(I realise I can convert after importing, but with many date columns like this, it would be easier to do it in the import step)

Example:

I have a .csv with date columns in the format %d/%m/%Y.

dataImport <- read.csv("data.csv", colClasses = c("factor","factor","Date"))

This gets the conversion wrong. For example, 15/07/2008 becomes 0015-07-20.

Reproducible code:

data <-
structure(list(func_loc = structure(c(1L, 2L, 3L, 3L, 3L, 3L,
3L, 4L, 4L, 5L), .Label = c("3076WAG0003", "3076WAG0004", "3076WAG0007",
"3076WAG0009", "3076WAG0010"), class = "factor"), order_type = structure(c(3L,
3L, 1L, 1L, 1L, 1L, 2L, 2L, 3L, 1L), .Label = c("PM01", "PM02",
"PM03"), class = "factor"), actual_finish = structure(c(4L, 6L,
1L, 2L, 3L, 7L, 1L, 8L, 1L, 5L), .Label = c("", "11/03/2008",
"14/08/2008", "15/07/2008", "17/03/2008", "19/01/2009", "22/09/2008",
"6/09/2007"), class = "factor")), .Names = c("func_loc", "order_type",
"actual_finish"), row.names = c(NA, 10L), class = "data.frame")

write.csv(data,"data.csv", row.names = F)

dataImport <- read.csv("data.csv")
str(dataImport)
dataImport

dataImport <- read.csv("data.csv", colClasses = c("factor","factor","Date"))
str(dataImport)
dataImport

And here's what the output looks like:

Body:
A long time ago, in the meantime the problem has been solved by Hadley Wickham. So nowadays the solution is reduced to a oneliner:

library(readr)
data <- read_csv("data.csv",
                  col_types = cols(actual_finish = col_datetime(format = "%d/%m/%Y")))

Maybe we want even to get rid of unnecessary stuff:

data <- as.data.frame(data)

ContentLicense: CC BY-SA 4.0


答:
Here's a simple, verbose solution. (I'm sure a much more elegant one is possible):

function newState(oldState){
  // Defines an array to hold our result
  let result = [];
  // Examines each row of the old state separately
  for (let row of oldState){
    // Names the columns a, b, c, & d
    let a = row[0], b = row[1], c = row[2], d = row[3];
    // Checks for match in the rightmost pair
    if(d == c && d != 0){
      d = d * 2; // Combines matching cells
      // Checks for secondary match
      if(b == a && b != 0){
        // Traditional 2048 logic: combines matching cells *into 'c'* & shifts the rest
        c = b * 2; b = 0; a = 0;
        // For the alternative logic requested in a comment by OP,
        //   replace the above line with `c = 0; b = b * 2; a = 0;`
      }
      else{
        c = b; b = a; a = 0; // Shifts the rest
      }
    }
    else{
      // Checks for match in the middle pair
      if(c == b && c != 0){
        c = c * 2; b = a; a = 0; // Combines matching cells and shifts the rest
      }
      else{
        // Checks for match in the leftmost pair
        if(b == a && b != 0){
          b = b * 2; a = 0; // Combines matching cells and shifts the rest
        }
      }
    }
    // Populates the current row in the result matrix
    result.push([a, b, c, d]);
  }
  // Returns the result matrix
  return JSON.stringify(result);
}

console.log(newState([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(newState([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]));
console.log(newState([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]));
console.log(newState([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]));
console.log(newState([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]));```

Title: Do only one move to right in 2048 game

Body:
I have 4x4 matrix like in game 2048, and I need to print result of one move to right. For example we have matrix:

0 0 2 2
4 4 8 4
64 64 8 4
16 8 64 8

Result is:

0 0 0 4
0 8 8 4
0 128 8 4
16 8 64 8

My code:

function solution(x){
  for (let i = 0; i < x.length; i++){
   for (let j = 0; j < x.length; j++){
     if (x[i][j] == x[i][j+1]){
        x[i][j+1] = x[i][j+1] * 2;
        x[i][j] = 0;
      }
   }
  }
  return JSON.stringify(x)
}
console.log(solution([[0,0,2,2], [4,4,8,4], [64,64,8,4], [16,8,64,8]]));
console.log(solution([[2,2,4,8],[8,8,64,64],[64,8,16,8],[8,8,8,8]]))
console.log(solution([[64,64,64,64],[8,8,8,8],[4,4,4,4],[2,2,2,2]]))
console.log(solution([[0,0,4,4],[4,8,4,8],[8,8,8,8],[64,8,16,8]]))
console.log(solution([[2,0,4,4],[4,4,4,4],[8,0,0,8],[0,64,64,64]]))

In the second version I get wrong result on the first row [0,0,0,16], the correct result is [0, 4, 4, 8]


问:
AppCompat Toolbar: Change Overflow Icon Color in ActionMode
With the AppCompat Toolbar, I want to be able to change the color of the overflow menu icon on ActionMode change.

For example, the overflow icon will be white in normal Toolbar mode. And will turn black on ActionMode. So far, I have managed to change the background of the action mode as well as the title text. But I have yet to find a way to change the overflow menu icon color.

I know that there's an answer available:
Change ActionMode Overflow icon

I tried the first solution and I wasn't able to find the overflow icon.

The second solution, even with a 50L delay causes the overflow menu icon to flash the ActionMode's intended color for a brief split second that is very jarring.

答:
```<code><style name="ToolBarTheme" parent="ThemeOverlay.AppCompat.ActionBar">
    <item name="android:tint">@color/colorAccent</item>
</code>```

create the above theme.set tint with your color and add this theme to the toolbar.

```<code><androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ToolBarTheme"/>
</code>```

Body:
<style name="ToolBarTheme" parent="ThemeOverlay.AppCompat.ActionBar">
    <item name="android:tint">@color/colorAccent</item>

create the above theme.set tint with your color and add this theme to the toolbar.

<androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ToolBarTheme"/>


问:
Cannot connect frontend app{Angular} to Backend{SpringBoot} in kubernetes
I am trying to containerize my angular+java app in Kubernetes cluster. I have a frontend deployment and a backend deployment in my k8 cluster. My database is in AWS{RDS}. But i am confused that what API-URL should i give in my Frontend code so that it can get connected to my backend app in k8 cluster.
For e.g :-
In local system i use something like {localhost:8080/api/customers} in my Frontend code but what should i change it to at the time of deploying in Kubernetes cluster.

I have a Kubernetes cluster setup with 1 master and 2 slave nodes, I created a deployment of my backend app and exposed it through Cluster Ip, and than i gave this cluster ip and port in my frontend application.
After that i pushed the image to docker hub and than created a k8 deployment for it, but still its not working.

My main ask is what URL and Port should i mention in my Frontend application target URL so that it can find hit my java APIs.

答:
if your two applications run in the same kubernetes cluster so you would have to call your backend service like this: svcname:port for example

```<code>http://login:8080/login
</code>```

This assuming the pods for your frontend are on the same Kubernetes namespace. If they are on a different namespace you would call something like this:

```<code>http://login.<namespace>.svc.cluster.local:5555/login
</code>```

Body:
if your two applications run in the same kubernetes cluster so you would have to call your backend service like this: svcname:port for example

http://login:8080/login

This assuming the pods for your frontend are on the same Kubernetes namespace. If they are on a different namespace you would call something like this:

http://login.<namespace>.svc.cluster.local:5555/login


问:
Django Emailfield fixed suffix
In my Contact model I use an EmailField to assure I'm saving a valid email address.

In my form however, I only want the user to be able to change the part before the @, the domain part is not user defined. (e.g. every email needs to end with @gmail.com)

I have looked at a lot of questions about modifying Django form field values before and after validation and display phase, but a lot of the answers are kind of 'hacky' or seem to much of a workaround for my case.

Is there some support of kind of a display filter, which manages a fixed prefix/suffix of a Django form field, without having to edit POST values or needing to suppress certain validations?

答:
Use the clean method in your form to validate the email.  It'll be something like this</p>

```<code>def clean(self):
    """Check if valid email for institution."""
    super().clean()
    cleaned_data = self.cleaned_data

    if not '@gmail.com' in cleaned_data['email']
        msg = forms.ValidationError("Your email must be @gmail")
        self.add_error('email', msg)
</code>```

Title: Django Emailfield fixed suffix

Body:
Use the clean method in your form to validate the email.  It'll be something like this

def clean(self):
    """Check if valid email for institution."""
    super().clean()
    cleaned_data = self.cleaned_data

    if not '@gmail.com' in cleaned_data['email']
        msg = forms.ValidationError("Your email must be @gmail")
        self.add_error('email', msg)


问:
How can I retry a Future in Dart/Flutter?
I have a method that does some async processing and want it to retry X times. How can I achieve that in Dart/Flutter?</p>

答:
Use this function:

```<code>typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture) async {
  try {
    return await aFuture();
  } catch (e) {
    if (retries > 1) {
      return retry(retries - 1, aFuture);
    }

    rethrow;
  }
}
</code>```

And to use it:

```<code>main(List<String> arguments) {

  retry(2, doSometing);

}

Future doSometing() async {
  print("Doing something...");
  await Future.delayed(Duration(milliseconds: 500));
  return "Something";
}
</code>```

Body:
Use this function:

typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture) async {
  try {
    return await aFuture();
  } catch (e) {
    if (retries > 1) {
      return retry(retries - 1, aFuture);
    }

    rethrow;
  }
}

And to use it:

main(List<String> arguments) {

  retry(2, doSometing);

}

Future doSometing() async {
  print("Doing something...");
  await Future.delayed(Duration(milliseconds: 500));
  return "Something";
}


问:
Calling internal nodes programmatically on CONNECT platform
When programmatically calling internal nodes on CONNECT platform, should you use the original path or is it okay to just use an alias? This question mainly refers to what the best practice would be, as aliases might introduce additional dependencies and may result in errors in the future.</p>

答:
well it really depends on what you want to do. 'aliasing' basically is a mechanism for dependency injection on CONNECT platform, meaning other packages will be able to replace some nodes with a specific alias silently, so that other nodes depending on that functionality will seamlessly be calling the 'injected' node.

to give an example, if you have something like '/firestore/insert', which is aliased by '/db/insert', then no other package can overwrite '/firestore/insert' path, but they can overwrite the alias on '/db/insert' path. so when you are making your call, if you make it directly to '/firestore/insert', it would definitely do the insert on firestore, while if you are making the call to '/db/insert', it would invoke the insert node on any database backend that is being used.

as a rule of thumb, it is always recommended to make calls to aliases so that you can take full advantage of the dependency injection system. however in some cases you might want finer control, in which case you can make your calls to the original path. in case of a package, this can get pretty tricky, as it might affect the internal workings of your package and you might want to not allow injection into that flow. however, consider the situation, and if it is not the case, i.e. if you can allow other packages to inject nodes into the flow of your package, then make your calls to the aliases. otherwise, make strict calls to the actual paths.


问:
Create Folder that can not accessible by any other application
i want to create a one folder that can not accessible by any other application.

Is it possible to do this ? If yes then give me the solution how to achieve this functionality.

答: Check out Using the Internal Storage to use the storage that is private to your app.</p>


问:
Laravel pass subdomain as a value to another route
now I have this code

```<code>    Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function()
{
    Route::any('/', function($subdomain)
    {
        Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index');
    });
});
</code>```

I want to pass {subdomain} to  Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index'); for when call subdomain.localhost/identifier I call AController@index I should pass the value of subdomain to AController@index

答:
I figured out the answer thanks guys for your help ,
the answer is just call the route inside route::group

```<code>Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function()
{
    Route::any('/{identifier}/{reCreate?}','AController@index');
});
</code>```

and inside Controller function index I can access the value as normal function($subdomain)

Body:
now I have this code

    Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function()
{
    Route::any('/', function($subdomain)
    {
        Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index');
    });
});

I want to pass {subdomain} to  Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index'); for when call subdomain.localhost/identifier I call AController@index I should pass the value of subdomain to AController@index

Body:
I figured out the answer thanks guys for your help ,
the answer is just call the route inside route::group

Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function()
{
    Route::any('/{identifier}/{reCreate?}','AController@index');
});

and inside Controller function index I can access the value as normal function($subdomain)


问:
How to add methods to the object literal being assigned to the variable c, so that the type-checking is satisfied?
How to satisfy the type checking in the code snippet below ? </p>

```<code>interface Counter {
    getCount: () => number
    increment: (n: number) => void
}
let c: Counter = {}
</code>```

答:
Like this</p>

```<code>let c: Counter = {
    getCount: () => 1,
    increment: (n: number) => {}
}
</code>```

Body:
How to satisfy the type checking in the code snippet below ?

interface Counter {
    getCount: () => number
    increment: (n: number) => void
}
let c: Counter = {}

Body:
Like this

let c: Counter = {
    getCount: () => 1,
    increment: (n: number) => {}
}


问:
Accessing 3 dimension array in ionic 3
Here is my JSON file which contains all the data

```<code>{
"item1": [
    {
        "seller": "5b4724b9683087332440d3bd",
        "subject": "Price",
        "id": "5b61c14143ef6a1610695105",
        "user": "5b5772930e74ea36b445659b",
        "message": "High price"
    },
    {
        "seller": "5b4724b9683087332440d3bd",
        "subject": "Customer Service",
        "id": "5b61c2e143ef6a1610695106",
        "user": "5b5772930e74ea36b445659b",
        "message": "Good customer service"
    }
],
"item2": [
    {
        "product": "5b561de369716706c81b4d65",
        "id": "5b5c801b0b7302174c135c69",
        "user": "5b5772930e74ea36b445659b",
        "message": "Good product with a high quality display"
    }
]
</code>```

From the provider, I'm getting data from the API by calling the get method as follow. It's working properly

```<code> getCustomerFeedbackByID(cid) {
return new Promise(resolve => {
  this.http.get(this.postapiUrl + '/user/' + cid + '/feedbacks').subscribe(data => {
    resolve(data);
  }, err => {
    console.log(err);
  });
});
</code>```

then I wrote a function to access the data inside the JSON file. For certain depth, it read the data. But I cannot get the seller name and other attributes

getCustomerFeedback() {

```<code>this.cust.getCustomerFeedbackByID(this.custID)

  .then(data => {
    this.custFeedback.push(data);
    console.log("feedbacks:" + this.custFeedback)

    this.custFeedback.forEach(element => {

      this.feedback.push(element.item1)

      console.log("element seller:" + element.seller);

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

}

As the output of console.log("element seller:"+element.seller) it give me as Undefine

Please, someone, help with this to get the values of this JSON file to display in the ionic 3 mobile app

答:
First you have to access the path to the feedback array such as

```<code> this.custFeedback.forEach(element => {

         this.feedback.push(element.item1)
     });
</code>```

then feedback array has the item1 element. So you can access that array to get the seller details as

```<code>    this.feedback.forEach(data =>{

         console.log("element seller:" + data['seller']);

     });
</code>```

Title: Accessing 3 dimension array in ionic 3

Body:
Here is my JSON file which contains all the data

{
"item1": [
    {
        "seller": "5b4724b9683087332440d3bd",
        "subject": "Price",
        "id": "5b61c14143ef6a1610695105",
        "user": "5b5772930e74ea36b445659b",
        "message": "High price"
    },
    {
        "seller": "5b4724b9683087332440d3bd",
        "subject": "Customer Service",
        "id": "5b61c2e143ef6a1610695106",
        "user": "5b5772930e74ea36b445659b",
        "message": "Good customer service"
    }
],
"item2": [
    {
        "product": "5b561de369716706c81b4d65",
        "id": "5b5c801b0b7302174c135c69",
        "user": "5b5772930e74ea36b445659b",
        "message": "Good product with a high quality display"
    }
]

From the provider, I'm getting data from the API by calling the get method as follow. It's working properly

 getCustomerFeedbackByID(cid) {
return new Promise(resolve => {
  this.http.get(this.postapiUrl + '/user/' + cid + '/feedbacks').subscribe(data => {
    resolve(data);
  }, err => {
    console.log(err);
  });
});

then I wrote a function to access the data inside the JSON file. For certain depth, it read the data. But I cannot get the seller name and other attributes

getCustomerFeedback() {

this.cust.getCustomerFeedbackByID(this.custID)

  .then(data => {
    this.custFeedback.push(data);
    console.log("feedbacks:" + this.custFeedback)

    this.custFeedback.forEach(element => {

      this.feedback.push(element.item1)

      console.log("element seller:" + element.seller);

    });
  })

}

As the output of console.log("element seller:"+element.seller) it give me as Undefine

Please, someone, help with this to get the values of this JSON file to display in the ionic 3 mobile app

Body:
First you have to access the path to the feedback array such as

 this.custFeedback.forEach(element => {

         this.feedback.push(element.item1)
     });

then feedback array has the item1 element. So you can access that array to get the seller details as

    this.feedback.forEach(data =>{

         console.log("element seller:" + data['seller']);

     });


问:
wijmo grid - convert rows to columns and columns to rows in wijmo grid
I am using wijmo grid in my angular4 application. The problem is that while converting rows to columns and columns to rows in wijmo grid. How can I achieve transpose of wijmo grid..?

```<code>  data = this.getData();
  getData() {
    let countries = 'US,Germany,UK,Japan,Italy,Greece'.split(','),
    data = [];
    for (let i = 0; i < countries.length; i++) {
      data.push({
        country: countries[i],
        sales: Math.random() * 10000,
        expenses: Math.random() * 5000,
        downloads: Math.round(Math.random() * 20000)
      });
    }
    return new CollectionView(data);
  }
</code>```

HTML:

```<code> <wj-flex-grid [itemsSource]="data">
 </wj-flex-grid>
</code>```

答:
On various requests from the Wijmo users, Wijmo team created a demo sample for transposed view of FlexGrid. Please refer to the following demo fiddle sample for reference:
Codehttps://jsfiddle.net/Wijmo5/tce6ro57/

Body:
I am using wijmo grid in my angular4 application. The problem is that while converting rows to columns and columns to rows in wijmo grid. How can I achieve transpose of wijmo grid..?

  data = this.getData();
  getData() {
    let countries = 'US,Germany,UK,Japan,Italy,Greece'.split(','),
    data = [];
    for (let i = 0; i < countries.length; i++) {
      data.push({
        country: countries[i],
        sales: Math.random() * 10000,
        expenses: Math.random() * 5000,
        downloads: Math.round(Math.random() * 20000)
      });
    }
    return new CollectionView(data);
  }

HTML:

 <wj-flex-grid [itemsSource]="data">
 </wj-flex-grid>


答:
On the SD card (without a rooted phone) you can't create a folder which is only accessible by your application.

But everything you write to your "internal storage" is only accessible by your application.
see http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Title: Create Folder that can not accessible by any other application

Body:
i want to create a one folder that can not accessible by any other application.

Is it possible to do this ? If yes then give me the solution how to achieve this functionality.


问:
Searching for numbers in a comma separated string in a dataframe in python
df1:

```<code>id, Name, Lastname, Account, ProofID1, ProofID2, transaction_codes_history
1,  ab1,  dc1,      312,     1224,     111,      0, 1.3, 2.1, 3, 4.1, 9.1, 1.1, 7.2
2,  ab2,  dc2,      434,     1225,     112,      0, 1.2, 2.1, 1.4, 3, 4.4, 12.2
3,  ab3,  dc3,      578,     1226,     111,      0, 1.2, 2.1, 1.4, 3, 4.2, 12.1
4,  ab4,  dc4,      624,     1227,     112,      0, 1.1, 7.2
5,  ab5,  dc5,      684,     1228,     113,      0, 1.3, 2.1, 3, 9.2, 11.2
</code>```

I am trying to copy specific columns according to their transaction_codes_history.

If transaction_codes_history contains at least 4.1 or 7.2 or 1.1, then we will copy those columns into a dataframe.

transaction_codes_history is a comma separated string of float numbers.

Expected output:

```<code>Name, Account, ProofID1, ProofID2
ab1,  312,     1224,     111
ab3,  578,     1225,     111
ab4,  624,     1227,     112
</code>```

答:
You can do it by creating additionnal columns like:

```<code>df["to_keep"] = df["transaction_codes_history"].str.contains("1.1|4.1|7.2", regex=True)
</code>```

then you can keep only the rows you want :

```<code>df[df["to_keep"]][["id", "Name", "Lastname", "Account"]]
</code>```

I hope it helps,
Nicolas

Body:
df1:

id, Name, Lastname, Account, ProofID1, ProofID2, transaction_codes_history
1,  ab1,  dc1,      312,     1224,     111,      0, 1.3, 2.1, 3, 4.1, 9.1, 1.1, 7.2
2,  ab2,  dc2,      434,     1225,     112,      0, 1.2, 2.1, 1.4, 3, 4.4, 12.2
3,  ab3,  dc3,      578,     1226,     111,      0, 1.2, 2.1, 1.4, 3, 4.2, 12.1
4,  ab4,  dc4,      624,     1227,     112,      0, 1.1, 7.2
5,  ab5,  dc5,      684,     1228,     113,      0, 1.3, 2.1, 3, 9.2, 11.2

I am trying to copy specific columns according to their transaction_codes_history.

If transaction_codes_history contains at least 4.1 or 7.2 or 1.1, then we will copy those columns into a dataframe.

transaction_codes_history is a comma separated string of float numbers.

Expected output:

Name, Account, ProofID1, ProofID2
ab1,  312,     1224,     111
ab3,  578,     1225,     111
ab4,  624,     1227,     112

Body:
You can do it by creating additionnal columns like:

df["to_keep"] = df["transaction_codes_history"].str.contains("1.1|4.1|7.2", regex=True)

then you can keep only the rows you want :

df[df["to_keep"]][["id", "Name", "Lastname", "Account"]]

I hope it helps,
Nicolas


问:
Create a template that shuffles a dynamic array of objects
So I need to create a template function that shuffles a dynamic array of dynamic objects. The exercise is guiding me a bit by giving me a starting point.

```<code>#include<iostream>

using namespace std;

template < class X > void shuffle(X ** myArray, int myArraySize) {
  // TODO: Implement here the shuffle algorithm
}
</code>```

I'm kinda lost on how I should use the pointer inside the function but have a general idea on how the code should be. I know it has a lot of mistakes but it's just an idea.

```<code>for (int i = myArraySize - 1; i > 0; i--) {
  int index = //a random index in the span [0,i]
  int a = myArray[index];

  myArray[index] = myArray[i];
  myArray[i] = a;
}
</code>```

答:
Do you mean something like this?</p>

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

template< class T >
void shuffle(T* myArray, int myArraySize){
    int index;
    T temp;
    for (int i = myArraySize - 1; i > 0; i--) {
        index = rand() % myArraySize;

        temp = myArray[index];
        myArray[index] = myArray[i];
        myArray[i] = temp;
    }
}

int main(){
    int* ints = new int[10];

    for(int i=0; i<10; i++){
        ints[i] = i+1;
    }
    for(int i=0; i<10; i++){
        cout << ints[i] << "-";
    }
    cout << " Before Shuffle" << endl;

    shuffle<int>(ints, 10);

    for(int i=0; i<10; i++){
        cout << ints[i] << "-";
    }
    cout << " After Shuffle" << endl;
}
</code>```

Body:
So I need to create a template function that shuffles a dynamic array of dynamic objects. The exercise is guiding me a bit by giving me a starting point.

#include<iostream>

using namespace std;

template < class X > void shuffle(X ** myArray, int myArraySize) {
  // TODO: Implement here the shuffle algorithm
}

I'm kinda lost on how I should use the pointer inside the function but have a general idea on how the code should be. I know it has a lot of mistakes but it's just an idea.

for (int i = myArraySize - 1; i > 0; i--) {
  int index = //a random index in the span [0,i]
  int a = myArray[index];

  myArray[index] = myArray[i];
  myArray[i] = a;
}

Body:
Do you mean something like this?

#include <iostream>
#include <stdlib.h>
using namespace std;

template< class T >
void shuffle(T* myArray, int myArraySize){
    int index;
    T temp;
    for (int i = myArraySize - 1; i > 0; i--) {
        index = rand() % myArraySize;

        temp = myArray[index];
        myArray[index] = myArray[i];
        myArray[i] = temp;
    }
}

int main(){
    int* ints = new int[10];

    for(int i=0; i<10; i++){
        ints[i] = i+1;
    }
    for(int i=0; i<10; i++){
        cout << ints[i] << "-";
    }
    cout << " Before Shuffle" << endl;

    shuffle<int>(ints, 10);

    for(int i=0; i<10; i++){
        cout << ints[i] << "-";
    }
    cout << " After Shuffle" << endl;
}


问:
How to query multiple databases in the same select query in clickhouse database?
I have a clickhouse database. It contains multiple databases. The tables inside the databases are identical.

For example DB1 has the table "Table1", DB2 also has the table "Table1" (Here the databases are different, Tables are also different but they have identical schema and contain similar type of information).

Is there a way that i can write a query to get the information from all the different tables from all the different databases optimally? Currently i am querying each table individually and doing an Union among them.

答:
I would propose to create one more DB:

```<code>create database <your_db_name> on cluster <your_cluster_name>;
</code>```

Then create a Merge table for each of you existing DB:

```<code>CREATE TABLE <your_db_name>.<merge_table_name> On cluster <your_cluster_name> (<fields list you need to deal with>)  ENGINE=Merge(<existing_db_name>, '<regex>');
</code>```

Create a View for each of the Merge tables (using a view you can execute any aggregate functions, group by and etc.):

```<code>CREATE VIEW <your_db_name>.view_<merge_table_name> on cluster <your_cluster_name> (<list of fields>) AS SELECT <list of fields> FROM <your_db_name>.<merge_table_name>;
</code>```

Finally create a "result" Merge table that combines all the views newly created:

```<code>CREATE TABLE <your_db_name>.<result_table_name> on cluster <your_cluster_name> (<list of fields>)  ENGINE=Merge(<your_db_name>, '<regex>');
</code>```

Name the tables and views in such a way that your regular expression matches all you need and make sure you avoid loops.

Body:
I would propose to create one more DB:

create database <your_db_name> on cluster <your_cluster_name>;

Then create a Merge table for each of you existing DB:

CREATE TABLE <your_db_name>.<merge_table_name> On cluster <your_cluster_name> (<fields list you need to deal with>)  ENGINE=Merge(<existing_db_name>, '<regex>');

Create a View for each of the Merge tables (using a view you can execute any aggregate functions, group by and etc.):

CREATE VIEW <your_db_name>.view_<merge_table_name> on cluster <your_cluster_name> (<list of fields>) AS SELECT <list of fields> FROM <your_db_name>.<merge_table_name>;

Finally create a "result" Merge table that combines all the views newly created:

CREATE TABLE <your_db_name>.<result_table_name> on cluster <your_cluster_name> (<list of fields>)  ENGINE=Merge(<your_db_name>, '<regex>');

Name the tables and views in such a way that your regular expression matches all you need and make sure you avoid loops.


问:
Program not working as well - C
The following code gives me a zero value for 'count' all the time...

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

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}
</code>```

Thanks !

答:
You cant change a constant, so int const count = 0; can't be modified by const++;, to solve it you just have to remove the const keyword:

```<code> int count = 0;
</code>```

Title: Program not working as well - C

Body:
The following code gives me a zero value for 'count' all the time...

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

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}

Thanks !

Body:
You cant change a constant, so int const count = 0; can't be modified by const++;, to solve it you just have to remove the const keyword:

 int count = 0;


问:
How to fix "ReferenceError: primordials is not defined" in Node.js
I have installed Node.js modules by 'npm install', and then I tried to do gulp sass-watch in a command prompt. After that, I got the below response.

[18:18:32] Requiring external module babel-register
fs.js:27
const { Math, Object, Reflect } = primordials;
                                  ^

ReferenceError: primordials is not defined
```
<p>I have tried this before <code>gulp sass-watch</code>:</p>
<pre class="lang-none prettyprint-override"><code>npm -g install gulp-cli
</code>```

答:
Using NVM to manage what Node.js version you're using, running the following commands worked for me:

cd /to/your/project/
nvm install lts/dubnium
nvm use lts/dubnium
yarn upgrade # or `npm install`
```

Body:
I have installed Node.js modules by 'npm install', and then I tried to do gulp sass-watch in a command prompt. After that, I got the below response.

[18:18:32] Requiring external module babel-register
fs.js:27
const { Math, Object, Reflect } = primordials;
                                  ^

ReferenceError: primordials is not defined

I have tried this before gulp sass-watch:

npm -g install gulp-cli


问:
Firejail+Apparmor change profile from firejail-default
i recently installed Firejail on my Ubuntu.
It says it has an Apparmor support, which i am already using.

After the setup of Firejail, i made some profile files in Firejail.

When i run firejail --apparmor firefox, Firejail loads the certain profile of firefox.

But Apparmor is loading the firejail-default profile.

Is there a way to tell apparmor to load my old already existing apparmor-profile of firefox instead of firejail-default.

So that both are loading their firefox profile, not only one of them.

Thanks :)

答: I'm afraid you have to patch it.</p>

Body: I'm afraid you have to patch it.


问:
How to write unix regular expression to select for specific files in a cp for-loop
I've got a directory with a bunch of files. Instead of describing the filenames and extensions, I'll just show you what is in the directory:

```<code>P01_1.atag  P03_3.tgt   P05_6.src   P08_3.atag  P10_5.tgt
P01_1.src   P03_4.atag  P05_6.tgt   P08_3.src   P10_6.atag
P01_1.tgt   P03_4.src   P06_1.atag  P08_3.tgt   P10_6.src
P01_2.atag  P03_4.tgt   P06_1.src   P08_4.atag  P10_6.tgt
P01_2.src   P03_5.atag  P06_1.tgt   P08_4.src   P11_1.atag
P01_2.tgt   P03_5.src   P06_2.atag  P08_4.tgt   P11_1.src
P01_3.atag  P03_5.tgt   P06_2.src   P08_5.atag  P11_1.tgt
P01_3.src   P03_6.atag  P06_2.tgt   P08_5.src   P11_2.atag
P01_3.tgt   P03_6.src   P06_3.atag  P08_5.tgt   P11_2.src
P01_4.atag  P03_6.tgt   P06_3.src   P08_6.atag  P11_2.tgt
P01_4.src   P04_1.atag  P06_3.tgt   P08_6.src   P11_3.atag
P01_4.tgt   P04_1.src   P06_4.atag  P08_6.tgt   P11_3.src
P01_5.atag  P04_1.tgt   P06_4.src   P09_1.atag  P11_3.tgt
P01_5.src   P04_2.atag  P06_4.tgt   P09_1.src   P11_4.atag
P01_5.tgt   P04_2.src   P06_5.atag  P09_1.tgt   P11_4.src
P01_6.atag  P04_2.tgt   P06_5.src   P09_2.atag  P11_4.tgt
P01_6.src   P04_3.atag  P06_5.tgt   P09_2.src   P11_5.atag
P01_6.tgt   P04_3.src   P06_6.atag  P09_2.tgt   P11_5.src
P02_1.atag  P04_3.tgt   P06_6.src   P09_3.atag  P11_5.tgt
P02_1.src   P04_4.atag  P06_6.tgt   P09_3.src   P11_6.atag
P02_1.tgt   P04_4.src   P07_1.atag  P09_3.tgt   P11_6.src
P02_2.atag  P04_4.tgt   P07_1.src   P09_4.atag  P11_6.tgt
P02_2.src   P04_5.atag  P07_1.tgt   P09_4.src   P12_1.atag
P02_2.tgt   P04_5.src   P07_2.atag  P09_4.tgt   P12_1.src
P02_3.atag  P04_5.tgt   P07_2.src   P09_5.atag  P12_1.tgt
P02_3.src   P04_6.atag  P07_2.tgt   P09_5.src   P12_2.atag
P02_3.tgt   P04_6.src   P07_3.atag  P09_5.tgt   P12_2.src
P02_4.atag  P04_6.tgt   P07_3.src   P09_6.atag  P12_2.tgt
P02_4.src   P05_1.atag  P07_3.tgt   P09_6.src   P12_3.atag
P02_4.tgt   P05_1.src   P07_4.atag  P09_6.tgt   P12_3.src
P02_5.atag  P05_1.tgt   P07_4.src   P10_1.atag  P12_3.tgt
P02_5.src   P05_2.atag  P07_4.tgt   P10_1.src   P12_4.atag
P02_5.tgt   P05_2.src   P07_5.atag  P10_1.tgt   P12_4.src
P02_6.atag  P05_2.tgt   P07_5.src   P10_2.atag  P12_4.tgt
P02_6.src   P05_3.atag  P07_5.tgt   P10_2.src   P12_5.atag
P02_6.tgt   P05_3.src   P07_6.atag  P10_2.tgt   P12_5.src
P03_1.atag  P05_3.tgt   P07_6.src   P10_3.atag  P12_5.tgt
P03_1.src   P05_4.atag  P07_6.tgt   P10_3.src   P12_6.atag
P03_1.tgt   P05_4.src   P08_1.atag  P10_3.tgt   P12_6.src
P03_2.atag  P05_4.tgt   P08_1.src   P10_4.atag  P12_6.tgt
P03_2.src   P05_5.atag  P08_1.tgt   P10_4.src
P03_2.tgt   P05_5.src   P08_2.atag  P10_4.tgt
P03_3.atag  P05_5.tgt   P08_2.src   P10_5.atag
P03_3.src   P05_6.atag  P08_2.tgt   P10_5.src
</code>```

I have a file that is just outside of this directory that I need to copy to all of the files that end with "_1.src" inside the directory.

I'm working with unix in the Terminal app, so I tried writing this for loop, but it rejected my regular expression:

```<code>for .*1.src in ./
> do
> cp ../1.src
> done
</code>```

I've only written regular expressions in Python before and have minimal experience, but I was under the impression that .* would match any combination of characters. However, I got the following error message:

```<code>-bash: `.*1.src': not a valid identifier
</code>```

I then tried the same for loop with the following regular expression:

```<code>^[a-zA-Z0-9_]*1.src$
</code>```

But I got the same error message:

```<code>-bash: `^[a-zA-Z0-9_]*1.src$': not a valid identifier
</code>```

I tried the same regular expression with and without quotation marks, but it always gives the same 'not a valid identifier' error message.

答:
Apparently, my previous answer didn't work. But this seems to:

```<code>$ for x in `echo ./P[01][012]_1.src`; do echo "$x"; done
./P01_1.src
./P02_1.src
</code>```

So, when you run this echo alone, this pattern gets expanded into many names:

```<code>$ echo ./P[01][012]_1.src  # note that the 'regex' is not enclosed in quotes
./P01_1.src ./P02_1.src
</code>```

And then you can iterate over these names in a loop.

BTW, as noted in the comments, you don't even need that echo, so you can plug the pattern right into the loop:

```<code>for x in ./P[01][012]_1.src; do echo "$x"; done
</code>```

Body:
I've got a directory with a bunch of files. Instead of describing the filenames and extensions, I'll just show you what is in the directory:

P01_1.atag  P03_3.tgt   P05_6.src   P08_3.atag  P10_5.tgt
P01_1.src   P03_4.atag  P05_6.tgt   P08_3.src   P10_6.atag
P01_1.tgt   P03_4.src   P06_1.atag  P08_3.tgt   P10_6.src
P01_2.atag  P03_4.tgt   P06_1.src   P08_4.atag  P10_6.tgt
P01_2.src   P03_5.atag  P06_1.tgt   P08_4.src   P11_1.atag
P01_2.tgt   P03_5.src   P06_2.atag  P08_4.tgt   P11_1.src
P01_3.atag  P03_5.tgt   P06_2.src   P08_5.atag  P11_1.tgt
P01_3.src   P03_6.atag  P06_2.tgt   P08_5.src   P11_2.atag
P01_3.tgt   P03_6.src   P06_3.atag  P08_5.tgt   P11_2.src
P01_4.atag  P03_6.tgt   P06_3.src   P08_6.atag  P11_2.tgt
P01_4.src   P04_1.atag  P06_3.tgt   P08_6.src   P11_3.atag
P01_4.tgt   P04_1.src   P06_4.atag  P08_6.tgt   P11_3.src
P01_5.atag  P04_1.tgt   P06_4.src   P09_1.atag  P11_3.tgt
P01_5.src   P04_2.atag  P06_4.tgt   P09_1.src   P11_4.atag
P01_5.tgt   P04_2.src   P06_5.atag  P09_1.tgt   P11_4.src
P01_6.atag  P04_2.tgt   P06_5.src   P09_2.atag  P11_4.tgt
P01_6.src   P04_3.atag  P06_5.tgt   P09_2.src   P11_5.atag
P01_6.tgt   P04_3.src   P06_6.atag  P09_2.tgt   P11_5.src
P02_1.atag  P04_3.tgt   P06_6.src   P09_3.atag  P11_5.tgt
P02_1.src   P04_4.atag  P06_6.tgt   P09_3.src   P11_6.atag
P02_1.tgt   P04_4.src   P07_1.atag  P09_3.tgt   P11_6.src
P02_2.atag  P04_4.tgt   P07_1.src   P09_4.atag  P11_6.tgt
P02_2.src   P04_5.atag  P07_1.tgt   P09_4.src   P12_1.atag
P02_2.tgt   P04_5.src   P07_2.atag  P09_4.tgt   P12_1.src
P02_3.atag  P04_5.tgt   P07_2.src   P09_5.atag  P12_1.tgt
P02_3.src   P04_6.atag  P07_2.tgt   P09_5.src   P12_2.atag
P02_3.tgt   P04_6.src   P07_3.atag  P09_5.tgt   P12_2.src
P02_4.atag  P04_6.tgt   P07_3.src   P09_6.atag  P12_2.tgt
P02_4.src   P05_1.atag  P07_3.tgt   P09_6.src   P12_3.atag
P02_4.tgt   P05_1.src   P07_4.atag  P09_6.tgt   P12_3.src
P02_5.atag  P05_1.tgt   P07_4.src   P10_1.atag  P12_3.tgt
P02_5.src   P05_2.atag  P07_4.tgt   P10_1.src   P12_4.atag
P02_5.tgt   P05_2.src   P07_5.atag  P10_1.tgt   P12_4.src
P02_6.atag  P05_2.tgt   P07_5.src   P10_2.atag  P12_4.tgt
P02_6.src   P05_3.atag  P07_5.tgt   P10_2.src   P12_5.atag
P02_6.tgt   P05_3.src   P07_6.atag  P10_2.tgt   P12_5.src
P03_1.atag  P05_3.tgt   P07_6.src   P10_3.atag  P12_5.tgt
P03_1.src   P05_4.atag  P07_6.tgt   P10_3.src   P12_6.atag
P03_1.tgt   P05_4.src   P08_1.atag  P10_3.tgt   P12_6.src
P03_2.atag  P05_4.tgt   P08_1.src   P10_4.atag  P12_6.tgt
P03_2.src   P05_5.atag  P08_1.tgt   P10_4.src
P03_2.tgt   P05_5.src   P08_2.atag  P10_4.tgt
P03_3.atag  P05_5.tgt   P08_2.src   P10_5.atag
P03_3.src   P05_6.atag  P08_2.tgt   P10_5.src

I have a file that is just outside of this directory that I need to copy to all of the files that end with "_1.src" inside the directory.

I'm working with unix in the Terminal app, so I tried writing this for loop, but it rejected my regular expression:

for .*1.src in ./
> do
> cp ../1.src
> done

I've only written regular expressions in Python before and have minimal experience, but I was under the impression that .* would match any combination of characters. However, I got the following error message:

-bash: `.*1.src': not a valid identifier

I then tried the same for loop with the following regular expression:

^[a-zA-Z0-9_]*1.src$

But I got the same error message:

-bash: `^[a-zA-Z0-9_]*1.src$': not a valid identifier

I tried the same regular expression with and without quotation marks, but it always gives the same 'not a valid identifier' error message.

Body:
Apparently, my previous answer didn't work. But this seems to:

$ for x in `echo ./P[01][012]_1.src`; do echo "$x"; done
./P01_1.src
./P02_1.src

So, when you run this echo alone, this pattern gets expanded into many names:

$ echo ./P[01][012]_1.src  # note that the 'regex' is not enclosed in quotes
./P01_1.src ./P02_1.src

And then you can iterate over these names in a loop.

BTW, as noted in the comments, you don't even need that echo, so you can plug the pattern right into the loop:

for x in ./P[01][012]_1.src; do echo "$x"; done


问:
How to modify macro LLVMToolchainPrebuiltRoot in VS2017?
When I compile my Android native library within VS 2017, here is what it displays:

```<code>1>------ Rebuild All started: Project: MyNativeAndroid, Configuration: Debug x86 ------
1>ANDROID_HOME=C:\ProgramData\Microsoft\AndroidSDK\25
1>ANT_HOME=C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Apps\apache-ant-1.9.3
1>JAVA_HOME=C:\Program Files\Java\jdk1.8.0_161
1>NDK_ROOT=C:\\Microsoft\AndroidNDK64\android-ndk-r13b
</code>```

None of these variables are defined in my system environment.

I need to update NDK_ROOT to be set to C:\Microsoft\AndroidNDK64\android-ndk-17b.

It appears I need to update a global macro $(LLVMToolchainPrebuiltRoot) for this purpose.  This macro is also being used by C++ include path.

How does one modify this macro?

答:
You can modifiy part of the $(LLVMToolchainPrebuiltRoot), macro by setting the ndk path (which is what you want in your case), by going to:

Tools->Options->Cross Platform->C++->Android

Then change the Android NDK path to your ndk path (in your case: C:\Microsoft\AndroidNDK64\android-ndk-17b)

Body:
When I compile my Android native library within VS 2017, here is what it displays:

1>------ Rebuild All started: Project: MyNativeAndroid, Configuration: Debug x86 ------
1>ANDROID_HOME=C:\ProgramData\Microsoft\AndroidSDK\25
1>ANT_HOME=C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Apps\apache-ant-1.9.3
1>JAVA_HOME=C:\Program Files\Java\jdk1.8.0_161
1>NDK_ROOT=C:\\Microsoft\AndroidNDK64\android-ndk-r13b

None of these variables are defined in my system environment.

I need to update NDK_ROOT to be set to C:\Microsoft\AndroidNDK64\android-ndk-17b.

It appears I need to update a global macro $(LLVMToolchainPrebuiltRoot) for this purpose.  This macro is also being used by C++ include path.

How does one modify this macro?


问:
How to calculate R-squared after using bagging function to develop CART decision trees?
I am using the following bagging function with ipred to bootstrap the sample 500 times in R in order to develop decision trees:

```<code>baggedsample <- bagging(p ~., data, nbagg=500, coob=TRUE, control = list
(minbucket=5))
</code>```

After this, I would like to know the R-squared.

I notice that if I do the bagging with caret function, R-squared would be automatically calculated as follows:

```<code># Specify 10-fold cross validation
ctrl <- trainControl(method = "cv",  number = 10)

# CV bagged model
baggedsample <- train(
  p ~ .,
  data,
  method = "treebag",
  trControl = ctrl,
  importance = TRUE
  )

# assess results
baggedsample

RMSE      Rsquared   MAE
##   36477.25  0.7001783  24059.85
</code>```

Appreciate any guidance on this issue, thanks.

答:
Since you do not provide any data, I will illustrate using the built-in iris data.

You can simply compute R-squared from the formula.

```<code>attach(iris)
BAG = bagging(Sepal.Length ~ ., data=iris)
R2 = 1 - sum((Sepal.Length - predict(BAG))^2) /
    sum((Sepal.Length - mean(Sepal.Length))^2)
R2
[1] 0.824782
</code>```

Body:
I am using the following bagging function with ipred to bootstrap the sample 500 times in R in order to develop decision trees:

baggedsample <- bagging(p ~., data, nbagg=500, coob=TRUE, control = list
(minbucket=5))

After this, I would like to know the R-squared.

I notice that if I do the bagging with caret function, R-squared would be automatically calculated as follows:

# Specify 10-fold cross validation
ctrl <- trainControl(method = "cv",  number = 10)

# CV bagged model
baggedsample <- train(
  p ~ .,
  data,
  method = "treebag",
  trControl = ctrl,
  importance = TRUE
  )

# assess results
baggedsample

RMSE      Rsquared   MAE
##   36477.25  0.7001783  24059.85

Appreciate any guidance on this issue, thanks.

Body:
Since you do not provide any data, I will illustrate using the built-in iris data.

You can simply compute R-squared from the formula.

attach(iris)
BAG = bagging(Sepal.Length ~ ., data=iris)
R2 = 1 - sum((Sepal.Length - predict(BAG))^2) /
    sum((Sepal.Length - mean(Sepal.Length))^2)
R2
[1] 0.824782


问:
Alias a model's property to a different name in asp.net-core
I wish to alias the name of my request object properties, so that these requests both work and both go to the same controller:

myapi/cars?colors=red&colors=blue&colors=green and myapi/cars?c=red&c=blue&c=green

for request object:

```<code>public class CarRequest {
    Colors string[] { get; set; }
}
</code>```

Has anyone been able to use the new ModelBinders to solve this without having to write ModelBindings from scratch?

Here is a similar problem for an older version of asp.net and also here

答:
I wrote a model binder to do this:

EDIT:
Here's the repo on github. There are two nuget packages you can add to your code that solve this problem. Details in the readme

It basically takes the place of the ComplexTypeModelBinder (I'm too cowardly to replace it, but I slot it in front with identical criteria), except that it tries to use my new attribute to expand the fields it's looking for.

Binder:

```<code>using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MYDOMAIN.Client;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Logging;

namespace MYDOMAIN.Web.AliasModelBinder
{
    public class AliasModelBinder : ComplexTypeModelBinder
    {
        public AliasModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders, ILoggerFactory loggerFactory,
            bool allowValidatingTopLevelNodes)
            : base(propertyBinders, loggerFactory, allowValidatingTopLevelNodes)
        {
        }

        protected override Task BindProperty(ModelBindingContext bindingContext)
        {
            var containerType = bindingContext.ModelMetadata.ContainerType;
            if (containerType != null)
            {
                var propertyType = containerType.GetProperty(bindingContext.ModelMetadata.PropertyName);
                var attributes = propertyType.GetCustomAttributes(true);

                var aliasAttributes = attributes.OfType<BindingAliasAttribute>().ToArray();
                if (aliasAttributes.Any())
                {
                    bindingContext.ValueProvider = new AliasValueProvider(bindingContext.ValueProvider,
                        bindingContext.ModelName, aliasAttributes.Select(attr => attr.Alias));
                }
            }

            return base.BindProperty(bindingContext);
        }
    }
}
</code>```

Provider:

```<code>using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Logging;

namespace MYDOMAIN.Web.AliasModelBinder
{
    public class AliasModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType)
            {
                var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();

                foreach (var property in context.Metadata.Properties)
                {
                    propertyBinders.Add(property, context.CreateBinder(property));
                }

                return new AliasModelBinder(propertyBinders,
                    (ILoggerFactory) context.Services.GetService(typeof(ILoggerFactory)), true);
            }

            return null;
        }

        /// <summary>
        /// Setup the AliasModelBinderProvider Mvc project to use BindingAlias attribute, to allow for aliasing property names in query strings
        /// </summary>
        public static void Configure(MvcOptions options)
        {
            // Place in front of ComplexTypeModelBinderProvider to replace this binder type in practice
            for (int i = 0; i < options.ModelBinderProviders.Count; i++)
            {
                if (options.ModelBinderProviders[i] is ComplexTypeModelBinderProvider)
                {
                    options.ModelBinderProviders.Insert(i, new AliasModelBinderProvider());
                    return;
                }
            }

            options.ModelBinderProviders.Add(new AliasModelBinderProvider());
        }
    }
}
</code>```

Value Provider:

```<code>using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Primitives;

namespace MYDOMAIN.Web.AliasModelBinder
{
    public class AliasValueProvider : IValueProvider
    {
        private readonly IValueProvider _provider;
        private readonly string _originalName;
        private readonly string[] _allNamesToBind;

        public AliasValueProvider(IValueProvider provider, string originalName, IEnumerable<string> aliases)
        {
            _provider = provider;
            _originalName = originalName;
            _allNamesToBind = new[] {_originalName}.Concat(aliases).ToArray();
        }

        public bool ContainsPrefix(string prefix)
        {
            if (prefix == _originalName)
            {
                return _allNamesToBind.Any(_provider.ContainsPrefix);
            }

            return _provider.ContainsPrefix(prefix);
        }

        public ValueProviderResult GetValue(string key)
        {
            if (key == _originalName)
            {
                var results = _allNamesToBind.Select(alias => _provider.GetValue(alias)).ToArray();
                StringValues values = results.Aggregate(values, (current, r) => StringValues.Concat(current, r.Values));

                return new ValueProviderResult(values, results.First().Culture);
            }

            return _provider.GetValue(key);
        }
    }
}
</code>```

And an attribute to go in / be referenced by the client project

```<code>using System;

namespace MYDOMAIN.Client
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
    public class BindingAliasAttribute : Attribute
    {
        public string Alias { get; }

        public BindingAliasAttribute(string alias)
        {
            Alias = alias;
        }
    }
}
</code>```

Configured in the Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
        {
            services
                ...
                .AddMvcOptions(options =>
                {
                    AliasModelBinderProvider.Configure(options);
                    ...
                })
                ...
</code>```

Usage:

```<code>public class SomeRequest
{
    [BindingAlias("f")]
    public long[] SomeVeryLongNameForSomeKindOfFoo{ get; set; }
}
</code>```

leading to a request that looks either like this:

```<code>api/controller/action?SomeVeryLongNameForSomeKindOfFoo=1&SomeVeryLongNameForSomeKindOfFoo=2
</code>```

or

```<code>api/controller/action?f=1&f=2
</code>```

I put most things in my web project, and the attribute in my client project.

Body:
I wish to alias the name of my request object properties, so that these requests both work and both go to the same controller:

myapi/cars?colors=red&colors=blue&colors=green and myapi/cars?c=red&c=blue&c=green

for request object:

public class CarRequest {
    Colors string[] { get; set; }
}

Has anyone been able to use the new ModelBinders to solve this without having to write ModelBindings from scratch?

Here is a similar problem for an older version of asp.net and also here

Body:
I wrote a model binder to do this:

EDIT:
Here's the repo on github. There are two nuget packages you can add to your code that solve this problem. Details in the readme

It basically takes the place of the ComplexTypeModelBinder (I'm too cowardly to replace it, but I slot it in front with identical criteria), except that it tries to use my new attribute to expand the fields it's looking for.

Binder:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MYDOMAIN.Client;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Logging;

namespace MYDOMAIN.Web.AliasModelBinder
{
    public class AliasModelBinder : ComplexTypeModelBinder
    {
        public AliasModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders, ILoggerFactory loggerFactory,
            bool allowValidatingTopLevelNodes)
            : base(propertyBinders, loggerFactory, allowValidatingTopLevelNodes)
        {
        }

        protected override Task BindProperty(ModelBindingContext bindingContext)
        {
            var containerType = bindingContext.ModelMetadata.ContainerType;
            if (containerType != null)
            {
                var propertyType = containerType.GetProperty(bindingContext.ModelMetadata.PropertyName);
                var attributes = propertyType.GetCustomAttributes(true);

                var aliasAttributes = attributes.OfType<BindingAliasAttribute>().ToArray();
                if (aliasAttributes.Any())
                {
                    bindingContext.ValueProvider = new AliasValueProvider(bindingContext.ValueProvider,
                        bindingContext.ModelName, aliasAttributes.Select(attr => attr.Alias));
                }
            }

            return base.BindProperty(bindingContext);
        }
    }
}

Provider:

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Logging;

namespace MYDOMAIN.Web.AliasModelBinder
{
    public class AliasModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType)
            {
                var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();

                foreach (var property in context.Metadata.Properties)
                {
                    propertyBinders.Add(property, context.CreateBinder(property));
                }

                return new AliasModelBinder(propertyBinders,
                    (ILoggerFactory) context.Services.GetService(typeof(ILoggerFactory)), true);
            }

            return null;
        }

        /// <summary>
        /// Setup the AliasModelBinderProvider Mvc project to use BindingAlias attribute, to allow for aliasing property names in query strings
        /// </summary>
        public static void Configure(MvcOptions options)
        {
            // Place in front of ComplexTypeModelBinderProvider to replace this binder type in practice
            for (int i = 0; i < options.ModelBinderProviders.Count; i++)
            {
                if (options.ModelBinderProviders[i] is ComplexTypeModelBinderProvider)
                {
                    options.ModelBinderProviders.Insert(i, new AliasModelBinderProvider());
                    return;
                }
            }

            options.ModelBinderProviders.Add(new AliasModelBinderProvider());
        }
    }
}

Value Provider:

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Primitives;

namespace MYDOMAIN.Web.AliasModelBinder
{
    public class AliasValueProvider : IValueProvider
    {
        private readonly IValueProvider _provider;
        private readonly string _originalName;
        private readonly string[] _allNamesToBind;

        public AliasValueProvider(IValueProvider provider, string originalName, IEnumerable<string> aliases)
        {
            _provider = provider;
            _originalName = originalName;
            _allNamesToBind = new[] {_originalName}.Concat(aliases).ToArray();
        }

        public bool ContainsPrefix(string prefix)
        {
            if (prefix == _originalName)
            {
                return _allNamesToBind.Any(_provider.ContainsPrefix);
            }

            return _provider.ContainsPrefix(prefix);
        }

        public ValueProviderResult GetValue(string key)
        {
            if (key == _originalName)
            {
                var results = _allNamesToBind.Select(alias => _provider.GetValue(alias)).ToArray();
                StringValues values = results.Aggregate(values, (current, r) => StringValues.Concat(current, r.Values));

                return new ValueProviderResult(values, results.First().Culture);
            }

            return _provider.GetValue(key);
        }
    }
}

And an attribute to go in / be referenced by the client project

using System;

namespace MYDOMAIN.Client
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
    public class BindingAliasAttribute : Attribute
    {
        public string Alias { get; }

        public BindingAliasAttribute(string alias)
        {
            Alias = alias;
        }
    }
}

Configured in the Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services
                ...
                .AddMvcOptions(options =>
                {
                    AliasModelBinderProvider.Configure(options);
                    ...
                })
                ...

Usage:

public class SomeRequest
{
    [BindingAlias("f")]
    public long[] SomeVeryLongNameForSomeKindOfFoo{ get; set; }
}

leading to a request that looks either like this:

api/controller/action?SomeVeryLongNameForSomeKindOfFoo=1&SomeVeryLongNameForSomeKindOfFoo=2

or

api/controller/action?f=1&f=2

I put most things in my web project, and the attribute in my client project.


问:
pytorch masked_fill: why can't I mask all zeros?
I want to mask the all the zeros in the score matrix with -np.inf, but I can only get part of zeros masked, looked like

you see in the upper right corner there are still zeros that didn't get masked with -np.inf

Here's my codes:

```<code>q = torch.Tensor([np.random.random(10),np.random.random(10),np.random.random(10), np.random.random(10), np.zeros((10,1)), np.zeros((10,1))])
k = torch.Tensor([np.random.random(10),np.random.random(10),np.random.random(10), np.random.random(10), np.zeros((10,1)), np.zeros((10,1))])
scores = torch.matmul(q, k.transpose(0,1)) / math.sqrt(10)
mask = torch.Tensor([1,1,1,1,0,0])
mask = mask.unsqueeze(1)
scores = scores.masked_fill(mask==0, -np.inf)
</code>```

Maybe the mask is wrong?

Body:
I want to mask the all the zeros in the score matrix with -np.inf, but I can only get part of zeros masked, looked like

you see in the upper right corner there are still zeros that didn't get masked with -np.inf

Here's my codes:

q = torch.Tensor([np.random.random(10),np.random.random(10),np.random.random(10), np.random.random(10), np.zeros((10,1)), np.zeros((10,1))])
k = torch.Tensor([np.random.random(10),np.random.random(10),np.random.random(10), np.random.random(10), np.zeros((10,1)), np.zeros((10,1))])
scores = torch.matmul(q, k.transpose(0,1)) / math.sqrt(10)
mask = torch.Tensor([1,1,1,1,0,0])
mask = mask.unsqueeze(1)
scores = scores.masked_fill(mask==0, -np.inf)

Maybe the mask is wrong?

Body:
Your mask is wrong. Try

scores = scores.masked_fill(scores == 0, -np.inf)

scores now looks like

tensor([[1.4796, 1.2361, 1.2137, 0.9487,   -inf,   -inf],
        [0.6889, 0.4428, 0.6302, 0.4388,   -inf,   -inf],
        [0.8842, 0.7614, 0.8311, 0.6431,   -inf,   -inf],
        [0.9884, 0.8430, 0.7982, 0.7323,   -inf,   -inf],
        [  -inf,   -inf,   -inf,   -inf,   -inf,   -inf],
        [  -inf,   -inf,   -inf,   -inf,   -inf,   -inf]])


问:
Deleting a node by class is not working in my Tampermonkey script?
I know how to remove a div by class (document.getElementsByClassName('Button')[0].remove()).

But when it is in a link:

```<code><a class="Button" href=""><span>test</span></a>
</code>```

it isn't working.

Why not?

答:
The problem is probably that the page adds that link dynamically using javascript (AJAX).

(Also, the question code would only kill the first such node, and the one you want gone may be later.)

In that case, you need to use AJAX-compensating techniques such as MutationObserver or waitForKeyElements (or clunky hand-coded timers).

Here's a robust way (complete working script):

```<code>// ==UserScript==
// @name     _Remove node(s) with a specified class
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @noframes
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.
/* global $, waitForKeyElements */

waitForKeyElements (".Button", removeNode);

function removeNode (jNode) {
    jNode.remove ();
}
</code>```

Notes:

.Button is the CSS and jQuery selector for nodes with the Button class.

The shown code removes all nodes with class Button.  To remove only the first node, use: waitForKeyElements (".Button", removeNode, true); -- but this is seldom needed.

See Choosing and activating the right controls on an AJAX-driven site for tips on identifying and refining selectors.

Body:
I know how to remove a div by class (document.getElementsByClassName('Button')[0].remove()).

But when it is in a link:

test

it isn't working.

Why not?

Body:
The problem is probably that the page adds that link dynamically using javascript (AJAX).

(Also, the question code would only kill the first such node, and the one you want gone may be later.)

In that case, you need to use AJAX-compensating techniques such as MutationObserver or waitForKeyElements (or clunky hand-coded timers).

Here's a robust way (complete working script):

// ==UserScript==
// @name     _Remove node(s) with a specified class
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @noframes
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.
/* global $, waitForKeyElements */

waitForKeyElements (".Button", removeNode);

function removeNode (jNode) {
    jNode.remove ();
}

Notes:

.Button is the CSS and jQuery selector for nodes with the Button class.

The shown code removes all nodes with class Button.  To remove only the first node, use: waitForKeyElements (".Button", removeNode, true); -- but this is seldom needed.

See Choosing and activating the right controls on an AJAX-driven site for tips on identifying and refining selectors.


问:
Macro metrics (recall/F1...) for multiclass CNN
I use CNN for image classification on unbalance dataset. I'm totaly new with tensorflow backend. It's multiclass problem (not multilabel) and I have 16 classes. Class are one hot encoded.

I want to compute MACRO metrics for each epoch: F1, precision and recall.

I found a code to print those Macro metrics but it's only work on validation set
From: https://medium.com/@thongonary/how-to-compute-f1-score-for-each-epoch-in-keras-a1acd17715a2

class Metrics(Callback):

 def on_train_begin(self, logs={}):
  self.val_f1s = []
  self.val_recalls = []
  self.val_precisions = []

 def on_epoch_end(self, epoch, logs={}):
  val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()
  val_targ = self.validation_data[1]
  _val_f1 = f1_score(val_targ, val_predict,average='macro')
  _val_recall = recall_score(val_targ, val_predict,average='macro')
  _val_precision = precision_score(val_targ, val_predict,average='macro')
  self.val_f1s.append(_val_f1)
  self.val_recalls.append(_val_recall)
  self.val_precisions.append(_val_precision)
  print (" — val_f1: %f — val_precision: %f — val_recall %f" % (_val_f1, _val_precision, _val_recall))
  return

metrics = Metrics()
```

<p>I'm not even sure this code is really working since we use </p>

``` val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()
```

<p><strong>could ROUND lead to error in case of multiclass classification?</strong></p>

<p>And I use this code to print the metrics (only recall since that the important metrics for me) on the training set (also compute on validation set since it's used in model.compute)
code has been adapted from: Custom macro for recall in keras</p>

<pre class="lang-py prettyprint-override"><code>

def recall(y_true,y_pred):
     true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
     possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
     return  true_positives / (possible_positives + K.epsilon())

def unweightedRecall(y_true, y_pred):
    return (recall(y_true[:,0],y_pred[:,0]) + recall(y_true[:,1],y_pred[:,1])+recall(y_true[:,2],y_pred[:,2]) + recall(y_true[:,3],y_pred[:,3])
            +recall(y_true[:,4],y_pred[:,4]) + recall(y_true[:,5],y_pred[:,5])
            +recall(y_true[:,6],y_pred[:,6]) + recall(y_true[:,7],y_pred[:,7])
            +recall(y_true[:,8],y_pred[:,8]) + recall(y_true[:,9],y_pred[:,9])
            +recall(y_true[:,10],y_pred[:,10]) + recall(y_true[:,11],y_pred[:,11])
            +recall(y_true[:,12],y_pred[:,12]) + recall(y_true[:,13],y_pred[:,13])
            +recall(y_true[:,14],y_pred[:,14]) + recall(y_true[:,15],y_pred[:,15]))/16.

</code>```

I run my model with

model.compile(optimizer="adam", loss="categorical_crossentropy",metrics=[unweightedRecall,"accuracy"])   #model compilation with unweightedRecall metrics

train =model.fit_generator(image_gen.flow(train_X, train_label, batch_size=64),epochs=100,verbose=1,validation_data=(valid_X, valid_label),class_weight=class_weights,callbacks=[metrics],steps_per_epoch=len(train_X)/64)  #run the model

```

<p>VALIDATION macro recall differ from the 2 different code.</p>

<p>i.e (look <strong>val_unweightedRecall</strong> and <strong>val_recall</strong>)</p>

```Epoch 10/100
19/18 [===============================] - 13s 703ms/step - loss: 1.5167 - unweightedRecall: 0.1269 - acc: 0.5295 - val_loss: 1.5339 - val_unweightedRecall: 0.1272 - val_acc: 0.5519
 — val_f1: 0.168833 — val_precision: 0.197502 — val_recall 0.15636

```

Why do i have different value on my macro validation recall with the two different code?

Bonus question: For people who have already tryied this, is it really worth to use custom loss based on our interested metric (recall for example) or categorical cross entropy with weights produce same result?

答:
let me answer both question but in the opposite order:

You can't use Recall as a base for a custom loss: It is not convex! If you do not fully understand why Recall or precision or f1 can't be used as a loss, please take the time to see the role of the loss (it is afterall a huge parameter in your model).

Indeed, the round is intended for a binary problem. As they say, if it's not you then it's the other. But in your case it's wrong. Let's go throw the code:

```<code>val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()
</code>```

from the inside out, he take the data (self.validation_data[0;]) and predict a number (1 neuron as output). As such he compute the probability of being a 1. If this probability is over 0.5, then the round transforms it into a 1, if it is under, it transforms it to a 0. As you can see, it is wrong for you. In some case you won't predict any class. Following this mistake, the rest is also wrong.

Now, the solution. You want to compute the mean Recall at every step. by the way, "but it only works on validation set". yes that is intended, you use the validation to validate the model, not the train, else it is cheating.

so Recall is equal to true positive over all positives. Let's do that!

```<code>def recall(y_true, y_pred):
     recall = 0
     pred = K.argmax(y_pred)
     true = K.argmax(y_true)
     for i in range(16):
         p = K.cast(K.equal(pred,i),'int32')
         t = K.cast(K.equal(true,i),'int32')
         # Compute the true positive
         common = K.sum(K.dot(K.reshape(t,(1,-1)),K.reshape(p,(-1,1))))
         # divide by all positives in t
         recall += common/ (K.sum(t) + K.epsilon)
     return recall/16
</code>```

This gives you the mean recall for all classes.
you could print the value for every class.

Tell me if you have any question!

for an implementation of the binary Recall, see this question from which the code is adapted.

Body:
I use CNN for image classification on unbalance dataset. I'm totaly new with tensorflow backend. It's multiclass problem (not multilabel) and I have 16 classes. Class are one hot encoded.

I want to compute MACRO metrics for each epoch: F1, precision and recall.

I found a code to print those Macro metrics but it's only work on validation set
From: https://medium.com/@thongonary/how-to-compute-f1-score-for-each-epoch-in-keras-a1acd17715a2

class Metrics(Callback):

 def on_train_begin(self, logs={}):
  self.val_f1s = []
  self.val_recalls = []
  self.val_precisions = []

 def on_epoch_end(self, epoch, logs={}):
  val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()
  val_targ = self.validation_data[1]
  _val_f1 = f1_score(val_targ, val_predict,average='macro')
  _val_recall = recall_score(val_targ, val_predict,average='macro')
  _val_precision = precision_score(val_targ, val_predict,average='macro')
  self.val_f1s.append(_val_f1)
  self.val_recalls.append(_val_recall)
  self.val_precisions.append(_val_precision)
  print (" — val_f1: %f — val_precision: %f — val_recall %f" % (_val_f1, _val_precision, _val_recall))
  return

metrics = Metrics()

I'm not even sure this code is really working since we use

 val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()

could ROUND lead to error in case of multiclass classification?

And I use this code to print the metrics (only recall since that the important metrics for me) on the training set (also compute on validation set since it's used in model.compute)
code has been adapted from: Custom macro for recall in keras

def recall(y_true,y_pred):
     true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
     possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
     return  true_positives / (possible_positives + K.epsilon())

def unweightedRecall(y_true, y_pred):
    return (recall(y_true[:,0],y_pred[:,0]) + recall(y_true[:,1],y_pred[:,1])+recall(y_true[:,2],y_pred[:,2]) + recall(y_true[:,3],y_pred[:,3])
            +recall(y_true[:,4],y_pred[:,4]) + recall(y_true[:,5],y_pred[:,5])
            +recall(y_true[:,6],y_pred[:,6]) + recall(y_true[:,7],y_pred[:,7])
            +recall(y_true[:,8],y_pred[:,8]) + recall(y_true[:,9],y_pred[:,9])
            +recall(y_true[:,10],y_pred[:,10]) + recall(y_true[:,11],y_pred[:,11])
            +recall(y_true[:,12],y_pred[:,12]) + recall(y_true[:,13],y_pred[:,13])
            +recall(y_true[:,14],y_pred[:,14]) + recall(y_true[:,15],y_pred[:,15]))/16.

I run my model with

model.compile(optimizer="adam", loss="categorical_crossentropy",metrics=[unweightedRecall,"accuracy"])   #model compilation with unweightedRecall metrics

train =model.fit_generator(image_gen.flow(train_X, train_label, batch_size=64),epochs=100,verbose=1,validation_data=(valid_X, valid_label),class_weight=class_weights,callbacks=[metrics],steps_per_epoch=len(train_X)/64)  #run the model

VALIDATION macro recall differ from the 2 different code.

i.e (look val_unweightedRecall and val_recall)

Epoch 10/100
19/18 [===============================] - 13s 703ms/step - loss: 1.5167 - unweightedRecall: 0.1269 - acc: 0.5295 - val_loss: 1.5339 - val_unweightedRecall: 0.1272 - val_acc: 0.5519
 — val_f1: 0.168833 — val_precision: 0.197502 — val_recall 0.15636

Why do i have different value on my macro validation recall with the two different code?

Bonus question: For people who have already tryied this, is it really worth to use custom loss based on our interested metric (recall for example) or categorical cross entropy with weights produce same result?

Body:
let me answer both question but in the opposite order:

You can't use Recall as a base for a custom loss: It is not convex! If you do not fully understand why Recall or precision or f1 can't be used as a loss, please take the time to see the role of the loss (it is afterall a huge parameter in your model).

Indeed, the round is intended for a binary problem. As they say, if it's not you then it's the other. But in your case it's wrong. Let's go throw the code:

val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()

from the inside out, he take the data (self.validation_data[0;]) and predict a number (1 neuron as output). As such he compute the probability of being a 1. If this probability is over 0.5, then the round transforms it into a 1, if it is under, it transforms it to a 0. As you can see, it is wrong for you. In some case you won't predict any class. Following this mistake, the rest is also wrong.

Now, the solution. You want to compute the mean Recall at every step. by the way, "but it only works on validation set". yes that is intended, you use the validation to validate the model, not the train, else it is cheating.

so Recall is equal to true positive over all positives. Let's do that!

def recall(y_true, y_pred):
     recall = 0
     pred = K.argmax(y_pred)
     true = K.argmax(y_true)
     for i in range(16):
         p = K.cast(K.equal(pred,i),'int32')
         t = K.cast(K.equal(true,i),'int32')
         # Compute the true positive
         common = K.sum(K.dot(K.reshape(t,(1,-1)),K.reshape(p,(-1,1))))
         # divide by all positives in t
         recall += common/ (K.sum(t) + K.epsilon)
     return recall/16

This gives you the mean recall for all classes.
you could print the value for every class.

Tell me if you have any question!

for an implementation of the binary Recall, see this question from which the code is adapted.


问:
replacing the key value with another property in array of objects
merging array with object and returning an array with all the properties with array of object value or null

```<code>let object = {
  keys: {
    test1: {label: "Test_1"},
    test2: {label: "Test_2"},
    test3: {label: "Test_3"}
  }
}

let data = [{test1: "1", test2: "2", default:"123134" }, {test1: "1", test2: "2", default:"123134"}, {test1: "1", test3: "3"}, {test3: "3"}]
</code>```

I am expecting the below array of objects

```<code>let expectedArray = [{Test_1: "1", Test_2: "2", Test_3: null ,default:"123134" }, {Test_1: "1", Test_2: "2", Test_3: null,  default:"123134"}, {Test_1: "1", Test_3: "3", Test_2:null }, {Test_3: "3", Test_1: null, Test_2: null}]
</code>```

Tried below snippet

```<code>let res = data.map(o => {
  let obj = {}
  let c = Object.keys(o).forEach(aa => {
      obj[object.keys[aa].label] = o[aa]
  })
  return obj
})
</code>```

Any help appreciated

答:
You could replace existent key of object and rebuild new objects.

var object = { keys: { test1: { label: "Test 1" }, test2: { label: "Test 2" }, test3: { label: "Test 3" } } },
    data = [{ test1: "1", test2: "2", default: "123134" }, { test1: "1", test2: "2", default: "123134" }, { test1: "1", test3: "3" }, { test3: "3" }],
    templates = Object.values(object.keys).map(({ label }) => ({ [label]: null })),
    result = data.map(o => Object.assign(
        {},
        ...templates,
        ...Object
            .entries(o)
            .map(([k, v]) => ({ [k in object.keys ? object.keys[k].label : k]: v }))
    ));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
merging array with object and returning an array with all the properties with array of object value or null

let object = {
  keys: {
    test1: {label: "Test_1"},
    test2: {label: "Test_2"},
    test3: {label: "Test_3"}
  }
}

let data = [{test1: "1", test2: "2", default:"123134" }, {test1: "1", test2: "2", default:"123134"}, {test1: "1", test3: "3"}, {test3: "3"}]

I am expecting the below array of objects

let expectedArray = [{Test_1: "1", Test_2: "2", Test_3: null ,default:"123134" }, {Test_1: "1", Test_2: "2", Test_3: null,  default:"123134"}, {Test_1: "1", Test_3: "3", Test_2:null }, {Test_3: "3", Test_1: null, Test_2: null}]

Tried below snippet

let res = data.map(o => {
  let obj = {}
  let c = Object.keys(o).forEach(aa => {
      obj[object.keys[aa].label] = o[aa]
  })
  return obj
})

Any help appreciated

Body:
You could replace existent key of object and rebuild new objects.

var object = { keys: { test1: { label: "Test 1" }, test2: { label: "Test 2" }, test3: { label: "Test 3" } } },
    data = [{ test1: "1", test2: "2", default: "123134" }, { test1: "1", test2: "2", default: "123134" }, { test1: "1", test3: "3" }, { test3: "3" }],
    templates = Object.values(object.keys).map(({ label }) => ({ [label]: null })),
    result = data.map(o => Object.assign(
        {},
        ...templates,
        ...Object
            .entries(o)
            .map(([k, v]) => ({ [k in object.keys ? object.keys[k].label : k]: v }))
    ));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Basic C question on copying char arrays to char pointers
I have some doubts in basic C programming.

I have a char array and I have to copy it to a char pointer. So I did the following:

```<code>char a[] = {0x3f, 0x4d};
char *p = a;
printf("a = %s\n",a);
printf("p = %s\n",p);
unsigned char str[] = {0x3b, 0x4b};
unsigned char *pstr =str;
memcpy(pstr, str, sizeof str);
printf("str = %s\n",str);
printf("pstr = %s\n",pstr);
</code>```

My printf statements for pstr and str get appended with the data "a".
If I remove memcpy I get junk. Can some C Guru enlighten me?

答:
The standard way C strings are represented is that in memory, they are a sequence of non-zero bytes representing the characters, followed by a zero (or NULL) byte. You should declare:

```<code>char a[] = {0x3f, 0x4d, 0};
</code>```

When you assign a string pointer (as in unsigned char *pstr = str;) both pointers point to the same memory area, and thus the same characters. There is no need to copy the characters.

When you do need to copy characters, you should be using strlen(), the sizeof() operator returns the number of bytes its argument uses in memory. sizeof(pointer) is the number of bytes the pointer uses, not the length of the string. You find the length of a string (i.e. the number of bytes it occupies in memory) with the strlen() function. Also, there are standard functions to copy C strings. You should rely on those to do the right thing:

```<code>strcpy(pstr, str);
</code>```

Body:
I have some doubts in basic C programming.

I have a char array and I have to copy it to a char pointer. So I did the following:

char a[] = {0x3f, 0x4d};
char *p = a;
printf("a = %s\n",a);
printf("p = %s\n",p);
unsigned char str[] = {0x3b, 0x4b};
unsigned char *pstr =str;
memcpy(pstr, str, sizeof str);
printf("str = %s\n",str);
printf("pstr = %s\n",pstr);

My printf statements for pstr and str get appended with the data "a".
If I remove memcpy I get junk. Can some C Guru enlighten me?

Body:
The standard way C strings are represented is that in memory, they are a sequence of non-zero bytes representing the characters, followed by a zero (or NULL) byte. You should declare:

char a[] = {0x3f, 0x4d, 0};

When you assign a string pointer (as in unsigned char *pstr = str;) both pointers point to the same memory area, and thus the same characters. There is no need to copy the characters.

When you do need to copy characters, you should be using strlen(), the sizeof() operator returns the number of bytes its argument uses in memory. sizeof(pointer) is the number of bytes the pointer uses, not the length of the string. You find the length of a string (i.e. the number of bytes it occupies in memory) with the strlen() function. Also, there are standard functions to copy C strings. You should rely on those to do the right thing:

strcpy(pstr, str);


问:
Set up kubernetes cluster with multiple pods automatically
Sorry if the question is a bit abstract but I am currently getting into GCP.

First of all my goal - I want to set up automatic creation of kubernetes cluster with a number of pods.

What I have so far - I have past few days looking in the GCP and Kubernetes documentation as well as some examples. I have two working bits:

I have created a cluster config with yaml and jinja files and I
can use deployment manager to set them up.

```<code>gcloud deployment-manager deployments create my-config --config my-config.yaml
</code>```

I have created another configuration yaml file which uses a docker image stored in the GCP Container Registry to start some pods on the cluster above (which again works fine)

kubectl apply -f image-config.yaml --record

My question is is it possible to combine somehow the above into a single config file and start everything up with a single command?
Or if you can point me in the direction of some appropriate example.

答:
Yes that is entirely possible. You should combine the two config files in a multi-document YAML file, the first of which contains a sequence of commands to be executed on document two and following.

```<code>---
- gcloud deployment-manager deployments create my-config --config $doc2:my-config.yaml
- kubectl apply -f $doc3:image-config.yaml --record
---
<insert contents of my-config.yaml here>
---
<insert contents of image-config.yaml here>
</code>```

A small program can load the documents, parse the sequence in the first doc, extract the name of the temporary file to write, dump the appropriate doc to that file, execute the command (removing $docN:), remove the temporary file. My guess is that should be doable in about 15 lines of code.

Body:
Sorry if the question is a bit abstract but I am currently getting into GCP.

First of all my goal - I want to set up automatic creation of kubernetes cluster with a number of pods.

What I have so far - I have past few days looking in the GCP and Kubernetes documentation as well as some examples. I have two working bits:

I have created a cluster config with yaml and jinja files and I
can use deployment manager to set them up.

gcloud deployment-manager deployments create my-config --config my-config.yaml

I have created another configuration yaml file which uses a docker image stored in the GCP Container Registry to start some pods on the cluster above (which again works fine)

kubectl apply -f image-config.yaml --record

My question is is it possible to combine somehow the above into a single config file and start everything up with a single command?
Or if you can point me in the direction of some appropriate example.

Body:
Yes that is entirely possible. You should combine the two config files in a multi-document YAML file, the first of which contains a sequence of commands to be executed on document two and following.

---
- gcloud deployment-manager deployments create my-config --config $doc2:my-config.yaml
- kubectl apply -f $doc3:image-config.yaml --record
---
<insert contents of my-config.yaml here>
---
<insert contents of image-config.yaml here>

A small program can load the documents, parse the sequence in the first doc, extract the name of the temporary file to write, dump the appropriate doc to that file, execute the command (removing $docN:), remove the temporary file. My guess is that should be doable in about 15 lines of code.


问:
Vba code for keeping chart object on one sheet when using range.exporttopdf method
I have code that outputs a range and a pivotchart to pdf. At this point I am struggling to have the chart element on one page instead of it possibly being cutoff. Here is my code:

```<code>With nxraySheet.PageSetup
        .FitToPagesWide = 1
        .FitToPagesTall = False
        .Orientation = xlLandscape
        .Zoom = 85
        .LeftMargin = 0
        .RightMargin = 0
        .CenterHorizontally = True
        End With

        nxraySheet.Columns("A:H").HorizontalAlignment = xlCenter
        nxraySheet.Range("A:H").ExportAsFixedFormat _
            Type:=xlTypePDF, _
            Filename:="Blah Blah Blah\Test Location\AVITEST\PDFs\X-Rays\" & "X-Ray-" & facilityList.Cells(i, 1) & "-" & Format(Date, "mm-dd-yy") & ".xlsx", _
            Quality:=xlQualityStandard, _
            IncludeDocProperties:=True, _
            IgnorePrintAreas:=False, _
            OpenAfterPublish:=False
</code>```

[]

答:
In Excel, unfortunately you can not tell a chart to be printed as a whole (would be like "Excel, please move the chart some rows up or down to get printed altogether").

Here are some options:

Overall Zoom

You can not have both FitToPagesWide = 1 and Zoom = 85 at the same time. This doesn't raise an error, but these settings conflict with each other and zoom factor wins.
So you may decide for a lower zoom factor:

```<code>With nxraySheet.PageSetup
    .Zoom = 75
</code>```

Fit vertically on 1 Page

If you want it to fit vertically on 1 page, reset the zoom factor first:

```<code>With nxraySheet.PageSetup
    .Zoom = False
    .FitToPagesWide = False
    .FitToPagesTall = 1
</code>```

Fit horizontally on 1 Page, add Page Break

You can print with 1 page width and add a manual horizontal page break directly before the PivotChart:

```<code>With nxraySheet
    .PageSetup.Zoom = False
    .PageSetup.FitToPagesWide = 1
    .PageSetup.FitToPagesTall = False
    .ResetAllPageBreaks
    .HPageBreaks.Add Before:=.ChartObjects(1).TopLeftCell.Row
</code>```

Body:
I have code that outputs a range and a pivotchart to pdf. At this point I am struggling to have the chart element on one page instead of it possibly being cutoff. Here is my code:

With nxraySheet.PageSetup
        .FitToPagesWide = 1
        .FitToPagesTall = False
        .Orientation = xlLandscape
        .Zoom = 85
        .LeftMargin = 0
        .RightMargin = 0
        .CenterHorizontally = True
        End With

        nxraySheet.Columns("A:H").HorizontalAlignment = xlCenter
        nxraySheet.Range("A:H").ExportAsFixedFormat _
            Type:=xlTypePDF, _
            Filename:="Blah Blah Blah\Test Location\AVITEST\PDFs\X-Rays\" & "X-Ray-" & facilityList.Cells(i, 1) & "-" & Format(Date, "mm-dd-yy") & ".xlsx", _
            Quality:=xlQualityStandard, _
            IncludeDocProperties:=True, _
            IgnorePrintAreas:=False, _
            OpenAfterPublish:=False

[]

Body:
In Excel, unfortunately you can not tell a chart to be printed as a whole (would be like "Excel, please move the chart some rows up or down to get printed altogether").

Here are some options:

Overall Zoom

You can not have both FitToPagesWide = 1 and Zoom = 85 at the same time. This doesn't raise an error, but these settings conflict with each other and zoom factor wins.
So you may decide for a lower zoom factor:

With nxraySheet.PageSetup
    .Zoom = 75

Fit vertically on 1 Page

If you want it to fit vertically on 1 page, reset the zoom factor first:

With nxraySheet.PageSetup
    .Zoom = False
    .FitToPagesWide = False
    .FitToPagesTall = 1

Fit horizontally on 1 Page, add Page Break

You can print with 1 page width and add a manual horizontal page break directly before the PivotChart:

With nxraySheet
    .PageSetup.Zoom = False
    .PageSetup.FitToPagesWide = 1
    .PageSetup.FitToPagesTall = False
    .ResetAllPageBreaks
    .HPageBreaks.Add Before:=.ChartObjects(1).TopLeftCell.Row


问:
How to check angular radio button by default?
I was trying to check an angular mat button by default! But it does not work !

```<code>    <div class="container shadow">
        <mat-radio-group>
          <mat-radio-button class="mat-button-custom" [checked]="true">Problems</mat-radio-button>
          <mat-radio-button class="mat-button-custom" [checked]="false">My Submission</mat-radio-button>
        </mat-radio-group>
     </div>
</code>```

Another thing is how to change only the button color!When I override the mat-radio-button css with background color: red it also colors the button label ! But I only want to change the circle part that means only the button.

答:
```<code><mat-radio-button class="mat-button-custom" checked>Problems</mat-radio-button>
</code>```

This checks the radio button when the page loads. If you remove checked the button will not be checked.

Body:
I was trying to check an angular mat button by default! But it does not work !

        <mat-radio-group>
          <mat-radio-button class="mat-button-custom" [checked]="true">Problems</mat-radio-button>
          <mat-radio-button class="mat-button-custom" [checked]="false">My Submission</mat-radio-button>
        </mat-radio-group>

Another thing is how to change only the button color!When I override the mat-radio-button css with background color: red it also colors the button label ! But I only want to change the circle part that means only the button.

Body:
<mat-radio-button class="mat-button-custom" checked>Problems</mat-radio-button>

This checks the radio button when the page loads. If you remove checked the button will not be checked.