问:
WordPress: Redirect homepage and pages to account page when not in a specific user role
I want to redirect every page (including the homepage) in WordPress to a specific page.
But I also want to set some exceptions. Pages I don't want to redirect.
The redirect should only take place if the current user is not part of the user role "editor".

As example:

I want to redirect every user without that role to the page with the page ID 9.
But the pages with the IDs 1,2,3 and 4 should not be redirected.

I managed to redirect the home page to the page with the ID 9.
But only the home page.

But how can I add every other page to that funtion and also add the exceptions?
I guess I have to white list the exceptions in a way but I just don't get it at the moment.

EDIT: Here's some more background: I have a user role (in this example "editor") with an own member area. Now I want to limit the access to the whole site for every user and role. But if the user is logged in with the role "editor", I want to allow them to navigate in the member area. But if the user isn't logged in, I need the login page and a register page to be open for everyone. Everything else should be redirected to the login page (ID 9).

This is the current code:

```<code>function redirect_homepage() {
    if( ! is_home() && ! is_front_page() )
        return;

    wp_redirect( get_permalink('9') );
    exit;
}

add_action( 'template_redirect', 'redirect_homepage' );
</code>```

答:
The way I got your problem with your edit:

You want to have your whole page only be accessible for logged in users.

But there should be visible register and login pages, so users can register and log in.

These pages are custom pages (not wp-admin) and you have the IDs of the pages.

Only logged in user with the role 'editor' can use the whole page. If you are logged in, but do not have the role of 'editor' your access on the page is the same as for not logged in users (no access / so redirect to login page or other).

So you can put the code the functions.php file of your theme:

```<code><?php

function editors_only() {

    /* Redirect not logged in users */

    // instead of '12' and '13' you write the page ids of your login and register pages
    if ( !is_user_logged_in() && !is_page( 12 ) && !is_page( 13 ) ) {
        wp_redirect( get_permalink(12) ); // redirect to login page
        exit;
    }

    /* Redirect logged in users */

    if ( is_user_logged_in() ) {

        $user = wp_get_current_user(); // get current user
        $user_access = false; // set boolean for access to false
        if ( in_array( 'editor', (array) $user->roles ) ) {
            $user_access = true; // if user role correct set boolean to true
        }

        if ( $user_access == false ) { // is user has not the editor role
            wp_redirect( get_permalink(12) ); // redirect to login page
            exit;
        }
    }
}
add_action( 'wp', 'editors_only' );

?>
</code>```

I think it is not the best practice or intended to redirect your logged in users to your login page, as they are already logged in, but just do not have a "editor" role. Maybe you have an upgrade account page or other pages for this role of users. You can add this page id in your "redirect not logged in users" code (another && !is_page(id)) and put the ID of this page in the get_permalink(id) function if the user access is false.

Body:
I want to redirect every page (including the homepage) in WordPress to a specific page.
But I also want to set some exceptions. Pages I don't want to redirect.
The redirect should only take place if the current user is not part of the user role "editor".

As example:

I want to redirect every user without that role to the page with the page ID 9.
But the pages with the IDs 1,2,3 and 4 should not be redirected.

I managed to redirect the home page to the page with the ID 9.
But only the home page.

But how can I add every other page to that funtion and also add the exceptions?
I guess I have to white list the exceptions in a way but I just don't get it at the moment.

EDIT: Here's some more background: I have a user role (in this example "editor") with an own member area. Now I want to limit the access to the whole site for every user and role. But if the user is logged in with the role "editor", I want to allow them to navigate in the member area. But if the user isn't logged in, I need the login page and a register page to be open for everyone. Everything else should be redirected to the login page (ID 9).

This is the current code:

function redirect_homepage() {
    if( ! is_home() && ! is_front_page() )
        return;

    wp_redirect( get_permalink('9') );
    exit;
}

add_action( 'template_redirect', 'redirect_homepage' );

Body:
The way I got your problem with your edit:

You want to have your whole page only be accessible for logged in users.

But there should be visible register and login pages, so users can register and log in.

These pages are custom pages (not wp-admin) and you have the IDs of the pages.

Only logged in user with the role 'editor' can use the whole page. If you are logged in, but do not have the role of 'editor' your access on the page is the same as for not logged in users (no access / so redirect to login page or other).

So you can put the code the functions.php file of your theme:

<?php

function editors_only() {

    /* Redirect not logged in users */

    // instead of '12' and '13' you write the page ids of your login and register pages
    if ( !is_user_logged_in() && !is_page( 12 ) && !is_page( 13 ) ) {
        wp_redirect( get_permalink(12) ); // redirect to login page
        exit;
    }

    /* Redirect logged in users */

    if ( is_user_logged_in() ) {

        $user = wp_get_current_user(); // get current user
        $user_access = false; // set boolean for access to false
        if ( in_array( 'editor', (array) $user->roles ) ) {
            $user_access = true; // if user role correct set boolean to true
        }

        if ( $user_access == false ) { // is user has not the editor role
            wp_redirect( get_permalink(12) ); // redirect to login page
            exit;
        }
    }
}
add_action( 'wp', 'editors_only' );

?>

I think it is not the best practice or intended to redirect your logged in users to your login page, as they are already logged in, but just do not have a "editor" role. Maybe you have an upgrade account page or other pages for this role of users. You can add this page id in your "redirect not logged in users" code (another && !is_page(id)) and put the ID of this page in the get_permalink(id) function if the user access is false.


来源: stackexchange

问:
How to use MySQL with Vue SSR directly without REST API backend?
I would like to use MySQL as the data source when fetching for the content during server side rendering so I don't need to create an external API server for the purpose of fetching the data from the database.</p>

答:
Vue js is client side language. Not for server side.

For access mySql You must need to access via server side language like php, nodeJs,  python.

You can also follow some official  documentation for better understand   about server side rendering
https://v2.vuejs.org/v2/guide/ssr.html

ContentLicense: CC BY-SA 4.0


问:
jQuery get closest previous element
In this example I have multiple a tags. Under the Structure where you can see my unordered list, that list was generated by a CMS I am using. But this ul needs to a dropdown menu of the previous a, which in this case is Structure.
I am trying to add some classes and attributes to the structure, but with the code I am using, it gets all a tags elements. But I only need the element before ul

