问:
Angular - Life-cycle: Child component to be fully loaded
Is it possible for a parent component to be notified for a child component to be loaded especially when it comes to ng-container and ng-template.

As in Yes! I see that you've grown strong, my child!

Say we have a component like this:

@Component({
  selector: 'my-app',
  template: `
  <ng-container *ngIf="!showElse; else elseBlock">

Hi!

  </ng-container>
  <ng-template #elseBlock>
    <hello name="{{ name }}"></hello>
  </ng-template>
  <button (click)="showElse = !showElse">Show else</button>
  `,
  styles: ['']
})
export class AppComponent  {
  name = 'Angular';
  showElse = false;
  @ViewChild('hello') hello: HelloComponent;
}
```

Is there a way for AppComponent to know if HelloComponentis fully loaded or do I need a custom solution inside HelloComponent?

I'm currently sitting with a less-than-optimal solution (a setTimeout() based stuff that I don't like).

Here's what I'm thinking about:

- Add an EventEmitter to my HelloComponent;

- Use the HelloComponent's life cycle to emit an event during, say, ngAfterContentChecked

- Intercept this event in my AppComponent and do the thing.

What are your thoughts on that subject?

Edit

So far, I've tried what you've suggested (hook to AfterViewInit, make use of @ViewChildren...) but had no success.

Just to be sure, I tried again without the <ng-container>...<ng-template> stuff and simply hiding my HelloComponent using the [hidden] directive...

By emitting an event during the HelloComponent's AfterContentChecked and hooking this event in AppComponent, it works like a charm. (see on stackblitz )

This solution is way more classy than my previous setTimeout-based one

Now, the reason I wanted to make use of the <ng-container>...<ng-template> mechanic is because my actual component is just a tiny bit heavier than the example HelloComponent.

If anyone has a better idea to keep using the container-template mechanic, I'm all ears.

答:
Like you suggested, use an EventEmitter in the lifecycle hook AfterContentChecked() to emit an event to your parent component.  It's straightforward, and makes proper use of Angular's lifecycle API.
https://angular.io/guide/lifecycle-hooks#lifecycle-sequence</p>

Body:
Is it possible for a parent component to be notified for a child component to be loaded especially when it comes to ng-container and ng-template.

As in Yes! I see that you've grown strong, my child!

Say we have a component like this:

@Component({
  selector: 'my-app',
  template: `
  <ng-container *ngIf="!showElse; else elseBlock">

Hi!

  </ng-container>
  <ng-template #elseBlock>
    <hello name="{{ name }}"></hello>
  </ng-template>
  <button (click)="showElse = !showElse">Show else</button>
  `,
  styles: ['']
})
export class AppComponent  {
  name = 'Angular';
  showElse = false;
  @ViewChild('hello') hello: HelloComponent;
}

Is there a way for AppComponent to know if HelloComponentis fully loaded or do I need a custom solution inside HelloComponent?

I'm currently sitting with a less-than-optimal solution (a setTimeout() based stuff that I don't like).

Here's what I'm thinking about:

- Add an EventEmitter to my HelloComponent;

- Use the HelloComponent's life cycle to emit an event during, say, ngAfterContentChecked

- Intercept this event in my AppComponent and do the thing.

What are your thoughts on that subject?

Edit

So far, I've tried what you've suggested (hook to AfterViewInit, make use of @ViewChildren...) but had no success.

Just to be sure, I tried again without the <ng-container>...<ng-template> stuff and simply hiding my HelloComponent using the [hidden] directive...

By emitting an event during the HelloComponent's AfterContentChecked and hooking this event in AppComponent, it works like a charm. (see on stackblitz )

This solution is way more classy than my previous setTimeout-based one

Now, the reason I wanted to make use of the <ng-container>...<ng-template> mechanic is because my actual component is just a tiny bit heavier than the example HelloComponent.

If anyone has a better idea to keep using the container-template mechanic, I'm all ears.


来源: stackexchange

问:
Prevent dispatch_after() background task from being executed
This is my issue. When my application enters background I want it to perform a function after certain period of time. This is what I do:

```<code>- (void)applicationDidEnterBackground:(UIApplication *)application
{
    isRunningInBackground = YES;

    taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];

    int64_t delayInSeconds = 30;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
    {
        [self doSomething];
    });
}

- (void)doSomething
{
   NSLog(@"HELLO");
}
</code>```

taskIdentifier variable is declared in myAppDelegate.h file like this:

```<code>UIBackgroundTaskIdentifier taskIdentifier;
</code>```

Everything works as it supposed to, I see that console prints HELLO just right after 30 seconds are gone. But I don't want doSomething to be executed if the app enters foreground until 30 seconds are over. So I need to cancel it. This is how i do that:

```<code>- (void)applicationWillEnterForeground:(UIApplication *)application
{
    isRunningInBackground = NO;
    [self stopBackgroundExecution];
}

