问:
Close open Desktop Taskpane using office.js or Add-in manifest function
We have created add-in manifest xml file for our application and also embed office.js file.
We have use custom ribbon feature by assigning url to icon. When we click on icon, it open task pane on desktop. We want to open third party url in new window of browser using Add-in manifest and taskpane should be close.
We have gone through AppDomains and uses Office.addin.hide function. But both solutions are not working.
Please provide us solution if exist.</p>

答:
You may try to use UI less function, in UI less function, you could execute a javascript code to open a page in the default browser.

You could refer to this answer.
Open directly a web page from a button in Ribbon in a browser outside Excel?


来源: stackexchange

问:
How to use a time interval for each iteration of a for loop?
I want to show each word of a string of text in 60 seconds intervals on screen and came up with something like this:

```<code>let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");

function showWords() {
  // Print words to the screen one at a time.

  let textArray = text.split(" ");
  for(let i = 0; i < poemArray.length; i++) {
    mainId.textContent = poemArray[i];
  }
}
</code>```

I know that I should use a setInterval() method here, I'm not just sure how I should use it. I have tried to put the whole for loop as the function part of it and even tried to put the code inside the for loop as the function part and nothing works.

答:
Basic queue with shift and setInterval()

let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");

function showWords() {
  let textArray = text.split(" ");
  function next() {
    // grab first index off array and display it
    mainId.innerText = textArray.shift()
    // if we still have items, create timeout to get next
    if (textArray.length) {
      setTimeout(next, 1000)
    }
  }
  next()
}

showWords()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to show each word of a string of text in 60 seconds intervals on screen and came up with something like this:

let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");

function showWords() {
  // Print words to the screen one at a time.

  let textArray = text.split(" ");
  for(let i = 0; i < poemArray.length; i++) {
    mainId.textContent = poemArray[i];
  }
}

I know that I should use a setInterval() method here, I'm not just sure how I should use it. I have tried to put the whole for loop as the function part of it and even tried to put the code inside the for loop as the function part and nothing works.

Body:
Basic queue with shift and setInterval()

let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");

function showWords() {
  let textArray = text.split(" ");
  function next() {
    // grab first index off array and display it
    mainId.innerText = textArray.shift()
    // if we still have items, create timeout to get next
    if (textArray.length) {
      setTimeout(next, 1000)
    }
  }
  next()
}

showWords()

<div id="main"></div>


问:
create pip-installable single-module package with associated data
There are many variations on this question I've found, but none seem to address my exact situation where

The Python code for the project is contained in a single file

There are required data directories that must be included with the installation

I am trying to create a pip-installable version of the following Python project, where the project consists of a single Python script myscript, plus two different data directories, data and test_data. data contains required data files that are sourced by myscript.py at runtime:

```<code>myscript
|
├── myscript
│   ├── data
│   ├── __init__.py
│   ├── myscript.py
│   └── test_data
├── LICENSE
├── README.md
└── setup.py
</code>```

I've seen the recommendation to use py_modules in setup.py for similar issues, but that doesn't seem to allow for inclusion of the data directories upon install with pip, and I cannot find documentation that seems to cover this specific case.

I've also seen it recommended to just have users do a git clone of the repo instead of using pip, but it seems like a usability benefit to offer a way to pip-install with all dependencies while correctly adding the script to the PATH in an OS-dependent manner.

答:
I think you're missing the MANIFEST.in file

please look at following mini-project:

Directory structure

```<code>./MANIFEST.in
./mini/data/f1.txt
./mini/__init__.py
./mini/mini.py
./mini/test_data/f1.txt
./README.md
./setup.py
</code>```

setup.py

```<code>from setuptools import setup

setup(name="mini",
      version="0.0.1",
      description="one file pip installable mod",
      long_description="long description",
      long_description_content_type="text/x-rst",
      classifiers=[
            "Development Status :: 3 - Alpha",
      ],
      keywords="sample",
      url="https://github.com/demo",
      author="me",
      author_email="me@my.email.com",
      license="MIT",
      packages=["mini"],
      scripts=[],
      entry_points={
          "console_scripts": [
            "mini = mini.mini:main",
            ]
      },
      install_requires=[],
      extras_require={},
      python_requires=">=3.4",
      setup_requires=[],
      tests_require=[],
      zip_safe=False,
      include_package_data=True,
      )
</code>```

MANIFEST.in

```<code>include README.md
recursive-include mini/data/ *
recursive-include mini/test_data/ *
</code>```

mini/mini.py

```<code>#!/usr/bin/env python

import os

MYPATH = os.path.realpath(os.path.dirname(__file__))

DATA_PATH = os.path.join(MYPATH, "data")
TEST_DATA_PATH = os.path.join(MYPATH, "test_data")

def main():
    print("I am the miniscript")
    with open(os.path.join(DATA_PATH, "f1.txt")) as fin:
        print("DATA FILE", fin.read())
    with open(os.path.join(TEST_DATA_PATH, "f1.txt")) as fin:
        print("TEST DATA FILE", fin.read())

main()
</code>```

Try out with:

```<code>python -m setup sdist
tar tvfz dist/mini-0.0.1.tar.gz
</code>```

Body:
There are many variations on this question I've found, but none seem to address my exact situation where

The Python code for the project is contained in a single file

There are required data directories that must be included with the installation

I am trying to create a pip-installable version of the following Python project, where the project consists of a single Python script myscript, plus two different data directories, data and test_data. data contains required data files that are sourced by myscript.py at runtime:

myscript
|
├── myscript
│   ├── data
│   ├── __init__.py
│   ├── myscript.py
│   └── test_data
├── LICENSE
├── README.md
└── setup.py

I've seen the recommendation to use py_modules in setup.py for similar issues, but that doesn't seem to allow for inclusion of the data directories upon install with pip, and I cannot find documentation that seems to cover this specific case.

I've also seen it recommended to just have users do a git clone of the repo instead of using pip, but it seems like a usability benefit to offer a way to pip-install with all dependencies while correctly adding the script to the PATH in an OS-dependent manner.

Body:
I think you're missing the MANIFEST.in file

please look at following mini-project:

Directory structure

./MANIFEST.in
./mini/data/f1.txt
./mini/__init__.py
./mini/mini.py
./mini/test_data/f1.txt
./README.md
./setup.py

setup.py

from setuptools import setup

