问:
React router 4 HashRouter, how do I hide hash in the url?
I am using react-router-4 HashRouter because I put my static build to AWS bucket and served through cloudfront. So essentially I do not have a server at the front end side of things to support BrowserRoute.

What I want is: example.com/#/accounts_ to be _example.com/accounts

In angular 1.x I would use $locationProvider.html5Mode(true) to achieve the same.

Any help would be much appreciated.

答:
You can use BrowserRouter. And I would suggest reading up on how the client and server routing works.

Using this approach, if you are planning on using anything in a production environment, you will need to configure that environment to have a fallback route to your index page to then handle client-side routing.

```<code>import { BrowserRouter, Switch, Route } from 'react-router-dom';

<BrowserRouter>
  <Switch>
    <Route exact path="/foo" component={FooController}
    <Route path="/foo/bar" component={FooController} />
  </Switch>
</BrowserRouter>
</code>```

And your webpack.config.js

```<code>devServer: {
  historyApiFallback: true,
},
</code>```

Body:
You can use BrowserRouter. And I would suggest reading up on how the client and server routing works.

Using this approach, if you are planning on using anything in a production environment, you will need to configure that environment to have a fallback route to your index page to then handle client-side routing.

import { BrowserRouter, Switch, Route } from 'react-router-dom';

<BrowserRouter>
  <Switch>
    <Route exact path="/foo" component={FooController}
    <Route path="/foo/bar" component={FooController} />
  </Switch>
</BrowserRouter>

And your webpack.config.js

devServer: {
  historyApiFallback: true,
},


来源: stackexchange

问:
Global using variables definition and declaration in C++
I am beginer in C++ programing language and i want to learn how to use all my variables in every single part of project in C++ (separate .cpp files or classes...).
For example, if we make comparation to Fortran, in Fortran we can make declaration or definition of variables in one module and we can use that module for sharing variables in main program or any other module. What concept from C++ is equivalent to concept of modules in Fortran?</p>

答:
The C++ equivalent to Fortran's modules is namespaces.

Have a look over there to learn more about namespaces.

Namespace introduces the idea of scope:

```<code>namespace V { // original-namespace-definition for V
    void f(); // declaration of V::f
  }
  void V::f() {} // definition of V::f
  void f() {} // declaration and definition of f() # different from V::f()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The C++ equivalent to Fortran's modules is namespaces.

Have a look over there to learn more about namespaces.

Namespace introduces the idea of scope:

namespace V { // original-namespace-definition for V
    void f(); // declaration of V::f
  }
  void V::f() {} // definition of V::f
  void f() {} // declaration and definition of f() # different from V::f()


问:
Paintcode export to subfolder
When defining export to image settings for a canvas, is there a way to let PaintCode export to different folders depending on the canvas?

A few of my canvasses are language dependend and need to be exported into subfolders with the language in it (android)....

答:
Currently there is no option for doing what you want.

I believe what you should be doing, instead, is to parameterize the String itself, like so:

This way you expose your String and can set whatever you want at runtime.

Title: Paintcode export to subfolder


问:
How to use a WITH block with dynamic sql query
I've got a plpgsql function that needs to prepare data from 3 tables based on user input, and export the data using COPY TO. The data are road accidents, so the 3 tables are accident, casualty and vehicle, each accident links to zero or more records in the vehicle and casualty tables via an accidentid column that exists in all three tables. severity and local_authorities are input parameters (both text []).

```<code>sql_query = 'SELECT COUNT(*) FROM accident WHERE severity = ANY(' || quote_literal(severity)
 || ') AND local_auth = ANY (' || quote_literal(local_authorities) || ')';

EXECUTE sql_query INTO result_count;

IF result_count > 0 THEN
   -- replace Select Count(*) With Select *
   sql_query = Overlay(sql_query placing '*' from 8 for 8);

   -- copy the accident data first
   EXECUTE 'COPY (' || sql_query || ') TO ' || quote_literal(file_path || file_name_a) ||
     ' CSV';
</code>```

This first bit will get the relevant accidents, so I'm now looking for the most efficient way to use the accidentid's from the first query to download the related vehicle and casualty data.

I thought I'd be able to use a WITH block like this:

```<code>-- replace * with accidentid
sql_query = Overlay(sql_query placing 'accidentid' from 8 for 1);

WITH acc_ids AS (sql_query)
  EXECUTE 'COPY (SELECT * FROM vehicle WHERE accidentid IN (SELECT accidentid FROM
  acc_ids)) TO ' || out_path_and_vfilename || ' CSV';
  EXECUTE 'COPY (SELECT * FROM casualty WHERE accidentid IN (SELECT accidentid FROM
  acc_ids)) TO ' || out_path_and_cfilename || ' CSV';
</code>```

but get an error:

ERROR:  syntax error at or near "$1"

LINE 1: WITH acc_ids AS ( $1 ) EXECUTE 'COPY (SELECT * FROM accident....

I have tried the above in a non-dynamic test case e.g.

```<code>WITH acc_ids AS (
    SELECT accidentid FROM accident
    WHERE severity = ANY ('{3,2}')
    AND local_auth = ANY ('{E09000001,E09000002}')
    )
    SELECT * FROM vehicle
    WHERE accidentid IN (
    SELECT accidentid FROM acc_ids);
</code>```

which works. Unfortunately the server is still running Postgres 8.4 so I can't use format() for the time being.

Perhaps this isn't possible with a WITH block, but I hope it at least illustrates what I'm trying to achieve.

Edit/Update

The main goal is to get the relevant data from the 3 tables in 3 separate csv files, ideally without having to run the selection on the accident table 3 times

答:
This does what I need to do without CTE but I can't see this being the most efficient way of solving this since I have to perform the same query on the accident table 3 times:

```<code>sql_query = sql_query || which_tab || ' WHERE severity = ANY ('||
   quote_literal(severity) ||') AND ' || date_start || ' AND ' ||
   date_end || ' AND local_auth = ANY (' ||
   quote_literal(local_authorities) || ')';

-- replace * with COUNT(*)
sql_query = Overlay(sql_query placing 'COUNT(*)' from 8 for 1);
EXECUTE sql_query INTO result_count;

IF result_count > 0 THEN

   -- replace COUNT(*) with *
   sql_query = Overlay(sql_query placing '*' from 8 for 8);
   -- copy the accident data first
   EXECUTE 'COPY (' || sql_query || ') TO ' || quote_literal(file_path ||
      file_name_a) || ' CSV';

   sql_query = Overlay(sql_query placing 'accidentid' from 8 for 1);
   -- vehicles
   EXECUTE 'COPY (SELECT * FROM vehicle WHERE accidentid IN (
    SELECT accidentid FROM accident
    WHERE severity = ANY (' || quote_literal(severity) || ')
    AND local_auth = ANY (' || quote_literal(local_authorities) ||')))
    TO ' || quote_literal(file_path || file_name_v) || ' CSV';
   -- casualties
   EXECUTE 'COPY (SELECT * FROM casualty WHERE accidentid IN (
    SELECT accidentid FROM accident
    WHERE severity = ANY (' || quote_literal(severity) || ')
    AND local_auth = ANY (' || quote_literal(local_authorities) ||')))
    TO ' || quote_literal(file_path || file_name_c) || ' CSV';
