问:
Angular 2 - get datas from a json file
How can I get my datas from a JSON in an angular 2 project? I tried (code below) but this doesn't work. Maybe I forgot some details... thanks a lot for an answer

Ps. I need to display on my html that "uno" included in json file.

app.component.ts:

```<code>     import { Component } from '@angular/core';
     import {Http} from '@angular/http';

    @Component({
        selector: 'app-header',
        templateUrl: '../partials/app.header.html',
        styleUrls: ['../css/partials/app.header.css']
    })
        export class AppComponent {
          title = 'app works!';
          data;
          constructor(private http:Http) {
                this.http.get('app/header.json')
               .subscribe(res => this.data = res.json());
          }
        }
</code>```

app.module.ts:

```<code>    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { AppComponent } from './app.component';

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
</code>```

app.header.html:

```<code><header>
    {{title}}//this works
    {{elemento}}//here i want to show "uno" included in json file
    ...
</header>
</code>```

header.json:

```<code>    {
        "elemento": "uno"
    }
</code>```

答:
Just do,</p>

```<code><header>
    {{title}}
    {{data?.elemento}}
</header>
</code>```

Title: Angular 2 - get datas from a json file

Body:
How can I get my datas from a JSON in an angular 2 project? I tried (code below) but this doesn't work. Maybe I forgot some details... thanks a lot for an answer

Ps. I need to display on my html that "uno" included in json file.

app.component.ts:

     import { Component } from '@angular/core';
     import {Http} from '@angular/http';

    @Component({
        selector: 'app-header',
        templateUrl: '../partials/app.header.html',
        styleUrls: ['../css/partials/app.header.css']
    })
        export class AppComponent {
          title = 'app works!';
          data;
          constructor(private http:Http) {
                this.http.get('app/header.json')
               .subscribe(res => this.data = res.json());
          }
        }

app.module.ts:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { AppComponent } from './app.component';

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

app.header.html:

    {{title}}//this works
    {{elemento}}//here i want to show "uno" included in json file
    ...

header.json:

    {
        "elemento": "uno"
    }

Body:
Just do,

<header>
    {{title}}
    {{data?.elemento}}
</header>


来源: stackexchange

问:
Need help in teradata
In one of the tables I've a time column where the data is something like this :
01:21:00.000000
 for all the records.

I want to retrieve the data which looks like below.

01:21:00  in teradata.

Please advise. I'm new to teradata and don't know how to achieve this

答:
If your column is timestamp, then we can use Timestamp(0) is  YYYY-MM-DDbHH:MI:SS and Timestamp(6) is YYYY-MM-DDbHH:MI:SS.ssssss (milliseconds extra).

If your column is just time, then we can use 'CAST'.

select cast( as time(0)) from ;

ContentLicense: CC BY-SA 3.0

Title: Need help in teradata


问:
Python IPv6 Bytes To Address
I am running python on the iOS App Pythonista 3.
When I try to get an IPv6 address it ends up
returning bytes rather than a formatted address.
Right now I am trying to find a way to either get the address properly without bytes, or to find a way to make the bytes become the address.
Here is the code I ran to get the address:

```<code>def getIPv6Addr(input):
    return socket.getaddrinfo(input, None, socket.AF_INET6)
</code>```

and here was the output:

```<code>[(30, 2, 17, '', (30, '\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14')), (30, 1, 6, '', (30, '\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14'))]
</code>```

Edit: The alternative solution is to find what type of encoding is being used to turn this data into bytes.

```<code>What Makes:
2607:f8b0:4000:814::200e
become
\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14
</code>```

答: You can use the ipaddress module that is included with python. Just pass the bytes to the constructor of ipaddress.IPv6Address and you'll get an object representing the address and giving you lots of possibilities to print and manipulate it.

Title: Python IPv6 Bytes To Address

Body:
I am running python on the iOS App Pythonista 3.
When I try to get an IPv6 address it ends up
returning bytes rather than a formatted address.
Right now I am trying to find a way to either get the address properly without bytes, or to find a way to make the bytes become the address.
Here is the code I ran to get the address:

def getIPv6Addr(input):
    return socket.getaddrinfo(input, None, socket.AF_INET6)

and here was the output:

[(30, 2, 17, '', (30, '\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14')), (30, 1, 6, '', (30, '\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14'))]

Edit: The alternative solution is to find what type of encoding is being used to turn this data into bytes.

What Makes:
2607:f8b0:4000:814::200e
become
\x00\x00\x00\x00\x00\x00&\x07\xf8\xb0@\x00\x08\x14


问:
Resizing Custom MKAnnotationView According to MapKit Zoom Level
Here is the situation:
I am displaying images on the map by using custom annotations. Everything works fine but I would like to improve it visually by resizing the AnnotationView so that it shrinks as the map is zoomed out. I want to do this because, obviously, more annotations fill up the screen and need to be shrunk so that they don't overlap each other too much and the user can see more annotations. (Of course, I would like to enlarge AnnotationViews when the map is zoomed in again).

I have achieved this by removing all annotations from the map and adding them back again, whenever regionDidChangeAnimated is called. However, these images are loaded from the internet, so downloading the images again (since the annotations have been removed) doesn't seem to make sense.

I hope I have explained the situation well, and hope to contribute to SO in the future.

Thanks in advance.

P.S. I'm developing with iOS 4.0

答: It sounds like you're already on the right path and that the only real problem is the downloading of the images. Is there any particular reason you can't cache them by writing them to the documents directory (or the cache directory if you want them to go way when the app quits) when you receive them and look there first before displaying them?</p>

ContentLicense: CC BY-SA 2.5


问:
How to create a date range with php?
I tried to make time with PHP. start date of 2017-01-29 to 2017-12-29. But that happened I could not print in February because the month maximum of only 28 days. How to order printed anyway but with the February date up to 28.

my script:

```<code>date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
    echo "$date\n";
    echo "<br>";
    $date = date ("Y-m-d", strtotime("+1 month", strtotime($date)));
}
</code>```

Output:

答:
use this

```<code>date ("Y-m-t", strtotime("+1 month", strtotime($date)));
</code>```

instead of this to get last day of the month

```<code>date ("Y-m-d", strtotime("+1 month", strtotime($date)));
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to create a date range with php?

Body:
I tried to make time with PHP. start date of 2017-01-29 to 2017-12-29. But that happened I could not print in February because the month maximum of only 28 days. How to order printed anyway but with the February date up to 28.

my script:

date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
    echo "$date\n";
    echo "
";
    $date = date ("Y-m-d", strtotime("+1 month", strtotime($date)));
}

Output:

Body:
use this

date ("Y-m-t", strtotime("+1 month", strtotime($date)));

instead of this to get last day of the month

date ("Y-m-d", strtotime("+1 month", strtotime($date)));


问:
How to select
 inside

Assume I have html structure as

```<code>ul
  li //this one
    ul
      li
      li
      li
  li //this one
</code>```

I don't want to get all li's.
As I commented I just want to get first segment li's. How can I select them?

```<code>document.querySelectorAll("ul > li");
</code>```

returns all li's.

edit: actually this is just a snippet of the tree.

I can't modify the structure as adding class or id. I'm looking for an answer to get the list of first layer lis

答:
You can add an id to that specific li:

```<code><li id="someID"></li>
</code>```

then select it using:

```<code>var chosenOne = document.getElementById("someID");
</code>```

Title: How to select <li> inside <ul>

Body:
Assume I have html structure as

ul
  li //this one
    ul
      li
      li
      li
  li //this one

I don't want to get all li's.
As I commented I just want to get first segment li's. How can I select them?

document.querySelectorAll("ul > li");

returns all li's.

edit: actually this is just a snippet of the tree.

I can't modify the structure as adding class or id. I'm looking for an answer to get the list of first layer lis

Body:
You can add an id to that specific li:

<li id="someID"></li>

then select it using:

var chosenOne = document.getElementById("someID");


答:
just do this</p>

```<code>{{data?.elemento}}
</code>```

Title: Angular 2 - get datas from a json file

Body:
just do this

{{data?.elemento}}


问:
How to get document root path in PHP with CLI?

```<code>echo __DIR__;
</code>```

"    How to get document root path in PHP from any subdirectory using command line?

```<code>my directory structure--

/dinesh
       /data
            /asset
</code>```

Suppose my root directry is /dinesh

and currently my script in asset but I require document root path till /dinesh only

by using command line php CLI

How will I get this?

I have tried DIR and FILE but that give path till  asset and one more thing that dinesh is my local root folder  name that is changeable when I move my code to other server"

答: echo($_SERVER["PWD"]); its working</p>

Body:
echo __DIR__;

"    How to get document root path in PHP from any subdirectory using command line?

my directory structure--

/dinesh
       /data
            /asset

Suppose my root directry is /dinesh

and currently my script in asset but I require document root path till /dinesh only

by using command line php CLI

How will I get this?

I have tried DIR and FILE but that give path till  asset and one more thing that dinesh is my local root folder  name that is changeable when I move my code to other server"

Body: echo($_SERVER["PWD"]); its working


问:
MySQL Table - Display name once along with their total score
I have the below data entered into a database from a website:

```<code> USER  |  SCORE
 abc   |    4
 ghi   |    2
 abc   |    6
 def   |    1
 abc   |    3