- (void)stopBackgroundExecution
{
    [[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
    taskIdentifier = UIBackgroundTaskInvalid;
}
</code>```

But unfortunately it doesn't cancel doSomething, it is still performed. What am I doing wrong? How do I cancel that function?

答:
https://developer.apple.com/documentation/dispatch/1431058-dispatch_block_cancel

dispatch_block_cancel
Cancels the specified dispatch block asynchronously.

```<code>void dispatch_block_cancel(dispatch_block_t block);
</code>```

(iOS 8.0+, macOS 10.10+, tvOS 9.0+, watchOS 2.0+)

ContentLicense: CC BY-SA 3.0

Body:
This is my issue. When my application enters background I want it to perform a function after certain period of time. This is what I do:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    isRunningInBackground = YES;

    taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];

    int64_t delayInSeconds = 30;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
    {
        [self doSomething];
    });
}

- (void)doSomething
{
   NSLog(@"HELLO");
}

taskIdentifier variable is declared in myAppDelegate.h file like this:

UIBackgroundTaskIdentifier taskIdentifier;

Everything works as it supposed to, I see that console prints HELLO just right after 30 seconds are gone. But I don't want doSomething to be executed if the app enters foreground until 30 seconds are over. So I need to cancel it. This is how i do that:

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    isRunningInBackground = NO;
    [self stopBackgroundExecution];
}

- (void)stopBackgroundExecution
{
    [[UIApplication sharedApplication] endBackgroundTask:taskIdentifier];
    taskIdentifier = UIBackgroundTaskInvalid;
}

But unfortunately it doesn't cancel doSomething, it is still performed. What am I doing wrong? How do I cancel that function?

Body:
https://developer.apple.com/documentation/dispatch/1431058-dispatch_block_cancel

dispatch_block_cancel
Cancels the specified dispatch block asynchronously.

void dispatch_block_cancel(dispatch_block_t block);

(iOS 8.0+, macOS 10.10+, tvOS 9.0+, watchOS 2.0+)

ContentLicense: CC BY-SA 4.0


问:
Where is the tag navigator in Visual Studio 2019
I've searched everywhere but can't find how to turn on the tag navigator in VS2019.  Does anyone know how?</p>

答: The tag navigator was removed in Visual Studio 2019.</p>


问:
How to fix this issue with JSP?
I am try to deploy a web app using apache tomcat and facing issue with exception.I am completely new to java so help me clearly.
Message org.apache.jasper.JasperException: Unable to compile class for JSP.

Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Looking into my login page java code is below

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%@ page import ="javax.swing.JOptionPane;" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Login</title>
    </head>
<body>

<%
    //connection to database

    Connection conn = null;
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","***");
    Statement st= conn.createStatement();
    String username=request.getParameter("username");
    String password=request.getParameter("userpass");

    //Check if username or password is empty

    if(username!="" && password!="")
    {
        session.setAttribute("username",username);
        //session.setAttribute("refreshCount","0");
        ResultSet rs=st.executeQuery("select * from login where userId='"+username+"'");
        if(rs.next())
        {
            //Check if user password matches with database password

            if(rs.getString(2).equals(password))
            {
                //retrieving the role of user form the database 1-Manager and 0 - student

                int role=rs.getInt(4);

                if(role==1)
                {
                    response.sendRedirect("managerHome.jsp");
                }
                else
                {

                    response.sendRedirect("studentHome.jsp");
                }

            }
            else
            {
                JOptionPane.showMessageDialog(null, "Invalid username or password.");
                String redirectURL= "index.jsp";
                    response.sendRedirect(redirectURL);

            }
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Invalid username or password.");
            String redirectURL= "index.jsp";
                response.sendRedirect(redirectURL);

        }

    }
    else
    {
        JOptionPane.showMessageDialog(null, "Username or password should not be empty");
                String redirectURL= "index.jsp";
                    response.sendRedirect(redirectURL);
    }
%>

</body>
</html>
</code>```

Exception:

```<code>org.apache.jasper.JasperException: org.apache.jasper.JasperException: Unable to compile class for JSP
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:604)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:422)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</code>```

Root Cause:

```<code>org.apache.jasper.JasperException: Unable to compile class for JSP
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:619)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:399)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

java.lang.IllegalArgumentException: Page directive: invalid value for import
org.apache.jasper.compiler.Node$PageDirective.validateImport(Node.java:619)
org.apache.jasper.compiler.Node$PageDirective.addImport(Node.java:599)
org.apache.jasper.compiler.Parser.parsePageDirective(Parser.java:366)
org.apache.jasper.compiler.Parser.parseDirective(Parser.java:478)
org.apache.jasper.compiler.Parser.parseFileDirectives(Parser.java:1797)
org.apache.jasper.compiler.Parser.parse(Parser.java:141)
org.apache.jasper.compiler.ParserController.doParse(ParserController.java:244)
org.apache.jasper.compiler.ParserController.parseDirectives(ParserController.java:127)
org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:202)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:385)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:362)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:346)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:603)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:399)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</code>```

Coming to my xml file it is below
Web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" metadata-complete="true" version="3.0">
  <display-name>SEProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>ManagerTimesheetsServlet</display-name>
    <servlet-name>ManagerTimesheetsServlet</servlet-name>
    <servlet-class>timesheet.ManagerTimesheetsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ManagerTimesheetsServlet</servlet-name>
    <url-pattern>/ManagerTimesheetsServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>StudentTimesheetServlet</display-name>
    <servlet-name>StudentTimesheetServlet</servlet-name>
    <servlet-class>timesheet.StudentTimesheetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>StudentTimesheetServlet</servlet-name>
    <url-pattern>/StudentTimesheetServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>StudentUpdateServlet</display-name>
    <servlet-name>StudentUpdateServlet</servlet-name>
    <servlet-class>timesheet.StudentUpdateServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>StudentUpdateServlet</servlet-name>
    <url-pattern>/StudentUpdateServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>CreateTimesheetServlet</display-name>
    <servlet-name>CreateTimesheetServlet</servlet-name>
    <servlet-class>timesheet.CreateTimesheetsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CreateTimesheetServlet</servlet-name>
    <url-pattern>/CreateTimesheetsServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <display-name>ApplyLeaveHandler</display-name>
    <servlet-name>ApplyLeaveHandler</servlet-name>
    <servlet-class>timesheet.ApplyLeaveHandler</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ApplyLeaveHandler</servlet-name>
    <url-pattern>/ApplyLeaveHandler</url-pattern>
  </servlet-mapping>
  <servlet>
    <display-name>EditLeaveHandler</display-name>
    <servlet-name>EditLeaveHandler</servlet-name>
    <servlet-class>timesheet.EditLeaveHandler</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EditLeaveHandler</servlet-name>
    <url-pattern>/EditLeaveHandler</url-pattern>
  </servlet-mapping>
  <servlet>
    <display-name>SubmitUpdatedLeaveHandler</display-name>
    <servlet-name>SubmitUpdatedLeaveHandler</servlet-name>
    <servlet-class>timesheet.SubmitUpdatedLeaveHandler</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SubmitUpdatedLeaveHandler</servlet-name>
    <url-pattern>/SubmitUpdatedLeaveHandler</url-pattern>
  </servlet-mapping>
  <servlet>
    <display-name>UpdateLeaveHandler</display-name>
    <servlet-name>UpdateLeaveHandler</servlet-name>
    <servlet-class>timesheet.UpdateLeaveHandler</servlet-class>
  </servlet>
  <servlet>
    <display-name>ViewLeaveHandler</display-name>
    <servlet-name>ViewLeaveHandler</servlet-name>
    <servlet-class>timesheet.ViewLeaveHandler</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UpdateLeaveHandler</servlet-name>
    <url-pattern>/UpdateLeaveHandler</url-pattern>
  </servlet-mapping>
</web-app>
</code>```

答:
I know this is not the answer to your question but believe me this will save you from a lot of trouble (tested it myself).

Try not using raw java code in your JSP pages, instead you can do your job on the server (.java files) and return variables and arrays on the JSP pages and build your page with that variables using JSTL.

How to avoid Java code in JSP files?

Title: How to fix this issue with JSP?

Body:
I am try to deploy a web app using apache tomcat and facing issue with exception.I am completely new to java so help me clearly.
Message org.apache.jasper.JasperException: Unable to compile class for JSP.

Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Looking into my login page java code is below

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%@ page import ="javax.swing.JOptionPane;" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Login</title>

<%
    //connection to database

    Connection conn = null;
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","***");
    Statement st= conn.createStatement();
    String username=request.getParameter("username");
    String password=request.getParameter("userpass");

    //Check if username or password is empty

    if(username!="" && password!="")
    {
        session.setAttribute("username",username);
        //session.setAttribute("refreshCount","0");
        ResultSet rs=st.executeQuery("select * from login where userId='"+username+"'");
        if(rs.next())
        {
            //Check if user password matches with database password

            if(rs.getString(2).equals(password))
            {
                //retrieving the role of user form the database 1-Manager and 0 - student

                int role=rs.getInt(4);

                if(role==1)
                {
                    response.sendRedirect("managerHome.jsp");
                }
                else
                {

                    response.sendRedirect("studentHome.jsp");
                }

            }
            else
            {
                JOptionPane.showMessageDialog(null, "Invalid username or password.");
                String redirectURL= "index.jsp";
                    response.sendRedirect(redirectURL);

            }
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Invalid username or password.");
            String redirectURL= "index.jsp";
                response.sendRedirect(redirectURL);

        }

    }
    else
    {
        JOptionPane.showMessageDialog(null, "Username or password should not be empty");
                String redirectURL= "index.jsp";
                    response.sendRedirect(redirectURL);
    }
%>

Exception:

org.apache.jasper.JasperException: org.apache.jasper.JasperException: Unable to compile class for JSP
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:604)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:422)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause:

org.apache.jasper.JasperException: Unable to compile class for JSP
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:619)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:399)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

java.lang.IllegalArgumentException: Page directive: invalid value for import
org.apache.jasper.compiler.Node$PageDirective.validateImport(Node.java:619)
org.apache.jasper.compiler.Node$PageDirective.addImport(Node.java:599)
org.apache.jasper.compiler.Parser.parsePageDirective(Parser.java:366)
org.apache.jasper.compiler.Parser.parseDirective(Parser.java:478)
org.apache.jasper.compiler.Parser.parseFileDirectives(Parser.java:1797)
org.apache.jasper.compiler.Parser.parse(Parser.java:141)
org.apache.jasper.compiler.ParserController.doParse(ParserController.java:244)
org.apache.jasper.compiler.ParserController.parseDirectives(ParserController.java:127)
org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:202)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:385)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:362)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:346)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:603)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:399)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Coming to my xml file it is below
Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" metadata-complete="true" version="3.0">
  <display-name>SEProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>ManagerTimesheetsServlet</display-name>
    <servlet-name>ManagerTimesheetsServlet</servlet-name>
    <servlet-class>timesheet.ManagerTimesheetsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ManagerTimesheetsServlet</servlet-name>
    <url-pattern>/ManagerTimesheetsServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>StudentTimesheetServlet</display-name>
    <servlet-name>StudentTimesheetServlet</servlet-name>
    <servlet-class>timesheet.StudentTimesheetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>StudentTimesheetServlet</servlet-name>
    <url-pattern>/StudentTimesheetServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>StudentUpdateServlet</display-name>
    <servlet-name>StudentUpdateServlet</servlet-name>
    <servlet-class>timesheet.StudentUpdateServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>StudentUpdateServlet</servlet-name>
    <url-pattern>/StudentUpdateServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>CreateTimesheetServlet</display-name>
    <servlet-name>CreateTimesheetServlet</servlet-name>
    <servlet-class>timesheet.CreateTimesheetsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CreateTimesheetServlet</servlet-name>
    <url-pattern>/CreateTimesheetsServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <display-name>ApplyLeaveHandler</display-name>
    <servlet-name>ApplyLeaveHandler</servlet-name>
    <servlet-class>timesheet.ApplyLeaveHandler</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ApplyLeaveHandler</servlet-name>
    <url-pattern>/ApplyLeaveHandler</url-pattern>
  </servlet-mapping>
  <servlet>
    <display-name>EditLeaveHandler</display-name>
    <servlet-name>EditLeaveHandler</servlet-name>
    <servlet-class>timesheet.EditLeaveHandler</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EditLeaveHandler</servlet-name>
    <url-pattern>/EditLeaveHandler</url-pattern>
  </servlet-mapping>
  <servlet>
    <display-name>SubmitUpdatedLeaveHandler</display-name>
    <servlet-name>SubmitUpdatedLeaveHandler</servlet-name>
    <servlet-class>timesheet.SubmitUpdatedLeaveHandler</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SubmitUpdatedLeaveHandler</servlet-name>
    <url-pattern>/SubmitUpdatedLeaveHandler</url-pattern>
  </servlet-mapping>
  <servlet>
    <display-name>UpdateLeaveHandler</display-name>
    <servlet-name>UpdateLeaveHandler</servlet-name>
    <servlet-class>timesheet.UpdateLeaveHandler</servlet-class>
  </servlet>
  <servlet>
    <display-name>ViewLeaveHandler</display-name>
    <servlet-name>ViewLeaveHandler</servlet-name>
    <servlet-class>timesheet.ViewLeaveHandler</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UpdateLeaveHandler</servlet-name>
    <url-pattern>/UpdateLeaveHandler</url-pattern>
  </servlet-mapping>
</web-app>


问:
What is attr in R class in Android?
I've seen an empty class named attr inside my autogenerated R.java class; what is its meaning? I know that styles can be defined in style.xml with style tag, so I don't know what attr is?

答:
R.attr is for "theme attributes" (not styles).

They're defined in a values xml file like this:

<attr name="textAppearanceLarge" format="reference" />

They're used in View contructors for the defStyle parameter, as in:

public TextView (Context context, AttributeSet attrs, int defStyle)

I'd imagine it's pretty rare for apps to add their own attr values. Usually the ones in android.R.attr will be used if at all.

Title: What is attr in R class in Android?


问:
Load file in rspec before block VS load them once
Today I'm tryng to speed up my tests suite. My application is basically a big integrator between systems so most of my tests are using Savon mocks like this

RSpec.describe MyClass do

  describe 'a function which sends a SOAP request'do
    before do
      savon.mock!
      savon.expects(action).returns(File.read("spec/fixtures/somefile.xml"))
    end

    after { savon.unmock! }

    it 'checks something'
    it 'checks something else'
    it 'checks something more'
    it 'checks something different'
  end
end
```

<p>Obviously most of those tests are quite slow as they are loading a file. Moreover sometimes these mocks are inside nested contexts in order to combine multiple shared examples which increases the amount of loads.
Thinking to speed up some of these tests I tried to reduce the number of file loads moving them outside the <code>before</code> block. like this </p>

<pre class="lang-rb prettyprint-override"><code>RSpec.describe MyClass do

  describe 'a function which sends a SOAP request'do
    the_file = File.read("spec/fixtures/somefile.xml")

    before do
      savon.mock!
      savon.expects(action).returns(the_file)
    end

    after { savon.unmock! }

    it 'checks something'
    it 'checks something else'
    it 'checks something more'
    it 'checks something different'
  end
end
</code>```

Indeed, the speed does not change; I have blocks of 96 tests with multiples, nested contexts and checks and I haven't gained not even 0.01 seconds. So my questions are:

I supposed the before block loads the file for each it, am I
right?

Does Rspec or Savon have some kind of cache?

How can I track the number of times I'm really loading my example file?

Thank you!

答: Using let let(:the_file) { File.read("spec/fixtures/somefile.xml") } will solve your problem as let is lazy evaluated

Body:
Today I'm tryng to speed up my tests suite. My application is basically a big integrator between systems so most of my tests are using Savon mocks like this

RSpec.describe MyClass do

  describe 'a function which sends a SOAP request'do
    before do
      savon.mock!
      savon.expects(action).returns(File.read("spec/fixtures/somefile.xml"))
    end

    after { savon.unmock! }

    it 'checks something'
    it 'checks something else'
    it 'checks something more'
    it 'checks something different'
  end
end

Obviously most of those tests are quite slow as they are loading a file. Moreover sometimes these mocks are inside nested contexts in order to combine multiple shared examples which increases the amount of loads.
Thinking to speed up some of these tests I tried to reduce the number of file loads moving them outside the before block. like this

RSpec.describe MyClass do

  describe 'a function which sends a SOAP request'do
    the_file = File.read("spec/fixtures/somefile.xml")

    before do
      savon.mock!
      savon.expects(action).returns(the_file)
    end

    after { savon.unmock! }

    it 'checks something'
    it 'checks something else'
    it 'checks something more'
    it 'checks something different'
  end
end

Indeed, the speed does not change; I have blocks of 96 tests with multiples, nested contexts and checks and I haven't gained not even 0.01 seconds. So my questions are:

I supposed the before block loads the file for each it, am I
right?

Does Rspec or Savon have some kind of cache?

How can I track the number of times I'm really loading my example file?

Thank you!


问:
Rest API (Post) Availability Test in Azure App Insights
I want to check whether my api is working fine. I have an api which only has post requests and no GET.

The tutorial here: https://learn.microsoft.com/en-us/azure/application-insights/app-insights-monitor-web-app-availability mentions that it is very easy to check whether a rest api is working fine.

When I write an availability test, it just asks me a url, but this is not enough for my case as it is a post request.

How to do that in App Insights? Is it not possible??

答: You can sue also some custom code to do your POST request, and report the telemetry to Application Insight. Here a .netcore sample: https://github.com/rbickel/Azure.Function.AppInsightAvailabilityTest</p>


问:
Get values from a number line at specific position
I have a dataframe with three columns. The first is "A" or "B" the second is a value and the third is a value (from and to). Now I want to get the values of the first column for given values of the two other columns.

I got this data frame:

```<code>a <- c('A','B','A','B')
b <- c(0,40,60,80)
c <- c(40,60,80,100)

frame <- data.frame(a,b,c)

> frame
  a  b   c
1 A  0  40
2 B 40  60
3 A 60  80
4 B 80 100
</code>```

And I want to generate this second data frame from the first one.

```<code>> frame2
   d   e
1  A  10
2  A  20
3  A  30
4  A  40
5  B  50
6  B  60
7  A  70
8  A  80
9  B  90
10 B 100
</code>```

Body:
I have a dataframe with three columns. The first is "A" or "B" the second is a value and the third is a value (from and to). Now I want to get the values of the first column for given values of the two other columns.

I got this data frame:

a <- c('A','B','A','B')
b <- c(0,40,60,80)
c <- c(40,60,80,100)

frame <- data.frame(a,b,c)

> frame
  a  b   c
1 A  0  40
2 B 40  60
3 A 60  80
4 B 80 100

And I want to generate this second data frame from the first one.

> frame2
   d   e
1  A  10
2  A  20
3  A  30
4  A  40
5  B  50
6  B  60
7  A  70
8  A  80
9  B  90
10 B 100

Body:
An option in base R

stack(setNames(apply(frame[-1], 1, function(x)
        seq(x[1]+10, x[2], by = 10)), frame[,1]))[2:1]
#    ind values
#1    A     10
#2    A     20
#3    A     30
#4    A     40
#5    B     50
#6    B     60
#7    A     70
#8    A     80
#9    B     90
#10   B    100


问:
Weird scrolling effect caused by overflow: hidden on body, html
If I disable overflow: hidden; on my body, html adds some sort of crop at the bottom of the screen. If I have it enabled I also can't get the scroll-to-top button to work.

Is there any way I can fix this or maybe have the grid scroll affect the button reveal? Also the arrow key scrolling doesn't seem to work as well on the grid div. Hope you guys can help!

body, html {
  overflow: hidden; /*scrolling problem*/
  height: 100%;
}
```

<p>Full code:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("backTop").style.opacity = "1";
  } else {
    document.getElementById("backTop").style.opacity = "0";
  }
}

