问:
Restart/ReInit a servlet
I want to restart a servlet (declared in web.xml, when JBoss is running) simply because its init-param points to a file which content has changed (i.e. providers.fac below has been modified).

If there is a way to reload the init-param without restarting the servlet, it will be good too.

I suppose I can modify the servlet to add a request param and function to restart itself ?
Is there any other option?

```<code> <servlet>
    <servlet-name>coverage</servlet-name>
    <servlet-class>coverageServlet</servlet-class>
    <init-param>
        <param-name>ConfigUrl</param-name>
        <param-value>file:///C:/coverage/providers.fac</param-value>
    </init-param>
    <init-param>
        <param-name>CacheDir</param-name>
        <param-value>coverage</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
</code>```

Environment:
Servlet Api 2.4
JBoss 4.2
Spring Framework 2.5

答:
I would separate these concerns by pulling the file management out of the servlet and putting it into a JBoss JMX ServiceMBean. The MBean can take care of watching the file for changes and reloading when necessary, and can also expose the required operations [to the calling servlet]. This will allow you not to have to reload and re-init the servlet (or the WAR) which are fairly heavyweight operations.

I will invent a couple of operations for the FileManager:

```<code>public interface FileManagerMBean extends org.jboss.system.ServiceMBean {
   public void setFileName(String fileName);
   public void setCheckFrequency(long freq);
   public String getCoverageData(......);
   public String getProviderData(......);
}
</code>```

The implementation might be  (in the same package please :) )

```<code>public class FileManager extends org.jboss.system.ServiceMBeanSupport implements FileManagerMBean  {
   public void setFileName(String fileName) { .... }
   public void setCheckFrequency(long freq) { .... }
   public String getCoverageData(......) {  /* impl */ }
   public String getProviderData(......) {  /* impl */ }
   public void startService() throws Exception {
       /* Start a file watcher thread */
   }
   public void stopService() throws Exception {
       /* Stop the file watcher thread */
   }

}
</code>```

Your servlet might look like this:

```<code>// A ref to the MBean
FileManagerMBean fileMgr = null;
// The JMX MBean's ObjectName
ObjectName fileMgrOn = org.jboss.mx.util.ObjectNameFactory.create("portoalet.com:service=FileManager");

public void init() {
   // Get the JBoss MBeanServer
   MBeanServer server = org.jboss.mx.util.MBeanServerLocator.locateJBoss();
   // Create an MBeanInvoker for the service
   fileMgr = (FileManagerMBean)javax.management.MBeanServerInvocationHandler.newProxyInstance(server, fileMgrOn,FileManagerMBean.class, false);
}
</code>```

Now you can use the fileMgr instance to make calls to your FileManager MBean, which should be thread safe unless you synchronize access to fileMgr.

I realize this looks a bit over-engineered, but you really should separate the functions of the servlet from the functions of managing the file.

Title: Restart/ReInit a servlet

Body:
I want to restart a servlet (declared in web.xml, when JBoss is running) simply because its init-param points to a file which content has changed (i.e. providers.fac below has been modified).

If there is a way to reload the init-param without restarting the servlet, it will be good too.

I suppose I can modify the servlet to add a request param and function to restart itself ?
Is there any other option?

 <servlet>
    <servlet-name>coverage</servlet-name>
    <servlet-class>coverageServlet</servlet-class>
    <init-param>
        <param-name>ConfigUrl</param-name>
        <param-value>file:///C:/coverage/providers.fac</param-value>
    </init-param>
    <init-param>
        <param-name>CacheDir</param-name>
        <param-value>coverage</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Environment:
Servlet Api 2.4
JBoss 4.2
Spring Framework 2.5

Body:
I would separate these concerns by pulling the file management out of the servlet and putting it into a JBoss JMX ServiceMBean. The MBean can take care of watching the file for changes and reloading when necessary, and can also expose the required operations [to the calling servlet]. This will allow you not to have to reload and re-init the servlet (or the WAR) which are fairly heavyweight operations.

I will invent a couple of operations for the FileManager:

public interface FileManagerMBean extends org.jboss.system.ServiceMBean {
   public void setFileName(String fileName);
   public void setCheckFrequency(long freq);
   public String getCoverageData(......);
   public String getProviderData(......);
}

The implementation might be  (in the same package please :) )

public class FileManager extends org.jboss.system.ServiceMBeanSupport implements FileManagerMBean  {
   public void setFileName(String fileName) { .... }
   public void setCheckFrequency(long freq) { .... }
   public String getCoverageData(......) {  /* impl */ }
   public String getProviderData(......) {  /* impl */ }
   public void startService() throws Exception {
       /* Start a file watcher thread */
   }
   public void stopService() throws Exception {
       /* Stop the file watcher thread */
   }

}

Your servlet might look like this:

// A ref to the MBean
FileManagerMBean fileMgr = null;
// The JMX MBean's ObjectName
ObjectName fileMgrOn = org.jboss.mx.util.ObjectNameFactory.create("portoalet.com:service=FileManager");

public void init() {
   // Get the JBoss MBeanServer
   MBeanServer server = org.jboss.mx.util.MBeanServerLocator.locateJBoss();
   // Create an MBeanInvoker for the service
   fileMgr = (FileManagerMBean)javax.management.MBeanServerInvocationHandler.newProxyInstance(server, fileMgrOn,FileManagerMBean.class, false);
}

Now you can use the fileMgr instance to make calls to your FileManager MBean, which should be thread safe unless you synchronize access to fileMgr.

I realize this looks a bit over-engineered, but you really should separate the functions of the servlet from the functions of managing the file.


来源: stackexchange

问:
Dynamically add "notification panels" to win fom c#
I am trying to make a sort of notification within my form. The panel will consist of a rich textbox followed by two buttons underneath it.

Design of panel

I would need a way of programatically displaying new panels with different data in each one and having it displayed so that it can be scrolled. Initially, i have tried to create a table layout panel and then a panel. I could not figure out how to create a new instance of the panel i created in designer to place it into the table layout.

If there is another simple way of achieving my goal of having a group of controls being added beneath each other programatically i would appreciate it.

答:
You can use this code to generate dynamic controls, but i am just sharing with you sample code.</p>

```<code>        int n = 10;
           Panel[] p=new Panel[n];
           int j = 10;
           for (int i=0;i<n;i++)
           {
                j += 10;
                p[i] = new Panel();
                p[i].BorderStyle = BorderStyle.Fixed3D;
                p[i].Height = 100;
                p[i].Location = new Point(100,10+j);
                this.Controls.Add(p[i]);
           }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use this code to generate dynamic controls, but i am just sharing with you sample code.

        int n = 10;
           Panel[] p=new Panel[n];
           int j = 10;
           for (int i=0;i<n;i++)
           {
                j += 10;
                p[i] = new Panel();
                p[i].BorderStyle = BorderStyle.Fixed3D;
                p[i].Height = 100;
                p[i].Location = new Point(100,10+j);
                this.Controls.Add(p[i]);
           }


问:
Birthdays in the scope of java.time.LocalDate
I'm trying to select birthdays (independent of the year) within a Collection of java.time.LocalDate . Why LocalDate ? because this type seems the best for birthday.

Let's say I want to filter the birthdays between March 6 and April 30 irrespective of the year.
How to do this ?

If I were to do it, I would replace the year in LocalDate  and use the method isAfter and isBefore.
The fact that I have to change the year is just a plain hack. Or I  used the wrong data type (LocalDate)

答:
I would rather use the type MonthDay which is the "date-without-year" and which is also comparable and offers methods like isAfter() or isBefore(). Furthermore, a MonthDay can be extended to a LocalDate using the method atYear(int).

If you insist on LocalDate then you should only use leap years because otherwise the 29th of February would be a problem.


问:
IdentityServer4 Error: No DbContext named 'ConfigurationDbContext' was found
I am trying to hook up persistence to my identity server by adding entity framework. Currently, when trying to add a migration I am receiving the error

No DbContext named 'ConfigurationDbContext' was found.

Before running the migration, I have cd'd into the directory my .csproj file sits in and am running dotnet ef migrations add InitConfigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/Configuration to attempt to add the migration.

My Startup.cs class looks as follows:

```<code>    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var migrationsAssembly = typeof(ApplicationDbContext).GetTypeInfo().Assembly.GetName().Name;

            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddAspNetIdentity<ApplicationUser>()
                .AddConfigurationStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                            db => db.MigrationsAssembly(migrationsAssembly));
                })
                .AddOperationalStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                            db => db.MigrationsAssembly(migrationsAssembly));
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseIdentityServer();

            app.UseMvc();
        }
    }