</code>```

I want to now display a list of all the users, in alphabetical order, without repeating itself, and their total score. So with the table above, it would look something like:

```<code> abc: 13
 def: 1
 ghi: 2
</code>```

How do I do that? I would use php, right? Or javascript?

答:
You need to fetch data from table and iterate through it. Below is SQL:</p>

```<code>   SELECT User, SUM(Score) as total
   FROM TABLE_NAME
   GROUP BY User
   ORDER BY User;
</code>```

Body:
I have the below data entered into a database from a website:

 USER  |  SCORE
 abc   |    4
 ghi   |    2
 abc   |    6
 def   |    1
 abc   |    3

I want to now display a list of all the users, in alphabetical order, without repeating itself, and their total score. So with the table above, it would look something like:

 abc: 13
 def: 1
 ghi: 2

How do I do that? I would use php, right? Or javascript?

Body:
You need to fetch data from table and iterate through it. Below is SQL:

   SELECT User, SUM(Score) as total
   FROM TABLE_NAME
   GROUP BY User
   ORDER BY User;


问:
got 'VerifyError' when Mock in Spock1.1
when i try to mock a spring service, i got verifyError. i have check spock version and groovy version, it's seens no problem. can somebody point me how to resovle this issue ? Thanks!

Spock version: spock-core-1.1-groovy-2.4-rc-3.jar

Groovy version: groovy-all-2.4.6.jar

Cglib version: cglib-nodep-3.2.4.jar

java.lang.VerifyError: class net.sf.cglib.core.DebuggingClassWriter overrides final method visit.(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at net.sf.cglib.core.AbstractClassGenerator.(AbstractClassGenerator.java:38)
at net.sf.cglib.core.KeyFactory$Generator.(KeyFactory.java:127)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:112)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
at net.sf.cglib.proxy.Enhancer.(Enhancer.java:69)
at org.spockframework.mock.runtime.ProxyBasedMockFactory$CglibMockFactory.createMock(ProxyBasedMockFactory.java:144)
at org.spockframework.mock.runtime.ProxyBasedMockFactory.create(ProxyBasedMockFactory.java:66)
at org.spockframework.mock.runtime.JavaMockFactory.createInternal(JavaMockFactory.java:59)
at org.spockframework.mock.runtime.JavaMockFactory.create(JavaMockFactory.java:40)
at org.spockframework.mock.runtime.CompositeMockFactory.create(CompositeMockFactory.java:44)
at org.spockframework.lang.SpecInternals.createMock(SpecInternals.java:45)
at org.spockframework.lang.SpecInternals.createMockImpl(SpecInternals.java:281)
at org.spockframework.lang.SpecInternals.MockImpl(SpecInternals.java:99)
at com.example.apiimpl.query.UserAccountAuthQueryServiceSpec.setup(UserAccountAuthQueryServiceSpec.groovy:86)

答: cglib is no longer actively maintained and it has some problems dealing with newer byte code. Spock is capable of using Byte Buddy for code generation if you use a newer version. Just put it on the class path for using it.</p>

Title: got 'VerifyError' when Mock in Spock1.1


问:
C# TrimEnd trimming too many chars
I'm seeing odd results when using string.TrimEnd() method

```<code>var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd("freshviprint01".ToCharArray());
Console.WriteLine(x);
</code>```

Produces

FDLBicester.

However, slightly changing the TrimEnd to include the . as well:

```<code>var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd(".freshviprint01".ToCharArray());
Console.WriteLine(x);
</code>```

Produces

FDLBic

????

Why am I losing ester by also trimming the .?

答:
TrimEnd() will trim all the characters passed to it.

When you don't pass the . the trimming stops there, since the . isn't in the list of chars to trim.

When you do pass the ., then it is in the list of chars to trim - and so are several other characters before it (namely, e, s, t and r), which therefore also get trimmed.

Title: C# TrimEnd trimming too many chars

Body:
I'm seeing odd results when using string.TrimEnd() method

var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd("freshviprint01".ToCharArray());
Console.WriteLine(x);

Produces

FDLBicester.

However, slightly changing the TrimEnd to include the . as well:

var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd(".freshviprint01".ToCharArray());
Console.WriteLine(x);

Produces

FDLBic

????

Why am I losing ester by also trimming the .?


问:
add tag base on variable in loop
imagine I have to generate a list of li

```<code>{map(listItems, (obj,i) =>
    <li key={i}>
      <a target="_blank" href={obj.itemName === 'view_detail' ? `event/${id}` : ''} >
            <i className={obj.icon}></i>
            {obj.name}
      </a>
    </li>
)}
</code>```

this won't work, because even the li is not view_detail, it will still have target blank.

答:
As one of solution - change target dynamicly as href</p>

```<code><li key={i}>
      <a target={obj.itemName === 'view_detail' ? `_blank` : ''} href={obj.itemName === 'view_detail' ? `event/${id}` : ''} >
            <i className={obj.icon}></i>
            {obj.name}
      </a>
    </li>
</code>```

Title: add tag base on variable in loop

Body:
imagine I have to generate a list of li

{map(listItems, (obj,i) =>

      <a target="_blank" href={obj.itemName === 'view_detail' ? `event/${id}` : ''} >

            {obj.name}

)}

this won't work, because even the li is not view_detail, it will still have target blank.

Body:
As one of solution - change target dynamicly as href

<li key={i}>
      <a target={obj.itemName === 'view_detail' ? `_blank` : ''} href={obj.itemName === 'view_detail' ? `event/${id}` : ''} >
            <i className={obj.icon}></i>
            {obj.name}
      </a>
    </li>


答:
TrimEnd trimms every character from the end that is part of the passed trim array, and repeats this until the last character of the string is not part of the array.

```<code>var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd(".freshviprint01".ToCharArray());
</code>```

The chars in cester.freshviprint01 are all part of the trim array, that's why they get removed. It does not matter in which order they are passed.

```<code>var x = s.TrimEnd(".01efihnprstv".ToCharArray());
</code>```

would have the same result.

Title: C# TrimEnd trimming too many chars

Body:
TrimEnd trimms every character from the end that is part of the passed trim array, and repeats this until the last character of the string is not part of the array.

var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd(".freshviprint01".ToCharArray());

The chars in cester.freshviprint01 are all part of the trim array, that's why they get removed. It does not matter in which order they are passed.

var x = s.TrimEnd(".01efihnprstv".ToCharArray());

would have the same result.


问:
Drupal — disable CSS cache
I am using Drupal 6. Every time I modify the CSS files, I need to clear the cache to see the updated result, which is a waste of my time. Is there any way to disable the cache system?</p>

答: Have a look at Disabling the Drupal cache. That should get you going in the right direction.</p>

Title: Drupal — disable CSS cache


问:
Spring boot JNDI datasource lookup failure - Name comp/env/jdbc not found in context "java:"
I have setup a spring boot (v 1.1.9) application to deploy as a WAR file. And I'm trying to integrate this web application with an existing data service module (added as a maven dependency).

Environment trying to deploy: WebSphere Application Server 8.5.5.4

The issue I'm facing is an application start-up failure when try to look-up a JNDI dataSource (jdbc/fileUploadDS) as below within the dependent data service module.

```<code>@Configuration
@Profile("prod")
public class JndiDataConfig implements DataConfig {

    @Bean
    public DataSource dataSource() throws NamingException {
          Context ctx = new InitialContext();
          return (DataSource) ctx.lookup("java:comp/env/jdbc/fileUploadDS");
    }

}
</code>```

My Spring Boot configuration:

```<code>@Configuration
@ComponentScan(basePackages = { "au.com.aiaa.fileupload.data.*", "demo" })
@EnableAutoConfiguration(exclude = { HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class })
public class SampleApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(applicationClass, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(applicationClass);
    }

    private static Class<SampleApplication> applicationClass = SampleApplication.class;

    @Bean
    public static Properties fileUploadJndiProperties() throws NamingException {
        JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
        jndiFactoryBean.setJndiName("props/FileUploadProperties");
        jndiFactoryBean.setExpectedType(Properties.class);
        jndiFactoryBean.setLookupOnStartup(true);
        jndiFactoryBean.afterPropertiesSet();
        return (Properties) jndiFactoryBean.getObject();
    }

}
</code>```

Note that I'm able to lookup props/FileUploadProperties successfully. But failing to do the same for a datasource.

My doubt is it is trying to load a EmbeddedWebApplicationContext which is not what I want.

The stack trace is:

```<code>Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource() throws javax.naming.NamingException] threw exception; nested exception is **javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".**
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:301)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
        at **org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)**
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
        at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:142)
        at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:89)
        at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:51)
        at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)

..................

Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource() throws javax.naming.NamingException] threw exception; nested exception is **javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".**
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
        ... 132 common frames omitted