$('.custom-dropdown').each(function() {
    if($(this).children('ul').length) {
        $(this).addClass('dropdown');
        $(this).children('a').addClass('dropdown-toggle'); // the problem is here. I have tried closest(), .prev() but I couldn't use it properly to make it work
        $(this).children('a').attr({'role':'button','data-toggle':'dropdown','id':'navbarDropdown2'});
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown-menu custom-dropdown" aria-labelledby="navbarDropdown">
   About Us
   Structure
   <ul>
      <li class="first nav-item">
         Organizational Chart
      </li>
      <li class="last nav-item">
         Commissioner
      </li>
   </ul>
   Mission
   Strategies
</div></code>```

答:
Given the structure, to find all the  tags with a corresponding ul as the next sibling, you can use:

```<code>$(this).find('ul>li>a').closest("ul").prev("a")
</code>```

which will find, given this==.custom-dropdown, any ul (at any level) that has an li and a as direct descendants, then using .closest to go back to that ul with .prev to get the corresponding a that matches.

Using .prev(selector) will select the previous only if it matches the selector, it's the same as .prev().filter(selector) - it's not the same as .prevAll().first() (or is that .last, either way).

Example snippet with added .hide just to demo it working - this would normally be handled by adding the drop down classes/attributes.

$(".custom-dropdown").find('ul>li>a').closest("ul").hide().prev("a").addClass("red");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red { color: red; }</code>```

  About Us
  Structure

      Organizational Chart

      Commissioner

  Mission
  Strategies

```

Title: jQuery get closest previous element

Body:
In this example I have multiple a tags. Under the Structure where you can see my unordered list, that list was generated by a CMS I am using. But this ul needs to a dropdown menu of the previous a, which in this case is Structure.
I am trying to add some classes and attributes to the structure, but with the code I am using, it gets all a tags elements. But I only need the element before ul

$('.custom-dropdown').each(function() {
    if($(this).children('ul').length) {
        $(this).addClass('dropdown');
        $(this).children('a').addClass('dropdown-toggle'); // the problem is here. I have tried closest(), .prev() but I couldn't use it properly to make it work
        $(this).children('a').attr({'role':'button','data-toggle':'dropdown','id':'navbarDropdown2'});
    }
});

   About Us
   Structure

         Organizational Chart

         Commissioner

   Mission
   Strategies

Body:
Given the structure, to find all the <a> tags with a corresponding ul as the next sibling, you can use:

$(this).find('ul>li>a').closest("ul").prev("a")

which will find, given this==.custom-dropdown, any ul (at any level) that has an li and a as direct descendants, then using .closest to go back to that ul with .prev to get the corresponding a that matches.

Using .prev(selector) will select the previous only if it matches the selector, it's the same as .prev().filter(selector) - it's not the same as .prevAll().first() (or is that .last, either way).

Example snippet with added .hide just to demo it working - this would normally be handled by adding the drop down classes/attributes.

$(".custom-dropdown").find('ul>li>a').closest("ul").hide().prev("a").addClass("red");

.red { color: red; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdown-menu custom-dropdown" aria-labelledby="navbarDropdown">
  <a href="" class="nav-link">About Us</a>
  <a href="" class="nav-link">Structure</a>
  <ul>
    <li class="first nav-item">
      <a href="" class="nav-link">Organizational Chart</a>
    </li>
    <li class="last nav-item">
      <a href="" class="nav-link">Commissioner</a>
    </li>
  </ul>
  <a href="" class="nav-link">Mission</a>
  <a href="" class="nav-link">Strategies</a>
</div>


问:
What is up with jQuery Nivo Slider on my site?
I have installed the Nivo Slider (http://nivo.dev7studios.com/) that uses jQuery on my site which is a Magento ecommerce site.

My site is http://bikeshop.gostorego.com/

Any ideas why on the homepage you can see where the slider goes, but the loading icon is only present not showing the slides?

Thanks

答:
jQuery isn't being loaded on the page.

This is how you're attempting to load it:

```<code><script src=’https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js’ type="text/javascript"></script>
</code>```

Firebug shows that this URL is what's actually being requested:

http://bikeshop.gostorego.com/%E2%80%99https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js%E2%80%99

So, those unusual quotes are the problem; you need normal single or double quotes:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
jQuery isn't being loaded on the page.

This is how you're attempting to load it:

<script src=’https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js’ type="text/javascript"></script>

Firebug shows that this URL is what's actually being requested:

http://bikeshop.gostorego.com/%E2%80%99https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js%E2%80%99

So, those unusual quotes are the problem; you need normal single or double quotes:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>


问:
Python: How to call and run python scripts from desktop by giving command in python editor?
I have two python script files in my desktop folder and I would like to run based on if statement. For example: If calling 'Ram' and 'Sam' then run python script file_1 and for 'Mohan' run python script file_2. Is there any way where I can call and run the scripts by giving some command based on if statement? Below is the path of files and dataframe.</p>

```<code>file_1 = 'c:/users/rec/name/file_1.py'
file_2 = 'c:/users/rec/name/file_2.py'

df = {'name': ['Ram','Mohan','Sam'], 'salary':[1000, 2000, 1500]}
</code>```

答:
Use an import statement to run:

First, name the file you showed us as 'c:/users/rec/name/<filename>.py'

Next, try running this:

```<code>df = {'name': ['Ram','Mohan','Sam'], 'salary':[1000, 2000, 1500]}

person = 'Ram' #Get somebody in this variable

#Import each program depending on person
if person == 'Ram' or person == 'Sam':
    import file_1

else if person == 'Mohan':
    import file_2

else:
    print('Person was not Sam, Ram, or Mohan.')

#Adjust as needed
</code>```

To rename a file, use os.rename:

```<code>import os

os.rename('original file name', 'new file name')
</code>```

Body:
I have two python script files in my desktop folder and I would like to run based on if statement. For example: If calling 'Ram' and 'Sam' then run python script file_1 and for 'Mohan' run python script file_2. Is there any way where I can call and run the scripts by giving some command based on if statement? Below is the path of files and dataframe.

file_1 = 'c:/users/rec/name/file_1.py'
file_2 = 'c:/users/rec/name/file_2.py'

df = {'name': ['Ram','Mohan','Sam'], 'salary':[1000, 2000, 1500]}

Body:
Use an import statement to run:

First, name the file you showed us as 'c:/users/rec/name/<filename>.py'

Next, try running this:

df = {'name': ['Ram','Mohan','Sam'], 'salary':[1000, 2000, 1500]}

person = 'Ram' #Get somebody in this variable

#Import each program depending on person
if person == 'Ram' or person == 'Sam':
    import file_1

else if person == 'Mohan':
    import file_2

else:
    print('Person was not Sam, Ram, or Mohan.')

#Adjust as needed

To rename a file, use os.rename:

import os

os.rename('original file name', 'new file name')


问:
How to make counter two digit even if below 10 on timer
I have as simple timer as below, but how do I make it show two digits when it falls below 10, for 09, 08, 07, 06 etc.?</p>

```<code>startTimer(60);
function startTimer(num){
      count = num;
      countdown = setInterval(function(){
             count--;
      }, 1000);
     };
</code>```

答:
var str = (count < 10) ? '0' + count : count;

this worked for me, for setInterval() for my Pomodoro project.

Body:
I have as simple timer as below, but how do I make it show two digits when it falls below 10, for 09, 08, 07, 06 etc.?

startTimer(60);
function startTimer(num){
      count = num;
      countdown = setInterval(function(){
             count--;
      }, 1000);
     };


问:
deparse(substitute()) with lapply
I want to give labels to data frames using a combination of a small function in combination with lapply()

I have the following code:

```<code>df1 <- data.frame(c(1,2,3), c(3,4,5))
df2 <- data.frame(c(6,7,8), c(9,10,11))

f.generate.name <- function(x) {
  x$name <- deparse(substitute(x))
  return(x)
  }

my_list <- list(df1, df2)

# This works fine.
f.generate.name(df1)

# This does not work.
lapply(my_list, f.generate.name)

</code>```

which produces the following output

```<code>[[1]]
  c.1..2..3. c.3..4..5.   name
1          1          3 X[[i]]
2          2          4 X[[i]]
3          3          5 X[[i]]

[[2]]
  c.6..7..8. c.9..10..11.   name
1          6            9 X[[i]]
2          7           10 X[[i]]
3          8           11 X[[i]]

</code>```

What I want instead is:

```<code>[[1]]
  c.1..2..3. c.3..4..5.   name
1          1          3 df1
2          2          4 df1
3          3          5 df1

[[2]]
  c.6..7..8. c.9..10..11.   name
1          6            9 df2
2          7           10 df2
3          8           11 df2
</code>```

What is the best way of dong this without using loops? How can I tweak the lapply() function or the function that I created in order to achieve the desired result?

答:
Really the question is where do the names come from?  An unnamed list like my_list in the question has lost the df1 and df2 names as we can see by looking at its internals:

```<code>dput(my_list)  # no df1 or df2 seen
## list(structure(list(c.1..2..3. = c(1, 2, 3), c.3..4..5. = c(3,
## 4, 5)), class = "data.frame", row.names = c(NA, -3L)), structure(list(
##     c.6..7..8. = c(6, 7, 8), c.9..10..11. = c(9, 10, 11)), class =
## "data.frame", row.names = c(NA,
## -3L)))
</code>```

Thus either we need to create a named list in the first place or else provide a vector of names.  We show both using only base R.

Named list

First create a named list of the data frames and then use Map as shown:

```<code>L <- mget(ls("^df"))  # create named list
Map(data.frame, L, name = names(L))
</code>```

Unnamed list

Alternately if all you have is an unnamed list then we can Map over that and a vector of names:

```<code>my_list <- list(df1, df2) # unnamed list as in question
Map(data.frame, my_list, name = c("df1", "df2"))
</code>```

Pass individual data frames

Yet another approach is to pass the individual data frames instead of a list.  Because we have not destroyed the original names by creating an unnamed list we can still retrieve them.  On R 4.0 and later deparse1 could optionally be used in place of deparse in the code.

```<code>add_names <- function(...) {
  mc <- match.call()
  Map(data.frame, list(...), names = sapply(mc[-1], deparse))
}

add_names(df1, df2)
</code>```

Title: deparse(substitute()) with lapply

Body:
I want to give labels to data frames using a combination of a small function in combination with lapply()

I have the following code:

df1 <- data.frame(c(1,2,3), c(3,4,5))
df2 <- data.frame(c(6,7,8), c(9,10,11))

f.generate.name <- function(x) {
  x$name <- deparse(substitute(x))
  return(x)
  }

my_list <- list(df1, df2)

# This works fine.
f.generate.name(df1)

# This does not work.
lapply(my_list, f.generate.name)

which produces the following output

[[1]]
  c.1..2..3. c.3..4..5.   name
1          1          3 X[[i]]
2          2          4 X[[i]]
3          3          5 X[[i]]

[[2]]
  c.6..7..8. c.9..10..11.   name
1          6            9 X[[i]]
2          7           10 X[[i]]
3          8           11 X[[i]]

What I want instead is:

[[1]]
  c.1..2..3. c.3..4..5.   name
1          1          3 df1
2          2          4 df1
3          3          5 df1

[[2]]
  c.6..7..8. c.9..10..11.   name
1          6            9 df2
2          7           10 df2
3          8           11 df2

What is the best way of dong this without using loops? How can I tweak the lapply() function or the function that I created in order to achieve the desired result?

Body:
Really the question is where do the names come from?  An unnamed list like my_list in the question has lost the df1 and df2 names as we can see by looking at its internals:

dput(my_list)  # no df1 or df2 seen
## list(structure(list(c.1..2..3. = c(1, 2, 3), c.3..4..5. = c(3,
## 4, 5)), class = "data.frame", row.names = c(NA, -3L)), structure(list(
##     c.6..7..8. = c(6, 7, 8), c.9..10..11. = c(9, 10, 11)), class =
## "data.frame", row.names = c(NA,
## -3L)))

Thus either we need to create a named list in the first place or else provide a vector of names.  We show both using only base R.

Named list

First create a named list of the data frames and then use Map as shown:

L <- mget(ls("^df"))  # create named list
Map(data.frame, L, name = names(L))

Unnamed list

Alternately if all you have is an unnamed list then we can Map over that and a vector of names:

my_list <- list(df1, df2) # unnamed list as in question
Map(data.frame, my_list, name = c("df1", "df2"))

Pass individual data frames

Yet another approach is to pass the individual data frames instead of a list.  Because we have not destroyed the original names by creating an unnamed list we can still retrieve them.  On R 4.0 and later deparse1 could optionally be used in place of deparse in the code.

add_names <- function(...) {
  mc <- match.call()
  Map(data.frame, list(...), names = sapply(mc[-1], deparse))
}

add_names(df1, df2)


问:
sidebar navigation that expands from small icons
So this is kinda a weird question but canva.com has the coolest sidebar I have ever seen. Its got smile icons that then expand into a bigger selection area. Does anyone have any idea how I would do that in bootstrap 4?

答:
You are not going to find this type of side-bar on internet easily especially in Bootstrap.

CODEPEN is the best source where you can find plenty of sidebars and other code related stuff's

Here is the code of somewhat similar to the action you want on each button click of sidebar. you can download it from here. It has various version demo 4 is similar to your's need

codepen link of sidebar

You can easily reduce the width of the left side div content based on your need and add search bar and rest of the stuff.


问:
oracle - fetch first n json objects from json array
I have a table in which one column we have json array data. in some rows this json is very big (with 10000+ json objects) like below. wanted to know is there any way just to select first 250 objects from the array-</p>

```<code>[
   {
      "product":"Vegetable",
      "name":"Potato",
      "price":"$60.00"
   },
   {
      "product":"Fruit",
      "name":"Mango",
      "price":"$3.30"
   },
   {
      "product":"Milk",
      "name":"Milk",
      "price":"$1.08"
   },
.....10,000
]
</code>```

答:
Well I investigated the question, and I found one can use json_query to select single entries from the JSON.

```<code>CREATE TABLE json_table ( JSON varchar(1024) NOT NULL , constraint CK_JSON_IS_JSON check (JSON is json));

insert into json_table columns (JSON) values ('[ { "product":"Vegetable", "name":"Potato", "price":"$60.00" }, { "product":"Fruit", "name":"Mango", "price":"$3.30" }, { "product":"Milk", "name":"Milk", "price":"$1.08" }]');

select json_query(JSON, '$[0]'),
       json_query(JSON, '$[1]'),
       json_query(JSON, '$[2]'),
       json_query(JSON, '$[3]')
from json_table;
</code>```

This selects entries 0 to 3, with 3 not being found and being NULL.

You could probably stitch together a database stored procedure to return a list of the first n entries in the JSON.

Body:
I have a table in which one column we have json array data. in some rows this json is very big (with 10000+ json objects) like below. wanted to know is there any way just to select first 250 objects from the array-

[
   {
      "product":"Vegetable",
      "name":"Potato",
      "price":"$60.00"
   },
   {
      "product":"Fruit",
      "name":"Mango",
      "price":"$3.30"
   },
   {
      "product":"Milk",
      "name":"Milk",
      "price":"$1.08"
   },
.....10,000
]

Body:
Well I investigated the question, and I found one can use json_query to select single entries from the JSON.

CREATE TABLE json_table ( JSON varchar(1024) NOT NULL , constraint CK_JSON_IS_JSON check (JSON is json));

insert into json_table columns (JSON) values ('[ { "product":"Vegetable", "name":"Potato", "price":"$60.00" }, { "product":"Fruit", "name":"Mango", "price":"$3.30" }, { "product":"Milk", "name":"Milk", "price":"$1.08" }]');

select json_query(JSON, '$[0]'),
       json_query(JSON, '$[1]'),
       json_query(JSON, '$[2]'),
       json_query(JSON, '$[3]')
from json_table;

This selects entries 0 to 3, with 3 not being found and being NULL.

You could probably stitch together a database stored procedure to return a list of the first n entries in the JSON.


问:
Widget cant send signal if it is disabled
I have a basic question

There is a pushbutton to enable a widget as follows:

```<code>connect(ui->pushButton_currOnOne, &QPushButton::clicked, ui->widget_currentOne, &CurrentButtonOne::setEnabled);
</code>```

and this widget is connected to a slot to adjust a value:

```<code> connect(ui->widget_currentOne, &CurrentButtonOne::getValue, this, &stageProgram::setCurrOnChannelOne);
</code>```

and the slot is:

```<code>void stageProgram::setCurrOnChannelOne(unsigned int current_uA)
{
    tetra_grip_api::stimulation_set_current( m_channelOne, current_uA); // second argument I get as signal from the widget
}
</code>```

But what I now need if the widget is disabled the signal value should be 0 (meaning the current_uA = 0)

I was thinking to call different slot and set current_uA = 0. Looks like it's not possible..

I tried using Lambda

```<code>connect(ui->widget_currentOne, &CurrentButtonOne::getValue,
        [this](unsigned int current_uA) { setCurrOnChannelOne(ui->widget_currentOne->isEnabled() ? current_uA : 0); } );
//this does not send 0 when it is disabled
</code>```

can you suggest a way to send zero signal when the widget is disabled ?

答:
I think its better to define the following slot for the CurrentButtonOne:

```<code>void disableMe() {

    //Disable
    setDisabled(true);

    //Reset current_uA
    current_uA = 0;
}
</code>```

and then connect the signals and slots as follows:

```<code>connect(ui->pushButton_currOnOne, &QPushButton::clicked, ui->widget_currentOne, &CurrentButtonOne::disableMe);

</code>```

Hope this helps.

Body:
I have a basic question

There is a pushbutton to enable a widget as follows:

connect(ui->pushButton_currOnOne, &QPushButton::clicked, ui->widget_currentOne, &CurrentButtonOne::setEnabled);

and this widget is connected to a slot to adjust a value:

 connect(ui->widget_currentOne, &CurrentButtonOne::getValue, this, &stageProgram::setCurrOnChannelOne);

and the slot is:

void stageProgram::setCurrOnChannelOne(unsigned int current_uA)
{
    tetra_grip_api::stimulation_set_current( m_channelOne, current_uA); // second argument I get as signal from the widget
}

But what I now need if the widget is disabled the signal value should be 0 (meaning the current_uA = 0)

I was thinking to call different slot and set current_uA = 0. Looks like it's not possible..

I tried using Lambda

connect(ui->widget_currentOne, &CurrentButtonOne::getValue,
        [this](unsigned int current_uA) { setCurrOnChannelOne(ui->widget_currentOne->isEnabled() ? current_uA : 0); } );
//this does not send 0 when it is disabled

can you suggest a way to send zero signal when the widget is disabled ?

Body:
I think its better to define the following slot for the CurrentButtonOne:

void disableMe() {

    //Disable
    setDisabled(true);

    //Reset current_uA
    current_uA = 0;
}

and then connect the signals and slots as follows:

connect(ui->pushButton_currOnOne, &QPushButton::clicked, ui->widget_currentOne, &CurrentButtonOne::disableMe);

Hope this helps.


问:
Boyer Moore Algorithm Understanding and Example?
I am facing issues in understanding Boyer Moore String Search algorithm.

I am following the following document. Link

I am not able to work out my way as to exactly what is the real meaning of delta1 and delta2 here, and how are they applying this to find string search algorithm.
Language looked little vague..

Kindly if anybody out there can help me out in understanding this, it would be really helpful.

Or, if you know of any other link or document available that is easy to understand, then please share.

Thanks in advance.

答:
The algorithm is based on a simple principle.  Suppose that I'm trying to match a substring of length m.  I'm going to first look at character at index m.  If that character is not in my string, I know that the substring I want can't start in characters at indices 1, 2, ... , m.

If that character is in my string, I'll assume that it is at the last place in my string that it can be.  I'll then jump back and start trying to match my string from that possible starting place.  This piece of information is my first table.

Once I start matching from the beginning of the substring, when I find a mismatch, I can't just start from scratch.  I could be partially through a match starting at a different point.  For instance if I'm trying to match anand in ananand successfully match, anan,  realize that the following a is not a d, but I've just matched an, and so I should jump back to trying to match my third character in my substring.  This, "If I fail after matching x characters, I could be on the y'th character of a match" information is stored in the second table.

Note that when I fail to match the second table knows how far along in a match I might be based on what I just matched.  The first table knows how far back I might be based on the character that I just saw which I failed to match.  You want to use the more pessimistic of those two pieces of information.

With this in mind the algorithm works like this:

```<code>start at beginning of string
start at beginning of match
while not at the end of the string:
    if match_position is 0:
        Jump ahead m characters
        Look at character, jump back based on table 1
        If match the first character:
            advance match position
        advance string position
    else if I match:
        if I reached the end of the match:
           FOUND MATCH - return
        else:
           advance string position and match position.
    else:
        pos1 = table1[ character I failed to match ]
        pos2 = table2[ how far into the match I am ]
        if pos1 < pos2:
            jump back pos1 in string
            set match position at beginning
        else:
            set match position to pos2
FAILED TO MATCH
</code>```

Body:
The algorithm is based on a simple principle.  Suppose that I'm trying to match a substring of length m.  I'm going to first look at character at index m.  If that character is not in my string, I know that the substring I want can't start in characters at indices 1, 2, ... , m.

If that character is in my string, I'll assume that it is at the last place in my string that it can be.  I'll then jump back and start trying to match my string from that possible starting place.  This piece of information is my first table.

Once I start matching from the beginning of the substring, when I find a mismatch, I can't just start from scratch.  I could be partially through a match starting at a different point.  For instance if I'm trying to match anand in ananand successfully match, anan,  realize that the following a is not a d, but I've just matched an, and so I should jump back to trying to match my third character in my substring.  This, "If I fail after matching x characters, I could be on the y'th character of a match" information is stored in the second table.

Note that when I fail to match the second table knows how far along in a match I might be based on what I just matched.  The first table knows how far back I might be based on the character that I just saw which I failed to match.  You want to use the more pessimistic of those two pieces of information.

With this in mind the algorithm works like this:

start at beginning of string
start at beginning of match
while not at the end of the string:
    if match_position is 0:
        Jump ahead m characters
        Look at character, jump back based on table 1
        If match the first character:
            advance match position
        advance string position
    else if I match:
        if I reached the end of the match:
           FOUND MATCH - return
        else:
           advance string position and match position.
    else:
        pos1 = table1[ character I failed to match ]
        pos2 = table2[ how far into the match I am ]
        if pos1 < pos2:
            jump back pos1 in string
            set match position at beginning
        else:
            set match position to pos2
FAILED TO MATCH


问:
Where to find list of jenkins plugins for Ansible
I am using ansible and Jenkins and want to install plugin throw ansible. So for that I did following piece of code.

```<code>- name: Install Jenkins plugins using password.
  jenkins_plugin:
    name: "{{ item }}"
    jenkins_home: "{{ jenkins_home }}"
    url_username: "{{ jenkins_admin_username }}"
    url_password: "{{ jenkins_admin_password }}"
    state: "{{ jenkins_plugins_state }}"
    timeout: "{{ jenkins_plugin_timeout }}"
    updates_expiration: "{{ jenkins_plugin_updates_expiration }}"
    url: "http://{{ jenkins_hostname }}:{{ jenkins_http_port }}{{ jenkins_url_prefix }}"
    with_dependencies: "{{ jenkins_plugins_install_dependencies }}"
  **with_items: "{{ jenkins_plugins }}"**
  when: jenkins_admin_password != ""
  notify: restart jenkins
  tags: ['skip_ansible_lint']
</code>```

you will see Jenkins_plugins is variable and its value is coming from one variable.yml file. where value looks like following code.

```<code>jenkins_plugins: [Git]
</code>```

With this code ansible successfully installed the git plugin in Jenkins.
Going forward using the same technique I want to install few more plugin for Jenkins.

Now I have two question.

Where I can find the list of plugins for ansible like maven, sonar etc.

I tried to installed maven using same approach and following is piece of code for that.

jenkins_plugins: [maven;sonar]
or
jenkins_plugins: [maven,sonar]

But nothing is working otherthan Git plugin installation.

答:
The URL to get the list of Jenkins available plugins is:

```<code>http://updates.jenkins-ci.org/download/plugins/
</code>```

To install a list of plugins, you may do this:

```<code>- name: Install Jenkins plugins
  jenkins_plugin:
    name: "{{ item }}"
    jenkins_home: "{{ jenkins_home_directory }}"
    url_username: "admin_username"
    url_password: "admin_password"
    state: present
    with_dependencies: yes
  with_items:
    - git
    - maven
</code>```

Body:
I am using ansible and Jenkins and want to install plugin throw ansible. So for that I did following piece of code.

- name: Install Jenkins plugins using password.
  jenkins_plugin:
    name: "{{ item }}"
    jenkins_home: "{{ jenkins_home }}"
    url_username: "{{ jenkins_admin_username }}"
    url_password: "{{ jenkins_admin_password }}"
    state: "{{ jenkins_plugins_state }}"
    timeout: "{{ jenkins_plugin_timeout }}"
    updates_expiration: "{{ jenkins_plugin_updates_expiration }}"
    url: "http://{{ jenkins_hostname }}:{{ jenkins_http_port }}{{ jenkins_url_prefix }}"
    with_dependencies: "{{ jenkins_plugins_install_dependencies }}"
  **with_items: "{{ jenkins_plugins }}"**
  when: jenkins_admin_password != ""
  notify: restart jenkins
  tags: ['skip_ansible_lint']

you will see Jenkins_plugins is variable and its value is coming from one variable.yml file. where value looks like following code.

jenkins_plugins: [Git]

With this code ansible successfully installed the git plugin in Jenkins.
Going forward using the same technique I want to install few more plugin for Jenkins.

Now I have two question.

Where I can find the list of plugins for ansible like maven, sonar etc.

I tried to installed maven using same approach and following is piece of code for that.

jenkins_plugins: [maven;sonar]
or
jenkins_plugins: [maven,sonar]

But nothing is working otherthan Git plugin installation.

Body:
The URL to get the list of Jenkins available plugins is:

http://updates.jenkins-ci.org/download/plugins/

To install a list of plugins, you may do this:

- name: Install Jenkins plugins
  jenkins_plugin:
    name: "{{ item }}"
    jenkins_home: "{{ jenkins_home_directory }}"
    url_username: "admin_username"
    url_password: "admin_password"
    state: present
    with_dependencies: yes
  with_items:
    - git
    - maven


问:
Automate Outlook on Mac with Python
I can automate Outlook on windows with win32/COM, but does anyone know of a pure python way to do the same on mac osx?

A simple use case would be:

Open outlook/connect to the active instance

Launch a blank new email

I want to create an app to create email templates and attach files, then let the user finish editing the email and send when ready, NOT just send emails.

Is there a python wrapper for applescript that may work? (I don't know anything about applescript, so an example would help).

答:
@ajrwhite adding attachments had one trick, you need to use 'Alias' from mactypes to convert a string/path object to a mactypes path. I'm not sure why but it works.

here's a working example which creates messages with recipients and can add attachments:

```<code>from appscript import app, k
from mactypes import Alias
from pathlib import Path

def create_message_with_attachment():
    subject = 'This is an important email!'
    body = 'Just kidding its not.'
    to_recip = ['myboss@mycompany.com', 'theguyih8@mycompany.com']

    msg = Message(subject=subject, body=body, to_recip=to_recip)

    # attach file
    p = Path('path/to/myfile.pdf')
    msg.add_attachment(p)

    msg.show()

class Outlook(object):
    def __init__(self):
    self.client = app('Microsoft Outlook')

class Message(object):
    def __init__(self, parent=None, subject='', body='', to_recip=[], cc_recip=[], show_=True):

        if parent is None: parent = Outlook()
        client = parent.client

        self.msg = client.make(
            new=k.outgoing_message,
            with_properties={k.subject: subject, k.content: body})

        self.add_recipients(emails=to_recip, type_='to')
        self.add_recipients(emails=cc_recip, type_='cc')

        if show_: self.show()

    def show(self):
        self.msg.open()
        self.msg.activate()

    def add_attachment(self, p):
        # p is a Path() obj, could also pass string

        p = Alias(str(p)) # convert string/path obj to POSIX/mactypes path

        attach = self.msg.make(new=k.attachment, with_properties={k.file: p})

    def add_recipients(self, emails, type_='to'):
        if not isinstance(emails, list): emails = [emails]
        for email in emails:
            self.add_recipient(email=email, type_=type_)

    def add_recipient(self, email, type_='to'):
        msg = self.msg

        if type_ == 'to':
            recipient = k.to_recipient
        elif type_ == 'cc':
            recipient = k.cc_recipient

        msg.make(new=recipient, with_properties={k.email_address: {k.address: email}})
</code>```

Title: Automate Outlook on Mac with Python

Body:
@ajrwhite adding attachments had one trick, you need to use 'Alias' from mactypes to convert a string/path object to a mactypes path. I'm not sure why but it works.

here's a working example which creates messages with recipients and can add attachments:

from appscript import app, k
from mactypes import Alias
from pathlib import Path

def create_message_with_attachment():
    subject = 'This is an important email!'
    body = 'Just kidding its not.'
    to_recip = ['myboss@mycompany.com', 'theguyih8@mycompany.com']

    msg = Message(subject=subject, body=body, to_recip=to_recip)

    # attach file
    p = Path('path/to/myfile.pdf')
    msg.add_attachment(p)

    msg.show()

class Outlook(object):
    def __init__(self):
    self.client = app('Microsoft Outlook')

class Message(object):
    def __init__(self, parent=None, subject='', body='', to_recip=[], cc_recip=[], show_=True):

        if parent is None: parent = Outlook()
        client = parent.client

        self.msg = client.make(
            new=k.outgoing_message,
            with_properties={k.subject: subject, k.content: body})

        self.add_recipients(emails=to_recip, type_='to')
        self.add_recipients(emails=cc_recip, type_='cc')

        if show_: self.show()

    def show(self):
        self.msg.open()
        self.msg.activate()

    def add_attachment(self, p):
        # p is a Path() obj, could also pass string

        p = Alias(str(p)) # convert string/path obj to POSIX/mactypes path

        attach = self.msg.make(new=k.attachment, with_properties={k.file: p})

    def add_recipients(self, emails, type_='to'):
        if not isinstance(emails, list): emails = [emails]
        for email in emails:
            self.add_recipient(email=email, type_=type_)

    def add_recipient(self, email, type_='to'):
        msg = self.msg

        if type_ == 'to':
            recipient = k.to_recipient
        elif type_ == 'cc':
            recipient = k.cc_recipient

        msg.make(new=recipient, with_properties={k.email_address: {k.address: email}})


问:
How to use margin on checkboxes so they will be on each other
I have the following code:

```<code>    <LinearLayout
        android:id="@+id/availability_sunday"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tile_divider"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/text_sunday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sunday:" />

        <CheckBox
            android:id="@+id/checkbox_sunday_morning"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="true"
            android:layout_width="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginStart="10dp" />

        <TextView
            android:id="@+id/text_sunday_morning"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Morning"/>

        <CheckBox
            android:id="@+id/checkbox_sunday_evening"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="true"
            android:layout_width="wrap_content" />

        <TextView
            android:id="@+id/text_sunday_evening"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Evening"/>
    </LinearLayout>
</code>```

In a RelativeLayout. I would like the layout to be:

```<code>Sunday     [] Morning [] Evening
Monday     [] Morning [] Evening
...
Thursday   [] Morning [] Evening
</code>```

But If I add the same block for monday I will get:

Because the work android:layout_marginStart and android:layout_marginLeft. I want the checkbox to be above each other. How can I do it?

答:
try Constraint layout it will be easier..

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--For sunday-->
<TextView
    android:id="@+id/text_sunday"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:text="Sunday:"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_sunday_morning"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@id/checkbox_sunday_morning" />

<CheckBox
    android:id="@+id/checkbox_sunday_morning"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:drawSelectorOnTop="true"
    app:layout_constraintStart_toEndOf="@id/text_sunday"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_sunday_morning"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="4dp"
    android:text="Morning"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_sunday_morning"
    app:layout_constraintStart_toEndOf="@id/checkbox_sunday_morning"
    app:layout_constraintTop_toTopOf="@id/checkbox_sunday_morning" />

<CheckBox
    android:id="@+id/checkbox_sunday_evening"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:drawSelectorOnTop="true"
    app:layout_constraintStart_toEndOf="@id/text_sunday_morning"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_sunday_evening"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Evening"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_sunday_evening"
    app:layout_constraintStart_toEndOf="@id/checkbox_sunday_evening"
    app:layout_constraintTop_toTopOf="@id/checkbox_sunday_evening" />
<!--for monday-->
<CheckBox
    android:id="@+id/checkbox_monday_morning"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:drawSelectorOnTop="true"
    app:layout_constraintStart_toStartOf="@id/checkbox_sunday_morning"
    app:layout_constraintTop_toBottomOf="@id/checkbox_sunday_morning" />

<TextView
    android:id="@+id/text_monday_morning"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="4dp"
    android:text="Morning"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_monday_morning"
    app:layout_constraintStart_toEndOf="@id/checkbox_monday_morning"
    app:layout_constraintTop_toTopOf="@id/checkbox_monday_morning" />

<CheckBox
    android:id="@+id/checkbox_monday_evening"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:drawSelectorOnTop="true"
    app:layout_constraintStart_toStartOf="@id/checkbox_sunday_evening"
    app:layout_constraintTop_toBottomOf="@id/checkbox_sunday_evening" />

<TextView
    android:id="@+id/text_Monday_evening"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Evening"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_monday_evening"
    app:layout_constraintStart_toEndOf="@id/checkbox_monday_evening"
    app:layout_constraintTop_toTopOf="@id/checkbox_monday_evening" />

<TextView
    android:id="@+id/text_monday"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:text="Monday:"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_monday_morning"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@id/checkbox_monday_morning" />
</code>```

Body:
I have the following code:

    <LinearLayout
        android:id="@+id/availability_sunday"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tile_divider"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/text_sunday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sunday:" />

        <CheckBox
            android:id="@+id/checkbox_sunday_morning"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="true"
            android:layout_width="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginStart="10dp" />

        <TextView
            android:id="@+id/text_sunday_morning"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Morning"/>

        <CheckBox
            android:id="@+id/checkbox_sunday_evening"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="true"
            android:layout_width="wrap_content" />

        <TextView
            android:id="@+id/text_sunday_evening"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Evening"/>
    </LinearLayout>

In a RelativeLayout. I would like the layout to be:

Sunday     [] Morning [] Evening
Monday     [] Morning [] Evening
...
Thursday   [] Morning [] Evening

But If I add the same block for monday I will get:

Because the work android:layout_marginStart and android:layout_marginLeft. I want the checkbox to be above each other. How can I do it?

Body:
try Constraint layout it will be easier..

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--For sunday-->
<TextView
    android:id="@+id/text_sunday"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:text="Sunday:"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_sunday_morning"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@id/checkbox_sunday_morning" />

<CheckBox
    android:id="@+id/checkbox_sunday_morning"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:drawSelectorOnTop="true"
    app:layout_constraintStart_toEndOf="@id/text_sunday"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_sunday_morning"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="4dp"
    android:text="Morning"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_sunday_morning"
    app:layout_constraintStart_toEndOf="@id/checkbox_sunday_morning"
    app:layout_constraintTop_toTopOf="@id/checkbox_sunday_morning" />

<CheckBox
    android:id="@+id/checkbox_sunday_evening"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:drawSelectorOnTop="true"
    app:layout_constraintStart_toEndOf="@id/text_sunday_morning"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_sunday_evening"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Evening"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_sunday_evening"
    app:layout_constraintStart_toEndOf="@id/checkbox_sunday_evening"
    app:layout_constraintTop_toTopOf="@id/checkbox_sunday_evening" />
<!--for monday-->
<CheckBox
    android:id="@+id/checkbox_monday_morning"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:drawSelectorOnTop="true"
    app:layout_constraintStart_toStartOf="@id/checkbox_sunday_morning"
    app:layout_constraintTop_toBottomOf="@id/checkbox_sunday_morning" />

<TextView
    android:id="@+id/text_monday_morning"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="4dp"
    android:text="Morning"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_monday_morning"
    app:layout_constraintStart_toEndOf="@id/checkbox_monday_morning"
    app:layout_constraintTop_toTopOf="@id/checkbox_monday_morning" />

<CheckBox
    android:id="@+id/checkbox_monday_evening"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:drawSelectorOnTop="true"
    app:layout_constraintStart_toStartOf="@id/checkbox_sunday_evening"
    app:layout_constraintTop_toBottomOf="@id/checkbox_sunday_evening" />

<TextView
    android:id="@+id/text_Monday_evening"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Evening"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_monday_evening"
    app:layout_constraintStart_toEndOf="@id/checkbox_monday_evening"
    app:layout_constraintTop_toTopOf="@id/checkbox_monday_evening" />

<TextView
    android:id="@+id/text_monday"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:text="Monday:"
    app:layout_constraintBottom_toBottomOf="@id/checkbox_monday_morning"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@id/checkbox_monday_morning" />


问:
How to repeat values in case of null values on left join
I have a table with a calendar, and a table with rates. In the table with the rates, there are no values existing for days in the weekend. I'm trying to join the two, in order to have a table where there is a rate for all days, and I need the rates in the weekend to be the latest available rate. Instad of it showing NULL values, as it would when you make a left join and the record doesn't exist, it should just take the latest available, repeating the previous value.

I have the below code, which works, but it takes 2 min to do on 7,397 rows, which is way too long.

Does anyone know a faster way to get the same results?

```<code>SELECT
c.CalendarID,
MAX(r.RateID)

FROM Dim_Calendar c

LEFT JOIN Dim_Rates r ON r.RateDate <= c.CalendarID
</code>```

What I get without <= and just an = is the following

```<code>CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | NULL
20131006   | NULL
20131007   | 6
</code>```

And this is the desired table:

```<code>CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | 5
20131006   | 5
20131007   | 6
</code>```

答:
As pointed out, you need to check for proper and covering indexing. It appears you are running a against a DW DB and if that is the case then you can replace the CTE with indexed temp tables if the esitmated row count approximation is way off in the query plan.</p>

```<code>;WITH NormalizedData AS
(
    SELECT
        RateID,CalendarID,
        VirtualGroupID = SUM(LastRecordBeforeGap) OVER (ORDER BY CalendarID ROWS UNBOUNDED PRECEDING)
    FROM
    (
        SELECT RateID,CalendarID,
        LastRecordBeforeGap = CASE WHEN LEAD(RateID) OVER(ORDER BY CalendarID) IS NULL AND RateID IS NOT NULL THEN 1 ELSE 0 END
        FROM
            Dim_Calendar  c
            LEFT JOIN Dim_Rates  r ON r.RateDate = c.CalendarID
    )AS x
)

SELECT
    RateID = ISNULL(RateID, SUM(RateID) OVER(PARTITION BY VirtualGroupID)),
    CalendarID
FROM
    NormalizedData
</code>```

Body:
I have a table with a calendar, and a table with rates. In the table with the rates, there are no values existing for days in the weekend. I'm trying to join the two, in order to have a table where there is a rate for all days, and I need the rates in the weekend to be the latest available rate. Instad of it showing NULL values, as it would when you make a left join and the record doesn't exist, it should just take the latest available, repeating the previous value.

I have the below code, which works, but it takes 2 min to do on 7,397 rows, which is way too long.

Does anyone know a faster way to get the same results?

SELECT
c.CalendarID,
MAX(r.RateID)

FROM Dim_Calendar c

LEFT JOIN Dim_Rates r ON r.RateDate <= c.CalendarID

What I get without <= and just an = is the following

CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | NULL
20131006   | NULL
20131007   | 6

And this is the desired table:

CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | 5
20131006   | 5
20131007   | 6

Body:
As pointed out, you need to check for proper and covering indexing. It appears you are running a against a DW DB and if that is the case then you can replace the CTE with indexed temp tables if the esitmated row count approximation is way off in the query plan.

;WITH NormalizedData AS
(
    SELECT
        RateID,CalendarID,
        VirtualGroupID = SUM(LastRecordBeforeGap) OVER (ORDER BY CalendarID ROWS UNBOUNDED PRECEDING)
    FROM
    (
        SELECT RateID,CalendarID,
        LastRecordBeforeGap = CASE WHEN LEAD(RateID) OVER(ORDER BY CalendarID) IS NULL AND RateID IS NOT NULL THEN 1 ELSE 0 END
        FROM
            Dim_Calendar  c
            LEFT JOIN Dim_Rates  r ON r.RateDate = c.CalendarID
    )AS x
)

SELECT
    RateID = ISNULL(RateID, SUM(RateID) OVER(PARTITION BY VirtualGroupID)),
    CalendarID
FROM
    NormalizedData


问:
conv1D does 2d convolution by default
So most guides to CNNs explain convolution in one dimension as a series of 1D kernels being convolved with your input sequence (Like traditional FIR filters). However, as far as i can understand, the default of conv1d implements convolution across all your channels for each output (essentially 2D convolution).
If the traditional FIR filter implementation is desired, you should specify groups=in_channels.

Inspecting the weights seems to verify this:

```<code>from torch import nn

C1 = nn.Conv1d(in_channels=3, out_channels=6, kernel_size=7)
C2 = nn.Conv1d(in_channels=3, out_channels=6, kernel_size=7,groups=3)
C3 = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=7)
C4 = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=7, groups=3)

print(C1.weight.shape, '<-- 6 filters which convolve across two dimensions')
print(C2.weight.shape, '<-- 6 filters which convolve across one dimensions')
print(C3.weight.shape, '<-- 6 filters which convolve across three dimensions')
print(C4.weight.shape, '<-- 6 filters which convolve across two dimensions')
</code>```

providing the following output:

```<code>torch.Size([6, 3, 7]) <-- 6 filters which convolve across two dimensions
torch.Size([6, 1, 7]) <-- 6 filters which convolve across one dimensions
torch.Size([6, 3, 7, 7]) <-- 6 filters which convolve across three dimensions
torch.Size([6, 1, 7, 7]) <-- 6 filters which convolve across two dimensions
</code>```

Am i wrong in this observation?

If a am correct, i believe the naming of conv1d is quite confusing as it implies 1d convolution.

答:
A few things to consider:

1) Conv1d runs a convolution with a kernel of 1 dimension (vector). C1  and C2 would have a kernel of size (7).

2) Conv2d runs a convolution with a kernel of 2 dimensions (matrix). C3 and C4 would have a kernel of size (7, 7).

3) Groups are a way to control connections between the input and output channels, were you can produce several simultaneous convolutions at the same time.

