问:
Logback - can you define appender name and class from env variables?
I want to have dynamic logback appender properties which can easily be added to the logback config file, however trying to set the class and name of the appender(which are in a xml attributes instead of elements under the appender element).

So here is my application.yml(hardcoded the values for the example, but in the real world use case those will be passed as env variables from Helm, during the deploy to K8s cluster):

```<code>log:
  config:
    appender:
      name: CONSOLE
      class: ch.qos.logback.core.ConsoleAppender
</code>```

And here is how I try to access those in logback-spring.xml(spring boot version - 2.2.4.RELEASE

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- use Spring default values like patterns -->
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <!-- declaration of ENV properties:   -->
    <springProperty name="LOG_CONFIG_APPENDER_NAME" source="log.config.appender.name"/>
    <springProperty name="LOG_CONFIG_APPENDER_CLASS" source="log.config.appender.class"/>

    <appender name="${LOG_CONFIG_APPENDER_NAME}" class="${LOG_CONFIG_APPENDER_CLASS}">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="${LOG_CONFIG_APPENDER_NAME}"/>
    </root>
</configuration>
</code>```

This leads to the following exception:

```<code>ERROR in ch.qos.logback.core.joran.action.AppenderAction - Could not create an Appender of type [${LOG_CONFIG_APPENDER_CLASS}]. ch.qos.logback.core.util.DynamicClassLoadingException: Failed to instantiate type ${LOG_CONFIG_APPENDER_CLASS}
</code>```

So my question is: is it possible to define the appender name and class dynamically ?

答:
For the local env I want to have simple console log appender. For anything else I will use the LayoutWrappingEncoder and JacksonJsonFormatter to add custom fields for our ELK stack.

So you want to use the <springProfile> tag in your logback-spring.xml:

The <springProfile> tag lets you optionally include or exclude sections of configuration based on the active Spring profiles. Profile sections are supported anywhere within the <configuration> element. Use the name attribute to specify which profile accepts the configuration. The <springProfile> tag can contain a simple profile name (for example staging) or a profile expression. A profile expression allows for more complicated profile logic to be expressed, for example production & (eu-central | eu-west). Check the reference guide for more details.

See the example below:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <springProfile name="staging">

    </springProfile>

    <springProfile name="dev | staging">

    </springProfile>

    <springProfile name="!production">

    </springProfile>

</configuration>
```

Body:
I want to have dynamic logback appender properties which can easily be added to the logback config file, however trying to set the class and name of the appender(which are in a xml attributes instead of elements under the appender element).

So here is my application.yml(hardcoded the values for the example, but in the real world use case those will be passed as env variables from Helm, during the deploy to K8s cluster):

log:
  config:
    appender:
      name: CONSOLE
      class: ch.qos.logback.core.ConsoleAppender

And here is how I try to access those in logback-spring.xml(spring boot version - 2.2.4.RELEASE

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <springProperty name="LOG_CONFIG_APPENDER_NAME" source="log.config.appender.name"/>
    <springProperty name="LOG_CONFIG_APPENDER_CLASS" source="log.config.appender.class"/>

    <appender name="${LOG_CONFIG_APPENDER_NAME}" class="${LOG_CONFIG_APPENDER_CLASS}">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="${LOG_CONFIG_APPENDER_NAME}"/>
    </root>
</configuration>

This leads to the following exception:

ERROR in ch.qos.logback.core.joran.action.AppenderAction - Could not create an Appender of type [${LOG_CONFIG_APPENDER_CLASS}]. ch.qos.logback.core.util.DynamicClassLoadingException: Failed to instantiate type ${LOG_CONFIG_APPENDER_CLASS}

So my question is: is it possible to define the appender name and class dynamically ?

Body:
For the local env I want to have simple console log appender. For anything else I will use the LayoutWrappingEncoder and JacksonJsonFormatter to add custom fields for our ELK stack.

So you want to use the <springProfile> tag in your logback-spring.xml:

The <springProfile> tag lets you optionally include or exclude sections of configuration based on the active Spring profiles. Profile sections are supported anywhere within the <configuration> element. Use the name attribute to specify which profile accepts the configuration. The <springProfile> tag can contain a simple profile name (for example staging) or a profile expression. A profile expression allows for more complicated profile logic to be expressed, for example production & (eu-central | eu-west). Check the reference guide for more details.

See the example below:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <springProfile name="staging">
        <!-- configuration to be enabled when the "staging" profile is active -->
    </springProfile>

    <springProfile name="dev | staging">
        <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
    </springProfile>

    <springProfile name="!production">
        <!-- configuration to be enabled when the "production" profile is not active -->
    </springProfile>

</configuration>


来源: stackexchange

问:
How to replace a title in span with plain text and username (or diplay name) with PHP
Here is my situation.

I'm using flatsome theme with woocommerce. In its theme customizer, I can just check option boxes to make Account header show "Login / Register" before logging in and show display name (TEST in picture) after logging in. https://imgur.com/7tekdTo https://imgur.com/dYWQg75

These options work correctly on desktop but on mobile website it is not at all. These options don't apply. I figure my only choice here is JavaScript. But I know next to nothing about HTML and JavaScript. https://imgur.com/p6Tn7Ig https://imgur.com/0i1tCkB

My question here are

How can I change Login to Login / Register before logging in on mobile.

How can I make it show display name instead of My Account after logging in on mobile.

I really want to save cost so plug-in isn't viable option for me. I prefer this default header too because creating custom menu I can't use popup login / register screen. I have searched online and none of solution work so far.

These are my elements of the mentioned account header.

Before logging in.

```<code><a href="https://www.mywebsite.com/my-account/" class="nav-top-link nav-top-not-logged-in " data-open="#login-form-popup">
<span>
Login / Register </span>
</a>
</code>```

After logging in.

```<code><a href="https://www.mywebsite.com/my-account/" class="account-link account-login
  " title="My account">

            <span class="header-account-title">
        test        </span>
</a>
</code>```

答:
@MihaiT is right. Dig around.

Very hard to help with specifics because you're using a builder, there are so many variables at play in how you have it set up. But all themes use header.php to display whatever is consistent across all headers - notably, login/logout details. You could take a look at your header.php and have a play around with something like this:

```<code><?php global $current_user; wp_get_current_user(); ?>

<?php if ( is_user_logged_in() ) { ?>

<div class="account-details">
    <p class="username">Welcome back <?php echo $current_user->display_name; ?></p>
    <a href="<?php echo wp_logout_url( get_permalink() ); ?>"> | Logout</a>
</div>

 <?php } else { ?>

 <div class="account-details">
    <a href="/login/">Login |</a>
    <a href="/register/"> Register</a>
</div>

 <?php } ?>
</code>```

You would need to make any changes on a child theme so as not to overwrite any changes you make with a theme update. If you have no intention of ever creating a custom theme, then maybe this approach is not for you, and it's best to reach out to the theme devs for support. The big problem with themes and builders is the moment you need something that's not included, you're in a pickle.

The above code uses a basic if/else and a wordpress function that detects if the user is logged in. Because you're running this in the back end you have access to useful data such as username. You'd need to figure out the links for logging in/out but this is the general theory.

ContentLicense: CC BY-SA 4.0

Body:
Here is my situation.

I'm using flatsome theme with woocommerce. In its theme customizer, I can just check option boxes to make Account header show "Login / Register" before logging in and show display name (TEST in picture) after logging in. https://imgur.com/7tekdTo https://imgur.com/dYWQg75

These options work correctly on desktop but on mobile website it is not at all. These options don't apply. I figure my only choice here is JavaScript. But I know next to nothing about HTML and JavaScript. https://imgur.com/p6Tn7Ig https://imgur.com/0i1tCkB

My question here are

How can I change Login to Login / Register before logging in on mobile.

How can I make it show display name instead of My Account after logging in on mobile.

I really want to save cost so plug-in isn't viable option for me. I prefer this default header too because creating custom menu I can't use popup login / register screen. I have searched online and none of solution work so far.

These are my elements of the mentioned account header.

Before logging in.

Login / Register

After logging in.

        test

Body:
@MihaiT is right. Dig around.

Very hard to help with specifics because you're using a builder, there are so many variables at play in how you have it set up. But all themes use header.php to display whatever is consistent across all headers - notably, login/logout details. You could take a look at your header.php and have a play around with something like this:

<?php global $current_user; wp_get_current_user(); ?>

<?php if ( is_user_logged_in() ) { ?>

<div class="account-details">
    <p class="username">Welcome back <?php echo $current_user->display_name; ?></p>
    <a href="<?php echo wp_logout_url( get_permalink() ); ?>">&nbsp;|&nbsp;Logout</a>
</div>

 <?php } else { ?>

 <div class="account-details">
    <a href="/login/">Login&nbsp;|</a>
    <a href="/register/">&nbsp;Register</a>
</div>

 <?php } ?>

You would need to make any changes on a child theme so as not to overwrite any changes you make with a theme update. If you have no intention of ever creating a custom theme, then maybe this approach is not for you, and it's best to reach out to the theme devs for support. The big problem with themes and builders is the moment you need something that's not included, you're in a pickle.

The above code uses a basic if/else and a wordpress function that detects if the user is logged in. Because you're running this in the back end you have access to useful data such as username. You'd need to figure out the links for logging in/out but this is the general theory.


问:
How would I get the 2nd max date with if
How would I get the 2nd max date if there is date entered as today? Note I always need to select the yesterdays date.</p>

```<code>Select *
From MyList
Where Date = (Select Max(Date)
</code>```

答:
One way would be:

```<code>Select *
From MyList
Where Date = (Select top 1 Date from MyList where Date < (select Max(Date) from MyList) order by Date DESC)
</code>```

Which translates roughly to: Select everything from your list where Date is equal to the date where date is less than the largest date

Based on the on the comments ramon posted I believe this is what he needs:

```<code>    SELECT TOP 1  [date] FROM (
    SELECT MAX(DATE) [date]
    FROM MyList
    WHERE [DATE] <
    (
        SELECT MAX(DATE) FROM MyList
    )
    AND EXISTS
    (
        SELECT 1 FROM MyList WHERE [DATE] = CAST(GETDATE() AS DATE)
    )
    UNION
    SELECT MAX(DATE)
    FROM MyList
    WHERE NOT EXISTS
    (
        SELECT 1 FROM MyList WHERE [DATE] = CAST(GETDATE() AS DATE)
    )) x ORDER BY [x].[date] desc
</code>```

Everything together:

```<code>SELECT * from MyList where [Date] = (
    SELECT TOP 1  [date] FROM (
    SELECT MAX(DATE) [date]
    FROM MyList
    WHERE [DATE] <
    (
        SELECT MAX(DATE) FROM MyList
    )
    AND EXISTS
    (
        SELECT 1 FROM MyList WHERE [DATE] = CAST(GETDATE() AS DATE)
    )
    UNION
    SELECT MAX(DATE)
    FROM MyList
    WHERE NOT EXISTS
    (
        SELECT 1 FROM MyList WHERE [DATE] = CAST(GETDATE() AS DATE)
    )) x ORDER BY [x].[date] desc)
</code>```

First part of the UNION selects 2nd max(date) if there's data for today's date. Second part of the union selects max(date) if there's no data for Today.

Body:
How would I get the 2nd max date if there is date entered as today? Note I always need to select the yesterdays date.

Select *
From MyList
Where Date = (Select Max(Date)

Body:
One way would be:

Select *
From MyList
Where Date = (Select top 1 Date from MyList where Date < (select Max(Date) from MyList) order by Date DESC)

Which translates roughly to: Select everything from your list where Date is equal to the date where date is less than the largest date

Based on the on the comments ramon posted I believe this is what he needs:

    SELECT TOP 1  [date] FROM (
    SELECT MAX(DATE) [date]
    FROM MyList
    WHERE [DATE] <
    (
        SELECT MAX(DATE) FROM MyList
    )
    AND EXISTS
    (
        SELECT 1 FROM MyList WHERE [DATE] = CAST(GETDATE() AS DATE)
    )
    UNION
    SELECT MAX(DATE)
    FROM MyList
    WHERE NOT EXISTS
    (
        SELECT 1 FROM MyList WHERE [DATE] = CAST(GETDATE() AS DATE)
    )) x ORDER BY [x].[date] desc

Everything together:

SELECT * from MyList where [Date] = (
    SELECT TOP 1  [date] FROM (
    SELECT MAX(DATE) [date]
    FROM MyList
    WHERE [DATE] <
    (
        SELECT MAX(DATE) FROM MyList
    )
    AND EXISTS
    (
        SELECT 1 FROM MyList WHERE [DATE] = CAST(GETDATE() AS DATE)
    )
    UNION
    SELECT MAX(DATE)
    FROM MyList
    WHERE NOT EXISTS
    (
        SELECT 1 FROM MyList WHERE [DATE] = CAST(GETDATE() AS DATE)
    )) x ORDER BY [x].[date] desc)

First part of the UNION selects 2nd max(date) if there's data for today's date. Second part of the union selects max(date) if there's no data for Today.


问:
How to avoid string repetition
I have two different string String A="example"; String B="example";
if concat both the string i am getting examplexample. Is there any possibility to avoid repetition of string with same name..??

答:
How about this ?</p>

```<code>if(!a.equals(b)){// or if needed use contains() , equalIgnoreCase() depending on your need
 //concat
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to avoid string repetition

Body:
How about this ?

if(!a.equals(b)){// or if needed use contains() , equalIgnoreCase() depending on your need
 //concat
}


问:
How to fix multiprocessing problems in python in windows10
I try to use this tutorial to train my own car model recognition model: https://github.com/Helias/Car-Model-Recognition. And i want to use coda and my gpu perfomance to enhance training speed (preprocesssing step was completed without any errors).But when I try to train my model, I've got the following errors:

```<code>######### ERROR #######

        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

######### batch #######
Traceback (most recent call last):
  File "D:\Car-Model-Recognition\main.py", line 78, in train_model

######### ERROR #######
[Errno 32] Broken pipe
    for i, batch in enumerate(loaders[mode]):

######### batch #######  File "C:\Program Files\Python37\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__

    return _MultiProcessingDataLoaderIter(self)
Traceback (most recent call last):
  File "C:\Program Files\Python37\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
  File "main.py", line 78, in train_model
    w.start()
  File "C:\Program Files\Python37\lib\multiprocessing\process.py", line 112, in start
    for i, batch in enumerate(loaders[mode]):
  File "C:\Program Files\Python37\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    self._popen = self._Popen(self)
  File "C:\Program Files\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Program Files\Python37\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Program Files\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    w.start()
    return Popen(process_obj)
  File "C:\Program Files\Python37\lib\multiprocessing\popen_spawn_win32.py", line 46, in __init__
  File "C:\Program Files\Python37\lib\multiprocessing\process.py", line 112, in start
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Program Files\Python37\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    self._popen = self._Popen(self)
  File "C:\Program Files\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    _check_not_importing_main()
  File "C:\Program Files\Python37\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Program Files\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    is not going to be frozen to produce an executable.''')
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
    return Popen(process_obj)
</code>```

I have used the exact code from given link, and if i start my code using wsl, everything is ok, but I can't use my gpu from wsl. Where should I insert this name == 'main' check to prevent such a mistake or how can i disable this multiprocessing

答:
Looking at main.py, you run a lot of code at the module level. On Windows, python's multiprocessing module will start a new python interpreter, import your modules, unpickle a snapshot of your parent context and then call your worker function. The problem is that all of that module level code executes merely by import and you essentially run a new copy of your program instead of building a context for your worker.

The solution is two-fold. First, move all of the module level code into functions. You want to be a able to import your module without side effects. Second, call the function(s) that start your program from a conditional

```<code>def main():
    the stuff you were doing a module level

if __name__ == "__main__":
    main()
</code>```

The reason this works is in the module name. When you run the top level script of a python (e.g., python main.py), its a script called "__main__", not a module. If a different program imports main its a module called "main" (or whatever you named your script). That 'if' stops your main code from executing if its imported by some other python code - such as the multiprocessing module.

Its okay to have some executable code at the module level, especially if you are setting up defaults and such. But don't do anything at the module level that you wouldn't want done if some other code imports your script.

Body:
I try to use this tutorial to train my own car model recognition model: https://github.com/Helias/Car-Model-Recognition. And i want to use coda and my gpu perfomance to enhance training speed (preprocesssing step was completed without any errors).But when I try to train my model, I've got the following errors:

######### ERROR #######

        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

######### batch #######
Traceback (most recent call last):
  File "D:\Car-Model-Recognition\main.py", line 78, in train_model

######### ERROR #######
[Errno 32] Broken pipe
    for i, batch in enumerate(loaders[mode]):

######### batch #######  File "C:\Program Files\Python37\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__

    return _MultiProcessingDataLoaderIter(self)
Traceback (most recent call last):
  File "C:\Program Files\Python37\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
  File "main.py", line 78, in train_model
    w.start()
  File "C:\Program Files\Python37\lib\multiprocessing\process.py", line 112, in start
    for i, batch in enumerate(loaders[mode]):
  File "C:\Program Files\Python37\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    self._popen = self._Popen(self)
  File "C:\Program Files\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Program Files\Python37\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Program Files\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    w.start()
    return Popen(process_obj)
  File "C:\Program Files\Python37\lib\multiprocessing\popen_spawn_win32.py", line 46, in __init__
  File "C:\Program Files\Python37\lib\multiprocessing\process.py", line 112, in start
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Program Files\Python37\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    self._popen = self._Popen(self)
  File "C:\Program Files\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    _check_not_importing_main()
  File "C:\Program Files\Python37\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Program Files\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    is not going to be frozen to produce an executable.''')
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
    return Popen(process_obj)

I have used the exact code from given link, and if i start my code using wsl, everything is ok, but I can't use my gpu from wsl. Where should I insert this name == 'main' check to prevent such a mistake or how can i disable this multiprocessing

Body:
Looking at main.py, you run a lot of code at the module level. On Windows, python's multiprocessing module will start a new python interpreter, import your modules, unpickle a snapshot of your parent context and then call your worker function. The problem is that all of that module level code executes merely by import and you essentially run a new copy of your program instead of building a context for your worker.

The solution is two-fold. First, move all of the module level code into functions. You want to be a able to import your module without side effects. Second, call the function(s) that start your program from a conditional

def main():
    the stuff you were doing a module level

if __name__ == "__main__":
    main()

The reason this works is in the module name. When you run the top level script of a python (e.g., python main.py), its a script called "__main__", not a module. If a different program imports main its a module called "main" (or whatever you named your script). That 'if' stops your main code from executing if its imported by some other python code - such as the multiprocessing module.

Its okay to have some executable code at the module level, especially if you are setting up defaults and such. But don't do anything at the module level that you wouldn't want done if some other code imports your script.


问:
My code doesn't calculate min and max numbers
I'm trying to write a code which will show the highest, lowest, the difference of them and the average of inputted 30 numbers.
But its not working and is showing the same result for both min and max numbers. Here is the code.</p>

```<code>public class aa {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] daystemp = new int[30];
        int i = 0;
        int dayHot = 0;
        int dayCold = 0;
        while(i < daystemp.length){
            daystemp[i] = input.nextInt();
            i++;
        }
        int maxTemp = daystemp[0];
        while (i < daystemp.length) {
            if (daystemp[i] > maxTemp) {
                maxTemp = daystemp[i];
                dayHot = i + 1;
                i++;
            }
        }
        System.out.println(maxTemp);
        int minTemp = daystemp[0];
        while (i < daystemp.length) {
            if (daystemp[i] < minTemp) {
                minTemp = daystemp[i];
                dayCold = i + 1;
                i++;
            }
        }
        System.out.println(minTemp);
        int diff = maxTemp - minTemp;
        System.out.println("The difference between them is"+diff);
        double sum = 0;
        while(i < daystemp.length) {
            sum += daystemp[i];
            i++;
        }
        double average = sum / daystemp.length;
        System.out.println("Average was"+average);
    }
}
</code>```

答:
After the first loop (the input loop), i value is daystemp.length (i.e. 30).

It's never reset to 0. So each while loop condition is false.

Add i=0 before the loops and do i++outside the ifblocks or your code will never end.

example:

```<code>    i=0;
    int maxTemp = daystemp[0];
    while (i < daystemp.length) {
        if (daystemp[i] > maxTemp) {
            maxTemp = daystemp[i];
            dayHot = i + 1;
        }
        i++;
    }
</code>```

Body:
I'm trying to write a code which will show the highest, lowest, the difference of them and the average of inputted 30 numbers.
But its not working and is showing the same result for both min and max numbers. Here is the code.

public class aa {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] daystemp = new int[30];
        int i = 0;
        int dayHot = 0;
        int dayCold = 0;
        while(i < daystemp.length){
            daystemp[i] = input.nextInt();
            i++;
        }
        int maxTemp = daystemp[0];
        while (i < daystemp.length) {
            if (daystemp[i] > maxTemp) {
                maxTemp = daystemp[i];
                dayHot = i + 1;
                i++;
            }
        }
        System.out.println(maxTemp);
        int minTemp = daystemp[0];
        while (i < daystemp.length) {
            if (daystemp[i] < minTemp) {
                minTemp = daystemp[i];
                dayCold = i + 1;
                i++;
            }
        }
        System.out.println(minTemp);
        int diff = maxTemp - minTemp;
        System.out.println("The difference between them is"+diff);
        double sum = 0;
        while(i < daystemp.length) {
            sum += daystemp[i];
            i++;
        }
        double average = sum / daystemp.length;
        System.out.println("Average was"+average);
    }
}

Body:
After the first loop (the input loop), i value is daystemp.length (i.e. 30).

It's never reset to 0. So each while loop condition is false.

Add i=0 before the loops and do i++outside the ifblocks or your code will never end.

example:

    i=0;
    int maxTemp = daystemp[0];
    while (i < daystemp.length) {
        if (daystemp[i] > maxTemp) {
            maxTemp = daystemp[i];
            dayHot = i + 1;
        }
        i++;
    }


问:
Turn off device programmatically
I am writing an App that is designed to run on one specific device model (an Android set-top device that runs Amlogic based firmware). I have both root capability and my App is signed with the firmware certificate.

My App is the main focus of the device, and it would be helpful to be able to initiate a complete power-off.

I do not have the shutdown command. I do have the reboot command.

reboot -p does not help. It simply freezes the device while remaining powered on.

The PowerManager is one step better, but it sets the device into sleep mode, instead of a complete shutdown:

```<code>PowerManager pm = (PowerManager)getSystemService(Service.POWER_SERVICE);
pm.goToSleep(SystemClock.uptimeMillis());
</code>```

I am open to all suggestions - hacky or otherwise. The version of Android is expected to remain at 4.2.2.

Intents

This command will cause the device to reboot. Intent.ACTION_SHUTDOWN does not appear to do anything. Is this Intent perhaps only to report a shutdown, and not to initiate one?

```<code>Intent i = new Intent(Intent.ACTION_REBOOT);
i.putExtra("nowait", 1);
i.putExtra("interval", 1);
i.putExtra("window", 0);
sendBroadcast(i);
</code>```

The most luck I had with this was to request a shutdown by Intent:

```<code>Intent i = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
i.putExtra("android.intent.extra.KEY_CONFIRM", true);
startActivity(i);
</code>```

Shutdown Thread

That is a bit closer. Definitely interesting. Can you find an example of using it?

So far I have come up with this:

```<code>Class<?> sdClass = Class.forName("com.android.server.power.ShutdownThread");
Constructor<?> con = sdClass.getDeclaredConstructors()[0];
con.setAccessible(true);

for (Method m : sdClass.getDeclaredMethods()) {
    if (m.getName().matches("shutdown")) {
        m.setAccessible(true);
        m.invoke(sdClass, PlayerActivity.this, false);
    } else if (m.getName().matches("rebootOrShutdown")) {
        m.setAccessible(true);
        m.invoke(sdClass, PlayerActivity.this, false);
    } else if (m.getName().matches("beginShutdownSequence")) {
        m.setAccessible(true);
        m.invoke(sdClass, PlayerActivity.this, false);
    }
}
</code>```

shutdown and beginShutdownSequence create NullPointerExceptions (do you see why?) and rebootOrShutdown creates an InvocationTargetException due to an UnsatisfiedLinkError... It cannot find a native method:

java.lang.UnsatisfiedLinkError: Native method not found:
  com.android.server.power.PowerManagerService.nativeShutdown:()V   at
  com.android.server.power.PowerManagerService.nativeShutdown(Native
  Method)   at
  com.android.server.power.PowerManagerService.lowLevelShutdown(PowerManagerService.java:2163)
    at
  com.android.server.power.ShutdownThread.rebootOrShutdown(ShutdownThread.java:543)
    at
  com.android.server.power.ShutdownThread.run(ShutdownThread.java:393)

lowLevelShutdown is the function that all the functions eventually reach, when configured to shutdown (and not reboot). So figuring out how to avoid this link error may be key.

答: In newer android versions you aren't allowed to shut down the device from the nonSystem app.</p>

Title: Turn off device programmatically

Body:
I am writing an App that is designed to run on one specific device model (an Android set-top device that runs Amlogic based firmware). I have both root capability and my App is signed with the firmware certificate.

My App is the main focus of the device, and it would be helpful to be able to initiate a complete power-off.

I do not have the shutdown command. I do have the reboot command.

reboot -p does not help. It simply freezes the device while remaining powered on.

The PowerManager is one step better, but it sets the device into sleep mode, instead of a complete shutdown:

PowerManager pm = (PowerManager)getSystemService(Service.POWER_SERVICE);
pm.goToSleep(SystemClock.uptimeMillis());

I am open to all suggestions - hacky or otherwise. The version of Android is expected to remain at 4.2.2.

Intents

This command will cause the device to reboot. Intent.ACTION_SHUTDOWN does not appear to do anything. Is this Intent perhaps only to report a shutdown, and not to initiate one?

Intent i = new Intent(Intent.ACTION_REBOOT);
i.putExtra("nowait", 1);
i.putExtra("interval", 1);
i.putExtra("window", 0);
sendBroadcast(i);

The most luck I had with this was to request a shutdown by Intent:

Intent i = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
i.putExtra("android.intent.extra.KEY_CONFIRM", true);
startActivity(i);

Shutdown Thread

That is a bit closer. Definitely interesting. Can you find an example of using it?

So far I have come up with this:

Class<?> sdClass = Class.forName("com.android.server.power.ShutdownThread");
Constructor<?> con = sdClass.getDeclaredConstructors()[0];
con.setAccessible(true);

for (Method m : sdClass.getDeclaredMethods()) {
    if (m.getName().matches("shutdown")) {
        m.setAccessible(true);
        m.invoke(sdClass, PlayerActivity.this, false);
    } else if (m.getName().matches("rebootOrShutdown")) {
        m.setAccessible(true);
        m.invoke(sdClass, PlayerActivity.this, false);
    } else if (m.getName().matches("beginShutdownSequence")) {
        m.setAccessible(true);
        m.invoke(sdClass, PlayerActivity.this, false);
    }
}

shutdown and beginShutdownSequence create NullPointerExceptions (do you see why?) and rebootOrShutdown creates an InvocationTargetException due to an UnsatisfiedLinkError... It cannot find a native method:

java.lang.UnsatisfiedLinkError: Native method not found:
  com.android.server.power.PowerManagerService.nativeShutdown:()V   at
  com.android.server.power.PowerManagerService.nativeShutdown(Native
  Method)   at
  com.android.server.power.PowerManagerService.lowLevelShutdown(PowerManagerService.java:2163)
    at
  com.android.server.power.ShutdownThread.rebootOrShutdown(ShutdownThread.java:543)
    at
  com.android.server.power.ShutdownThread.run(ShutdownThread.java:393)

lowLevelShutdown is the function that all the functions eventually reach, when configured to shutdown (and not reboot). So figuring out how to avoid this link error may be key.


问:
Why include when you can require in PHP?
What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?

答: Because you don't want the missing files stop your show.  ;)</p>


问:
How to get the component's return value
I have some code like this:

import React from "react";
import "./styles.css";

const t = () => ["test1", "test2"];
const Translate = () => t("myText");

const MyComponent = ({ children }) => {
  console.log(children);
  return (
    children &&
    typeof children === "object" &&
    Array.isArray(children) &&
    children.map(val => (
      <>
        {`${val}__attached`}

      </>
    ))
  );
};

export default function App() {
  return (

      <MyComponent>
        <Translate />
      </MyComponent>

  );
}
```

<p>When I check the console, I get a React element printed. But I want its return value.</p>

<p>For example, if I replace this code:</p>

```    <MyComponent>
        <Translate />
    </MyComponent>

```

<p>with</p>

```    <MyComponent>
        {t()}
    </MyComponent>
```

Then I get an array with 2 objects printed on console. I want to see this same output in my first case.

I want it, because I want to loop through the values returned by Translate and generate output based on that.

Thank you.

Here is the codesandbox link:

答:
You cannot achieve what you want. Indeed, when you write {t()} you actually provide an array as a children for MyComponent and can therefore map its values.

However, as soon as you write <Translate/>, children of MyComponent is no longer an array but a React Element (HTML element so to speak)  (print children in MyComponent to check) making your test always false (so it prints nothing)

Try to call <Translate/> outside of MyComponent and you will see "test1test2" displayed on your page. It is no longer an array.

Instead of writing this:

```<code><MyComponent>
   <Translate />
</MyComponent>
</code>```

I think you should do the other way around to be able to easily manipulate what comes from Translate and passing it to MyComponent:

```<code>   <Translate>
      {values => <MyComponent values={values}>}
   </Translate>
</code>```

with Translate being:

```<code>const Translate = ({ children }) => children(t("myText"));

</code>```

and MyComponent:

```<code>const MyComponent = ({ values }) => {
  return (
    Array.isArray(values) &&
    values.map(val => (
      <>
        {`${val}__attached`}
        <br />
      </>
    ))
  );
};

</code>```

Live demo here

Title: How to get the component's return value

Body:
I have some code like this:

import React from "react";
import "./styles.css";

const t = () => ["test1", "test2"];
const Translate = () => t("myText");

const MyComponent = ({ children }) => {
  console.log(children);
  return (
    children &&
    typeof children === "object" &&
    Array.isArray(children) &&
    children.map(val => (
      <>
        {`${val}__attached`}

      </>
    ))
  );
};

export default function App() {
  return (

      <MyComponent>
        <Translate />
      </MyComponent>

  );
}

When I check the console, I get a React element printed. But I want its return value.

For example, if I replace this code:

    <MyComponent>
        <Translate />
    </MyComponent>

with

    <MyComponent>
        {t()}
    </MyComponent>

Then I get an array with 2 objects printed on console. I want to see this same output in my first case.

I want it, because I want to loop through the values returned by Translate and generate output based on that.

Thank you.

Here is the codesandbox link:

Body:
You cannot achieve what you want. Indeed, when you write {t()} you actually provide an array as a children for MyComponent and can therefore map its values.

However, as soon as you write <Translate/>, children of MyComponent is no longer an array but a React Element (HTML element so to speak)  (print children in MyComponent to check) making your test always false (so it prints nothing)

Try to call <Translate/> outside of MyComponent and you will see "test1test2" displayed on your page. It is no longer an array.

Instead of writing this:

<MyComponent>
   <Translate />
</MyComponent>

I think you should do the other way around to be able to easily manipulate what comes from Translate and passing it to MyComponent:

   <Translate>
      {values => <MyComponent values={values}>}
   </Translate>

with Translate being:

const Translate = ({ children }) => children(t("myText"));

and MyComponent:

const MyComponent = ({ values }) => {
  return (
    Array.isArray(values) &&
    values.map(val => (
      <>
        {`${val}__attached`}
        <br />
      </>
    ))
  );
};

Live demo here


问:
Display: none on Deck.gl React component causes huge performance issue
EDIT: This issue is specific to this setup. Please use the code from here if you wish to help. Thanks!

I am using Deck.gl with react to display a map. When I try to hide the map with display: none it starts to freeze up my whole computer. I have worked around this by using visibility: collapse instead, but I would like to know why display: none causes this problem.

The console starts perpetually filling up with warnings:

```<code>luma: Device pixel ratio clamped context.js:202:84
Error: WebGL warning: clear: Requested size 21535x8218 was too large, but resize to 10767x4109 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawElements: Drawing to a destination rect smaller than the viewport rect. (This warning will only be given once) bundle.min.js line 15214 > eval:32:191695
Error: WebGL warning: drawingBufferWidth: Requested size 21535x8218 was too large, but resize to 10767x4109 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 20020x7637 was too large, but resize to 10010x3818 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 20020x7637 was too large, but resize to 10010x3818 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 18609x7099 was too large, but resize to 9304x3549 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 18609x7099 was too large, but resize to 9304x3549 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 17297x6598 was too large, but resize to 8648x3299 succeeded. bundle.min.js line 15214 > eval:32:60490
Source map error: Error: NetworkError when attempting to fetch resource.
Resource URL: webpack:///./node_modules/@luma.gl/webgl/dist/esm/context/context.js?
Source Map URL: context.js.map
Error: WebGL warning: drawingBufferWidth: Requested size 17297x6598 was too large, but resize to 8648x3299 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 21925x8361 was too large, but resize to 10962x4180 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 21925x8361 was too large, but resize to 10962x4180 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 20379x7772 was too large, but resize to 10189x3886 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 20379x7772 was too large, but resize to 10189x3886 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 18943x7225 was too large, but resize to 9471x3612 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 18943x7225 was too large, but resize to 9471x3612 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 17607x6715 was too large, but resize to 8803x3357 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 17607x6715 was too large, but resize to 8803x3357 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 22314x8510 was too large, but resize to 11157x4255 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 22314x8510 was too large, but resize to 11157x4255 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 20743x7911 was too large, but resize to 10371x3955 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 20743x7911 was too large, but resize to 10371x3955 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 19280x7354 was too large, but resize to 9640x3677 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 19280x7354 was too large, but resize to 9640x3677 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 17925x6834 was too large, but resize to 8962x3417 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 17925x6834 was too large, but resize to 8962x3417 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 16662x6351 was too large, but resize to 8331x3175 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 16662x6351 was too large, but resize to 8331x3175 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 21115x8049 was too large, but resize to 10557x4024 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 21115x8049 was too large, but resize to 10557x4024 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 19626x7482 was too large, but resize to 9813x3741 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 19626x7482 was too large, but resize to 9813x3741 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 18246x6954 was too large, but resize to 9123x3477 succeeded. bundle.min.js line 15214 > eval:32:60490
</code>```

I took a look at performance with the React profiler:
React Profiler output

In every commit that takes longer to process than normal, it shows AutoSizer taking a long time to render.

Reproducing the problem:

Node version: v10.16.3

Run create-react-app my-app.

Copy code below.

Apply display: none on any element containing the map, including the elements rendered by Deck.gl.

WARNING: Reproducing this issue takes up a lot of resources and might crash your computer!

The code

index.tsx

```<code>import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import 'mapbox-gl/dist/mapbox-gl.css';
import {GeoMapChart} from './GeoMapChart'

ReactDOM.render(<GeoMapChart />, document.getElementById('root'));

serviceWorker.unregister();
</code>```

GeoMapChart.tsx

```<code>import * as React from 'react';
import DeckGL from '@deck.gl/react';
import {StaticMap} from 'react-map-gl';

export function GeoMapChart() {

    const [viewState, setViewState] = React.useState(INITIAL_VIEW_STATE);

    return (
            <DeckGL viewState={viewState} controller={true} width={'100%'} height={'100%'} layers={[]}  onViewStateChange={
                ({viewState, oldViewState, interactionState}) => {
                    const newViewState = {...viewState};
                    setViewState(newViewState);
                }}>

                <StaticMap width={'100%'} height={'100%'} mapStyle={MAPBOX_BASE_LAYER}/>
            </DeckGL>
    )
}

const MAX_ZOOM = 19;
const MIN_ZOOM = 2;
const INITIAL_VIEW_STATE = {
    latitude: 37.77,
    longitude: -122.42,
    zoom: 5,
    bearing: 0,
    pitch: 0,
    maxZoom: MAX_ZOOM,
    minZoom: MIN_ZOOM
};

const BASEMAP_TILE_SOURCE_NAME = 'simple-tiles';
const BASEMAP_TILE_SERVERS = [
    'http://a.tile.osm.org/{z}/{x}/{y}.png',
    'http://b.tile.osm.org/{z}/{x}/{y}.png',
    'http://c.tile.osm.org/{z}/{x}/{y}.png',
    //'//stamen-tiles-a.a.ssl.fastly.net/terrain/{z}/{x}/{y}.jpg',
    //'//stamen-tiles-b.a.ssl.fastly.net/terrain/{z}/{x}/{y}.jpg',
    //'//stamen-tiles-c.a.ssl.fastly.net/terrain/{z}/{x}/{y}.jpg',
];
const BASEMAP_ATTRIBUTION = `Map tiles by <a href="http://stamen.com">Stamen Design</a>, under
<a href="http://creativecommons.org/licenses/by/3.0"> CC BY 3.0</a>. Data by
<a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">
ODbL</a>.`.replace(/\n/gm, '');
const COMMON_LAYER_CONFIG = {
    minZoom: 2,
    maxZoom: 17, // New data will be requested until this level
    pixelScaleFactor: 8,
    tileSize: 256,
    isTms: true,
    topoLayerClusteringSwithLevel: 13,
    maxVisibleRasterLayers: 3,
    maxConfigurableLayers: 26,
};
const MAP_CONFIG = {
    MIN_ZOOM: 1,
    MAX_ZOOM: 18,
    INITIAL_ZOOM: 9,
    SHOW_TILE_BOUNDARIES: false,
    DRAG_ROTATE: false,
    ZOOM_NO_DATA: 2,
    SEARCH_DEFAULT_ZOOM: 14,
};

const MAPBOX_BASE_LAYER = {
    version: 8,
    sources: {
        [BASEMAP_TILE_SOURCE_NAME]: {
            type: 'raster',
            tiles: BASEMAP_TILE_SERVERS,
            tileSize: COMMON_LAYER_CONFIG.tileSize,
            attribution: BASEMAP_ATTRIBUTION,
        }
    },
    layers: [
        {
            id: BASEMAP_TILE_SOURCE_NAME,
            type: 'raster',
            source: BASEMAP_TILE_SOURCE_NAME,
            minzoom: MAP_CONFIG.MIN_ZOOM,
            maxzoom: MAP_CONFIG.MAX_ZOOM,
        }
    ],
};
</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />

  <title>Deck.gl performance issue</title>
</head>

<body>
  <div id="root"></div>

</body>

</html>
</code>```

package.json

```<code>{
    "name": "NOT_PUBLIC",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        "@types/lodash": "^4.14.149",
        "@types/node": "13.1.8",
        "@types/react": "16.8.3",
        "@types/react-dom": "16.0.11",
        "@types/react-router-dom": "5.1.3",
        "axios": "0.19.0",
        "deck.gl": "7.3.7",
        "jss": "10.0.0-alpha.3",
        "lodash": "4.17.15",
        "react": "16.8.5",
        "react-dom": "16.8.5",
        "react-map-gl": "5.1.3",
        "react-router-dom": "5.1.2"
    },
    "scripts": {
        "start": "webpack-dev-server --mode development --hot",
        "build": "webpack --mode production",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
    },
    "eslintConfig": {
        "extends": "react-app"
    },
    "browserslist": [
        ">0.2%",
        "not dead",
        "not ie <= 11",
        "not op_mini all"
    ],
    "devDependencies": {
        "@danmarshall/deckgl-typings": "^3.4.3",
        "@types/react-map-gl": "^5.0.3",
        "@types/uuid": "^3.4.6",
        "awesome-typescript-loader": "^5.2.1",
        "babel-jest": "^23.6.0",
        "css-loader": "^2.1.0",
        "enzyme": "^3.8.0",
        "enzyme-adapter-react-16": "^1.7.1",
        "enzyme-to-json": "^3.3.5",
        "html-loader": "^0.5.5",
        "html-webpack-plugin": "^3.2.0",
        "jest": "^23.6.0",
        "node-sass": "^4.11.0",
        "react-scripts": "2.1.2",
        "react-test-renderer": "^16.7.0",
        "sass-loader": "^7.1.0",
        "source-map-loader": "^0.2.4",
        "style-loader": "^0.23.1",
        "typescript": "3.7.4",
        "webpack": "^4.28.1",
        "webpack-cli": "^3.2.1",
        "webpack-dev-server": "^3.1.14"
    },
    "jest": {
        "snapshotSerializers": [
            "enzyme-to-json/serializer"
        ]
    }
}
</code>```

webpack.config.js

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

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.tsx',
  devServer: {
    port: 9012,
    historyApiFallback: true,
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js']
  },
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.min.js'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader'
      },
      {
        test:/\.css$/,
        use:['style-loader','css-loader', 'sass-loader']
      },
      {
        test: /\.scss$/,
        use:["css-loader",'sass-loader']
      },
      {
        test: /\.(?:png|jpg|svg)$/,
        loader: 'url-loader'

    },
    {
      test: /\.(ico|jpeg|gif|eot|otf|webp|ttf|woff|woff2)(\?.*)?$/,
      loader: 'file-loader'

  },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: '!!html-loader!./src/index.html'
    }),

  ]
}
</code>```

tsconfig.json

```<code>{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es6",
        "jsx": "react",
        // "suppressImplicitAnyIndexErrors": true,
    },
    "include": [
        "./src/**/*"
    ]
}
</code>```

答:
I will try to clear the confusion here. Maybe it answers your questions.

You have tried to set the div hidden using display: none and it uses a lot much more memory than it used while display: block or setting the style to visibility: collapse. I think this as the problem statement.

Below are the options to hide an element in html:-

opacity: 0

visibility: hidden

visibility: collapse

display: none

Now, the actual thing these styles do html is below

opacity: 0 - hides an element, but it does occupy space in the layout, can click on the element.

visibility: hidden - hides an element, but it does occupy space in the layout, no clicks possible.

visibility: collapse - hides an element, but it does occupy space in the layout, no clicks possible. (it does not occupy space in the layout if the element is a table)

display: none - hides an element entirely, it doesn't occupy any space in the layout, no clicks possible.

From this comparison, we can understand that display: none; doesn't allow the element to occupy the space, so the attributes clientHeight and clientWidth of the div will be zero. The following are just my assumptions.

As this turned out to be, the width and height marked as "100%" might have resulted in zero. But the library set/reset this height and width to some higher number, probably based on some validations and screen height and screen width (I am not sure, but in my system, it was 8144x4072 and yours seems to be 9123x3477). Also, the library seems to be caching canvas values during the render process. So these calculations and caching might be expensive in terms of memory and CPU.

so, these might have (You can imagine storing an array of size 8144x4072) caused the memory issues, especially when the audit is going on the RAM will get filled up easily and caused the issues.

Hope this gives you some clarity.

Body:
EDIT: This issue is specific to this setup. Please use the code from here if you wish to help. Thanks!

I am using Deck.gl with react to display a map. When I try to hide the map with display: none it starts to freeze up my whole computer. I have worked around this by using visibility: collapse instead, but I would like to know why display: none causes this problem.

The console starts perpetually filling up with warnings:

luma: Device pixel ratio clamped context.js:202:84
Error: WebGL warning: clear: Requested size 21535x8218 was too large, but resize to 10767x4109 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawElements: Drawing to a destination rect smaller than the viewport rect. (This warning will only be given once) bundle.min.js line 15214 > eval:32:191695
Error: WebGL warning: drawingBufferWidth: Requested size 21535x8218 was too large, but resize to 10767x4109 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 20020x7637 was too large, but resize to 10010x3818 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 20020x7637 was too large, but resize to 10010x3818 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 18609x7099 was too large, but resize to 9304x3549 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 18609x7099 was too large, but resize to 9304x3549 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 17297x6598 was too large, but resize to 8648x3299 succeeded. bundle.min.js line 15214 > eval:32:60490
Source map error: Error: NetworkError when attempting to fetch resource.
Resource URL: webpack:///./node_modules/@luma.gl/webgl/dist/esm/context/context.js?
Source Map URL: context.js.map
Error: WebGL warning: drawingBufferWidth: Requested size 17297x6598 was too large, but resize to 8648x3299 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 21925x8361 was too large, but resize to 10962x4180 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 21925x8361 was too large, but resize to 10962x4180 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 20379x7772 was too large, but resize to 10189x3886 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 20379x7772 was too large, but resize to 10189x3886 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 18943x7225 was too large, but resize to 9471x3612 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 18943x7225 was too large, but resize to 9471x3612 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 17607x6715 was too large, but resize to 8803x3357 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 17607x6715 was too large, but resize to 8803x3357 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 22314x8510 was too large, but resize to 11157x4255 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 22314x8510 was too large, but resize to 11157x4255 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 20743x7911 was too large, but resize to 10371x3955 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 20743x7911 was too large, but resize to 10371x3955 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 19280x7354 was too large, but resize to 9640x3677 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 19280x7354 was too large, but resize to 9640x3677 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 17925x6834 was too large, but resize to 8962x3417 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 17925x6834 was too large, but resize to 8962x3417 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 16662x6351 was too large, but resize to 8331x3175 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 16662x6351 was too large, but resize to 8331x3175 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 21115x8049 was too large, but resize to 10557x4024 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 21115x8049 was too large, but resize to 10557x4024 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 19626x7482 was too large, but resize to 9813x3741 succeeded. bundle.min.js line 15214 > eval:32:60490
Error: WebGL warning: drawingBufferWidth: Requested size 19626x7482 was too large, but resize to 9813x3741 succeeded. bundle.min.js line 7141 > eval:201:9
Error: WebGL warning: clear: Requested size 18246x6954 was too large, but resize to 9123x3477 succeeded. bundle.min.js line 15214 > eval:32:60490

I took a look at performance with the React profiler:
React Profiler output

In every commit that takes longer to process than normal, it shows AutoSizer taking a long time to render.

Reproducing the problem:

Node version: v10.16.3

Run create-react-app my-app.

Copy code below.

Apply display: none on any element containing the map, including the elements rendered by Deck.gl.

WARNING: Reproducing this issue takes up a lot of resources and might crash your computer!

The code

index.tsx

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import 'mapbox-gl/dist/mapbox-gl.css';
import {GeoMapChart} from './GeoMapChart'

ReactDOM.render(<GeoMapChart />, document.getElementById('root'));

serviceWorker.unregister();

GeoMapChart.tsx

import * as React from 'react';
import DeckGL from '@deck.gl/react';
import {StaticMap} from 'react-map-gl';

export function GeoMapChart() {

    const [viewState, setViewState] = React.useState(INITIAL_VIEW_STATE);

    return (
            <DeckGL viewState={viewState} controller={true} width={'100%'} height={'100%'} layers={[]}  onViewStateChange={
                ({viewState, oldViewState, interactionState}) => {
                    const newViewState = {...viewState};
                    setViewState(newViewState);
                }}>

                <StaticMap width={'100%'} height={'100%'} mapStyle={MAPBOX_BASE_LAYER}/>
            </DeckGL>
    )
}

const MAX_ZOOM = 19;
const MIN_ZOOM = 2;
const INITIAL_VIEW_STATE = {
    latitude: 37.77,
    longitude: -122.42,
    zoom: 5,
    bearing: 0,
    pitch: 0,
    maxZoom: MAX_ZOOM,
    minZoom: MIN_ZOOM
};

const BASEMAP_TILE_SOURCE_NAME = 'simple-tiles';
const BASEMAP_TILE_SERVERS = [
    'http://a.tile.osm.org/{z}/{x}/{y}.png',
    'http://b.tile.osm.org/{z}/{x}/{y}.png',
    'http://c.tile.osm.org/{z}/{x}/{y}.png',
    //'//stamen-tiles-a.a.ssl.fastly.net/terrain/{z}/{x}/{y}.jpg',
    //'//stamen-tiles-b.a.ssl.fastly.net/terrain/{z}/{x}/{y}.jpg',
    //'//stamen-tiles-c.a.ssl.fastly.net/terrain/{z}/{x}/{y}.jpg',
];
const BASEMAP_ATTRIBUTION = `Map tiles by Stamen Design, under
 CC BY 3.0. Data by
