问:
html radio button has to be selected by default on page load
I am trying to do make the radio button selected by default on page load.

From the below screen it is a frame which is loaded. I am trying to make the radio buttons enable by using

document.formName.radioButtonId[1].checked = true;

Where formName is my form name that I declared in html, radioButtonId is id for radio button I used in html.

```<code><div>
 <form name = "formName">
.
.
.
.
   <div>
     <input type = "radio"
            id = "radioButton"
.
.
.
   </div>
 </form>
</div>

</code>```

So my expectation is from the above code Joe radio button has to be enabled.

But the html is not completely loaded and when I do
document.formName.radioButtonId[1].checked = true; the error on console says radioButton was undefined because of the form is not available.

I am not able to access any of the elements from form until it is completely loaded. Is there any way that I can check for the page title is loaded or visible then do the condition that I want to do?

I tried

```<code>if (document.readyState === "complete") { //do something }
</code>```

This didn't work because document.readyState is always complete as the document is referring to parent document from the screenshot you can see it was referring to background page.

Once the Modify Name is completely loaded then I was able to access formName form and I was able to make Joe as selected using document.formName.radioButtonId[1].checked = true;

I am making Joe as checked based on condition from the code that I have (fyi). That might change so want to be generic.

[![Modify Name is child to background image like a popup][2]][2]
Need help on how to make Joe as checked after loading the page automatically.

答:
Just put checked inline HTML :

e.g:

```<code><input type = "radio" id = "radioButton" value="Joe" checked>Joe
</code>```

Body:
I am trying to do make the radio button selected by default on page load.

From the below screen it is a frame which is loaded. I am trying to make the radio buttons enable by using

document.formName.radioButtonId[1].checked = true;

Where formName is my form name that I declared in html, radioButtonId is id for radio button I used in html.

 <form name = "formName">
.
.
.
.

     <input type = "radio"
            id = "radioButton"
.
.
.

 </form>

So my expectation is from the above code Joe radio button has to be enabled.

But the html is not completely loaded and when I do
document.formName.radioButtonId[1].checked = true; the error on console says radioButton was undefined because of the form is not available.

I am not able to access any of the elements from form until it is completely loaded. Is there any way that I can check for the page title is loaded or visible then do the condition that I want to do?

I tried