More information here.

Title: conv1D does 2d convolution by default

Body:
So most guides to CNNs explain convolution in one dimension as a series of 1D kernels being convolved with your input sequence (Like traditional FIR filters). However, as far as i can understand, the default of conv1d implements convolution across all your channels for each output (essentially 2D convolution).
If the traditional FIR filter implementation is desired, you should specify groups=in_channels.

Inspecting the weights seems to verify this:

from torch import nn

C1 = nn.Conv1d(in_channels=3, out_channels=6, kernel_size=7)
C2 = nn.Conv1d(in_channels=3, out_channels=6, kernel_size=7,groups=3)
C3 = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=7)
C4 = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=7, groups=3)

print(C1.weight.shape, '<-- 6 filters which convolve across two dimensions')
print(C2.weight.shape, '<-- 6 filters which convolve across one dimensions')
print(C3.weight.shape, '<-- 6 filters which convolve across three dimensions')
print(C4.weight.shape, '<-- 6 filters which convolve across two dimensions')

providing the following output:

torch.Size([6, 3, 7]) <-- 6 filters which convolve across two dimensions
torch.Size([6, 1, 7]) <-- 6 filters which convolve across one dimensions
torch.Size([6, 3, 7, 7]) <-- 6 filters which convolve across three dimensions
torch.Size([6, 1, 7, 7]) <-- 6 filters which convolve across two dimensions