OpenStreetMap, under
ODbL.`.replace(/\n/gm, '');
const COMMON_LAYER_CONFIG = {
    minZoom: 2,
    maxZoom: 17, // New data will be requested until this level
    pixelScaleFactor: 8,
    tileSize: 256,
    isTms: true,
    topoLayerClusteringSwithLevel: 13,
    maxVisibleRasterLayers: 3,
    maxConfigurableLayers: 26,
};
const MAP_CONFIG = {
    MIN_ZOOM: 1,
    MAX_ZOOM: 18,
    INITIAL_ZOOM: 9,
    SHOW_TILE_BOUNDARIES: false,
    DRAG_ROTATE: false,
    ZOOM_NO_DATA: 2,
    SEARCH_DEFAULT_ZOOM: 14,
};

const MAPBOX_BASE_LAYER = {
    version: 8,
    sources: {
        [BASEMAP_TILE_SOURCE_NAME]: {
            type: 'raster',
            tiles: BASEMAP_TILE_SERVERS,
            tileSize: COMMON_LAYER_CONFIG.tileSize,
            attribution: BASEMAP_ATTRIBUTION,
        }
    },
    layers: [
        {
            id: BASEMAP_TILE_SOURCE_NAME,
            type: 'raster',
            source: BASEMAP_TILE_SOURCE_NAME,
            minzoom: MAP_CONFIG.MIN_ZOOM,
            maxzoom: MAP_CONFIG.MAX_ZOOM,
        }
    ],
};

index.html

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />

  <title>Deck.gl performance issue</title>

package.json

{
    "name": "NOT_PUBLIC",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        "@types/lodash": "^4.14.149",
        "@types/node": "13.1.8",
        "@types/react": "16.8.3",
        "@types/react-dom": "16.0.11",
        "@types/react-router-dom": "5.1.3",
        "axios": "0.19.0",
        "deck.gl": "7.3.7",
        "jss": "10.0.0-alpha.3",
        "lodash": "4.17.15",
        "react": "16.8.5",
        "react-dom": "16.8.5",
        "react-map-gl": "5.1.3",
        "react-router-dom": "5.1.2"
    },
    "scripts": {
        "start": "webpack-dev-server --mode development --hot",
        "build": "webpack --mode production",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
    },
    "eslintConfig": {
        "extends": "react-app"
    },
    "browserslist": [
        ">0.2%",
        "not dead",
        "not ie <= 11",
        "not op_mini all"
    ],
    "devDependencies": {
        "@danmarshall/deckgl-typings": "^3.4.3",
        "@types/react-map-gl": "^5.0.3",
        "@types/uuid": "^3.4.6",
        "awesome-typescript-loader": "^5.2.1",
        "babel-jest": "^23.6.0",
        "css-loader": "^2.1.0",
        "enzyme": "^3.8.0",
        "enzyme-adapter-react-16": "^1.7.1",
        "enzyme-to-json": "^3.3.5",
        "html-loader": "^0.5.5",
        "html-webpack-plugin": "^3.2.0",
        "jest": "^23.6.0",
        "node-sass": "^4.11.0",
        "react-scripts": "2.1.2",
        "react-test-renderer": "^16.7.0",
        "sass-loader": "^7.1.0",
        "source-map-loader": "^0.2.4",
        "style-loader": "^0.23.1",
        "typescript": "3.7.4",
        "webpack": "^4.28.1",
        "webpack-cli": "^3.2.1",
        "webpack-dev-server": "^3.1.14"
    },
    "jest": {
        "snapshotSerializers": [
            "enzyme-to-json/serializer"
        ]
    }
}

webpack.config.js

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.tsx',
  devServer: {
    port: 9012,
    historyApiFallback: true,
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js']
  },
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.min.js'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader'
      },
      {
        test:/\.css$/,
        use:['style-loader','css-loader', 'sass-loader']
      },
      {
        test: /\.scss$/,
        use:["css-loader",'sass-loader']
      },
      {
        test: /\.(?:png|jpg|svg)$/,
        loader: 'url-loader'

    },
    {
      test: /\.(ico|jpeg|gif|eot|otf|webp|ttf|woff|woff2)(\?.*)?$/,
      loader: 'file-loader'

  },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: '!!html-loader!./src/index.html'
    }),

  ]
}

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es6",
        "jsx": "react",
        // "suppressImplicitAnyIndexErrors": true,
    },
    "include": [
        "./src/**/*"
    ]
}


问:
Plot a function with an integer variable in Wolfram Alpha
I'd like to plot the following function in Wolfram Alpha (n is a positive integer variable):

```<code>f = n * (2^(-n) - 1)
</code>```

In Matlab the corresponding function is stem

How can I specify that n is a positive integer variable?

Thank you for your time.

答:
You can append a plot keyword at the beginning of your function. So, in your case, it would be something like this

```<code>plot f = n * (2^(-n) - 1) with n > 0
</code>```

which will give the following result

Body:
I'd like to plot the following function in Wolfram Alpha (n is a positive integer variable):

f = n * (2^(-n) - 1)

In Matlab the corresponding function is stem

How can I specify that n is a positive integer variable?

Thank you for your time.

Body:
You can append a plot keyword at the beginning of your function. So, in your case, it would be something like this

plot f = n * (2^(-n) - 1) with n > 0

which will give the following result


问:
How do I create a pipeline of functions so that functions run one after another?
I want to create classes where each class is associated with some function. I want to stack these functions in series such that one function runs after another in a user defined order. I am new to C++ so correct me wherever my syntax is wrong.

```<code>#include<iostream>
using namespace std;
class Function
{
public:
    virtual void setSuccessor(Function *) = 0;
    virtual void Start(int value) = 0;
};