function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}</code>```

body,
html {
  overflow: hidden; /*scrolling problem*/
  height: 100%;
}

.container {
  background-color: white;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
}

.left-div {
  background-color: yellow;
  height: 100vh;
  width: 100px;
}

.mid-div {
  background-color: pink;
  height: 100vh;
  width: 100%;
  overflow: scroll;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  grid-gap: 10px;
  grid-auto-rows: minmax(90px, auto);
  grid-auto-flow: dense;
  padding: 10px;
}

  .grid-item {
    position: relative;
    grid-row-end: span 1;
    grid-column-end: span 2;
    background-color: red;
  }

    .span-wide {
        grid-column-end: span 2;
        grid-row-end: span 2;
    }

    .span-long {
        grid-column-end: span 1;
        grid-row-end: span 4;
    }

.right-div {
  background-color: blue;
  height: 100vh;
  width: 100px;
}

  #backTop {
    opacity: 0;
    transition: 1s opacity;
    width: 40px;
    height: 40px;
    border-radius: 2em;
    position: absolute;
    bottom: 20px;
    right: 20px;
    background-color: green;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left-div"></div>

  <div class="mid-div">
    <div class="grid-item"></div>
    <div class="grid-item span-wide"></div>
    <div class="grid-item"></div>
    <div class="grid-item span-long"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item span-long"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
  </div>

  <div class="right-div">
    <button onclick="topFunction()" id="backTop" title="Back to Top">Top</button>
  </div>
</div></code>```

答:
You need to remove the padding and margin from the body:

```<code>body,
html {
  padding: 0;
  margin: 0;
}
</code>```

and adjust the height of the mid-div to be 100vh minus the height of a scrollbar:

```<code>.mid-div {
  height: calc(100vh - 20px);
}
</code>```

I've updated your fiddle here: https://jsfiddle.net/bjqLmswz/

Body:
If I disable overflow: hidden; on my body, html adds some sort of crop at the bottom of the screen. If I have it enabled I also can't get the scroll-to-top button to work.

Is there any way I can fix this or maybe have the grid scroll affect the button reveal? Also the arrow key scrolling doesn't seem to work as well on the grid div. Hope you guys can help!

body, html {
  overflow: hidden; /*scrolling problem*/
  height: 100%;
}

Full code:

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("backTop").style.opacity = "1";
  } else {
    document.getElementById("backTop").style.opacity = "0";
  }
}

function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}

body,
html {
  overflow: hidden; /*scrolling problem*/
  height: 100%;
}

.container {
  background-color: white;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
}

.left-div {
  background-color: yellow;
  height: 100vh;
  width: 100px;
}

.mid-div {
  background-color: pink;
  height: 100vh;
  width: 100%;
  overflow: scroll;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  grid-gap: 10px;
  grid-auto-rows: minmax(90px, auto);
  grid-auto-flow: dense;
  padding: 10px;
}

  .grid-item {
    position: relative;
    grid-row-end: span 1;
    grid-column-end: span 2;
    background-color: red;
  }

    .span-wide {
        grid-column-end: span 2;
        grid-row-end: span 2;
    }

    .span-long {
        grid-column-end: span 1;
        grid-row-end: span 4;
    }

.right-div {
  background-color: blue;
  height: 100vh;
  width: 100px;
}

  #backTop {
    opacity: 0;
    transition: 1s opacity;
    width: 40px;
    height: 40px;
    border-radius: 2em;
    position: absolute;
    bottom: 20px;
    right: 20px;
    background-color: green;
  }

    <button onclick="topFunction()" id="backTop" title="Back to Top">Top</button>

Body:
You need to remove the padding and margin from the body:

body,
html {
  padding: 0;
  margin: 0;
}

and adjust the height of the mid-div to be 100vh minus the height of a scrollbar:

.mid-div {
  height: calc(100vh - 20px);
}

I've updated your fiddle here: https://jsfiddle.net/bjqLmswz/


问:
C++ pointers objects difference
Can somebody explain me the difference between the following?

Those two

float *pointer[10];

float *(pointer[10]);
```

<ol start="2">
<li>and those two</li>
</ol>

<pre class="lang-cpp prettyprint-override"><code>int(*pointer_function)();

int *pointer_function();
</code>```

答:
These two declarations

```<code>float *pointer[10];

float *(pointer[10]);
</code>```

are equivalent. You can write even the following way