Am i wrong in this observation?

If a am correct, i believe the naming of conv1d is quite confusing as it implies 1d convolution.


问:
How does foursquare determine the timezone of a checkin?
Looking at their checkin api when you add a checkin it does not require passing in any datetime or timezone information, but when you query a users checkin history it returns a timezone field indicating the timezone of where the checkin took place. I imagine somehow they're looking it up by lat/lng or something. Does anyone know specifically how they're doing it?</p>

答:
It's most certainly a location-based look up against the check-in location.

My guess is that they compute and cache the timezone for a venue when it is created.  I'd store this information as a map of tuples to strings keyed on data like city,[state],country in a distributed hash table database like memcached.  I'd keep bounding polygons available for each timezone (as well as many other geographic data) and provide a service for querying it based on lat/lon.  This is typically called a geocoding service.  Depending on memory constraints and usage variability, I'd populate the tuple mapping from this service lazily (ie, only as users request it).

For venueless check-ins they probably compute it once based on the lat/lon and cache this information for a shorter period of time in case others perform check-ins to the same location.  I'd bet that they also routinely take advantage of the fact that the timezone field is optional and don't populate it if the geocoding service is overloaded.

If you're looking for a service which can handle these kinds of queries, check out http://www.geonames.com (documentation).


问:
How do I get sum of two different columns from two diffrent tables and group them
I have two tables which I wanna perform join between two tables and group them by date

