问:
Is there a unique ID for objects clicked within target?
With the following code, as you can see with each oval created, the name always remains the same.
So no matter which oval I click, I get the same name. Is there some kind of unique ID buried in the target attribute?</p>

```<code><!DOCTYPE html>
<html lang="en">
<input type="button" onClick="doit()" value="Do it">

<script>
function doit() {
    drawOval(160,80,50);
    myOval = document.getElementById("newdiv");
}

function drawOval(width, height, radius) {
    if (document.createElement) {

       newdiv=document.createElement("div");
       newdiv.style.width = width+"px";
       newdiv.style.height = height+"px";
       newdiv.style.backgroundColor = 'red';
       newdiv.style.visibility = 'visible';
       newdiv.style.borderRadius = radius+"%"

       newdiv.id = 'newdiv';// + i;
       document.body.appendChild(newdiv);
    }
}

document.onclick = function(f){
    alert(f.target.id)
}
</script>

</html>
</code>```

答:
Try this</p>

```<code><!DOCTYPE html>
<html lang="en">
<input type="button" onClick="doit()" value="Do it">

<script>
    var id = 1;
function doit() {
    drawOval(160,80,50);
    myOval = document.getElementById("newdiv");
}

function drawOval(width, height, radius) {
    if (document.createElement) {

       newdiv=document.createElement("div");
       newdiv.style.width = width+"px";
       newdiv.style.height = height+"px";
       newdiv.style.backgroundColor = 'red';
       newdiv.style.visibility = 'visible';
       newdiv.style.borderRadius = radius+"%"

       newdiv.id = 'newdiv' + id;// + i;
        id++;
       document.body.appendChild(newdiv);
    }
}

document.onclick = function(f){
    alert(f.target.id)
}
</script>

</html>

</code>```

Body:
With the following code, as you can see with each oval created, the name always remains the same.
So no matter which oval I click, I get the same name. Is there some kind of unique ID buried in the target attribute?

<!DOCTYPE html>

<input type="button" onClick="doit()" value="Do it">

Body:
Try this

<!DOCTYPE html>
<html lang="en">
<input type="button" onClick="doit()" value="Do it">

<script>
    var id = 1;
function doit() {
    drawOval(160,80,50);
    myOval = document.getElementById("newdiv");
}

function drawOval(width, height, radius) {
    if (document.createElement) {

       newdiv=document.createElement("div");
       newdiv.style.width = width+"px";
       newdiv.style.height = height+"px";
       newdiv.style.backgroundColor = 'red';
       newdiv.style.visibility = 'visible';
       newdiv.style.borderRadius = radius+"%"

       newdiv.id = 'newdiv' + id;// + i;
        id++;
       document.body.appendChild(newdiv);
    }
}

document.onclick = function(f){
    alert(f.target.id)
}
</script>

</html>


来源: stackexchange

问:
When do Cloud Functions retry?
Having enabled retries for my Cloud Function, I am wondering what all the cases are that it will retry.

This section seems contradictary to me. Hence, I assume that I do not understand it.

I thought that the following implies that the function that have "Retry on failure" enabled will also retry on fatal errors:

Cloud Functions does not understand a fatal error that shouldn't be retried

However, what is the point of catching errors and using Promise.reject in that case?

I tried to use Promise.reject to cancel retries of my Cloud Function, however, that does not happen.

```<code>return Promise.reject(..) // will retry
throw Error() // will retry
</code>```

Both will retry for a week if the function is not redeployed.

To me it seems like fatal errors and Promise.reject will both retry, however, the documentation says:

you should modify your code accordingly if you support fatal errors

What is the point of this section in the documentation and what should I really do now?

答:
I think the code sample in the Google docs is simply wrong. I would suggest it should be:

```<code>return doFooAsync().catch(err => {
    if (isFatal(err)) {
        console.error(`Fatal error ${err}`);

        return true;
    }

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

If the error is fatal (you don't want to retry), log the error and return true (you do not need to Promise.resolve(true) as the framework will wrap the return value in a Promise. If the error is not fatal (you want to retry), just re-throw the error (again, Promise.reject(err) is redundant).

ContentLicense: CC BY-SA 4.0

Title: When do Cloud Functions retry?

Body:
Having enabled retries for my Cloud Function, I am wondering what all the cases are that it will retry.

This section seems contradictary to me. Hence, I assume that I do not understand it.

I thought that the following implies that the function that have "Retry on failure" enabled will also retry on fatal errors:

Cloud Functions does not understand a fatal error that shouldn't be retried

However, what is the point of catching errors and using Promise.reject in that case?

I tried to use Promise.reject to cancel retries of my Cloud Function, however, that does not happen.

return Promise.reject(..) // will retry
throw Error() // will retry

Both will retry for a week if the function is not redeployed.

To me it seems like fatal errors and Promise.reject will both retry, however, the documentation says:

you should modify your code accordingly if you support fatal errors

What is the point of this section in the documentation and what should I really do now?

Body:
I think the code sample in the Google docs is simply wrong. I would suggest it should be:

return doFooAsync().catch(err => {
    if (isFatal(err)) {
        console.error(`Fatal error ${err}`);

        return true;
    }

    throw err;
});

If the error is fatal (you don't want to retry), log the error and return true (you do not need to Promise.resolve(true) as the framework will wrap the return value in a Promise. If the error is not fatal (you want to retry), just re-throw the error (again, Promise.reject(err) is redundant).


问:
Fix issue with regex expression getting first word in string in Java?
I am running a simple Java application and I want to grab the very first word in each string that I pass. So I did a str.split(" "); but I realized that my string that I have is very dynamic and it is constantly changing. So I pick up a , tagged on to the string which once I pass as a parameter crashes my code. So I am trying to find a particualry regex expression to just grab the very first words up until either a space, coma, period, or etc.

Example String:

```<code>WebServer, Config where AppConfig.display ends-with '/conf/workers.properties'  and Config.content.content contains 'worker.lyc_' and Config.parent.guid==WebServer.guid and exists(WebServer.container.virtualHosts.serverName contains 'www.laffatservices.gix.com')
</code>```

My goal would to be to just grab WebServer.

答:
If your goal is to grab only the first word then here is your regex ^[A-Za-z]{2,}.

Note that this matches a sequence of, at least two, capital and lower letters. And that match must be only in the start.

Hope that helps your case.

Body:
I am running a simple Java application and I want to grab the very first word in each string that I pass. So I did a str.split(" "); but I realized that my string that I have is very dynamic and it is constantly changing. So I pick up a , tagged on to the string which once I pass as a parameter crashes my code. So I am trying to find a particualry regex expression to just grab the very first words up until either a space, coma, period, or etc.

Example String:

WebServer, Config where AppConfig.display ends-with '/conf/workers.properties'  and Config.content.content contains 'worker.lyc_' and Config.parent.guid==WebServer.guid and exists(WebServer.container.virtualHosts.serverName contains 'www.laffatservices.gix.com')

My goal would to be to just grab WebServer.


问:
How to colour vertices and highlight links in igraph plot
I'm new to igraph and I'm trying to plot small world networks where I color the vertices based on an attribute and highlight specific links.

Say I have an adjacency matrix (adj_matrix) for a network (myNet) with 8 vertices:

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

And in a separate dataframe (df), I have 8 corresponding values:

```<code>> df
  name    values
1    1 0.3568838
2    2 0.5260344
3    3 0.3568838
4    4 0.7374865
5    5 0.7140553
6    6 0.5260344
7    7 0.4125705
8    8 0.7374865
</code>```

As a makeshift solution, I can plot this as an undirected network with the vertices coloured by nodes$values manually like so:

```<code>as_edgelist(myNet, names = TRUE)

links <- data.frame(
  source=as_edgelist(myNet, names = TRUE)[,1],
  target=as_edgelist(myNet, names = TRUE)[,2])

palf <- colorRampPalette(c("gray80", "red"))
network <- graph_from_data_frame(d = links, vertices = df, directed = F)
plot(network, vertex.color = palf(8), layout=layout_in_circle)
</code>```

But this is obviously tedious, and there must be a better way. Ideally there would be a way to use only an adjacency matrix to plot the edges and a vector of values to colour the vertices. How might I do this?

In addition, I'd like to know how to highlight (i.e., bold, change the colour, and/or change the line type) of a given edge.

答:
You can colour vertices and edges in igraph by specifying values of vertex.color and edge.color when you plot().

So far so good in your example, but you should really try to work with igraph-objects instead of your makeshift solutions. Consider making your graph with graph_from_edgelist() or graph_from_adjacency_matrix().

The igraph-object naturally plots verticy-attributes like color and edge-attributes like color and width. You could set them setting them like so:

```<code>V(network)$color <- "white"
V(network)$color <- "black"
</code>```

Note also, that your code above doesn't colour edges according to your values in the df, but rather as a linear gradient from gray to red generated by your palf() :)

This code replicates your example data

```<code>df <- data.frame(name=1:8, values=c(0.3568838,0.5260344, 0.3568838,0.7374865,0.7140553,0.5260344,0.4125705,0.7374865))
g <- make_empty_graph(n=8, directed=F) %>% add_edges(c(1,2,2,3,3,4,4,8,1,8,8,7,7,6,6,5))
adj_matrix <- as.matrix(as_adjacency_matrix(g))
</code>```

This is how you could start colouring and highlighting

```<code># Make network and assign values from dataframe
network <- graph_from_adjacency_matrix(adj_matrix, mode="undirected")
V(network)$value <- df$values
V(network)$col_values <- round( V(network)$value, 2) * 100

# Colour vertecies
colours <- colorRampPalette(c("gray80", "red"))(100)
V(network)$color <- colours[ V(network)$col_values ]

# Color edges
E(network)$color <- "black"

#Highlight edge
E(network)$width <- 1
E(network)$width[5] <- 5