</code>```

How can I resolve this issue?

EDIT: After further investigation, when i use the --project flag when generating the migration as follows: dotnet ef migrations add InitConfigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/Configuration --project BleacherBuddy.IdentityServerService, I receive the error:

MSBUILD : error MSB1009: Project file does not exist. Unable to
  retrieve project metadata. Ensure it's an MSBuild-based .NET Core
  project

My current guess is that because this is a service fabric project (stateless .net core), the build process is failing here and not allowing me to generate the migration. After some research, I'm still unsure how to overcome this or if this is the actual issue. I recreated the simple identity server project as a web api (not using service fabric) and I was able to generate the classes as expected. All help is appreciated.

答:
The issue will happen in three cases:

Even you are putting your migrations in separate class library so in this case you have to implement the design time interface and follow the Microsoft instructions.

Or you are installing this Nuget package to a class library by mistake  IdentityServer4.EntityFrameWork.

You may have the docker-compose enable via visual studio which may cause the same issue as i described here: Add-Migration while using database in separate Docker container throws an error

In all cases make sure to clean then build the solution before run the command again.

Body:
I am trying to hook up persistence to my identity server by adding entity framework. Currently, when trying to add a migration I am receiving the error

No DbContext named 'ConfigurationDbContext' was found.

Before running the migration, I have cd'd into the directory my .csproj file sits in and am running dotnet ef migrations add InitConfigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/Configuration to attempt to add the migration.

My Startup.cs class looks as follows:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var migrationsAssembly = typeof(ApplicationDbContext).GetTypeInfo().Assembly.GetName().Name;

            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddAspNetIdentity<ApplicationUser>()
                .AddConfigurationStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                            db => db.MigrationsAssembly(migrationsAssembly));
                })
                .AddOperationalStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                            db => db.MigrationsAssembly(migrationsAssembly));
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseIdentityServer();

            app.UseMvc();
        }
    }

How can I resolve this issue?

EDIT: After further investigation, when i use the --project flag when generating the migration as follows: dotnet ef migrations add InitConfigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/Configuration --project BleacherBuddy.IdentityServerService, I receive the error:

MSBUILD : error MSB1009: Project file does not exist. Unable to
  retrieve project metadata. Ensure it's an MSBuild-based .NET Core
  project

My current guess is that because this is a service fabric project (stateless .net core), the build process is failing here and not allowing me to generate the migration. After some research, I'm still unsure how to overcome this or if this is the actual issue. I recreated the simple identity server project as a web api (not using service fabric) and I was able to generate the classes as expected. All help is appreciated.


问:
Unable to open site url in browser
I have created simple basic automation script in Python using Selenium..
Getting unwanted exception.

File:-

```<code>import pandas as pd
from pandas import ExcelWriter
from selenium import webdriver

import selenium as sel

# Data = pd.read_excel(r"C:\Users\Admin\PycharmProjects\Web_Automation_Form_Filling\challenge.xlsx",sheet_name="Sheet1")

# browser = webdriver.Chrome(executable_path=r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");
browser.sleep(1000);
browser.get("http://www.python.org")
</code>```

Error log:-

```<code>C:\Users\Admin\PycharmProjects\Web_Automation_Form_Filling\venv\Scripts\python.exe C:/Users/Admin/PycharmProjects/Web_Automation_Form_Filling/venv/Web_Auto_Filling.py
Traceback (most recent call last):
  File "C:/Users/Admin/PycharmProjects/Web_Automation_Form_Filling/venv/Web_Auto_Filling.py", line 10, in <module>
    browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\common\service.py", line 98, in start
    self.assert_process_still_running()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\common\service.py", line 109, in assert_process_still_running
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: Service C:\Program Files (x86)\Google\Chrome\Application\chrome.exe unexpectedly exited. Status code was: 0

Process finished with exit code 1
</code>```

Any suggestion will be appreciated..
Thanks...

答:
The problem here in your codes is that you are passing chrome executable path rather than passing the path to chromedriver which is a different executable.

An appropriate version of chromedriver can be downloaded from here according to your Chrome version.

For more info, you can refer to the chromedriver documentation here.
And your final code should be something like:

```<code>from selenium import webdriver
path = 'C:/Users/Avinash/Downloads/chromedriver.exe'
driver = webdriver.Chrome(path)
driver.get('http://www.google.com/');
#..here what ever you want to do with page here
driver.quit()
</code>```

Title: Unable to open site url in browser

Body:
I have created simple basic automation script in Python using Selenium..
Getting unwanted exception.

File:-

import pandas as pd
from pandas import ExcelWriter
from selenium import webdriver

import selenium as sel

# Data = pd.read_excel(r"C:\Users\Admin\PycharmProjects\Web_Automation_Form_Filling\challenge.xlsx",sheet_name="Sheet1")

# browser = webdriver.Chrome(executable_path=r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");
browser.sleep(1000);
browser.get("http://www.python.org")

Error log:-

C:\Users\Admin\PycharmProjects\Web_Automation_Form_Filling\venv\Scripts\python.exe C:/Users/Admin/PycharmProjects/Web_Automation_Form_Filling/venv/Web_Auto_Filling.py
Traceback (most recent call last):
  File "C:/Users/Admin/PycharmProjects/Web_Automation_Form_Filling/venv/Web_Auto_Filling.py", line 10, in <module>
    browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe");
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\common\service.py", line 98, in start
    self.assert_process_still_running()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\common\service.py", line 109, in assert_process_still_running
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: Service C:\Program Files (x86)\Google\Chrome\Application\chrome.exe unexpectedly exited. Status code was: 0

Process finished with exit code 1

Any suggestion will be appreciated..
Thanks...

Body:
The problem here in your codes is that you are passing chrome executable path rather than passing the path to chromedriver which is a different executable.

An appropriate version of chromedriver can be downloaded from here according to your Chrome version.

For more info, you can refer to the chromedriver documentation here.
And your final code should be something like:

from selenium import webdriver
path = 'C:/Users/Avinash/Downloads/chromedriver.exe'
driver = webdriver.Chrome(path)
driver.get('http://www.google.com/');
#..here what ever you want to do with page here
driver.quit()


问:
Recursive regex for div tags(not trying to parse html with regex)
I have a bunch of wiki markup, sometimes people just throw random html down in the middle of wiki markup and somehow wikipedia just rolls with it, as it does for all kinds of other badly formed wiki markup.  I want to match everything inside the divs.

I need to recursively find all the
blah
 tags including div tags with other div tags inside them.  I am trying to match the div tags and everything inside of them.  I have this which I believe almost works:

```<code>new Regex(@"\<div.*?\> (?<DEPTH>)                   # opening
            (?>                # now match...
               [^(\<div.*?\>)(\<\/div\>)]+          # any characters except divs
            |                  # or
               \<div.*?\>  (?<DEPTH>)  # a opening div, increasing the depth counter
            |                  # or
               \<\/div\>  (?<-DEPTH>) # a closing div, decreasing the depth counter
            )*                 # any number of times
            (?(DEPTH)(?!))     # until the depth counter is zero again
          \<\/div\>                   # then match the closing fix",
            RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
</code>```

Maybe I should be using another methodology to parse this but at this point this is the final regex statement that I need.

Here is an example:

```<code><div class="infobox sisterproject" style="font-size: 90%; padding: .5em 1em 1em 1em;">
<div style="text-align:center;">
Find more about '''{{{display|{{{1|{{PAGENAME}}}}}}}}''' on Wikipedia's [[Wikipedia:Wikimedia sister projects|sister projects]]:
</div><!--
-->{{#ifeq:{{{wikt}}}|no||<!--
-->[[File:Wiktionary-logo-en.svg|25px|link=wikt:Special:Search/{{{wikt|{{{1|{{PAGENAME}}}}}}}}|Search Wiktionary]] [[wikt:Special:Search/{{{wikt|{{{1|{{PAGENAME}}}}}}}}|Definitions]] from Wiktionary<br />}}<!--
-->{{#ifeq:{{{b}}}|no||<!--
-->[[File:Wikibooks-logo.svg|25px|link=b:Special:Search/{{{b|{{{1|{{PAGENAME}}}}}}}}|Search Wikibooks]] [[b:Special:Search/{{{b|{{{1|{{PAGENAME}}}}}}}}|Textbooks]] from Wikibooks<br />}}<!--
-->{{#ifeq:{{{q}}}|no||<!--
-->[[File:Wikiquote-logo.svg|25px|link=q:Special:Search/{{{q|{{{1|{{PAGENAME}}}}}}}}|Search Wikiquote]] [[q:Special:Search/{{{q|{{{1|{{PAGENAME}}}}}}}}|Quotations]] from Wikiquote<br />}}<!--
-->{{#ifeq:{{{s}}}|no||{{#ifeq:{{{author|no}}}|yes|<!--
-->[[File:Wikisource-logo.svg|25px|link=s:Special:Search/Author:{{{s|{{{1|{{PAGENAME}}}}}}}}|Search Wikisource]] [[s:Special:Search/Author:{{{s|{{{1|{{PAGENAME}}}}}}}}|Source texts]] from Wikisource<br />|<!--
-->[[File:Wikisource-logo.svg|25px|link=s:Special:Search/{{{s|{{{1|{{PAGENAME}}}}}}}}|Search Wikisource]] [[s:Special:Search/{{{s|{{{1|{{PAGENAME}}}}}}}}|Source texts]] from Wikisource<br />}}}}<!--
-->{{#ifeq:{{{commons}}}|no||<!--
-->[[File:Commons-logo.svg|25px|link=commons:Special:Search/{{{commons|{{{1|{{PAGENAME}}}}}}}}|Search Commons]] [[commons:Special:Search/{{{commons|{{{1|{{PAGENAME}}}}}}}}|Images and media]] from Commons<br />}}<!--
-->{{#ifeq:{{{n}}}|no||<!--
-->[[File:Wikinews-logo.svg|25px|link=n:Special:Search/{{{n|{{{1|{{PAGENAME}}}}}}}}|Search Wikinews]] [[n:Special:Search/{{{n|{{{1|{{PAGENAME}}}}}}}}|News stories]] from Wikinews<br />}}<!--
-->{{#ifeq:{{{v}}}|no||<!--
-->[[File:Wikiversity-logo-Snorky.svg|25px|link=v:Special:Search/{{{v|{{{1|{{PAGENAME}}}}}}}}|Search Wikiversity]] [[v:Special:Search/{{{v|{{{1|{{PAGENAME}}}}}}}}|Learning resources]] from Wikiversity<br />}}<!--
-->{{#ifeq:{{{species<includeonly>|no</includeonly>}}}|no||<!--
-->[[File:Wikispecies-logo.svg|25px|link=species:Special:Search/{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}|Search Wikispecies]] [[species:Special:Search/{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}|{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}]] from Wikispecies}}
</div><noinclude>
</code>```

Thanks

答:
I think it is not a good idea to parse the html with regex you could use the
Html Agility pack</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a bunch of wiki markup, sometimes people just throw random html down in the middle of wiki markup and somehow wikipedia just rolls with it, as it does for all kinds of other badly formed wiki markup.  I want to match everything inside the divs.

I need to recursively find all the
blah
 tags including div tags with other div tags inside them.  I am trying to match the div tags and everything inside of them.  I have this which I believe almost works:

new Regex(@"\
 (?<DEPTH>)                   # opening
            (?>                # now match...
               [^(\
)(\<\/div\>)]+          # any characters except divs
            |                  # or
               \
  (?<DEPTH>)  # a opening div, increasing the depth counter
            |                  # or
               \<\/div\>  (?<-DEPTH>) # a closing div, decreasing the depth counter
            )*                 # any number of times
            (?(DEPTH)(?!))     # until the depth counter is zero again
          \<\/div\>                   # then match the closing fix",
            RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

Maybe I should be using another methodology to parse this but at this point this is the final regex statement that I need.

Here is an example:

Find more about '''{{{display|{{{1|{{PAGENAME}}}}}}}}''' on Wikipedia's [[Wikipedia:Wikimedia sister projects|sister projects]]:

{{#ifeq:{{{wikt}}}|no||[[File:Wiktionary-logo-en.svg|25px|link=wikt:Special:Search/{{{wikt|{{{1|{{PAGENAME}}}}}}}}|Search Wiktionary]] [[wikt:Special:Search/{{{wikt|{{{1|{{PAGENAME}}}}}}}}|Definitions]] from Wiktionary
}}{{#ifeq:{{{b}}}|no||[[File:Wikibooks-logo.svg|25px|link=b:Special:Search/{{{b|{{{1|{{PAGENAME}}}}}}}}|Search Wikibooks]] [[b:Special:Search/{{{b|{{{1|{{PAGENAME}}}}}}}}|Textbooks]] from Wikibooks
}}{{#ifeq:{{{q}}}|no||[[File:Wikiquote-logo.svg|25px|link=q:Special:Search/{{{q|{{{1|{{PAGENAME}}}}}}}}|Search Wikiquote]] [[q:Special:Search/{{{q|{{{1|{{PAGENAME}}}}}}}}|Quotations]] from Wikiquote
}}{{#ifeq:{{{s}}}|no||{{#ifeq:{{{author|no}}}|yes|[[File:Wikisource-logo.svg|25px|link=s:Special:Search/Author:{{{s|{{{1|{{PAGENAME}}}}}}}}|Search Wikisource]] [[s:Special:Search/Author:{{{s|{{{1|{{PAGENAME}}}}}}}}|Source texts]] from Wikisource
|[[File:Wikisource-logo.svg|25px|link=s:Special:Search/{{{s|{{{1|{{PAGENAME}}}}}}}}|Search Wikisource]] [[s:Special:Search/{{{s|{{{1|{{PAGENAME}}}}}}}}|Source texts]] from Wikisource
}}}}{{#ifeq:{{{commons}}}|no||[[File:Commons-logo.svg|25px|link=commons:Special:Search/{{{commons|{{{1|{{PAGENAME}}}}}}}}|Search Commons]] [[commons:Special:Search/{{{commons|{{{1|{{PAGENAME}}}}}}}}|Images and media]] from Commons
}}{{#ifeq:{{{n}}}|no||[[File:Wikinews-logo.svg|25px|link=n:Special:Search/{{{n|{{{1|{{PAGENAME}}}}}}}}|Search Wikinews]] [[n:Special:Search/{{{n|{{{1|{{PAGENAME}}}}}}}}|News stories]] from Wikinews
}}{{#ifeq:{{{v}}}|no||[[File:Wikiversity-logo-Snorky.svg|25px|link=v:Special:Search/{{{v|{{{1|{{PAGENAME}}}}}}}}|Search Wikiversity]] [[v:Special:Search/{{{v|{{{1|{{PAGENAME}}}}}}}}|Learning resources]] from Wikiversity
}}{{#ifeq:{{{species<includeonly>|no</includeonly>}}}|no||[[File:Wikispecies-logo.svg|25px|link=species:Special:Search/{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}|Search Wikispecies]] [[species:Special:Search/{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}|{{{species<noinclude>|{{{1|{{PAGENAME}}}}}</noinclude>}}}]] from Wikispecies}}

<noinclude>

Thanks


问:
VBA Regex only returns the last match
I'm trying to find all occurrences of terms that are found in quotes inside brackets ("TERM TO BE FOUND"), whether there are other words in the brackets or not (this is also a "TERM TO BE FOUND").

The content of my ActiveDocument is:

```<code>This is a ("Test") and another (second "Test2")
</code>```

My code is:

```<code>Dim regEx As Object
Dim matchCollection As Object
Dim extractedString As String
Dim match As Object
Dim RealQ
Dim n As Integer