if (document.readyState === "complete") { //do something }

This didn't work because document.readyState is always complete as the document is referring to parent document from the screenshot you can see it was referring to background page.

Once the Modify Name is completely loaded then I was able to access formName form and I was able to make Joe as selected using document.formName.radioButtonId[1].checked = true;

I am making Joe as checked based on condition from the code that I have (fyi). That might change so want to be generic.

[![Modify Name is child to background image like a popup][2]][2]
Need help on how to make Joe as checked after loading the page automatically.

Body:
Just put checked inline HTML :

e.g:

<input type = "radio" id = "radioButton" value="Joe" checked>Joe


来源: stackexchange

问:
Safari doesn't open .pkpass wallet pass
I have read all similar issues posted on PassKit and pass download issues with Safari.

Tried mime to Apple pass type in header from handler lambda.
My case might be a bit different.

Have a create_pass lambda handler function hosted behind API Gateway.

Set binary encoding to true.
Binary type to / in API GW.

Iam able to download .pkpass file in windows and android. The link downloads first when clicked on downloaded file opens in Passes App in android.

Using the same download link throws errors on IOS with Chrome and Safari.

Has anyone had same errors?

Thnx!

答:
The generated pass wasnt working, think Safari is trying to preview and it fails.
Tried with a diffrent pass certifate and key and it worked.</p>

ContentLicense: CC BY-SA 4.0

Title: Safari doesn't open .pkpass wallet pass


问:
Css3 evaluatable expressions?
Are there any techniques that allow for expressions in css3 statements?

Frequently it is helpful to do such things as width: 35%+20px or similar. Right now the only solutions I have to these circumstances are to either redesign the page or to use javascript to dynamically set the css.

答:
The calc() function can be used wherever length values are allowed.  This is defined in CSS3 Values and Units (see http://www.w3.org/TR/css3-values/).  I don't know what browser are supporting it.</p>

```<code>section {
   float: left;
   margin: 1em; border: solid 1px;
   width: calc(100%/3 - 2*1em - 2*1px);
}

p {
   margin: calc(1rem - 2px) calc(1rem - 1px);
   border: solid transparent; border-width: 2px 1px;
}
p:hover { border-color: yellow; }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Css3 evaluatable expressions?

Body:
The calc() function can be used wherever length values are allowed.  This is defined in CSS3 Values and Units (see http://www.w3.org/TR/css3-values/).  I don't know what browser are supporting it.

section {
   float: left;
   margin: 1em; border: solid 1px;
   width: calc(100%/3 - 2*1em - 2*1px);
}

p {
   margin: calc(1rem - 2px) calc(1rem - 1px);
   border: solid transparent; border-width: 2px 1px;
}
p:hover { border-color: yellow; }


问:
Unnecessary border shown when clicked content area on understrap theme
I'm developing wordpress theme using Understrap, with using customstrap child theme of livecanvas. It uses Bootstrap 4.

I developed my theme, but there is unnecessary border when I clicked the content area on theme. I checked the code on browser using inspects but i could not find the code that caused this problem.

here is understrap repo: https://github.com/understrap/understrap

and my page.php

```<code><?php
/**
 * The template for displaying all pages
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package understrap
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

get_header();

$container = get_theme_mod( 'understrap_container_type' );

?>

<div class="wrapper" id="page-wrapper">

    <div class="<?php echo esc_attr( $container ); ?>" id="content" tabindex="-1">

        <div class="row">

            <!-- Do the left sidebar check -->
            <?php get_template_part( 'global-templates/left-sidebar-check' ); ?>

            <main class="site-main" id="main">

                <?php
                while ( have_posts() ) {
                    the_post();
                    get_template_part( 'loop-templates/content', 'page' );

                }
                ?>

            </main><!-- #main -->

            <!-- Do the right sidebar check -->
            <?php get_template_part( 'global-templates/right-sidebar-check' ); ?>

        </div><!-- .row -->

    </div><!-- #content -->

</div><!-- #page-wrapper -->

<?php
get_footer();
</code>```

Which selector that I need to use to prevent this problem?

Here is the image of this be like:

1- 1st image is Default

2- 2nd image When I clicked the content area

When I clicked the content area

答:
When I add the code below to custom css in wordpress:

```<code>*:focus{outline: none !important;}
</code>```

It works.

But I don't understand that why it does not work when I add it into style.css

Body:
I'm developing wordpress theme using Understrap, with using customstrap child theme of livecanvas. It uses Bootstrap 4.

I developed my theme, but there is unnecessary border when I clicked the content area on theme. I checked the code on browser using inspects but i could not find the code that caused this problem.

here is understrap repo: https://github.com/understrap/understrap

and my page.php

<?php
/**
 * The template for displaying all pages
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package understrap
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

get_header();

$container = get_theme_mod( 'understrap_container_type' );

?>

    <div class="<?php echo esc_attr( $container ); ?>" id="content" tabindex="-1">

            <?php get_template_part( 'global-templates/left-sidebar-check' ); ?>

                <?php
                while ( have_posts() ) {
                    the_post();
                    get_template_part( 'loop-templates/content', 'page' );

                }
                ?>

            <?php get_template_part( 'global-templates/right-sidebar-check' ); ?>

<?php
get_footer();

Which selector that I need to use to prevent this problem?

Here is the image of this be like:

1- 1st image is Default

2- 2nd image When I clicked the content area

When I clicked the content area

Body:
When I add the code below to custom css in wordpress:

*:focus{outline: none !important;}

It works.

But I don't understand that why it does not work when I add it into style.css


问:
Emulate Python shell's "return value" behaviour
Let's imagine I have a JSON list of Python strings to evaluate. For example, maybe I am building a client-server Python GUI.

One convenient thing about the regular Python interpreter is that it shows the "pseudo-return value" of each line, like this:

```<code> $ python3 -c "import code; code.interact()"
 Python 3.7.7 (default, Mar 10 2020, 15:43:03)
 (InteractiveConsole)
 >>> import os; os.curdir
 '.'
</code>```

I didn't have to ask to print out the '.'. It just did it.

Under the covers, one can see that this is implemented with the exec() function:

https://github.com/python/cpython/blob/800a35c623bbcdb5793c7d7a4974524286311479/Lib/code.py#L90

```<code>    try:
        exec(code, self.locals)
    except SystemExit:
        raise
    except:
        self.showtraceback()
</code>```

The weird thing is that there is no explicit instruction there to output the result of the exec(). And yet we can see that it does output it.

We can see that this behaviour is very context specific like this:

```<code>$ echo "5" | python3 -c "import code; code.interact()"
Python 3.7.7 (default, Mar 10 2020, 15:43:03)
(InteractiveConsole)
>>> 5
>>>
now exiting InteractiveConsole...
enter code here
</code>```

I assume that if I dig into the C code I will see that it is querying its context to see whether to output the value or not. But it wouldn't answer my main question, which is how to emulate this behaviour in an arbitrary context.

How can I can I execute and get the "pseudo-return value" from a Python string, regardless of whether the string represents an expression or a statement?

答:
The Python compiler has a flag to keep track of whether Python is being run in interactive mode.

If this flag is set, when the compiler visits a statement node in the AST, it emits an extra PRINT_EXPR opcode.

The interpreter executes PRINT_EXPR by popping the result of the expression off the stack and passing it as an argument to sys.displayhook. The displayhook prints the repr of this value to stdout, unless the value is None. It also assigns the value to builtins._.

(I guess the reason why the behavior is different when you pipe a command to Python is that then it is not in interactive mode.)

So as long as you are running Python in interactive mode, you can read the value of the _ builtin after running code with the exec builtin.

Body:
Let's imagine I have a JSON list of Python strings to evaluate. For example, maybe I am building a client-server Python GUI.

One convenient thing about the regular Python interpreter is that it shows the "pseudo-return value" of each line, like this:

 $ python3 -c "import code; code.interact()"
 Python 3.7.7 (default, Mar 10 2020, 15:43:03)
 (InteractiveConsole)
 >>> import os; os.curdir
 '.'

I didn't have to ask to print out the '.'. It just did it.

Under the covers, one can see that this is implemented with the exec() function:

https://github.com/python/cpython/blob/800a35c623bbcdb5793c7d7a4974524286311479/Lib/code.py#L90

    try:
        exec(code, self.locals)
    except SystemExit:
        raise
    except:
        self.showtraceback()

The weird thing is that there is no explicit instruction there to output the result of the exec(). And yet we can see that it does output it.

We can see that this behaviour is very context specific like this:

$ echo "5" | python3 -c "import code; code.interact()"
Python 3.7.7 (default, Mar 10 2020, 15:43:03)
(InteractiveConsole)
>>> 5
>>>
now exiting InteractiveConsole...
enter code here

I assume that if I dig into the C code I will see that it is querying its context to see whether to output the value or not. But it wouldn't answer my main question, which is how to emulate this behaviour in an arbitrary context.

How can I can I execute and get the "pseudo-return value" from a Python string, regardless of whether the string represents an expression or a statement?


问:
Erlang: Finding my IP Address
I'm attempting to complete a Load Balancer / Login Server / Game Server setup using Redis for some parts. Load balancing is one of them. In my Redis load balancing instance I'm using ordered sets. The key is the application name, the members are the IP addresses of the game servers.

Herein lies my issue. I would like to use a public method within erlang. I cannot find anything that fits my needs. I'm wondering if I'm over looking something.

```<code>{ok, L} = inet:getif(),
IP = element(1, hd(L)),
</code>```

Gives me what I'm looking for. I believe currently it's {192,168,0,14}. But the function is not "public."

```<code>{ok, Socket} = gen_tcp:listen(?PORT_LISTEN_GAME, [{active,once}, {reuseaddr, true}]),
{ok, {IP, _} = inet:sockname(Socket),
</code>```

Gives me {0,0,0,0}. I've tried inet:getaddr("owl") which gives me {127,0,1,1}.

Am I limited to sending messages via TCP and using inet:peername(Socket)? Seems like a lot to get something so simple. All the different parts of my app are running on the same computer for testing. Is it going to give me back {127,0,0,1}? That wouldn't work. I need to send the IP back to the user (my mobile phone) so they can link up with the proper server. Loopback wouldn't do....

Current Code

I would like to thank all the responses. Yes, I noticed Lol4t0's comment just after the New Year. So I changed my code to reflect that. Posting this for the slow people like myself. I have to wrack my brain for a bit to get these things to click.

```<code>hd([Addr || {_, Opts} <- Addrs,
    {addr, Addr} <- Opts,
    {flags, Flags} <- Opts,
    lists:member(loopback,Flags) =/= true]).
</code>```

答:
Using the getifaddr() function from OTP gives a detailed list of all interfaces available to the machine. The following solution should clear up a lot of confused newcomers to erlang as it stumped me too. This function is not optimized but is very readable and gives you your machines local IP4 address like the one you'd use at a LAN party:

```<code> %Get the local IP4 address of this machine in the local network (LAN party address)
local_ip_v4() ->
  {ok, IntfList} = inet:getifaddrs(), %Get a list of all interfaces (Wifi, Lan, Internal loopback etc)

  %Filter this list to look for an interface that is "up and running" (has a connection)
   SelectedInf = lists:foldl( fun(El, SelectedIf)->
                {InfName,InfOpts} = El,
                Flags = lists:keyfind(flags,1,InfOpts),
                case Flags of
                  {flags,[up,running]} ->
                    {InfName,InfOpts};
                  _->
                    SelectedIf
                end
                end,
                none,IntfList),

  io:format("~n INTERFACES: ~p ",[IntfList]),
  io:format("~n Selected INTERFACE: ~p ",[SelectedInf]),

  %Look through this interface's properties for the addresses, but only match one
  % that has 4 components in the tuple!
  {Sel_InfName,Sel_InfOpts} = SelectedInf,
  Address_I4 = lists:foldl( fun(El,Addr)->
                              case El of
                                {addr,{A,B,C,D}}->
                                  {A,B,C,D};
                                _->
                                  Addr
                              end
                            end, none, Sel_InfOpts),
  io:format("~n Selected INTERFACE IP4: ~p ~n",[Address_I4]),
  Address_I4.
</code>```

Hope this helps :)

Title: Erlang: Finding my IP Address

Body:
I'm attempting to complete a Load Balancer / Login Server / Game Server setup using Redis for some parts. Load balancing is one of them. In my Redis load balancing instance I'm using ordered sets. The key is the application name, the members are the IP addresses of the game servers.

Herein lies my issue. I would like to use a public method within erlang. I cannot find anything that fits my needs. I'm wondering if I'm over looking something.

{ok, L} = inet:getif(),
IP = element(1, hd(L)),

Gives me what I'm looking for. I believe currently it's {192,168,0,14}. But the function is not "public."

{ok, Socket} = gen_tcp:listen(?PORT_LISTEN_GAME, [{active,once}, {reuseaddr, true}]),
{ok, {IP, _} = inet:sockname(Socket),

Gives me {0,0,0,0}. I've tried inet:getaddr("owl") which gives me {127,0,1,1}.

Am I limited to sending messages via TCP and using inet:peername(Socket)? Seems like a lot to get something so simple. All the different parts of my app are running on the same computer for testing. Is it going to give me back {127,0,0,1}? That wouldn't work. I need to send the IP back to the user (my mobile phone) so they can link up with the proper server. Loopback wouldn't do....

Current Code

I would like to thank all the responses. Yes, I noticed Lol4t0's comment just after the New Year. So I changed my code to reflect that. Posting this for the slow people like myself. I have to wrack my brain for a bit to get these things to click.

hd([Addr || {_, Opts} <- Addrs,
    {addr, Addr} <- Opts,
    {flags, Flags} <- Opts,
    lists:member(loopback,Flags) =/= true]).

Body:
Using the getifaddr() function from OTP gives a detailed list of all interfaces available to the machine. The following solution should clear up a lot of confused newcomers to erlang as it stumped me too. This function is not optimized but is very readable and gives you your machines local IP4 address like the one you'd use at a LAN party:

 %Get the local IP4 address of this machine in the local network (LAN party address)
local_ip_v4() ->
  {ok, IntfList} = inet:getifaddrs(), %Get a list of all interfaces (Wifi, Lan, Internal loopback etc)

  %Filter this list to look for an interface that is "up and running" (has a connection)
   SelectedInf = lists:foldl( fun(El, SelectedIf)->
                {InfName,InfOpts} = El,
                Flags = lists:keyfind(flags,1,InfOpts),
                case Flags of
                  {flags,[up,running]} ->
                    {InfName,InfOpts};
                  _->
                    SelectedIf
                end
                end,
                none,IntfList),

  io:format("~n INTERFACES: ~p ",[IntfList]),
  io:format("~n Selected INTERFACE: ~p ",[SelectedInf]),

  %Look through this interface's properties for the addresses, but only match one
  % that has 4 components in the tuple!
  {Sel_InfName,Sel_InfOpts} = SelectedInf,
  Address_I4 = lists:foldl( fun(El,Addr)->
                              case El of
                                {addr,{A,B,C,D}}->
                                  {A,B,C,D};
                                _->
                                  Addr
                              end
                            end, none, Sel_InfOpts),
  io:format("~n Selected INTERFACE IP4: ~p ~n",[Address_I4]),
  Address_I4.

Hope this helps :)


问:
Why am I getting ::1 as the IP address in ASP.NET, and how to get the proper IP address?
I am running an ASP.NET MVC app in the localhost - dev server given with a Visual Studio. I want to get the IP address. I tried

Request.UserHostAddress

and

Request.ServerVariables("REMOTE_ADDR")

In both cases, I am getting::1 as a result. What is it? Why am I getting it? How can I get 127.0.0.1 or 192.168.1.xxx?

答:
If you get ipv6 address , after that you can find it valid ipv4 address map for ipv6 address.

c # code is below;

```<code>  public static string GetIP4Address(string ip) {
        try {
            var hostNames = Dns.GetHostEntry(ip);
            var ipv4 = hostNames.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
            if(ipv4 != null) {
                return ipv4.ToString();
            }

        } catch(Exception ex) {
            log.WarnFormat("Error When Getting Client Ipv4");
        }

        return ip;
    }
</code>```

Body:
If you get ipv6 address , after that you can find it valid ipv4 address map for ipv6 address.

c # code is below;

  public static string GetIP4Address(string ip) {
        try {
            var hostNames = Dns.GetHostEntry(ip);
            var ipv4 = hostNames.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
            if(ipv4 != null) {
                return ipv4.ToString();
            }

        } catch(Exception ex) {
            log.WarnFormat("Error When Getting Client Ipv4");
        }

        return ip;
    }


问:
R pipe in does not work with stringR's str_extract_all()
I encountered a weird and annoying thing: piping with stringR does not work properly:

```<code># lets get the 5th number-block out of a string

# with piping -> error
"Test region     test    1235   45   245   2345   1432   1432" %>%
  str_extract_all('[:digit:]+',
                  simplify = TRUE)[,5]
</code>```

Error in type(pattern) : argument "pattern" is missing, with no default

```<code># do the same without piping -> works
  str_extract_all("Test region     test    1235   45   245   2345   1432   1432",
                  '[:digit:]+',
                  simplify = TRUE)[,5]
</code>```

[1] "1432"

Any ideas what could be the problem? It took me forever to find out that this was the problem -.-

```<code>> sessionInfo()
R version 4.0.0 (2020-04-24)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252    LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] pdftools_2.3.1  XML_3.99-0.3    forcats_0.5.0   stringr_1.4.0   dplyr_0.8.5     purrr_0.3.4     readr_1.3.1     tidyr_1.0.2     tibble_3.0.1    ggplot2_3.3.0
[11] tidyverse_1.3.0 readxl_1.3.1

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.4.6     cellranger_1.1.0 pillar_1.4.3     compiler_4.0.0   dbplyr_1.4.3     tools_4.0.0      digest_0.6.25    lubridate_1.7.8  jsonlite_1.6.1
[10] lifecycle_0.2.0  nlme_3.1-147     gtable_0.3.0     lattice_0.20-41  pkgconfig_2.0.3  rlang_0.4.5      reprex_0.3.0     cli_2.0.2        DBI_1.1.0
[19] rstudioapi_0.11  haven_2.2.0      withr_2.2.0      xml2_1.3.2       httr_1.4.1       askpass_1.1      fs_1.4.1         generics_0.0.2   vctrs_0.2.4
[28] hms_0.5.3        grid_4.0.0       tidyselect_1.0.0 glue_1.4.0       qpdf_1.1         R6_2.4.1         fansi_0.4.1      farver_2.0.3     modelr_0.1.6
[37] magrittr_1.5     backports_1.1.6  scales_1.1.0     ellipsis_0.3.0   rvest_0.3.5      assertthat_0.2.1 colorspace_1.4-1 labeling_0.3     utf8_1.1.4
[46] stringi_1.4.6    munsell_0.5.0    broom_0.5.6      crayon_1.3.4
</code>```

答:
We can use

```<code>"Test region     test    1235   45   245   2345   1432   1432" %>%
     str_extract_all('[:digit:]+',
              simplify = TRUE) %>%
              .[,5]
#[1] "1432"
</code>```

Or block it in within {}

```<code>"Test region     test    1235   45   245   2345   1432   1432" %>%
    {str_extract_all(., '[:digit:]+',
                   simplify = TRUE)[,5]}
</code>```

Body:
I encountered a weird and annoying thing: piping with stringR does not work properly:

# lets get the 5th number-block out of a string

# with piping -> error
"Test region     test    1235   45   245   2345   1432   1432" %>%
  str_extract_all('[:digit:]+',
                  simplify = TRUE)[,5]

Error in type(pattern) : argument "pattern" is missing, with no default

# do the same without piping -> works
  str_extract_all("Test region     test    1235   45   245   2345   1432   1432",
                  '[:digit:]+',
                  simplify = TRUE)[,5]

[1] "1432"

Any ideas what could be the problem? It took me forever to find out that this was the problem -.-

> sessionInfo()
R version 4.0.0 (2020-04-24)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252    LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] pdftools_2.3.1  XML_3.99-0.3    forcats_0.5.0   stringr_1.4.0   dplyr_0.8.5     purrr_0.3.4     readr_1.3.1     tidyr_1.0.2     tibble_3.0.1    ggplot2_3.3.0
[11] tidyverse_1.3.0 readxl_1.3.1

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.4.6     cellranger_1.1.0 pillar_1.4.3     compiler_4.0.0   dbplyr_1.4.3     tools_4.0.0      digest_0.6.25    lubridate_1.7.8  jsonlite_1.6.1
[10] lifecycle_0.2.0  nlme_3.1-147     gtable_0.3.0     lattice_0.20-41  pkgconfig_2.0.3  rlang_0.4.5      reprex_0.3.0     cli_2.0.2        DBI_1.1.0
[19] rstudioapi_0.11  haven_2.2.0      withr_2.2.0      xml2_1.3.2       httr_1.4.1       askpass_1.1      fs_1.4.1         generics_0.0.2   vctrs_0.2.4
[28] hms_0.5.3        grid_4.0.0       tidyselect_1.0.0 glue_1.4.0       qpdf_1.1         R6_2.4.1         fansi_0.4.1      farver_2.0.3     modelr_0.1.6
[37] magrittr_1.5     backports_1.1.6  scales_1.1.0     ellipsis_0.3.0   rvest_0.3.5      assertthat_0.2.1 colorspace_1.4-1 labeling_0.3     utf8_1.1.4
[46] stringi_1.4.6    munsell_0.5.0    broom_0.5.6      crayon_1.3.4

Body:
We can use

"Test region     test    1235   45   245   2345   1432   1432" %>%
     str_extract_all('[:digit:]+',
              simplify = TRUE) %>%
              .[,5]
#[1] "1432"

Or block it in within {}

"Test region     test    1235   45   245   2345   1432   1432" %>%
    {str_extract_all(., '[:digit:]+',
                   simplify = TRUE)[,5]}


问:
How make the Button disabled in Angular form
I have a button that I need to disable when the form is empty so when I open the form at the beginning it should be disabled and make it enable when any inputs in form get value, I have this code, but it is not disable when form loads, as when form load it is valid, how I can make it not valid so the button will be disabled?

HTML:

```<code><button
  class="search-form__btn"
  type="submit"
  size="large"
  [disabled]="!isEnabled"
>
  Run Search
</button>
</code>```

TS file:

```<code>public get isEnabled(): boolean {
  const form: FormGroup = this.searchForm;
  if (form.get('filters.firstName').value !== ''
    || form.get('filters.lastName').value !== ''
    || form.get('filters.company').value !== ''
    || form.get('filters.phone').value !== ''
    || form.get('filters.email').value !== ''
    || form.get('filters.officer').value !== ''
    || form.get('filters.number').value !== ''
    || form.get('filters.state').value !== '') {
    return form.valid;
  }
}
</code>```

and this is my form:

```<code>constructor(private fb: FormBuilder) {
  this.searchForm = this.fb.group({
    filters: this.fb.group({
      searchString: [""],
      firstName: [""],
      lastName: [""],
      company: [""],
      email: [null, [Validators.email]],
      phone: [""],
      officer: [""],
      number: [""],
      state: [""],
      exactMatch: [false],
    }),
    pageSize: [100],
    currentPage: [1],
  });
}
</code>```

答:
you can add Validators.required for fields and bind disabled attr like so:</p>

```<code><button
  class="search-form__btn"
  type="submit"
  size="large"
  [disabled]="searchForm.invalid">Run Search</button>
</code>```

Body:
I have a button that I need to disable when the form is empty so when I open the form at the beginning it should be disabled and make it enable when any inputs in form get value, I have this code, but it is not disable when form loads, as when form load it is valid, how I can make it not valid so the button will be disabled?

HTML:

<button
  class="search-form__btn"
  type="submit"
  size="large"
  [disabled]="!isEnabled"
>
  Run Search
</button>

TS file:

public get isEnabled(): boolean {
  const form: FormGroup = this.searchForm;
  if (form.get('filters.firstName').value !== ''
    || form.get('filters.lastName').value !== ''
    || form.get('filters.company').value !== ''
    || form.get('filters.phone').value !== ''
    || form.get('filters.email').value !== ''
    || form.get('filters.officer').value !== ''
    || form.get('filters.number').value !== ''
    || form.get('filters.state').value !== '') {
    return form.valid;
  }
}

and this is my form:

constructor(private fb: FormBuilder) {
  this.searchForm = this.fb.group({
    filters: this.fb.group({
      searchString: [""],
      firstName: [""],
      lastName: [""],
      company: [""],
      email: [null, [Validators.email]],
      phone: [""],
      officer: [""],
      number: [""],
      state: [""],
      exactMatch: [false],
    }),
    pageSize: [100],
    currentPage: [1],
  });
}

Body:
you can add Validators.required for fields and bind disabled attr like so:

<button
  class="search-form__btn"
  type="submit"
  size="large"
  [disabled]="searchForm.invalid">Run Search</button>


问:
FTP - File name not allowed. (REMOTE SERVER ERROR 533) C#
My app is simple:

Getting list of files from ftp - step 1

Looping each of items and getting file - step 2

Writing content from a xml file to database - step 3

Before moving to another item in loop let's move processed file to
  another folder - step 4 (error)

Here's my code (please read comments!) :

```<code>if (ftpFiles.Any())
{
    foreach (var file in ftpFiles)
    {
        try
        {
            var item_path = $"ftp://my.url.ok:somePort/{item.FtpFolderName}/in/" + file;
            FtpWebRequest xml_request = (FtpWebRequest)WebRequest.Create(item_path);
            xml_request.Method = WebRequestMethods.Ftp.DownloadFile;
            xml_request.Credentials = new NetworkCredential("username", "password");

            using (FtpWebResponse xml_response = (FtpWebResponse)xml_request.GetResponse())
            {
                using (StreamReader xml_reader = new StreamReader(xml_response.GetResponseStream()))
                {
                    // PROCESSING XML FILE AND MAKING DATABASE CALL TO INSERT VALUE TO DB AND THAT IS FINE!
                }
            }

            // BEFORE I MOVE TO ANOTHER FILE IN LOOP I WANT TO MOVE PREVIOUS FILE TO ANOTHER FOLDER

            var item_to_move_original_path = $"ftp://my.url.ok:somePort/{item.FtpFolderName}/in/" + file;
            var item_to_move_new_path = $"ftp://my.url.ok:somePort/{item.FtpFolderName}/processed/" + file;

            FtpWebRequest xml_request_rename = (FtpWebRequest)WebRequest.Create(item_to_move_original_path);
            xml_request_rename.Method = WebRequestMethods.Ftp.Rename;

            xml_request_rename.Credentials = new NetworkCredential("username", "password");
            xml_request_rename.RenameTo = item_to_move_new_path;

            // IN LINE BELOW APP CRASHES AND IT SAYS THAT File name is not allowed

            // One more question here is can I use xml_request that I've created in a loop earlier to rename/move a file or I have to crate this
            // xml_request_rename
            FtpWebResponse response = (FtpWebResponse)xml_request_rename.GetResponse();

        }
        catch(Exception ex)
        {}
    }
}
</code>```

答:
I've been able to solve this by changing this url (removing part of the url):

```<code>var item_to_move_new_path = $"ftp://my.url.ok:somePort/{item.FtpFolderName}/processed/" + file;
</code>```

to:

```<code>var item_to_move_new_path = $"/{item.FtpFolderName}/processed/" + file;
</code>```

As it's possible to notice I've removed an

```<code>ftp://my.url.ok:somePort/
</code>```

from path, and everything worked, how come???

Everything works but I don't know why, if anyone could explain this to me and to other ppl who are watching this thead that would be awesome!

Body:
My app is simple:

Getting list of files from ftp - step 1

Looping each of items and getting file - step 2

Writing content from a xml file to database - step 3

Before moving to another item in loop let's move processed file to
  another folder - step 4 (error)

Here's my code (please read comments!) :

if (ftpFiles.Any())
{
    foreach (var file in ftpFiles)
    {
        try
        {
            var item_path = $"ftp://my.url.ok:somePort/{item.FtpFolderName}/in/" + file;
            FtpWebRequest xml_request = (FtpWebRequest)WebRequest.Create(item_path);
            xml_request.Method = WebRequestMethods.Ftp.DownloadFile;
            xml_request.Credentials = new NetworkCredential("username", "password");

            using (FtpWebResponse xml_response = (FtpWebResponse)xml_request.GetResponse())
            {
                using (StreamReader xml_reader = new StreamReader(xml_response.GetResponseStream()))
                {
                    // PROCESSING XML FILE AND MAKING DATABASE CALL TO INSERT VALUE TO DB AND THAT IS FINE!
                }
            }

            // BEFORE I MOVE TO ANOTHER FILE IN LOOP I WANT TO MOVE PREVIOUS FILE TO ANOTHER FOLDER

            var item_to_move_original_path = $"ftp://my.url.ok:somePort/{item.FtpFolderName}/in/" + file;
            var item_to_move_new_path = $"ftp://my.url.ok:somePort/{item.FtpFolderName}/processed/" + file;

            FtpWebRequest xml_request_rename = (FtpWebRequest)WebRequest.Create(item_to_move_original_path);
            xml_request_rename.Method = WebRequestMethods.Ftp.Rename;

            xml_request_rename.Credentials = new NetworkCredential("username", "password");
            xml_request_rename.RenameTo = item_to_move_new_path;

            // IN LINE BELOW APP CRASHES AND IT SAYS THAT File name is not allowed

            // One more question here is can I use xml_request that I've created in a loop earlier to rename/move a file or I have to crate this
            // xml_request_rename
            FtpWebResponse response = (FtpWebResponse)xml_request_rename.GetResponse();

        }
        catch(Exception ex)
        {}
    }
}

Body:
I've been able to solve this by changing this url (removing part of the url):

var item_to_move_new_path = $"ftp://my.url.ok:somePort/{item.FtpFolderName}/processed/" + file;

to:

var item_to_move_new_path = $"/{item.FtpFolderName}/processed/" + file;

As it's possible to notice I've removed an

ftp://my.url.ok:somePort/

from path, and everything worked, how come???

Everything works but I don't know why, if anyone could explain this to me and to other ppl who are watching this thead that would be awesome!


问:
Keycloak is not defined in angularjs 2 Example
I'm trying to implement keycloak into an angularjs 2 app (typescript).
I used the code from this example, but when I start the app I get:

```<code>Error: ReferenceError: Keycloak is not defined(…)
</code>```

Any ideas?

答:
try to include this in the "scripts" section like below:

```<code>"scripts": ["../node_modules/keycloak-js/dist/keycloak.js"]
</code>```

Body:
I'm trying to implement keycloak into an angularjs 2 app (typescript).
I used the code from this example, but when I start the app I get:

Error: ReferenceError: Keycloak is not defined(…)

Any ideas?

Body:
try to include this in the "scripts" section like below:

"scripts": ["../node_modules/keycloak-js/dist/keycloak.js"]


问:
How to make CSS animations occur after clicking on an image
I'm trying to have images move using CSS animations, but after I click on them. Currently, they move as soon as I get on the page. I want it to be that when you click on any of the images, the CSS animation occurs. I believe you would have to do that with some javascript code, but I don't know how to. I'm new to programming and I would love any help I can get. Let me know if you guys need any more information. Thanks

var doineedtowait = 0;
function myFunction(imgs) {
  if(doineedtowait == 0){
  sleep(1000);
  }
  var expandImg = document.getElementById("expandedImg");
  expandImg.src = imgs.src;
  var imgParagraph = document.getElementById('img-paragraph');
  imgParagraph.innerHTML = imgs.getAttribute("yeep");

  expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
  doineedtowait++; //after executing we update the doineedtowait to +1
  //so the if with sleep for 1 second will not be used anymore
}
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}
document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 80px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}
#column1 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column2 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column3 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column4 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

```

答:
You can trigger the animation when you click on the image using JavaScript by changing the CSS class of the item that you wish to animate:

function testFunction() {
  document.getElementById('img').classList.add('animation');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  display: flex;
  align-items: center;
  justify-content: center;
}

.animation {
  animation: animation 1s linear infinite;
}

@keyframes animation {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(2);

  100% {
    transform: scale(1);
  }
}</code>```

```

That should add the animation to your element. If you want to toggle the animation on click, just chang the classList.add('animation'); to classList.toggle('animation');. I hope this helps.

Body:
I'm trying to have images move using CSS animations, but after I click on them. Currently, they move as soon as I get on the page. I want it to be that when you click on any of the images, the CSS animation occurs. I believe you would have to do that with some javascript code, but I don't know how to. I'm new to programming and I would love any help I can get. Let me know if you guys need any more information. Thanks

var doineedtowait = 0;
function myFunction(imgs) {
  if(doineedtowait == 0){
  sleep(1000);
  }
  var expandImg = document.getElementById("expandedImg");
  expandImg.src = imgs.src;
  var imgParagraph = document.getElementById('img-paragraph');
  imgParagraph.innerHTML = imgs.getAttribute("yeep");

  expandImg.parentElement.style.display = "table-cell";
  imgParagraph.style.display = 'table-cell';
  doineedtowait++; //after executing we update the doineedtowait to +1
  //so the if with sleep for 1 second will not be used anymore
}
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}
document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}

@font-face {
  font-family: 'futuralight';
  src: url('../Fonts/Futura Light/futura_light_regular-webfont.woff2') format('woff2'), url('../Fonts/Futura Light/futura_light_regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'tekoregular';
  src: url('../Fonts/Teko/teko-regular-webfont.woff2') format('woff2'), url('../Fonts/Teko/teko-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'playfair_displayregular';
  src: url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff2') format('woff2'), url('../Fonts/Playfair Display/playfairdisplay-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'poppinsmedium';
  src: url('../Fonts/Poppins/poppins-medium-webfont.woff2') format('woff2'), url('../Fonts/Poppins/poppins-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  margin: 0px;
  padding: 0px;
  border: 0px;
}

.topnav {
  background-color: rgb(84, 104, 217);
  overflow: hidden;
  font-family: 'futuralight';
  font-weight: 900;
}

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 20px 21px;
  text-decoration: none;
  font-size: 19px;
  position: relative;
  left: 2%;
}

.topnav a:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

.topnav a:hover:before {
  visibility: visible;
  transform: scaleX(1);
}

.topnav a.active-menu:before {
  content: "";
  position: absolute;
  width: 84%;
  height: 2px;
  bottom: 6px;
  left: 8%;
  background-color: white;
  visibility: visible;
  transform: scaleX(1);
  transition: all 0.3s ease-in-out 0s;
}

.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Style the images inside the grid */

.column img {
  opacity: 0.85;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

.totalbody {
  background-color: #EEF0FC;
  height: 5000px;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

/* The expanding image container */

#expandedImg {
  width: 40%;
  padding-top:20px;
  padding-left:20px;
}

/* Expanding image text */

/* image paragraph */

#img-paragraph {
  display: none;
  vertical-align: top;
  text-align: left;
  position: absolute;
  height: 400px;
  width: 50%;
  background-color: white;
  box-shadow: 0 2.8px 2.2px rgba(0, 0, 0, 0.034), 0 6.7px 5.3px rgba(0, 0, 0, 0.048), 0 12.5px 10px rgba(0, 0, 0, 0.06), 0 22.3px 17.9px rgba(0, 0, 0, 0.072), 0 41.8px 33.4px rgba(0, 0, 0, 0.086), 0 100px 80px rgba(0, 0, 0, 0.12);
  border-radius: 7px;
  float: right;
  right: 30px;
  top: 120px;
}

#expanded-wrapper {
  width: 100%;
}

/* Closable button inside the expanded image */

.row {
  position: absolute;
  top: 80px;
}

.yeep1 {
  position: relative;
  left: 12px;
  top: 16px;
  color: rgb(84, 104, 217);
  font-weight: 900;
  font-size: 40px;
  font-family: 'futuralight';
  text-decoration: none;
  line-height: 1;
  padding-left:4%;
  padding-top:30px;
}

.yeep2 {
  color: purple;
}

.yeep3 {
  color: green;
}
.yeep4 {
  color: blue;
}

.yeep1::before {
  content: '';
  background-color: rgb(84, 104, 217);
  width: 12px;
  height: 100%;
  position: absolute;
  right: 100%;
  bottom: -16px;
}
#column1 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column2 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column3 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}
#column4 {
  position: relative;
  -webkit-animation: floatBubble 2s  normal ease-out;
  animation: floatBubble 2s forwards normal ease-out;
}
@-webkit-keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
  }
}
@keyframes floatBubble {
  0% {
      top:00px;
  }
  100% {
      top: 500px;
      left:50px;
  }
}