setup(name="mini",
      version="0.0.1",
      description="one file pip installable mod",
      long_description="long description",
      long_description_content_type="text/x-rst",
      classifiers=[
            "Development Status :: 3 - Alpha",
      ],
      keywords="sample",
      url="https://github.com/demo",
      author="me",
      author_email="me@my.email.com",
      license="MIT",
      packages=["mini"],
      scripts=[],
      entry_points={
          "console_scripts": [
            "mini = mini.mini:main",
            ]
      },
      install_requires=[],
      extras_require={},
      python_requires=">=3.4",
      setup_requires=[],
      tests_require=[],
      zip_safe=False,
      include_package_data=True,
      )

MANIFEST.in

include README.md
recursive-include mini/data/ *
recursive-include mini/test_data/ *

mini/mini.py

#!/usr/bin/env python

import os

MYPATH = os.path.realpath(os.path.dirname(__file__))

DATA_PATH = os.path.join(MYPATH, "data")
TEST_DATA_PATH = os.path.join(MYPATH, "test_data")

def main():
    print("I am the miniscript")
    with open(os.path.join(DATA_PATH, "f1.txt")) as fin:
        print("DATA FILE", fin.read())
    with open(os.path.join(TEST_DATA_PATH, "f1.txt")) as fin:
        print("TEST DATA FILE", fin.read())

main()

Try out with:

python -m setup sdist
tar tvfz dist/mini-0.0.1.tar.gz


问:
Flutter how to get subtext aligned under title in appbar?
I have the following app bar in flutter and trying to align the subtext "Your desired business name" under the title enter. I have tried different methods but still can't get to align. It should have "enter" at the top and then the subtext aligned center

Here is my current code

```<code>Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
          preferredSize: Size.fromHeight(75.0),
          child: AppBar(
            centerTitle: true,
            title: Text('enter'),
            actions: <Widget>[
              new Container(),
              new Center(
                  child: Text(
                'Your desired business name',
                textAlign: TextAlign.center,
                style: new TextStyle(
                  fontSize: 14.0,
                  color: Colors.white,
                ),
              )),
            ],
          )),
    );
  }
</code>```

答:
```<code>appBar: AppBar(
      title: Center(
        child: Text('Flutter Tutorial'),
      ),
</code>```

Body:
I have the following app bar in flutter and trying to align the subtext "Your desired business name" under the title enter. I have tried different methods but still can't get to align. It should have "enter" at the top and then the subtext aligned center

Here is my current code

Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
          preferredSize: Size.fromHeight(75.0),
          child: AppBar(
            centerTitle: true,
            title: Text('enter'),
            actions: <Widget>[
              new Container(),
              new Center(
                  child: Text(
                'Your desired business name',
                textAlign: TextAlign.center,
                style: new TextStyle(
                  fontSize: 14.0,
                  color: Colors.white,
                ),
              )),
            ],
          )),
    );
  }


问:
Maximum network bandwidth for Azure File Share
What would be the best configuration of Azure VM and Azure File Share to get maximum network bandwidth between the two?

Can I do anything more than placing both in the same region?
Can Accelerated Networking be used in this scenario?

Thanks!

答:
Once you are going to consume your file share form an Azure VM, not from anywhere outside (internet). I would say you can consider 3 things, it is going to improve your performance and security. Just in case you should also verify if any other resources in your storage account can be affected after changing to private endpoint, please deep read all articles below about it.

1 - configure a private endpoint for your storage account where you have configure your file share, please refer to this article

2 - there is an option for networking accelarator as described into these Web Site and Microsoft Documentation

3 - some tips about size of VM, refer to article1, article2 and this test


答:
Start an interval, and set the id to a variable so you can clear it out later.

Remove the first element of the array with .shifit() and do something with it. When the array has a length of 0, clear the interval.

```<code>let intervalId = setInterval(() => {
    if (textArray.length>0) {
        console.log(textArray.shift());
    } else {
        clearInterval(intervalId);
    }
}, 60000);
</code>```

Title: How to use a time interval for each iteration of a for loop?

Body:
Start an interval, and set the id to a variable so you can clear it out later.

Remove the first element of the array with .shifit() and do something with it. When the array has a length of 0, clear the interval.

let intervalId = setInterval(() => {
    if (textArray.length>0) {
        console.log(textArray.shift());
    } else {
        clearInterval(intervalId);
    }
}, 60000);


问:
Python Capn Proto: Restorers?
Reading through the Cap'n Proto RPC docs, if you need object references to persist across multiple connections, you need to write restorers.

On the client side, it's pretty clear how to get the write object out of it (although the lack of type info makes it obnoxiously verbose).

On the server side, it's unclear how to select what kind of object you'll get out of it?

答:
The docs are super unclear on this, and I'm not even sure I got this right.

First, you need to select what shape of reference you'll use: "ez" or struct (although you could maybe use a struct type as ez? The docs don't discuss this at all.)

If you go with ez, you'll use it like so:

```<code># Client
calculator = client.ez_restore('calculator').cast_as(calculator_capnp.Calculator)

# Server
def restore(ref_id):
    if ref_id == 'calculator':
        return Calculator()
    else:
        raise Exception('Unrecognized ref passed to restore')

server = capnp.TwoPartyServer(sock, restore)
</code>```

Otherwise, your reference can be a struct, and you would use code like this:

```<code># Client
calculator = client.restore(calculator_capnp.ObjRef.new_message(id='calculator')).cast_as(calculator_capnp.Calculator)

# Server
class ObjRestorer(calculator_capnp.ObjRef.Restorer):

    def restore(self, objref):
        if objref.id == 'calculator':
            return Calculator()
        else:
            raise Exception('Unrecognized ref passed to restore')

server = capnp.TwoPartyServer(sock, ObjRestorer())
</code>```

A given RPC must have a single restorer style and type, I think. You certainly cannot use multiple struct restorers.

Title: Python Capn Proto: Restorers?

Body:
The docs are super unclear on this, and I'm not even sure I got this right.

First, you need to select what shape of reference you'll use: "ez" or struct (although you could maybe use a struct type as ez? The docs don't discuss this at all.)

If you go with ez, you'll use it like so:

# Client
calculator = client.ez_restore('calculator').cast_as(calculator_capnp.Calculator)

# Server
def restore(ref_id):
    if ref_id == 'calculator':
        return Calculator()
    else:
        raise Exception('Unrecognized ref passed to restore')

server = capnp.TwoPartyServer(sock, restore)

Otherwise, your reference can be a struct, and you would use code like this:

# Client
calculator = client.restore(calculator_capnp.ObjRef.new_message(id='calculator')).cast_as(calculator_capnp.Calculator)

# Server
class ObjRestorer(calculator_capnp.ObjRef.Restorer):

    def restore(self, objref):
        if objref.id == 'calculator':
            return Calculator()
        else:
            raise Exception('Unrecognized ref passed to restore')

server = capnp.TwoPartyServer(sock, ObjRestorer())