END IF;
</code>```

Body:
I've got a plpgsql function that needs to prepare data from 3 tables based on user input, and export the data using COPY TO. The data are road accidents, so the 3 tables are accident, casualty and vehicle, each accident links to zero or more records in the vehicle and casualty tables via an accidentid column that exists in all three tables. severity and local_authorities are input parameters (both text []).

sql_query = 'SELECT COUNT(*) FROM accident WHERE severity = ANY(' || quote_literal(severity)
 || ') AND local_auth = ANY (' || quote_literal(local_authorities) || ')';

EXECUTE sql_query INTO result_count;

IF result_count > 0 THEN
   -- replace Select Count(*) With Select *
   sql_query = Overlay(sql_query placing '*' from 8 for 8);

   -- copy the accident data first
   EXECUTE 'COPY (' || sql_query || ') TO ' || quote_literal(file_path || file_name_a) ||
     ' CSV';

This first bit will get the relevant accidents, so I'm now looking for the most efficient way to use the accidentid's from the first query to download the related vehicle and casualty data.

I thought I'd be able to use a WITH block like this:

-- replace * with accidentid
sql_query = Overlay(sql_query placing 'accidentid' from 8 for 1);

WITH acc_ids AS (sql_query)
  EXECUTE 'COPY (SELECT * FROM vehicle WHERE accidentid IN (SELECT accidentid FROM
  acc_ids)) TO ' || out_path_and_vfilename || ' CSV';
  EXECUTE 'COPY (SELECT * FROM casualty WHERE accidentid IN (SELECT accidentid FROM
  acc_ids)) TO ' || out_path_and_cfilename || ' CSV';

but get an error:

ERROR:  syntax error at or near "$1"

LINE 1: WITH acc_ids AS ( $1 ) EXECUTE 'COPY (SELECT * FROM accident....

I have tried the above in a non-dynamic test case e.g.

WITH acc_ids AS (
    SELECT accidentid FROM accident
    WHERE severity = ANY ('{3,2}')
    AND local_auth = ANY ('{E09000001,E09000002}')
    )
    SELECT * FROM vehicle
    WHERE accidentid IN (
    SELECT accidentid FROM acc_ids);

which works. Unfortunately the server is still running Postgres 8.4 so I can't use format() for the time being.

Perhaps this isn't possible with a WITH block, but I hope it at least illustrates what I'm trying to achieve.

Edit/Update

The main goal is to get the relevant data from the 3 tables in 3 separate csv files, ideally without having to run the selection on the accident table 3 times

Body:
This does what I need to do without CTE but I can't see this being the most efficient way of solving this since I have to perform the same query on the accident table 3 times:

sql_query = sql_query || which_tab || ' WHERE severity = ANY ('||
   quote_literal(severity) ||') AND ' || date_start || ' AND ' ||
   date_end || ' AND local_auth = ANY (' ||
   quote_literal(local_authorities) || ')';

-- replace * with COUNT(*)
sql_query = Overlay(sql_query placing 'COUNT(*)' from 8 for 1);
EXECUTE sql_query INTO result_count;

IF result_count > 0 THEN

   -- replace COUNT(*) with *
   sql_query = Overlay(sql_query placing '*' from 8 for 8);
   -- copy the accident data first
   EXECUTE 'COPY (' || sql_query || ') TO ' || quote_literal(file_path ||
      file_name_a) || ' CSV';

   sql_query = Overlay(sql_query placing 'accidentid' from 8 for 1);
   -- vehicles
   EXECUTE 'COPY (SELECT * FROM vehicle WHERE accidentid IN (
    SELECT accidentid FROM accident
    WHERE severity = ANY (' || quote_literal(severity) || ')
    AND local_auth = ANY (' || quote_literal(local_authorities) ||')))
    TO ' || quote_literal(file_path || file_name_v) || ' CSV';
   -- casualties
   EXECUTE 'COPY (SELECT * FROM casualty WHERE accidentid IN (
    SELECT accidentid FROM accident
    WHERE severity = ANY (' || quote_literal(severity) || ')
    AND local_auth = ANY (' || quote_literal(local_authorities) ||')))
    TO ' || quote_literal(file_path || file_name_c) || ' CSV';
END IF;


问:
Dual-Core Hyperthreading: Should I use 4 threads or 3 or 2?
If you're spawning multiple threads (or processes) concurrently, is it better to spawn as many as the number of physical processors or the number of logical processors, assuming the task is CPU-bound? Or is it better to do something in between (say, 3 threads)?

Does the performance depend on the kind of instructions that are getting executed (say, would non-local memory access be much different from cache hits)? If so, in which cases is it better to take advantage of hyperthreading?

Update:

The reason I'm asking is, I remember reading somewhere that if you have as many tasks as the number of virtual processors, tasks on the same physical core can sometimes starve some CPU resources and prevent each other from getting as many resources as needed, possibly decreasing performance. That's why I'm wondering if having as many threads as virtual cores is a good idea.

答:
Chances are pretty good that you will see a performance improvement running 2 threads per core with HyperThreading enabled. Jobs that appear to be entirely CPU bound usually aren't, and HyperThreading can extract a few "extra" cycles out of the occasional interrupt or context switch.

On the other hand, with a core iX processor that has Turbo Boost, you might actually do better running 1 thread per core to encourage the CPU to overclock itself.

At work, we routinely run many-core servers at full CPU doing various kinds of calculation for days at a time. A while back we measured the performance difference with and without HT. We found that on average, with HyperThreading, and running twice as many jobs at once, we could complete the same amount of jobs about 10% faster than than without HyperThreading.

Assume that 2 × cores is a good place to start, but the bottom line is: measure!

ContentLicense: CC BY-SA 2.5


问:
Storing ONLY MONTH and DATE in a single Column in MYSQL
Hi I am trying to store Month and Date in a single column.

UseCase

I am dumping data into mysql for reporting purpose and report is monthly.

I will be using Hibernate later to retreive data

答: It is better to use TIMESTAMP for repoting purpose instead of just Date, Month or both.</p>


问:
HTTP Status 500 - Servlet.init() for servlet appServlet threw exception
I want to try a simple program but getting following error. I am using Eclipse Kelper and Tomcat 7.0.
Tried a lot of things, but nothing is working for me.

```<code>HTTP Status 500 - Servlet.init() for servlet appServlet threw exception
type Exception report

message Servlet.init() for servlet appServlet threw exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet.init() for servlet appServlet threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

root cause

java.lang.IllegalArgumentException
    org.springframework.asm.ClassReader.<init>(Unknown Source)
    org.springframework.asm.ClassReader.<init>(Unknown Source)
    org.springframework.asm.ClassReader.<init>(Unknown Source)
    org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52)
    org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
    org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)
    org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
    org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298)
    org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
    org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
    org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230)
    org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153)
    org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130)
    org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285)
    org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223)
    org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:652)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:600)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:666)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:519)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:460)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:160)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.47 logs.
</code>```

There is source code:

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</code>```

servlet-context.xml:

```<code>?
</code>```

Could somebody explain what is the problem?

答:
try this out:
servlet-context.xml:</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://geronimo.apache.org/xml/ns/j2ee/web-1.1">
  <dep:environment xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.1">
    <dep:moduleId>
      <dep:groupId>org.apache.geronimo.samples.jws</dep:groupId>
      <dep:artifactId>Calculator</dep:artifactId>
      <dep:version>1.0</dep:version>
      <dep:type>car</dep:type>
    </dep:moduleId>
    <dep:dependencies>
    </dep:dependencies>
  </dep:environment>
  <context-root>/jaxws-calculator-1.0</context-root>
  <service-ref>
    <service-ref-name>services/Calculator</service-ref-name>
    <port>
      <port-name>CalculatorPort</port-name>
      <protocol>http</protocol>
      <host>localhost</host>
      <port>8080</port>
      <uri>/jaxws-calculator/calculator</uri>
    </port>
  </service-ref>