Caused by: javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".
        at com.ibm.ws.naming.ipbase.NameSpace.getParentCtxInternal(NameSpace.java:1970)
        at com.ibm.ws.naming.ipbase.NameSpace.retrieveBinding(NameSpace.java:1377)
        at com.ibm.ws.naming.ipbase.NameSpace.lookupInternal(NameSpace.java:1220)
        at com.ibm.ws.naming.ipbase.NameSpace.lookup(NameSpace.java:1142)
        at com.ibm.ws.naming.urlbase.UrlContextImpl.lookupExt(UrlContextImpl.java:1436)
        at com.ibm.ws.naming.java.javaURLContextImpl.lookupExt(javaURLContextImpl.java:477)
        at com.ibm.ws.naming.java.javaURLContextRoot.lookupExt(javaURLContextRoot.java:485)
        at com.ibm.ws.naming.java.javaURLContextRoot.lookup(javaURLContextRoot.java:370)
        at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)
        at javax.naming.InitialContext.lookup(InitialContext.java:436)
        at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource(JndiDataConfig.java:41)
        at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe.CGLIB$dataSource$0(<generated>)
        at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe$$FastClassBySpringCGLIB$$3c9e0518.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
        at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe.dataSource(<generated>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
        at java.lang.reflect.Method.invoke(Method.java:611)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
</code>```

What am I missing here? Even when I try to explicitly define the dataSource bean method in SampleApplication.java like below it fails with the same error.

```<code>@Bean
    public static DataSource dataSource() throws NamingException {
        JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
        jndiFactoryBean.setJndiName("java:comp/env/jdbc/fileUploadDS");
        jndiFactoryBean.setExpectedType(DataSource.class);
        jndiFactoryBean.setLookupOnStartup(true);
        jndiFactoryBean.setResourceRef(true);
        jndiFactoryBean.afterPropertiesSet();
        return (DataSource) jndiFactoryBean.getObject();
    }
</code>```

I referred this and it says we need to set enableNaming() on servlet container? Can I do something similar for non-embedded web application context? Or is it purely a WAS 8.5 issue??

答:
I am able to connect my Spring-Boot application (deployed in Websphere Application Server 9) to WAS datasource.
The following code worked for me, for connecting to DataSource:

```<code>@Bean(name = "WASDataSource")
public DataSource WASDataSource() throws Exception {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource("DSNAME");
}

@Bean(name = "WASDataSourceJdbcTemplate")
public JdbcTemplate jdbcTemplate_WASDS(@Qualifier("WASDataSource")
DataSource dsDB2) {
return new JdbcTemplate(dsDB2);
}
</code>```

Note: The name of Datasource "DSNAME" is the name which appears on the UI of Websphere console.
You can see that via -> Select Resources > JDBC > Data Sources.

Then I created jdbc template:

```<code>@Autowired
@Qualifier("WASDataSourceJdbcTemplate")
private JdbcTemplate db2WASTemplate;`
</code>```

And running query using the query method works fine :

    db2WASTemplate.query()

I did not create any Web.xml or ibm-web-bnd.xml files

Body:
I have setup a spring boot (v 1.1.9) application to deploy as a WAR file. And I'm trying to integrate this web application with an existing data service module (added as a maven dependency).

Environment trying to deploy: WebSphere Application Server 8.5.5.4

The issue I'm facing is an application start-up failure when try to look-up a JNDI dataSource (jdbc/fileUploadDS) as below within the dependent data service module.

@Configuration
@Profile("prod")
public class JndiDataConfig implements DataConfig {

    @Bean
    public DataSource dataSource() throws NamingException {
          Context ctx = new InitialContext();
          return (DataSource) ctx.lookup("java:comp/env/jdbc/fileUploadDS");
    }

}

My Spring Boot configuration:

@Configuration
@ComponentScan(basePackages = { "au.com.aiaa.fileupload.data.*", "demo" })
@EnableAutoConfiguration(exclude = { HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class })
public class SampleApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(applicationClass, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(applicationClass);
    }

    private static Class<SampleApplication> applicationClass = SampleApplication.class;

    @Bean
    public static Properties fileUploadJndiProperties() throws NamingException {
        JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
        jndiFactoryBean.setJndiName("props/FileUploadProperties");
        jndiFactoryBean.setExpectedType(Properties.class);
        jndiFactoryBean.setLookupOnStartup(true);
        jndiFactoryBean.afterPropertiesSet();
        return (Properties) jndiFactoryBean.getObject();
    }

}

Note that I'm able to lookup props/FileUploadProperties successfully. But failing to do the same for a datasource.

My doubt is it is trying to load a EmbeddedWebApplicationContext which is not what I want.

The stack trace is:

Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource() throws javax.naming.NamingException] threw exception; nested exception is **javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".**
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:301)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
        at **org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)**
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
        at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:142)
        at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:89)
        at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:51)
        at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)

..................

Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource() throws javax.naming.NamingException] threw exception; nested exception is **javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".**
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
        ... 132 common frames omitted
Caused by: javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".
        at com.ibm.ws.naming.ipbase.NameSpace.getParentCtxInternal(NameSpace.java:1970)
        at com.ibm.ws.naming.ipbase.NameSpace.retrieveBinding(NameSpace.java:1377)
        at com.ibm.ws.naming.ipbase.NameSpace.lookupInternal(NameSpace.java:1220)
        at com.ibm.ws.naming.ipbase.NameSpace.lookup(NameSpace.java:1142)
        at com.ibm.ws.naming.urlbase.UrlContextImpl.lookupExt(UrlContextImpl.java:1436)
        at com.ibm.ws.naming.java.javaURLContextImpl.lookupExt(javaURLContextImpl.java:477)
        at com.ibm.ws.naming.java.javaURLContextRoot.lookupExt(javaURLContextRoot.java:485)
        at com.ibm.ws.naming.java.javaURLContextRoot.lookup(javaURLContextRoot.java:370)
        at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)
        at javax.naming.InitialContext.lookup(InitialContext.java:436)
        at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource(JndiDataConfig.java:41)
        at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe.CGLIB$dataSource$0(<generated>)
        at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe$$FastClassBySpringCGLIB$$3c9e0518.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
        at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe.dataSource(<generated>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
        at java.lang.reflect.Method.invoke(Method.java:611)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)

What am I missing here? Even when I try to explicitly define the dataSource bean method in SampleApplication.java like below it fails with the same error.

@Bean
    public static DataSource dataSource() throws NamingException {
        JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
        jndiFactoryBean.setJndiName("java:comp/env/jdbc/fileUploadDS");
        jndiFactoryBean.setExpectedType(DataSource.class);
        jndiFactoryBean.setLookupOnStartup(true);
        jndiFactoryBean.setResourceRef(true);
        jndiFactoryBean.afterPropertiesSet();
        return (DataSource) jndiFactoryBean.getObject();
    }

I referred this and it says we need to set enableNaming() on servlet container? Can I do something similar for non-embedded web application context? Or is it purely a WAS 8.5 issue??

Body:
I am able to connect my Spring-Boot application (deployed in Websphere Application Server 9) to WAS datasource.
The following code worked for me, for connecting to DataSource:

@Bean(name = "WASDataSource")
public DataSource WASDataSource() throws Exception {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource("DSNAME");
}

@Bean(name = "WASDataSourceJdbcTemplate")
public JdbcTemplate jdbcTemplate_WASDS(@Qualifier("WASDataSource")
DataSource dsDB2) {
return new JdbcTemplate(dsDB2);
}

Note: The name of Datasource "DSNAME" is the name which appears on the UI of Websphere console.
You can see that via -> Select Resources > JDBC > Data Sources.

Then I created jdbc template:

@Autowired
@Qualifier("WASDataSourceJdbcTemplate")
private JdbcTemplate db2WASTemplate;`

And running query using the query method works fine :

    db2WASTemplate.query()

I did not create any Web.xml or ibm-web-bnd.xml files


问:
java.lang.NoClassDefFoundError on maven spring webapp
I'm building a webapp using maven and Spring. I have a DTO in my service module and I want to use it in my web module, so, I've put the dependency with the service like this:

```<code><dependency>
    <groupId>my.web</groupId>
    <artifactId>my.service</artifactId>
    <version>1.0.0</version>
</dependency>
</code>```

In my Controller I use it:

```<code>UserDTO u1 = new UserDTO(1,"User 1", "New User");
</code>```

However, I'm getting a:

```<code>java.lang.NoClassDefFoundError: my/service/dto/UserDTO
my.web.controllers.Controller.home(Controller.java:38)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</code>```

Don't know how to solve it. Maybe something is wrong with maven?

答:
If you use springboot with multiple modules add repackage</p>

```<code>         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <classifier>exec</classifier>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

Body:
I'm building a webapp using maven and Spring. I have a DTO in my service module and I want to use it in my web module, so, I've put the dependency with the service like this:

<dependency>
    <groupId>my.web</groupId>
    <artifactId>my.service</artifactId>
    <version>1.0.0</version>
</dependency>

In my Controller I use it:

UserDTO u1 = new UserDTO(1,"User 1", "New User");

However, I'm getting a:

java.lang.NoClassDefFoundError: my/service/dto/UserDTO
my.web.controllers.Controller.home(Controller.java:38)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Don't know how to solve it. Maybe something is wrong with maven?

Body:
If you use springboot with multiple modules add repackage

         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <classifier>exec</classifier>
                    </configuration>
                </execution>
            </executions>
        </plugin>


问:
How to apply transform translate property to element using ngStyle in Angular2+
I'm trying to conditionally apply a transform: translateX($value) directly to the template element using [ngStyle] but I cannot find anyone talking about this. Mainly because I don't know what to search for :D.

I've seen some approaches doing basic styling with [style.color] or something a bit more advanced with [attr.style]="{'transform': 'translateX(4rem)'}" but the last one returns in the rendered HTML this: style="unsafe". I've seen that you can use the Sanitizer to sanitize or bypass your styles/scripts etc... but at this point it was starting to 'smell' like something that you're not supposed to do? I'm looking for a clean way to achieve this. But I have no clue on where to look.