A given RPC must have a single restorer style and type, I think. You certainly cannot use multiple struct restorers.


问:
How can I read a parameter array from excel so that its values are available when stocks are initialized?
The problem:

I need to read a row of values from an excel spreadsheet into a parameter array and use these values to set the initial values of stocks.

The specifics:

a. I can successfully set the scalar parameters default values from excel using ExcelControlName.getCellNumericValue("ExcelSheetName", RowNumber, ColumnNumber).

b. Trying to set default values for array parameters with ExcelControlName.readHyperArray(DestinationArrayName,"ExcelSheetName",RowNumber, ColumnNumber, false) returns a "Cannot return a void result" error on build.

c. I can read the parameter arrays from a function called from the Agent actions "On startup:" section using ExcelControlName.readHyperArray(DestinationArrayName,"ExcelSheetName",RowNumber, ColumnNumber, false).

d. Stocks with their initial values set to the parameter array that was successfully loaded by the function are all zero even though the parameter array shows values (when run). Initial value: ParameterArrayName.

e. When I set the parameter array values through the value editor the stocks initialize correctly.

My suspicion:

I'm thinking that the issue has something to do with the internal timing within the entrails of the model generated by Anylogic such that the function to load the parameters is executed after the stocks get initial values - but that could just be the delirium caused by repeatedly smashing my forehead into the wall. But, if this is indeed the case, how can I sneak the function in earlier or, better yet, how would someone who actually knows what they're doing accomplish this?

What I'm trying to accomplish:

As a septuagenarian with lots of time on my hands and a vague recollection of dynamic modeling using Dynamo from a Systems Science program in the early seventies (and not used since), I thought I'd take a whack at age-based modeling of the COVID-19 pandemic. I wanted to see, among other things, whether establishing elder-prisons (in now vacant Club-Meds, Sandals... I'm sure) would be an economically advantageous strategy. Getting there requires dis-aggregating classic SIR approaches into age-specific chains of causality. So far, I'm at 27 age-specific parameters for eight age-groups and 24 scalar parameters. As much as I'd like to type and retype... all this data I'm really hoping there is a better way.

I must say that I am amazed at how far modeling has come in only 50 or so years and I am enthralled with Anylogic's application - even though it's a bit java-ish for me.

Thank you ever so much,

Carl Cottrell

Equivalent parameter arrays - one with values entered in edit the other read from excel file through a function

答:
Not sure if I understand but here it goes:

I understand that you have the following structure:

and you want to initialize the stock as follows.

To do that, on the initial value of your parameter use a function that returns an HyperParameter:

the function getInitialValue should return an HyperParameter and I think this code should work for you (you have to choose RowNumber according to whatever is on your excelfile, MyDimension is the name of your dimension, and ExcelControlName is the excel in which you hold the values of the initial values of the stock)

```<code>HyperArray x=new HyperArray(MyDimension);
for(int i=0;i<=numColumns;i++){
    x.set(ExcelControlName.getCellNumericValue("ExcelSheetName", RowNumber, i), i);
}

return x;
</code>```

Body:
Not sure if I understand but here it goes:

I understand that you have the following structure:

and you want to initialize the stock as follows.

To do that, on the initial value of your parameter use a function that returns an HyperParameter:

the function getInitialValue should return an HyperParameter and I think this code should work for you (you have to choose RowNumber according to whatever is on your excelfile, MyDimension is the name of your dimension, and ExcelControlName is the excel in which you hold the values of the initial values of the stock)

HyperArray x=new HyperArray(MyDimension);
for(int i=0;i<=numColumns;i++){
    x.set(ExcelControlName.getCellNumericValue("ExcelSheetName", RowNumber, i), i);
}

return x;


问:
AspNetCore.Session-Distributed Cache keeps timing out on distributed servers
I have an AspNetCore (core 2.1) web appl that works fine in any single server environment, but times out after a few seconds in the environment with 2 load-balanced web servers.

Here are my startup.cs and other classes, and a screenshot of my AppSessionState table. I hope someone can point me to the right path. I've spent 2 days on this and can't find anything else that needs settings or what's wrong with what I'm doing.

Some explanation of below code:

As seen, I've followed the steps to configure the app to use Distributed SQL Server caching and have a helper static class HttpSessionService which handles adding/getting values from the Session State. Also, I have a Session-Timeout attribute that I annotate each of my controllers to control the session timeouts. And after a few seconds or clicks in the app, as each controller action makes this call

HttpSessionService.Redirect()

this Redirect() method gets a NULL user session from this line, which causes the app to timeout.

var userSession = GetValues<UserIdentityView>(SessionKeys.User);

I've attached two VS debuggers to both servers and I've noticed that even when all sessions coming to one of the debugger instance (one server) the AspNet Session still returned NULL for the above userSession value.

Again, this ONLY happens on a distributed environment, i.e. if I stop one of the sites on one of the web servers everything works fine.

I have looked and implemented the session state distributed caching with SQLServer as explained (the same) in different pages, here are few.

https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-3.0

https://www.c-sharpcorner.com/article/configure-sql-server-session-state-in-asp-net-core/

And I do see sessions being written to my created AppSessionState table, yet the app continues to timeout in the environment with 2 load-balanced servers.

Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
         // Session State distributed cache configuration against SQLServer.
         var aspStateConnStr = ConfigurationManager.ConnectionStrings["ASPState"].ConnectionString;
         var aspSessionStateSchemaName = _config.GetValue<string>("AppSettings:AspSessionStateSchemaName");
         var aspSessionStateTbl = _config.GetValue<string>("AppSettings:AspSessionStateTable");
         services.AddDistributedSqlServerCache(options =>
         {
            options.ConnectionString = aspStateConnStr;
            options.SchemaName = aspSessionStateSchemaName;
            options.TableName = aspSessionStateTbl;
         });

         ....
         services.AddSession(options =>
         {
            options.IdleTimeout = 1200;
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
         });

         services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

         ...
         services.AddMvc().AddJsonOptions(opt => opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime, IDistributedCache distCache)
    {
        var distCacheOptions = new DistributedCacheEntryOptions()
                    .SetSlidingExpiration(TimeSpan.FromMinutes(5));

        // Session State distributed cache configuration.
        lifetime.ApplicationStarted.Register(() =>
        {
            var currentTimeUTC = DateTime.UtcNow.ToString();
            byte[] encodedCurrentTimeUTC = Encoding.UTF8.GetBytes(currentTimeUTC);
            distCache.Set("cachedTimeUTC", encodedCurrentTimeUTC, distCacheOptions);
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseSession();   // This must be called before the app.UseMvc()

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        HttpSessionService.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>(), distCache, distCacheOptions);

     }

```

<p>HttpSessionService (helper class):</p>

<pre class="lang-cs prettyprint-override"><code>    public class HttpSessionService
    {
        private static IHttpContextAccessor _httpContextAccessor;
        private static IDistributedCache _distributedCache;

        private static ISession _session => _httpContextAccessor.HttpContext.Session;

        public static void Configure(IHttpContextAccessor httpContextAccessor, IDistributedCache distCache)
        {
            _httpContextAccessor = httpContextAccessor;
            _distributedCache = distCache;
        }

        public static void SetValues<T>(string key, T value)
        {
            _session.Set<T>(key, value);
        }

        public static T GetValues<T>(string key)
        {
            var sessionValue = _session.Get<T>(key);
            return sessionValue == null ? default(T) : sessionValue;
        }

        public static bool Redirect()
        {
            var result = false;
            var userSession = GetValues<UserIdentityView>(SessionKeys.User);

            if (userSession == null || userSession?.IsAuthenticated == false)
            {
                result = true;
            }

            return result;
        }
    }
</code>```

SessionTimeoutAttribute:

    public class SessionTimeoutAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var redirect = HttpSessionService.Redirect();

            if (redirect)
            {
                context.Result = new RedirectResult("~/Account/SessionTimeOut");
                return;
            }

            base.OnActionExecuting(context);
        }

    }