</web-app>
</code>```

Body:
I want to try a simple program but getting following error. I am using Eclipse Kelper and Tomcat 7.0.
Tried a lot of things, but nothing is working for me.

HTTP Status 500 - Servlet.init() for servlet appServlet threw exception
type Exception report

message Servlet.init() for servlet appServlet threw exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet.init() for servlet appServlet threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

root cause

java.lang.IllegalArgumentException
    org.springframework.asm.ClassReader.<init>(Unknown Source)
    org.springframework.asm.ClassReader.<init>(Unknown Source)
    org.springframework.asm.ClassReader.<init>(Unknown Source)
    org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52)
    org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
    org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)
    org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
    org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298)
    org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
    org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
    org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230)
    org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153)
    org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130)
    org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285)
    org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223)
    org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:652)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:600)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:666)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:519)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:460)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:160)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.47 logs.

There is source code:

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

servlet-context.xml:

?

Could somebody explain what is the problem?

Body:
try this out:
servlet-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://geronimo.apache.org/xml/ns/j2ee/web-1.1">
  <dep:environment xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.1">
    <dep:moduleId>
      <dep:groupId>org.apache.geronimo.samples.jws</dep:groupId>
      <dep:artifactId>Calculator</dep:artifactId>
      <dep:version>1.0</dep:version>
      <dep:type>car</dep:type>
    </dep:moduleId>
    <dep:dependencies>
    </dep:dependencies>
  </dep:environment>
  <context-root>/jaxws-calculator-1.0</context-root>
  <service-ref>
    <service-ref-name>services/Calculator</service-ref-name>
    <port>
      <port-name>CalculatorPort</port-name>
      <protocol>http</protocol>
      <host>localhost</host>
      <port>8080</port>
      <uri>/jaxws-calculator/calculator</uri>
    </port>
  </service-ref>
</web-app>


问:
Passing value from Table View to textfield in IOS
I have a textfield in my view controller, in which when user type car name it shows related car name list in table view and user can select the any car from table view. If car name has space between name for example: "Honda Civic" the space is replaced by %20 and becomes "Honda%20Civic" and it pass value from textfield to the API.Now I'm getting an issue that when I type any letter like ho it shows list of cars of Honda when I select any car it comes textfield text , when I send the textfield value it goes to ho instead of the name I have selected from table view. How can I send it to the API the name of car I have selected from tableview list?
My code to replaced space by %20 is this,

```<code>-(void)textFieldDidChanges :(UITextField *)theTextField{
result=theTextField.text;
NSLog(@"XXX%@",result);
result=[result stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSLog(@"VVV %@",result);
//just use this result where you want
}
</code>```

This is table view methods,

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView==_year01) {
    return [year1Array count];
}else{
    return [carArray count];
}
return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

if (tableView == _year01){
    cell.textLabel.text=[year1Array objectAtIndex:indexPath.row];
}else{
    cell.textLabel.text=[carArray objectAtIndex:indexPath.row];
}

cell.backgroundColor=[UIColor darkGrayColor];
cell.textLabel.textColor=[UIColor whiteColor];

return cell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Cell %@",selectedCell);

if (tableView == _year01){
    self.year1.text=@"";
    self.year1.text=[year1Array objectAtIndex:indexPath.row];
    self.year01.hidden=YES;
}else{
    self.carName.text=@"";
    self.carName.text=[carArray objectAtIndex:indexPath.row];
    _carTable.hidden=YES;
    [_carName resignFirstResponder];
}
}
</code>```

This is I'm storing in NSUserdefault and passing to next view,

```<code> [[NSUserDefaults standardUserDefaults] setObject:result forKey:@"name"];` [[NSUserDefaults standardUserDefaults] synchronize];`
</code>```

The value in result come the letter I write instead of the value selected from table view list.

答:
In my opinion, saving something in user defaults just for reading it on the same controller is unnecessary. Why you just don't use dependency injection if you are using segue? Creating one global object in that class that will contain value that you want to send is just enough if you're not. User defaults are more used for getting some info after termination of the as a lightweight info.

Example:

```<code>@property (nonatomic, string) NSString *carYear;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Cell %@",selectedCell);

if (tableView == _year01){
    self.year1.text=@"";
    self.year1.text=[year1Array objectAtIndex:indexPath.row];
    self.carYear = [carArray objectAtIndex:indexPath.row];
    self.year01.hidden=YES;
}else{
    self.carName.text=@"";
    self.carName.text=[carArray objectAtIndex:indexPath.row]; //This will have stored name
    _carTable.hidden=YES;
    [_carName resignFirstResponder];
}
}
</code>```

And after this just if you are using pass that value as:

```<code>[self performSegueWithIdentifier:@"identifier" sender:self.carYear];
</code>```

OR:

```<code>YourVCToPassValue *vc = [YourVCTOPassValue new];
vc.valueToBePassed = self.carYear;
</code>```

Body:
I have a textfield in my view controller, in which when user type car name it shows related car name list in table view and user can select the any car from table view. If car name has space between name for example: "Honda Civic" the space is replaced by %20 and becomes "Honda%20Civic" and it pass value from textfield to the API.Now I'm getting an issue that when I type any letter like ho it shows list of cars of Honda when I select any car it comes textfield text , when I send the textfield value it goes to ho instead of the name I have selected from table view. How can I send it to the API the name of car I have selected from tableview list?
My code to replaced space by %20 is this,

-(void)textFieldDidChanges :(UITextField *)theTextField{
result=theTextField.text;
NSLog(@"XXX%@",result);
result=[result stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSLog(@"VVV %@",result);
//just use this result where you want
}

This is table view methods,

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView==_year01) {
    return [year1Array count];
}else{
    return [carArray count];
}
return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

if (tableView == _year01){
    cell.textLabel.text=[year1Array objectAtIndex:indexPath.row];
}else{
    cell.textLabel.text=[carArray objectAtIndex:indexPath.row];
}

cell.backgroundColor=[UIColor darkGrayColor];
cell.textLabel.textColor=[UIColor whiteColor];

return cell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Cell %@",selectedCell);

if (tableView == _year01){
    self.year1.text=@"";
    self.year1.text=[year1Array objectAtIndex:indexPath.row];
    self.year01.hidden=YES;
}else{
    self.carName.text=@"";
    self.carName.text=[carArray objectAtIndex:indexPath.row];
    _carTable.hidden=YES;
    [_carName resignFirstResponder];
}
}

This is I'm storing in NSUserdefault and passing to next view,

 [[NSUserDefaults standardUserDefaults] setObject:result forKey:@"name"];` [[NSUserDefaults standardUserDefaults] synchronize];`

The value in result come the letter I write instead of the value selected from table view list.

Body:
In my opinion, saving something in user defaults just for reading it on the same controller is unnecessary. Why you just don't use dependency injection if you are using segue? Creating one global object in that class that will contain value that you want to send is just enough if you're not. User defaults are more used for getting some info after termination of the as a lightweight info.

Example:

@property (nonatomic, string) NSString *carYear;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Cell %@",selectedCell);

if (tableView == _year01){
    self.year1.text=@"";
    self.year1.text=[year1Array objectAtIndex:indexPath.row];
    self.carYear = [carArray objectAtIndex:indexPath.row];
    self.year01.hidden=YES;
}else{
    self.carName.text=@"";
    self.carName.text=[carArray objectAtIndex:indexPath.row]; //This will have stored name
    _carTable.hidden=YES;
    [_carName resignFirstResponder];
}
}