RealQ = Chr(34)

Set regEx = CreateObject("VBScript.RegExp")
With regEx
  .IgnoreCase = IgnoreCase
  .Global = True
  .MultiLine = True
  .Pattern = "\(.*" & RealQ & "(.*)" & RealQ & "\)"
End With

Set matchCollection = regEx.Execute(ActiveDocument.Content.Text)

extractedString = ""

For Each match In matchCollection

    Debug.Print (match.submatches(0))

Next
</code>```

The above only finds the last occurrence, i.e. "Test2". What am I missing?

Thanks a lot!!

答:
You can do this task using the wildcard search in Word itself without needing to invoke Regexp.  The code below will return a scripting.dictionary of range objects from which you can extract text, or with a very minor tweak just return the captured texts.  The key function allows you to define which sets of parentheses you want to use and also which characters you wish to use for the quotes.  In the test case below I have used the characters for smart quotes in word.

The test text I used was

```<code>Blah blah blah (blah "Text 1" blah) blah blah blah Blah blah blah (blah “Text 2” blah) Blah blah blah (blah “Text 3” blah) Blah blah blah (blah “Text 4” blah)
</code>```

Which gives an output of

```<code>Text 2
Text 3
Text 4
</code>```

because the first set of quotes are not smart quotes.  You don't say if you just need to extract text or find the text and then process it inside the Word document in some way, hence my first option of returning the Word.Ranges of the found text.  The tweak to get just the text is provided in the comments to the function.

The code below raises no code inspections from the fantastic RubberDuck add in.

```<code>Public Sub testGetTextInQuotesInBrackets()

Dim myTexts As Scripting.Dictionary

    Set myTexts = _
        GetTextInQuotesInBrackets _
        ( _
            "(,)", _
            ChrW$(&H201C) & "," & ChrW$(&H201D), _
            ActiveDocument.StoryRanges(wdMainTextStory) _
        )

    Dim myItem As Variant
    For Each myItem In myTexts

        Debug.Print myTexts.Item(myItem).Text
        ' if just the text was collected
        'Debug.Print myItem

    Next

End Sub

'@Description("Returns a scripting.Dictionary of long vs word.range objects)
Function GetTextInQuotesInBrackets _
( _
    ByVal ipBrackets As String, _
    ByVal ipQuotes As String, _
    ByRef ipRange As Word.Range _
) As Scripting.Dictionary

    Dim myTextRanges As Scripting.Dictionary
    Set myTextRanges = New Scripting.Dictionary

    Dim myBrackets As Variant
    myBrackets = Split(ipBrackets, ",")

    Dim myQuotes As Variant
    myQuotes = Split(ipQuotes, ",")

    With ipRange

        With .Find

            .ClearFormatting
            .Text = "[" & myBrackets(0) & "]*[" & myQuotes(0) & "]*[" & myQuotes(1) & "]" ' is there any need to process the following closing bracket
            .MatchWildcards = True
            .Wrap = wdFindStop

        End With

        Do While .Find.Execute

            Dim myFoundRange As Word.Range
            Set myFoundRange = .Duplicate
            With myFoundRange

                .MoveStartUntil cset:=myQuotes(0)
                ' Select the text within the quotes
                .MoveStart Count:=1
                .MoveEnd Count:=-1

            End With

            myTextRanges.Add myTextRanges.Count, myFoundRange
            ' Alternatively, if you just need the text
            'myTextRanges.add myTextRanges.count, myFoundRange.Text
            .Start = myFoundRange.End + 2
            .End = ipRange.End

        Loop

    End With

    Set GetTextInQuotesInBrackets = myTextRanges