@media only screen and (max-width: 830px) and (min-width: 760px) {
  .topnav {
    background-color: yellow;
    overflow: hidden;
  }
}

@media only screen and (max-width: 759px) and (min-width: 646px) {
  .topnav {
    background-color: red;
    overflow: hidden;
  }
}

@media only screen and (max-width: 645px) {
  .topnav {
    background-color: black;
    overflow: hidden;
  }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css"  href="../CSS/styleprojects.css" />

    <title>Projects</title>

    Home
    Academics
    Projects
    Community Service

Body:
You can trigger the animation when you click on the image using JavaScript by changing the CSS class of the item that you wish to animate:

function testFunction() {
  document.getElementById('img').classList.add('animation');
}

a {
  display: flex;
  align-items: center;
  justify-content: center;
}

.animation {
  animation: animation 1s linear infinite;
}

@keyframes animation {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(2);

  100% {
    transform: scale(1);
  }
}

<a href="#" onclick="testFunction()">
  <img id="img" src="https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1Mu3b?ver=5c31" alt="" />
</a>

That should add the animation to your element. If you want to toggle the animation on click, just chang the classList.add('animation'); to classList.toggle('animation');. I hope this helps.


答: You would write in your html <input type="radio" id="radioButton" checked />. That's much less complicated than using javascript to do it.

Title: html radio button has to be selected by default on page load

Body:
I am trying to do make the radio button selected by default on page load.

From the below screen it is a frame which is loaded. I am trying to make the radio buttons enable by using

document.formName.radioButtonId[1].checked = true;

Where formName is my form name that I declared in html, radioButtonId is id for radio button I used in html.

 <form name = "formName">
.
.
.
.

     <input type = "radio"
            id = "radioButton"
.
.
.

 </form>

So my expectation is from the above code Joe radio button has to be enabled.

But the html is not completely loaded and when I do
document.formName.radioButtonId[1].checked = true; the error on console says radioButton was undefined because of the form is not available.

I am not able to access any of the elements from form until it is completely loaded. Is there any way that I can check for the page title is loaded or visible then do the condition that I want to do?

I tried

if (document.readyState === "complete") { //do something }

This didn't work because document.readyState is always complete as the document is referring to parent document from the screenshot you can see it was referring to background page.

Once the Modify Name is completely loaded then I was able to access formName form and I was able to make Joe as selected using document.formName.radioButtonId[1].checked = true;

I am making Joe as checked based on condition from the code that I have (fyi). That might change so want to be generic.

[![Modify Name is child to background image like a popup][2]][2]
Need help on how to make Joe as checked after loading the page automatically.


问:
No such property: variantConfiguration for class:
After upgrading gradle 4.0.0 app build failed with error message:

No such property: variantConfiguration for class: com.android.build.gradle.internal.variant.ApplicationVariantData

is there any way to migrate gradle ?

```<code>android.applicationVariants.all { variant ->
        variant.outputs.all {
            def buildType = variant.variantData.variantConfiguration.buildType.name
            ...

        }
    }
</code>```

app level gradle file

```<code>dependencies {
        classpath 'com.android.tools.build:gradle:4.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
</code>```

答:
In the last gradle Relase ApplicationVariant implement BaseVariant

Instead of

```<code>def buildType = variant.variantData.variantConfiguration.buildType.name
</code>```

Should be

```<code>def buildType = variant.buildType.name
</code>```

Body:
After upgrading gradle 4.0.0 app build failed with error message:

No such property: variantConfiguration for class: com.android.build.gradle.internal.variant.ApplicationVariantData

is there any way to migrate gradle ?

android.applicationVariants.all { variant ->
        variant.outputs.all {
            def buildType = variant.variantData.variantConfiguration.buildType.name
            ...

        }
    }

app level gradle file

dependencies {
        classpath 'com.android.tools.build:gradle:4.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }

Body:
In the last gradle Relase ApplicationVariant implement BaseVariant

Instead of

def buildType = variant.variantData.variantConfiguration.buildType.name

Should be

def buildType = variant.buildType.name


问:
Cannot compile nms_cuda in mmdetection using colaboratory
```<code>/usr/local/lib/python3.6/dist-packages/torch/include/ATen/core/TensorBody.h:262:30: note: declared here
   DeprecatedTypeProperties & type() const {
                              ^~~~
mmdet/ops/nms/src/nms_cuda.cpp:4:23: error: ‘AT_CHECK’ was not declared in this scope
 #define CHECK_CUDA(x) AT_CHECK(x.type().is_cuda(), #x, " must be a CUDAtensor ")
                       ^
mmdet/ops/nms/src/nms_cuda.cpp:4:23: note: in definition of macro ‘CHECK_CUDA’
 #define CHECK_CUDA(x) AT_CHECK(x.type().is_cuda(), #x, " must be a CUDAtensor ")
                       ^~~~~~~~
mmdet/ops/nms/src/nms_cuda.cpp:4:23: note: suggested alternative: ‘DCHECK’
 #define CHECK_CUDA(x) AT_CHECK(x.type().is_cuda(), #x, " must be a CUDAtensor ")
                       ^
mmdet/ops/nms/src/nms_cuda.cpp:4:23: note: in definition of macro ‘CHECK_CUDA’
 #define CHECK_CUDA(x) AT_CHECK(x.type().is_cuda(), #x, " must be a CUDAtensor ")
                       ^~~~~~~~
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
</code>```

Now all the info I get:

sys.version 8.2

/usr/bin/gcc 7

gcc versio 7.5

Is it normal?
What happened? Cuda error? gcc error?
How to solve. I'm hurried to use it to run mmdetection program.

答:
The solution is:

```<code>conda install pytorch cudatoolkit==10.0 torchvision -c pytorch -y
</code>```

if using branch earlier than v2.0.0.

or:

```<code>conda install pytorch cudatoolkit torchvision -c pytorch -y
</code>```

if branch is equal to v2.0.0.

Took me 3 days to figure this out. Basically if you install cudatoolkit==10.0 this will force pytorch to be downgraded to pytorch version 1.4 which makes the whole thing work. Its not at all obvious. And is in my opinion a bug in the mmdetection installation guide.

Body:
/usr/local/lib/python3.6/dist-packages/torch/include/ATen/core/TensorBody.h:262:30: note: declared here
   DeprecatedTypeProperties & type() const {
                              ^~~~
mmdet/ops/nms/src/nms_cuda.cpp:4:23: error: ‘AT_CHECK’ was not declared in this scope
 #define CHECK_CUDA(x) AT_CHECK(x.type().is_cuda(), #x, " must be a CUDAtensor ")
                       ^
mmdet/ops/nms/src/nms_cuda.cpp:4:23: note: in definition of macro ‘CHECK_CUDA’
 #define CHECK_CUDA(x) AT_CHECK(x.type().is_cuda(), #x, " must be a CUDAtensor ")
                       ^~~~~~~~
mmdet/ops/nms/src/nms_cuda.cpp:4:23: note: suggested alternative: ‘DCHECK’
 #define CHECK_CUDA(x) AT_CHECK(x.type().is_cuda(), #x, " must be a CUDAtensor ")
                       ^
mmdet/ops/nms/src/nms_cuda.cpp:4:23: note: in definition of macro ‘CHECK_CUDA’
 #define CHECK_CUDA(x) AT_CHECK(x.type().is_cuda(), #x, " must be a CUDAtensor ")
                       ^~~~~~~~
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

Now all the info I get:

sys.version 8.2

/usr/bin/gcc 7

gcc versio 7.5

Is it normal?
What happened? Cuda error? gcc error?
How to solve. I'm hurried to use it to run mmdetection program.

Body:
The solution is:

conda install pytorch cudatoolkit==10.0 torchvision -c pytorch -y

if using branch earlier than v2.0.0.

or:

conda install pytorch cudatoolkit torchvision -c pytorch -y

if branch is equal to v2.0.0.

Took me 3 days to figure this out. Basically if you install cudatoolkit==10.0 this will force pytorch to be downgraded to pytorch version 1.4 which makes the whole thing work. Its not at all obvious. And is in my opinion a bug in the mmdetection installation guide.


问:
How to add a node selector to a system pod in kubernetes?
I want to apply a yaml file which will add a node selector to a pod matching k8s-app=metrics-server label. What should I put in the yaml file to this?

答:
The Node should be labelled with the label k8s-app: metrics-server in order for pods to be scheduled on it.

Check if you have the labels added to the nodes of your cluster:
kubectl get nodes --show-labels

And the label should be k8s-app: metrics-server.

```<code>apiVersion: v1
kind: Pod
metadata:
  name: testpod
spec:
  containers:
    - name: nginx
      image: nginx:latest
  nodeSelector:
    k8s-app: metrics-server
</code>```

Also to check if the pod was scheduled on that node run the following command:
kubectl get pods -o wide

Then looking at the “NODE” that the Pod was assigned to.

Following is an excercise again from the kubernetes docs https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#nodeselector

Also before you post up a question please try and check online if your question's answer is available. The more you dig, the deeper you will know. Kubernetes docs are too detailed and very easy to understand.

Body:
The Node should be labelled with the label k8s-app: metrics-server in order for pods to be scheduled on it.

Check if you have the labels added to the nodes of your cluster:
kubectl get nodes --show-labels

And the label should be k8s-app: metrics-server.

apiVersion: v1
kind: Pod
metadata:
  name: testpod
spec:
  containers:
    - name: nginx
      image: nginx:latest
  nodeSelector:
    k8s-app: metrics-server

Also to check if the pod was scheduled on that node run the following command:
kubectl get pods -o wide

Then looking at the “NODE” that the Pod was assigned to.

Following is an excercise again from the kubernetes docs https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#nodeselector

Also before you post up a question please try and check online if your question's answer is available. The more you dig, the deeper you will know. Kubernetes docs are too detailed and very easy to understand.


问:
VueJS select object from list and display with function
I need to get the element I click which is displayed in a list. And print this element on a method which is on my vue instance throug mail-list tag which is on index.html

So I have Vue component which iterates json object and only prints two attributes from every element of it:

```<code>Vue.component('mail-list', {
  props: ['inboxmail'],
  methods: {
    selectmail: function(){
      this.$emit('selectmail', this.mail);
    }

  },
  template:
  `
  <div>
    <ul>
      <li v-for="i in inboxmail" @click="selectedmail">
      {{i.from}}:{{i.subject}}
      </li>
    </ul>
  </div>
  `
  });
</code>```

After run this I have two elements displayed on my index.html which are:

test1@test.com:Hi

test2@test.com:How are you?

I want to click one of this two elements and get the one I clicked. Then send it to vue method called setSelectedMail throug mail-list tag which is in index.html

index.html:

```<code><div id="app">
        <mail-list v-bind:inboxmail="inbox" @selectmail="setSelectedMail($event)"></mail-list>
</div>
</code>```

And finally, heres is the vue instance from where I want to get the selected mail:

```<code>let options = {
  el: "#app",
  data: {
    inbox: '',
    selectedMail:{}
  },
  methods: {
      setSelectedMail: function(mail){
          this.selectedMail = mail;
      }

  } //end methods
 }
//ViewModel (vm)
let vm = new Vue(options);
</code>```

What am I doing wrong?

答:
Check this. some corrections in your code.

```<code>@click="selectmail(i.from)"

methods: {
        selectmail: function(value) {
          this.$emit("selectmail", value);
        }
      }
</code>```

Demo with your code in codesandbox or Github.

```<code><!-- Complete code -->

<!-- MailList -->

<template>
  <div>
    <ul>
      <li v-for="i in inboxmail" @click="selectmail(i.from)"
      v-bind:key="i.from">{{i.from}}:{{i.subject}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "MailList",
  props: ["inboxmail"],
  methods: {
    selectmail: function(value) {
      this.$emit("selectmail", value);
    }
  }
};
</script>

<!-- App.Vue -->

<template>
  <div id="app">
    <mail-list v-bind:inboxmail="inbox"
      @selectmail="setSelectedMail($event)">
    </mail-list>

    Selected: {{selectedMail}}
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";
import MailList from "./components/MailList";

export default {
  name: "App",
  components: {
    HelloWorld, MailList
  },
  data: function(){
    return {
      inbox: [{
        from: 'test1@test.com',
        subject: 'Hi'
      },{
        from: 'test2@test.com',
        subject: 'How are you?'
      }],
      selectedMail: {}
    };
  },
  methods: {
    setSelectedMail: function(mail) {
      this.selectedMail = mail;
    }
  } //end methods
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
</code>```

Body:
I need to get the element I click which is displayed in a list. And print this element on a method which is on my vue instance throug mail-list tag which is on index.html

So I have Vue component which iterates json object and only prints two attributes from every element of it:

Vue.component('mail-list', {
  props: ['inboxmail'],
  methods: {
    selectmail: function(){
      this.$emit('selectmail', this.mail);
    }

  },
  template:
  `

      {{i.from}}:{{i.subject}}

  `
  });

After run this I have two elements displayed on my index.html which are:

test1@test.com:Hi

test2@test.com:How are you?

I want to click one of this two elements and get the one I clicked. Then send it to vue method called setSelectedMail throug mail-list tag which is in index.html

index.html:

        <mail-list v-bind:inboxmail="inbox" @selectmail="setSelectedMail($event)"></mail-list>

And finally, heres is the vue instance from where I want to get the selected mail:

let options = {
  el: "#app",
  data: {
    inbox: '',
    selectedMail:{}
  },
  methods: {
      setSelectedMail: function(mail){
          this.selectedMail = mail;
      }

  } //end methods
 }
//ViewModel (vm)
let vm = new Vue(options);

What am I doing wrong?

Body:
Check this. some corrections in your code.

@click="selectmail(i.from)"

methods: {
        selectmail: function(value) {
          this.$emit("selectmail", value);
        }
      }

Demo with your code in codesandbox or Github.

<!-- Complete code -->

<!-- MailList -->

<template>
  <div>
    <ul>
      <li v-for="i in inboxmail" @click="selectmail(i.from)"
      v-bind:key="i.from">{{i.from}}:{{i.subject}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "MailList",
  props: ["inboxmail"],
  methods: {
    selectmail: function(value) {
      this.$emit("selectmail", value);
    }
  }
};
</script>

<!-- App.Vue -->

<template>
  <div id="app">
    <mail-list v-bind:inboxmail="inbox"
      @selectmail="setSelectedMail($event)">
    </mail-list>

    Selected: {{selectedMail}}
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";
import MailList from "./components/MailList";

export default {
  name: "App",
  components: {
    HelloWorld, MailList
  },
  data: function(){
    return {
      inbox: [{
        from: 'test1@test.com',
        subject: 'Hi'
      },{
        from: 'test2@test.com',
        subject: 'How are you?'
      }],
      selectedMail: {}
    };
  },
  methods: {
    setSelectedMail: function(mail) {
      this.selectedMail = mail;
    }
  } //end methods
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>


问:
How to obtain and save "for" loop results as list after running Dijkstra's algorithm?
I am trying to solve a problem with Dijkstra's algorithm. Basically, I want to randomly select start and end nodes and find the distances along each path after pairing the nodes and running the algorithm. Finally, I want to save the result as a list. So far, the code works well, however, I am having a challenge saving the result as a list.
Here is the code I have used.

```<code>import random
from random import seed
from random import random
from random import randint
import pandas as pd
import numpy as np
import statistics
</code>```

```<code>distance = [(0,7,3,0,0),(7,0,1,2,6),(3,1,0,2,0),(0,2,2,0,4),(0,6,0,4,0)]
dist = np.array(distance)
graph = dist
</code>```

```<code># Python program for Dijkstra's

from collections import defaultdict
class Graph:
    def minDistance(self,dist,queue):
        minimum = float("Inf")
        min_index = -1
        for i in range(len(dist)):
            if dist[i] < minimum and i in queue:
                minimum = dist[i]
                min_index = i
        return min_index
    def printPath(self, parent, end):
        if parent[end] == -1 :
            #print (end),
            return
        self.printPath(parent , parent[end])
        #print (end),
    def printSolution(self, dist, parent):
        #print("Vertex and Path \t\tDistance from Source")
        #print((start, end, dist[end])), self.printPath(parent,end)  #if you want to see start and end nodes

        print(dist[end]), self.printPath(parent,end)  #if you do not want to see start and end nodes

    '''Function that implements Dijkstra's single source shortest path
    algorithm for a graph represented using adjacency matrix
    representation'''
    def dijkstra(self, graph, start):
        row = len(graph)
        col = len(graph[0])
        dist = [float("Inf")] * row
        parent = [-1] * row
        dist[start] = 0
        queue = []
        for i in range(row):
            queue.append(i)
        while queue:
            u = self.minDistance(dist,queue)
            queue.remove(u)
            for i in range(col):
                '''Update dist[i] only if it is in queue, there is
                an edge from u to i, and total weight of path from
                start to i through u is smaller than current value of
                dist[i]'''
                if graph[u][i] and i in queue:
                    if dist[u] + graph[u][i] < dist[i]:
                        dist[i] = dist[u] + graph[u][i]
                        parent[i] = u
        self.printSolution(dist,parent)
g= Graph()
</code>```

```<code>seed(1)
start1 = []
for x in range(3):
    start = randint(0, 3)
    start1.append(start)
</code>```

```<code>seed(3)
end1 = []
for x in range(3):
    end = randint(2,4)
    end1.append(end)
</code>```

```<code>start = start1
end = end1
</code>```

```<code>results = []
for i in start1:
    for q in end1:
        start = i
        end = q
        if i != q:
            results.append(g.dijkstra(graph,i))
</code>```

The above code produces this result ...

```<code>1
6
6
3
9
9
6
6
</code>```

When I call for the saved list, I get "none" values.

```<code>results
</code>```

```<code>[None, None, None, None, None, None, None, None]
</code>```

I wish to get the results as follows:

```<code>[1,6,6,3,9,9,6,6,]
</code>```

As I am a beginner at using python, I would be exceedingly grateful if someone can help me to save the result as a list.

答:
in results you append return value from g.dijkstra(graph,i). And b/c there is no return command, it returns None. Hence you append only None.
Add return some-value at the end of dijkstra() and it should work.

Body:
I am trying to solve a problem with Dijkstra's algorithm. Basically, I want to randomly select start and end nodes and find the distances along each path after pairing the nodes and running the algorithm. Finally, I want to save the result as a list. So far, the code works well, however, I am having a challenge saving the result as a list.
Here is the code I have used.

import random
from random import seed
from random import random
from random import randint
import pandas as pd
import numpy as np
import statistics

distance = [(0,7,3,0,0),(7,0,1,2,6),(3,1,0,2,0),(0,2,2,0,4),(0,6,0,4,0)]
dist = np.array(distance)
graph = dist

# Python program for Dijkstra's

from collections import defaultdict
class Graph:
    def minDistance(self,dist,queue):
        minimum = float("Inf")
        min_index = -1
        for i in range(len(dist)):
            if dist[i] < minimum and i in queue:
                minimum = dist[i]
                min_index = i
        return min_index
    def printPath(self, parent, end):
        if parent[end] == -1 :
            #print (end),
            return
        self.printPath(parent , parent[end])
        #print (end),
    def printSolution(self, dist, parent):
        #print("Vertex and Path \t\tDistance from Source")
        #print((start, end, dist[end])), self.printPath(parent,end)  #if you want to see start and end nodes

        print(dist[end]), self.printPath(parent,end)  #if you do not want to see start and end nodes

    '''Function that implements Dijkstra's single source shortest path
    algorithm for a graph represented using adjacency matrix
    representation'''
    def dijkstra(self, graph, start):
        row = len(graph)
        col = len(graph[0])
        dist = [float("Inf")] * row
        parent = [-1] * row
        dist[start] = 0
        queue = []
        for i in range(row):
            queue.append(i)
        while queue:
            u = self.minDistance(dist,queue)
            queue.remove(u)
            for i in range(col):
                '''Update dist[i] only if it is in queue, there is
                an edge from u to i, and total weight of path from
                start to i through u is smaller than current value of
                dist[i]'''
                if graph[u][i] and i in queue:
                    if dist[u] + graph[u][i] < dist[i]:
                        dist[i] = dist[u] + graph[u][i]
                        parent[i] = u
        self.printSolution(dist,parent)
g= Graph()

seed(1)
start1 = []
for x in range(3):
    start = randint(0, 3)
    start1.append(start)

seed(3)
end1 = []
for x in range(3):
    end = randint(2,4)
    end1.append(end)

start = start1
end = end1

results = []
for i in start1:
    for q in end1:
        start = i
        end = q
        if i != q:
            results.append(g.dijkstra(graph,i))

The above code produces this result ...

1
6
6
3
9
9
6
6

When I call for the saved list, I get "none" values.

results

[None, None, None, None, None, None, None, None]

I wish to get the results as follows:

[1,6,6,3,9,9,6,6,]

As I am a beginner at using python, I would be exceedingly grateful if someone can help me to save the result as a list.


问:
how to download en_core_web_sm in orange3?
I want to use spacy inside Python script in Orange3 tool, but I get this error Can't find model 'en_core_web_sm' for using nlp = spacy.load("en_core_web_sm"). I wonder how I can install this model in orange3?. Btw, I am using Orange3 as individual tool , not inside Anaconda jupyter notebook

Error: Traceback (most recent call last): File "", line 1, in  File "", line 2, in  File "C:\Users\saif\AppData\Local\Orange\lib\site-packages\spacy__init__.py", line 30, in load return util.load_model(name, **overrides) File "C:\Users\saif\AppData\Local\Orange\lib\site-packages\spacy\util.py", line 169, in load_model raise IOError(Errors.E050.format(name=name)) OSError: [E050] Can't find model 'en_core_web_sm'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data directory. >>>

Thanks in advance

答:
It appears that spaCy wants you to download their models using their command line interface, however if you're working in a development environment where all you can do is write scripts and run them (which I assume is the case regarding Orange3), you can import the function that spaCy uses internally to download and install models and call that.</p>

```<code>from spacy.cli.download import download
download('en_core_web_sm')
</code>```

Body:
It appears that spaCy wants you to download their models using their command line interface, however if you're working in a development environment where all you can do is write scripts and run them (which I assume is the case regarding Orange3), you can import the function that spaCy uses internally to download and install models and call that.

from spacy.cli.download import download
download('en_core_web_sm')


问:
Continue column with average of previous values
I have a number of columns all indexed by datetime and I need to project a forecast for some of the columns based on the past n (lets say in this case 4) days.

```<code>          A  B  C
31-12-201917 19 49
1-1-2020  4  9  2
2-1-2020  2  23 3
3-1-2020  8  23 7
4-1-2020  6  21 4
5-1-2020  5
6-1-2020  5
7-1-2020  5
8-1-2020  5
9-1-2020  5
10-1-2020 5
11-1-2020 5
</code>```

So the desired output would have the average of the last 4 days as the respective value for that column for each of the future dates (as shown in column A). Note it should only take the last 4 days as opposed to all dates in the dataframe.

I've tried various rolling ave functions but all seem to require a new column!

Could anyone assist?

答:
So by repeating 5 values in the column, I assume it is as simple as filling NaN with a constant value obtained from some averaging, right?

So how about:

```<code>for c in df.columns:
    df[c].fillna(
        df[df[c].notna()].tail(4)[c].mean(),
        inplace=True
    )
</code>```

.fillna() simply fills NaN values

df[df[c].notna()].tail(4) gives you the last 4 non-nan days. feel free to change the value of .tail()

[c].mean() averages the values for column c

Body:
I have a number of columns all indexed by datetime and I need to project a forecast for some of the columns based on the past n (lets say in this case 4) days.

          A  B  C
31-12-201917 19 49
1-1-2020  4  9  2
2-1-2020  2  23 3
3-1-2020  8  23 7
4-1-2020  6  21 4
5-1-2020  5
6-1-2020  5
7-1-2020  5
8-1-2020  5
9-1-2020  5
10-1-2020 5
11-1-2020 5

So the desired output would have the average of the last 4 days as the respective value for that column for each of the future dates (as shown in column A). Note it should only take the last 4 days as opposed to all dates in the dataframe.

I've tried various rolling ave functions but all seem to require a new column!

Could anyone assist?

Body:
So by repeating 5 values in the column, I assume it is as simple as filling NaN with a constant value obtained from some averaging, right?

So how about:

for c in df.columns:
    df[c].fillna(
        df[df[c].notna()].tail(4)[c].mean(),
        inplace=True
    )

.fillna() simply fills NaN values

df[df[c].notna()].tail(4) gives you the last 4 non-nan days. feel free to change the value of .tail()

[c].mean() averages the values for column c


问:
My batch file for installing programs is crashing
I made this batch file intending to automate program installation between some Windows machines I constantly have to reformat, but when I run it, it just close the CMD without any error, I've tried many different things like BatCodeCheck but I wasn't able to find why it's crashing. I am not experienced with batch files so I am struggling really hard right now.

The idea behind my batch file is to have to run just one file and install all the basic software needed for the average Joe.

Here's my AIO install everything.bat file.

```<code>@echo off
SETLOCAL EnableExtensions

::##################################################################
:: Elevate this script                                             #
::##################################################################

(
    :: Check Admin rights and create VBS Script to elevate
    >nul fsutil dirty query %SYSTEMDRIVE% 2>&1 || (

        :: Very little red console
        mode con cols=80 lines=3
        color cf

        :: Message
        title Please wait...
        echo[
        echo                         Requesting elevated shell...

        :: Create VBS script
        echo Set UAC = CreateObject^("Shell.Application"^)>"%TEMP%\elevate.vbs"
        echo UAC.ShellExecute "%~f0", "%TEMP%\elevate.vbs", "", "runas", 1 >>"%TEMP%\elevate.vbs"
        if exist "%TEMP%\elevate.vbs" start /b /wait >nul cscript /nologo "%TEMP%\elevate.vbs" 2>&1

        :: Delete elevation script if exist
        if exist "%TEMP%\elevate.vbs" >nul del /f "%TEMP%\elevate.vbs" 2>&1

        exit /b
    )
)
pushd "%~dp0"
::##################################################################
:: Finished elevation                                              #
::##################################################################

set "javafolder=jre1.8.0_251"
set "java32installer=jre-8u251-windows-i586"
set "java64installer=jre-8u251-windows-x64"
set "winrar32installer=winrar-x32-590br"
set "winrar64installer=winrar-x64-590br"
set "libreoffice32installer=LibreOffice_6.4.3_Win_x86"
set "libreoffice64installer=LibreOffice_6.4.3_Win_x64"
set "chromesetup=ChromeSetup"
set "firefoxsetup=Firefox Installer"
set "klite=K-Lite_Codec_Pack_1544_Mega"

if "%PROCESSOR_ARCHITECTURE%"=="AMD64" (
    set "PF86=%ProgramFiles(x86)%"
    set "is64=1"
) ELSE (
    set "PF86=%ProgramFiles%"
    set "is64=0"
)

IF "%is64%"=="1" (
    set "nircmd=%CD%\nircmd64.exe"
) ELSE (
    set "nircmd=%CD%\nircmd32.exe"
)

REM --> Verifying dependances
IF NOT EXIST "%nircmd%" (
    echo Error
    goto END
)

REM --> Getting Windows version and saving in "windowsversion" variable
for /f "tokens=4-7 delims=[.] " %%i in ('ver') do (if %%i==Version (set windowsversion=%%j.%%k) else (set windowsversion=%%i.%%j))

REM --> Installing programs
IF NOT EXIST "%ProgramFiles%\WinRAR" (
    IF "%is64%"=="1" (
        start /d "%CD%" %winrar64installer%.exe -s
        %nircmd% cmdwait 200 waitprocess %winrar64installer%.exe
    ) ELSE (
        start /d "%CD%" %winrar32installer%.exe -s
        %nircmd% cmdwait 200 waitprocess %winrar32installer%.exe
    )
    IF NOT EXIST "%ProgramFiles%\WinRAR\WinRAR_goods.exe" start /d "%CD%" /wait cmd /c "winrar tweaks.bat"
    echo WinRAR installed
)

IF NOT EXIST "%PF86%\Google\Chrome" (
    start /d "%CD%" %chromesetup%.exe -silent -install
    %nircmd% cmdwait 200 waitprocess %chromesetup%.exe
    echo Google Chrome installed
)

IF NOT EXIST "%PF86%\K-Lite Codec Pack" (
    start /d "%CD%" %klite%.exe -verysilent -norestart
    %nircmd% cmdwait 200 waitprocess %klite%.exe
    echo K-Lite Codec Pack installed
)

IF NOT EXIST "%ProgramFiles%\Mozilla Firefox" (
    start /d "%CD%" "%firefoxsetup%.exe" -ms
    %nircmd% cmdwait 200 waitprocess "%firefoxsetup%.exe"
    echo Firefox installed
)

IF NOT EXIST "%PF86%\Java\%javafolder%" (
    start /d "%CD%" %java32installer%.exe
    %nircmd% cmdwait 200 waitprocess %java32installer%.exe
    echo Java 32 bits installed
)

IF "%is64%"=="1" (
    IF NOT EXIST "%ProgramFiles%\Java\%javafolder%" (
        start /d "%CD%" %java64installer%.exe
        %nircmd% cmdwait 200 waitprocess %java64installer%.exe
        echo Java 64 bits installed
    )
)

IF "%windowsversion%" NEQ "10.0" (
    IF NOT EXIST "%ProgramFiles%\LibreOffice" (
        IF "%is64%"=="1" (
            %SystemRoot%\system32\msiexec.exe /i "%CD%\%libreoffice64installer%.msi" /QN
            %nircmd% cmdwait 200 waitprocess %libreoffice64installer%.msi
        ) ELSE (
            %SystemRoot%\system32\msiexec.exe /i "%CD%\%libreoffice32installer%.msi" /QN
            %nircmd% cmdwait 200 waitprocess %libreoffice32installer%.msi
        )
        echo LibreOffice installed
    )
)

echo EVERYTHING WAS SUCCESSFULLY INSTALLED!

:END
pause
endlocal
exit
</code>```

If someone can point me where the error is, I would really appreciate it, thank you very much.

答:
Run as Admin changes current directory. Check out the link below to prove it to yourself.

Run as Admin changes current directory

Body:
I made this batch file intending to automate program installation between some Windows machines I constantly have to reformat, but when I run it, it just close the CMD without any error, I've tried many different things like BatCodeCheck but I wasn't able to find why it's crashing. I am not experienced with batch files so I am struggling really hard right now.

The idea behind my batch file is to have to run just one file and install all the basic software needed for the average Joe.

Here's my AIO install everything.bat file.

@echo off
SETLOCAL EnableExtensions

::##################################################################
:: Elevate this script                                             #
::##################################################################

(
    :: Check Admin rights and create VBS Script to elevate
    >nul fsutil dirty query %SYSTEMDRIVE% 2>&1 || (

        :: Very little red console
        mode con cols=80 lines=3
        color cf

        :: Message
        title Please wait...
        echo[
        echo                         Requesting elevated shell...

        :: Create VBS script
        echo Set UAC = CreateObject^("Shell.Application"^)>"%TEMP%\elevate.vbs"
        echo UAC.ShellExecute "%~f0", "%TEMP%\elevate.vbs", "", "runas", 1 >>"%TEMP%\elevate.vbs"
        if exist "%TEMP%\elevate.vbs" start /b /wait >nul cscript /nologo "%TEMP%\elevate.vbs" 2>&1

        :: Delete elevation script if exist
        if exist "%TEMP%\elevate.vbs" >nul del /f "%TEMP%\elevate.vbs" 2>&1

        exit /b
    )
)
pushd "%~dp0"
::##################################################################
:: Finished elevation                                              #
::##################################################################

set "javafolder=jre1.8.0_251"
set "java32installer=jre-8u251-windows-i586"
set "java64installer=jre-8u251-windows-x64"
set "winrar32installer=winrar-x32-590br"
set "winrar64installer=winrar-x64-590br"
set "libreoffice32installer=LibreOffice_6.4.3_Win_x86"
set "libreoffice64installer=LibreOffice_6.4.3_Win_x64"
set "chromesetup=ChromeSetup"
set "firefoxsetup=Firefox Installer"
set "klite=K-Lite_Codec_Pack_1544_Mega"

if "%PROCESSOR_ARCHITECTURE%"=="AMD64" (
    set "PF86=%ProgramFiles(x86)%"
    set "is64=1"
) ELSE (
    set "PF86=%ProgramFiles%"
    set "is64=0"
)

IF "%is64%"=="1" (
    set "nircmd=%CD%\nircmd64.exe"
) ELSE (
    set "nircmd=%CD%\nircmd32.exe"
)

REM --> Verifying dependances
IF NOT EXIST "%nircmd%" (
    echo Error
    goto END
)

REM --> Getting Windows version and saving in "windowsversion" variable
for /f "tokens=4-7 delims=[.] " %%i in ('ver') do (if %%i==Version (set windowsversion=%%j.%%k) else (set windowsversion=%%i.%%j))

REM --> Installing programs
IF NOT EXIST "%ProgramFiles%\WinRAR" (
    IF "%is64%"=="1" (
        start /d "%CD%" %winrar64installer%.exe -s
        %nircmd% cmdwait 200 waitprocess %winrar64installer%.exe
    ) ELSE (
        start /d "%CD%" %winrar32installer%.exe -s
        %nircmd% cmdwait 200 waitprocess %winrar32installer%.exe
    )
    IF NOT EXIST "%ProgramFiles%\WinRAR\WinRAR_goods.exe" start /d "%CD%" /wait cmd /c "winrar tweaks.bat"
    echo WinRAR installed
)

IF NOT EXIST "%PF86%\Google\Chrome" (
    start /d "%CD%" %chromesetup%.exe -silent -install
    %nircmd% cmdwait 200 waitprocess %chromesetup%.exe
    echo Google Chrome installed
)

IF NOT EXIST "%PF86%\K-Lite Codec Pack" (
    start /d "%CD%" %klite%.exe -verysilent -norestart
    %nircmd% cmdwait 200 waitprocess %klite%.exe
    echo K-Lite Codec Pack installed
)

IF NOT EXIST "%ProgramFiles%\Mozilla Firefox" (
    start /d "%CD%" "%firefoxsetup%.exe" -ms
    %nircmd% cmdwait 200 waitprocess "%firefoxsetup%.exe"
    echo Firefox installed
)

IF NOT EXIST "%PF86%\Java\%javafolder%" (
    start /d "%CD%" %java32installer%.exe
    %nircmd% cmdwait 200 waitprocess %java32installer%.exe
    echo Java 32 bits installed
)

IF "%is64%"=="1" (
    IF NOT EXIST "%ProgramFiles%\Java\%javafolder%" (
        start /d "%CD%" %java64installer%.exe
        %nircmd% cmdwait 200 waitprocess %java64installer%.exe
        echo Java 64 bits installed
    )
)

IF "%windowsversion%" NEQ "10.0" (
    IF NOT EXIST "%ProgramFiles%\LibreOffice" (
        IF "%is64%"=="1" (
            %SystemRoot%\system32\msiexec.exe /i "%CD%\%libreoffice64installer%.msi" /QN
            %nircmd% cmdwait 200 waitprocess %libreoffice64installer%.msi
        ) ELSE (
            %SystemRoot%\system32\msiexec.exe /i "%CD%\%libreoffice32installer%.msi" /QN
            %nircmd% cmdwait 200 waitprocess %libreoffice32installer%.msi
        )
        echo LibreOffice installed
    )
)

echo EVERYTHING WAS SUCCESSFULLY INSTALLED!

:END
pause
endlocal
exit

If someone can point me where the error is, I would really appreciate it, thank you very much.


问:
How can I find the device uuid's of all connected devices through a command line script?
I am running automated tests on iOS devices.  I want to not have to always have all devices connected.  So I want to find all device id's and then only start the process of building, deploying, and running tests if that device is connected.

So my question is, how can I find the device uuid's of all connected devices through a shell script?

Thanks!

答: If you have XCode go to Window > Devices & Simulators. On that page, any connected device will display along with other IDs and stats on your device. This will also connect to devices over WIFI.</p>


问:
How to resolve branches when git diff .. returns nothing but git diff ... returns changes?
I think my master and release branches somehow diverged and I'm wondering what the best way to bring them back in sync is.

I have a master branch which is supposed to be used for development, but then I'll merge this master branch into a release branch to create final builds that can be deployed. It was working fine, but as of a week ago, whenever I try to create a pull request merging from master into release, I get a list of commits that should've already been in release. I'll merge the PR, but this keeps happening with every new PR trying to merge from master to release.

I tried looking at changes to make sure both branches are identical

git diff upstream/master..upstream/release gives me no diffs.

git diff upstream/release..upstream/master also gives me no diffs.

However git diff upstream/master...upstream/release gives me the changes from all the commits since the one that probably diverged my two branches.

I think what might be happening is that my two branches are identical in raw code, but they have different commits? I'm still taking classes on git and how to use it more effectively so any help would be greatly appreciated!

答:
I bet that if you run git diff upstream/release...upstream/master you will get the same output as the 3rd command you posted there... and yes, the branches have diverged, but they have the same content, that's why you have no diff with 2 dots but you get output with 3 dots.

That still doesn't answer your question. It really depends on what you call "bring them in sync".

If you mean have the same content: they already do

If you mean get the branch histories together, you might try merging them.

If you mean get one branch to have the exact same history as the other, that implies resetting --hard (therefore rewriting history) and some force-pushing.


Title: How make the Button disabled in Angular form

Body:
I have a button that I need to disable when the form is empty so when I open the form at the beginning it should be disabled and make it enable when any inputs in form get value, I have this code, but it is not disable when form loads, as when form load it is valid, how I can make it not valid so the button will be disabled?

HTML:

<button
  class="search-form__btn"
  type="submit"
  size="large"
  [disabled]="!isEnabled"
>
  Run Search
</button>

TS file:

public get isEnabled(): boolean {
  const form: FormGroup = this.searchForm;
  if (form.get('filters.firstName').value !== ''
    || form.get('filters.lastName').value !== ''
    || form.get('filters.company').value !== ''
    || form.get('filters.phone').value !== ''
    || form.get('filters.email').value !== ''
    || form.get('filters.officer').value !== ''
    || form.get('filters.number').value !== ''
    || form.get('filters.state').value !== '') {
    return form.valid;
  }
}

and this is my form:

constructor(private fb: FormBuilder) {
  this.searchForm = this.fb.group({
    filters: this.fb.group({
      searchString: [""],
      firstName: [""],
      lastName: [""],
      company: [""],
      email: [null, [Validators.email]],
      phone: [""],
      officer: [""],
      number: [""],
      state: [""],
      exactMatch: [false],
    }),
    pageSize: [100],
    currentPage: [1],
  });
}

Body: [disabled]="searchForm.invalid"


问:
g++ warning when using optional 'struct' keyword
If I write this program:

```<code>#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}
</code>```

and compile it with:

```<code>g++ main.cxx -Wall -Wextra
</code>```

It gives me this warning:

```<code>main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]
</code>```

However, if I take out the struct keyword after the new keyword:

```<code>#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}
</code>```

and compile it the same way, g++ outputs no warnings.  Why does g++ output that warning if I use the struct keyword?

答: In C++, the struct keyword defines a type, and the new type no longer needs the struct keyword.  This is one of the many differences between C and C++.

Body:
If I write this program:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}

and compile it with:

g++ main.cxx -Wall -Wextra

It gives me this warning:

main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]

However, if I take out the struct keyword after the new keyword:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}

and compile it the same way, g++ outputs no warnings.  Why does g++ output that warning if I use the struct keyword?


问:
Alter the audio format for Amazon connect recordings
So the basic problem is that I am setting up an Amazon connect instance and have successfully started recording calls too but I want the recording audio file to be stored in the S3 bucket in some format(.mp3, .mp4, etc) other than the default that is provided by Amazon (.wav).

Since .wav is the default format and I am not getting any official documentation regarding the change in any format, Any leads would be welcome.

Rather than downloading the file and converting it to the target format, which I have already done, I need the file to be stored in the S3 in the target format itself(anything other than .wav).

答:
Currently there is no capability to change audio format for Connect call recordings; it's fixed at 8 kHz, 16 bit WAV files. But you could set up a MediaConvert job to automatically convert to any format you'd like.

Alternatively you could have a trigger call a Lambda function to do the same thing. Here's a CloudFormation template that sets that up for you.

In both solutions, you might want to adjust the process a bit to delete the WAV file after conversion, to save on storage costs


答:
Have you tried (assuming df is a pandas.DataFrame):

```<code>days_logged = 5
rolling_days = 4
cols = ['B', 'C']

for col in cols:
    for i in range(days_logged, len(df.index)):
        df[col].iloc[i] =  df[col].iloc[i - rolling_days: i].mean()
</code>```

Title: Continue column with average of previous values

Body:
Have you tried (assuming df is a pandas.DataFrame):

days_logged = 5
rolling_days = 4
cols = ['B', 'C']

for col in cols:
    for i in range(days_logged, len(df.index)):
        df[col].iloc[i] =  df[col].iloc[i - rolling_days: i].mean()


问:
.Net MVC3 Custom Model Binder - Initially Loading Model
I am creating a custom model binder to initially load a model from the database before updating the model with incoming values. (Inheriting from DefaultModelBinder)

Which method do I need to override to do this?

答: You'll want to override BindModel to do this. </p>


问:
Control the Bokeh xwheel_zoom tool using a Bokeh widget/callback
I am using xwheel_zoom (WheelZoomTool) for a Bokeh chart with datetime axis.

```<code>p = figure(x_axis_type="datetime", tools='xwheel_zoom, crosshair, undo, reset')
</code>```

I provide pandas TimeStamp as the x value of this chart. For example:pd.Timestamp.now(tz='utc'). The x axis range of this chart is for the last 24 hours.

start = pd.Timestamp.now(tz='utc') - pd.Timedelta(hours=24)

Using xwheel_zoom, I could zoom in to see my chart better for a given time (e.g. last hour).

Is there any way in Bokeh I could achieve this zoom functionality by coding or connecting to the xwheel_zoom and controling it with a Bokeh widget (e.g. Bokeh dropdown)?

My objective is to have a button to click on and let it show me the zoomed in x_axis for the last hour, or show the chart between a datetime period I define. Idealy, I do not want to re-define/re-draw the chart again and just want to control the xwheel_zoom functionality.

答:
You don't need any tools to do that. Just change the desired range in a callback. Something like:

b = Button()

def update():
    p.x_range.update(start=0, end=1)

b.on_click(update)
```

The example will work only if used with bokeh serve. If you're not using that, you can rewrite the code to work with CustomJS and js_on_click.

Body:
I am using xwheel_zoom (WheelZoomTool) for a Bokeh chart with datetime axis.

p = figure(x_axis_type="datetime", tools='xwheel_zoom, crosshair, undo, reset')

I provide pandas TimeStamp as the x value of this chart. For example:pd.Timestamp.now(tz='utc'). The x axis range of this chart is for the last 24 hours.

start = pd.Timestamp.now(tz='utc') - pd.Timedelta(hours=24)

Using xwheel_zoom, I could zoom in to see my chart better for a given time (e.g. last hour).

Is there any way in Bokeh I could achieve this zoom functionality by coding or connecting to the xwheel_zoom and controling it with a Bokeh widget (e.g. Bokeh dropdown)?

My objective is to have a button to click on and let it show me the zoomed in x_axis for the last hour, or show the chart between a datetime period I define. Idealy, I do not want to re-define/re-draw the chart again and just want to control the xwheel_zoom functionality.

Body:
You don't need any tools to do that. Just change the desired range in a callback. Something like:

b = Button()

def update():
    p.x_range.update(start=0, end=1)

b.on_click(update)

The example will work only if used with bokeh serve. If you're not using that, you can rewrite the code to work with CustomJS and js_on_click.