Table one is fb_data

```<code>id  name created_at           revenue
1   as   2020-05-29 19:30:54  5
2   as   2020-05-28 19:30:54  10
3   ad   2020-05-29 19:31:42  6
4  ad    2020-05-28 19:31:54 65
5  as    2020-05-29 19:32:10 7
6  ad    2020-05-28 19:31:54 5
</code>```

Table two is google_data

```<code>id name   created_at           sessions
1  as     2020-05-29 19:38:32    5
2  ad     2020-05-29 19:38:41    10
3  as      2020-05-29 19:38:49   7
4  as      2020-05-28 19:39:02   6
5  ad     2020-05-28 19:39:13   8
6  ad    2020-05-28 19:41:41   13
</code>```

Now what I want is to join two columns by name then group them by created_at . Something like this

```<code>Name , date(created_at) as date , sum(fb_data.revenue) , sum(google_data.revenue)
</code>```

I have one sql query but that doesn't gives result as I expected

```<code>select gd.name,fb.total_revenue,fb.created_at,gd.total_sessions
from (select date(fb_data.created_at) as created_at, sum(fb_data.revenue) as total_revenue, name
      from fb_data
      group by date(fb_data.created_at), name) fb,
     (select date(google_data.created_at) as created_at, sum(google_data.session) as total_sessions, name
      from google_data
      group by name, date(google_data.created_at)) as gd
      where fb.name = gd.name
      group by  gd.name,fb.name,fb.created_at,gd.total_sessions
</code>```