```<code>float *( ( pointer )[10] );
</code>```

That is it is a declaration of an array of 10 pointers to float.

These declarations

```<code>int(*pointer_function)();

int *pointer_function();
</code>```

are different. The first one declares a pointer to a function of type int(). The second one declares a function (not a pointer to a function) with type int *().

Here is a demonstrative program

```<code>#include <iostream>

int * pointer_function() // #1
{
    static int x = 1'000'000;

    return &x;
};

int f1() // #2
{
    return 2'000'000;
}

int main()
{
    std::cout << *pointer_function() /* calling #1 */<< '\n';

    int( *pointer_function )() = f1;

    std::cout << pointer_function() /* calling #2 */ << '\n';

    return 0;
}
</code>```

Its output is

```<code>1000000
2000000
</code>```

To make more obvious the difference between the declarations you can rewrite the second declaration (that is the declaration of function) the following way

```<code>int * ( pointer_function )();
</code>```

Compare it with the pointer to function declaration

```<code>int ( *pointer_function )();
</code>```

Take into account that a declarator may be enclosed in parentheses.

Title: C++ pointers objects difference

Body:
Can somebody explain me the difference between the following?

Those two

float *pointer[10];

float *(pointer[10]);

and those two

int(*pointer_function)();

int *pointer_function();

Body:
These two declarations

float *pointer[10];

float *(pointer[10]);

are equivalent. You can write even the following way

float *( ( pointer )[10] );

That is it is a declaration of an array of 10 pointers to float.

These declarations

int(*pointer_function)();

int *pointer_function();

are different. The first one declares a pointer to a function of type int(). The second one declares a function (not a pointer to a function) with type int *().

Here is a demonstrative program

#include <iostream>

int * pointer_function() // #1
{
    static int x = 1'000'000;

    return &x;
};

int f1() // #2
{
    return 2'000'000;
}

int main()
{
    std::cout << *pointer_function() /* calling #1 */<< '\n';

    int( *pointer_function )() = f1;

    std::cout << pointer_function() /* calling #2 */ << '\n';

    return 0;
}

Its output is

1000000
2000000

To make more obvious the difference between the declarations you can rewrite the second declaration (that is the declaration of function) the following way

int * ( pointer_function )();

Compare it with the pointer to function declaration

int ( *pointer_function )();

Take into account that a declarator may be enclosed in parentheses.


问:
Add Variable To All Routes
I need to display a variable (taken from user model) to all routes in my application which has no impact on the route it's being displayed on. So home/variable will display the same home page regardless of that variable to all users. If the user just goes to myapp/home the variable would append itself to the url as myapp/home/variable.

I already have my desired outcome with the below in web.php, but I have to do this with every route, so if my app has two pages I do the same redirect for both /home and /example. It also means I have to add the variable whenever I redirect from another controller.

```<code>Route::get( '/example',function(){
    $var  = Auth::user()->thevariable;
    return redirect('example/'.$var);
});
Route::get( 'example/{var}','ExampleController@index');

// changes the url from example, to example/variable, and also returns
the correct controller / view if directed to example/variable.
</code>```

In my controllers I do something like this to redirect if needed:

```<code>return redirect()->action('HomeController@index',$user->thevariable)
//I can also just redirect to the /home url and the variable is added
automatically, but this messes up passing session data.
</code>```

Can it be done better with a composer, middleware or even through the RouteServiceProvider? If anyone can point me in the right direction it would be greatly appreciated (laravel 5.4).

答:
My knowledge so far: If you want to use different paths you need to write down every path in the Routing. But the decision which one is choosen, will be done by a middleware. So you create your own middleware and attach here to all those paths with ->middleware('myOwnMW');. It should like:

```<code><?php

namespace App\Http\Middleware;

use Closure;

class myOwnMW
{

public function handle($request, Closure $next)
{
    if (Auth::user()->thevariable) {
        //redirect to your path
        $uri = $request->path() . '/'. $variableIwantToAttach;
        return redirect($uri);
    }

    return $next($request);
}
}
</code>```

Hope you get the idea. Check here for path. Dont forget to register your middleware inside the Kernel.php and here is a tutorial i used a while ago.

Title: Add Variable To All Routes

Body:
I need to display a variable (taken from user model) to all routes in my application which has no impact on the route it's being displayed on. So home/variable will display the same home page regardless of that variable to all users. If the user just goes to myapp/home the variable would append itself to the url as myapp/home/variable.

I already have my desired outcome with the below in web.php, but I have to do this with every route, so if my app has two pages I do the same redirect for both /home and /example. It also means I have to add the variable whenever I redirect from another controller.

Route::get( '/example',function(){
    $var  = Auth::user()->thevariable;
    return redirect('example/'.$var);
});
Route::get( 'example/{var}','ExampleController@index');

// changes the url from example, to example/variable, and also returns
the correct controller / view if directed to example/variable.

In my controllers I do something like this to redirect if needed:

return redirect()->action('HomeController@index',$user->thevariable)
//I can also just redirect to the /home url and the variable is added
automatically, but this messes up passing session data.

Can it be done better with a composer, middleware or even through the RouteServiceProvider? If anyone can point me in the right direction it would be greatly appreciated (laravel 5.4).

Body:
My knowledge so far: If you want to use different paths you need to write down every path in the Routing. But the decision which one is choosen, will be done by a middleware. So you create your own middleware and attach here to all those paths with ->middleware('myOwnMW');. It should like:

<?php

namespace App\Http\Middleware;

use Closure;

class myOwnMW
{

public function handle($request, Closure $next)
{
    if (Auth::user()->thevariable) {
        //redirect to your path
        $uri = $request->path() . '/'. $variableIwantToAttach;
        return redirect($uri);
    }

    return $next($request);
}
}

Hope you get the idea. Check here for path. Dont forget to register your middleware inside the Kernel.php and here is a tutorial i used a while ago.


问:
How To Change The Bottom Line EditText Color?
I have an EditText in an AlertDialog and the bottom line color is not what I want, and I can't figure out how to change it.

Here is what I have so far.

```<code>AlertDialog.Builder adb = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.EditTextAlertDialog));
    adb.setTitle("Title");
    inputET = new EditText(this);
    inputET.setInputType(InputType.TYPE_CLASS_TEXT);
    inputET.setTextColor(getResources().getColor(android.R.color.white));
   inputET.setHighlightColor(getResources().getColor(android.R.color.white)); //This should change it, but it's not.
    adb.setView(inputET);

    adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    adb.show();
</code>```

For some weird reason that is not working, setHightlightColor should be it.

答:
You can create a style for your dialog.

```<code><style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="colorAccent">@color/yourEditTextColor</item>
    </style>
</code>```

And then add it while creating your Dialog

```<code>AlertDialog.Builder adb = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.MyDialogTheme));
</code>```

Body:
I have an EditText in an AlertDialog and the bottom line color is not what I want, and I can't figure out how to change it.

Here is what I have so far.

AlertDialog.Builder adb = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.EditTextAlertDialog));
    adb.setTitle("Title");
    inputET = new EditText(this);
    inputET.setInputType(InputType.TYPE_CLASS_TEXT);
    inputET.setTextColor(getResources().getColor(android.R.color.white));
   inputET.setHighlightColor(getResources().getColor(android.R.color.white)); //This should change it, but it's not.
    adb.setView(inputET);

    adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    adb.show();

For some weird reason that is not working, setHightlightColor should be it.

Body:
You can create a style for your dialog.

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="colorAccent">@color/yourEditTextColor</item>
    </style>

And then add it while creating your Dialog

AlertDialog.Builder adb = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.MyDialogTheme));


问:
Next js doesn't update URL
I have the following component:

```<code>import React, {Component} from "react";
import fetch from 'isomorphic-unfetch';
import {Router} from '../routes';

class About extends Component {
  state = {
    results: null,
    postcode: null
  }

  handleOnChange = e => {
    this.setState({
      postcode: e.target.value
    });
  }

  handleOnSubmit = e => {
    e.preventDefault();
      // calling the api passing the postcode
      console.log(this.state.postcode)
    fetch(`http://localhost:3001/${this.state.postcode}`)
      .then(response => response.json())
      .then(data => {
          this.setState({
            results: data
          })
      })
      .catch(error => console.error(error))

      Router.pushRoute('/about', {postcode: this.state.postcode})
  }

  render() {
    console.log(this.state.results)
   return(
    <form>
      <input name="postcode" onChange={this.handleOnChange} />
      <button onClick={this.handleOnSubmit}>submit postcode</button>
    </form>
   )
  }
}

About.getInitialProps = async function(context) {
  console.log('context: ', context.query)
  return {
    results: 'data'
  }
}

export default About;
</code>```

and my routes file like so:

```<code>const routes = module.exports = require('next-routes')()

routes
.add('index')
.add('about', '/about/:postcode', 'about');
</code>```

however when I submit the form I would expect the URL to be updated with the submitted value like so:

```<code>http://localhost:3000/about/ => http://localhost:3000/about/postcodeValueSubmitted
</code>```

It doesn't throw any error but the URL remains:

```<code>http://localhost:3000/about
</code>```

I would need the value to be updated so that I can use 'getInitialProps' to do the server side rendering.

答:
This helped:

```<code>Router.pushRoute('about', {postcode: this.state.postcode})
</code>```

note the difference without the '/'

Title: Next js doesn't update URL

Body:
I have the following component:

import React, {Component} from "react";
import fetch from 'isomorphic-unfetch';
import {Router} from '../routes';

class About extends Component {
  state = {
    results: null,
    postcode: null
  }

  handleOnChange = e => {
    this.setState({
      postcode: e.target.value
    });
  }

  handleOnSubmit = e => {
    e.preventDefault();
      // calling the api passing the postcode
      console.log(this.state.postcode)
    fetch(`http://localhost:3001/${this.state.postcode}`)
      .then(response => response.json())
      .then(data => {
          this.setState({
            results: data
          })
      })
      .catch(error => console.error(error))

      Router.pushRoute('/about', {postcode: this.state.postcode})
  }

  render() {
    console.log(this.state.results)
   return(
    <form>
      <input name="postcode" onChange={this.handleOnChange} />
      <button onClick={this.handleOnSubmit}>submit postcode</button>
    </form>
   )
  }
}