And after this just if you are using pass that value as:

[self performSegueWithIdentifier:@"identifier" sender:self.carYear];

OR:

YourVCToPassValue *vc = [YourVCTOPassValue new];
vc.valueToBePassed = self.carYear;


问:
Convert a custom helper without LinqExpression to one using LinqExpression
I have a custom helper that works.

Custom helper without LinqExpression (this is working)

```<code>public static MvcHtmlString Image(this HtmlHelper html, byte[] image)
 {
   var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(image));
   return new MvcHtmlString("<img src='" + img + "'  />");
 }
</code>```

Using above custom helper (this works)

```<code>@Html.Image(item.Picture)
</code>```

I am trying to re-write the same custom helper using LinqExpression.

I have come up with the following code, but TModel and TValue are not being recognized in Visual Studio and also I am not sure how to get the byte[] value passed to this custom helper i.e. set the value of variable databaseImge.

I am getting following compile time errors when using the LinqExpression version of the custom helper.

The type or namespace name 'TModel' could not be found...
  The type or namespace name 'TValue' could not be found...

Question : What am I missing in my method and how would I get the value of item.Picture passed to this helper?

Custom Helper with LinqExpression (this is giving compile-time error)

```<code>public static MvcHtmlString DatabaseImage(this HtmlHelper htmlHelper, Expression<Func<TModel, TValue>> expression)
{

  //TModel model = (TModel)helper.ViewContext.ViewData.ModelMetadata.Model;
  //var metadata = ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData);
  var dastabaseImg = expression.Compile().Invoke(htmlHelper.ViewData.Model);
  var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(dastabaseImg));
  return new MvcHtmlString("<img src='" + img + "'  />");
}
</code>```

I would like to use the above LinqExpression helper, by using the below code, where item.Picture returns a byte[].

```<code> @Html.DatabaseImage(modeItem => item.Picture)
</code>```

答:
The signature of your method needs to be

```<code>public static MvcHtmlString DatabaseImage<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
</code>```

You should then use

```<code>ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData);
byte[] dastabaseImg = metadata.Model as byte[];
var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(dastabaseImg));
return new MvcHtmlString("<img src='" + img + "'  />");
</code>```

Body:
I have a custom helper that works.

Custom helper without LinqExpression (this is working)

public static MvcHtmlString Image(this HtmlHelper html, byte[] image)
 {
   var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(image));
   return new MvcHtmlString("");
 }

Using above custom helper (this works)

@Html.Image(item.Picture)

I am trying to re-write the same custom helper using LinqExpression.

I have come up with the following code, but TModel and TValue are not being recognized in Visual Studio and also I am not sure how to get the byte[] value passed to this custom helper i.e. set the value of variable databaseImge.

I am getting following compile time errors when using the LinqExpression version of the custom helper.

The type or namespace name 'TModel' could not be found...
  The type or namespace name 'TValue' could not be found...

Question : What am I missing in my method and how would I get the value of item.Picture passed to this helper?

Custom Helper with LinqExpression (this is giving compile-time error)

public static MvcHtmlString DatabaseImage(this HtmlHelper htmlHelper, Expression<Func<TModel, TValue>> expression)
{

  //TModel model = (TModel)helper.ViewContext.ViewData.ModelMetadata.Model;
  //var metadata = ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData);
  var dastabaseImg = expression.Compile().Invoke(htmlHelper.ViewData.Model);
  var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(dastabaseImg));
  return new MvcHtmlString("");
}

I would like to use the above LinqExpression helper, by using the below code, where item.Picture returns a byte[].

 @Html.DatabaseImage(modeItem => item.Picture)

Body:
The signature of your method needs to be

public static MvcHtmlString DatabaseImage<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)

You should then use

ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData);
byte[] dastabaseImg = metadata.Model as byte[];
var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(dastabaseImg));
return new MvcHtmlString("<img src='" + img + "'  />");


问:
MYSQL PHP veriable not working in WHERE IN() CLAUSE
```<code>$ci = implode('&#39,&#39', $_GET['city']);

$res = mysqli_query($link,"SELECT * FROM data WHERE (date BETWEEN '$dd1' AND '$dd2') AND (city IN('$ci')) ORDER BY id DESC")or die (mysql_error());
</code>```

If i echo $ci than it shows value JND','RJT','ABD but not working with variable

if i put directly  city IN ('JND','RJT','ABD') thn it works..

using veriable not perfoming query

答:
Try to check your query text</p>

```<code>$ci = implode("','", $_GET['city']);

$query = "SELECT * FROM data WHERE (date BETWEEN '$dd1' AND '$dd2') AND (city IN('$ci')) ORDER BY id DESC";

echo $query;

$res = mysqli_query($link,$query)or die (mysql_error());
</code>```

Body:
$ci = implode('&#39,&#39', $_GET['city']);

$res = mysqli_query($link,"SELECT * FROM data WHERE (date BETWEEN '$dd1' AND '$dd2') AND (city IN('$ci')) ORDER BY id DESC")or die (mysql_error());

If i echo $ci than it shows value JND','RJT','ABD but not working with variable

if i put directly  city IN ('JND','RJT','ABD') thn it works..

using veriable not perfoming query

Body:
Try to check your query text

$ci = implode("','", $_GET['city']);

$query = "SELECT * FROM data WHERE (date BETWEEN '$dd1' AND '$dd2') AND (city IN('$ci')) ORDER BY id DESC";

echo $query;

$res = mysqli_query($link,$query)or die (mysql_error());


问:
How best to do a JavaScript array with non-consecutive indexes?
I'm writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive ID numbers.

(This is because I need to be able to efficiently look up the values later, using an ID number that comes from another source outside my control.)

For example:

```<code>var myObjects = [] ;

myObjects[471] = {foo: "bar"} ;

myObjects[3119] = {hello: "goodbye"}
</code>```

When I do console.log(myObjects), in the console I see the entire array printed out, with all the thousands of 'missing' indexes showing undefined.

My question is: does this matter? Is this wasting any memory?

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