End Function
</code>```

Title: VBA Regex only returns the last match

Body:
I'm trying to find all occurrences of terms that are found in quotes inside brackets ("TERM TO BE FOUND"), whether there are other words in the brackets or not (this is also a "TERM TO BE FOUND").

The content of my ActiveDocument is:

This is a ("Test") and another (second "Test2")

My code is:

Dim regEx As Object
Dim matchCollection As Object
Dim extractedString As String
Dim match As Object
Dim RealQ
Dim n As Integer

RealQ = Chr(34)

Set regEx = CreateObject("VBScript.RegExp")
With regEx
  .IgnoreCase = IgnoreCase
  .Global = True
  .MultiLine = True
  .Pattern = "\(.*" & RealQ & "(.*)" & RealQ & "\)"
End With

Set matchCollection = regEx.Execute(ActiveDocument.Content.Text)

extractedString = ""

For Each match In matchCollection

    Debug.Print (match.submatches(0))

Next

The above only finds the last occurrence, i.e. "Test2". What am I missing?

Thanks a lot!!

Body:
You can do this task using the wildcard search in Word itself without needing to invoke Regexp.  The code below will return a scripting.dictionary of range objects from which you can extract text, or with a very minor tweak just return the captured texts.  The key function allows you to define which sets of parentheses you want to use and also which characters you wish to use for the quotes.  In the test case below I have used the characters for smart quotes in word.

The test text I used was

Blah blah blah (blah "Text 1" blah) blah blah blah Blah blah blah (blah “Text 2” blah) Blah blah blah (blah “Text 3” blah) Blah blah blah (blah “Text 4” blah)

Which gives an output of

Text 2
Text 3
Text 4

because the first set of quotes are not smart quotes.  You don't say if you just need to extract text or find the text and then process it inside the Word document in some way, hence my first option of returning the Word.Ranges of the found text.  The tweak to get just the text is provided in the comments to the function.

The code below raises no code inspections from the fantastic RubberDuck add in.

Public Sub testGetTextInQuotesInBrackets()

Dim myTexts As Scripting.Dictionary

    Set myTexts = _
        GetTextInQuotesInBrackets _
        ( _
            "(,)", _
            ChrW$(&H201C) & "," & ChrW$(&H201D), _
            ActiveDocument.StoryRanges(wdMainTextStory) _
        )

    Dim myItem As Variant
    For Each myItem In myTexts

        Debug.Print myTexts.Item(myItem).Text
        ' if just the text was collected
        'Debug.Print myItem

    Next

End Sub

'@Description("Returns a scripting.Dictionary of long vs word.range objects)
Function GetTextInQuotesInBrackets _
( _
    ByVal ipBrackets As String, _
    ByVal ipQuotes As String, _
    ByRef ipRange As Word.Range _
) As Scripting.Dictionary

    Dim myTextRanges As Scripting.Dictionary
    Set myTextRanges = New Scripting.Dictionary

    Dim myBrackets As Variant
    myBrackets = Split(ipBrackets, ",")

    Dim myQuotes As Variant
    myQuotes = Split(ipQuotes, ",")

    With ipRange

        With .Find

            .ClearFormatting
            .Text = "[" & myBrackets(0) & "]*[" & myQuotes(0) & "]*[" & myQuotes(1) & "]" ' is there any need to process the following closing bracket
            .MatchWildcards = True
            .Wrap = wdFindStop

        End With

        Do While .Find.Execute

            Dim myFoundRange As Word.Range
            Set myFoundRange = .Duplicate
            With myFoundRange

                .MoveStartUntil cset:=myQuotes(0)
                ' Select the text within the quotes
                .MoveStart Count:=1
                .MoveEnd Count:=-1

            End With

            myTextRanges.Add myTextRanges.Count, myFoundRange
            ' Alternatively, if you just need the text
            'myTextRanges.add myTextRanges.count, myFoundRange.Text
            .Start = myFoundRange.End + 2
            .End = ipRange.End

        Loop

    End With

    Set GetTextInQuotesInBrackets = myTextRanges

End Function


问:
Google Sheets Array formula for counting the number of values in each column
I'm trying to create an array formula to auto-populate the total count of values for each column as columns are added.

I've tried doing this using a combination of count and indirect, as well as tried my hand at query, but I can't seem to get it to show unique value counts for each column.

This is my first time attempting to use query, and at first it seemed possible from reading through the documentation on the query language, but I haven't been able to figure it out.

Here's the shared document: https://docs.google.com/spreadsheets/d/15VwsL7uTsORLqBDrnT3VdwAWlXLh-JgoJVbz7wkoMAo/edit?usp=sharing

I know I can do this by writing a custom function in apps script, but I'd like to use the built-in functions if I can for performance reasons (there is going to be a lot of data), and I want quick refresh rates.

答:
try:

```<code>=ARRAYFORMULA(IF(B5:5="",,TRANSPOSE(MMULT(TRANSPOSE(N(B6:99<>"")), SIGN(ROW(B6:99))))))
</code>```

Body:
try:

=ARRAYFORMULA(IF(B5:5="",,TRANSPOSE(MMULT(TRANSPOSE(N(B6:99<>"")), SIGN(ROW(B6:99))))))


问:
Removing a SheduledAction with aws cli
How can I remove a scheduled action with the AWS CLI?

I can already create them with:

aws elasticbeanstalk update-environment --environment-name $myenv
  --option-settings file://my.json

my.json:

[ { "Namespace": "aws:autoscaling:scheduledaction", "OptionName":
  "MinSize", "Value": "1", "ResourceName": "MyResource" } ... ]

Now I would like to remove MyResource.

答:
The following has to be used:

aws elasticbeanstalk update-environment --environment-name $myenv --options-to-remove file://delete.json

Now the trick is that you have to list all of the properties (MinSize, MaxSize, Suspended, ...) you have set to the resource or else a misleading error is raised.

Title: Removing a SheduledAction with aws cli


问:
TypeError: Cannot find function includes in object
I have very little experience using Google Script but I was attempting to use it to search through one column of a spreadsheet and find all instances of the string "Film Dub" (knowing that there can be only one per cell).

Below is my code:

```<code>    function filmDub() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var data = sheet.getDataRange().getValues();
      for (var i = 1; i < 100; i++) {
        var s = data[i][2].toString();
        if (s.includes('Film Dub')) {
          data[5][13]++;
        }
      }
    }
</code>```

However I keep receiving the error

TypeError: Cannot find function includes in object Let's Make A Date, Film Dub, Three Headed Broadway Star, Film TV Theater Styles, Greatest Hits, World's Worst. (line 6, file "Code")

"Let's Make A Date, Film Dub, Three Headed Broadway Star, Film TV Theater Styles, Greatest Hits, World's Worst" is the correct content of data[i][2] so it is getting correct information from the spreadsheet. I have used the debugger in Google Script Editor to verify that s is a string (this was one of the solutions to similar questions here on Stack Overflow) but that didn't fix my problem. What else could be wrong with it?

答: Make sure your Sheet is running the current version of Apps Script. When you open the script editor you should see a yellow notice at the top that says "This project is running on our new Apps Script runtime powered by Chrome V8." If not, there should be an option to enable it. The includes function is new for Sheets scripting. You'll need to enable it individually for every Sheet in which you intend to use it.</p>

Body:
I have very little experience using Google Script but I was attempting to use it to search through one column of a spreadsheet and find all instances of the string "Film Dub" (knowing that there can be only one per cell).

Below is my code:

    function filmDub() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var data = sheet.getDataRange().getValues();
      for (var i = 1; i < 100; i++) {
        var s = data[i][2].toString();
        if (s.includes('Film Dub')) {
          data[5][13]++;
        }
      }
    }

However I keep receiving the error

TypeError: Cannot find function includes in object Let's Make A Date, Film Dub, Three Headed Broadway Star, Film TV Theater Styles, Greatest Hits, World's Worst. (line 6, file "Code")

"Let's Make A Date, Film Dub, Three Headed Broadway Star, Film TV Theater Styles, Greatest Hits, World's Worst" is the correct content of data[i][2] so it is getting correct information from the spreadsheet. I have used the debugger in Google Script Editor to verify that s is a string (this was one of the solutions to similar questions here on Stack Overflow) but that didn't fix my problem. What else could be wrong with it?


问:
Microsoft Azure Refresh Token Expires after 90 days
For a given user account on a customer's tenant, we followed the Microsoft Azure on-behalf-of procedure to grant Microsoft Graph permissions, including the offline_access scope, to our Web Application. We were then provided an access token and a refresh token. The user gave permission only once.

Everything went smoothly from then, for several months, then out of the blue we received an alert that the refresh token had expired after the 90-day inactivity period. Note that the refresh token was used within this window and for longer than 90 days.

Do you know why this happened? Is there a way to make a refresh token never expire, and if so, is that set on our side (Azure application) or on the customer's side?

What I do not understand is that we are theoretically in the "Token lifetime with confidential client refresh tokens" scenario described here (though I don't know how to check whether we are considered as a confidential client or not)

Note that unlike in this question, I have made sure that the refresh token is replaced with the new refresh token when making calls to https://login.microsoftonline.com/common/oauth2/v2.0/token

答:
the default lifetimes of refresh tokens issued to these flows is until-revoked, cannot be changed by using policy, and will not be revoked on voluntary password resets.

While refresh tokens are often long-lived, the authorization server can invalidate them. Some of the reasons a refresh token may no longer be valid include:

1.The authorization server has revoked the refresh token

2.The user has revoked their consent for authorization

3.The refresh token has expired(max inactive time is 90 days)

4.The authentication policy for the resource has changed (e.g., originally the resource only used usernames and passwords, but now it requires MFA)


问:
Why can't nativescript-geolocation resolve when building an APK for release?
I am using Svelte Native, which is an offshoot of NativeScript.  One of the libraries that I've imported has been nativescript-geolocation.

I've done this like so:  import * as geolocation from "nativescript-geolocation";

This works fine when I do a cloud build and test out on my phone using tns preview

When I try and build an APK using tns cloud build android it cannot resolve the nativescript-geolocation dependency.

I get the following error:

```<code>ERROR in ./App.svelte
Module not found: Error: Can't resolve 'nativescript-geolocation' in '/home/arthur/todoapp/app'
 @ ./App.svelte 14:0-56 68:1-34 72:1-26
 @ ./app.ts