About.getInitialProps = async function(context) {
  console.log('context: ', context.query)
  return {
    results: 'data'
  }
}

export default About;

and my routes file like so:

const routes = module.exports = require('next-routes')()

routes
.add('index')
.add('about', '/about/:postcode', 'about');

however when I submit the form I would expect the URL to be updated with the submitted value like so:

http://localhost:3000/about/ => http://localhost:3000/about/postcodeValueSubmitted

It doesn't throw any error but the URL remains:

http://localhost:3000/about

I would need the value to be updated so that I can use 'getInitialProps' to do the server side rendering.

Body:
This helped:

Router.pushRoute('about', {postcode: this.state.postcode})

note the difference without the '/'


问:
Random number generator in VHDL
I'm designing a test bench and I need to create a random sequence of bits for one of the system's inputs which is normally controlled by the user.
I also want this sequence of bits not being in the same order every time I run the simulation.

I cannot use a PRNG since its initial state will be predefined meaning it while produce the same numbers every time. I also used the uniform function but I had the same issue.

```<code>RAND_GEN : process(clk) is
    variable seed1, seed2 : positive := 1;
    variable re           : real;
begin
    if rising_edge(clk) then
        uniform(seed1, seed2, re);
        if (re < 0.5) then
            rand_bit <= '0';
        else
            rand_bit <= '1';
        end if;
    end if;
end process;
</code>```

Is there any alternatives for this problem?

答:
Testing with randomly generated inputs is a powerful tehnique and is the technique commonly used to verify ICs these days. Normally, you would run a test with a known, per-determined seed, whereas you want to be able to generate a varying seed. So, you absolutely MUST record this seed when you run the test and provide a mechanism to run a test using this seed. Otherwise, when you find a bug, you will not be able to test whether you've fixed it. You might find it more useful to a a fixed set of tests with a smaller number of manually-generated seeds.

You could use the linux date command with the %s format specifier, which outputs the number of seconds since 1/1/1970 and redirect that to a file.

```<code>date +%s >! seed.txt
</code>```

Then read the file, eg:

```<code>RAND_GEN : process(clk) is
    variable seed1, seed2 : positive := 1;
    variable re           : real;
    file F: TEXT;
    variable L: LINE;
    variable seed_RNG : boolean := false;
begin
    if not seed_RNG then
        file_open(F, "seed.txt", READ_MODE);
        readline (F, L);
        read (L, seed1);  -- or seed2
        file_close(F);
        report "seed1 = " & integer'image(seed1);
        seed_RNG := true;
    end if;
    if rising_edge(clk) then
        uniform(seed1, seed2, re);
        if (re < 0.5) then
            rand_bit <= '0';
        else
            rand_bit <= '1';
        end if;
    end if;
end process;
</code>```

Title: Random number generator in VHDL

Body:
I'm designing a test bench and I need to create a random sequence of bits for one of the system's inputs which is normally controlled by the user.
I also want this sequence of bits not being in the same order every time I run the simulation.

I cannot use a PRNG since its initial state will be predefined meaning it while produce the same numbers every time. I also used the uniform function but I had the same issue.

RAND_GEN : process(clk) is
    variable seed1, seed2 : positive := 1;
    variable re           : real;
begin
    if rising_edge(clk) then
        uniform(seed1, seed2, re);
        if (re < 0.5) then
            rand_bit <= '0';
        else
            rand_bit <= '1';
        end if;
    end if;
end process;

Is there any alternatives for this problem?

Body:
Testing with randomly generated inputs is a powerful tehnique and is the technique commonly used to verify ICs these days. Normally, you would run a test with a known, per-determined seed, whereas you want to be able to generate a varying seed. So, you absolutely MUST record this seed when you run the test and provide a mechanism to run a test using this seed. Otherwise, when you find a bug, you will not be able to test whether you've fixed it. You might find it more useful to a a fixed set of tests with a smaller number of manually-generated seeds.

You could use the linux date command with the %s format specifier, which outputs the number of seconds since 1/1/1970 and redirect that to a file.

date +%s >! seed.txt

Then read the file, eg:

RAND_GEN : process(clk) is
    variable seed1, seed2 : positive := 1;
    variable re           : real;
    file F: TEXT;
    variable L: LINE;
    variable seed_RNG : boolean := false;
begin
    if not seed_RNG then
        file_open(F, "seed.txt", READ_MODE);
        readline (F, L);
        read (L, seed1);  -- or seed2
        file_close(F);
        report "seed1 = " & integer'image(seed1);
        seed_RNG := true;
    end if;
    if rising_edge(clk) then
        uniform(seed1, seed2, re);
        if (re < 0.5) then
            rand_bit <= '0';
        else
            rand_bit <= '1';
        end if;
    end if;
end process;


问:
Substring of a specific occurence
I have a column as varchar2 datatype, the data in it is in format:

```<code>100323.3819823.222
100.323123.443422
1001010100.233888
LOL12333.DDD33.44
</code>```

I need to remove the whole part after the first occurrence of '.'

In the end it should look like this:

```<code>100323
100
1001010100
LOL12333
</code>```

I cant seem to find the exact substring expression due to the fact that there is not  any fix length of the first part.

答:
One way is to use REGEXP_SUBSTR:

```<code>SELECT REGEXP_SUBSTR(column_name,'^[^.]*') FROM table
</code>```

The other way is to combine SUBSTR with INSTR, which is a bit faster, but will result in NULL if the data doesn't contain a dot, so you'll have to add a switch if needed:

```<code>SELECT SUBSTR(column_name, 1, INSTR(column_name,'.') - 1) FROM table
</code>```

Title: Substring of a specific occurence

Body:
I have a column as varchar2 datatype, the data in it is in format:

100323.3819823.222
100.323123.443422
1001010100.233888
LOL12333.DDD33.44

I need to remove the whole part after the first occurrence of '.'

In the end it should look like this:

100323
100
1001010100
LOL12333

I cant seem to find the exact substring expression due to the fact that there is not  any fix length of the first part.

Body:
One way is to use REGEXP_SUBSTR:

SELECT REGEXP_SUBSTR(column_name,'^[^.]*') FROM table

The other way is to combine SUBSTR with INSTR, which is a bit faster, but will result in NULL if the data doesn't contain a dot, so you'll have to add a switch if needed:

SELECT SUBSTR(column_name, 1, INSTR(column_name,'.') - 1) FROM table


问:
Is there an equivalent for DropwizardTestSupport in Micronaut?
I'd like to run my application with JUnit for the integration test.

For Dropwizard, I've been using DropwizardTestSupport library to achieve that.

Wondering if there's an equivalent for that in Micronaut.

Thanks

答:
I cannot say that is the equivalent of DropwizardTestSupport because I have not used that but we do have a Micronaut Test library which is described at https://micronaut-projects.github.io/micronaut-test/latest/guide/index.html.  In short, you can annotation your test with @MicronautTest and that causes useful things to happen including starting up the app and subjecting your test class to dependency injection.

I hope that helps.


问:
Execution of a Java Program starts from which line? Is it main method?
From where does execution of a java program starts?    I heard people say its from main method. I think execution starts from static block. Am i right??</p>

答:
If a class contains static block and main method () jvm Wil executive the static block first and then main method will be executed.
But if you don't mention the static block in a class and the class contain only main method then jvm starts execution from main method only.</p>


问:
how to get maxLocals by core api in ASM?
I want to get maxLocals for storing data，like

```<code>int index = mv.visitLocalVariable(name, desc, null, start, end, ++maxLocals);
</code>```

by tree api , this.nextLocals = methodNode.maxLocals;
but core api , nothing.

Inject into out , error method around biz~.

like this:

@Test
    public void testCode() {
        hooK hook = StatisGet.get(1L);
        hook.into();
        try {
            //biz
            hook.out();
        } catch (Throwable e) {
            hook.error(e);
        }
    }
```

now I am able to successfully inject bytecode, but solt sometimes gets wrong because I can't get maxLocal.

答:
Assuming with “Core API” you mean the Visitor API, there is the method visitMaxs on the MethodVisitor, which will be invoked with the maximum stack and local variable numbers.

But there is a catch; this method will be invoked after the other visitor methods. So you can’t use that number beforehand to find an unused local variable.

A solution is to use an adapter, the LocalVariablesSorter, if you consider it to be part of the “Core API”. It allows you to invoke newLocal when you need a free local variable and it will tell you the next variable number that has not been encountered so far. It will then remember the number and if encountering conflicting variable number uses when continuing to visit the original code, it will renumber those variable numbers, to solve the conflict.

You only have to care to invoke the visitor methods on the original method visitor (the writer) when dealing with your injected code, as the visitor methods on the LocalVariablesSorter will be invoked for the original code and transformed. See also this answer and that answer.

Body:
I want to get maxLocals for storing data，like

int index = mv.visitLocalVariable(name, desc, null, start, end, ++maxLocals);

by tree api , this.nextLocals = methodNode.maxLocals;
but core api , nothing.

Inject into out , error method around biz~.

like this:

@Test
    public void testCode() {
        hooK hook = StatisGet.get(1L);
        hook.into();
        try {
            //biz
            hook.out();
        } catch (Throwable e) {
            hook.error(e);
        }
    }

now I am able to successfully inject bytecode, but solt sometimes gets wrong because I can't get maxLocal.


问:
Reduce Trying to understand the parameters in the callback function of .reduce()
I'm trying to learn JS and I have some questions about reduce()
I want to know how can I know what parameters this function needs and how I should call them.

are this parameters connected with any data or the array outside the function.

or this parameters propose is only to be available in this local context of the callback to work as const and be able to store some date for the correct execution of the .reduce() .

Thank You For Your Time

Just trying to understand .reduce()

```<code>const companies= [
  {name: "Company One", category: "Finance", start: 1981, end: 2004},
  {name: "Company Two", category: "Retail", start: 1992, end: 2008},
  {name: "Company Three", category: "Auto", start: 1999, end: 2007},
  {name: "Company Four", category: "Retail", start: 1989, end: 2010},
  {name: "Company Five", category: "Technology", start: 2009, end: 2014},
  {name: "Company Six", category: "Finance", start: 1987, end: 2010},
  {name: "Company Seven", category: "Auto", start: 1986, end: 1996},
  {name: "Company Eight", category: "Technology", start: 2011, end: 2016},
  {name: "Company Nine", category: "Retail", start: 1981, end: 1989}
];