Thanks in advance to everyone!

答:
You can use [ngStyle] as follows, assuming you have a $value variable in your controller:

```<code>[ngStyle]="{'transform': 'translateX(' + $value + 'px)'}"
</code>```

and suppose you want to change both the axis having controller variables $x , $y

```<code>[ngStyle]="{'transform': 'translate(' + $x + 'px, ' + $y + 'px)'}"
</code>```

Body:
You can use [ngStyle] as follows, assuming you have a $value variable in your controller:

[ngStyle]="{'transform': 'translateX(' + $value + 'px)'}"

and suppose you want to change both the axis having controller variables $x , $y

[ngStyle]="{'transform': 'translate(' + $x + 'px, ' + $y + 'px)'}"


问:
Sort Json based on multiple values
In Java, I want to sort my JSON objects (not a JSON array) based on multiple values. Below is an example of input JSON file content.

```<code>{"Name":"John","Age":27,"Gender":"Male"}
{"Name":"Lynda","Age":42,"Gender":"Female"}
{"Name":"Peter","Age":34,"Gender":"Male"}
{"Name":"Sheebha","Age":23,"Gender":"Female"}
</code>```

I need to sort these objects by Age and Gender. I need an output like below.

```<code>{"Name":"John","Age":27,"Gender":"Male"}
{"Name":"Peter","Age":34,"Gender":"Male"}
{"Name":"Sheebha","Age":23,"Gender":"Female"}
{"Name":"Lynda","Age":42,"Gender":"Female"}
</code>```

I am using GSON to parse the JSON. I just want an approach to do it.  I am able to find solutions to sort a JSON array, but couldn't find one for objects.

Also, let me know the best API to parse JSON; GSON or JSON.simple or anything else.

答:
You should essentially have a comparator method like this, in your POJO object.

```<code>public int compareTo(Object obj) {
    if(obj == null)
            return 1;
    else if (obj instanceof Person)
    {
        Person p2 = (Person) obj;
        if(this.gender.compareTo(p2.gender) < 0)
            return 1;
        else if(this.gender.compareTo(p2.gender) == 0)
            return this.age.compareTo(p2.age);
        else
            return -1;
    }
    else return 1;

}
</code>```

It will sort first on the basis of Gender and then age, this is what I understand from your sample output.

From your JSON object convert to POJO object like this.

```<code>List<Person> personList = new ArrayList<>();
Person p =new GSON().fromJson(String , yourPOJO.class); // do this for all inputs
personList.add(p);
</code>```

then you need to sort using

```<code>Collections.sort(personList);
</code>```

hope this helps!

Good luck!

Title: Sort Json based on multiple values

Body:
In Java, I want to sort my JSON objects (not a JSON array) based on multiple values. Below is an example of input JSON file content.

{"Name":"John","Age":27,"Gender":"Male"}
{"Name":"Lynda","Age":42,"Gender":"Female"}
{"Name":"Peter","Age":34,"Gender":"Male"}
{"Name":"Sheebha","Age":23,"Gender":"Female"}

I need to sort these objects by Age and Gender. I need an output like below.

{"Name":"John","Age":27,"Gender":"Male"}
{"Name":"Peter","Age":34,"Gender":"Male"}
{"Name":"Sheebha","Age":23,"Gender":"Female"}
{"Name":"Lynda","Age":42,"Gender":"Female"}

I am using GSON to parse the JSON. I just want an approach to do it.  I am able to find solutions to sort a JSON array, but couldn't find one for objects.

Also, let me know the best API to parse JSON; GSON or JSON.simple or anything else.

Body:
You should essentially have a comparator method like this, in your POJO object.

public int compareTo(Object obj) {
    if(obj == null)
            return 1;
    else if (obj instanceof Person)
    {
        Person p2 = (Person) obj;
        if(this.gender.compareTo(p2.gender) < 0)
            return 1;
        else if(this.gender.compareTo(p2.gender) == 0)
            return this.age.compareTo(p2.age);
        else
            return -1;
    }
    else return 1;

}

It will sort first on the basis of Gender and then age, this is what I understand from your sample output.

From your JSON object convert to POJO object like this.

List<Person> personList = new ArrayList<>();
Person p =new GSON().fromJson(String , yourPOJO.class); // do this for all inputs
personList.add(p);

then you need to sort using

Collections.sort(personList);

hope this helps!

Good luck!


问:
How to handle back button on Ionic 2
How can I handle the back button action on Ionic 2?

I want to be able to know what to do depending on which page is being shown to the user.

I didn't find a good answer to this question, but after a while I figured it out myself a way to do it. I'm gonna share with you all.

Thanks

答:
Ionic Latest version 3.xx app.component.ts file  import { Platform, Nav, Config, ToastController} from 'ionic-angular';

```<code>constructor(public toastCtrl: ToastController,public platform: Platform) {
platform.ready().then(() => {
      //back button handle
      //Registration of push in Android and Windows Phone
      var lastTimeBackPress=0;
      var timePeriodToExit=2000;

  platform.registerBackButtonAction(() => {
     // get current active page
      let view = this.nav.getActive();
    if(view.component.name=="TabsPage"){
                    //Double check to exit app
                    if(new Date().getTime() - lastTimeBackPress < timePeriodToExit){
                         this.platform.exitApp(); //Exit from app
                    }else{
                         let toast = this.toastCtrl.create({
                            message: 'Press back again to exit App?',
                            duration: 3000,
                            position: 'bottom'
                          });
                            toast.present();
                            lastTimeBackPress=new Date().getTime();
                    }
    }else{
         // go to previous page
              this.nav.pop({});
    }
  });

});

}
</code>```

Title: How to handle back button on Ionic 2

Body:
Ionic Latest version 3.xx app.component.ts file  import { Platform, Nav, Config, ToastController} from 'ionic-angular';

constructor(public toastCtrl: ToastController,public platform: Platform) {
platform.ready().then(() => {
      //back button handle
      //Registration of push in Android and Windows Phone
      var lastTimeBackPress=0;
      var timePeriodToExit=2000;

  platform.registerBackButtonAction(() => {
     // get current active page
      let view = this.nav.getActive();
    if(view.component.name=="TabsPage"){
                    //Double check to exit app
                    if(new Date().getTime() - lastTimeBackPress < timePeriodToExit){
                         this.platform.exitApp(); //Exit from app
                    }else{
                         let toast = this.toastCtrl.create({
                            message: 'Press back again to exit App?',
                            duration: 3000,
                            position: 'bottom'
                          });
                            toast.present();
                            lastTimeBackPress=new Date().getTime();
                    }
    }else{
         // go to previous page
              this.nav.pop({});
    }
  });

});

}


问:
ui-router how to set default state and "not found (404)" state
I am migrating to ui-router in Angular 1.5 and I need to setup the state provider so when I enter the base URL for my app it goes to my home state, but if user enters some non-existing path, it shows a custom "404" template.

If I set the default state with urlProvider.otherwise(), I can no longer set the 404 template, and if I set up a state with url: "" and set up urlProvider.otherwise() for showing 404 template, then the base url will show the 404 template always.

How can I correctly configure this?

答:
Simply create a 404 state. Check this out. If you have a different url for a home state than your base url, you can use

```<code>urlProvider.when('base-url', 'home-state-url');
</code>```

Then you can remove the urlProvider.otherwise()

Body:
Simply create a 404 state. Check this out. If you have a different url for a home state than your base url, you can use

urlProvider.when('base-url', 'home-state-url');

Then you can remove the urlProvider.otherwise()


问:
LoadApplication(new App()) throws error on IOS! Working fine on Android Xamarin forms
My application is working as desired on Android but when I try to run it on ios (Emulator/device) it throws Null reference exception.

Here is the code in App.xaml.cs

```<code>public App()
        {
            InitializeComponent();

            if (true)
            {
                if (CrossConnectivity.Current.IsConnected)
                {
                    do something
                }
                MainPage = new MyApp.MenuItems();
            }
            else
            {
                MainPage = new MyApp.MainPage();
            }

        }
</code>```

Please help as app is fully ready for android and something going wrong with ios.

答: are you sure that you have installed connectivity plugin into ios project too? </p>

Body:
My application is working as desired on Android but when I try to run it on ios (Emulator/device) it throws Null reference exception.

Here is the code in App.xaml.cs

public App()
        {
            InitializeComponent();

            if (true)
            {
                if (CrossConnectivity.Current.IsConnected)
                {
                    do something
                }
                MainPage = new MyApp.MenuItems();
            }
            else
            {
                MainPage = new MyApp.MainPage();
            }

        }

Please help as app is fully ready for android and something going wrong with ios.


问:
How can I remove "/url?q=" from text data in R
I want to remove "/url?q=" from text data in R Studio.
This is my code for google search:

```<code>## Code for Google Search
# Enter Search Term Here
 search.term <- "r-project"
# Creating Function
 getGoogleURL <- function(search.term, domain = '.co.in', quotes=TRUE)
{
   # Getting Search Term
    search.term <- gsub(' ', '%20', search.term)
    if(quotes) search.term <- paste('%22', search.term, '%22', sep='')
   # Putting Search Term in Google Search
    getGoogleURL <- paste('http://www.google', domain, '/search?q=', search.term, sep='') }

## Get Links from Google Search
# Creating Function to Get URLs From Search Results
 getGoogleLinks <- function(google.url) {
  # Creating a File to Save URLs
   doc <- getURL(google.url, httpheader = c("User-Agent" = "R(3.4.0)"))
  # Removing HTML code and Setting Nodes
   html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function(...){})
   nodes <- getNodeSet(html, "//h3[@class='r']//a")
   return(sapply(nodes, function(x) x <- xmlAttrs(x)[["href"]])) }

## Remove quoted text, Create URL List
  quotes <- "FALSE"
  search.url <- getGoogleURL(search.term=search.term, quotes=quotes)
  links <- getGoogleLinks(search.url)

## Print URL List
  links
</code>```

And my result is:

[1] "/url?q=https://www.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQFggUMAA&usg=AFQjCNEqtiOAIA7OOTa3meWC8zaTjjTy8A"

  [2] "/url?q=http://www.cran.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQjBAIGzAB&usg=AFQjCNF8QmYbLzG0c66QZM2wsXF1n1-9tQ"

What can I do to remove "/url?q=" from the links above?

答:
Alternatively to @JTeam's answer you can try this (given the links always start with /url?q=):

lapply(links,function(x) paste0(strsplit(x,'=')[[1]][-1],collapse = ''))

This gives you a nice list of clean links (if you prefer a vector, try sapply)

Body:
I want to remove "/url?q=" from text data in R Studio.
This is my code for google search:

## Code for Google Search
# Enter Search Term Here
 search.term <- "r-project"
# Creating Function
 getGoogleURL <- function(search.term, domain = '.co.in', quotes=TRUE)
{
   # Getting Search Term
    search.term <- gsub(' ', '%20', search.term)
    if(quotes) search.term <- paste('%22', search.term, '%22', sep='')
   # Putting Search Term in Google Search
    getGoogleURL <- paste('http://www.google', domain, '/search?q=', search.term, sep='') }

## Get Links from Google Search
# Creating Function to Get URLs From Search Results
 getGoogleLinks <- function(google.url) {
  # Creating a File to Save URLs
   doc <- getURL(google.url, httpheader = c("User-Agent" = "R(3.4.0)"))
  # Removing HTML code and Setting Nodes
   html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function(...){})
   nodes <- getNodeSet(html, "//h3[@class='r']//a")
   return(sapply(nodes, function(x) x <- xmlAttrs(x)[["href"]])) }

## Remove quoted text, Create URL List
  quotes <- "FALSE"
  search.url <- getGoogleURL(search.term=search.term, quotes=quotes)
  links <- getGoogleLinks(search.url)

## Print URL List
  links

And my result is:

[1] "/url?q=https://www.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQFggUMAA&usg=AFQjCNEqtiOAIA7OOTa3meWC8zaTjjTy8A"

  [2] "/url?q=http://www.cran.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQjBAIGzAB&usg=AFQjCNF8QmYbLzG0c66QZM2wsXF1n1-9tQ"

What can I do to remove "/url?q=" from the links above?


问:
R columns replace alphabet by other columns in a data frame
I have a data frame with three reference columns ref, het and hom in every row and I want to replace the alphabet/genotype in the columns which G=C, A=T, AG=TC or vice versa based on the reference columns.

```<code>structure(list(SNP = c("rs1", "rs2", "rs3", "rs4", "rs5", "rs6",
"rs7", "rs8", "rs9"), ref = c("GG", "AA", "AA", "GG", "GG", "GG",
"AA", "CC", "GG"), het = c("AG", "AG", "AG", "AG", "AG", "AG",
"AG", "AC", "AG"), hom = c("AA", "GG", "GG", "AA", "AA", "AA",
"GG", "AA", "AA"), A = c("TC", "TC", "CC", "AG", "TT", "TC",
"AA", "GG", "GG"), B = c("CC", "TT", "CC", "AG", "TT", "CC",
"AA", "TG", "GG"), C = c("CC", "CC", "CC", "GG", "CC", "TT",
"AA", "TG", "GG"), D = c("TT", "TC", "CC", "AG", "TT", "TT",
"AA", "GG", "AG"), E = c("CC", "TT", "CC", "AG", "TC", "TT",
"AA", "TG", "GG"), F = c("TC", "TT", "TC", "GG", "TC", "TC",
"AA", "GG", "GG"), G = c("TC", "TC", "CC", "AG", "TC", "TC",
"AA", "GG", "GG"), H = c("TC", "TC", "TC", "GG", "TC", "TC",
"AA", "TG", "GG")), .Names = c("SNP", "ref", "het", "hom", "A",
"B", "C", "D", "E", "F", "G", "H"), class = "data.frame", row.names =
c(NA,
-9L))

Input:
SNP ref het hom A   B   C   D   E   F   G   H   I
rs1 GG  AG  AA  TC  CC  CC  TT  CC  TC  TC  TC  …
rs2 AA  AG  GG  TC  TT  CC  TC  TT  TT  TC  TC  …
rs3 AA  AG  GG  CC  CC  CC  CC  CC  TC  CC  TC  …
rs4 GG  AG  AA  AG  AG  GG  AG  AG  GG  AG  GG  …
rs5 GG  AG  AA  TT  TT  CC  TT  TC  TC  TC  TC  …
rs6 GG  AG  AA  TC  CC  TT  TT  TT  TC  TC  TC  …
rs7 AA  AG  GG  AA  AA  AA  AA  AA  AA  AA  AA  …
rs8 CC  AC  AA  GG  TG  TG  GG  TG  GG  GG  TG  …
rs9 GG  AG  AA  GG  GG  GG  AG  GG  GG  GG  GG  …

Desired Output:
SNP ref het hom A   B   C   D   E   F   G   H   I
rs1 GG  AG  AA  AG  GG  GG  AA  GG  AG  AG  AG  …
rs2 AA  AG  GG  AG  AA  GG  AG  AA  AA  AG  AG  …
rs3 AA  AG  GG  GG  GG  GG  GG  GG  AG  GG  AG  …
rs4 GG  AG  AA  AG  AG  GG  AG  AG  GG  AG  GG  …
rs5 GG  AG  AA  AA  AA  GG  AA  AG  AG  AG  AG  …
rs6 GG  AG  AA  AG  GG  AA  AA  AA  AG  AG  AG  …
rs7 AA  AG  GG  AA  AA  AA  AA  AA  AA  AA  AA  …
rs8 CC  AC  AA  AA  AC  AC  CC  AC  CC  CC  AC  …
rs9 GG  AG  AA  GG  GG  GG  AG  GG  GG  GG  GG  …
</code>```

how can I write a function to replace these alphabet based on the reference columns? Thank you.

答:
We can create a "dictionary" with all the possible genotypes and their correspondence, than go through the list of SNPs, check the first element (column A). If it is not in ref/het/hom, than we suppose that the elements in that row need to be changed, otherwise we just return the row as it is.</p>

```<code>key = list(AA="TT",TT="AA",
           GG="CC",CC="GG",
           AG="TC",TC="AG",
           GA="CT",CT="GA",
           AC="TG",TG="AC",
           CA="GT",GT="CA")

changeAlleles <- function(myrow) {
  if (!(myrow[5] %in% myrow[2:4])) {
    myrow <- c(myrow[1:4],sapply(myrow[5:length(myrow)], function(x) key[[x]]))
  }
  return(myrow)
}

df2=as.data.frame(t(apply(df,1,changeAlleles)))

   SNP ref het hom  A  B  C  D  E  F  G  H
2  rs1  GG  AG  AA AG GG GG AA GG AG AG AG
3  rs2  AA  AG  GG AG AA GG AG AA AA AG AG
4  rs3  AA  AG  GG GG GG GG GG GG AG GG AG
5  rs4  GG  AG  AA AG AG GG AG AG GG AG GG
6  rs5  GG  AG  AA AA AA GG AA AG AG AG AG
7  rs6  GG  AG  AA AG GG AA AA AA AG AG AG
8  rs7  AA  AG  GG AA AA AA AA AA AA AA AA
9  rs8  CC  AC  AA CC AC AC CC AC CC CC AC
10 rs9  GG  AG  AA GG GG GG AG GG GG GG GG
</code>```

Body:
I have a data frame with three reference columns ref, het and hom in every row and I want to replace the alphabet/genotype in the columns which G=C, A=T, AG=TC or vice versa based on the reference columns.

structure(list(SNP = c("rs1", "rs2", "rs3", "rs4", "rs5", "rs6",
"rs7", "rs8", "rs9"), ref = c("GG", "AA", "AA", "GG", "GG", "GG",
"AA", "CC", "GG"), het = c("AG", "AG", "AG", "AG", "AG", "AG",
"AG", "AC", "AG"), hom = c("AA", "GG", "GG", "AA", "AA", "AA",
"GG", "AA", "AA"), A = c("TC", "TC", "CC", "AG", "TT", "TC",
"AA", "GG", "GG"), B = c("CC", "TT", "CC", "AG", "TT", "CC",
"AA", "TG", "GG"), C = c("CC", "CC", "CC", "GG", "CC", "TT",
"AA", "TG", "GG"), D = c("TT", "TC", "CC", "AG", "TT", "TT",
"AA", "GG", "AG"), E = c("CC", "TT", "CC", "AG", "TC", "TT",
"AA", "TG", "GG"), F = c("TC", "TT", "TC", "GG", "TC", "TC",
"AA", "GG", "GG"), G = c("TC", "TC", "CC", "AG", "TC", "TC",
"AA", "GG", "GG"), H = c("TC", "TC", "TC", "GG", "TC", "TC",
"AA", "TG", "GG")), .Names = c("SNP", "ref", "het", "hom", "A",
"B", "C", "D", "E", "F", "G", "H"), class = "data.frame", row.names =
c(NA,
-9L))