```

<p>MyController</p>

<pre class="lang-cs prettyprint-override"><code>    [SessionTimeout]
    public class MyController : Controller
    {

         // Every action in this and any other controller time out and I get redirected by SessionTimeoutAttribute to "~/Account/SessionTimeOut"

    }
</code>```

答:
Sorry for the late reply on this. I've changed my original implementation, by injecting IDistributedCache interface to all of my controllers and using this setting in the Statusup.cs class in ConfigureServices() function.

```<code>services.AddDistributedSqlServerCache(options =>
{
    options.ConnectionString = aspStateConnStr;
    options.SchemaName = aspSessionStateSchemaName;
    options.TableName = aspSessionStateTbl;
    options.ExpiredItemsDeletionInterval = null;
});
</code>```

That made it work in a web farm.
As you can see I'm setting the ExpiredItemsDeletionInterval to null to prevent some basic cache entries from clearing out of cache, but with doing so I ran into another problem that when I attempt to get them I still get null back even if the entry is in the database table. So, that's another thing I'm trying to figure out.

Body:
I have an AspNetCore (core 2.1) web appl that works fine in any single server environment, but times out after a few seconds in the environment with 2 load-balanced web servers.

Here are my startup.cs and other classes, and a screenshot of my AppSessionState table. I hope someone can point me to the right path. I've spent 2 days on this and can't find anything else that needs settings or what's wrong with what I'm doing.

Some explanation of below code:

As seen, I've followed the steps to configure the app to use Distributed SQL Server caching and have a helper static class HttpSessionService which handles adding/getting values from the Session State. Also, I have a Session-Timeout attribute that I annotate each of my controllers to control the session timeouts. And after a few seconds or clicks in the app, as each controller action makes this call

HttpSessionService.Redirect()

this Redirect() method gets a NULL user session from this line, which causes the app to timeout.

var userSession = GetValues<UserIdentityView>(SessionKeys.User);

I've attached two VS debuggers to both servers and I've noticed that even when all sessions coming to one of the debugger instance (one server) the AspNet Session still returned NULL for the above userSession value.

Again, this ONLY happens on a distributed environment, i.e. if I stop one of the sites on one of the web servers everything works fine.

I have looked and implemented the session state distributed caching with SQLServer as explained (the same) in different pages, here are few.

https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-3.0

https://www.c-sharpcorner.com/article/configure-sql-server-session-state-in-asp-net-core/

And I do see sessions being written to my created AppSessionState table, yet the app continues to timeout in the environment with 2 load-balanced servers.

Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
         // Session State distributed cache configuration against SQLServer.
         var aspStateConnStr = ConfigurationManager.ConnectionStrings["ASPState"].ConnectionString;
         var aspSessionStateSchemaName = _config.GetValue<string>("AppSettings:AspSessionStateSchemaName");
         var aspSessionStateTbl = _config.GetValue<string>("AppSettings:AspSessionStateTable");
         services.AddDistributedSqlServerCache(options =>
         {
            options.ConnectionString = aspStateConnStr;
            options.SchemaName = aspSessionStateSchemaName;
            options.TableName = aspSessionStateTbl;
         });

         ....
         services.AddSession(options =>
         {
            options.IdleTimeout = 1200;
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
         });

         services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

         ...
         services.AddMvc().AddJsonOptions(opt => opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime, IDistributedCache distCache)
    {
        var distCacheOptions = new DistributedCacheEntryOptions()
                    .SetSlidingExpiration(TimeSpan.FromMinutes(5));

        // Session State distributed cache configuration.
        lifetime.ApplicationStarted.Register(() =>
        {
            var currentTimeUTC = DateTime.UtcNow.ToString();
            byte[] encodedCurrentTimeUTC = Encoding.UTF8.GetBytes(currentTimeUTC);
            distCache.Set("cachedTimeUTC", encodedCurrentTimeUTC, distCacheOptions);
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseSession();   // This must be called before the app.UseMvc()

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        HttpSessionService.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>(), distCache, distCacheOptions);

     }

HttpSessionService (helper class):

    public class HttpSessionService
    {
        private static IHttpContextAccessor _httpContextAccessor;
        private static IDistributedCache _distributedCache;

        private static ISession _session => _httpContextAccessor.HttpContext.Session;

        public static void Configure(IHttpContextAccessor httpContextAccessor, IDistributedCache distCache)
        {
            _httpContextAccessor = httpContextAccessor;
            _distributedCache = distCache;
        }

        public static void SetValues<T>(string key, T value)
        {
            _session.Set<T>(key, value);
        }

        public static T GetValues<T>(string key)
        {
            var sessionValue = _session.Get<T>(key);
            return sessionValue == null ? default(T) : sessionValue;
        }

        public static bool Redirect()
        {
            var result = false;
            var userSession = GetValues<UserIdentityView>(SessionKeys.User);

            if (userSession == null || userSession?.IsAuthenticated == false)
            {
                result = true;
            }

            return result;
        }
    }

SessionTimeoutAttribute:

    public class SessionTimeoutAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var redirect = HttpSessionService.Redirect();

            if (redirect)
            {
                context.Result = new RedirectResult("~/Account/SessionTimeOut");
                return;
            }

            base.OnActionExecuting(context);
        }

    }