</code>```

How can I get native-script geolocation to resolve?

答:
Seems like your build is missing the nativescript-geolocation dependency.

Running tns plugin add nativescript-geolocation should add it to package.json and fix the build.

I believe the reason it works in the preview version is that the Preview app has the geolocation plugin pre-installed.

Body:
I am using Svelte Native, which is an offshoot of NativeScript.  One of the libraries that I've imported has been nativescript-geolocation.

I've done this like so:  import * as geolocation from "nativescript-geolocation";

This works fine when I do a cloud build and test out on my phone using tns preview

When I try and build an APK using tns cloud build android it cannot resolve the nativescript-geolocation dependency.

I get the following error:

ERROR in ./App.svelte
Module not found: Error: Can't resolve 'nativescript-geolocation' in '/home/arthur/todoapp/app'
 @ ./App.svelte 14:0-56 68:1-34 72:1-26
 @ ./app.ts

How can I get native-script geolocation to resolve?


问:
How to set width of table td width
I want to have table cells of width 60 %, 20% and 20%, I use jquery I have added inline style as shown below. I tried setting display property to unset before it was table.

let $cell00 = $('').appendTo($row22).css({"width":"60%"});

They don't seem to have any effect they seem to be in 33%, 33% and 33% case.

How to get the td of width 60%, 20% and 20%?

function maintest () {

   table1();
   addClasses();
  }

 function table1 () {
    addClasses ();

    let h1 = $("
").html("Borrowed Features:").prop("class","underline").appendTo("#BorrowedTable");
    let $table1 = $('
').attr({"id" : "borrowed"}).appendTo("#BorrowedTable");
    let $row11 = $('
').appendTo($table1);
    let header1 = $('').text("Feature").appendTo($row11).css({"width":"60%"});
    let header12 = $('').text("Return Date").appendTo($row11).css({"width":"20%"});
    let $header22 = $('').appendTo($row11).css({"width":"20%"});
    $('<button>Return All Now</button>').appendTo($header22).css({"bottom":"20px","position":"relative"});

    for( i=0 ; i < 3 ; i++ ) {
        let $row22 = $('
').appendTo($table1);
        let $cell00 = $('').appendTo($row22).css({"width":"50%"});
        let $autocomplete12 = $("<input>").attr({"id" : "selector"+i+1,"class":"biscuitColorInput"}).appendTo($cell00);

        let $cell11 = $('').appendTo($row22).css({"width":"20%"});
        let $autocomplete22 = $("<input>").attr({"id" : "date"+i+1,"class":"biscuitColorInput"}).appendTo($cell11);

        let $cell22 = $('').appendTo($row22).css({"width":"20%"});
        let $autocomplete33 = $("<button> Return Now </button>").attr("id" , "returnBtns"+i+1).appendTo($cell22).css({"bottom":"20px","position":"relative"});

    }

}

function addClasses () {
    let tableRows = $('tr').addClass('tableRows');
    let tableDefn = $('td').attr({"class":"tableDefn"});
    let tableHeader = $('th').attr({"class":"tableHeader"});
    let tbodyDOM = $('tbody').attr({"class" : "tbodyDOM"});
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#buttonsdiv {
     height: unset !important;
     width:50%;
     position: relative;
     left :50px !important;
     bottom :0px !important;
     background-color: papayawhip !important;
  }

  #BorrowedTable, #BorrowableTable {
    display: flex !important;
    flex-direction: column;
    height:fit-content !important;

  }

    #borrowed , #borrowable {
      display: unset !important;
      border-collapse: collapse;
      border-spacing :unset !important;
      margin-left:100px;
  }

  #BorrowedTable,.biscuitColorInput {
    background-color: sandybrown;
  }

  #BorrowableTable,.creamcolorInput,#buttonsdiv {
    background-color: papayawhip;

  }

.tableRows, .tableDefn, .tableHeader { /*added from addClasses() */

      padding: 0;
      margin: 0;
      font-family: ffunit;
      font-size: 14px;
      font-weight: bold;
      padding-right: 50px !important;
    }

   button {
      height:36px;
      width:205px;
      cursor: pointer;
      border: solid 1px;
      background-color:#f2a900;
      font-family: ffunit;
      font-size: 14px;
      margin-top:20px;
      margin-left: 1px;
  }

  input {
    height: 30px;
    width: 100%;
    font-size: 20px;
    text-indent: 6px;

  }</code>```

```

new image

答:
Seems like you have set

```<code>display:flex;
</code>```

on table. Instead don't set display on table and give it some width either in percentage or in pixels. After this if you give width in percentage to td it should work.

Title: How to set width of table td width

Body:
I want to have table cells of width 60 %, 20% and 20%, I use jquery I have added inline style as shown below. I tried setting display property to unset before it was table.

let $cell00 = $('').appendTo($row22).css({"width":"60%"});

They don't seem to have any effect they seem to be in 33%, 33% and 33% case.

How to get the td of width 60%, 20% and 20%?

function maintest () {

   table1();
   addClasses();
  }

 function table1 () {
    addClasses ();

    let h1 = $("
").html("Borrowed Features:").prop("class","underline").appendTo("#BorrowedTable");
    let $table1 = $('
').attr({"id" : "borrowed"}).appendTo("#BorrowedTable");
    let $row11 = $('
').appendTo($table1);
    let header1 = $('').text("Feature").appendTo($row11).css({"width":"60%"});
    let header12 = $('').text("Return Date").appendTo($row11).css({"width":"20%"});
    let $header22 = $('').appendTo($row11).css({"width":"20%"});
    $('<button>Return All Now</button>').appendTo($header22).css({"bottom":"20px","position":"relative"});

    for( i=0 ; i < 3 ; i++ ) {
        let $row22 = $('
').appendTo($table1);
        let $cell00 = $('').appendTo($row22).css({"width":"50%"});
        let $autocomplete12 = $("<input>").attr({"id" : "selector"+i+1,"class":"biscuitColorInput"}).appendTo($cell00);

        let $cell11 = $('').appendTo($row22).css({"width":"20%"});
        let $autocomplete22 = $("<input>").attr({"id" : "date"+i+1,"class":"biscuitColorInput"}).appendTo($cell11);

        let $cell22 = $('').appendTo($row22).css({"width":"20%"});
        let $autocomplete33 = $("<button> Return Now </button>").attr("id" , "returnBtns"+i+1).appendTo($cell22).css({"bottom":"20px","position":"relative"});

    }

}

function addClasses () {
    let tableRows = $('tr').addClass('tableRows');
    let tableDefn = $('td').attr({"class":"tableDefn"});
    let tableHeader = $('th').attr({"class":"tableHeader"});
    let tbodyDOM = $('tbody').attr({"class" : "tbodyDOM"});
}

#buttonsdiv {
     height: unset !important;
     width:50%;
     position: relative;
     left :50px !important;
     bottom :0px !important;
     background-color: papayawhip !important;
  }

  #BorrowedTable, #BorrowableTable {
    display: flex !important;
    flex-direction: column;
    height:fit-content !important;

  }

    #borrowed , #borrowable {
      display: unset !important;
      border-collapse: collapse;
      border-spacing :unset !important;
      margin-left:100px;
  }

  #BorrowedTable,.biscuitColorInput {
    background-color: sandybrown;
  }

  #BorrowableTable,.creamcolorInput,#buttonsdiv {
    background-color: papayawhip;

  }

.tableRows, .tableDefn, .tableHeader { /*added from addClasses() */

      padding: 0;
      margin: 0;
      font-family: ffunit;
      font-size: 14px;
      font-weight: bold;
      padding-right: 50px !important;
    }

   button {
      height:36px;
      width:205px;
      cursor: pointer;
      border: solid 1px;
      background-color:#f2a900;
      font-family: ffunit;
      font-size: 14px;
      margin-top:20px;
      margin-left: 1px;
  }

  input {
    height: 30px;
    width: 100%;
    font-size: 20px;
    text-indent: 6px;

  }

new image

Body:
Seems like you have set

display:flex;

on table. Instead don't set display on table and give it some width either in percentage or in pixels. After this if you give width in percentage to td it should work.


问:
What's the best way to hide a tab in a TabNavigator?
I'd like to conditionally hide a tab in a TabNavigator.  It seems that setting visible doesn't work properly (presumably because this is how the TabNavigator hides the tabs that aren't currently selected).

What's the right way to do this?

答:
```<code>var secondTab = tabNavigator.removeChildAt(0);
</code>```

ContentLicense: CC BY-SA 2.5


问:
Automatically fetch component,result file name in the mos script
Using a mos script, I am reading and plotting the data of certain variables that belong to a component 'x' in my model. If the component name is changed from 'x' to 'y', how can it be updated automatically in the script? I would like to write a flexible script so that it can be used even though the name of the result file or component is changed.

Thanks a lot.

答:
It is (currently) not possible to do this automatically in Dymola.

You might be able to reduce the problem by creating a variable for the expression, Real mySdd=kinematicPTP.sdd; and then plot mySdd. Renaming kinematicPTP will not cause any problems in this case. (Obviously renaming mySdd causes the same problems, but the idea would be that those names are more stable.)


问:
ID Save and Display Name - material ui multiselect with chips
I am using Material UI Multiple Select based on documentation example. I need to save id of the selected option and show name,
I have tried many ways but nothing helps.
I need to store the id and Display the value. Please help me with your guidance.

Here is my codesandbox link

答:
I was wondering about the same and the only way I found to make it work is by transforming the array to an object.

Here goes the sandbox: https://codesandbox.io/s/material-demo-5cy6p

In it you can see how names is no longer an array but an object with the value of the menu option as a key and the name you want to actual show as the value:

```<code>const names = {
 1: 'Lorem',
 2: 'Ipsum',
}
</code>```

This way you can access the value(the name) in O(1) time (if you are not familiar with the Big O notation gives this a read: https://en.wikipedia.org/wiki/Big_O_notation), this is way faster than going through the whole array looking for an object with the same id as the one you are mapping.

Body:
I was wondering about the same and the only way I found to make it work is by transforming the array to an object.

Here goes the sandbox: https://codesandbox.io/s/material-demo-5cy6p

In it you can see how names is no longer an array but an object with the value of the menu option as a key and the name you want to actual show as the value:

const names = {
 1: 'Lorem',
 2: 'Ipsum',
}

This way you can access the value(the name) in O(1) time (if you are not familiar with the Big O notation gives this a read: https://en.wikipedia.org/wiki/Big_O_notation), this is way faster than going through the whole array looking for an object with the same id as the one you are mapping.


问:
VueJS csv Filereader
I'm trying to get the input of a .csv File, after I choose it with my Html 5 input field. Therefor I use a onFileChange method and a FileReader().
Here is an example I used: http://codepen.io/Atinux/pen/qOvawK/ (except that I want to read the text input, and not an image file).

My Problem is, that I get an empty input on the first try, but on the second try it works. Why is that? Any ideas? (I'm a javascript beginner ;) )

html:

```<code><form enctype="multipart/form-data">
    <input type="file" @change="onFileChange">