# Plot
plot(network, layout=layout_in_circle)
</code>```

A very straightforward way, if your data-frames are in order, is to directly assign attributes to edges and vertices when creating the network using graph_from_data_frame(). Just make sure that the data-frames for vertices and edges actuarially have columns named color or width or whatever other values you would like to set and appropriate values for those attributes.

See the manual ?graph_from_data_frame() for a good example.

Body:
I'm new to igraph and I'm trying to plot small world networks where I color the vertices based on an attribute and highlight specific links.

Say I have an adjacency matrix (adj_matrix) for a network (myNet) with 8 vertices:

> adj_matrix
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    0    1    0    0    0    0    0    1
[2,]    1    0    1    0    0    0    0    0
[3,]    0    1    0    1    0    0    0    0
[4,]    0    0    1    0    0    0    0    1
[5,]    0    0    0    0    0    1    0    0
[6,]    0    0    0    0    1    0    1    0
[7,]    0    0    0    0    0    1    0    1
[8,]    1    0    0    1    0    0    1    0

And in a separate dataframe (df), I have 8 corresponding values:

> df
  name    values
1    1 0.3568838
2    2 0.5260344
3    3 0.3568838
4    4 0.7374865
5    5 0.7140553
6    6 0.5260344
7    7 0.4125705
8    8 0.7374865

As a makeshift solution, I can plot this as an undirected network with the vertices coloured by nodes$values manually like so:

as_edgelist(myNet, names = TRUE)

links <- data.frame(
  source=as_edgelist(myNet, names = TRUE)[,1],
  target=as_edgelist(myNet, names = TRUE)[,2])

palf <- colorRampPalette(c("gray80", "red"))
network <- graph_from_data_frame(d = links, vertices = df, directed = F)
plot(network, vertex.color = palf(8), layout=layout_in_circle)

But this is obviously tedious, and there must be a better way. Ideally there would be a way to use only an adjacency matrix to plot the edges and a vector of values to colour the vertices. How might I do this?

In addition, I'd like to know how to highlight (i.e., bold, change the colour, and/or change the line type) of a given edge.

Body:
You can colour vertices and edges in igraph by specifying values of vertex.color and edge.color when you plot().

So far so good in your example, but you should really try to work with igraph-objects instead of your makeshift solutions. Consider making your graph with graph_from_edgelist() or graph_from_adjacency_matrix().

The igraph-object naturally plots verticy-attributes like color and edge-attributes like color and width. You could set them setting them like so:

V(network)$color <- "white"
V(network)$color <- "black"

Note also, that your code above doesn't colour edges according to your values in the df, but rather as a linear gradient from gray to red generated by your palf() :)

This code replicates your example data

df <- data.frame(name=1:8, values=c(0.3568838,0.5260344, 0.3568838,0.7374865,0.7140553,0.5260344,0.4125705,0.7374865))
g <- make_empty_graph(n=8, directed=F) %>% add_edges(c(1,2,2,3,3,4,4,8,1,8,8,7,7,6,6,5))
adj_matrix <- as.matrix(as_adjacency_matrix(g))

This is how you could start colouring and highlighting

# Make network and assign values from dataframe
network <- graph_from_adjacency_matrix(adj_matrix, mode="undirected")
V(network)$value <- df$values
V(network)$col_values <- round( V(network)$value, 2) * 100

# Colour vertecies
colours <- colorRampPalette(c("gray80", "red"))(100)
V(network)$color <- colours[ V(network)$col_values ]

# Color edges
E(network)$color <- "black"

#Highlight edge
E(network)$width <- 1
E(network)$width[5] <- 5

# Plot
plot(network, layout=layout_in_circle)

A very straightforward way, if your data-frames are in order, is to directly assign attributes to edges and vertices when creating the network using graph_from_data_frame(). Just make sure that the data-frames for vertices and edges actuarially have columns named color or width or whatever other values you would like to set and appropriate values for those attributes.

See the manual ?graph_from_data_frame() for a good example.


问:
How do I convert a python array of shape (25000, 256,256,3) to (25000,3,256,256,3) where the 3 images are exactly the same?
I have an array of 25000 RGB images of dimension 256x256x3 [25000,256,256,3]. Now, I want to replicate each of these images 2 times more and concatenate them such that the output array should be one dimension higher [25000,3,256,256,3]. This is channel last shape.</p>

答:
Without further clarification, I'm going to assume that you're working with basic NumPy arrays. In that case, you can use numpy.stack with axis specified:

my_array = ...
n_copies = 3
replicated_array = np.stack([my_array for _ in range(n_copies)], axis=1)
```

<p>Full example (dimensions changed for illustrative purposes):</p>

<pre class="lang-py prettyprint-override"><code>>>> import numpy as np
>>>
>>> a = np.array([[[0, 0, 1], [0, 1, 0]], [[0, 1, 1], [1, 0, 0]]])  # RGB images of dimension 2x2
>>> a
array([[[0, 0, 1],
        [0, 1, 0]],

       [[0, 1, 1],
        [1, 0, 0]]])
>>> a.shape
(2, 2, 3)
>>>
>>> a_array = np.stack([a for _ in range(4)])  # Array of 4 images
>>> a_array.shape
(4, 2, 2, 3)
>>>
>>> # Replicate each of these images 9 times more and concatenate them
>>> # such that the output array should be one dimension higher
>>> np.stack([a_array for _ in range(10)], axis=1).shape
(4, 10, 2, 2, 3)
</code>```

Body:
Without further clarification, I'm going to assume that you're working with basic NumPy arrays. In that case, you can use numpy.stack with axis specified:

my_array = ...
n_copies = 3
replicated_array = np.stack([my_array for _ in range(n_copies)], axis=1)

Full example (dimensions changed for illustrative purposes):

>>> import numpy as np
>>>
>>> a = np.array([[[0, 0, 1], [0, 1, 0]], [[0, 1, 1], [1, 0, 0]]])  # RGB images of dimension 2x2
>>> a
array([[[0, 0, 1],
        [0, 1, 0]],

       [[0, 1, 1],
        [1, 0, 0]]])
>>> a.shape
(2, 2, 3)
>>>
>>> a_array = np.stack([a for _ in range(4)])  # Array of 4 images
>>> a_array.shape
(4, 2, 2, 3)
>>>
>>> # Replicate each of these images 9 times more and concatenate them
>>> # such that the output array should be one dimension higher
>>> np.stack([a_array for _ in range(10)], axis=1).shape
(4, 10, 2, 2, 3)


问:
UIWebView eating all memory for loadRequest in iPad
I have read about lot of leak issues with UIWebView But my case is very simple so I decided to go for a new question.
When I try to load a file from WebView loadRequest method the memory allocation keeps on increasing if I watch in Instruments. But if I see the leaks there is no leaks at all in instruments.

I am using 4.3 sdk so I guess it has to be latest issue.

I have gone through  this article
Why UIWebView Eating so many Memory?
and this article http://blog.techno-barje.fr/post/2010/10/04/UIWebView-secrets-part1-memory-leaks-on-xmlhttprequest

but nothing seems to work for me.

```<code>@interface MyView: UIViewController <UIWebViewDelegate> {

IBOutlet UIWebView *webView;

}

@property (nonatomic, retain) IBOutlet UIWebView *webView;
</code>```

=========
inside my MyView Class

```<code>@synthesize webView;

-(void)viewDidLoad {

    [super viewDidLoad];

    NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", pathString]];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]] ];

}

-(void)dealloc {

   [webView release];

}
</code>```

Waiting for your replies.

Thanks in advance

答:
Have you tried logging the following delegate method?</p>

```<code>- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
   NSLog(@"Error: %@", [error description]);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have read about lot of leak issues with UIWebView But my case is very simple so I decided to go for a new question.
When I try to load a file from WebView loadRequest method the memory allocation keeps on increasing if I watch in Instruments. But if I see the leaks there is no leaks at all in instruments.

I am using 4.3 sdk so I guess it has to be latest issue.

I have gone through  this article
Why UIWebView Eating so many Memory?
and this article http://blog.techno-barje.fr/post/2010/10/04/UIWebView-secrets-part1-memory-leaks-on-xmlhttprequest

but nothing seems to work for me.

@interface MyView: UIViewController <UIWebViewDelegate> {

IBOutlet UIWebView *webView;

}

@property (nonatomic, retain) IBOutlet UIWebView *webView;

=========
inside my MyView Class

@synthesize webView;

-(void)viewDidLoad {

    [super viewDidLoad];

    NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", pathString]];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]] ];

}

-(void)dealloc {

   [webView release];

}

Waiting for your replies.

Thanks in advance

Body:
Have you tried logging the following delegate method?

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
   NSLog(@"Error: %@", [error description]);
}


问:
firebase cloud messaging: setBackgroundMessageHandler not called
I am prototyping browser push notifications with FCM. I just copied the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging). Messages are recieved and displayed as they should be. But when I try to modify the message in the Service Worker (messaging.setBackgroundMessageHandler) nothing happens. The service worker is called, and if I implement an event listener in that service worker for the push notifications, it catches the event. But the method setBackgroundMessageHandler is never called.
I am trying this on Chrome 54.

Any ideas what I need to do to customize the message in the service worker?

Thank you very much!

答:
As mentioned by others, including notification in the payload stops it working on the web JS SDK, however you need it present for it to work in native apps.

The workaround I found for the web was to use the web browser native EH push to handle the event manually:

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onpush

```<code>  self.addEventListener('notificationclick', function(event) {
    console.log('SW: Clicked notification', event)

    let data = event.notification.data

    event.notification.close()

    self.clients.openWindow(event.notification.data.link)
  })

  self.addEventListener('push', event => {
    let data = {}

    if (event.data) {
      data = event.data.json()
    }

    console.log('SW: Push received', data)

    if (data.notification && data.notification.title) {
      self.registration.showNotification(data.notification.title, {
        body: data.notification.body,
        icon: 'https://example.com/img/icons/icon-144x144.png',
        data
      })
    } else {
      console.log('SW: No notification payload, not showing notification')
    }
  })
</code>```

Body:
As mentioned by others, including notification in the payload stops it working on the web JS SDK, however you need it present for it to work in native apps.

The workaround I found for the web was to use the web browser native EH push to handle the event manually:

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onpush

  self.addEventListener('notificationclick', function(event) {
    console.log('SW: Clicked notification', event)

    let data = event.notification.data

    event.notification.close()

    self.clients.openWindow(event.notification.data.link)
  })

  self.addEventListener('push', event => {
    let data = {}

    if (event.data) {
      data = event.data.json()
    }

    console.log('SW: Push received', data)

    if (data.notification && data.notification.title) {
      self.registration.showNotification(data.notification.title, {
        body: data.notification.body,
        icon: 'https://example.com/img/icons/icon-144x144.png',
        data
      })
    } else {
      console.log('SW: No notification payload, not showing notification')
    }
  })


问:
how can I check if a queue exists on Activemq
I have this method that throws me an exception when the data queue doesn't exists, but is not. Do you have other way to solve this?</p>

```<code>public void checkDataQueue(String dataQueue) throws JMSException {

          Connection connection = null;
          Session session = null;
          connection = jmsTemplate.getConnectionFactory().createConnection();
          session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

          Queue queue = session.createQueue(dataQueue);
          QueueBrowser browser = session.createBrowser(queue);
      }
</code>```

答: ActiveMQ 5.x creates Queues on demand by default so you may have changed the default configuration to disallow this in which case the error should be expected to happen if you are hitting a non-existent queue and you should check for and handle that.  If you need to be sure then the broker provides a JMX interface to query for information on broker statistics etc.  There are also other ways of monitoring such as using Rest style calls over the Jolokia management interface.</p>

Body:
I have this method that throws me an exception when the data queue doesn't exists, but is not. Do you have other way to solve this?

public void checkDataQueue(String dataQueue) throws JMSException {

          Connection connection = null;
          Session session = null;
          connection = jmsTemplate.getConnectionFactory().createConnection();
          session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

          Queue queue = session.createQueue(dataQueue);
          QueueBrowser browser = session.createBrowser(queue);
      }


问:
Is there a way i can get a route parameter in vue
I am new to vuejs, i have my api in laravel having a route such as

Route::get('/get-song-details/{id}','SongsController@getSongDetails');. How do get this id in vue so that i can display only information about the selected song.

in the sample below, when i pass 1, i get information about song 1, and so on. how do i make it dynamic?