The result I get is

```<code>Name total_revenue   created_at     total_sessions
as   12              2020-05-29     12
as   12              2020-05-29     6
as   10              2020-05-28     12
as   10              2020-05-28     6
ad   6               2020-05-29     10
ad   6              2020-05-29      21
ad  70             2020-05-28       10
ad  70             2020-05-28      21
</code>```

The result that I am expecting is

```<code>name  total_revenue   created_at total_sessions
as    12              2020-05-29   12
as    10              2020-05-28   6
ad    6               2020-05-29   10
ad    70              2020-05-28   21
</code>```

答:
Please use below query,</p>

```<code>select gd.name,fb.total_revenue,fb.created_at, max(gd.total_sessions)
from (select date(fb_data.created_at) as created_at, sum(fb_data.revenue) as
total_revenue, name
  from fb_data
  group by date(fb_data.created_at), name) fb,
 (select date(google_data.created_at) as created_at, sum(google_data.session) as
total_sessions, name
  from google_data
  group by name, date(google_data.created_at)) as gd
  where fb.name = gd.name
  group by  gd.name,fb.name,fb.created_at;
</code>```

Body:
I have two tables which I wanna perform join between two tables and group them by date

Table one is fb_data

id  name created_at           revenue
1   as   2020-05-29 19:30:54  5
2   as   2020-05-28 19:30:54  10
3   ad   2020-05-29 19:31:42  6
4  ad    2020-05-28 19:31:54 65
5  as    2020-05-29 19:32:10 7
6  ad    2020-05-28 19:31:54 5

Table two is google_data

id name   created_at           sessions
1  as     2020-05-29 19:38:32    5
2  ad     2020-05-29 19:38:41    10
3  as      2020-05-29 19:38:49   7
4  as      2020-05-28 19:39:02   6
5  ad     2020-05-28 19:39:13   8
6  ad    2020-05-28 19:41:41   13

Now what I want is to join two columns by name then group them by created_at . Something like this

Name , date(created_at) as date , sum(fb_data.revenue) , sum(google_data.revenue)

I have one sql query but that doesn't gives result as I expected

select gd.name,fb.total_revenue,fb.created_at,gd.total_sessions
from (select date(fb_data.created_at) as created_at, sum(fb_data.revenue) as total_revenue, name
      from fb_data
      group by date(fb_data.created_at), name) fb,
     (select date(google_data.created_at) as created_at, sum(google_data.session) as total_sessions, name
      from google_data
      group by name, date(google_data.created_at)) as gd
      where fb.name = gd.name
      group by  gd.name,fb.name,fb.created_at,gd.total_sessions

The result I get is

Name total_revenue   created_at     total_sessions
as   12              2020-05-29     12
as   12              2020-05-29     6
as   10              2020-05-28     12
as   10              2020-05-28     6
ad   6               2020-05-29     10
ad   6              2020-05-29      21
ad  70             2020-05-28       10
ad  70             2020-05-28      21

The result that I am expecting is

name  total_revenue   created_at total_sessions
as    12              2020-05-29   12
as    10              2020-05-28   6
ad    6               2020-05-29   10
ad    70              2020-05-28   21

Body:
Please use below query,

select gd.name,fb.total_revenue,fb.created_at, max(gd.total_sessions)
from (select date(fb_data.created_at) as created_at, sum(fb_data.revenue) as
total_revenue, name
  from fb_data
  group by date(fb_data.created_at), name) fb,
 (select date(google_data.created_at) as created_at, sum(google_data.session) as
total_sessions, name
  from google_data
  group by name, date(google_data.created_at)) as gd
  where fb.name = gd.name
  group by  gd.name,fb.name,fb.created_at;


问:
SQL Merge statement with indexed view
I am using SQL Server 2016 and am trying to create a MERGE statement that will insert a new record if it doesn't exist or grab the id of the record if it does exists.

This is working properly, but is having the unintended side affect of causing an indexed view to be updated, even though there is no data being updated when I run this multiple times.

Is this expected behavior or am I just doing something wrong?

Intuitively I guess I would expect that because the merge finds a match, then only updates a local variable, no changes to the indexed view would show up at all in the execution plan.

```<code>CREATE TABLE dbo.Customer
(
    CustomerId INT IDENTITY(100,1) PRIMARY KEY NOT NULL,
    CustomerName VARCHAR(100) NOT NULL
)
GO

CREATE VIEW dbo.Customer_v
WITH SCHEMABINDING
AS
    SELECT CustomerId, CustomerName
    FROM dbo.Customer
GO

CREATE UNIQUE CLUSTERED INDEX [CL_IX_Customer_v]
ON dbo.Customer_v(CustomerId ASC);
GO

DECLARE @CustomerId AS INT
DECLARE @CustomerName AS VARCHAR(100) = 'Mike Smith'
DECLARE @WasCustomerCreated AS BIT = 0
DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

MERGE INTO dbo.Customer AS Target
USING (VALUES (@CustomerName)) AS Source (CustomerName) ON (Target.CustomerName = Source.CustomerName)

WHEN MATCHED THEN
    UPDATE SET @CustomerId = Target.CustomerId

WHEN NOT MATCHED THEN
    INSERT (CustomerName) VALUES (@CustomerName)

OUTPUT $action INTO @SummaryOfChanges;

IF EXISTS(SELECT * FROM @SummaryOfChanges WHERE Change = 'Insert')
BEGIN
    SET @WasCustomerCreated = 1
    SET @CustomerId = SCOPE_IDENTITY()
END

SELECT @CustomerId AS CustomerId, @WasCustomerCreated AS WasCustomerCreated
</code>```

答:
You can add "AND @CustomerId <> Target.CustomerId" to the merge statement:</p>