</form>
</code>```

js:

```<code>new Vue({
    el: '#app',
    data: {
        fileinput: ''
    },
    methods: {
        onFileChange(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length)
                return;
            this.createInput(files[0]);
        },
        createInput(file) {
            var reader = new FileReader();
            var vm = this;
            reader.onload = (e) => {

            vm.fileinput = reader.result;
            }
            reader.readAsText(file);

            console.log(this.fileinput);
        }

    }
})
</code>```

答:
Here you can handle async code using Promise function

```<code>new Vue({
  el: "#app",
  data: {
    fileinput: ""
  },
  methods: {
    onFileChange(e) {
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.createInput(files[0]);
    },
    createInput(file) {
      let promise = new Promise((resolve, reject) => {
        var reader = new FileReader();
        var vm = this;
        reader.onload = e => {
          resolve((vm.fileinput = reader.result));
        };
        reader.readAsText(file);
      });

      promise.then(
        result => {
          /* handle a successful result */
          console.log(this.fileinput);
        },
        error => {
          /* handle an error */
          console.log(error);
        }
      );
    }
  }
});
</code>```

Title: VueJS csv Filereader

Body:
I'm trying to get the input of a .csv File, after I choose it with my Html 5 input field. Therefor I use a onFileChange method and a FileReader().
Here is an example I used: http://codepen.io/Atinux/pen/qOvawK/ (except that I want to read the text input, and not an image file).

My Problem is, that I get an empty input on the first try, but on the second try it works. Why is that? Any ideas? (I'm a javascript beginner ;) )

html:

<form enctype="multipart/form-data">
    <input type="file" @change="onFileChange">
</form>

js:

new Vue({
    el: '#app',
    data: {
        fileinput: ''
    },
    methods: {
        onFileChange(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length)
                return;
            this.createInput(files[0]);
        },
        createInput(file) {
            var reader = new FileReader();
            var vm = this;
            reader.onload = (e) => {

            vm.fileinput = reader.result;
            }
            reader.readAsText(file);

            console.log(this.fileinput);
        }

    }
})

Body:
Here you can handle async code using Promise function

new Vue({
  el: "#app",
  data: {
    fileinput: ""
  },
  methods: {
    onFileChange(e) {
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.createInput(files[0]);
    },
    createInput(file) {
      let promise = new Promise((resolve, reject) => {
        var reader = new FileReader();
        var vm = this;
        reader.onload = e => {
          resolve((vm.fileinput = reader.result));
        };
        reader.readAsText(file);
      });

      promise.then(
        result => {
          /* handle a successful result */
          console.log(this.fileinput);
        },
        error => {
          /* handle an error */
          console.log(error);
        }
      );
    }
  }
});


问:
How to get the coordinates of point where I clicked while using Select interaction?
We use Vue.js and OpenLayers (4.6.5) in our web project. We have a lot of features on the map and some of them are polygons. When I select some particular polygon, its style turns to another color, which means it's highlighted (selected). Of course, I can get the coordinates of selected polygon. But, how can I get the coordinates of point inside that polygon where I clicked?

The code look as following:

```<code>markObject (mark) {
  if (!mark) {
    this.map.un('select', this.onMarkObject)
    if (this.markSelection) {
      this.markSelection.getFeatures().remove(this.lastSelectedFeature)
      this.map.removeInteraction(this.markSelection)
    }
    return
  }

  if (!this.markSelection) {
    this.markSelection = new Select({
      condition: condition.click,
      layers: [this.vectorLayer]
    })
    this.markSelection.on('select', this.onMarkObject)
  }

  this.map.addInteraction(this.markSelection)
},
onMarkObject (event) {
  if (event.selected && event.selected.length > 0) {
    const coordinates = event.selected[0].getGeometry().getCoordinates()
  }
}
</code>```

答:
Actually, I've found the solution:

```<code>onMarkObject (event) {
    const clickCoordinates = event.mapBrowserEvent.coordinate
    ...
}
</code>```

Thank you anyway.

Body:
We use Vue.js and OpenLayers (4.6.5) in our web project. We have a lot of features on the map and some of them are polygons. When I select some particular polygon, its style turns to another color, which means it's highlighted (selected). Of course, I can get the coordinates of selected polygon. But, how can I get the coordinates of point inside that polygon where I clicked?

The code look as following:

markObject (mark) {
  if (!mark) {
    this.map.un('select', this.onMarkObject)
    if (this.markSelection) {
      this.markSelection.getFeatures().remove(this.lastSelectedFeature)
      this.map.removeInteraction(this.markSelection)
    }
    return
  }

  if (!this.markSelection) {
    this.markSelection = new Select({
      condition: condition.click,
      layers: [this.vectorLayer]
    })
    this.markSelection.on('select', this.onMarkObject)
  }

  this.map.addInteraction(this.markSelection)
},
onMarkObject (event) {
  if (event.selected && event.selected.length > 0) {
    const coordinates = event.selected[0].getGeometry().getCoordinates()
  }
}

Body:
Actually, I've found the solution:

onMarkObject (event) {
    const clickCoordinates = event.mapBrowserEvent.coordinate
    ...
}

Thank you anyway.


问:
Take picture and convert to Base64
I use code below to make a picture with camera. Instead of saving I would like to encode it to Base64 and after that pass it to another API as an input. I can't see method, how to modify code to take pictures in Base64 instead of regular files.

```<code>public class CameraDemoActivity extends Activity {
    int TAKE_PHOTO_CODE = 0;
    public static int count = 0;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        File newdir = new File(dir);
        newdir.mkdirs();

        Button capture = (Button) findViewById(R.id.btnCapture);
        capture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                count++;
                String file = dir+count+".jpg";
                File newfile = new File(file);
                try {
                    newfile.createNewFile();
                }
                catch (IOException e)
                {
                }

                Uri outputFileUri = Uri.fromFile(newfile);

                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

                startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            Log.d("CameraDemo", "Pic saved");
        }
    }
}
</code>```

I try to use code below to convert an image to Base64.

```<code>public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality)
{
    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    image.compress(compressFormat, quality, byteArrayOS);
    return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);
}
</code>```

Above described should be a much more direct and easier way than saving image and after that looking for image to encode it.

答:
Just for converting from bitmap to base64 string in kotlin I use:</p>

```<code>private fun encodeImage(bm: Bitmap): String? {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val b = baos.toByteArray()
        return Base64.encodeToString(b, Base64.DEFAULT)
    }