```<code>export default {
    data(){
        return {
            songs : []
        }
    },
    created(){
        axios.get('/api/get-song-details/1')
        .then(response => this.songs = response.data);
    }
};
</script>

</code>```

答:
asumming you are using vue-router, the route component should be declared so:

```<code>routes: [
  { path: '/song/:id', component: Song }
]
</code>```

then in your created method of Song component can get the id param:

```<code>created() {
  axios.get('/api/get-song-details/' + this.$route.params.id)
  ...
}
</code>```

Body:
I am new to vuejs, i have my api in laravel having a route such as

Route::get('/get-song-details/{id}','SongsController@getSongDetails');. How do get this id in vue so that i can display only information about the selected song.

in the sample below, when i pass 1, i get information about song 1, and so on. how do i make it dynamic?

export default {
    data(){
        return {
            songs : []
        }
    },
    created(){
        axios.get('/api/get-song-details/1')
        .then(response => this.songs = response.data);
    }
};
</script>

Body:
asumming you are using vue-router, the route component should be declared so:

routes: [
  { path: '/song/:id', component: Song }
]

then in your created method of Song component can get the id param:

created() {
  axios.get('/api/get-song-details/' + this.$route.params.id)
  ...
}


问:
How to create brick pattern in WPF in code?
This question is similar to others, but my research has not uncovered the answer I seek. I am trying to fill a rectangle with a brick pattern. I understand there is not a HatchBrush in WPF and if there was perhaps I would do this: HatchBrush brush = new HatchBrush(HatchStyle.DiagonalBrick,System.Drawing.Color.Black); But since there is not I am using  a DrawingBrush as follows, which fills the rectangle with a darkblue solid color. Where do I specify the DiagonalBrick?

```<code>Rectangle fillRect = new Rectangle();
//Try to fill fillRect with a pattern
Rect aRect = new Rect();
aRect.Width = fillRect.Width;
aRect.Height = fillRect.Height;
GeometryGroup rectangle = new GeometryGroup();
GeometryDrawing geomDrawing = new GeometryDrawing(Brushes.DarkBlue,null, rectangle);
DrawingBrush drawingBrush = new DrawingBrush();
rectangle.Children.Add(new RectangleGeometry(aRect, 0, 0));
geomDrawing.Geometry = rectangle;
drawingBrush.Drawing = geomDrawing;
fillRect.Fill = drawingBrush;
</code>```

答:
There's actually quite a few different ways to do this, but based on the code you've posted I'll assume you want to create your own geometry, using pixels as your coordinate system, and use that to paint a rectangle. This is one of those cases where WPF's flexibility means you have to be a lot more verbose than you would in previous platforms, but let's work through it...

The brick pattern can be achieved by creating a DrawingBrush containing a GeometryDrawing. The trick is to create two bricks of size <60,40> that are offset:

The problem now is the black background poking through. We can solve that by placing a third brick to the left of the one on the bottom, and then setting the DrawBrush's Viewport and Viewbox to the rectangle <0,0,60,80>, and then setting TileMode to "Tile". The code to do this is as follows:

```<code>var brickBrush = new DrawingBrush
{
    Viewport = new Rect(0, 0, 60, 80),
    ViewportUnits = BrushMappingMode.Absolute,
    Viewbox = new Rect(0, 0, 60, 80),
    ViewboxUnits = BrushMappingMode.Absolute,
    TileMode = TileMode.Tile,
    Drawing = new GeometryDrawing
    {
        Brush = new SolidColorBrush(Color.FromRgb(0xB1, 0x78, 0x33)),
        Geometry = new GeometryGroup
        {
            Children = new GeometryCollection(new Geometry[] {
                new RectangleGeometry(new Rect( 0,   0, 60, 40)),
                new RectangleGeometry(new Rect( 30, 40, 60, 40)),
                new RectangleGeometry(new Rect(-30, 40, 60, 40))
            }),
        },
        Pen = new Pen(new SolidColorBrush(Color.FromRgb(0xE1, 0xD7, 0xBD)), 5)
    }
};

theRectangle.Fill = brickBrush;
</code>```

Which will generate the following pattern:

As your WPF skill improves you'll eventually want to start doing stuff like this in XAML. For the purpose of comparison, here is the code needed to achieve the same fill:

```<code><Window.Resources>

    <DrawingBrush x:Key="BrickBrush" Viewport="0,0,60,80" ViewportUnits="Absolute" Viewbox="0,0,60,80" ViewboxUnits="Absolute" TileMode="Tile">
        <DrawingBrush.Drawing>
            <GeometryDrawing Brush="#B17833">
                <GeometryDrawing.Geometry>
                    <GeometryGroup>
                        <RectangleGeometry Rect="0,0,60,40" />
                        <RectangleGeometry Rect="30,40,60,40" />
                        <RectangleGeometry Rect="-30,40,60,40" />
                    </GeometryGroup>
                </GeometryDrawing.Geometry>
                <GeometryDrawing.Pen>
                    <Pen Thickness="5" Brush="#E1D7BD" />
                </GeometryDrawing.Pen>
            </GeometryDrawing>
        </DrawingBrush.Drawing>
    </DrawingBrush>

</Window.Resources>

<Rectangle Fill="{StaticResource BrickBrush}" />
</code>```

You've also alluded to wanting diagonal bricks, to do that you simply add a rotation transform to the DrawingBrush:

```<code>var brickBrush = new DrawingBrush
{
    Transform = new RotateTransform(45),
    ... etc ...
</code>```

Body:
This question is similar to others, but my research has not uncovered the answer I seek. I am trying to fill a rectangle with a brick pattern. I understand there is not a HatchBrush in WPF and if there was perhaps I would do this: HatchBrush brush = new HatchBrush(HatchStyle.DiagonalBrick,System.Drawing.Color.Black); But since there is not I am using  a DrawingBrush as follows, which fills the rectangle with a darkblue solid color. Where do I specify the DiagonalBrick?

Rectangle fillRect = new Rectangle();
//Try to fill fillRect with a pattern
Rect aRect = new Rect();
aRect.Width = fillRect.Width;
aRect.Height = fillRect.Height;
GeometryGroup rectangle = new GeometryGroup();
GeometryDrawing geomDrawing = new GeometryDrawing(Brushes.DarkBlue,null, rectangle);
DrawingBrush drawingBrush = new DrawingBrush();
rectangle.Children.Add(new RectangleGeometry(aRect, 0, 0));
geomDrawing.Geometry = rectangle;
drawingBrush.Drawing = geomDrawing;
fillRect.Fill = drawingBrush;

Body:
There's actually quite a few different ways to do this, but based on the code you've posted I'll assume you want to create your own geometry, using pixels as your coordinate system, and use that to paint a rectangle. This is one of those cases where WPF's flexibility means you have to be a lot more verbose than you would in previous platforms, but let's work through it...

The brick pattern can be achieved by creating a DrawingBrush containing a GeometryDrawing. The trick is to create two bricks of size <60,40> that are offset:

The problem now is the black background poking through. We can solve that by placing a third brick to the left of the one on the bottom, and then setting the DrawBrush's Viewport and Viewbox to the rectangle <0,0,60,80>, and then setting TileMode to "Tile". The code to do this is as follows:

var brickBrush = new DrawingBrush
{
    Viewport = new Rect(0, 0, 60, 80),
    ViewportUnits = BrushMappingMode.Absolute,
    Viewbox = new Rect(0, 0, 60, 80),
    ViewboxUnits = BrushMappingMode.Absolute,
    TileMode = TileMode.Tile,
    Drawing = new GeometryDrawing
    {
        Brush = new SolidColorBrush(Color.FromRgb(0xB1, 0x78, 0x33)),
        Geometry = new GeometryGroup
        {
            Children = new GeometryCollection(new Geometry[] {
                new RectangleGeometry(new Rect( 0,   0, 60, 40)),
                new RectangleGeometry(new Rect( 30, 40, 60, 40)),
                new RectangleGeometry(new Rect(-30, 40, 60, 40))
            }),
        },
        Pen = new Pen(new SolidColorBrush(Color.FromRgb(0xE1, 0xD7, 0xBD)), 5)
    }
};

theRectangle.Fill = brickBrush;

Which will generate the following pattern:

As your WPF skill improves you'll eventually want to start doing stuff like this in XAML. For the purpose of comparison, here is the code needed to achieve the same fill:

<Window.Resources>

    <DrawingBrush x:Key="BrickBrush" Viewport="0,0,60,80" ViewportUnits="Absolute" Viewbox="0,0,60,80" ViewboxUnits="Absolute" TileMode="Tile">
        <DrawingBrush.Drawing>
            <GeometryDrawing Brush="#B17833">
                <GeometryDrawing.Geometry>
                    <GeometryGroup>
                        <RectangleGeometry Rect="0,0,60,40" />
                        <RectangleGeometry Rect="30,40,60,40" />
                        <RectangleGeometry Rect="-30,40,60,40" />
                    </GeometryGroup>
                </GeometryDrawing.Geometry>
                <GeometryDrawing.Pen>
                    <Pen Thickness="5" Brush="#E1D7BD" />
                </GeometryDrawing.Pen>
            </GeometryDrawing>
        </DrawingBrush.Drawing>
    </DrawingBrush>

</Window.Resources>

<Rectangle Fill="{StaticResource BrickBrush}" />

You've also alluded to wanting diagonal bricks, to do that you simply add a rotation transform to the DrawingBrush:

var brickBrush = new DrawingBrush
{
    Transform = new RotateTransform(45),
    ... etc ...


问:
How understand the granularity and block in ClickHouse?
I am not clear about these two words.
Whether does one block have a fixed number of rows?
Whether is one block the minimum unit to read from disk?
Whether are different blocks stored in different files?
Whether is the range of one block bigger than granule? That means, one block can have several granules skip indices.</p>

答:
https://clickhouse.tech/docs/en/operations/table_engines/mergetree/#primary-keys-and-indexes-in-queries

Primary key is sparsed. By default it contains 1 value of each 8192 rows (= 1 granule).

Let's disable adaptive granularity (for the test) -- index_granularity_bytes=0

```<code>create table X (A Int64)
Engine=MergeTree order by A
settings index_granularity=16,index_granularity_bytes=0;

insert into X select * from numbers(32);
</code>```

index_granularity=16 -- 32 rows = 2 granule , primary index have 2 values 0 and 16

```<code>select marks, primary_key_bytes_in_memory from system.parts where table = 'X';
┌─marks─┬─primary_key_bytes_in_memory─┐
│     2 │                          16 │
└───────┴─────────────────────────────┘
</code>```

16 bytes === 2 values of INT64.

Adaptive index granularity means that granules size various. Because wide rows (many bytes) needs (for performance) fewer (<8192) rows in granule.

index_granularity_bytes = 10MB ~ 1k row * 8129. So each granule have 10MB. If rows size 100k (long Strings), granule will have 100 rows (not 8192).

Skip index granules GRANULARITY 3 -- means that an index will store one value for each 3 table granules.

```<code>create table X (A Int64, B Int64, INDEX IX1 (B) TYPE minmax GRANULARITY 4)
Engine=MergeTree order by A
settings index_granularity=16,index_granularity_bytes=0;

insert into X select number, number from numbers(128);
</code>```

128/16 = 8, table have 8 granules, INDEX IX1 stores 2 values of minmax (8/4)

So minmax index stores 2 values -- (0..63) and (64..128)

0..63 -- points to the first 4 table's granules.

64..128 -- points to the second 4 table' granules.

```<code>set send_logs_level='debug'
select * from X where B=77
[ 84 ] <Debug> dw.X (SelectExecutor): **Index `IX1` has dropped 1 granules**
[ 84 ] <Debug> dw.X (SelectExecutor): Selected 1 parts by date, 1 parts by key, **4 marks** to read from 1 ranges
</code>```

SelectExecutor checked skip index - 4 table granules can be skipped because 77 is not in 0..63 .
And another 4 granules must be read ( 4 marks ) because 77 in (64..128) -- some of that 4 granules have B=77.

Body:
https://clickhouse.tech/docs/en/operations/table_engines/mergetree/#primary-keys-and-indexes-in-queries

Primary key is sparsed. By default it contains 1 value of each 8192 rows (= 1 granule).

Let's disable adaptive granularity (for the test) -- index_granularity_bytes=0

create table X (A Int64)
Engine=MergeTree order by A
settings index_granularity=16,index_granularity_bytes=0;

insert into X select * from numbers(32);

index_granularity=16 -- 32 rows = 2 granule , primary index have 2 values 0 and 16

select marks, primary_key_bytes_in_memory from system.parts where table = 'X';
┌─marks─┬─primary_key_bytes_in_memory─┐
│     2 │                          16 │
└───────┴─────────────────────────────┘

16 bytes === 2 values of INT64.

Adaptive index granularity means that granules size various. Because wide rows (many bytes) needs (for performance) fewer (<8192) rows in granule.

index_granularity_bytes = 10MB ~ 1k row * 8129. So each granule have 10MB. If rows size 100k (long Strings), granule will have 100 rows (not 8192).

Skip index granules GRANULARITY 3 -- means that an index will store one value for each 3 table granules.

create table X (A Int64, B Int64, INDEX IX1 (B) TYPE minmax GRANULARITY 4)
Engine=MergeTree order by A
settings index_granularity=16,index_granularity_bytes=0;

insert into X select number, number from numbers(128);

128/16 = 8, table have 8 granules, INDEX IX1 stores 2 values of minmax (8/4)

So minmax index stores 2 values -- (0..63) and (64..128)

0..63 -- points to the first 4 table's granules.

64..128 -- points to the second 4 table' granules.

set send_logs_level='debug'
select * from X where B=77
[ 84 ] <Debug> dw.X (SelectExecutor): **Index `IX1` has dropped 1 granules**
[ 84 ] <Debug> dw.X (SelectExecutor): Selected 1 parts by date, 1 parts by key, **4 marks** to read from 1 ranges

SelectExecutor checked skip index - 4 table granules can be skipped because 77 is not in 0..63 .
And another 4 granules must be read ( 4 marks ) because 77 in (64..128) -- some of that 4 granules have B=77.


问:
Maintain Dynamic HTML made with jquery after form validation triggers in ASP.NET MVC
I have this table in which I am able to generate rows for through a jquery click event.

Is it possible to keep my dynamic html after the pages model validation triggers with just the basic jquery library or should I use something else like ajax or the like in my MVC project?

答: If you mean, keep that state after a form has been submitted, you'll need to save that HTML fragment somehow e.g in a $_SESSION variable and then reload it on the next page.</p>


问:
Implementing roles with custom storage provider for Identity
Recently, I was able to successfully implement authentication (SSO with ADFS using WS-Federation) for an app. Now, I am trying to understand and get authorization working, so this question may be unclear.

I'm using this topic to implement roles with custom storage provider for Identity without entity framework.

I've got custom User and Role models set up, along with the custom UserStore and RoleStore that implement the appropriate interfaces. There's also tables for roles ready to be used.

I run into issues when trying to access either an [Authorized] or [Authorized(Roles = "RoleName")]. As expected, the actions require me to authenticate with ADFS, but when I submit correct credentials the login loops a few times and displays the ADFS error page. This problem with ADFS is not present without the role implementation. UserStore and RoleStore does not implement code yet, but the app never tries uses any of their methods.

I tried implementing different options in Startup.cs, some of which I have commented out, and reordering services. Inserting dummy code into the RoleStore didn't help either. Basically, I just want to be able to add role checks from custom storage using Identity. I can get the username of the user at any time after they log in to find their role.

Startup.cs ConfigureServices method is where it's most unclear for me, and probably the most likely place where something is set up incorrectly.

Startup.cs ConfigureServices():

```<code>public void ConfigureServices(IServiceCollection services)
{
    // Add identity types
    services.AddIdentity<User, Role>()
        //.AddUserManager<UserManager<User>>() // some other settings I've tried ...
        //.AddRoleManager<RoleManager<Role>>()
        //.AddUserStore<UserStore>()
        //.AddRoleStore<RoleStore>()
        //.AddRoles<Role>()
        .AddDefaultTokenProviders();

    // Identity Services
    services.AddTransient<IUserStore<User>, UserStore>();
    services.AddTransient<IRoleStore<Role>, RoleStore>();
    //for SQL connection, I'll be using a different one (not the one from the link to topic)

    //dependency injection
    services.AddScoped<ISomeService, SomeService>();

    services.AddAuthentication(sharedOptions =>
    {
        // authentication options...
    })
    .AddWsFederation(options =>
    {
        // wsfed options...
    })
    .AddCookie(options =>
    {
        options.Cookie.Name = "NameOfCookie";
        //options.LoginPath = "/Access/Login"; //app function the same without this
        options.LogoutPath = "/Access/Logout";
        options.AccessDeniedPath = "/Access/AccessDenied";
        options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
        options.SlidingExpiration = true;
    });

    services.AddControllersWithViews();
}
</code>```

答:
Another way of doing this is to add a custom attribute store to ADFS.

Then the roles etc. that you require from the custom attribute store can be configured as claims.

Body:
Recently, I was able to successfully implement authentication (SSO with ADFS using WS-Federation) for an app. Now, I am trying to understand and get authorization working, so this question may be unclear.

I'm using this topic to implement roles with custom storage provider for Identity without entity framework.

I've got custom User and Role models set up, along with the custom UserStore and RoleStore that implement the appropriate interfaces. There's also tables for roles ready to be used.

I run into issues when trying to access either an [Authorized] or [Authorized(Roles = "RoleName")]. As expected, the actions require me to authenticate with ADFS, but when I submit correct credentials the login loops a few times and displays the ADFS error page. This problem with ADFS is not present without the role implementation. UserStore and RoleStore does not implement code yet, but the app never tries uses any of their methods.

I tried implementing different options in Startup.cs, some of which I have commented out, and reordering services. Inserting dummy code into the RoleStore didn't help either. Basically, I just want to be able to add role checks from custom storage using Identity. I can get the username of the user at any time after they log in to find their role.

Startup.cs ConfigureServices method is where it's most unclear for me, and probably the most likely place where something is set up incorrectly.

Startup.cs ConfigureServices():

public void ConfigureServices(IServiceCollection services)
{
    // Add identity types
    services.AddIdentity<User, Role>()
        //.AddUserManager<UserManager<User>>() // some other settings I've tried ...
        //.AddRoleManager<RoleManager<Role>>()
        //.AddUserStore<UserStore>()
        //.AddRoleStore<RoleStore>()
        //.AddRoles<Role>()
        .AddDefaultTokenProviders();

    // Identity Services
    services.AddTransient<IUserStore<User>, UserStore>();
    services.AddTransient<IRoleStore<Role>, RoleStore>();
    //for SQL connection, I'll be using a different one (not the one from the link to topic)

    //dependency injection
    services.AddScoped<ISomeService, SomeService>();

    services.AddAuthentication(sharedOptions =>
    {
        // authentication options...
    })
    .AddWsFederation(options =>
    {
        // wsfed options...
    })
    .AddCookie(options =>
    {
        options.Cookie.Name = "NameOfCookie";
        //options.LoginPath = "/Access/Login"; //app function the same without this
        options.LogoutPath = "/Access/Logout";
        options.AccessDeniedPath = "/Access/AccessDenied";
        options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
        options.SlidingExpiration = true;
    });

    services.AddControllersWithViews();
}


问:
Vue Store Methods inside Array/Object
let's say we have 5 buttons with exactly same features. This is why I thought rather than copying and pasting these 5 buttons why I wouldn't use v-for.

```<code>methods: {
    a() {},
    b() {},
    ...
}
</code>```

Rather than

```<code><v-btn block color="primary" class="my-1" @click="a">A</v-btn>
<v-btn block color="primary" class="my-1" @click="b">B</v-btn>
<v-btn block color="primary" class="my-1" @click="c">C</v-btn>
<v-btn block color="primary" class="my-1" @click="d">D</v-btn>
<v-btn block color="primary" class="my-1" @click="e">E</v-btn>
</code>```

Tried to use

```<code> <v-btn v-for="(button, index) in buttons" :key="index"
      block color="primary" class="my-1"
      @click="button.click">{{button.text}}
 </v-btn>

buttons: [
        { click: this.a, text: "A"},
        { click: this.b, text: "B"},
        { click: this.c, text: "C"},
        { click: this.d, text: "D"},
        { click: this.e, text: "E"},
      ]
</code>```

It works as expected, however when I try to render this buttons object I am getting something like this. Why clicks are not there ?

```<code>[ { "text": "A" }, { "text": "B" }, { "text": "C" }, { "text": "D" }, { "text": "E" } ]
</code>```

Let's go one more step, and let's add a button with dynamic text (another data field)

```<code>boolean: true
F: "data1"

f() {boolean ? this.F = "data1" : "data2"}
<v-btn block color="primary" class="my-1" @click="F">{{F}}</v-btn>
</code>```

This time I am getting

```<code>[ { "text": "A" }, { "text": "B" }, { "text": "C" }, { "text": "D" }, { "text": "E" }, {} ]
</code>```

The button text doesn't change, however when I render {{F}} I am seeing the data changes.

What is the reason behind this, and how to handle this kind of situations ?

I have tried to create a method such as setButtons and returning buttons array and set buttons field, this time when I render buttons I am getting whole object as expected but when the data changes such as F, object isn't updated again.

答:
If my understanding is correct you want to render a method into a @click from a for-loop?

you can create a helper function to deal with it.

here bindFunction() will take the string button.click and return a function

new Vue({
  el: "#app",
  data: {
        buttons: [
        { click: "toggleA", text: "A" },
        { click: "toggleB", text: "B" },
        { click: "toggleC", text: "C" },
        { click: "toggleD", text: "D" },
        { click: "toggleE", text: "E" }
      ]
  },
  methods: {
   bindFunction(f) {
      this[f]();
    },
    toggleA() {
      console.log("toggleA");
    },
    toggleB() {
      console.log("toggleB");
    },
    toggleC() {
      console.log("toggleC");
    },
    toggleD() {
      console.log("toggleD");
    },
    toggleE() {
      console.log("toggleE");
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div v-for="(button, index) of buttons" :key="index">
      <button @click="bindFunction(button.click)">{{button.text}}</button>
    </div>
</div></code>```

Title: Vue Store Methods inside Array/Object

Body:
let's say we have 5 buttons with exactly same features. This is why I thought rather than copying and pasting these 5 buttons why I wouldn't use v-for.

methods: {
    a() {},
    b() {},
    ...
}

Rather than

<v-btn block color="primary" class="my-1" @click="a">A</v-btn>
<v-btn block color="primary" class="my-1" @click="b">B</v-btn>
<v-btn block color="primary" class="my-1" @click="c">C</v-btn>
<v-btn block color="primary" class="my-1" @click="d">D</v-btn>
<v-btn block color="primary" class="my-1" @click="e">E</v-btn>

Tried to use

 <v-btn v-for="(button, index) in buttons" :key="index"
      block color="primary" class="my-1"
      @click="button.click">{{button.text}}
 </v-btn>

buttons: [
        { click: this.a, text: "A"},
        { click: this.b, text: "B"},
        { click: this.c, text: "C"},
        { click: this.d, text: "D"},
        { click: this.e, text: "E"},
      ]

It works as expected, however when I try to render this buttons object I am getting something like this. Why clicks are not there ?

[ { "text": "A" }, { "text": "B" }, { "text": "C" }, { "text": "D" }, { "text": "E" } ]

Let's go one more step, and let's add a button with dynamic text (another data field)

boolean: true
F: "data1"

f() {boolean ? this.F = "data1" : "data2"}
<v-btn block color="primary" class="my-1" @click="F">{{F}}</v-btn>

This time I am getting

[ { "text": "A" }, { "text": "B" }, { "text": "C" }, { "text": "D" }, { "text": "E" }, {} ]

The button text doesn't change, however when I render {{F}} I am seeing the data changes.

What is the reason behind this, and how to handle this kind of situations ?

I have tried to create a method such as setButtons and returning buttons array and set buttons field, this time when I render buttons I am getting whole object as expected but when the data changes such as F, object isn't updated again.

Body:
If my understanding is correct you want to render a method into a @click from a for-loop?

you can create a helper function to deal with it.

here bindFunction() will take the string button.click and return a function

new Vue({
  el: "#app",
  data: {
        buttons: [
        { click: "toggleA", text: "A" },
        { click: "toggleB", text: "B" },
        { click: "toggleC", text: "C" },
        { click: "toggleD", text: "D" },
        { click: "toggleE", text: "E" }
      ]
  },
  methods: {
   bindFunction(f) {
      this[f]();
    },
    toggleA() {
      console.log("toggleA");
    },
    toggleB() {
      console.log("toggleB");
    },
    toggleC() {
      console.log("toggleC");
    },
    toggleD() {
      console.log("toggleD");
    },
    toggleE() {
      console.log("toggleE");
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div v-for="(button, index) of buttons" :key="index">
      <button @click="bindFunction(button.click)">{{button.text}}</button>
    </div>
</div>


问:
What is the best way to calculate maximum and minimum values for one list, for each distinct value of another list in Python?
Say I have three lists of paired numeric data in Python. The lists are for the day of year (number between 1-365), the hour of day (number between 0-24), and the corresponding temperature at that time. I have provided example lists below:

```<code>day_of_year = [1,1,1,1,1,1,1,1,1,1,1,1,1,1]      #day = Jan 1 in this example
hour_of_day = [2,4,6,8,10,12,14,16,18,20,22,24]
temperature =[23.1,22.0,24.1,26.5,23.8,40.1,32.7,41.3,29.4,36.4,22.0,24.1]

</code>```

I have these hourly paired data for a location for an entire year (I've just shown simplified lists above). So for each day I have 24 day_of_year values (that are just the same number repeated, in this example the day = 1) and 24 temperature values since they're hourly data. I'm trying to design a for loop that allows me to iterate through these data to calculate and use the maximum and minimum temperature for each day of year, since another function that my code uses needs to call on those values. What would be the best way to reference all the temperature values where day_of_year are the same to calculate max and min temperatures for every day.

I have a function that takes the following inputs:

minimum_temp_today, minimum_temp_tomorrow, maximum_temp_today, maximum_temp_yesterday

I need to figure out how to pull out those values for each day of the year. I am looking for suggestions on the best way to do this. Any suggestions/tips would be super appreciated!

答:
There are a lot of ways you could approach this, depending on what data structures you want to use. If you don't care about when the min and max occur, then personally I'd do something like this.

```<code>from collections import defaultdict

daily_temps = defaultdict(list)
for day, value in zip(day_of_year, temperature):
     daily_temps[day].append(value)

ranges = dict()
for day, values in temps.items():
    ranges[day] = (min(values), max(values))
</code>```

Basically, you're constructing an intermediate dict that maps each day of the year to a list of all the measurements for that day. Then in the second step you use that dict to create your final dict which maps each day of the year to a tuple which is the minimum and maximum value recorded for that day.

Body:
Say I have three lists of paired numeric data in Python. The lists are for the day of year (number between 1-365), the hour of day (number between 0-24), and the corresponding temperature at that time. I have provided example lists below:

day_of_year = [1,1,1,1,1,1,1,1,1,1,1,1,1,1]      #day = Jan 1 in this example
hour_of_day = [2,4,6,8,10,12,14,16,18,20,22,24]
temperature =[23.1,22.0,24.1,26.5,23.8,40.1,32.7,41.3,29.4,36.4,22.0,24.1]

I have these hourly paired data for a location for an entire year (I've just shown simplified lists above). So for each day I have 24 day_of_year values (that are just the same number repeated, in this example the day = 1) and 24 temperature values since they're hourly data. I'm trying to design a for loop that allows me to iterate through these data to calculate and use the maximum and minimum temperature for each day of year, since another function that my code uses needs to call on those values. What would be the best way to reference all the temperature values where day_of_year are the same to calculate max and min temperatures for every day.

I have a function that takes the following inputs:

minimum_temp_today, minimum_temp_tomorrow, maximum_temp_today, maximum_temp_yesterday

I need to figure out how to pull out those values for each day of the year. I am looking for suggestions on the best way to do this. Any suggestions/tips would be super appreciated!

Body:
There are a lot of ways you could approach this, depending on what data structures you want to use. If you don't care about when the min and max occur, then personally I'd do something like this.

from collections import defaultdict

daily_temps = defaultdict(list)
for day, value in zip(day_of_year, temperature):
     daily_temps[day].append(value)

ranges = dict()
for day, values in temps.items():
    ranges[day] = (min(values), max(values))

Basically, you're constructing an intermediate dict that maps each day of the year to a list of all the measurements for that day. Then in the second step you use that dict to create your final dict which maps each day of the year to a tuple which is the minimum and maximum value recorded for that day.


问:
Where are Ruby on Rails 6 scaffold templates located?
I'm starting work on a new Ruby on Rails 6 app and I need to find the default scaffold_controller template and also the default view files: _form.html.erb, index.hmtl.erb, edit.html.erb, etc...
so that I can customize them by placing them in the /lib/templates folders.

Where are the default templates located so that I can copy them to the /lib/templates folders and modify them?

Thanks !

答:
Default view template files are located at: https://github.com/rails/rails/tree/master/railties/lib/rails/generators/erb/scaffold/templates
Default controller template file is located at:
https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb.tt

In your app, put the customized view templates at: lib/templates/erb/scaffold/
Put the customized controller template at: lib/rails/scaffold_controller/

I hope this helps someone.


问:
Landscape virtual keyboard in android 2.3.3
I am trying to make changes in source code of virtual keyboard in android source code 2.3.3.
As you all know that in android 2.3 there is no LANDSCAPE mode of virtual keyboard.
when we try to pop up keyboard in landscape mode only a white line appears at bottom.

Can anybody tell me about this behavior.
And please also tell me how can I achieve this.
I will appreciate any help.

Thank you.

答:
maybe the keyboard you are trying to edit does not have an XML layout file yet?

quoted from the hello world example found here

Landscape layout

When you want a different design for landscape, put your layout XML file inside /res/layout-land. Android will automatically look here when the layout changes. Without this special landscape layout defined, Android will stretch the default layout.


问:
Maven version ordering for alpha and a
The answer https://stackoverflow.com/a/31482463/927493 explains the order of Maven versions. Following https://blog.soebes.de/blog/2017/02/04/apache-maven-how-version-comparison-works/, you can compare versions on the command line. I got the following results:

```<code>C:\coprogramme\apache-maven-3.5.0\lib>java -jar maven-artifact-3.5.0.jar 2.0.0 2.0.0-a
Display parameters as parsed by Maven (in canonical form) and comparison result:
1. 2.0.0 == 2
   2.0.0 < 2.0.0-a
2. 2.0.0-a == 2-a

C:\coprogramme\apache-maven-3.5.0\lib>java -jar maven-artifact-3.5.0.jar 2.0.0 2.0.0-alpha
Display parameters as parsed by Maven (in canonical form) and comparison result:
1. 2.0.0 == 2
   2.0.0 > 2.0.0-alpha
2. 2.0.0-alpha == 2-alpha
</code>```

Following the answer and also the Javadoc in https://github.com/apache/maven/blob/master/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java, the version parts alpha and a should be equal, which is apparently not the case.

Can anyone explain this to me?

答:
Despite what the documentation says, it appears that a is a synonym for alpha only when it is immediately followed by a digit. So

2.0.0-a1 is equivalent to 2.0.0-alpha1 and 2.0.0-alpha-1 (but not 2.0.0-alpha.1)

the a in 2.0.0-a, 2.0.0-a.1 or 2.0.0-a-1 is an "unknown qualifier", not equivalent to 2.0.0-alpha-1, and sorted after all the known qualifiers

The behaviour appears because ComparableVersion has two ways of defining aliases, in the inner class that deals with string components:

```<code>private static final List<String> QUALIFIERS =
        Arrays.asList( "alpha", "beta", "milestone", "rc", "snapshot", "", "sp"  );

private static final Properties ALIASES = new Properties();
static
{
    ALIASES.put( "ga", "" );
    ALIASES.put( "final", "" );
    ALIASES.put( "release", "" );
    ALIASES.put( "cr", "rc" );
}

// ...

StringItem( String value, boolean followedByDigit )
{
    if ( followedByDigit && value.length() == 1 )
    {
        // a1 = alpha-1, b1 = beta-1, m1 = milestone-1
        switch ( value.charAt( 0 ) )
        {
            case 'a':
                value = "alpha";
                break;
            case 'b':
                value = "beta";
                break;
            case 'm':
                value = "milestone";
                break;
            default:
        }
    }
    this.value = ALIASES.getProperty( value , value );
}
</code>```

A special-case scenario for single-letter qualifiers a, b, and m, that is only triggered if followedByDigit==true, and that only happens when the qualifier was terminated by the next character being a digit.

A list of aliases: ga, final and release are exactly equivalent to the empty string (with the latter being the canonical form), and cr's canonical form is rc. This part behaves as the OP expects.

I would guess that this is based on observed version usage, where sometimes letters are used literally as versions (e.g. OpenSSL used to use a trailing letter or two to number patch releases, such as 0.9.7m or 0.9.8zh), while alpha, beta and milestone releases always have a release number in practice, and projects using a short version aren't going to put any extra characters in: so a by itself meaning "alpha" never actually occurs.

It's a shame it's not documented properly!

Title: Maven version ordering for alpha and a

Body:
The answer https://stackoverflow.com/a/31482463/927493 explains the order of Maven versions. Following https://blog.soebes.de/blog/2017/02/04/apache-maven-how-version-comparison-works/, you can compare versions on the command line. I got the following results:

C:\coprogramme\apache-maven-3.5.0\lib>java -jar maven-artifact-3.5.0.jar 2.0.0 2.0.0-a
Display parameters as parsed by Maven (in canonical form) and comparison result:
1. 2.0.0 == 2
   2.0.0 < 2.0.0-a
2. 2.0.0-a == 2-a

C:\coprogramme\apache-maven-3.5.0\lib>java -jar maven-artifact-3.5.0.jar 2.0.0 2.0.0-alpha
Display parameters as parsed by Maven (in canonical form) and comparison result:
1. 2.0.0 == 2
   2.0.0 > 2.0.0-alpha
2. 2.0.0-alpha == 2-alpha

Following the answer and also the Javadoc in https://github.com/apache/maven/blob/master/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java, the version parts alpha and a should be equal, which is apparently not the case.

Can anyone explain this to me?

Body:
Despite what the documentation says, it appears that a is a synonym for alpha only when it is immediately followed by a digit. So

2.0.0-a1 is equivalent to 2.0.0-alpha1 and 2.0.0-alpha-1 (but not 2.0.0-alpha.1)

the a in 2.0.0-a, 2.0.0-a.1 or 2.0.0-a-1 is an "unknown qualifier", not equivalent to 2.0.0-alpha-1, and sorted after all the known qualifiers

The behaviour appears because ComparableVersion has two ways of defining aliases, in the inner class that deals with string components:

private static final List<String> QUALIFIERS =
        Arrays.asList( "alpha", "beta", "milestone", "rc", "snapshot", "", "sp"  );

private static final Properties ALIASES = new Properties();
static
{
    ALIASES.put( "ga", "" );
    ALIASES.put( "final", "" );
    ALIASES.put( "release", "" );
    ALIASES.put( "cr", "rc" );
}

// ...

StringItem( String value, boolean followedByDigit )
{
    if ( followedByDigit && value.length() == 1 )
    {
        // a1 = alpha-1, b1 = beta-1, m1 = milestone-1
        switch ( value.charAt( 0 ) )
        {
            case 'a':
                value = "alpha";
                break;
            case 'b':
                value = "beta";
                break;
            case 'm':
                value = "milestone";
                break;
            default:
        }
    }
    this.value = ALIASES.getProperty( value , value );
}

A special-case scenario for single-letter qualifiers a, b, and m, that is only triggered if followedByDigit==true, and that only happens when the qualifier was terminated by the next character being a digit.

A list of aliases: ga, final and release are exactly equivalent to the empty string (with the latter being the canonical form), and cr's canonical form is rc. This part behaves as the OP expects.

I would guess that this is based on observed version usage, where sometimes letters are used literally as versions (e.g. OpenSSL used to use a trailing letter or two to number patch releases, such as 0.9.7m or 0.9.8zh), while alpha, beta and milestone releases always have a release number in practice, and projects using a short version aren't going to put any extra characters in: so a by itself meaning "alpha" never actually occurs.

It's a shame it's not documented properly!


问:
Mongoose find and update all
So currently I am using this

```<code>await User.findOneAndUpdate({email: req.user.email }, {lastLoad: 'dfConsignee'});
</code>```

But I want to be able to update all users with the same truckNumber to be updated when the form is submitted.

SO I tried using this

```<code>await User.update({truckNumber: truckNumber }, {lastLoad: 'dfConsignee'});
</code>```

But this only updated the active user for some reason. How would I go about updating all the accounts with the same truck number on form completion?

Thank you guys in advance <3

Edit ----------------------------------------------------------------------------------------------------------------------------

By active user, I meant logged in user.

Mongoose Schema:

```<code>const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    },
    isVerified: {
        type: Boolean,
        default: false
    },
    profilePic: {
        type: String,
        default: 'abc'
    },
    truckDriver: {
        type: Boolean,
        default: false
    },
    truckNumber: {
        type: Number
    },
    admin: {
        type: Boolean,
        default: false
    },
    customer: {
        type: Boolean,
        default: false
    },
    loadPlanning: {
        type: Boolean,
        default: false
    },
    lastLoad: {
        type: String,
        default: "dfConsignee"
    }
});

const User = mongoose.model('User', UserSchema);

module.exports = User;
</code>```

Sample Document:

```<code>{"_id":{"$oid":"aaaaaaaaaaaaaaaa"},
"isVerified":true,
"profilePic":"abc",
"truckDriver":true,
"admin":false,
"customer":false,
"loadPlanning":false,
"lastLoad":"aAtShipper",
"name":"Nicholas Cage",
"email":"NicholasCage@thegreatestactorever.com",
"password":"password",
"date":{"$date":{"$numberLong":"1580858993547"}},"__v":{"$numberInt":"0"},
"truckNumber":"123",}
</code>```

To add a bit more clarification, when the form is submitted, it will pull the logged in users truck number. When the form is submitted, I am wanting everyone who shares that same truck number to have their value in lastLoad be updated as well.

答:
OMG Finally figured this out :D

I thought that when I restarted Nginx it would restart the app running on the server ( I would see front end changes doing this, but the back end changes wouldn't show up), once I restarted PM2 all the back end changes came along with it.

Thank you everyone for the help :D

Now "await Users.updateMany({truckNumber: req.user.truckNumber}, {lastLoad: 'aAtShipper'}" will update all accounts with a shared truck Number :D

Title: Mongoose find and update all

Body:
So currently I am using this

await User.findOneAndUpdate({email: req.user.email }, {lastLoad: 'dfConsignee'});

But I want to be able to update all users with the same truckNumber to be updated when the form is submitted.

SO I tried using this

await User.update({truckNumber: truckNumber }, {lastLoad: 'dfConsignee'});

But this only updated the active user for some reason. How would I go about updating all the accounts with the same truck number on form completion?

Thank you guys in advance <3

Edit ----------------------------------------------------------------------------------------------------------------------------

By active user, I meant logged in user.

Mongoose Schema:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    },
    isVerified: {
        type: Boolean,
        default: false
    },
    profilePic: {
        type: String,
        default: 'abc'
    },
    truckDriver: {
        type: Boolean,
        default: false
    },
    truckNumber: {
        type: Number
    },
    admin: {
        type: Boolean,
        default: false
    },
    customer: {
        type: Boolean,
        default: false
    },
    loadPlanning: {
        type: Boolean,
        default: false
    },
    lastLoad: {
        type: String,
        default: "dfConsignee"
    }
});

const User = mongoose.model('User', UserSchema);

module.exports = User;

Sample Document:

{"_id":{"$oid":"aaaaaaaaaaaaaaaa"},
"isVerified":true,
"profilePic":"abc",
"truckDriver":true,
"admin":false,
"customer":false,
"loadPlanning":false,
"lastLoad":"aAtShipper",
"name":"Nicholas Cage",
"email":"NicholasCage@thegreatestactorever.com",
"password":"password",
"date":{"$date":{"$numberLong":"1580858993547"}},"__v":{"$numberInt":"0"},
"truckNumber":"123",}

To add a bit more clarification, when the form is submitted, it will pull the logged in users truck number. When the form is submitted, I am wanting everyone who shares that same truck number to have their value in lastLoad be updated as well.


问:
How can I format this date into Day - Month - Year
```<code>def UpdateDate(WorstDate):
    Day = WorstDate[5:]
    Month = WorstDate[2:6]
    Year = WorstDate[:2]
    return Day + "-" + Month + "-" + Year
print(UpdateDate("202011Jan"))
</code>```

I keep getting (1Jan-2011-20)
I'm no pro so any advice would be appreciated.

答:
Below is the updated solution:

```<code>
    def UpdateDate(WorstDate):
        Day = WorstDate[4:6]
        Month = WorstDate[6:]
        Year = WorstDate[:4]
        return Day + "-" + Month + "-" + Year

    print(UpdateDate("202011Jan"))

</code>```

Output:

11-Jan-2020

Body:
def UpdateDate(WorstDate):
    Day = WorstDate[5:]
    Month = WorstDate[2:6]
    Year = WorstDate[:2]
    return Day + "-" + Month + "-" + Year
print(UpdateDate("202011Jan"))

I keep getting (1Jan-2011-20)
I'm no pro so any advice would be appreciated.

Body:
Below is the updated solution:

    def UpdateDate(WorstDate):
        Day = WorstDate[4:6]
        Month = WorstDate[6:]
        Year = WorstDate[:4]
        return Day + "-" + Month + "-" + Year

    print(UpdateDate("202011Jan"))

Output:

11-Jan-2020


问:
Java Generics Wildcards Question
I'm facing some problems with Generics when using Google Guava's excellent Multimap. I have a type Handler defined as such

```<code>public interface Handler<T extends Serializable> {
    void handle(T t);
}
</code>```

In another class I've defined a multimap that maps a String to a collection of Handlers.

```<code>private Multimap<String, Handler<? extends Serializable>> multimap =
    ArrayListMultimap.create();
</code>```

Now when I try to do stuff with the multimap, I'm getting compiler errors. My first attempt looked like this:

```<code>public <T extends Serializable> void doStuff1(String s, T t)  {
    Collection<Handler<T>> collection = multimap.get(s);
    for (Handler<T> handler : collection) {
        handler.handle(t);
    }
}
</code>```

which resulted in the following error.

Type mismatch: cannot convert from Collection<Handler<? extends Serializable>>
to Collection<Handler<T>>

Afterwards, I tried to code it like this

```<code>public void doStuff2(String s, Serializable serializable)  {
    Collection<Handler<? extends Serializable>> collection = multimap.get(s);
    for (Handler<? extends Serializable> handler : collection) {
        handler.handle(serializable);
    }
}
</code>```

which unfortunately failed as well:

The method handle(capture#1-of ? extends Serializable) in the type
Handler<capture#1-of ? extends Serializable> is not applicable for the arguments
(Serializable)

Any help would be greatly appreciated. Thanks.

Update:

The only way I have managed to fix this is by suppressing compiler warnings. Given the following handler:

```<code>public interface Handler<T extends Event> {
    void handle(T t);

    Class<T> getType();
}
</code>```

I can write the event bus as such.

```<code>public class EventBus {

    private Multimap<Class<?>, Handler<?>> multimap = ArrayListMultimap.create();

    public <T extends Event> void subscribe(Handler<T> handler) {
        multimap.put(handler.getType(), handler);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void publish(Event event)  {
        Collection<Handler<?>> collection = multimap.get(event.getClass());
        for (Handler handler : collection) {
            handler.handle(event);
        }
    }
}
</code>```

I guess there's no way to handle this with less or even without @SuppressWarnings?

答:
I modified your updated code a bit.
Now it works without @SuppressWarnings.

I've made some assumptions, of course.

But I hope it will be helpful.

```<code>public interface Handler<T extends Event> {
    //void handle(T t);
    // It seems you won't need dependency of T in this method implementation.
    // So, you can use generic method here.
    <S extends Event> void handle(S s);

    Class<T> getType();
}
</code>```

Modified EventBus.

```<code>public class EventBus {
    //private Multimap<Class<?>, Handler<?>> multimap = ArrayListMultimap.create();
    // It seems you don't need anything except Event here.
    // So. Logicaly more correct to use the bounded wildcard.
    private Multimap<Class<? extends Event>, Handler<? extends Event>>
        multimap = ArrayListMultimap.create();

    //public <T extends Event> void subscribe(Handler<T> handler) {
    // You don't need to use generic method here.
    // Because T is never used in method implementation.
    // Wildcard fits simpler.
    public void subscribe(Handler<? extends Event> handler) {
        multimap.put(handler.getType(), handler);
    }

    //@SuppressWarnings({ "rawtypes", "unchecked" })
    public void publish(Event event)  {
        //Collection<Handler<?>> collection = multimap.get(event.getClass());
        // The bounded wildcard again.
        Collection<Handler<? extends Event>>
            collection = multimap.get(event.getClass());
        //for (Handler handler : collection) {
        for (Handler<? extends Event> handler : collection) {
            handler.handle(event);
        }
    }
}
</code>```

And some more code, just to complete the example.

```<code>public class Main {

    public static void main(String[] args) {
        EventBus bus = new EventBus();

        bus.subscribe(new Handler<MyEvent> () {

            public <S extends Event> void handle(S s) {
                System.out.println(s);
            }

            public Class<MyEvent> getType() {
                return MyEvent.class;
            }
        });

        bus.publish(new MyEvent());
    }
}

class MyEvent implements Event {

// Event implementation ...

}
</code>```

The program output looks like this:

```<code>MyEvent@12276af2
</code>```

Title: Java Generics Wildcards Question

Body:
I'm facing some problems with Generics when using Google Guava's excellent Multimap. I have a type Handler defined as such

public interface Handler<T extends Serializable> {
    void handle(T t);
}

In another class I've defined a multimap that maps a String to a collection of Handlers.

private Multimap<String, Handler<? extends Serializable>> multimap =
    ArrayListMultimap.create();

Now when I try to do stuff with the multimap, I'm getting compiler errors. My first attempt looked like this:

public <T extends Serializable> void doStuff1(String s, T t)  {
    Collection<Handler<T>> collection = multimap.get(s);
    for (Handler<T> handler : collection) {
        handler.handle(t);
    }
}

which resulted in the following error.

Type mismatch: cannot convert from Collection<Handler<? extends Serializable>>
to Collection<Handler<T>>

Afterwards, I tried to code it like this

public void doStuff2(String s, Serializable serializable)  {
    Collection<Handler<? extends Serializable>> collection = multimap.get(s);
    for (Handler<? extends Serializable> handler : collection) {
        handler.handle(serializable);
    }
}

which unfortunately failed as well:

The method handle(capture#1-of ? extends Serializable) in the type
Handler<capture#1-of ? extends Serializable> is not applicable for the arguments
(Serializable)

Any help would be greatly appreciated. Thanks.

Update:

The only way I have managed to fix this is by suppressing compiler warnings. Given the following handler:

public interface Handler<T extends Event> {
    void handle(T t);

    Class<T> getType();
}

I can write the event bus as such.

public class EventBus {

    private Multimap<Class<?>, Handler<?>> multimap = ArrayListMultimap.create();

    public <T extends Event> void subscribe(Handler<T> handler) {
        multimap.put(handler.getType(), handler);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void publish(Event event)  {
        Collection<Handler<?>> collection = multimap.get(event.getClass());
        for (Handler handler : collection) {
            handler.handle(event);
        }
    }
}

I guess there's no way to handle this with less or even without @SuppressWarnings?

Body:
I modified your updated code a bit.
Now it works without @SuppressWarnings.

I've made some assumptions, of course.

But I hope it will be helpful.

public interface Handler<T extends Event> {
    //void handle(T t);
    // It seems you won't need dependency of T in this method implementation.
    // So, you can use generic method here.
    <S extends Event> void handle(S s);

    Class<T> getType();
}

Modified EventBus.

public class EventBus {
    //private Multimap<Class<?>, Handler<?>> multimap = ArrayListMultimap.create();
    // It seems you don't need anything except Event here.
    // So. Logicaly more correct to use the bounded wildcard.
    private Multimap<Class<? extends Event>, Handler<? extends Event>>
        multimap = ArrayListMultimap.create();

    //public <T extends Event> void subscribe(Handler<T> handler) {
    // You don't need to use generic method here.
    // Because T is never used in method implementation.
    // Wildcard fits simpler.
    public void subscribe(Handler<? extends Event> handler) {
        multimap.put(handler.getType(), handler);
    }

    //@SuppressWarnings({ "rawtypes", "unchecked" })
    public void publish(Event event)  {
        //Collection<Handler<?>> collection = multimap.get(event.getClass());
        // The bounded wildcard again.
        Collection<Handler<? extends Event>>
            collection = multimap.get(event.getClass());
        //for (Handler handler : collection) {
        for (Handler<? extends Event> handler : collection) {
            handler.handle(event);
        }
    }
}

And some more code, just to complete the example.

public class Main {

    public static void main(String[] args) {
        EventBus bus = new EventBus();

        bus.subscribe(new Handler<MyEvent> () {

            public <S extends Event> void handle(S s) {
                System.out.println(s);
            }

            public Class<MyEvent> getType() {
                return MyEvent.class;
            }
        });

        bus.publish(new MyEvent());
    }
}

class MyEvent implements Event {

// Event implementation ...

}

The program output looks like this:

MyEvent@12276af2


问:
How to trigger the Sonic Bomb device to shake from a third-party Android app?
I recently purchased a Sonic Bomb vibration-based alarm device, controllable from phones.

However, there does not seem to be a public API available for controlling it.

Is there any way to trigger device shakes from third-party apps, without needing to reverse-engineer the communication protocol?

答:
I found out how to do this by finding a list of Android intents received by the official Sonic Bomb app.

The two Android intents we're interested in: com.sonicalert.v2.intent.test_shake, com.sonicalert.v2.intent.alarm_dismiss

Usage:

```<code>val patterns = arrayOf(
    "!WLALALALALALALALA;", // default
    "!WTRG0TRG0TRG0TRG;", // pulse
    "!WPJ0FPV7S1J600;" // sos
    // you can add your own patterns by mixing and matching the vibration components
);

// strength is between 0 and 100; pattern follows the format seen above
fun SonicBomb_Shake(strength: Int, pattern: String, playAlarmAudio: Boolean = false) {
    val intent = Intent()
    intent.action = "com.sonicalert.v2.intent.test_shake"
    intent.putExtra("current strength m", strength)
    intent.putExtra("current pattern", pattern)
    intent.putExtra("current alarm audio", playAlarmAudio)
    MainActivity.instance!!.sendBroadcast(intent)
}
fun SonicBomb_StopShake() {
    val intent = Intent()
    intent.action = "com.sonicalert.v2.intent.alarm_dismiss"
    MainActivity.instance!!.sendBroadcast(intent)
}
</code>```

I can confirm that it works just fine. :)

Note that this does require the official app to be installed and running -- but it can be in the background, so it's not been a problem for me. (You should also be able to have your app start up the official app when it starts up, though I haven't added this yet.)

It should also be possible to reverse-engineer the official app, to figure out how to communicate with the device without needing it installed. But overall, the effort doesn't seem worth it to me given how sufficient the intent-based solution is. Also, this way you don't have to maintain the code to pair with the device and such, which is nice.

Body:
I found out how to do this by finding a list of Android intents received by the official Sonic Bomb app.

The two Android intents we're interested in: com.sonicalert.v2.intent.test_shake, com.sonicalert.v2.intent.alarm_dismiss

Usage:

val patterns = arrayOf(
    "!WLALALALALALALALA;", // default
    "!WTRG0TRG0TRG0TRG;", // pulse
    "!WPJ0FPV7S1J600;" // sos
    // you can add your own patterns by mixing and matching the vibration components
);

// strength is between 0 and 100; pattern follows the format seen above
fun SonicBomb_Shake(strength: Int, pattern: String, playAlarmAudio: Boolean = false) {
    val intent = Intent()
    intent.action = "com.sonicalert.v2.intent.test_shake"
    intent.putExtra("current strength m", strength)
    intent.putExtra("current pattern", pattern)
    intent.putExtra("current alarm audio", playAlarmAudio)
    MainActivity.instance!!.sendBroadcast(intent)
}
fun SonicBomb_StopShake() {
    val intent = Intent()
    intent.action = "com.sonicalert.v2.intent.alarm_dismiss"
    MainActivity.instance!!.sendBroadcast(intent)
}

I can confirm that it works just fine. :)

Note that this does require the official app to be installed and running -- but it can be in the background, so it's not been a problem for me. (You should also be able to have your app start up the official app when it starts up, though I haven't added this yet.)

It should also be possible to reverse-engineer the official app, to figure out how to communicate with the device without needing it installed. But overall, the effort doesn't seem worth it to me given how sufficient the intent-based solution is. Also, this way you don't have to maintain the code to pair with the device and such, which is nice.


问:
Assigning an integer into index in char * pointer array
Redoing my previous question since I didn't provide enough detail.

I have a char pointer array, char* token[100]. Let's say I have a double-digit number, like 33.

How do I assign this int into an index in the token array, so that when I print out that token it will give me 33 and not some sort of ASCII value?

```<code>char* token[100];
int num = 33;
//How do I assign num into a specific token index, like for example:
token[1] = num;
//When I print out that token index, I want 33 to be printed out
cout << token[1] << endl; // I want to have 33 be the result. Right now I have '!' as an output
</code>```

答:
It seems you mean something like the following

```<code>#include <iostream>
#include <string>
#include <cstring>

int main()
{
    char * token[100] = {};
    int num = 33;

    std::string s= std::to_string( num );

    token[1] = new char[s.size() + 1];

    std::strcpy( token[1], s.c_str() );

    std::cout << "token[1] = " << token[1] << '\n';

    delete [] token[1];

    return 0;
}
</code>```

The program output is

```<code>token[1] = 33
</code>```

If you are not allowed to use C++ containers and functions then the program can look the following way

```<code>#include <iostream>
#include <cstdio>
#include <cstring>

int main()
{
    char * token[100] = {};
    int num = 33;

    char buffer[12];

    std::sprintf( buffer, "%d", num );

    token[1] = new char[std::strlen( buffer ) + 1];

    std::strcpy( token[1], buffer );

    std::cout << "token[1] = " << token[1] << '\n';

    delete [] token[1];

    return 0;
}
</code>```

Body:
Redoing my previous question since I didn't provide enough detail.

I have a char pointer array, char* token[100]. Let's say I have a double-digit number, like 33.

How do I assign this int into an index in the token array, so that when I print out that token it will give me 33 and not some sort of ASCII value?

char* token[100];
int num = 33;
//How do I assign num into a specific token index, like for example:
token[1] = num;
//When I print out that token index, I want 33 to be printed out
cout << token[1] << endl; // I want to have 33 be the result. Right now I have '!' as an output

Body:
It seems you mean something like the following

#include <iostream>
#include <string>
#include <cstring>

int main()
{
    char * token[100] = {};
    int num = 33;

    std::string s= std::to_string( num );

    token[1] = new char[s.size() + 1];

    std::strcpy( token[1], s.c_str() );

    std::cout << "token[1] = " << token[1] << '\n';

    delete [] token[1];

    return 0;
}

The program output is

token[1] = 33

If you are not allowed to use C++ containers and functions then the program can look the following way

#include <iostream>
#include <cstdio>
#include <cstring>

int main()
{
    char * token[100] = {};
    int num = 33;

    char buffer[12];

    std::sprintf( buffer, "%d", num );

    token[1] = new char[std::strlen( buffer ) + 1];

    std::strcpy( token[1], buffer );

    std::cout << "token[1] = " << token[1] << '\n';

    delete [] token[1];

    return 0;
}


问:
Navigating to another screen after user authentication
I have a login app some users in a Firebase database. When a user logs in into their account succesfully, I want to redirect them to another screen I have. Unfortunately, every single approach I've tried since a couple of days does not work as intended.

This is my code, I'm omitting the StyleSheet and the libraries (and yes, I have my other screen imported into the App.js)

```<code>class HomeScreen extends Component {
  state = { username: null, password: null, nonValidInput: null }

  _onSubmit = ({ navigation }) =>{
    const { navigate } = this.props.navigation;

    if(EmailValidator.validate(this.state.username) == true) {
      this.setState({ nonValidInput: false });
      const { username, password } = this.state;

      try {
        firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(navigator.navigate('Age'));
      } catch {
        Alert.alert(
          'Error',
          'Los datos no son correctos',
          [
            { text: 'Ok' }
          ],
          { cancelable: false }
        );
      }

    } else {
      this.setState({ nonValidInput: true });
    }
  }

  render() {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
      enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.logo}>
          <Image source = {logo} style={styles.img}/>
          <Text style={styles.textLogoPrimary}>Neuron App</Text>
          <Text style={styles.textLogoSecondary}>Test</Text>
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Correo Electrónico</Text>
          <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
          style={styles.formInput} />
          {this.state.nonValidInput ? (
            <Text style={styles.textAlert}>Correo electrónico no valido.</Text>
          ) : null}
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Contraseña</Text>
          <TextInput style={styles.formInput} placeholder='Contraseña' onChangeText={value => this.setState({ password: value })}
          secureTextEntry={true}/>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
            <Text style={styles.buttonText}>Iniciar</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

const Stack = createStackNavigator();

class App extends Component {
  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator screenOptions={{headerShown: false}} initialRouteName="Home">
          <Stack.Screen name='Home' component={HomeScreen} />
          <Stack.Screen name='Age' component={AgeInput} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}
</code>```

Thanks for your help

答:
What is navigator? You can use navigate from navigation prop directly:

```<code>firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(() => this.props.navigation.navigate('Age'));
</code>```

Also, make sure you call the function in the then clause in the right way.

Body:
I have a login app some users in a Firebase database. When a user logs in into their account succesfully, I want to redirect them to another screen I have. Unfortunately, every single approach I've tried since a couple of days does not work as intended.

This is my code, I'm omitting the StyleSheet and the libraries (and yes, I have my other screen imported into the App.js)

class HomeScreen extends Component {
  state = { username: null, password: null, nonValidInput: null }

  _onSubmit = ({ navigation }) =>{
    const { navigate } = this.props.navigation;

    if(EmailValidator.validate(this.state.username) == true) {
      this.setState({ nonValidInput: false });
      const { username, password } = this.state;

      try {
        firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(navigator.navigate('Age'));
      } catch {
        Alert.alert(
          'Error',
          'Los datos no son correctos',
          [
            { text: 'Ok' }
          ],
          { cancelable: false }
        );
      }

    } else {
      this.setState({ nonValidInput: true });
    }
  }

  render() {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
      enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.logo}>
          <Image source = {logo} style={styles.img}/>
          <Text style={styles.textLogoPrimary}>Neuron App</Text>
          <Text style={styles.textLogoSecondary}>Test</Text>
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Correo Electrónico</Text>
          <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
          style={styles.formInput} />
          {this.state.nonValidInput ? (
            <Text style={styles.textAlert}>Correo electrónico no valido.</Text>
          ) : null}
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Contraseña</Text>
          <TextInput style={styles.formInput} placeholder='Contraseña' onChangeText={value => this.setState({ password: value })}
          secureTextEntry={true}/>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
            <Text style={styles.buttonText}>Iniciar</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

const Stack = createStackNavigator();

class App extends Component {
  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator screenOptions={{headerShown: false}} initialRouteName="Home">
          <Stack.Screen name='Home' component={HomeScreen} />
          <Stack.Screen name='Age' component={AgeInput} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}

Thanks for your help

Body:
What is navigator? You can use navigate from navigation prop directly:

firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(() => this.props.navigation.navigate('Age'));

Also, make sure you call the function in the then clause in the right way.


问:
I'm trying to get an estimate for the accuracy of a decision tree, Why do i get a TypeError?
```<code>from sklearn.tree import DecisionTreeClassifier
import pandas as pd
from sklearn.metrics import accuracy_score

## training data (20%)
data = pd.read_csv("train.csv", usecols=[1,2,9])
X_train = pd.read_csv("train.csv", usecols=[2,9])
y_train = pd.read_csv("train.csv", usecols=[1])

dt = DecisionTreeClassifier(max_depth=6)
dt.fit(X_train, y_train)

y_predict = dt.predict(X_test)

accuracy = dt(y_test, y_predict)
</code>```

<p>i get "TypeError: 'DecisionTreeClassifier' object is not callable" even though i (mostly followed a datacamp tutorial). </p>

答:
dt(...) is attempting to "call" dt which you can't do because dt is not a function. You need a function that calculates accuracy from true and predicted labels.

Try something like this

```<code>def calculate_accuracy(y_true, y_predicted):
    num_correct = sum(map(lambda t, p: t==p, y_true, y_predicted))
    return num_correct / len(y_true)
</code>```

```<code>accuracy = calculate_accuracy(y_test, y_predict)
</code>```

EDIT:

The more beginner friendly version of my calculate_accuracy() would look like

```<code>def calculate_accuracy(y_true, y_predicted):
    num_correct = 0
    for i in range(len(y_true)):
        if (y_true[i] == y_predicted[i]):
            num_correct = num_correct + 1
    return num_correct / len(y_true)
</code>```

Body:
from sklearn.tree import DecisionTreeClassifier
import pandas as pd
from sklearn.metrics import accuracy_score

## training data (20%)
data = pd.read_csv("train.csv", usecols=[1,2,9])
X_train = pd.read_csv("train.csv", usecols=[2,9])
y_train = pd.read_csv("train.csv", usecols=[1])

dt = DecisionTreeClassifier(max_depth=6)
dt.fit(X_train, y_train)

y_predict = dt.predict(X_test)

accuracy = dt(y_test, y_predict)

i get "TypeError: 'DecisionTreeClassifier' object is not callable" even though i (mostly followed a datacamp tutorial).

Body:
dt(...) is attempting to "call" dt which you can't do because dt is not a function. You need a function that calculates accuracy from true and predicted labels.

Try something like this

def calculate_accuracy(y_true, y_predicted):
    num_correct = sum(map(lambda t, p: t==p, y_true, y_predicted))
    return num_correct / len(y_true)

accuracy = calculate_accuracy(y_test, y_predict)

EDIT:

The more beginner friendly version of my calculate_accuracy() would look like

def calculate_accuracy(y_true, y_predicted):
    num_correct = 0
    for i in range(len(y_true)):
        if (y_true[i] == y_predicted[i]):
            num_correct = num_correct + 1
    return num_correct / len(y_true)


问:
How to get distance between points and multiple others
I'm trying to determine the distances (euclidean) between points I have in a data frame and others in another one.
Here's below an example of data.

```<code>x <- rnorm(5)
y <- rnorm(5)
df <- data.frame(x, y)

x1 <- rnorm(5)
y1 <- rnorm(5)
Id <- c(1:5)
df2 <- data.frame(Id, x1, y1)
</code>```

I tried this formula to get distance:

```<code>sqrt(((df2$x1 - df$x)^2) + ((df2$y1 - df$y)^2))
</code>```

But I cannot find how to get the distance between points by Id in the df1 and all the others in df

thanks for the help

Body:
I'm trying to determine the distances (euclidean) between points I have in a data frame and others in another one.
Here's below an example of data.

x <- rnorm(5)
y <- rnorm(5)
df <- data.frame(x, y)

x1 <- rnorm(5)
y1 <- rnorm(5)
Id <- c(1:5)
df2 <- data.frame(Id, x1, y1)

I tried this formula to get distance:

sqrt(((df2$x1 - df$x)^2) + ((df2$y1 - df$y)^2))

But I cannot find how to get the distance between points by Id in the df1 and all the others in df

thanks for the help

Body:
If you wanted to get distances between each (x,y) point in df2 with all of the other (x,y) points in df, you could do the following, using your Euclidean distance formula:

euclid_dist <- function(x1, y1, x2, y2) {
  sqrt(((x1 - x2)^2) + ((y1 - y2)^2))
}

t(apply(df2, 1, function(a) euclid_dist(a[["x1"]], a[["y1"]], df[["x"]], df[["y"]])))

With your data you would get in return:

set.seed(123)

x <- rnorm(5)
y <- rnorm(5)
df <- data.frame(x, y)

x1 <- rnorm(5)
y1 <- rnorm(5)
Id <- c(1:5)
df2 <- data.frame(Id, x1, y1)

         [,1]      [,2]     [,3]      [,4]      [,5]
[1,] 1.786003 1.9680289 3.070264 2.7295146 2.4865570
[2,] 1.525957 0.5911463 2.131949 1.2195161 0.9712662
[3,] 3.805099 2.5081895 1.353883 1.3216922 1.5449945
[4,] 1.215755 0.4171294 2.442043 1.3887899 1.1471688
[5,] 2.187861 0.9888714 2.258099 0.6619184 0.6856658

This matrix includes distances where each row represents each Id in df2.


问:
What's the jquery syntax for click function of submit button
my form has a submit button that's been defined this way:

```<code><input type="submit" name="submit-reg" value="Register" class="submit button">
</code>```

What is the syntax to call the button's jquery click() function?
I've tried:

```<code>$('#submit-reg').click(function()...
</code>```

But it's not working.

答:
If you want to make sure it only matches the one element (since .submit could match any number of elements), you could use:</p>

```<code>$("input[name='submit-reg']")
</code>```

Body:
my form has a submit button that's been defined this way:

<input type="submit" name="submit-reg" value="Register" class="submit button">

What is the syntax to call the button's jquery click() function?
I've tried:

$('#submit-reg').click(function()...

But it's not working.

Body:
If you want to make sure it only matches the one element (since .submit could match any number of elements), you could use:

$("input[name='submit-reg']")