Input:
SNP ref het hom A   B   C   D   E   F   G   H   I
rs1 GG  AG  AA  TC  CC  CC  TT  CC  TC  TC  TC  …
rs2 AA  AG  GG  TC  TT  CC  TC  TT  TT  TC  TC  …
rs3 AA  AG  GG  CC  CC  CC  CC  CC  TC  CC  TC  …
rs4 GG  AG  AA  AG  AG  GG  AG  AG  GG  AG  GG  …
rs5 GG  AG  AA  TT  TT  CC  TT  TC  TC  TC  TC  …
rs6 GG  AG  AA  TC  CC  TT  TT  TT  TC  TC  TC  …
rs7 AA  AG  GG  AA  AA  AA  AA  AA  AA  AA  AA  …
rs8 CC  AC  AA  GG  TG  TG  GG  TG  GG  GG  TG  …
rs9 GG  AG  AA  GG  GG  GG  AG  GG  GG  GG  GG  …

Desired Output:
SNP ref het hom A   B   C   D   E   F   G   H   I
rs1 GG  AG  AA  AG  GG  GG  AA  GG  AG  AG  AG  …
rs2 AA  AG  GG  AG  AA  GG  AG  AA  AA  AG  AG  …
rs3 AA  AG  GG  GG  GG  GG  GG  GG  AG  GG  AG  …
rs4 GG  AG  AA  AG  AG  GG  AG  AG  GG  AG  GG  …
rs5 GG  AG  AA  AA  AA  GG  AA  AG  AG  AG  AG  …
rs6 GG  AG  AA  AG  GG  AA  AA  AA  AG  AG  AG  …
rs7 AA  AG  GG  AA  AA  AA  AA  AA  AA  AA  AA  …
rs8 CC  AC  AA  AA  AC  AC  CC  AC  CC  CC  AC  …
rs9 GG  AG  AA  GG  GG  GG  AG  GG  GG  GG  GG  …

how can I write a function to replace these alphabet based on the reference columns? Thank you.

Body:
We can create a "dictionary" with all the possible genotypes and their correspondence, than go through the list of SNPs, check the first element (column A). If it is not in ref/het/hom, than we suppose that the elements in that row need to be changed, otherwise we just return the row as it is.

key = list(AA="TT",TT="AA",
           GG="CC",CC="GG",
           AG="TC",TC="AG",
           GA="CT",CT="GA",
           AC="TG",TG="AC",
           CA="GT",GT="CA")

changeAlleles <- function(myrow) {
  if (!(myrow[5] %in% myrow[2:4])) {
    myrow <- c(myrow[1:4],sapply(myrow[5:length(myrow)], function(x) key[[x]]))
  }
  return(myrow)
}

df2=as.data.frame(t(apply(df,1,changeAlleles)))

   SNP ref het hom  A  B  C  D  E  F  G  H
2  rs1  GG  AG  AA AG GG GG AA GG AG AG AG
3  rs2  AA  AG  GG AG AA GG AG AA AA AG AG
4  rs3  AA  AG  GG GG GG GG GG GG AG GG AG
5  rs4  GG  AG  AA AG AG GG AG AG GG AG GG
6  rs5  GG  AG  AA AA AA GG AA AG AG AG AG
7  rs6  GG  AG  AA AG GG AA AA AA AG AG AG
8  rs7  AA  AG  GG AA AA AA AA AA AA AA AA
9  rs8  CC  AC  AA CC AC AC CC AC CC CC AC
10 rs9  GG  AG  AA GG GG GG AG GG GG GG GG


问:
Progress bar loading is not stopped when the activity is called second time
I have created a welcome page(launcher) and included a progress bar.next activity will be displayed after this progress bar loading(for few seconds).For the first time,when the app is run,after few seconds the next activity is displayed.Now,when i press back button,welcome activity is being displayed.But this time,after few seconds,it is now calling the next activity(using Intent) like the first time.How to resolve this?
The code is:</p>

```<code>import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;

public class WelcomeActivity extends AppCompatActivity {
    ProgressBar p;
    private boolean mbActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        p = (ProgressBar) findViewById(R.id.progressBar);
        final Thread timerThread = new Thread() {
            @Override
            public void run() {
                mbActive = true;
                try {
                    int waited = 0;
                    while(mbActive && (waited < 1000)) {
                        sleep(200);
                        if(mbActive) {
                            waited += 200;
                            updateProgress(waited);
                        }
                    }
                } catch(InterruptedException e) {
                } finally {
                    onContinue();
                }
            }
        };
        timerThread.start();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    public void updateProgress(final int timePassed) {
        if(null != p) {
            final int progress = p.getMax() * timePassed / 100;
            p.setProgress(progress);
        }
    }

    public void onContinue() {
        Intent intd=new Intent(this,MainActivity.class);
        startActivity(intd);
    }

}
</code>```

答:
dismiss the Progress dialog</p>

```<code>public void onContinue()
{
p.dismiss();
Intent intd=new Intent(this,MainActivity.class);
startActivity(intd);
}
</code>```

Body:
I have created a welcome page(launcher) and included a progress bar.next activity will be displayed after this progress bar loading(for few seconds).For the first time,when the app is run,after few seconds the next activity is displayed.Now,when i press back button,welcome activity is being displayed.But this time,after few seconds,it is now calling the next activity(using Intent) like the first time.How to resolve this?
The code is:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;

public class WelcomeActivity extends AppCompatActivity {
    ProgressBar p;
    private boolean mbActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        p = (ProgressBar) findViewById(R.id.progressBar);
        final Thread timerThread = new Thread() {
            @Override
            public void run() {
                mbActive = true;
                try {
                    int waited = 0;
                    while(mbActive && (waited < 1000)) {
                        sleep(200);
                        if(mbActive) {
                            waited += 200;
                            updateProgress(waited);
                        }
                    }
                } catch(InterruptedException e) {
                } finally {
                    onContinue();
                }
            }
        };
        timerThread.start();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    public void updateProgress(final int timePassed) {
        if(null != p) {
            final int progress = p.getMax() * timePassed / 100;
            p.setProgress(progress);
        }
    }

    public void onContinue() {
        Intent intd=new Intent(this,MainActivity.class);
        startActivity(intd);
    }

}

Body:
dismiss the Progress dialog

public void onContinue()
{
p.dismiss();
Intent intd=new Intent(this,MainActivity.class);
startActivity(intd);
}


问:
What is the maximum size of SYSJOBID?
I'm capturing the automatic sysjobid macro variable in a table, and so it would help to know the range of possible types (Character/Numeric) and values (which are operating system dependent).

EDIT:  whilst theoretically any value could be passed, what is most useful is to know what is the maximum in 99% of cases.

What is the largest value that any of you have witnessed in your deployments?

答:
Let's see:

Linux:  32768 for 32-bit systems, or 4194304 for 64-bit systems (source)

Windows: up to DWORD_MAX (source), which I think in this context is 4294967295 (source)

Can anyone fill in the blanks for some of the other operating systems supported by SAS? There are many...

Title: What is the maximum size of SYSJOBID?


问:
how to get a average of days with two different tables
There are two tables 1)HR_OrderRequest (column to be considered is HRdate) other columns are HRUID,UID
                     2)HR_Supplydetails(colmn to be considered is HRUID) other columns are createddttm,UID
by considering the date from HR_Supplydetails we should find the average days taken for that particular UID time taken to release of HRdate .I have a problem getting a average of days

Please do the need .

答:
so the steps would be first getting the number of days for a order so you have like these tables:

```<code>order (id, date) # this date is the date the order was placed
supply (id, date) # this date is the date the order was filled
</code>```

these might not be right but i think they are close

```<code>select avg(days)
from (select (supply.date-order.date) as days
     from order join supply on order.id=supply.id)
</code>```

but the sub query isn't needed as it can be written as:

```<code>select avg(supply.date-order.date)
from order join supply on order.id=supply.id;
</code>```

now to map this to your tables:

```<code>HR_OrderRequest (HRUID, UID, HRdate)
HR_Supplydetails (HRUID, UID, createddttm)

select avg(HR_OrderRequest.HRdate-HR_Supplydetails.createddttm)
from HR_OrderRequest join HR_Supplydetails on HR_OrderRequest.HRUID=HR_Supplydetails.HRUID
where UID=?
</code>```

clearly if you have date functions use them

Body:
so the steps would be first getting the number of days for a order so you have like these tables:

order (id, date) # this date is the date the order was placed
supply (id, date) # this date is the date the order was filled

these might not be right but i think they are close

select avg(days)
from (select (supply.date-order.date) as days
     from order join supply on order.id=supply.id)

but the sub query isn't needed as it can be written as:

select avg(supply.date-order.date)
from order join supply on order.id=supply.id;

now to map this to your tables:

HR_OrderRequest (HRUID, UID, HRdate)
HR_Supplydetails (HRUID, UID, createddttm)

select avg(HR_OrderRequest.HRdate-HR_Supplydetails.createddttm)
from HR_OrderRequest join HR_Supplydetails on HR_OrderRequest.HRUID=HR_Supplydetails.HRUID
where UID=?

clearly if you have date functions use them


问:
VBA skipping over a filter criteria
Hi I have the below code where I wish to use VBA to filter lists in Excel, Each list will be different depending on which company I select.

```<code>With wsDest.Rows(1)
.AutoFilter field:=3, Criteria1:="Swap", Operator:=xlOr, Criteria2:="FwdSwap", Operator:=xlOr, Criteria3:="NDS"
  If wsDest.Range("C1:C" & lr).SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
  wsDest.Range("G2:G" & lr).SpecialCells(xlCellTypeVisible).Copy wsDest.Range("J" & Rows.Count).End(3)(2)
     End If
.AutoFilter
End With
</code>```

wsDest is the worksheet I am working in,  the code works fine except that lots of the lists i am filtering do not contain the "NDS" and the code breaks when this happens. Is there a way I can add into this 'if NDS exists in the list then use filter, else skip NDS as a filter'

Many thanks in advance

答:
```<code>.AutoFilter field:=3, Criteria1:="Swap", Operator:=xlOr, Criteria2:="FwdSwap", Operator:=xlOr, Criteria3:="NDS"
</code>```

Your syntax here is incorrect for filtering on multiple criteria. Although there is a Criteria2, there is no Criteria3 and so on for this method.

Where you want to filter for multiple values, you should instead use an array with Criteria1:

```<code>.AutoFilter Field:=3, Criteria1:=Array("Swap", "FwdSwap", "NDS"), Operator:=xlFilterValues
</code>```

Also note the change in Operator to xlFilterValues as pointed out by @YowE3K

Title: VBA skipping over a filter criteria

Body:
Hi I have the below code where I wish to use VBA to filter lists in Excel, Each list will be different depending on which company I select.

With wsDest.Rows(1)
.AutoFilter field:=3, Criteria1:="Swap", Operator:=xlOr, Criteria2:="FwdSwap", Operator:=xlOr, Criteria3:="NDS"
  If wsDest.Range("C1:C" & lr).SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
  wsDest.Range("G2:G" & lr).SpecialCells(xlCellTypeVisible).Copy wsDest.Range("J" & Rows.Count).End(3)(2)
     End If
.AutoFilter
End With

wsDest is the worksheet I am working in,  the code works fine except that lots of the lists i am filtering do not contain the "NDS" and the code breaks when this happens. Is there a way I can add into this 'if NDS exists in the list then use filter, else skip NDS as a filter'

Many thanks in advance

Body:
.AutoFilter field:=3, Criteria1:="Swap", Operator:=xlOr, Criteria2:="FwdSwap", Operator:=xlOr, Criteria3:="NDS"

Your syntax here is incorrect for filtering on multiple criteria. Although there is a Criteria2, there is no Criteria3 and so on for this method.

Where you want to filter for multiple values, you should instead use an array with Criteria1:

.AutoFilter Field:=3, Criteria1:=Array("Swap", "FwdSwap", "NDS"), Operator:=xlFilterValues

Also note the change in Operator to xlFilterValues as pointed out by @YowE3K


答:
The TrimEnd function removes any of those chars from the end of the string. It doesn't match the full string.

Try this instead:

```<code>var s = "FDLBicester.freshviprint01";
var t = ".freshviprint01";

var x =
    s.Length > t.Length && s.Substring(s.Length - t.Length) == t
        ? s.Substring(0, s.Length - t.Length)
        : s;

Console.WriteLine(x);
</code>```

Or even this:

```<code>var x = s.Split(new [] { t }, StringSplitOptions.None)[0];
</code>```

Title: C# TrimEnd trimming too many chars

Body:
I'm seeing odd results when using string.TrimEnd() method

var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd("freshviprint01".ToCharArray());
Console.WriteLine(x);

Produces

FDLBicester.

However, slightly changing the TrimEnd to include the . as well:

var s = "FDLBicester.freshviprint01";
var x = s.TrimEnd(".freshviprint01".ToCharArray());
Console.WriteLine(x);

Produces

FDLBic

????

Why am I losing ester by also trimming the .?

Body:
The TrimEnd function removes any of those chars from the end of the string. It doesn't match the full string.

Try this instead:

var s = "FDLBicester.freshviprint01";
var t = ".freshviprint01";

var x =
    s.Length > t.Length && s.Substring(s.Length - t.Length) == t
        ? s.Substring(0, s.Length - t.Length)
        : s;

Console.WriteLine(x);

Or even this:

var x = s.Split(new [] { t }, StringSplitOptions.None)[0];


问:
How to get document root path in PHP with CLI?

```<code>echo __DIR__;
</code>```

"    How to get document root path in PHP from any subdirectory using command line?

```<code>my directory structure--

/dinesh
       /data
            /asset
</code>```

Suppose my root directry is /dinesh

and currently my script in asset but I require document root path till /dinesh only

by using command line php CLI

How will I get this?

I have tried DIR and FILE but that give path till  asset and one more thing that dinesh is my local root folder  name that is changeable when I move my code to other server"

答:
You can print the result that comes out of the global variable

```<code>echo $_SERVER["DOCUMENT_ROOT"];
</code>```

And print

```<code>echo @getcwd();
</code>```

Body:
echo __DIR__;

"    How to get document root path in PHP from any subdirectory using command line?

my directory structure--

/dinesh
       /data
            /asset

Suppose my root directry is /dinesh

and currently my script in asset but I require document root path till /dinesh only

by using command line php CLI

How will I get this?

I have tried DIR and FILE but that give path till  asset and one more thing that dinesh is my local root folder  name that is changeable when I move my code to other server"

Body:
You can print the result that comes out of the global variable

echo $_SERVER["DOCUMENT_ROOT"];

And print

echo @getcwd();


问:
Reset a CoreData persistent store
Basically, what I'm trying to do is to wipe out all data in my CoreData persistent store, then import new data. How would you do this? It seems that the simplest solution is call [NSPersistentStoreCoordinator removePersistentStore:error:] and then remove the file. Is that the best practice available? Is it thread-safe?

Thank you very much,

#

Question 0.1: was

I am trying to update the data in a CoreData persistent store. My user is seeing a table view with statistical data. I want to update the application by deleting all existing data, then importing new data. I would like to show a progress view to tell the user that the application is not hanging.

I have added the following resetPersistentStore method in my AppDelegate (persistentStoreCoordinatoris given for reference):

```<code>// ...
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
// ...

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: kPersistentStoreFilename]];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return persistentStoreCoordinator;
}

/**
 * Will remove the persistent store
 */
- (NSPersistentStoreCoordinator *)resetPersistentStore {
    NSError *error;

    [managedObjectContext lock];

    // FIXME: dirty. If there are many stores...
    NSPersistentStore *store = [[persistentStoreCoordinator persistentStores] objectAtIndex:0];

    if (![persistentStoreCoordinator removePersistentStore:store error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    // Delete file
    if (![[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    // Delete the reference to non-existing store
    [persistentStoreCoordinator release];
    persistentStoreCoordinator = nil;

    NSPersistentStoreCoordinator *r = [self persistentStoreCoordinator];
    [managedObjectContext unlock];

    return r;
}
</code>```

Then in my view I do (in another thread since I am using MBProgressHUD:

```<code>PatrimoineAppDelegate *appDelegate = (PatrimoineAppDelegate *)[[UIApplication sharedApplication] delegate];
// Delete everything
[appDelegate resetPersistentStore];
</code>```

And I get an EXC_BAD_ACESS...

I do not know CoreData or multithreading very well, maybe I'm doing an evident error...

答:
Still not work!  Abort caused by ManagedObjectContext link with invalid persistance store.  Finally it work if I delete the ManagedObjectContext and let the app re-create later

Here is my modification

```<code>- (NSPersistentStoreCoordinator *)resetPersistentStore
{
  NSError *error = nil;

  if ([persistentStoreCoordinator_ persistentStores] == nil)
    return [self persistentStoreCoordinator];

  [managedObjectContext_ release];
  managedObjectContext_ = nil;

  // FIXME: dirty. If there are many stores...
  NSPersistentStore *store = [[persistentStoreCoordinator_ persistentStores] lastObject];

  if (![persistentStoreCoordinator_ removePersistentStore:store error:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }

  // Delete file
  if ([[NSFileManager defaultManager] fileExistsAtPath:store.URL.path]) {
    if (![[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:&error]) {
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
    }
  }

  // Delete the reference to non-existing store
  [persistentStoreCoordinator_ release];
  persistentStoreCoordinator_ = nil;

  NSPersistentStoreCoordinator *r = [self persistentStoreCoordinator];

  return r;
}
</code>```

Title: Reset a CoreData persistent store

Body:
Basically, what I'm trying to do is to wipe out all data in my CoreData persistent store, then import new data. How would you do this? It seems that the simplest solution is call [NSPersistentStoreCoordinator removePersistentStore:error:] and then remove the file. Is that the best practice available? Is it thread-safe?

Thank you very much,

#

Question 0.1: was

I am trying to update the data in a CoreData persistent store. My user is seeing a table view with statistical data. I want to update the application by deleting all existing data, then importing new data. I would like to show a progress view to tell the user that the application is not hanging.

I have added the following resetPersistentStore method in my AppDelegate (persistentStoreCoordinatoris given for reference):

// ...
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
// ...

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: kPersistentStoreFilename]];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return persistentStoreCoordinator;
}