答:
First of all, everyone, please learn that what the for-in statement does is called enumeration (though it's an IterationStatement) in order to differentiate from iteration. This is very important, because it leads to confusion especially among beginners.

To answer the OP's question: It doesn't take up more space (test) (you could say it's implementation dependent, but we're talking about a Google Chrome Extension!), and it isn't slower either (test).

Yet my advice is: Use what's appropriate!
In this situation: use objects!

What you want to do with them is clearly a hashing mechanism, keys are converted to strings anyway so you can safely use object for this task.

I won't show you a lot of code, other answers do it already,  I've just wanted to make things clear.

```<code>// keys are converted to strings
// (numbers can be used safely)
var obj = {}
obj[1] = "value"
alert(obj[1])   // "value"
alert(obj["1"]) // "value"
</code>```

Note on sparse arrays

The main reason why a sparse array will NOT waste any space is because the specification doesn't say so. There is no point where it would require property accessors to check if the internal [[Class]] property is an "Array", and then create every element from 0 < i < len to be the value undefined etc. They just happen to be undefined when the toString method is iterating over the array. It basically means they are not there.

11.2.1 Property Accessors

The production MemberExpression : MemberExpression [ Expression ] is evaluated as follows:

Let baseReference be the result of evaluating MemberExpression.

Let baseValue be GetValue(baseReference).

Let propertyNameReference be the result of evaluating Expression.

Let propertyNameValue be GetValue(propertyNameReference).

Call CheckObjectCoercible(baseValue).

Let propertyNameString be ToString(propertyNameValue).

If the syntactic production that is being evaluated is contained in strict mode code, let strict be true, else let strict be false.

Return a value of type Reference whose base value is baseValue and whose referenced name is propertyNameString, and whose strict mode flag is strict.

The production CallExpression : CallExpression [ Expression ] is evaluated in exactly the same manner, except that the contained CallExpression is evaluated in step 1.

ECMA-262 5th Edition (http://www.ecma-international.org/publications/standards/Ecma-262.htm)

Body:
I'm writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive ID numbers.

(This is because I need to be able to efficiently look up the values later, using an ID number that comes from another source outside my control.)

For example:

var myObjects = [] ;

myObjects[471] = {foo: "bar"} ;

myObjects[3119] = {hello: "goodbye"}

When I do console.log(myObjects), in the console I see the entire array printed out, with all the thousands of 'missing' indexes showing undefined.

My question is: does this matter? Is this wasting any memory?

And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

Body:
First of all, everyone, please learn that what the for-in statement does is called enumeration (though it's an IterationStatement) in order to differentiate from iteration. This is very important, because it leads to confusion especially among beginners.

To answer the OP's question: It doesn't take up more space (test) (you could say it's implementation dependent, but we're talking about a Google Chrome Extension!), and it isn't slower either (test).

Yet my advice is: Use what's appropriate!
In this situation: use objects!

What you want to do with them is clearly a hashing mechanism, keys are converted to strings anyway so you can safely use object for this task.

I won't show you a lot of code, other answers do it already,  I've just wanted to make things clear.

// keys are converted to strings
// (numbers can be used safely)
var obj = {}
obj[1] = "value"
alert(obj[1])   // "value"
alert(obj["1"]) // "value"

Note on sparse arrays

The main reason why a sparse array will NOT waste any space is because the specification doesn't say so. There is no point where it would require property accessors to check if the internal [[Class]] property is an "Array", and then create every element from 0 < i < len to be the value undefined etc. They just happen to be undefined when the toString method is iterating over the array. It basically means they are not there.

11.2.1 Property Accessors

The production MemberExpression : MemberExpression [ Expression ] is evaluated as follows:

Let baseReference be the result of evaluating MemberExpression.

Let baseValue be GetValue(baseReference).

Let propertyNameReference be the result of evaluating Expression.

Let propertyNameValue be GetValue(propertyNameReference).

Call CheckObjectCoercible(baseValue).

Let propertyNameString be ToString(propertyNameValue).

If the syntactic production that is being evaluated is contained in strict mode code, let strict be true, else let strict be false.

Return a value of type Reference whose base value is baseValue and whose referenced name is propertyNameString, and whose strict mode flag is strict.

The production CallExpression : CallExpression [ Expression ] is evaluated in exactly the same manner, except that the contained CallExpression is evaluated in step 1.

ECMA-262 5th Edition (http://www.ecma-international.org/publications/standards/Ecma-262.htm)


问:
Cursor position in an editable  tag using highlight.js? Highlighting code "on the go" as you write it?
I'm quite new to all this stuff, currently I'm trying to highlight code as I write it. I'm using highlight.js, which is working just fine and styles all the code when I (re)load the site.

My problem comes when I write new code and it's not saved yet - those of you who are familiar with the library know what I'm talking about (I read the documentation a several times and I didn't find anything about live highlighting?)

So I replace my  tag on every keyup event inside it. This works fine and highlights, the problem is that my cursor always jumps to the beginning of the . Which is very user-enemy, if you want to keep writing your code and your cursor always jumps to the beginning.

I found some solutions on how to find cursor position in a textarea, but that doesn't work for me. I need to know the cursor position before the keyup event and when it happens, the replace function is called and I need to place my cursor in the same exact position.

Is there any way to do it? Can anybody advise me please?

/**
 * inits highlight.js upon changing the code
 */
$(document).on('keyup', '.js-grid__code-val code', function () {
    $('.js-grid__code-val code').each(function (i, block) {
        hljs.highlightBlock(block);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid__code-val js-grid__code-val">
  ```

  ```
</div></code>```

答:
I had the same problem and this solution using rangy worked for me.

Download rangy and import in your project:

```<code><script src="rangy/rangy-core.min.js"></script>
<script src="rangy/rangy-textrange.min.js"></script>
<script src="rangy/rangy-selectionsaverestore.min.js"></script>

<div class="grid__code-val js-grid__code-val">
    ```

    ```
</div>

<script>
     function highlightBlock(el) {
            let savedSel = rangy.saveSelection();
            hljs.highlightBlock(el);
            rangy.restoreSelection(savedSel);
    }
</script>
</code>```

/**
 * inits highlight.js upon changing the code
 */
$(document).on('keyup', '.js-grid__code-val code', function () {
    $('.js-grid__code-val code').each(function (i, block) {
        highlightBlock(block);
    });
});
```

Title: Cursor position in an editable <code> tag using highlight.js? Highlighting code "on the go" as you write it?

Body:
I had the same problem and this solution using rangy worked for me.

Download rangy and import in your project:

<script src="rangy/rangy-core.min.js"></script>
<script src="rangy/rangy-textrange.min.js"></script>
<script src="rangy/rangy-selectionsaverestore.min.js"></script>

<div class="grid__code-val js-grid__code-val">
    <pre>
        <code class="hljs" contenteditable=""></code>
    </pre>
</div>

<script>
     function highlightBlock(el) {
            let savedSel = rangy.saveSelection();
            hljs.highlightBlock(el);
            rangy.restoreSelection(savedSel);
    }
</script>

/**
 * inits highlight.js upon changing the code
 */
$(document).on('keyup', '.js-grid__code-val code', function () {
    $('.js-grid__code-val code').each(function (i, block) {
        highlightBlock(block);
    });
});


问:
php redirect to desktop site from mobile
I read alot from this site and try to create redirect to desktop site.
but it keep coming back to mobile site. At first, it was redirected but redirected back to mobile site while desktop site wasn't load completely.

Check the Full Site link

Here is my code -

```<code>$isPhone = preg_match('/' . implode($uaPhone, '|') . '/i', $uaFull);
$isMobile = preg_match('/' . implode($uaMobile, '|') . '/i', $uaStart);

if($isPhone || $isMobile) {
    $_SESSION["mb"]="jaw";
}

if(!isset($_SESSION['desktop'])) {
    $_SESSION['desktop'] = false;
} else if(isset($_GET['desktop']) && $_GET['desktop'] ==yes) {
    $_SESSION['desktop'] = true;
}

if(!$_SESSION['desktop']) {
    if (isset($_SESSION["MB"] )) {
      header ("Location: http://vipnet.byethost7.com/mobile/m.index.html");
    }
}
</code>```

答:
add exit after header

```<code> header ("Location: http://vipnet.byethost7.com/mobile/m.index.html");
</code>```

to

```<code> header ("Location: http://vipnet.byethost7.com/mobile/m.index.html");
 exit();
</code>```

Body:
I read alot from this site and try to create redirect to desktop site.
but it keep coming back to mobile site. At first, it was redirected but redirected back to mobile site while desktop site wasn't load completely.

Check the Full Site link

Here is my code -

$isPhone = preg_match('/' . implode($uaPhone, '|') . '/i', $uaFull);
$isMobile = preg_match('/' . implode($uaMobile, '|') . '/i', $uaStart);

if($isPhone || $isMobile) {
    $_SESSION["mb"]="jaw";
}

if(!isset($_SESSION['desktop'])) {
    $_SESSION['desktop'] = false;
} else if(isset($_GET['desktop']) && $_GET['desktop'] ==yes) {
    $_SESSION['desktop'] = true;
}

if(!$_SESSION['desktop']) {
    if (isset($_SESSION["MB"] )) {
      header ("Location: http://vipnet.byethost7.com/mobile/m.index.html");
    }
}

Body:
add exit after header

 header ("Location: http://vipnet.byethost7.com/mobile/m.index.html");

to

 header ("Location: http://vipnet.byethost7.com/mobile/m.index.html");
 exit();


问:
Add a diagonal of zeros to a matrix in MATLAB
Suppose I have a matrix A of dimension Nx(N-1) in MATLAB, e.g.

```<code>N=5;
A=[1  2  3  4;
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
   17 18 19 20 ];
</code>```

I want to transform A into an NxN matrix B, just by adding a zero diagonal, i.e.,

```<code>B=[ 0  1   2   3   4;
    5  0   6   7   8;
    9  10  0   11  12;
    13 14  15  0   16;
    17 18  19  20  0];
</code>```

This code does what I want:

```<code>B_temp = zeros(N,N);
B_temp(1,:) = [0 A(1,:)];
B_temp(N,:) = [A(N,:) 0];
for j=2:N-1
    B_temp(j,:)= [A(j,1:j-1) 0 A(j,j:end)];
end
B = B_temp;
</code>```

Could you suggest an efficient way to vectorise it?

答:
You can do this with upper and lower triangular parts of the matrix (triu and tril).

Then it's a 1 line solution:

```<code>B = [tril(A,-1) zeros(N, 1)] + [zeros(N,1) triu(A)];
</code>```

Edit: benchmark

This is a comparison of the loop method, the 2 methods in Sardar's answer, and my method above.

Benchmark code, using timeit for timing and directly lifting code from question and answers:

```<code>function benchie()
    N = 1e4; A = rand(N,N-1); % Initialise large matrix
    % Set up anonymous functions for input to timeit
    s1 = @() sardar1(A,N); s2 = @() sardar2(A,N);
    w =  @() wolfie(A,N); u = @() user3285148(A,N);
    % timings
    timeit(s1), timeit(s2), timeit(w), timeit(u)
end
function sardar1(A, N) % using eye as an indexing matrix
    B=double(~eye(N)); B(find(B))=A.'; B=B.';
end
function sardar2(A,N) % similar to sardar1, but avoiding slow operations
    B=1-eye(N); B(logical(B))=A.'; B=B.';
end
function wolfie(A,N) % using triangular parts of the matrix
    B = [tril(A,-1) zeros(N, 1)] + [zeros(N,1) triu(A)];
end
function user3285148(A, N) % original looping method
    B = zeros(N,N); B(1,:) = [0 A(1,:)]; B(N,:) = [A(N,:) 0];
    for j=2:N-1; B(j,:)= [A(j,1:j-1) 0 A(j,j:end)]; end
end
</code>```

Results:

Sardar method 1: 2.83 secs

Sardar method 2: 1.82 secs

My method: 1.45 secs

Looping method: 3.80 secs (!)

Conclusions:

Your desire to vectorise this was well founded, looping is way slower than other methods.

Avoiding data conversions and find for large matrices is important, saving ~35% processing time between Sardar's methods.

By avoiding indexing all together you can save a further 20% processing time.

Body:
Suppose I have a matrix A of dimension Nx(N-1) in MATLAB, e.g.

N=5;
A=[1  2  3  4;
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
   17 18 19 20 ];

I want to transform A into an NxN matrix B, just by adding a zero diagonal, i.e.,

B=[ 0  1   2   3   4;
    5  0   6   7   8;
    9  10  0   11  12;
    13 14  15  0   16;
    17 18  19  20  0];

This code does what I want:

B_temp = zeros(N,N);
B_temp(1,:) = [0 A(1,:)];
B_temp(N,:) = [A(N,:) 0];
for j=2:N-1
    B_temp(j,:)= [A(j,1:j-1) 0 A(j,j:end)];
end
B = B_temp;

Could you suggest an efficient way to vectorise it?

Body:
You can do this with upper and lower triangular parts of the matrix (triu and tril).

Then it's a 1 line solution:

B = [tril(A,-1) zeros(N, 1)] + [zeros(N,1) triu(A)];

Edit: benchmark

This is a comparison of the loop method, the 2 methods in Sardar's answer, and my method above.

Benchmark code, using timeit for timing and directly lifting code from question and answers:

function benchie()
    N = 1e4; A = rand(N,N-1); % Initialise large matrix
    % Set up anonymous functions for input to timeit
    s1 = @() sardar1(A,N); s2 = @() sardar2(A,N);
    w =  @() wolfie(A,N); u = @() user3285148(A,N);
    % timings
    timeit(s1), timeit(s2), timeit(w), timeit(u)
end
function sardar1(A, N) % using eye as an indexing matrix
    B=double(~eye(N)); B(find(B))=A.'; B=B.';
end
function sardar2(A,N) % similar to sardar1, but avoiding slow operations
    B=1-eye(N); B(logical(B))=A.'; B=B.';
end
function wolfie(A,N) % using triangular parts of the matrix
    B = [tril(A,-1) zeros(N, 1)] + [zeros(N,1) triu(A)];
end
function user3285148(A, N) % original looping method
    B = zeros(N,N); B(1,:) = [0 A(1,:)]; B(N,:) = [A(N,:) 0];
    for j=2:N-1; B(j,:)= [A(j,1:j-1) 0 A(j,j:end)]; end
end

Results:

Sardar method 1: 2.83 secs

Sardar method 2: 1.82 secs

My method: 1.45 secs

Looping method: 3.80 secs (!)

Conclusions:

Your desire to vectorise this was well founded, looping is way slower than other methods.

Avoiding data conversions and find for large matrices is important, saving ~35% processing time between Sardar's methods.

By avoiding indexing all together you can save a further 20% processing time.


问:
How to check if a string starts with another string in C?
Is there something like startsWith(str_a, str_b) in the standard C library?

It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.

Examples:

```<code>"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc"    -> true
</code>```

答:
I'd probably go with strncmp(), but just for fun a raw implementation:

```<code>_Bool starts_with(const char *restrict string, const char *restrict prefix)
{
    while(*prefix)
    {
        if(*prefix++ != *string++)
            return 0;
    }

    return 1;
}
</code>```

Body:
Is there something like startsWith(str_a, str_b) in the standard C library?

It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.

Examples:

"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc"    -> true

Body:
I'd probably go with strncmp(), but just for fun a raw implementation:

_Bool starts_with(const char *restrict string, const char *restrict prefix)
{
    while(*prefix)
    {
        if(*prefix++ != *string++)
            return 0;
    }

    return 1;
}


问:
Unity3D setting velocity won't take effect immediately in OnCollisionEnter
I have a simple script to set the velocity to zero when a collision with something, but seems it won't work immediately:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveController : MonoBehaviour {

    [SerializeField]
    private float shootVelocity=30f;

    void Start () {

    }

    private void OnGUI()
    {
        if(GUI.Button(new Rect(0,0,100,100), "shoot"))
        {
            GetComponent<Rigidbody>().velocity = shootVelocity * Vector3.forward;
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        GetComponent<Rigidbody>().velocity = Vector3.zero;
        GetComponent<Rigidbody>().isKinematic = true;
    }

}
</code>```

I also have made a youtube video to demonstrate the problem.

It's really important to make the ball stop immediately after a collision happens.

How to do that?

答:
That's how physics work.

If the moving object has higher velocity, it would have higher momentum hence would take more time to stop.

You can try updating your code like this to make it more efficient.

```<code>public class MoveController : MonoBehaviour
{

    [SerializeField]
    private float shootVelocity=30f;

    Rigidbody rb;
    void Start ()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void OnGUI()
    {
        if(GUI.Button(new Rect(0,0,100,100), "shoot"))
        {
            rb.velocity = shootVelocity * Vector3.forward;
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        rb.isKinematic = true;
        rb.velocity = Vector3.zero;
        rb.angularVelocity = Vector3.zero;
    }
}
</code>```

Hope this helps :)

Body:
I have a simple script to set the velocity to zero when a collision with something, but seems it won't work immediately:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveController : MonoBehaviour {

    [SerializeField]
    private float shootVelocity=30f;

    void Start () {

    }

    private void OnGUI()
    {
        if(GUI.Button(new Rect(0,0,100,100), "shoot"))
        {
            GetComponent<Rigidbody>().velocity = shootVelocity * Vector3.forward;
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        GetComponent<Rigidbody>().velocity = Vector3.zero;
        GetComponent<Rigidbody>().isKinematic = true;
    }

}

I also have made a youtube video to demonstrate the problem.

It's really important to make the ball stop immediately after a collision happens.

How to do that?

Body:
That's how physics work.

If the moving object has higher velocity, it would have higher momentum hence would take more time to stop.

You can try updating your code like this to make it more efficient.

public class MoveController : MonoBehaviour
{

    [SerializeField]
    private float shootVelocity=30f;

    Rigidbody rb;
    void Start ()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void OnGUI()
    {
        if(GUI.Button(new Rect(0,0,100,100), "shoot"))
        {
            rb.velocity = shootVelocity * Vector3.forward;
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        rb.isKinematic = true;
        rb.velocity = Vector3.zero;
        rb.angularVelocity = Vector3.zero;
    }
}

Hope this helps :)


问:
Comparing rotated images
I'm looking for a way to compare images that are almost identical (95%+ similarity) but that could be rotated around a central axis.

I'm new to the whole computer graphics/vision field, and not really sure if there is a ready built tool or system for it, or even if this is the right stack exchange to ask on.

Currently, I'm investigating using C# to generate a bitmap histogram, then running it through Panda for analysis and to ideally group the images based on the similarity of histograms, though I've heard something like OpenCv + tesseract may be a viable alternative.

答:
You need to compute the affine transformation matrix between your two images in order the get the information regarding scaling, translation and rotation.

How this matrix looks and how can you get the rotation difference?

From this answer:

I have used the following Java code (using OpenCV 3.2) which computes the scaling, translation and rotation difference between two Mat images. I hope you will find it useful.

```<code>static void calculateDifferences(Mat img1, Mat img2){

        // Initialization
        FeatureDetector detector = FeatureDetector.create(FeatureDetector.ORB);
        DescriptorExtractor descriptor = DescriptorExtractor.create(DescriptorExtractor.ORB);
        DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);

        // First image objects
        Mat img1_descriptors = new Mat();
        MatOfKeyPoint img1_keypoints_mat = new MatOfKeyPoint();

        // Detect KeyPoints for first image
        detector.detect(img1, img1_keypoints_mat);
        descriptor.compute(img1, img1_keypoints_mat, img1_descriptors);

        // Second image objects
        Mat img2_descriptors = new Mat();
        MatOfKeyPoint img2_keypoints_mat = new MatOfKeyPoint();

        // Detect KeyPoints for second image
        detector.detect(img2, img2_keypoints_mat);
        descriptor.compute(img2, img2_keypoints_mat, img2_descriptors);

        // Match KeyPoints
        MatOfDMatch matOfDMatch = new MatOfDMatch();
        matcher.match(img1_descriptors, img2_descriptors, matOfDMatch);

        // Filtering the matches
        List<DMatch> dMatchList = matOfDMatch.toList();
        Double max_dist = 0.0;
        Double min_dist = 100.0;

        for(int i = 0; i < img1_descriptors.rows(); i++){
            Double dist = (double) dMatchList.get(i).distance;
            if(dist < min_dist) min_dist = dist;
            if(dist > max_dist) max_dist = dist;
        }
        LinkedList<DMatch> good_matches = new LinkedList<>();
        for(int i = 0; i < img1_descriptors.rows(); i++){
            if(dMatchList.get(i).distance < 3*min_dist){
                good_matches.addLast(dMatchList.get(i));
            }
        }

        // Converting to MatOfPoint2f format
        LinkedList<Point> img1_points_list = new LinkedList<>();
        LinkedList<Point> img2_points_list = new LinkedList<>();

        List<KeyPoint> img1_keyPoints_list = img1_keypoints_mat.toList();
        List<KeyPoint> img2_keyPoints_list = img2_keypoints_mat.toList();

        int limit = good_matches.size();
        for(int i = 0; i < limit; i++){
            img1_points_list.addLast(img1_keyPoints_list.get(good_matches.get(i).queryIdx).pt);
            img2_points_list.addLast(img2_keyPoints_list.get(good_matches.get(i).trainIdx).pt);
        }

        MatOfPoint2f img1_point2f_mat = new MatOfPoint2f();
        img1_point2f_mat.fromList(img1_points_list);

        MatOfPoint2f img2_point2f_mat = new MatOfPoint2f();
        img2_point2f_mat.fromList(img2_points_list);

        // Computing the affine transform matrix
        Mat result = Video.estimateRigidTransform(img1_point2f_mat, img2_point2f_mat, true);
        printMat(result); // Printing the optimal affine transformation 2x3 array

        // The following variables correspond to the estimateRigidTransform result as shown here: https://stackoverflow.com/a/29511091/5165833
        double a = result.get(0,0)[0];
        double b = result.get(0,1)[0];
        double d = result.get(1,1)[0];
        double c = result.get(1,0)[0];
        double tx = result.get(0,2)[0];
        double ty = result.get(1,2)[0];

        // Solving for scale,translation and rotation as shown in the link above
        double scale_x = Math.signum(a) * Math.sqrt( (a*a) + (b*b) ); // Axis x scale difference
        double scale_y = Math.signum(d) * Math.sqrt( (c*c) + (d*d) ); // Axis y scale difference
        double translation = ty; // The translation difference
        double rotation_angle = Math.atan2(c,d); // Rotation difference

        // Printing results
        println("Scale_x diff: " + scale_x);
        println("Scale_y diff: " + scale_y);
        println("Translation diff: " + translation);
        println("Rotation diff: " + rotation_angle);
    }

    static void printMat(Mat m)
    {
        for (int x=0; x < m.height(); x++) {
            for (int y=0; y < m.width(); y++) {
                System.out.printf("%f",m.get(x,y)[0]);
                System.out.printf("%s"," ");
            }
            System.out.println();
        }
    }
</code>```

Title: Comparing rotated images

Body:
You need to compute the affine transformation matrix between your two images in order the get the information regarding scaling, translation and rotation.

How this matrix looks and how can you get the rotation difference?

From this answer:

I have used the following Java code (using OpenCV 3.2) which computes the scaling, translation and rotation difference between two Mat images. I hope you will find it useful.

static void calculateDifferences(Mat img1, Mat img2){

        // Initialization
        FeatureDetector detector = FeatureDetector.create(FeatureDetector.ORB);
        DescriptorExtractor descriptor = DescriptorExtractor.create(DescriptorExtractor.ORB);
        DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);

        // First image objects
        Mat img1_descriptors = new Mat();
        MatOfKeyPoint img1_keypoints_mat = new MatOfKeyPoint();

        // Detect KeyPoints for first image
        detector.detect(img1, img1_keypoints_mat);
        descriptor.compute(img1, img1_keypoints_mat, img1_descriptors);

        // Second image objects
        Mat img2_descriptors = new Mat();
        MatOfKeyPoint img2_keypoints_mat = new MatOfKeyPoint();

        // Detect KeyPoints for second image
        detector.detect(img2, img2_keypoints_mat);
        descriptor.compute(img2, img2_keypoints_mat, img2_descriptors);

        // Match KeyPoints
        MatOfDMatch matOfDMatch = new MatOfDMatch();
        matcher.match(img1_descriptors, img2_descriptors, matOfDMatch);

        // Filtering the matches
        List<DMatch> dMatchList = matOfDMatch.toList();
        Double max_dist = 0.0;
        Double min_dist = 100.0;

        for(int i = 0; i < img1_descriptors.rows(); i++){
            Double dist = (double) dMatchList.get(i).distance;
            if(dist < min_dist) min_dist = dist;
            if(dist > max_dist) max_dist = dist;
        }
        LinkedList<DMatch> good_matches = new LinkedList<>();
        for(int i = 0; i < img1_descriptors.rows(); i++){
            if(dMatchList.get(i).distance < 3*min_dist){
                good_matches.addLast(dMatchList.get(i));
            }
        }

        // Converting to MatOfPoint2f format
        LinkedList<Point> img1_points_list = new LinkedList<>();
        LinkedList<Point> img2_points_list = new LinkedList<>();

        List<KeyPoint> img1_keyPoints_list = img1_keypoints_mat.toList();
        List<KeyPoint> img2_keyPoints_list = img2_keypoints_mat.toList();

        int limit = good_matches.size();
        for(int i = 0; i < limit; i++){
            img1_points_list.addLast(img1_keyPoints_list.get(good_matches.get(i).queryIdx).pt);
            img2_points_list.addLast(img2_keyPoints_list.get(good_matches.get(i).trainIdx).pt);
        }

        MatOfPoint2f img1_point2f_mat = new MatOfPoint2f();
        img1_point2f_mat.fromList(img1_points_list);

        MatOfPoint2f img2_point2f_mat = new MatOfPoint2f();
        img2_point2f_mat.fromList(img2_points_list);

        // Computing the affine transform matrix
        Mat result = Video.estimateRigidTransform(img1_point2f_mat, img2_point2f_mat, true);
        printMat(result); // Printing the optimal affine transformation 2x3 array

        // The following variables correspond to the estimateRigidTransform result as shown here: https://stackoverflow.com/a/29511091/5165833
        double a = result.get(0,0)[0];
        double b = result.get(0,1)[0];
        double d = result.get(1,1)[0];
        double c = result.get(1,0)[0];
        double tx = result.get(0,2)[0];
        double ty = result.get(1,2)[0];

        // Solving for scale,translation and rotation as shown in the link above
        double scale_x = Math.signum(a) * Math.sqrt( (a*a) + (b*b) ); // Axis x scale difference
        double scale_y = Math.signum(d) * Math.sqrt( (c*c) + (d*d) ); // Axis y scale difference
        double translation = ty; // The translation difference
        double rotation_angle = Math.atan2(c,d); // Rotation difference

        // Printing results
        println("Scale_x diff: " + scale_x);
        println("Scale_y diff: " + scale_y);
        println("Translation diff: " + translation);
        println("Rotation diff: " + rotation_angle);
    }

    static void printMat(Mat m)
    {
        for (int x=0; x < m.height(); x++) {
            for (int y=0; y < m.width(); y++) {
                System.out.printf("%f",m.get(x,y)[0]);
                System.out.printf("%s"," ");
            }
            System.out.println();
        }
    }


问:
Reading XML file via VBA
I am trying to read a XML file (this is not in a correct format). Below is the actual XML file that I have.

<?xml version="1.0" encoding="UTF-8"?><Report time="8/18/2017 12:54:42">
TABLE
<Application>Fruits</Application><Environment>AMAZON</Environment><Group>FOREST</Group><SubGroup>RAINFOREST</SubGroup><Row>3</Row><Release>SEPT</Release><Result>Pass</Result><Testname>HEALTHCHECK</Testname><Screenshotpath>C:\PracSession\ABC.png"</Screenshotpath></Report>
```

<p>Now I am trying to read this and save the XML format, but unable to get any further.</p>

<p>Format that I want and save it:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<Report time="8/18/2017 12:54:42">
<Table>TABLE</Table>
<Application>Fruits</Application>
<Environment>AMAZON</Environment>
<Group>FOREST</Group>
<SubGroup>RAINFOREST</SubGroup>
<Row>3</Row>
<Release>SEPT</Release>
<Result>Pass</Result>
<Testname>HEALTHCHECK</Testname>
<Screenshotpath>C:\PracSession\ABC.png"</Screenshotpath>
</Report>
</code>```

I am able to check the format but not able to save it. Below is the code that I have tried.

```<code>Public Sub Create_Report()
myFile = "C:\Prac_Session\OLB.xml"
Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(myFile, ForReading, False)
Do While Not txtStream.AtEndOfStream
    Debug.Print txtStream.ReadLine
    Tempstr = ">" & vbNewLine & "<"
    a = Replace(txtStream.ReadLine, "><", Tempstr)
    Debug.Print a
    ''Now to save.??''
Loop
txtStream.Close

End Sub
</code>```

答: The MSXML DOM library has a pretty print feature buried within it.  This blog post The Excel Development Platform_ VBA - Ease Xml debugging wth Xml document pretty print has some sample source code</p>

Title: Reading XML file via VBA

Body:
I am trying to read a XML file (this is not in a correct format). Below is the actual XML file that I have.

<?xml version="1.0" encoding="UTF-8"?><Report time="8/18/2017 12:54:42">
TABLE
<Application>Fruits</Application><Environment>AMAZON</Environment><Group>FOREST</Group><SubGroup>RAINFOREST</SubGroup><Row>3</Row><Release>SEPT</Release><Result>Pass</Result><Testname>HEALTHCHECK</Testname><Screenshotpath>C:\PracSession\ABC.png"</Screenshotpath></Report>

Now I am trying to read this and save the XML format, but unable to get any further.

Format that I want and save it:

<?xml version="1.0" encoding="UTF-8"?>
<Report time="8/18/2017 12:54:42">

TABLE

<Application>Fruits</Application>
<Environment>AMAZON</Environment>
<Group>FOREST</Group>
<SubGroup>RAINFOREST</SubGroup>
<Row>3</Row>
<Release>SEPT</Release>
<Result>Pass</Result>
<Testname>HEALTHCHECK</Testname>
<Screenshotpath>C:\PracSession\ABC.png"</Screenshotpath>
</Report>

I am able to check the format but not able to save it. Below is the code that I have tried.

Public Sub Create_Report()
myFile = "C:\Prac_Session\OLB.xml"
Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(myFile, ForReading, False)
Do While Not txtStream.AtEndOfStream
    Debug.Print txtStream.ReadLine
    Tempstr = ">" & vbNewLine & "<"
    a = Replace(txtStream.ReadLine, "><", Tempstr)
    Debug.Print a
    ''Now to save.??''
Loop
txtStream.Close

End Sub