</code>```

Title: Take picture and convert to Base64

Body:
I use code below to make a picture with camera. Instead of saving I would like to encode it to Base64 and after that pass it to another API as an input. I can't see method, how to modify code to take pictures in Base64 instead of regular files.

public class CameraDemoActivity extends Activity {
    int TAKE_PHOTO_CODE = 0;
    public static int count = 0;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        File newdir = new File(dir);
        newdir.mkdirs();

        Button capture = (Button) findViewById(R.id.btnCapture);
        capture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                count++;
                String file = dir+count+".jpg";
                File newfile = new File(file);
                try {
                    newfile.createNewFile();
                }
                catch (IOException e)
                {
                }

                Uri outputFileUri = Uri.fromFile(newfile);

                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

                startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            Log.d("CameraDemo", "Pic saved");
        }
    }
}

I try to use code below to convert an image to Base64.

public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality)
{
    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    image.compress(compressFormat, quality, byteArrayOS);
    return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);
}

Above described should be a much more direct and easier way than saving image and after that looking for image to encode it.

Body:
Just for converting from bitmap to base64 string in kotlin I use:

private fun encodeImage(bm: Bitmap): String? {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val b = baos.toByteArray()
        return Base64.encodeToString(b, Base64.DEFAULT)
    }


问:
SQL server 2005 can't reference column that has been "casted"
this query works:

```<code>select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0
order by sifra
</code>```

but if I want to see only only when sifra = 5 I get "Invalid column name 'sifra'."

```<code>select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0 and sifra = 5
order by sifra
</code>```

I tryed wraping working sql statement in another select and then using "where sifra = 5" it also fails..

答:
Because there is no column named sifra. You either cast in the where clause as well

```<code>select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0 and CAST(ist_sifra as float ) = 5
order by sifra
</code>```

or refer the uncasted column

```<code>select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0 and ist_sifra = 5
order by sifra
</code>```

Body:
this query works:

select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0
order by sifra

but if I want to see only only when sifra = 5 I get "Invalid column name 'sifra'."

select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0 and sifra = 5
order by sifra

I tryed wraping working sql statement in another select and then using "where sifra = 5" it also fails..

Body:
Because there is no column named sifra. You either cast in the where clause as well

select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0 and CAST(ist_sifra as float ) = 5
order by sifra

or refer the uncasted column

select ist_id,  ist_opis , CAST(ist_sifra as float ) as sifra
from IZOBRAZBENA_STOPNJA
where ist_aktivno<>0 and ist_sifra = 5
order by sifra


问:
Creating a list column in a dataframe based on values in another dataframe
I have two DataFrames:

df1:

```<code>       node        ids
0   ab          [978]
1   bc          [978, 121]
</code>```

df2:

```<code>       name        id
0   alpha          978
1   bravo          121
</code>```

I would like to add a new column called names in df1 where I get the list of names corresponding to ids column like this

```<code>   node            ids             names
0   ab            [978]            [alpha]
1   bc            [978, 121]       [alpha,bravo]
</code>```

Would apprreciate help.

答:
Use if both id values are integers (or both strings, same types):

```<code>d = df2.set_index('id')['name'].to_dict()
df1['names'] = [[d.get(y) for y in x] for x in df1['ids']]
print (df1)
  node         ids           names
0   ab       [978]         [alpha]
1   bc  [978, 121]  [alpha, bravo]
</code>```

If possible value in list not match value of df2['id'] is replaced some no match value:

```<code>d = df2.set_index('id')['name'].to_dict()
df1['names'] = [[d.get(y, 'no match') for y in x] for x in df1['ids']]
print (df1)
  node         ids              names
0   ab   [978, 10]  [alpha, no match]
1   bc  [978, 121]     [alpha, bravo]
</code>```

Or is possible omit this values:

```<code>d = df2.set_index('id')['name'].to_dict()
df1['names'] = [[d[y] for y in x if y in d.keys()] for x in df1['ids']]
print (df1)
  node         ids           names
0   ab   [978, 10]         [alpha]
1   bc  [978, 121]  [alpha, bravo]
</code>```

Body:
I have two DataFrames:

df1:

       node        ids
0   ab          [978]
1   bc          [978, 121]

df2:

       name        id
0   alpha          978
1   bravo          121

I would like to add a new column called names in df1 where I get the list of names corresponding to ids column like this

   node            ids             names
0   ab            [978]            [alpha]
1   bc            [978, 121]       [alpha,bravo]

Would apprreciate help.

Body:
Use if both id values are integers (or both strings, same types):

d = df2.set_index('id')['name'].to_dict()
df1['names'] = [[d.get(y) for y in x] for x in df1['ids']]
print (df1)
  node         ids           names
0   ab       [978]         [alpha]
1   bc  [978, 121]  [alpha, bravo]

If possible value in list not match value of df2['id'] is replaced some no match value:

d = df2.set_index('id')['name'].to_dict()
df1['names'] = [[d.get(y, 'no match') for y in x] for x in df1['ids']]
print (df1)
  node         ids              names
0   ab   [978, 10]  [alpha, no match]
1   bc  [978, 121]     [alpha, bravo]

Or is possible omit this values:

d = df2.set_index('id')['name'].to_dict()
df1['names'] = [[d[y] for y in x if y in d.keys()] for x in df1['ids']]
print (df1)
  node         ids           names
0   ab   [978, 10]         [alpha]
1   bc  [978, 121]  [alpha, bravo]


问:
Context error while testing RESTful API URL in Django
Dear community and forum,

I am in charge of developing RESTful API URLs for a website project. However, when it comes to testing I have got that error:

```<code>self = HyperlinkedIdentityField('api:request')
value = <ResourceRequest: JoKLLwwKqxrkrwWmcjOWzIscGzpsbgWJqRAOZabnwxQpiEDRfifeZhvzpRRp...ewyOFcaQVhchYNVIhUoiWBzKMrFYvYQBMNRZsLFfOZSjclHUXwyXZQHxjMtbHvWefMIlyZqvTvXqiu>

 def to_representation(self, value):
    assert 'request' in self.context, (
        "`%s` requires the request in the serializer"
        " context. Add `context={'request': request}` when instantiating "
           "the serializer." % self.__class__.__name__
    )
E       AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.

/usr/lib/python2.7/site-packages/rest_framework/relations.py:351: AssertionError
</code>```

The serialiser is (sorry for the ugly code so far):

```<code>class ResourceRequestSerializer(serializers.ModelSerializer):
    # context = self.kwargs.get('context', None)
    # request = kwargs['context']['request']
    # print(kwargs)
    view_name = 'api:request'
    url = serializers.HyperlinkedIdentityField(view_name)
    # print(self)
    # url = URLField(view_name=view_name, read_only=True, many=True)
    # url = serializers.SerializerMethodField()
    support_level = serializers.SerializerMethodField()
    originator = BriefUCLProfileSerializer(source='originator.ucl_profile')
    sponsor = BriefUCLProfileSerializer()
    versioned_dependencies = serializers.StringRelatedField(many=True)
    types_of_work = serializers.StringRelatedField(many=True)
    previous = serializers.SerializerMethodField()
    status_history = RequestStatusChangeSerializer(many=True)
</code>```

For the test:

```<code># Change the status through a POST request
response = self.app.post(
    reverse(
        'api:request',
        args=[request1.pk],
    ),
    params={
        'context': request1,
        'format': 'json',
        'status': ResourceRequest.STATUS_APPROVED,
    },
    # context=request1,
    headers=self.auth_headers,
)
</code>```

I am still wondering if the context has to be passed from within the serialiser or from the test.

Here is the view too:

```<code>class ResourceRequestAPIView(RetrieveAPIView):
"""Retrieve an individual resource request by pk and optionally update status"""
serializer_class = ResourceRequestSerializer
permission_classes = (IsAuthenticated,)
authentication_classes = (TokenAuthentication, SessionAuthentication)

def get_object(self):
    try:
        return ResourceRequest.objects.get(pk=self.kwargs.get('pk'))
    except ResourceRequest.DoesNotExist:
        raise Http404

def post(self, request, *args, **kwargs):
    resource_request = self.get_object()
    status = request.data['status']
    if status != ResourceRequest.STATUS_SUBMITTED:
        # Change the status
        resource_request.set_status(status,
                                    request.user)
        # And send emails
        request_url = request.build_absolute_uri(
            reverse('api:request', args=[resource_request.pk])
        )
        send_emails(resource_request,
                    request_url=request_url,
        )
    serializer = ResourceRequestSerializer(resource_request)
    return Response(serializer.data)