```<code>MERGE INTO dbo.Customer AS Target
USING (VALUES(@CustomerName)) AS Source (CustomerName)
ON (Target.CustomerName = Source.CustomerName)
WHEN MATCHED AND @CustomerId <> Target.CustomerId THEN UPDATE SET @CustomerId = Target.CustomerId
WHEN NOT MATCHED THEN INSERT (CustomerName) VALUES (@CustomerName)
OUTPUT $action INTO @SummaryOfChanges;
</code>```

Title: SQL Merge statement with indexed view

Body:
I am using SQL Server 2016 and am trying to create a MERGE statement that will insert a new record if it doesn't exist or grab the id of the record if it does exists.

This is working properly, but is having the unintended side affect of causing an indexed view to be updated, even though there is no data being updated when I run this multiple times.

Is this expected behavior or am I just doing something wrong?

Intuitively I guess I would expect that because the merge finds a match, then only updates a local variable, no changes to the indexed view would show up at all in the execution plan.

CREATE TABLE dbo.Customer
(
    CustomerId INT IDENTITY(100,1) PRIMARY KEY NOT NULL,
    CustomerName VARCHAR(100) NOT NULL
)
GO

CREATE VIEW dbo.Customer_v
WITH SCHEMABINDING
AS
    SELECT CustomerId, CustomerName
    FROM dbo.Customer
GO

CREATE UNIQUE CLUSTERED INDEX [CL_IX_Customer_v]
ON dbo.Customer_v(CustomerId ASC);
GO

DECLARE @CustomerId AS INT
DECLARE @CustomerName AS VARCHAR(100) = 'Mike Smith'
DECLARE @WasCustomerCreated AS BIT = 0
DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));

MERGE INTO dbo.Customer AS Target
USING (VALUES (@CustomerName)) AS Source (CustomerName) ON (Target.CustomerName = Source.CustomerName)

WHEN MATCHED THEN
    UPDATE SET @CustomerId = Target.CustomerId

WHEN NOT MATCHED THEN
    INSERT (CustomerName) VALUES (@CustomerName)

OUTPUT $action INTO @SummaryOfChanges;

IF EXISTS(SELECT * FROM @SummaryOfChanges WHERE Change = 'Insert')
BEGIN
    SET @WasCustomerCreated = 1
    SET @CustomerId = SCOPE_IDENTITY()
END

SELECT @CustomerId AS CustomerId, @WasCustomerCreated AS WasCustomerCreated

Body:
You can add "AND @CustomerId <> Target.CustomerId" to the merge statement:

MERGE INTO dbo.Customer AS Target
USING (VALUES(@CustomerName)) AS Source (CustomerName)
ON (Target.CustomerName = Source.CustomerName)
WHEN MATCHED AND @CustomerId <> Target.CustomerId THEN UPDATE SET @CustomerId = Target.CustomerId
WHEN NOT MATCHED THEN INSERT (CustomerName) VALUES (@CustomerName)
OUTPUT $action INTO @SummaryOfChanges;


问:
How to change the color of a widget while it is pressed in flutter?
I have a Widget, and I want to change its background color while the user is pressing it, and when the pressing is finished, it returns to its original color.

I tried to use a GestureDetector, implementing onTapDown and onTapUp functions, but it doesn't work: it takes a long time (~150ms) to change color and, if I tap at normal speed, the color doesn't change.

I am an Android developer, and what I want to do is done in Android using a selector as follows:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="..." android:state_pressed="true" />
  <item android:drawable="..." />
</selector>.
</code>```

But I don't know how to do that with flutter. I hope the piece of code will help to understand what I want to achieve.

答:
you was doing it right using GestureDetector but you used the wrong methods, the one you have used are onLongPressStart and onLongPressEnd like the example below:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _changeColor = false;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: GestureDetector(
        onLongPressStart: (_) => setState(() => _changeColor = !_changeColor),
        onLongPressEnd: (_) => setState(() => _changeColor = !_changeColor),
        child: Container(
          color: _changeColor ? Colors.red : Colors.yellow,
          child: Text('Change color'),
        ),
      ),
    );
  }
}
```

<p>another way of doing it is by using <code>MaterialStateColor</code> class as suggested by @pskink</p>

<pre class="lang-dart prettyprint-override"><code>class MyApp extends StatelessWidget {
  Color getTextColor(Set<MaterialState> states) {
    const Set<MaterialState> interactiveStates = <MaterialState>{
      MaterialState.pressed,
      MaterialState.hovered,
      MaterialState.focused,
    };
    if (states.any(interactiveStates.contains)) {
// the color to return when button is in pressed, hovered, focused state
      return Colors.red;
    }
// the color to return when button is in it's normal/unfocused state
    return Colors.yellow;
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: FlatButton(
        child: Text('FlatButton'),
        onPressed: () {},
        textColor: MaterialStateColor.resolveWith(getTextColor),
      ),
    );
  }
}
</code>```

Body:
I have a Widget, and I want to change its background color while the user is pressing it, and when the pressing is finished, it returns to its original color.

I tried to use a GestureDetector, implementing onTapDown and onTapUp functions, but it doesn't work: it takes a long time (~150ms) to change color and, if I tap at normal speed, the color doesn't change.

I am an Android developer, and what I want to do is done in Android using a selector as follows:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="..." android:state_pressed="true" />
  <item android:drawable="..." />
</selector>.

But I don't know how to do that with flutter. I hope the piece of code will help to understand what I want to achieve.

Body:
you was doing it right using GestureDetector but you used the wrong methods, the one you have used are onLongPressStart and onLongPressEnd like the example below:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _changeColor = false;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: GestureDetector(
        onLongPressStart: (_) => setState(() => _changeColor = !_changeColor),
        onLongPressEnd: (_) => setState(() => _changeColor = !_changeColor),
        child: Container(
          color: _changeColor ? Colors.red : Colors.yellow,
          child: Text('Change color'),
        ),
      ),
    );
  }
}

another way of doing it is by using MaterialStateColor class as suggested by @pskink

class MyApp extends StatelessWidget {
  Color getTextColor(Set<MaterialState> states) {
    const Set<MaterialState> interactiveStates = <MaterialState>{
      MaterialState.pressed,
      MaterialState.hovered,
      MaterialState.focused,
    };
    if (states.any(interactiveStates.contains)) {
// the color to return when button is in pressed, hovered, focused state
      return Colors.red;
    }
// the color to return when button is in it's normal/unfocused state
    return Colors.yellow;
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: FlatButton(
        child: Text('FlatButton'),
        onPressed: () {},
        textColor: MaterialStateColor.resolveWith(getTextColor),
      ),
    );
  }
}


问:
Xamarin.Forms Image gif animation doesn't play on android
I'am new to Xamarin and I try to play a Gif in a Image control. In my iOS Emulator it works very well but when I start the app in my Android emulator, the gif doesn't play. I don't use Legacy Renderer but I never specified using fast renderer (but I don't have to I think).
Thats my XAML File:

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Connect.Views.SplashPage">
<ContentPage.Content>
    <StackLayout Margin="20,35,20,20">
        <Image Source="splashAni.gif" VerticalOptions="CenterAndExpand"
               HorizontalOptions="Center" IsAnimationPlaying="True"/>
    </StackLayout>
</ContentPage.Content>
</code>```

I don't know what's wrong, I hope you can help me, thanks in advance!

答:
A bit late to the game here but here is a working example by Gerald Versluis that I was able to use to test some scenarios. It's a basic example that links out to source code on GitHub.

I'm suspicious that your resource might not be included in the Android project and it's not able to find the file. In Gerald's example his animated gif is located in both AnimatedGifForms.Android\Resources\drawable and AnimatedGifForms.iOS\Resources respectively.

Though you do mention it works for you in iOS. It may be worth your time to look at his simple example and compare it to what you're doing.

On that note:

I've tried using a modified version of his example to load an animated gif that is an EmbeddedResource in the NetStandard shared library of the project but have been unsuccessful. I'm using the ImageSource.FromStream( () => assembly.GetManifestResourceStream( resourcePath ) ); method to create the ImageSource from a stream in a binding converter. I can load static gif images without problems this way. I can even load the animated image, as a static image without issue (the IsAnimationPlaying property must be absent from the xaml), but when I add/set the IsAnimationPlaying property in xaml the Android app crashes with the following:

```<code>=================================================================
    Native Crash Reporting
=================================================================
Got a SEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================

No native Android stacktrace (see debuggerd output).

=================================================================
    Basic Fault Address Reporting
=================================================================
Memory around native instruction pointer (0x8c83a896):
0x8c83a886  10 8d 4d e4 8b 4d 10 89 4d e4 8d 4d e4 8b 4d e4  ..M..M..M..M..M.
0x8c83a896  89 4c 24 08 89 44 24 04 89 3c 24 8b c0 e8 c0 fe  .L$..D$..<$.....
0x8c83a8a6  ff ff 89 45 c4 8b 4d f0 8d 64 24 00 90 90 90 8b  ...E..M..d$.....
0x8c83a8b6  45 c4 e9 77 00 00 00 8b 4d f0 8d 64 24 00 90 90  E..w....M..d$...

=================================================================
    Managed Stacktrace:
=================================================================
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0012e>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0
.....
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform
.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.StreamImagesourceHandler:LoadImageAnimationAsync <0x0005b>
      at <UpdateBitmap>d__2:MoveNext <0x00768>
      at System.Runtime.CompilerServices.AsyncTaskMethodBuilder:Start <0x00127>
      at Xamarin.Forms.Platform.Android.ImageViewExtensions:UpdateBitmap <0x001bf>
      at Xamarin.Forms.Platform.Android.ImageViewExtensions:UpdateBitmap <0x00067>
      at <TryUpdateBitmap>d__6:MoveNext <0x0028f>
      at System.Runtime.CompilerServices.AsyncTaskMethodBuilder:Start <0x00147>
      at Xamarin.Forms.Platform.Android.FastRenderers.ImageElementManager:TryUpdateBitmap <0x0019b>
      at <OnElementChanged>d__3:MoveNext <0x004b7>
      at System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start <0x00127>
      at Xamarin.Forms.Platform.Android.FastRenderers.ImageElementManager:OnElementChanged <0x0015f>
      at System.EventHandler`1:invoke_void_object_TEventArgs <0x00143>
      at Xamarin.Forms.Platform.Android.FastRenderers.ImageRenderer:OnEl