const totalYears = companies.reduce((total, company) => total + (company.end - company.start), 0);

console.log(totalYears);
</code>```

答:
The parameters to reduce are related to the array. Here is a simple re-write to show what is effectively happening:

companies.reduce((total, company) => total + (company.end - company.start), 0);
```

<p>can also be expressed as:</p>

<pre class="lang-js prettyprint-override"><code>//first parameter to the callback
let total;

//value supplied as the second parameter to `.reduce()`
total = 0;

//the second parameter to the callback
for(let company of companies) { //this is the loop `.reduce` does for you

  //this variable does not show up in your code but is here for clarity
  let temp;

  //this is the body of your `.reduce()` callback
  temp = total + (company.end - company.start)

  //this would be `reduce` handing `total` to the next invocation
  total = temp;
}
</code>```

This is a simplification but it can work to understand what is happening.

The parameters you define can be named arbitrarily, but they would serve the same purpose

the first parameter to the callback (total, in your case) is often called "accumulator" - it's a generic term and, frankly, very confusing at first, but all that it does is return the last result of the callback. So, if you are trying to sum all members of the array, this could be your running total, if you're trying to find the smallest item, it could just hold the current smallest.

the second parameter to the callback (company, in your case) is also often called "item". It's just the current item the callback is executed against.

It's worth noting that the callback also gets called with more arguments. It's up to you whether you want to use them or not - a lot of times they aren't needed:

the third parameter is the index of the current element

the fourth parameter is the entire array

const sample = ["h", "e", "l", "l", "o"];

//a simple concatenation to illustrate how the parameters work
const output = sample.reduce((accumulator, item, index, array) => {
  console.log(accumulator, item, index, array);

  return accumulator + item;
})

console.log("output is:", output);```
</div>
</div>
</p>

<ul>
<li>the second parameter <em>to <code>.reduce()</code></em> not to the callback (<code>0</code> in your case) is the <em>starting</em> value of the accumulator (or <code>total</code> here). It's not strictly needed but it's useful in many occasions - you usually want to start from <em>some</em> value. If you don't supply this argument, then the first time <code>.reduce()</code> runs, it would start from the <em>second</em> value in the array and would set the accumulator to the first one:</li>
</ul>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let run = 1;
//no initial value set
["a", "b", "c"].reduce((accumulator, item) => {
  console.log(run++, accumulator, item);
})</code>```

let run = 1;
//with initial value set
["a", "b", "c"].reduce((accumulator, item) => {
  console.log(run++, accumulator, item);
}, "some initial value")```

Body:
I'm trying to learn JS and I have some questions about reduce()
I want to know how can I know what parameters this function needs and how I should call them.

are this parameters connected with any data or the array outside the function.

or this parameters propose is only to be available in this local context of the callback to work as const and be able to store some date for the correct execution of the .reduce() .

Thank You For Your Time

Just trying to understand .reduce()

const companies= [
  {name: "Company One", category: "Finance", start: 1981, end: 2004},
  {name: "Company Two", category: "Retail", start: 1992, end: 2008},
  {name: "Company Three", category: "Auto", start: 1999, end: 2007},
  {name: "Company Four", category: "Retail", start: 1989, end: 2010},
  {name: "Company Five", category: "Technology", start: 2009, end: 2014},
  {name: "Company Six", category: "Finance", start: 1987, end: 2010},
  {name: "Company Seven", category: "Auto", start: 1986, end: 1996},
  {name: "Company Eight", category: "Technology", start: 2011, end: 2016},
  {name: "Company Nine", category: "Retail", start: 1981, end: 1989}
];

const totalYears = companies.reduce((total, company) => total + (company.end - company.start), 0);

console.log(totalYears);

Body:
The parameters to reduce are related to the array. Here is a simple re-write to show what is effectively happening:

companies.reduce((total, company) => total + (company.end - company.start), 0);

can also be expressed as:

//first parameter to the callback
let total;

//value supplied as the second parameter to `.reduce()`
total = 0;

//the second parameter to the callback
for(let company of companies) { //this is the loop `.reduce` does for you

  //this variable does not show up in your code but is here for clarity
  let temp;

  //this is the body of your `.reduce()` callback
  temp = total + (company.end - company.start)

  //this would be `reduce` handing `total` to the next invocation
  total = temp;
}

This is a simplification but it can work to understand what is happening.

The parameters you define can be named arbitrarily, but they would serve the same purpose

the first parameter to the callback (total, in your case) is often called "accumulator" - it's a generic term and, frankly, very confusing at first, but all that it does is return the last result of the callback. So, if you are trying to sum all members of the array, this could be your running total, if you're trying to find the smallest item, it could just hold the current smallest.

the second parameter to the callback (company, in your case) is also often called "item". It's just the current item the callback is executed against.

It's worth noting that the callback also gets called with more arguments. It's up to you whether you want to use them or not - a lot of times they aren't needed:

the third parameter is the index of the current element

the fourth parameter is the entire array

const sample = ["h", "e", "l", "l", "o"];

//a simple concatenation to illustrate how the parameters work
const output = sample.reduce((accumulator, item, index, array) => {
  console.log(accumulator, item, index, array);

  return accumulator + item;
})

console.log("output is:", output);

the second parameter to .reduce() not to the callback (0 in your case) is the starting value of the accumulator (or total here). It's not strictly needed but it's useful in many occasions - you usually want to start from some value. If you don't supply this argument, then the first time .reduce() runs, it would start from the second value in the array and would set the accumulator to the first one:

let run = 1;
//no initial value set
["a", "b", "c"].reduce((accumulator, item) => {
  console.log(run++, accumulator, item);
})

let run = 1;
//with initial value set
["a", "b", "c"].reduce((accumulator, item) => {
  console.log(run++, accumulator, item);
}, "some initial value")


问:
How to bind ApplicationDbContext to a View in ASP.Net Core 2.2
I need to bind ApplicationDbContext to my View for using models but its not working.

I have tried @using ProjectName.Data for accessing ApplicationDbContext but vain.

@using TailorManagementSystem.Data in the head

ApplicationDbContext dbContext = new ApplicationDbContext();

The error comes out to be
"There is no argument given to that corresponds to the required formal parameter 'options' of ApplicationDbContext"

答:
You have to inject it into the view:

```<code>@inject TailorManagementSystem.Data.ApplicationDbContext Context
</code>```

Then you can use Context in your view.

However, you should never actually do this. Views should have as little logic as possible. Things like querying a database should be handled in your controller action or via something like a view component, never in the view itself.

Body:
You have to inject it into the view:

@inject TailorManagementSystem.Data.ApplicationDbContext Context

Then you can use Context in your view.

However, you should never actually do this. Views should have as little logic as possible. Things like querying a database should be handled in your controller action or via something like a view component, never in the view itself.


问:
Reuse cells of a scroll view
I am using a scrollview to display various items in a horizontal fashion.

How can I "reuse the cells" to conserve memory:

Edit:  Apologies for not being clear.  I plan to place a few labels and and another ImageView inside each ImageView so I am keen to reuse this each time instead of instantiating new items each time.  e.g. change the image's and update the labels instead of re-create it.

```<code>// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

    // load all the images from our bundle and add them to the scroll view
//  NSUInteger i;
    for (int i = 0; i <= 150; i++)
    {
        NSString *imageName = @"tempImage.jpg";
        UIImage *image = [UIImage imageNamed:imageName];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

        // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
        CGRect rect = imageView.frame;
        rect.size.height = kScrollObjHeight;
        rect.size.width = kScrollObjWidth;
        imageView.frame = rect;
        imageView.tag = i;  // tag our images for later use when we place them in serial fashion
        [self.bestSellScrollView addSubview:imageView];
        [imageView release];
    }

    [self layoutScrollImages];  // now place the photos in serial layout within the scrollview
}

- (void)layoutScrollImages
{
    UIImageView *view = nil;
    NSArray *subviews = [self.bestSellScrollView subviews];

    // reposition all image subviews in a horizontal serial fashion
    CGFloat curXLoc = 0;
    for (view in subviews)
    {
        if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
        {
            CGRect frame = view.frame;
            frame.origin = CGPointMake(curXLoc, 0);
            view.frame = frame;

            curXLoc += (kScrollObjWidth);
        }
    }

    // set the content size so it can be scrollable
    [self.bestSellScrollView setContentSize:CGSizeMake((150 * kScrollObjWidth),
                                                       [self.bestSellScrollView bounds].size.height)];
}
</code>```

答:
If you mean like what happens with respect UITableViewCell in a UITableView, then its not possible in the horizontal scroller.

The reusable cells property for a table view is provided by the system and it not applicable for horizontal scroller.