MyController

    [SessionTimeout]
    public class MyController : Controller
    {

         // Every action in this and any other controller time out and I get redirected by SessionTimeoutAttribute to "~/Account/SessionTimeOut"

    }

Body:
Sorry for the late reply on this. I've changed my original implementation, by injecting IDistributedCache interface to all of my controllers and using this setting in the Statusup.cs class in ConfigureServices() function.

services.AddDistributedSqlServerCache(options =>
{
    options.ConnectionString = aspStateConnStr;
    options.SchemaName = aspSessionStateSchemaName;
    options.TableName = aspSessionStateTbl;
    options.ExpiredItemsDeletionInterval = null;
});

That made it work in a web farm.
As you can see I'm setting the ExpiredItemsDeletionInterval to null to prevent some basic cache entries from clearing out of cache, but with doing so I ran into another problem that when I attempt to get them I still get null back even if the entry is in the database table. So, that's another thing I'm trying to figure out.


问:
Can I use HTML to add hidden text that still gets counted by ctrl+F?
I have a string of 1s and 0s that I want to have people count. However, to separate those people who are actually counting from those who are "cheating" by using ctrl+F, I'd like to include a few extra 1's that do not appear to people but would get counted if someone was using ctrl+F.

In other words, I'd like something to be displayed like this: 1 0 1 1

....but actually have two extra hidden 1's so anyone counting would see three ones but anyone using ctrl+F would report five ones (3 displayed + 2 hidden).

Is it possible to use HTML to have hidden text that isn't displayed but is counted by ctrl+F?

Here's what the code looks like right now.

```<code>Count the number of "ones" below: <br />
<br />
1 1 1 0 1 0 0 0 1 0 1 1 0 0 0 0 1 0 1
</code>```

I'm new to both HTML and HTML StackOverflow. Thanks so much in advance for any help you might offer!

答:
You can simply place your extra 1s within a span tag and style this with a display of none. These will be hidden and won't show up on the page, and won't be counted when using Ctrl+F to search for 1s:

.hide {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  Count the "ones":
</p>
<p>
  1 1 1 0 1 0 0 0 1 0 1 1 0 0 0 0 1 0 1 <span class='hide'>1 1 1</span>
</p>
<p>
  1 1 1 0 1 0 0 0 1 0 1 1 0 0 0 0 1 0 1 <span style="display:none;">1 1 1</span>
</p></code>```

Body:
I have a string of 1s and 0s that I want to have people count. However, to separate those people who are actually counting from those who are "cheating" by using ctrl+F, I'd like to include a few extra 1's that do not appear to people but would get counted if someone was using ctrl+F.

In other words, I'd like something to be displayed like this: 1 0 1 1

....but actually have two extra hidden 1's so anyone counting would see three ones but anyone using ctrl+F would report five ones (3 displayed + 2 hidden).

Is it possible to use HTML to have hidden text that isn't displayed but is counted by ctrl+F?

Here's what the code looks like right now.

Count the number of "ones" below:

1 1 1 0 1 0 0 0 1 0 1 1 0 0 0 0 1 0 1

I'm new to both HTML and HTML StackOverflow. Thanks so much in advance for any help you might offer!

Body:
You can simply place your extra 1s within a span tag and style this with a display of none. These will be hidden and won't show up on the page, and won't be counted when using Ctrl+F to search for 1s:

.hide {
  display: none;
}

<p>
  Count the &quot;ones&quot;:
</p>
<p>
  1 1 1 0 1 0 0 0 1 0 1 1 0 0 0 0 1 0 1 <span class='hide'>1 1 1</span>
</p>
<p>
  1 1 1 0 1 0 0 0 1 0 1 1 0 0 0 0 1 0 1 <span style="display:none;">1 1 1</span>
</p>


问:
Looping over Array of objects and returning random object value - JavaScript
I am trying to loop over an array of objects and display a random quote from the data, so far my code returns undefined. Any idea's why?

Code so far..

```<code>const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    for (var i = 0; i < 1; i += 1 )  {
    const randomQuote = quotesToUse[i][Math.floor(Math.random() * quotesToUse[i].quote.length)];
    document.getElementById("container").appendChild(text).append(randomQuote);
}
</code>```

I am trying to display the quote (String) randomly.

答:
You can return random quotes with this function:

const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    const randomQuote = quotesToUse[Math.floor(Math.random() * quotesToUse.length)];
    const quote = document.createElement("DIV");
    quote.textContent=randomQuote.quote;
    const author = document.createElement("DIV");
    author.textContent=randomQuote.author;  document.getElementById("container").appendChild(quote).appendChild(author);
}

randomQuotes();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container"></div></code>```

Body:
I am trying to loop over an array of objects and display a random quote from the data, so far my code returns undefined. Any idea's why?

Code so far..

const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    for (var i = 0; i < 1; i += 1 )  {
    const randomQuote = quotesToUse[i][Math.floor(Math.random() * quotesToUse[i].quote.length)];
    document.getElementById("container").appendChild(text).append(randomQuote);
}

I am trying to display the quote (String) randomly.

Body:
You can return random quotes with this function:

const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    const randomQuote = quotesToUse[Math.floor(Math.random() * quotesToUse.length)];
    const quote = document.createElement("DIV");
    quote.textContent=randomQuote.quote;
    const author = document.createElement("DIV");
    author.textContent=randomQuote.author;  document.getElementById("container").appendChild(quote).appendChild(author);
}

randomQuotes();

<div id="container"></div>


问:
CakePHP Routing - [home]/slug as URL
I'm trying to get to grips with Cake's routing, but I'm having no luck finding a solution to my particular problem.

I want to map www.example.com/slug to www.example.com/venues/view/slug, where slug is the URL friendly name of a record for a particular venue.

I also want to then map www.example.com/slug/events to www.example.com/events/index/venue:slug.

After reading the CakePHP documentation on Routing, a few times over, I'm none the wiser.  I understand how I would create these routes for each individual venue, but I'm not sure how to get Cake to generate the routes on the fly.

答:
You want to be careful mapping something to the first path after the domain name. This means that you would be breaking the controller/action/param/param paradigm. You can do this, but it may mean that you need to define every url for your site in your routes file rather than using Cake's routing magic.

An alternative may be to use /v/ for venues and /e/ for events to keep your url short but break up the url for the normal paradigm.

If you still want to do what you requested here, you could do something like the following. It limits the slug to letters, numbers, dashes, and underscores.

```<code>Router::connect(
    '/:slug',
    array(
        'controller' => 'venues',
        'action' => 'view'
        ),
    array(
    'slug' => '[a-zA-Z0-9_-]+'
    )
);
Router::connect(
    '/:slug/:events',
    array(
        'controller' => 'events',
        'action' => 'index'
        ),
    array(
    'slug' => '[a-zA-Z0-9_-]+'
    )
);
</code>```