</code>```

Any help greatly appreciated !

Thank you

Roland

答:
Right, so with that viewset in hand, you'll have to initialize the serializer with the context:

```<code>serializer = ResourceRequestSerializer(
   resource_request,
   context=self.get_serializer_context(),
)
</code>```

get_serializer_context() is provided by default by DRF viewsets.

Body:
Dear community and forum,

I am in charge of developing RESTful API URLs for a website project. However, when it comes to testing I have got that error:

self = HyperlinkedIdentityField('api:request')
value = <ResourceRequest: JoKLLwwKqxrkrwWmcjOWzIscGzpsbgWJqRAOZabnwxQpiEDRfifeZhvzpRRp...ewyOFcaQVhchYNVIhUoiWBzKMrFYvYQBMNRZsLFfOZSjclHUXwyXZQHxjMtbHvWefMIlyZqvTvXqiu>

 def to_representation(self, value):
    assert 'request' in self.context, (
        "`%s` requires the request in the serializer"
        " context. Add `context={'request': request}` when instantiating "
           "the serializer." % self.__class__.__name__
    )
E       AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.

/usr/lib/python2.7/site-packages/rest_framework/relations.py:351: AssertionError

The serialiser is (sorry for the ugly code so far):

class ResourceRequestSerializer(serializers.ModelSerializer):
    # context = self.kwargs.get('context', None)
    # request = kwargs['context']['request']
    # print(kwargs)
    view_name = 'api:request'
    url = serializers.HyperlinkedIdentityField(view_name)
    # print(self)
    # url = URLField(view_name=view_name, read_only=True, many=True)
    # url = serializers.SerializerMethodField()
    support_level = serializers.SerializerMethodField()
    originator = BriefUCLProfileSerializer(source='originator.ucl_profile')
    sponsor = BriefUCLProfileSerializer()
    versioned_dependencies = serializers.StringRelatedField(many=True)
    types_of_work = serializers.StringRelatedField(many=True)
    previous = serializers.SerializerMethodField()
    status_history = RequestStatusChangeSerializer(many=True)

For the test:

# Change the status through a POST request
response = self.app.post(
    reverse(
        'api:request',
        args=[request1.pk],
    ),
    params={
        'context': request1,
        'format': 'json',
        'status': ResourceRequest.STATUS_APPROVED,
    },
    # context=request1,
    headers=self.auth_headers,
)

I am still wondering if the context has to be passed from within the serialiser or from the test.

Here is the view too:

class ResourceRequestAPIView(RetrieveAPIView):
"""Retrieve an individual resource request by pk and optionally update status"""
serializer_class = ResourceRequestSerializer
permission_classes = (IsAuthenticated,)
authentication_classes = (TokenAuthentication, SessionAuthentication)

def get_object(self):
    try:
        return ResourceRequest.objects.get(pk=self.kwargs.get('pk'))
    except ResourceRequest.DoesNotExist:
        raise Http404

def post(self, request, *args, **kwargs):
    resource_request = self.get_object()
    status = request.data['status']
    if status != ResourceRequest.STATUS_SUBMITTED:
        # Change the status
        resource_request.set_status(status,
                                    request.user)
        # And send emails
        request_url = request.build_absolute_uri(
            reverse('api:request', args=[resource_request.pk])
        )
        send_emails(resource_request,
                    request_url=request_url,
        )
    serializer = ResourceRequestSerializer(resource_request)
    return Response(serializer.data)

Any help greatly appreciated !

Thank you

Roland

Body:
Right, so with that viewset in hand, you'll have to initialize the serializer with the context:

serializer = ResourceRequestSerializer(
   resource_request,
   context=self.get_serializer_context(),
)

get_serializer_context() is provided by default by DRF viewsets.


问:
Response is not showing while fetching data from an api
I am trying to fetch data from an api but I am getting an following error I am unable to find out where the problem is I am using separate UI thread to fetech data then too app crashes.

```<code>2020-02-20 17:20:01.088 22802-22802/com.example.flypped E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.flypped, PID: 22802
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.read(Exchange.kt:279)
    at okio.RealBufferedSource.select(RealBufferedSource.kt:93)
    at okhttp3.internal.Util.readBomAsCharset(Util.kt:256)
    at okhttp3.ResponseBody.string(ResponseBody.kt:187)
    at com.example.flypped.MainActivity$2$1.run(MainActivity.java:110)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7156)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
    Suppressed: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.Util.skipAll(Util.kt:337)
    at okhttp3.internal.Util.discard(Util.kt:358)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.close(Http1ExchangeCodec.kt:471)
    at okio.ForwardingSource.close(ForwardingSource.kt:34)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.close(Exchange.kt:306)
    at okio.RealBufferedSource.close(RealBufferedSource.kt:461)
    at kotlin.io.CloseableKt.closeFinally(Closeable.kt:56)
    at okhttp3.ResponseBody.string(ResponseBody.kt:186)
</code>```

Below is my code:

XML code:

```<code> <?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">

<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</com.google.android.material.appbar.AppBarLayout>

<include layout="@layout/content_main" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/bottomBar"
    android:layout_gravity="bottom"
    app:menu="@menu/bottom_menu"
    android:background="#fff"
    app:itemIconTint="@drawable/nav_check"
    app:itemTextColor="@drawable/nav_check"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

<com.google.android.material.navigation.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:id="@+id/nav_view">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include
            layout="@layout/nav_header"
            android:id="@+id/header"/>

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/header"
            android:id="@+id/menuRecycler"
            android:layout_marginTop="20dp"/>

    </RelativeLayout>

</com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

Java code:

```<code> private void getMenuData(){

    OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    Request request = new Request.Builder().url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());

                      //  Log.d("array", String.valueOf(jsonArray));

                       if(jsonArray.length() > 0){

                            for(int i=0;i<jsonArray.length();i++){

                                JSONObject jsonObject = jsonArray.getJSONObject(i);

                                String str1 = jsonObject.getString("name");
                                String str2 = jsonObject.getString("term_id");

                                MenuModel model = new MenuModel(str1,str2);
                                list.add(model);
                            }

                            adapter = new MenuAdapter(list,getApplicationContext());
                            menuRecycler.setAdapter(adapter);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }

    });

}
</code>```

Log cat showing error in below line

```<code>JSONArray jsonArray = new JSONArray(response.body().string());
</code>```

Someone please let me know what I am doing wrong.Any help would be appreciated.

THANKS

答:
Callbacks run on a background thread. If you want to immediately process something in the UI you will need to post to the main thread.</p>

```<code>private void hitApi(HttpCallBacks cb){
client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            mainHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        cb.onSuccess(null, throwable);
                    }
                });

        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

             mainHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        cb.onFailure( throwable);
                    }
                });
        }

    });

}
}
interface HttpCallBacks{
    void onFailure(Throwable t);
    void onSuccess(Response r);

}
</code>```

Body:
I am trying to fetch data from an api but I am getting an following error I am unable to find out where the problem is I am using separate UI thread to fetech data then too app crashes.

2020-02-20 17:20:01.088 22802-22802/com.example.flypped E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.flypped, PID: 22802
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.read(Exchange.kt:279)
    at okio.RealBufferedSource.select(RealBufferedSource.kt:93)
    at okhttp3.internal.Util.readBomAsCharset(Util.kt:256)
    at okhttp3.ResponseBody.string(ResponseBody.kt:187)
    at com.example.flypped.MainActivity$2$1.run(MainActivity.java:110)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7156)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
    Suppressed: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.Util.skipAll(Util.kt:337)
    at okhttp3.internal.Util.discard(Util.kt:358)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.close(Http1ExchangeCodec.kt:471)
    at okio.ForwardingSource.close(ForwardingSource.kt:34)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.close(Exchange.kt:306)
    at okio.RealBufferedSource.close(RealBufferedSource.kt:461)
    at kotlin.io.CloseableKt.closeFinally(Closeable.kt:56)
    at okhttp3.ResponseBody.string(ResponseBody.kt:186)

Below is my code:

XML code:

 <?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">

<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</com.google.android.material.appbar.AppBarLayout>

<include layout="@layout/content_main" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/bottomBar"
    android:layout_gravity="bottom"
    app:menu="@menu/bottom_menu"
    android:background="#fff"
    app:itemIconTint="@drawable/nav_check"
    app:itemTextColor="@drawable/nav_check"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

<com.google.android.material.navigation.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:id="@+id/nav_view">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include
            layout="@layout/nav_header"
            android:id="@+id/header"/>

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/header"
            android:id="@+id/menuRecycler"
            android:layout_marginTop="20dp"/>

    </RelativeLayout>

</com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

Java code:

 private void getMenuData(){

    OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    Request request = new Request.Builder().url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());

                      //  Log.d("array", String.valueOf(jsonArray));

                       if(jsonArray.length() > 0){

                            for(int i=0;i<jsonArray.length();i++){

                                JSONObject jsonObject = jsonArray.getJSONObject(i);

                                String str1 = jsonObject.getString("name");
                                String str2 = jsonObject.getString("term_id");

                                MenuModel model = new MenuModel(str1,str2);
                                list.add(model);
                            }

                            adapter = new MenuAdapter(list,getApplicationContext());
                            menuRecycler.setAdapter(adapter);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }

    });

}

Log cat showing error in below line

JSONArray jsonArray = new JSONArray(response.body().string());

Someone please let me know what I am doing wrong.Any help would be appreciated.

THANKS

Body:
Callbacks run on a background thread. If you want to immediately process something in the UI you will need to post to the main thread.

private void hitApi(HttpCallBacks cb){
client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            mainHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        cb.onSuccess(null, throwable);
                    }
                });

        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

             mainHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        cb.onFailure( throwable);
                    }
                });
        }

    });

}
}
interface HttpCallBacks{
    void onFailure(Throwable t);
    void onSuccess(Response r);

}