class Prime:public Function
{
public:
    Prime()
    {
        successor=NULL;
    }
    Function *successor;
    void setSuccessor(Function *f)
    {
//if a successor is not declared then assign successor.
//else if a successor is already defined then set the new function as the successor of the successor.
        if (successor == NULL)
            successor = f;
        else
            successor->setSuccessor(f);
    }

    void Start(int value)
    {
        //prime function
        cout<<"I am Prime Function\n";
        //if successor !=null
        //  call successor
        if(successor!=NULL)
            successor->Start(value);
    }

};
class Even:public Function
{
public:
    Even()
    {
        successor=NULL;
    }
    Function *successor;
    void setSuccessor(Function *f)
    {
        if (successor == NULL)
            successor = f;
        else
            successor->setSuccessor(f);
    }

    void Start(int value)
    {
        //prime function
        cout<<"I am Even Function\n";
        //if successor !=null
        //  call successor
        if(successor!=NULL)
            successor->Start(value);
    }

};

class Pipeline
{
    public:
    Function *function;
    void addToPipe(Function* function)
    {
        if(this->function==NULL)
            this->function=function;
        else
            function->setSuccessor(function);
    }
    void start(int value)
    {
        function->Start(value);
    }
};
int main()
{
    Pipeline pipe;
    pipe.addToPipe(new Prime());
    pipe.addToPipe(new Even());
    pipe.start(5);
}
</code>```

In this program I have stacked Prime first then Even. I want that my function prime starts then Even starts. Since no other function is added so it should stop after Even. This program has runtime errors. Please help me detect them

答:
Found two flaws in your program (could be reasoned to be simple typos):

Pipeline::function is never initialized, so it has some garbage value, which causes undefined behaviour when dereferencing it (for example a crash). Simply initialize it to NULL or preferably nullptr like you do in the other two classes.

In Pipeline::addToPipe you forgot a this:

```<code>void addToPipe(Function* function)
{
    if(this->function==NULL)
        this->function=function;
    else
        function->setSuccessor(function); // Calls setSuccessor on the local variable!!
}
</code>```

With those two fixed I received the (expected) output

```<code>I am Prime Function
I am Even Function
</code>```

Body:
I want to create classes where each class is associated with some function. I want to stack these functions in series such that one function runs after another in a user defined order. I am new to C++ so correct me wherever my syntax is wrong.

#include<iostream>
using namespace std;
class Function
{
public:
    virtual void setSuccessor(Function *) = 0;
    virtual void Start(int value) = 0;
};

class Prime:public Function
{
public:
    Prime()
    {
        successor=NULL;
    }
    Function *successor;
    void setSuccessor(Function *f)
    {
//if a successor is not declared then assign successor.
//else if a successor is already defined then set the new function as the successor of the successor.
        if (successor == NULL)
            successor = f;
        else
            successor->setSuccessor(f);
    }

    void Start(int value)
    {
        //prime function
        cout<<"I am Prime Function\n";
        //if successor !=null
        //  call successor
        if(successor!=NULL)
            successor->Start(value);
    }

};
class Even:public Function
{
public:
    Even()
    {
        successor=NULL;
    }
    Function *successor;
    void setSuccessor(Function *f)
    {
        if (successor == NULL)
            successor = f;
        else
            successor->setSuccessor(f);
    }

    void Start(int value)
    {
        //prime function
        cout<<"I am Even Function\n";
        //if successor !=null
        //  call successor
        if(successor!=NULL)
            successor->Start(value);
    }

};

class Pipeline
{
    public:
    Function *function;
    void addToPipe(Function* function)
    {
        if(this->function==NULL)
            this->function=function;
        else
            function->setSuccessor(function);
    }
    void start(int value)
    {
        function->Start(value);
    }
};
int main()
{
    Pipeline pipe;
    pipe.addToPipe(new Prime());
    pipe.addToPipe(new Even());
    pipe.start(5);
}

In this program I have stacked Prime first then Even. I want that my function prime starts then Even starts. Since no other function is added so it should stop after Even. This program has runtime errors. Please help me detect them

Body:
Found two flaws in your program (could be reasoned to be simple typos):

Pipeline::function is never initialized, so it has some garbage value, which causes undefined behaviour when dereferencing it (for example a crash). Simply initialize it to NULL or preferably nullptr like you do in the other two classes.

In Pipeline::addToPipe you forgot a this:

void addToPipe(Function* function)
{
    if(this->function==NULL)
        this->function=function;
    else
        function->setSuccessor(function); // Calls setSuccessor on the local variable!!
}

With those two fixed I received the (expected) output

I am Prime Function
I am Even Function


问:
Global API call Vue.js
I'm having trouble creating a global variable that contains API.
I need to use this variable throughout my app, so it will be easier to change API link when the time comes.
How can I do that?
So far I've done the following:

Created a file called config.js

```<code>const baseURL = 'http://myapi'