/**
 * Will remove the persistent store
 */
- (NSPersistentStoreCoordinator *)resetPersistentStore {
    NSError *error;

    [managedObjectContext lock];

    // FIXME: dirty. If there are many stores...
    NSPersistentStore *store = [[persistentStoreCoordinator persistentStores] objectAtIndex:0];

    if (![persistentStoreCoordinator removePersistentStore:store error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    // Delete file
    if (![[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    // Delete the reference to non-existing store
    [persistentStoreCoordinator release];
    persistentStoreCoordinator = nil;

    NSPersistentStoreCoordinator *r = [self persistentStoreCoordinator];
    [managedObjectContext unlock];

    return r;
}

Then in my view I do (in another thread since I am using MBProgressHUD:

PatrimoineAppDelegate *appDelegate = (PatrimoineAppDelegate *)[[UIApplication sharedApplication] delegate];
// Delete everything
[appDelegate resetPersistentStore];

And I get an EXC_BAD_ACESS...

I do not know CoreData or multithreading very well, maybe I'm doing an evident error...

Body:
Still not work!  Abort caused by ManagedObjectContext link with invalid persistance store.  Finally it work if I delete the ManagedObjectContext and let the app re-create later

Here is my modification

- (NSPersistentStoreCoordinator *)resetPersistentStore
{
  NSError *error = nil;

  if ([persistentStoreCoordinator_ persistentStores] == nil)
    return [self persistentStoreCoordinator];

  [managedObjectContext_ release];
  managedObjectContext_ = nil;

  // FIXME: dirty. If there are many stores...
  NSPersistentStore *store = [[persistentStoreCoordinator_ persistentStores] lastObject];

  if (![persistentStoreCoordinator_ removePersistentStore:store error:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
  }

  // Delete file
  if ([[NSFileManager defaultManager] fileExistsAtPath:store.URL.path]) {
    if (![[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:&error]) {
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
      abort();
    }
  }

  // Delete the reference to non-existing store
  [persistentStoreCoordinator_ release];
  persistentStoreCoordinator_ = nil;

  NSPersistentStoreCoordinator *r = [self persistentStoreCoordinator];

  return r;
}


问:
Visual Basic with Twain Application
Hello I have a small knowledge in vb so please help me. When I run my program that can access my scanner it has an error "AccessViolationExeption was unhandled" "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

Here is my code:

```<code>   Public Sub CloseSource()
        Try
            Dim rc As TwRC
            If Not Equals(SelectedDataSource.Id, IntPtr.Zero) Then
                Dim guif As TwUserInterface = New TwUserInterface()

                ' tell the data source to disable its user interface
                rc = DS_Userif(appid, SelectedDataSource, TwDG.TwDG_Control, TwDAT.TwDAT_UserInterface, TwMSG.TwMSG_DisableDS, guif)

                ' tell the device manager to release the source
                rc = DSM_Ident(appid, IntPtr.Zero, TwDG.TwDG_Control, TwDAT.TwDAT_Identity, TwMSG.TwMSG_CloseDS, SelectedDataSource)

                ' set the pointer to zero
                SelectedDataSource.Id = IntPtr.Zero
            End If
        Catch ex As Exception

        End Try

    End Sub
</code>```

答:
From your message and code I have understood that you have the exception when you closing the scanner. I think you have the exception because scanner is not ready for closing. Please make sure that scanner is in correct state and can be closed.

Best regards, Alexander

Title: Visual Basic with Twain Application

Body:
Hello I have a small knowledge in vb so please help me. When I run my program that can access my scanner it has an error "AccessViolationExeption was unhandled" "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

Here is my code:

   Public Sub CloseSource()
        Try
            Dim rc As TwRC
            If Not Equals(SelectedDataSource.Id, IntPtr.Zero) Then
                Dim guif As TwUserInterface = New TwUserInterface()

                ' tell the data source to disable its user interface
                rc = DS_Userif(appid, SelectedDataSource, TwDG.TwDG_Control, TwDAT.TwDAT_UserInterface, TwMSG.TwMSG_DisableDS, guif)

                ' tell the device manager to release the source
                rc = DSM_Ident(appid, IntPtr.Zero, TwDG.TwDG_Control, TwDAT.TwDAT_Identity, TwMSG.TwMSG_CloseDS, SelectedDataSource)

                ' set the pointer to zero
                SelectedDataSource.Id = IntPtr.Zero
            End If
        Catch ex As Exception

        End Try

    End Sub


问:
Accessing Spring Rest Service without Dispatcher Servlet
Here actually i am trying to access my spring based rest full service, I am not configuring DispatcherServlet in web.xml, instead of that i am using ContxtLoaderListener to load my spring configuration file.

From my logs i can see my service is getting initialized, when ever i access the above url, ICallServlet is receiving the request since it has the url-pattern as '/*'(this i can't modify).

Here my problem is i could not able to access my service, request is not reaching my service. without using DispatcherServlet is there any way to invoke my rest service, Some one please help me to resolve this issue.

I have a Rest Controller :

```<code>package mypackage;
@RestController
@RequestMapping("/api/casaOnboarding")
public class CasaOnboardingRestService {
    @ResponseBody
    @RequestMapping(value="/pwebXML", method=RequestMethod.POST, consumes={"application/json", "application/xml"})
    public ResponseEntity pwebXML(@RequestBody OnboardingReq onboardingReq,
            HttpServletRequest request, HttpServletResponse response){
 System.out.println("Request Reached");
----
}
}
</code>```

Web.xml (No Dispatcher Servlet)

```<code> <?xml version="1.0" encoding="UTF-8"?>
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:controllerServiceContext.xml</param-value>
</context-param>
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
<servlet>
   <servlet-name>iCallUI</servlet-name>
   <servlet-class>com.ui.ICallServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>iCallUI</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</code>```

controllerServiceContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"                                      xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"    xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:task="http://www.springframework.org/schema/task"
      xsi:schemaLocation="
      http://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
      http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd">

   <context:annotation-config />
   <context:component-scan base-package="mypackage"/>
   <task:annotation-driven />
</beans>
</code>```

Log File

```<code>10:45:41,643 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] (ServerService Thread Pool -- 62) Creating shared instance of singleton bean 'casaOnboardingRestService'
10:45:41,643 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] (ServerService Thread Pool -- 62) Creating instance of bean 'casaOnboardingRestService'
10:45:41,643 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] (ServerService Thread Pool -- 62) Eagerly caching bean 'casaOnboardingRestService' to allow for resolving potential circular references
10:45:41,643 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] (ServerService Thread Pool -- 62) Finished creating instance of bean 'casaOnboardingRestService'
</code>```

URL:
http://localhost:8080/icall-ui/api/casaOnboarding/pwebXML

答:
By using filter in web.xml</p>

```<code>    <!-- Spring security -->
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>
                  org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</code>```

Body:
Here actually i am trying to access my spring based rest full service, I am not configuring DispatcherServlet in web.xml, instead of that i am using ContxtLoaderListener to load my spring configuration file.

From my logs i can see my service is getting initialized, when ever i access the above url, ICallServlet is receiving the request since it has the url-pattern as '/*'(this i can't modify).

Here my problem is i could not able to access my service, request is not reaching my service. without using DispatcherServlet is there any way to invoke my rest service, Some one please help me to resolve this issue.

I have a Rest Controller :

package mypackage;
@RestController
@RequestMapping("/api/casaOnboarding")
public class CasaOnboardingRestService {
    @ResponseBody
    @RequestMapping(value="/pwebXML", method=RequestMethod.POST, consumes={"application/json", "application/xml"})
    public ResponseEntity pwebXML(@RequestBody OnboardingReq onboardingReq,
            HttpServletRequest request, HttpServletResponse response){
 System.out.println("Request Reached");
----
}
}

Web.xml (No Dispatcher Servlet)

 <?xml version="1.0" encoding="UTF-8"?>
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:controllerServiceContext.xml</param-value>
</context-param>
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
<servlet>
   <servlet-name>iCallUI</servlet-name>
   <servlet-class>com.ui.ICallServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>iCallUI</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

controllerServiceContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"                                      xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"    xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:task="http://www.springframework.org/schema/task"
      xsi:schemaLocation="
      http://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
      http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd">

   <context:annotation-config />
   <context:component-scan base-package="mypackage"/>
   <task:annotation-driven />
</beans>

Log File

10:45:41,643 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] (ServerService Thread Pool -- 62) Creating shared instance of singleton bean 'casaOnboardingRestService'
10:45:41,643 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] (ServerService Thread Pool -- 62) Creating instance of bean 'casaOnboardingRestService'
10:45:41,643 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] (ServerService Thread Pool -- 62) Eagerly caching bean 'casaOnboardingRestService' to allow for resolving potential circular references
10:45:41,643 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] (ServerService Thread Pool -- 62) Finished creating instance of bean 'casaOnboardingRestService'

URL:
http://localhost:8080/icall-ui/api/casaOnboarding/pwebXML

Body:
By using filter in web.xml

    <!-- Spring security -->
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>
                  org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>