You have to write on your own logic in order to achieve it, perhaps! Its a good question though. Will be tuned to other answers just in case if anything is possible.

Title: Reuse cells of a scroll view

Body:
I am using a scrollview to display various items in a horizontal fashion.

How can I "reuse the cells" to conserve memory:

Edit:  Apologies for not being clear.  I plan to place a few labels and and another ImageView inside each ImageView so I am keen to reuse this each time instead of instantiating new items each time.  e.g. change the image's and update the labels instead of re-create it.

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

    // load all the images from our bundle and add them to the scroll view
//  NSUInteger i;
    for (int i = 0; i <= 150; i++)
    {
        NSString *imageName = @"tempImage.jpg";
        UIImage *image = [UIImage imageNamed:imageName];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

        // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
        CGRect rect = imageView.frame;
        rect.size.height = kScrollObjHeight;
        rect.size.width = kScrollObjWidth;
        imageView.frame = rect;
        imageView.tag = i;  // tag our images for later use when we place them in serial fashion
        [self.bestSellScrollView addSubview:imageView];
        [imageView release];
    }

    [self layoutScrollImages];  // now place the photos in serial layout within the scrollview
}

- (void)layoutScrollImages
{
    UIImageView *view = nil;
    NSArray *subviews = [self.bestSellScrollView subviews];

    // reposition all image subviews in a horizontal serial fashion
    CGFloat curXLoc = 0;
    for (view in subviews)
    {
        if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
        {
            CGRect frame = view.frame;
            frame.origin = CGPointMake(curXLoc, 0);
            view.frame = frame;

            curXLoc += (kScrollObjWidth);
        }
    }

    // set the content size so it can be scrollable
    [self.bestSellScrollView setContentSize:CGSizeMake((150 * kScrollObjWidth),
                                                       [self.bestSellScrollView bounds].size.height)];
}


问:
How to extract the population figure of a country from en.wikipedia.org using Selenium through Java
I am trying to extract the population figure/text of an element.

I tried with parent but its showing error. I am trying to get the Population of China from this page table https://en.wikipedia.org/wiki/China

Code trial:

```<code>WebElement dateBox7 = driver.findElement(By.xpath("//*[contains(text(),'Population')]/parent::tr//td/a[text()]"));
</code>```

Error:

```<code>Exception in thread "main" org.openqa.selenium.NoSuchElementException:
</code>```

I have tried //*[contains(text(),'2016 estimate')]/ancestor::tr/td/text()[1] this xpath it's showing the population in DOM.But in selenium it's showing error:

```<code>Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: The result of the xpath expression "//*[contains(text(),'2016 estimate')]/ancestor::tr/td/text()[1]" is: [object Text]. It should be an element.
</code>```

Why it's not working?

答:
To extract the the Population of China i.e. the text 1,403,500,365 from this page table https://en.wikipedia.org/wiki/China you need to induce WebDriverWait for the visibilityOfElementLocated() and as the desired text is within a Text Node you need to use executeScript() and you can use the following Locator Strategy:

```<code>WebElement myElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[text()='Population']//following::tr[1]//td")));
System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].childNodes[2].textContent;", myElement).toString());
</code>```

You can find a similar discussion in How to retrieve text from an element using Selenium WebDriver and Java

Body:
I am trying to extract the population figure/text of an element.

I tried with parent but its showing error. I am trying to get the Population of China from this page table https://en.wikipedia.org/wiki/China

Code trial:

WebElement dateBox7 = driver.findElement(By.xpath("//*[contains(text(),'Population')]/parent::tr//td/a[text()]"));

Error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException:

I have tried //*[contains(text(),'2016 estimate')]/ancestor::tr/td/text()[1] this xpath it's showing the population in DOM.But in selenium it's showing error:

Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: The result of the xpath expression "//*[contains(text(),'2016 estimate')]/ancestor::tr/td/text()[1]" is: [object Text]. It should be an element.

Why it's not working?

Body:
To extract the the Population of China i.e. the text 1,403,500,365 from this page table https://en.wikipedia.org/wiki/China you need to induce WebDriverWait for the visibilityOfElementLocated() and as the desired text is within a Text Node you need to use executeScript() and you can use the following Locator Strategy:

WebElement myElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[text()='Population']//following::tr[1]//td")));
System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].childNodes[2].textContent;", myElement).toString());

You can find a similar discussion in How to retrieve text from an element using Selenium WebDriver and Java


问:
Handling skewed data in a matplotlib bar chart
I'm working on creating a bar chart for a skewed data set using python matplotlib.
While I'm able to generate the graph without any issue, In the graph generated, the bar related to the skewed data is covering the majority of the bar chart and making the other nonskewed data look relatively small and negligible.

Below is the code used to generate the bar graph.

```<code>import numpy as np
import matplotlib.pyplot as plt
x=["A","B","C","D","E","F"]
y=[25,11,46,895,68,5]
fig,ax = plt.subplots()
r1=plt.barh(y=x,
        width=y,
        height=0.8)

#ht = [x.get_width() for x in r1.get_children()]
r1y = np.asarray([x.get_y() for x in r1.get_children()])
r1h = np.asarray([x.get_height() for x in r1.get_children()])

for i in range(5):
    plt.text(y[i],r1y[i]+r1h[i]/2, '%s'% (y[i]), ha='left', va='center')

plt.xticks([0,10,100,1000])
plt.show()
</code>```

The above code would create a bar chart with 0,10,100 and 1000 as xtick values and they are placed at a relative distance based on their value.

While this is valid and expected behvaior, one single skewed bar is impacting the entire bar chart.

So,is it possible to place these xtick values at equidistant so that the skewed data doesn't occupy the majority of the space in the final output?

In the expected output, values related 0-10-100 should occupy around 66.6% of the space and 100-1000 should occupy the rest of the 33.3% of the space.

Example:

答:
Try to add plt.xscale('log'):

```<code>x=["A","B","C","D","E","F"]
y=[25,11,46,895,68,5]
fig,ax = plt.subplots()
r1=plt.barh(y=x,
        width=y,
        height=0.8)

r1y = np.asarray([x.get_y() for x in r1.get_children()])
r1h = np.asarray([x.get_height() for x in r1.get_children()])

for i in range(5):
    plt.text(y[i],r1y[i]+r1h[i]/2, '%s'% (y[i]), ha='left', va='center')

plt.xscale('log')

plt.show()
</code>```

Output:

Body:
I'm working on creating a bar chart for a skewed data set using python matplotlib.
While I'm able to generate the graph without any issue, In the graph generated, the bar related to the skewed data is covering the majority of the bar chart and making the other nonskewed data look relatively small and negligible.

Below is the code used to generate the bar graph.

import numpy as np
import matplotlib.pyplot as plt
x=["A","B","C","D","E","F"]
y=[25,11,46,895,68,5]
fig,ax = plt.subplots()
r1=plt.barh(y=x,
        width=y,
        height=0.8)

#ht = [x.get_width() for x in r1.get_children()]
r1y = np.asarray([x.get_y() for x in r1.get_children()])
r1h = np.asarray([x.get_height() for x in r1.get_children()])

for i in range(5):
    plt.text(y[i],r1y[i]+r1h[i]/2, '%s'% (y[i]), ha='left', va='center')

plt.xticks([0,10,100,1000])
plt.show()

The above code would create a bar chart with 0,10,100 and 1000 as xtick values and they are placed at a relative distance based on their value.

While this is valid and expected behvaior, one single skewed bar is impacting the entire bar chart.

So,is it possible to place these xtick values at equidistant so that the skewed data doesn't occupy the majority of the space in the final output?

In the expected output, values related 0-10-100 should occupy around 66.6% of the space and 100-1000 should occupy the rest of the 33.3% of the space.

Example:

Body:
Try to add plt.xscale('log'):

x=["A","B","C","D","E","F"]
y=[25,11,46,895,68,5]
fig,ax = plt.subplots()
r1=plt.barh(y=x,
        width=y,
        height=0.8)

r1y = np.asarray([x.get_y() for x in r1.get_children()])
r1h = np.asarray([x.get_height() for x in r1.get_children()])

for i in range(5):
    plt.text(y[i],r1y[i]+r1h[i]/2, '%s'% (y[i]), ha='left', va='center')

plt.xscale('log')

plt.show()

Output:


答:
For oracle you can try this:</p>

```<code>select substr (i,1,Instr(i,'.',i)-1) from Table name.
</code>```

Title: Substring of a specific occurence

Body:
For oracle you can try this:

select substr (i,1,Instr(i,'.',i)-1) from Table name.


问:
How to use a dictionary to translate a start and end date to a period of time, eg jan-dec being a calender year
I have a data frame which has the start date and end date of a period of time as yyyy-mm and I want to have a new column which has the period of time - for example start date of 2019-01 and end date of 2019-12 would be Cal-19 in the new column, want to have this for years and quarters and then if it isn't either of those to do mm-yyyy - mm-yyyy as a string of the start to end dates.

I have tried to do this with a dictionary which had two inputs, start and end date, and would have the output for the period but this hasn't worked.

```<code>from Dictionary import Period

df["Start Period"]=pd.to_datetime(df["Start Date"], dayfirst=True).dt.to_period("M")

df["End Period"]=pd.to_datetime(df["End Date"], dayfirst=True).dt.to_period("M")

df["Period"] = df["Start Period"].map(Period) #This is the line which isn't working
</code>```

Where Period is a dictionary as follows:

```<code>Period = dict({("2019-01","2019-12"):"Cal-19",
            ("2020-01","2020-12"):"Cal-20",
            ("2021-01","2021-12"):"Cal-21",
            ("2019-01","2019-03"):"Q1-19",
            ("2019-04","2019-06"):"Q2-19",
            ("2019-07","2019-09"):"Q3-19",
            ("2019-10","2019-12"):"Q4-19",
            ("2020-01","2020-03"):"Q1-20",
            ("2020-04","2020-06"):"Q2-20",
            ("2020-07","2020-09"):"Q3-20"})
</code>```