export default {
    baseURL
}
</code>```

I'm using Vuex to make api calls so the part where I try to receive data looks like this in my store:

```<code>import baseURL from '../../../config.js'

    async fetchStaff({ commit }, id, baseURL) {
    if (id === undefined) {
        const response = await axios.get(baseURL + `/employee/staff`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
        // eslint-disable-next-line no-console
        console.log(response.data)
    } else {
        const response = await axios.get(baseURL + `/employee/${id}`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
    }
},
</code>```

baseURL is undefind in store.
Can someone point out the mistake here, please?

答:
config.js

```<code>// Bases
export const baseURL = 'http://myapi'

// Endpoints
export const api_1 = '/api1'
export const api_2 = param1 => `/api2/ + ${param1}`
</code>```

store.js

```<code>// import apis you want to use this file.
import { baseURL, api_1 } from '../../../config.js'
</code>```

Title: Global API call Vue.js

Body:
I'm having trouble creating a global variable that contains API.
I need to use this variable throughout my app, so it will be easier to change API link when the time comes.
How can I do that?
So far I've done the following:

Created a file called config.js

const baseURL = 'http://myapi'

export default {
    baseURL
}

I'm using Vuex to make api calls so the part where I try to receive data looks like this in my store:

import baseURL from '../../../config.js'

    async fetchStaff({ commit }, id, baseURL) {
    if (id === undefined) {
        const response = await axios.get(baseURL + `/employee/staff`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
        // eslint-disable-next-line no-console
        console.log(response.data)
    } else {
        const response = await axios.get(baseURL + `/employee/${id}`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
    }
},

baseURL is undefind in store.
Can someone point out the mistake here, please?

Body:
config.js

// Bases
export const baseURL = 'http://myapi'

// Endpoints
export const api_1 = '/api1'
export const api_2 = param1 => `/api2/ + ${param1}`

store.js

// import apis you want to use this file.
import { baseURL, api_1 } from '../../../config.js'


问:
Play framework 2.0 Form.bindFromRequest().get() returns empty model
I need to receive same POST data from a socket communication.

This is the code that send the POST and receive the response, and seems to work correctly:

```<code>String data = "t=" + URLEncoder.encode("Title", "UTF-8") +
    "&u=" + URLEncoder.encode("http://www.myurl.com", "UTF-8");

URL url = new URL("http://localhost:9000/adserver");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output = "Data received\r\n", line;
while ((line = rd.readLine()) != null) {
    output += line;
}
wr.close();
rd.close();

return ok(output);
</code>```

This is the code that receive the POST:

```<code>Form<AdRequest> form = form(AdRequest.class).bindFromRequest();

if(form.hasErrors()) {
    return badRequest("error");
} else {
    AdRequest adr = form.get();
    return ok(adr.t + " - " + adr.u);
}
</code>```

The AdRequest model is defined in this way:

```<code>public class AdRequest {
    public String t;
    public String u;
}
</code>```

The form object receive the data because I can see them in debug, but the adr object returned by the get() method contains only null values:

```<code>adr = {
    t: null,
    u: null
}
</code>```

Instead, if I use this code to read the data it works correctly:

```<code>Map<String, String[]> asFormUrlEncoded = request().body().asFormUrlEncoded();
return ok(asFormUrlEncoded.get("t")[0] + " - " + asFormUrlEncoded.get("u")[0]);
</code>```

What I'm doing wrong?
Is it a Play Framework bug?

Thanks.

答:
This question is very old, but I'll describe our issue, just in case anyone is in the same situation.

Short answer

Try adding setters AdRequest.

Long answer

I've found that now the form model classes need setters or Play won't fill them. I don't know why. For some colleages, the code works like before, and for me, Play wants setters. No idea.

Debugging Form.bindFromRequest, it eventually reaches this line:

```<code>package org.springframework.beans;

class BeanWrapperImpl {
    ...
    private void setPropertyValue(BeanWrapperImpl.PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
        ...
        throw new NotWritablePropertyException(this.getRootClass(), this.nestedPath + propertyName, matches.buildErrorMessage(), matches.getPossibleMatches());
</code>```

And matches.buildErrorMessage() builds a message like this:

```<code>Bean property email is not writable or has an invalid setter method
</code>```

After adding the setters (e.g. setEmail) it works.

Update:

We've found that the form binding depends on the spring framework version. We were using 4.0.3-RELEASE and then we updated to 4.0.5-RELEASE, and that's when the Play forms started to fail.

Body:
I need to receive same POST data from a socket communication.

This is the code that send the POST and receive the response, and seems to work correctly:

String data = "t=" + URLEncoder.encode("Title", "UTF-8") +
    "&u=" + URLEncoder.encode("http://www.myurl.com", "UTF-8");

URL url = new URL("http://localhost:9000/adserver");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output = "Data received\r\n", line;
while ((line = rd.readLine()) != null) {
    output += line;
}
wr.close();
rd.close();

return ok(output);

This is the code that receive the POST:

Form<AdRequest> form = form(AdRequest.class).bindFromRequest();

if(form.hasErrors()) {
    return badRequest("error");
} else {
    AdRequest adr = form.get();
    return ok(adr.t + " - " + adr.u);
}

The AdRequest model is defined in this way:

public class AdRequest {
    public String t;
    public String u;
}

The form object receive the data because I can see them in debug, but the adr object returned by the get() method contains only null values:

adr = {
    t: null,
    u: null
}

Instead, if I use this code to read the data it works correctly:

Map<String, String[]> asFormUrlEncoded = request().body().asFormUrlEncoded();
return ok(asFormUrlEncoded.get("t")[0] + " - " + asFormUrlEncoded.get("u")[0]);

What I'm doing wrong?
Is it a Play Framework bug?

Thanks.

Body:
This question is very old, but I'll describe our issue, just in case anyone is in the same situation.

Short answer

Try adding setters AdRequest.

Long answer

I've found that now the form model classes need setters or Play won't fill them. I don't know why. For some colleages, the code works like before, and for me, Play wants setters. No idea.

Debugging Form.bindFromRequest, it eventually reaches this line:

package org.springframework.beans;

class BeanWrapperImpl {
    ...
    private void setPropertyValue(BeanWrapperImpl.PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
        ...
        throw new NotWritablePropertyException(this.getRootClass(), this.nestedPath + propertyName, matches.buildErrorMessage(), matches.getPossibleMatches());

And matches.buildErrorMessage() builds a message like this:

Bean property email is not writable or has an invalid setter method

After adding the setters (e.g. setEmail) it works.

Update:

We've found that the form binding depends on the spring framework version. We were using 4.0.3-RELEASE and then we updated to 4.0.5-RELEASE, and that's when the Play forms started to fail.


问:
Computed column through scalar function error
This question is in relation to user-defined scalar function to generate computed column

```<code>ALTER TABLE dbo.Installment
ADD SurchargeCalculated AS
   (select Amount * Days * InstSurchargePercentage / 365 / 100
    from InstallMentPlan
    where InstallMentPlan.PlanKey = Installment.PlanKey
   )
GO
</code>```

Error is:

Msg 1046, Level 15, State 1, Line 3

  Subqueries are not allowed in this context. Only scalar expressions are allowed.

答:
You can't do this with a computed column: it may reference solely columns from the same table and same row.

As a workaround, you could define a view:

```<code>create view dbo.InstallmentView as
select
    i.*,
    (
        select p.Amount * p.Days * p.InstSurchargePercentage / 365 / 100
        from dbo.InstallMentPlan p
        where p.PlanKey = i.PlanKey
    ) SurchargeCalculated
from  dbo.Installment i
</code>```

This can also be expressed with a join:

```<code>create view dbo.InstallmentView as
select
    i.*,
    p.Amount * p.Days * p.InstSurchargePercentage / 365 / 100 SurchargeCalculated
from  dbo.Installment i
left join dbo.InstallMentPlan p on p.PlanKey = i.PlanKey
</code>```

Note that you should enumerate the columns that you want to select form dbo.Installment instead of using * (I did so only because I have no knowledge of your database structure).

Body:
This question is in relation to user-defined scalar function to generate computed column

ALTER TABLE dbo.Installment
ADD SurchargeCalculated AS
   (select Amount * Days * InstSurchargePercentage / 365 / 100
    from InstallMentPlan
    where InstallMentPlan.PlanKey = Installment.PlanKey
   )
GO

Error is:

Msg 1046, Level 15, State 1, Line 3

  Subqueries are not allowed in this context. Only scalar expressions are allowed.

Body:
You can't do this with a computed column: it may reference solely columns from the same table and same row.

As a workaround, you could define a view:

create view dbo.InstallmentView as
select
    i.*,
    (
        select p.Amount * p.Days * p.InstSurchargePercentage / 365 / 100
        from dbo.InstallMentPlan p
        where p.PlanKey = i.PlanKey
    ) SurchargeCalculated
from  dbo.Installment i

This can also be expressed with a join:

create view dbo.InstallmentView as
select
    i.*,
    p.Amount * p.Days * p.InstSurchargePercentage / 365 / 100 SurchargeCalculated
from  dbo.Installment i
left join dbo.InstallMentPlan p on p.PlanKey = i.PlanKey

Note that you should enumerate the columns that you want to select form dbo.Installment instead of using * (I did so only because I have no knowledge of your database structure).


问:
DAX calculating running sum of column
I have already tried the various solutions found on the web (which are usually all the same), but nothing works.

As suggested in https://community.powerbi.com/t5/Desktop/Issue-with-Running-Total/td-p/310720

I tried using the dates column as a reference

Then I created an index column in Power Query and use this as a reference

As you can see it simply doesn't work:

instead of getting a running sum, starting from the first value (€ 37 800.68), I simply get a global  sum.

I have also tried creating a Quick New Measure selecting the Running Total option (see the full function automatically generated by Power BI) and then displaying the result with a chart in the report window, but again the result doesn't make sense (I simply get a copy of the field I want to sum...)

UPDATE

I implemented the suggestion by @sigdoug but I get the following

This is simply adding to each element in the column Amount the following value, forgetting the previous one.

What I mean by running sum is update the sum of the previous calculation.

I should get the following values:

37 800.68

35,845.11

35,348.57

35,347.57

...

Can someone help me in getting this right? Thank you

答:
Sorry andrea, I should have actually done a bigger test of this (and read the question properly). The following will solve your problem, add this as a calculated column:

```<code>SUMX(FILTER('Table','Table'[Column1<=EARLIER
('Table'[Column1])),'Table'[Column2])
</code>```

column1 being your index and column2 being the value you want added each time.

Title: DAX calculating running sum of column

Body:
Sorry andrea, I should have actually done a bigger test of this (and read the question properly). The following will solve your problem, add this as a calculated column:

SUMX(FILTER('Table','Table'[Column1<=EARLIER
('Table'[Column1])),'Table'[Column2])

column1 being your index and column2 being the value you want added each time.


问:
How to replace all strings in a column in R?
I have a column of data where I am trying to remove all characters which aren't numbers
The data looks like:

```<code>Col1
Name=12_Represse, Name=12_Represse, Name=12_Represse, Name=13_Heterochrom/l, Name=13_Heterochrom/lo
Name=13_Heterochrom/lo
Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx
</code>```

The output I expect is:

```<code>Col1
12,12,12,13,13
13
11,11,11,11,11,11
</code>```

I've tried to adapt from other questions which look to remove specific strings.
For example trying:

test <- str_replace_all(data$col1,"#[a-z,A-Z]*","")

However this, or similar adaptations where I have tried gsub, does not seem to work. I am new to R so any guidance would help.

答:
Here are two ways of keeping just the digits.

1. Base R.

```<code>gsub("[^[:digit:],]", "", data$col1)
#[1] "12,12,12,13,13"    "13"                "11,11,11,11,11,11"
</code>```

2. Package stringr.

```<code>stringr::str_remove_all(data$col1, "[^[:digit:],]")
#[1] "12,12,12,13,13"    "13"                "11,11,11,11,11,11"
</code>```

Data.

```<code>col1 <- c('Name = "12_Represse", Name="12_Represse", Name="12_Represse", Name="13_Heterochrom/l", Name="13_Heterochrom/lo"',
          'Name="13_Heterochrom/lo"',
          'Name="11_Weak_Tx", Name="11_Weak_Tx", Name="11_Weak_Tx", Name="11_Weak_Tx", Name="11_Weak_Tx", Name="11_Weak_Tx"')
data <- data.frame(col1)
</code>```

Body:
I have a column of data where I am trying to remove all characters which aren't numbers
The data looks like:

Col1
Name=12_Represse, Name=12_Represse, Name=12_Represse, Name=13_Heterochrom/l, Name=13_Heterochrom/lo
Name=13_Heterochrom/lo
Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx

The output I expect is:

Col1
12,12,12,13,13
13
11,11,11,11,11,11

I've tried to adapt from other questions which look to remove specific strings.
For example trying:

test <- str_replace_all(data$col1,"#[a-z,A-Z]*","")

However this, or similar adaptations where I have tried gsub, does not seem to work. I am new to R so any guidance would help.

Body:
Here are two ways of keeping just the digits.

1. Base R.

gsub("[^[:digit:],]", "", data$col1)
#[1] "12,12,12,13,13"    "13"                "11,11,11,11,11,11"

2. Package stringr.

stringr::str_remove_all(data$col1, "[^[:digit:],]")
#[1] "12,12,12,13,13"    "13"                "11,11,11,11,11,11"

Data.

col1 <- c('Name = "12_Represse", Name="12_Represse", Name="12_Represse", Name="13_Heterochrom/l", Name="13_Heterochrom/lo"',
          'Name="13_Heterochrom/lo"',
          'Name="11_Weak_Tx", Name="11_Weak_Tx", Name="11_Weak_Tx", Name="11_Weak_Tx", Name="11_Weak_Tx", Name="11_Weak_Tx"')
data <- data.frame(col1)


问:
How to properly refresh a token using JWT + HttpOnly Cookie?
I've successfully setup authentication in my AspNetCore API application using JWT + HttpOnly Cookies, inspired by this document and this topic.

Now I'm trying to integrate refresh token feature.
I've found this tutorial, but it is based on JWT only authentication and I'm stuck at the point where I should add a Token-Expired header to the response:

```<code>options.Events = new JwtBearerEvents
{
    OnAuthenticationFailed = context =>
    {
        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
        {
            context.Response.Headers.Add("Token-Expired", "true");
        }
        return Task.CompletedTask;
    }
};
</code>```

Because I'm using cookie based authentication, I use OnRedirectToLogin event instead of OnAuthenticationFailed event, and the context.Exception.GetType() method is not available to me.
So I don't know how to figure out that a refresh token is needed.

How can I solve this?

UPDATE 1

This is what I actually do:

```<code>options.Events.OnRedirectToLogin = context =>
{
   if (context.Request.Path.StartsWithSegments("/api"))
      context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
   else
      context.Response.Redirect(context.RedirectUri);

   return Task.FromResult(0);
};
</code>```

Here is where I want to add Token-Expired header, but based on what?

答:
Use a middleware that add your cookie to bearer header like this:</p>

```<code>        app.Use(async (context, next) =>
        {
            var token = context.Request.Cookies["access_token"];
            if (!string.IsNullOrEmpty(token)) context.Request.Headers.Add("Authorization", "Bearer " + token);
            await next();
        });
</code>```

Body:
I've successfully setup authentication in my AspNetCore API application using JWT + HttpOnly Cookies, inspired by this document and this topic.

Now I'm trying to integrate refresh token feature.
I've found this tutorial, but it is based on JWT only authentication and I'm stuck at the point where I should add a Token-Expired header to the response:

options.Events = new JwtBearerEvents
{
    OnAuthenticationFailed = context =>
    {
        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
        {
            context.Response.Headers.Add("Token-Expired", "true");
        }
        return Task.CompletedTask;
    }
};

Because I'm using cookie based authentication, I use OnRedirectToLogin event instead of OnAuthenticationFailed event, and the context.Exception.GetType() method is not available to me.
So I don't know how to figure out that a refresh token is needed.

How can I solve this?

UPDATE 1

This is what I actually do:

options.Events.OnRedirectToLogin = context =>
{
   if (context.Request.Path.StartsWithSegments("/api"))
      context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
   else
      context.Response.Redirect(context.RedirectUri);

   return Task.FromResult(0);
};

Here is where I want to add Token-Expired header, but based on what?

Body:
Use a middleware that add your cookie to bearer header like this:

        app.Use(async (context, next) =>
        {
            var token = context.Request.Cookies["access_token"];
            if (!string.IsNullOrEmpty(token)) context.Request.Headers.Add("Authorization", "Bearer " + token);
            await next();
        });


问:
type object 'datetime.datetime' has no attribute 'fromisoformat'
I have a script with the following import:

```<code>from datetime import datetime
</code>```

and a piece of code where I call:

```<code>datetime.fromisoformat(duedate)
</code>```

Sadly, when I run the script with an instance of Python 3.6, the console returns the following error:

AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'

I tried to run it from two instances of anaconda (3.7 and 3.8) and it works nice and smooth.
I supposed there was an import problem so I tried to copy datetime.py from anaconda/Lib to the script directory, with no success.

The datetime.py clearly contains the class datetime and the method fromisoformat but still it seems unlinked. I even tried to explicitly link the datetime.py file, with the same error:

```<code>parent_dir = os.path.abspath(os.path.dirname(__file__))
vendor_dir = os.path.join(parent_dir, 'libs')
sys.path.append(vendor_dir+os.path.sep+"datetime.py")
</code>```

Can you help me? My ideas are over...

答:
you should not use from datetime import datetime but import datetime, you just confusing naming of the module.
now you can use datetime.fromisoformat(duedate).

Body:
I have a script with the following import:

from datetime import datetime

and a piece of code where I call:

datetime.fromisoformat(duedate)

Sadly, when I run the script with an instance of Python 3.6, the console returns the following error:

AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'

I tried to run it from two instances of anaconda (3.7 and 3.8) and it works nice and smooth.
I supposed there was an import problem so I tried to copy datetime.py from anaconda/Lib to the script directory, with no success.

The datetime.py clearly contains the class datetime and the method fromisoformat but still it seems unlinked. I even tried to explicitly link the datetime.py file, with the same error:

parent_dir = os.path.abspath(os.path.dirname(__file__))
vendor_dir = os.path.join(parent_dir, 'libs')
sys.path.append(vendor_dir+os.path.sep+"datetime.py")

Can you help me? My ideas are over...


问:
When and how to use switchTo() method in webDriver (Selenium 2) to handle window/pop up
I am having trouble clicking or interacting with some page elements. They seem like normal DOM objects.  just buttons here is the code for one

```<code><div style="clear: both; text-align: right">
 <img id="nextstep" class="nextbtn" height="21" alt="" src="/edit/images/author/next.png">
</div>
</code>```

After clicking a button as "Upload file" another pop up window was opened. My task is to upload a file at pop up window and back to original window. I'll try to explain

I start a webDriver for

www.test.com   (<- made up name for example)

I login

click upload a file button

After this click our site redirects to www.foo.com instead of the above I am using the same driver created earlier and I try to interact with the buttons on the post upload page

button.click()

It never finds these buttons but they are there in firebug and appear normal.

答:
You may try to switch to the window again after the redirect.

Save you window handle:

```<code>String myWindowHandle = driver.getWindowHandle();
</code>```

redirect to the page you want and then call switchTo using the window handle:

```<code>driver.switchTo().window(myWindowHandle );
</code>```

Does your page contain any frames? It may also be possible that you are not in the correct frame after the redirect.

Body:
I am having trouble clicking or interacting with some page elements. They seem like normal DOM objects.  just buttons here is the code for one

After clicking a button as "Upload file" another pop up window was opened. My task is to upload a file at pop up window and back to original window. I'll try to explain

I start a webDriver for

www.test.com   (<- made up name for example)

I login

click upload a file button

After this click our site redirects to www.foo.com instead of the above I am using the same driver created earlier and I try to interact with the buttons on the post upload page

button.click()

It never finds these buttons but they are there in firebug and appear normal.

Body:
You may try to switch to the window again after the redirect.

Save you window handle:

String myWindowHandle = driver.getWindowHandle();

redirect to the page you want and then call switchTo using the window handle:

driver.switchTo().window(myWindowHandle );

Does your page contain any frames? It may also be possible that you are not in the correct frame after the redirect.