ementChanged <0x0011b>
      at Xamarin.Forms.Platform.Android.FastRenderers.ImageRenderer:Xamarin.Forms.Platform.Android.IVisualElementRenderer.SetElement <0x005d7>
      at Xamarin.Forms.Platform.Android.Platform:CreateRenderer <0x0013f>
      at Xamarin.Forms.Platform.Android.VisualElementPackager:AddChild <0x00487>
      at Xamarin.Forms.Platform.Android.VisualElementPackager:SetElement <0x00837>
      at Xamarin.Forms.Platform.Android.VisualElementPackager:Load <0x00057>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:SetPackager <0x00077>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:SetElement <0x007b7>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:Xamarin.Forms.Platform.Android.IVisualElementRenderer.SetElement <0x00187>
      at Xamarin.Forms.Platform.Android.Platform:CreateRenderer <0x0013f>
      at Xamarin.Forms.Platform.Android.VisualElementPackager:AddChild <0x00487>
      at Xamarin.Forms.Platform.Android.VisualElementPackager:SetElement <0x00837>
      at Xamarin.Forms.Platform
.Android.VisualElementPackager:Load <0x00057>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:SetPackager <0x00077>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:SetElement <0x007b7>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:Xamarin.Forms.Platform.Android.IVisualElementRenderer.SetElement <0x00187>
      at Xamarin.Forms.Platform.Android.Platform:CreateRenderer <0x0013f>
      at Xamarin.Forms.Platform.Android.AppCompat.Platform:AddChild <0x000b3>
      at Xamarin.Forms.Platform.Android.AppCompat.Platform:SetPageInternal <0x00297>
      at Xamarin.Forms.Platform.Android.AppCompat.Platform:SetPage <0x0067f>
      at Xamarin.Forms.Platform.Android.FormsAppCompatActivity:InternalSetPage <0x001b7>
      at Xamarin.Forms.Platform.Android.FormsAppCompatActivity:SetMainPage <0x00077>
      at Xamarin.Forms.Platform.Android.FormsAppCompatActivity:LoadApplication <0x0067b>
      at AnimatedGifForms.Droid.MainActivity:OnCreate <0x00143>
      at Android.App.Activity:n_OnCreate_Landroid_os_Bundle_ <0
x000ab>
      at Android.Runtime.DynamicMethodNameCounter:8 <0x000c3>
      at Android.Runtime.DynamicMethodNameCounter:8 <0x000b3>
=================================================================
[HotReload] (2020-05-29 10:24:00.4): ERROR: Caught exception in AgentStatusChangedHandler at 212: Xamarin.HotReload.DebuggerTimeoutException: Failed to Inject Assembly
   at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)
   at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)
</code>```

Which continues ad nauseam for pages and then it just dies. I've upgraded to the latest version of Xamarin.Forms (4.6.0.772) and Essentials (1.5.3.2) with no change in outcome.

Body:
I'am new to Xamarin and I try to play a Gif in a Image control. In my iOS Emulator it works very well but when I start the app in my Android emulator, the gif doesn't play. I don't use Legacy Renderer but I never specified using fast renderer (but I don't have to I think).
Thats my XAML File:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Connect.Views.SplashPage">
<ContentPage.Content>
    <StackLayout Margin="20,35,20,20">
        <Image Source="splashAni.gif" VerticalOptions="CenterAndExpand"
               HorizontalOptions="Center" IsAnimationPlaying="True"/>
    </StackLayout>
</ContentPage.Content>

I don't know what's wrong, I hope you can help me, thanks in advance!

Body:
A bit late to the game here but here is a working example by Gerald Versluis that I was able to use to test some scenarios. It's a basic example that links out to source code on GitHub.

I'm suspicious that your resource might not be included in the Android project and it's not able to find the file. In Gerald's example his animated gif is located in both AnimatedGifForms.Android\Resources\drawable and AnimatedGifForms.iOS\Resources respectively.

Though you do mention it works for you in iOS. It may be worth your time to look at his simple example and compare it to what you're doing.

On that note:

I've tried using a modified version of his example to load an animated gif that is an EmbeddedResource in the NetStandard shared library of the project but have been unsuccessful. I'm using the ImageSource.FromStream( () => assembly.GetManifestResourceStream( resourcePath ) ); method to create the ImageSource from a stream in a binding converter. I can load static gif images without problems this way. I can even load the animated image, as a static image without issue (the IsAnimationPlaying property must be absent from the xaml), but when I add/set the IsAnimationPlaying property in xaml the Android app crashes with the following:

=================================================================
    Native Crash Reporting
=================================================================
Got a SEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================

No native Android stacktrace (see debuggerd output).

=================================================================
    Basic Fault Address Reporting
=================================================================
Memory around native instruction pointer (0x8c83a896):
0x8c83a886  10 8d 4d e4 8b 4d 10 89 4d e4 8d 4d e4 8b 4d e4  ..M..M..M..M..M.
0x8c83a896  89 4c 24 08 89 44 24 04 89 3c 24 8b c0 e8 c0 fe  .L$..D$..<$.....
0x8c83a8a6  ff ff 89 45 c4 8b 4d f0 8d 64 24 00 90 90 90 8b  ...E..M..d$.....
0x8c83a8b6  45 c4 e9 77 00 00 00 8b 4d f0 8d 64 24 00 90 90  E..w....M..d$...

=================================================================
    Managed Stacktrace:
=================================================================
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0012e>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0
.....
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform
.Android.FormsAnimationDrawable:LoadImageAnimationAsync <0x0013f>
      at Xamarin.Forms.Platform.Android.StreamImagesourceHandler:LoadImageAnimationAsync <0x0005b>
      at <UpdateBitmap>d__2:MoveNext <0x00768>
      at System.Runtime.CompilerServices.AsyncTaskMethodBuilder:Start <0x00127>
      at Xamarin.Forms.Platform.Android.ImageViewExtensions:UpdateBitmap <0x001bf>
      at Xamarin.Forms.Platform.Android.ImageViewExtensions:UpdateBitmap <0x00067>
      at <TryUpdateBitmap>d__6:MoveNext <0x0028f>
      at System.Runtime.CompilerServices.AsyncTaskMethodBuilder:Start <0x00147>
      at Xamarin.Forms.Platform.Android.FastRenderers.ImageElementManager:TryUpdateBitmap <0x0019b>
      at <OnElementChanged>d__3:MoveNext <0x004b7>
      at System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start <0x00127>
      at Xamarin.Forms.Platform.Android.FastRenderers.ImageElementManager:OnElementChanged <0x0015f>
      at System.EventHandler`1:invoke_void_object_TEventArgs <0x00143>
      at Xamarin.Forms.Platform.Android.FastRenderers.ImageRenderer:OnEl
ementChanged <0x0011b>
      at Xamarin.Forms.Platform.Android.FastRenderers.ImageRenderer:Xamarin.Forms.Platform.Android.IVisualElementRenderer.SetElement <0x005d7>
      at Xamarin.Forms.Platform.Android.Platform:CreateRenderer <0x0013f>
      at Xamarin.Forms.Platform.Android.VisualElementPackager:AddChild <0x00487>
      at Xamarin.Forms.Platform.Android.VisualElementPackager:SetElement <0x00837>
      at Xamarin.Forms.Platform.Android.VisualElementPackager:Load <0x00057>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:SetPackager <0x00077>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:SetElement <0x007b7>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:Xamarin.Forms.Platform.Android.IVisualElementRenderer.SetElement <0x00187>
      at Xamarin.Forms.Platform.Android.Platform:CreateRenderer <0x0013f>
      at Xamarin.Forms.Platform.Android.VisualElementPackager:AddChild <0x00487>
      at Xamarin.Forms.Platform.Android.VisualElementPackager:SetElement <0x00837>
      at Xamarin.Forms.Platform
.Android.VisualElementPackager:Load <0x00057>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:SetPackager <0x00077>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:SetElement <0x007b7>
      at Xamarin.Forms.Platform.Android.VisualElementRenderer`1:Xamarin.Forms.Platform.Android.IVisualElementRenderer.SetElement <0x00187>
      at Xamarin.Forms.Platform.Android.Platform:CreateRenderer <0x0013f>
      at Xamarin.Forms.Platform.Android.AppCompat.Platform:AddChild <0x000b3>
      at Xamarin.Forms.Platform.Android.AppCompat.Platform:SetPageInternal <0x00297>
      at Xamarin.Forms.Platform.Android.AppCompat.Platform:SetPage <0x0067f>
      at Xamarin.Forms.Platform.Android.FormsAppCompatActivity:InternalSetPage <0x001b7>
      at Xamarin.Forms.Platform.Android.FormsAppCompatActivity:SetMainPage <0x00077>
      at Xamarin.Forms.Platform.Android.FormsAppCompatActivity:LoadApplication <0x0067b>
      at AnimatedGifForms.Droid.MainActivity:OnCreate <0x00143>
      at Android.App.Activity:n_OnCreate_Landroid_os_Bundle_ <0
x000ab>
      at Android.Runtime.DynamicMethodNameCounter:8 <0x000c3>
      at Android.Runtime.DynamicMethodNameCounter:8 <0x000b3>
=================================================================
[HotReload] (2020-05-29 10:24:00.4): ERROR: Caught exception in AgentStatusChangedHandler at 212: Xamarin.HotReload.DebuggerTimeoutException: Failed to Inject Assembly
   at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)
   at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)

Which continues ad nauseam for pages and then it just dies. I've upgraded to the latest version of Xamarin.Forms (4.6.0.772) and Essentials (1.5.3.2) with no change in outcome.