In your controller, you would then access the slug with the following (using the first route as an example).

```<code>function view(){
    if(isset($this->params['slug'])){
        //Do something with your code here.
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: CakePHP Routing - [home]/slug as URL

Body:
You want to be careful mapping something to the first path after the domain name. This means that you would be breaking the controller/action/param/param paradigm. You can do this, but it may mean that you need to define every url for your site in your routes file rather than using Cake's routing magic.

An alternative may be to use /v/ for venues and /e/ for events to keep your url short but break up the url for the normal paradigm.

If you still want to do what you requested here, you could do something like the following. It limits the slug to letters, numbers, dashes, and underscores.

Router::connect(
    '/:slug',
    array(
        'controller' => 'venues',
        'action' => 'view'
        ),
    array(
    'slug' => '[a-zA-Z0-9_-]+'
    )
);
Router::connect(
    '/:slug/:events',
    array(
        'controller' => 'events',
        'action' => 'index'
        ),
    array(
    'slug' => '[a-zA-Z0-9_-]+'
    )
);

In your controller, you would then access the slug with the following (using the first route as an example).

function view(){
    if(isset($this->params['slug'])){
        //Do something with your code here.
    }
}


问:
(R) renaming columns from names to Response time series
I need to rename columns with names “V4, V5, etc... V503” to be time series in increments of two ms (i.e. “-100-98, 97-95, etc... zip to 900 ms”).

These are 2 second increments for columns that contain brain data from -100 ms to 900ms. I’ve tried using names() and substring() but R didn’t like the numeric aspect. Can anyone help? Thank you!

答:
You need to turn the numbers into a string using as.character. You can just paste offsetting sequences
together for their ranges and it will coerce the data to a string using the - separator. Then you need to
remove instances of -- with gsub so that negative values don't have double -. Note that you need to use back ticks when subsetting these columns.

```<code>sq <- seq(-100, 898, by=2)
sq2 <- seq(-98, 900, by=2)

nams <- paste(sq, sq2, sep='-')
nams <- gsub('--', '-', nams)

# generating fake dataframe
n <- length(sq)
df <- matrix(data=rep(1, n), nrow = 1, ncol=n)
df <- as.data.frame(df)

# replace names

colnames(df) <- nams

head(df)
</code>```

Body:
You need to turn the numbers into a string using as.character. You can just paste offsetting sequences
together for their ranges and it will coerce the data to a string using the - separator. Then you need to
remove instances of -- with gsub so that negative values don't have double -. Note that you need to use back ticks when subsetting these columns.

sq <- seq(-100, 898, by=2)
sq2 <- seq(-98, 900, by=2)

nams <- paste(sq, sq2, sep='-')
nams <- gsub('--', '-', nams)

# generating fake dataframe
n <- length(sq)
df <- matrix(data=rep(1, n), nrow = 1, ncol=n)
df <- as.data.frame(df)

# replace names

colnames(df) <- nams

head(df)


答:
You can hide the hidden numbers by using a combination of absolute/fixed positioning and top/left translation.

Example:

.hidden {
   position: fixed;
   top: -9999px;
   left: -9999px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="hidden">1</span>
<span>1</span></code>```

It might be easier to grok if you look at this codepen.

You will physically see 8 1s in the browser, but CTRL + F shows 9.

Inline Style Example

1
1```

Title: Can I use HTML to add hidden text that still gets counted by ctrl+F?

Body:
You can hide the hidden numbers by using a combination of absolute/fixed positioning and top/left translation.

Example:

.hidden {
   position: fixed;
   top: -9999px;
   left: -9999px;
}

<span class="hidden">1</span>
<span>1</span>

It might be easier to grok if you look at this codepen.

You will physically see 8 1s in the browser, but CTRL + F shows 9.

Inline Style Example

<span style="position: fixed;top: -9999px;left: -9999px;">1</span>
<span>1</span>


问:
How to create the color background transition from reflectly?
Do you have any idea what they did to create this cool effect in flutter? Couldn't find any widget for this use case, since it doesn't seems to be a animation between several pages:

I tried to use an AnimatedContainer with BoxDecoration and then change the size of that to Something like 99999, but the Container will not go bigger than my display width.

答:
Okey i got it. Turns out that the Transform.scale widget can go bigger than your screen size. So I wrapped it around my AnimatedContainer Widget and it worked.

If someone has a better solution please let me know.


答:
let mainId = document.getElementById("main");
let timeDelay = 1000; // in ms
let text = "Hello world this is example text";

function showWords() {
  let textArray = text.split(" ");

  function Show(item) {
    if (item < textArray.length) {
      mainId.innerText = textArray[item];
      setTimeout(Show, timeDelay, item + 1);
    }
  }
  Show(0);
}

showWords();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main"></div></code>```

Body:
I want to show each word of a string of text in 60 seconds intervals on screen and came up with something like this:

let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");

function showWords() {
  // Print words to the screen one at a time.

  let textArray = text.split(" ");
  for(let i = 0; i < poemArray.length; i++) {
    mainId.textContent = poemArray[i];
  }
}

I know that I should use a setInterval() method here, I'm not just sure how I should use it. I have tried to put the whole for loop as the function part of it and even tried to put the code inside the for loop as the function part and nothing works.

Body:
let mainId = document.getElementById("main");
let timeDelay = 1000; // in ms
let text = "Hello world this is example text";

function showWords() {
  let textArray = text.split(" ");

  function Show(item) {
    if (item < textArray.length) {
      mainId.innerText = textArray[item];
      setTimeout(Show, timeDelay, item + 1);
    }
  }
  Show(0);
}

showWords();

<div id="main"></div>


问:
is there any module to merge os and tkinter ? by running the code it shows filename in pycharm but number in tkinter window
#well i want automation progress to pick file name by os mobule and place it as an label in tkinter</p>

```<code>import os
import tkinter as tk
root = tk.Tk()
root.geometry("800x800")
root.config(bg="black")

def Anime():#anime function              #this fuction works well
    name = os.listdir("D:/anime")
    few = name[0:10]
    for list in few:
        print(list)

def label(ly):#tkinter label function  #but this shows number in label of tkinter
    label = tk.Label(root,width=50,text=list,fg="pink",height=2,bg="green")
    label.place(relx=0.3,rely=ly)
ly = 0
count = 0
while (count < 0.78):
    count = count + 0.07
    print(label( ly + count))

Anime()
</code>```

答:
There is no module to merge tkinter and os.