Would expect to get the period but get an error within the dictionary itself but even when trying on a small subset of data I get NaN in the output column.

Body:
I have a data frame which has the start date and end date of a period of time as yyyy-mm and I want to have a new column which has the period of time - for example start date of 2019-01 and end date of 2019-12 would be Cal-19 in the new column, want to have this for years and quarters and then if it isn't either of those to do mm-yyyy - mm-yyyy as a string of the start to end dates.

I have tried to do this with a dictionary which had two inputs, start and end date, and would have the output for the period but this hasn't worked.

from Dictionary import Period

df["Start Period"]=pd.to_datetime(df["Start Date"], dayfirst=True).dt.to_period("M")

df["End Period"]=pd.to_datetime(df["End Date"], dayfirst=True).dt.to_period("M")

df["Period"] = df["Start Period"].map(Period) #This is the line which isn't working

Where Period is a dictionary as follows:

Period = dict({("2019-01","2019-12"):"Cal-19",
            ("2020-01","2020-12"):"Cal-20",
            ("2021-01","2021-12"):"Cal-21",
            ("2019-01","2019-03"):"Q1-19",
            ("2019-04","2019-06"):"Q2-19",
            ("2019-07","2019-09"):"Q3-19",
            ("2019-10","2019-12"):"Q4-19",
            ("2020-01","2020-03"):"Q1-20",
            ("2020-04","2020-06"):"Q2-20",
            ("2020-07","2020-09"):"Q3-20"})

Would expect to get the period but get an error within the dictionary itself but even when trying on a small subset of data I get NaN in the output column.

Body:
You need flatten dictionary for all combination of periods with values of dict by list comprehension with period_range:

Period = dict({("2019-01","2019-12"):"Cal-19",
            ("2020-01","2020-12"):"Cal-20",
            ("2021-01","2021-12"):"Cal-21",
            ("2019-01","2019-03"):"Q1-19",
            ("2019-04","2019-06"):"Q2-19",
            ("2019-07","2019-09"):"Q3-19",
            ("2019-10","2019-12"):"Q4-19",
            ("2020-01","2020-03"):"Q1-20",
            ("2020-04","2020-06"):"Q2-20",
            ("2020-07","2020-09"):"Q3-20"})

d = {x:v for (k1,k2), v in Period.items() for x in pd.period_range(k1, k2, freq='M')}

df = pd.DataFrame({'Start Period': pd.period_range('2019-01', '2020-09', freq='M')})

#map by dictioanry d
df["Period"] = df["Start Period"].map(d)
print (df)
   Start Period Period
0       2019-01  Q1-19
1       2019-02  Q1-19
2       2019-03  Q1-19
3       2019-04  Q2-19
4       2019-05  Q2-19
5       2019-06  Q2-19
6       2019-07  Q3-19
7       2019-08  Q3-19
8       2019-09  Q3-19
9       2019-10  Q4-19
10      2019-11  Q4-19
11      2019-12  Q4-19
12      2020-01  Q1-20
13      2020-02  Q1-20
14      2020-03  Q1-20
15      2020-04  Q2-20
16      2020-05  Q2-20
17      2020-06  Q2-20
18      2020-07  Q3-20
19      2020-08  Q3-20
20      2020-09  Q3-20


问:
How to fix 'bool' object has no attribute 'get'
im new to python with django frame work and im developing three articles

i have tried to debug but i have failed and im getting this error "bool object has no attribute 'get"

this is my models.py

```<code> from django.db import models

# Create your models here.
class Article(models.Model):# this new class articles inherits properties from models.model
    """docstring for Article"""
    title = models.CharField(max_length=255)
    body = models.TextField(max_length=255)
    pub_date = models.DateTimeField( 'date published')
    likes = models.IntegerField()

    def __unicode__(self):
                    return self.get
</code>```

and in my urls i have

```<code>from django.conf.urls import include, url
from article.views import article
#from django.shortcuts import redirect

urlpatterns =[
    url(r'^all/$', all, name='all'),
    url(r'^get/ (?P<article_id>\d+)/$', article, name='article'),
    ]
</code>```

i expect to have a list of articles and when i click on the articles im directed to another page

but i get such an error

System check identified no issues (0 silenced).

May 28, 2019 - 15:38:06

Django version 2.2.1, using settings 'finalreading.settings'

Starting development server at http://127.0.0.1:8000/

Quit the server with CTRL-BREAK.

Internal Server Error: /articles/all/

Traceback (most recent call last):

File "C:\code\lib\site-packages\django\core\handlers\exception.py", line 34, in inner

response = get_response(request)

File "C:\code\lib\site-packages\django\utils\deprecation.py", line 96, in call

response = self.process_response(request, response)

File "C:\code\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response

if response.get('X-Frame-Options') is not None:

AttributeError: 'bool' object has no attribute 'get'

[28/May/2019 15:38:15] "GET /articles/all/ HTTP/1.1" 500 57684

please help because i need to learn fast and work on the coming projects as well.

答:
Don't call your view all because it's a reserved function in python that returns a bool whether all elements of a list are True of not. Your urls.py contains this line:

```<code>url(r'^all/$', all, name='all'),
</code>```

but you're not importing all so it's never hitting your view all but calling the python all(). But again, you should rename it to article_list or something like that and import that (and use that in urls.py).

Body:
im new to python with django frame work and im developing three articles

i have tried to debug but i have failed and im getting this error "bool object has no attribute 'get"

this is my models.py

 from django.db import models

# Create your models here.
class Article(models.Model):# this new class articles inherits properties from models.model
    """docstring for Article"""
    title = models.CharField(max_length=255)
    body = models.TextField(max_length=255)
    pub_date = models.DateTimeField( 'date published')
    likes = models.IntegerField()

    def __unicode__(self):
                    return self.get

and in my urls i have

from django.conf.urls import include, url
from article.views import article
#from django.shortcuts import redirect

urlpatterns =[
    url(r'^all/$', all, name='all'),
    url(r'^get/ (?P<article_id>\d+)/$', article, name='article'),
    ]

i expect to have a list of articles and when i click on the articles im directed to another page

but i get such an error

System check identified no issues (0 silenced).

May 28, 2019 - 15:38:06

Django version 2.2.1, using settings 'finalreading.settings'

Starting development server at http://127.0.0.1:8000/

Quit the server with CTRL-BREAK.

Internal Server Error: /articles/all/

Traceback (most recent call last):

File "C:\code\lib\site-packages\django\core\handlers\exception.py", line 34, in inner

response = get_response(request)

File "C:\code\lib\site-packages\django\utils\deprecation.py", line 96, in call

response = self.process_response(request, response)

File "C:\code\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response

if response.get('X-Frame-Options') is not None:

AttributeError: 'bool' object has no attribute 'get'

[28/May/2019 15:38:15] "GET /articles/all/ HTTP/1.1" 500 57684

please help because i need to learn fast and work on the coming projects as well.

Body:
Don't call your view all because it's a reserved function in python that returns a bool whether all elements of a list are True of not. Your urls.py contains this line:

url(r'^all/$', all, name='all'),

but you're not importing all so it's never hitting your view all but calling the python all(). But again, you should rename it to article_list or something like that and import that (and use that in urls.py).


问:
Magento configurable swatch color option (1.9.1 native) not switching image in main product page
I am trying to add swatches to a configurable product, which I was successful in doing, however clicking on a swatch color does not change the product image. The color option click event is not triggered.
In product view page if click the media image it will be changed main product image but if i click the color option it will not change the main product image but it will select the label value for example red or black.I have not get any specific error when click the color option.

In my configurableswatches.xml file the following js has been included
 <name>js/configurableswatches/product-media.js</name></action>
<name>js/configurableswatches/swatches-list.js</name></action>
<name>js/configurableswatches/swatches-product.js</name></action>
Is any other js is missing to change the main product image?

currently site is running magento 1.9.1 and theme is rwd. Please provide me the solution for this.

答: Did you check the product page for JS errors (in your console) when you try to switch attributes? Because that's most of the times the case.</p>


问:
XAML trigger as StaticResource
Why can't I create a trigger and use it as a static resource in XAML?

```<code><Window.Resources>
    <Trigger x:Key="ValidationTrigger" x:Shared="False" Property="Validation.HasError" Value="true">
        <Setter Property="FrameworkElement.ToolTip"
                Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                Path=(Validation.Errors)/ErrorContent}"/>
    </Trigger>

    <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
        <Style.Triggers>
            <StaticResource ResourceKey="ValidationTrigger"/>
        </Style.Triggers>
    </Style>
</Window.Resources>
</code>```

I get an errormessage at runtime

"Value cannot be null.

Parameter name: triggerBase  Error at object 'System.Windows.Markup.StaticResourceHolder' in markup file"

答:
I imagine that this is because resources are loaded first.

So in this case, WPF would try to load your trigger before any control it might be associated with. Then the trigger value can't be evaluated at that time.

But that need to be confirmed :)

ContentLicense: CC BY-SA 2.5

Title: XAML trigger as StaticResource

Body:
Why can't I create a trigger and use it as a static resource in XAML?

<Window.Resources>
    <Trigger x:Key="ValidationTrigger" x:Shared="False" Property="Validation.HasError" Value="true">
        <Setter Property="FrameworkElement.ToolTip"
                Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                Path=(Validation.Errors)/ErrorContent}"/>
    </Trigger>

    </Style>
</Window.Resources>

I get an errormessage at runtime

"Value cannot be null.

Parameter name: triggerBase  Error at object 'System.Windows.Markup.StaticResourceHolder' in markup file"