To achieve what I think you want:

from tkinter import *
import os

window = Tk()
window.title("Window")
window.configure(bg = "black")
HEIGHT = window.winfo_screenheight()
WIDTH = window.winfo_screenwidth()
RESOL = str(WIDTH) + "x" + str(HEIGHT+7) + "+" + str(-7) + "+" + str(0)
window.geometry(RESOL)

l = os.listdir()
x = WIDTH/2
y = 0

for item in l:
    Label(window, text = item, bg = "green").place(x = x, y = y)
    y += 30
```

Hope this helps!

Body:
#well i want automation progress to pick file name by os mobule and place it as an label in tkinter

import os
import tkinter as tk
root = tk.Tk()
root.geometry("800x800")
root.config(bg="black")

def Anime():#anime function              #this fuction works well
    name = os.listdir("D:/anime")
    few = name[0:10]
    for list in few:
        print(list)

def label(ly):#tkinter label function  #but this shows number in label of tkinter
    label = tk.Label(root,width=50,text=list,fg="pink",height=2,bg="green")
    label.place(relx=0.3,rely=ly)
ly = 0
count = 0
while (count < 0.78):
    count = count + 0.07
    print(label( ly + count))

Anime()

Body:
There is no module to merge tkinter and os.

To achieve what I think you want:

from tkinter import *
import os

window = Tk()
window.title("Window")
window.configure(bg = "black")
HEIGHT = window.winfo_screenheight()
WIDTH = window.winfo_screenwidth()
RESOL = str(WIDTH) + "x" + str(HEIGHT+7) + "+" + str(-7) + "+" + str(0)
window.geometry(RESOL)

l = os.listdir()
x = WIDTH/2
y = 0

for item in l:
    Label(window, text = item, bg = "green").place(x = x, y = y)
    y += 30

Hope this helps!


问:
Is it possible to include symbols like +,*,/ and - to encode in base64 format?
I'm using base64 encrypting of html tags due to solve a postback issue with my code. My html tag contain symbols like + , - , / or * . While decrypting the encrypted string im getting the following error :

Invalid length for a Base-64 char array.

Can anybody suggest a workaround here please?

JavaScript Calling from aspx page.

```<code> var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    function encode64(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            }

            else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        }

        return output;
    }
</code>```

C# Code to decode the string @ pageload:

```<code> public string DecodeBase64String(string encodedData)
    {
        byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
        string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);

        return returnValue;
    }
</code>```

Error can be generated by giving a simple string that contain any of the symbols i'd mentioned or even a space character.

Html String :

```<code>"<tbody id=\"selectedColumnsTbody\">\n                    <tr style=\"cursor: move;\" id=\"ExprCountryMasterID10\"><td></td><td><input id=\"chk\" checked=\"checked\" class=\"textChangeClass\" type=\"checkbox\"></td><td>CountryMaster.ID + 10</td><td><input id=\"aliastextCountryMasterID10\" class=\"aliasTextChangeClass\" value=\"\" type=\"text\"></td>><td><input id=\"hiddenIDSortCountryMasterID10\" value=\"\" type=\"hidden\"></td></tr></tbody>\n
</code>```

Calling decrypt method from cs page:

protected void Page_Load(object sender, EventArgs e)
        {

```<code>        //HtmlTextWriter htmlTable = new HtmlTextWriter();

        //htmlTable.InnerHtml = htmlContent;
        //Master.FindControl("ContentPlaceHolder1").Controls.Add(htmlTable);
        if (Session["HtmlTable"] != null)
        {

            htmlContent = Session["HtmlTable"].ToString();
            //htmlContent = htmlContent.Replace(" ", "+");
            htmlContent = DecodeBase64String(htmlContent);
            htmlTable = new HtmlGenericControl();
            ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
            if (contentPlaceHolder != null)
            {
                htmlContent = "<table cellspacing=\"0\" cellpadding=\"0\" id=\"selectedColumns\" width=\"100%\">" + htmlContent + "</table>";
                htmlTable.InnerHtml = htmlContent;
                test.InnerHtml = htmlContent;
            }
        }
</code>```

}

Javascript where im calling htmlEncode
 function StoreSessionForHtml(htmlContent) {

```<code>        //            var encodedObject = htmlEncode(htmlContent);
        //            var decodedObject = htmlDecode(encodedObject);
        //htmlContent = htmlContent.replace(/ /g, "+");

        var encodedObject = encode64(htmlContent);

        var requesthtmlContentParameter = '{' +
                        'htmlContentToServer:"' + encodedObject + '"}';

        $.ajax({
            type: "POST",
            url: "Webtop.aspx/HTMLTableContent",
            data: requesthtmlContentParameter,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                //alert("Success", msg.d);
            }, //Event that'll be fired on Success
            error: function() {
               // alert("Try Again");

            } //Event that'll be fired on Error
        });
        $("#<%= HiddenHtmlContainer.ClientID %>").val(encodedObject);
    }
</code>```

答:
Why don't use the HttpUtility.HtmlEncode Method

to prevent attack

Body:
I'm using base64 encrypting of html tags due to solve a postback issue with my code. My html tag contain symbols like + , - , / or * . While decrypting the encrypted string im getting the following error :

Invalid length for a Base-64 char array.

Can anybody suggest a workaround here please?

JavaScript Calling from aspx page.

 var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    function encode64(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            }

            else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        }

        return output;
    }

C# Code to decode the string @ pageload:

 public string DecodeBase64String(string encodedData)
    {
        byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
        string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);

        return returnValue;
    }

Error can be generated by giving a simple string that contain any of the symbols i'd mentioned or even a space character.

Html String :

"
\n
	<input id=\"chk\" checked=\"checked\" class=\"textChangeClass\" type=\"checkbox\">	CountryMaster.ID + 10	<input id=\"aliastextCountryMasterID10\" class=\"aliasTextChangeClass\" value=\"\" type=\"text\">	><input id=\"hiddenIDSortCountryMasterID10\" value=\"\" type=\"hidden\">

\n

Calling decrypt method from cs page:

protected void Page_Load(object sender, EventArgs e)
        {

        //HtmlTextWriter htmlTable = new HtmlTextWriter();

        //htmlTable.InnerHtml = htmlContent;
        //Master.FindControl("ContentPlaceHolder1").Controls.Add(htmlTable);
        if (Session["HtmlTable"] != null)
        {

            htmlContent = Session["HtmlTable"].ToString();
            //htmlContent = htmlContent.Replace(" ", "+");
            htmlContent = DecodeBase64String(htmlContent);
            htmlTable = new HtmlGenericControl();
            ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
            if (contentPlaceHolder != null)
            {
                htmlContent = "
" + htmlContent + "
";
                htmlTable.InnerHtml = htmlContent;
                test.InnerHtml = htmlContent;
            }
        }

}

Javascript where im calling htmlEncode
 function StoreSessionForHtml(htmlContent) {

        //            var encodedObject = htmlEncode(htmlContent);
        //            var decodedObject = htmlDecode(encodedObject);
        //htmlContent = htmlContent.replace(/ /g, "+");

        var encodedObject = encode64(htmlContent);

        var requesthtmlContentParameter = '{' +
                        'htmlContentToServer:"' + encodedObject + '"}';

        $.ajax({
            type: "POST",
            url: "Webtop.aspx/HTMLTableContent",
            data: requesthtmlContentParameter,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                //alert("Success", msg.d);
            }, //Event that'll be fired on Success
            error: function() {
               // alert("Try Again");

            } //Event that'll be fired on Error
        });
        $("#<%= HiddenHtmlContainer.ClientID %>").val(encodedObject);
    }


问:
Caused by: java.lang.IllegalArgumentException: Application Context cannot be null
can someone help me, that's my configuration class

```<code> package net.king.cofingWeb;

import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

@Configuration
public class ThymeMvc extends WebMvcConfigurerAdapter {

      @Bean
      public ViewResolver viewResolver() {
            ThymeleafViewResolver resolver = new ThymeleafViewResolver();
            resolver.setTemplateEngine(templateEngine());
            resolver.setCharacterEncoding("UTF-8");
            return resolver;
          }

    @Bean
    public ITemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        return engine;
      }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding("UTF-8");
        resolver.setCacheable(false);
        resolver.setPrefix("classpath:/templates/");
        resolver.setSuffix(".html");
        return resolver;
      }

}
</code>```

my pom

```<code>    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
        <version>3.0.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>3.0.9.RELEASE</version>
    </dependency>
</code>```

My Controller

```<code>    package net.king.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import net.king.entities.Candidate;

@Controller
@EnableWebMvc
public class HomeController {

    @RequestMapping(value="/")
    public String index() {
        return "index";
    }

}
</code>```

my index file is in the template folder

my index file is in the template folder, after starting the server here is the result, I spend time solving but still no solutions

```<code>java.lang.IllegalArgumentException: Application Context cannot be null
    at org.thymeleaf.util.Validate.notNull(Validate.java:37) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresource.SpringResourceTemplateResource.<init>(SpringResourceTemplateResource.java:64) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver.computeTemplateResource(SpringResourceTemplateResolver.java:69) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver.computeTemplateResource(AbstractConfigurableTemplateResolver.java:1414) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractTemplateResolver.resolveTemplate(AbstractTemplateResolver.java:356) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:845) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:352) [thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) [thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1372) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_241]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_241]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_241]

2020-06-02 01:31:14.282 ERROR 9236 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception processing template (template: "index")] with root cause

java.lang.IllegalArgumentException: Application Context cannot be null
    at org.thymeleaf.util.Validate.notNull(Validate.java:37) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresource.SpringResourceTemplateResource.<init>(SpringResourceTemplateResource.java:64) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver.computeTemplateResource(SpringResourceTemplateResolver.java:69) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver.computeTemplateResource(AbstractConfigurableTemplateResolver.java:1414) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractTemplateResolver.resolveTemplate(AbstractTemplateResolver.java:356) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:845) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:352) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1372) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_241]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_241]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_241]
</code>```

答:
Here is a sample of a runnig config, you need to set a ApplicationContext attribute and             set it to resolver:</p>

```<code>@Configuration
@ComponentScan(basePackageClasses = { CervejasController.class })
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    @Bean
    public TemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.setTemplateResolver(templateResolver());
        engine.addDialect(new LayoutDialect());
        return engine;
    }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("classpath:/templates/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }
}
</code>```

Body:
can someone help me, that's my configuration class

 package net.king.cofingWeb;

import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

@Configuration
public class ThymeMvc extends WebMvcConfigurerAdapter {

      @Bean
      public ViewResolver viewResolver() {
            ThymeleafViewResolver resolver = new ThymeleafViewResolver();
            resolver.setTemplateEngine(templateEngine());
            resolver.setCharacterEncoding("UTF-8");
            return resolver;
          }

    @Bean
    public ITemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        return engine;
      }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding("UTF-8");
        resolver.setCacheable(false);
        resolver.setPrefix("classpath:/templates/");
        resolver.setSuffix(".html");
        return resolver;
      }

}

my pom

    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
        <version>3.0.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>3.0.9.RELEASE</version>
    </dependency>

My Controller

    package net.king.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import net.king.entities.Candidate;

@Controller
@EnableWebMvc
public class HomeController {

    @RequestMapping(value="/")
    public String index() {
        return "index";
    }

}

my index file is in the template folder

my index file is in the template folder, after starting the server here is the result, I spend time solving but still no solutions

java.lang.IllegalArgumentException: Application Context cannot be null
    at org.thymeleaf.util.Validate.notNull(Validate.java:37) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresource.SpringResourceTemplateResource.<init>(SpringResourceTemplateResource.java:64) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver.computeTemplateResource(SpringResourceTemplateResolver.java:69) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver.computeTemplateResource(AbstractConfigurableTemplateResolver.java:1414) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractTemplateResolver.resolveTemplate(AbstractTemplateResolver.java:356) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:845) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:352) [thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) [thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1372) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_241]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_241]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_241]

2020-06-02 01:31:14.282 ERROR 9236 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception processing template (template: "index")] with root cause

java.lang.IllegalArgumentException: Application Context cannot be null
    at org.thymeleaf.util.Validate.notNull(Validate.java:37) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresource.SpringResourceTemplateResource.<init>(SpringResourceTemplateResource.java:64) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver.computeTemplateResource(SpringResourceTemplateResolver.java:69) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver.computeTemplateResource(AbstractConfigurableTemplateResolver.java:1414) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.templateresolver.AbstractTemplateResolver.resolveTemplate(AbstractTemplateResolver.java:356) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:845) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:352) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190) ~[thymeleaf-spring4-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1372) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.15.RELEASE.jar:5.1.15.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_241]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_241]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.34.jar:9.0.34]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_241]

Body:
Here is a sample of a runnig config, you need to set a ApplicationContext attribute and             set it to resolver:

@Configuration
@ComponentScan(basePackageClasses = { CervejasController.class })
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    @Bean
    public TemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.setTemplateResolver(templateResolver());
        engine.addDialect(new LayoutDialect());
        return engine;
    }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("classpath:/templates/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }
}