问:
Maven Error - Expected START_TAG or END_TAG not TEXT
I am setting up a spring mvc web application + hibernate jpa + maven from scratch using Eclipse Indigo. I am stuck in this error when doing a Maven build.

```<code>[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error installing artifact's metadata: Error installing metadata: Error updating group repository metadata

expected START_TAG or END_TAG not TEXT (position: TEXT seen ...<extension>war</... @13:25)
[INFO] ------------------------------------------------------------------------
</code>```

I tried googling but can't find a solution that works for me. I even search the whole project for the text <extension>war</ and mysteriously, there is no text like this in my project. However, in the tomcat web.xml there are a lot of <extension> tag, but I doubt that it has something to do in this error because I never touched that web.xml

Here is my pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mycompany.applicationname</groupId>

    <artifactId>Application MVC</artifactId>

    <packaging>war</packaging>

    <version>0.0.1-SNAPSHOT</version>

    <name>Maven Application Webapp</name>

    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>3.0.3.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>ApplicationName</finalName>
    </build>
</project>
</code>```

As Funtik has suggested, I did a build with -X. Here is the stacktrace.

```<code>[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error installing artifact's metadata: Error installing metadata: Error updating group repository metadata

expected START_TAG or END_TAG not TEXT (position: TEXT seen ...<extension>war</... @13:25)
[INFO] ------------------------------------------------------------------------
[DEBUG] Trace
org.apache.maven.lifecycle.LifecycleExecutionException: Error installing artifact's metadata: Error installing metadata: Error updating group repository metadata
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:583)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:499)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:478)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:330)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:291)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:287)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error installing artifact's metadata: Error installing metadata: Error updating group repository metadata
    at org.apache.maven.plugin.install.InstallMojo.execute(InstallMojo.java:143)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:451)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:558)
    ... 16 more
Caused by: org.apache.maven.artifact.installer.ArtifactInstallationException: Error installing artifact's metadata: Error installing metadata: Error updating group repository metadata
    at org.apache.maven.artifact.installer.DefaultArtifactInstaller.install(DefaultArtifactInstaller.java:91)
    at org.apache.maven.plugin.install.InstallMojo.execute(InstallMojo.java:105)
    ... 18 more
Caused by: org.apache.maven.artifact.repository.metadata.RepositoryMetadataInstallationException: Error installing metadata: Error updating group repository metadata
    at org.apache.maven.artifact.repository.metadata.DefaultRepositoryMetadataManager.install(DefaultRepositoryMetadataManager.java:463)
    at org.apache.maven.artifact.installer.DefaultArtifactInstaller.install(DefaultArtifactInstaller.java:79)
    ... 19 more
Caused by: org.apache.maven.artifact.repository.metadata.RepositoryMetadataStoreException: Error updating group repository metadata
    at org.apache.maven.artifact.repository.metadata.AbstractRepositoryMetadata.storeInLocalRepository(AbstractRepositoryMetadata.java:76)
    at org.apache.maven.artifact.repository.metadata.DefaultRepositoryMetadataManager.install(DefaultRepositoryMetadataManager.java:459)
    ... 20 more
Caused by: org.codehaus.plexus.util.xml.pull.XmlPullParserException: expected START_TAG or END_TAG not TEXT (position: TEXT seen ...<extension>war</... @13:25)
    at org.codehaus.plexus.util.xml.pull.MXParser.nextTag(MXParser.java:1083)
    at org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader.parseVersioning(MetadataXpp3Reader.java:513)
    at org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader.parseMetadata(MetadataXpp3Reader.java:352)
    at org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader.read(MetadataXpp3Reader.java:866)
    at org.apache.maven.artifact.repository.metadata.AbstractRepositoryMetadata.updateRepositoryMetadata(AbstractRepositoryMetadata.java:98)
    at org.apache.maven.artifact.repository.metadata.AbstractRepositoryMetadata.storeInLocalRepository(AbstractRepositoryMetadata.java:68)
    ... 21 more
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Thu Jun 27 17:36:23 SGT 2013
[INFO] Final Memory: 9M/16M
[INFO] ------------------------------------------------------------------------
</code>```

web.xml

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

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Adjustment Tool</display-name>

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

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>
</code>```

Any ideas?

答: If you are getting this error when requesting an artifact from a Maven remote in Artifactory it can be solved by enabling the "Suppress POM Consistency Checks" option:

Body:
I am setting up a spring mvc web application + hibernate jpa + maven from scratch using Eclipse Indigo. I am stuck in this error when doing a Maven build.

[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error installing artifact's metadata: Error installing metadata: Error updating group repository metadata

expected START_TAG or END_TAG not TEXT (position: TEXT seen ...<extension>war</... @13:25)
[INFO] ------------------------------------------------------------------------

I tried googling but can't find a solution that works for me. I even search the whole project for the text <extension>war</ and mysteriously, there is no text like this in my project. However, in the tomcat web.xml there are a lot of <extension> tag, but I doubt that it has something to do in this error because I never touched that web.xml

Here is my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mycompany.applicationname</groupId>

    <artifactId>Application MVC</artifactId>

    <packaging>war</packaging>

    <version>0.0.1-SNAPSHOT</version>

    <name>Maven Application Webapp</name>

    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>3.0.3.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>ApplicationName</finalName>
    </build>
</project>

As Funtik has suggested, I did a build with -X. Here is the stacktrace.

[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error installing artifact's metadata: Error installing metadata: Error updating group repository metadata

expected START_TAG or END_TAG not TEXT (position: TEXT seen ...<extension>war</... @13:25)
[INFO] ------------------------------------------------------------------------
[DEBUG] Trace
org.apache.maven.lifecycle.LifecycleExecutionException: Error installing artifact's metadata: Error installing metadata: Error updating group repository metadata
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:583)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:499)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:478)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:330)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:291)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:287)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error installing artifact's metadata: Error installing metadata: Error updating group repository metadata
    at org.apache.maven.plugin.install.InstallMojo.execute(InstallMojo.java:143)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:451)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:558)
    ... 16 more
Caused by: org.apache.maven.artifact.installer.ArtifactInstallationException: Error installing artifact's metadata: Error installing metadata: Error updating group repository metadata
    at org.apache.maven.artifact.installer.DefaultArtifactInstaller.install(DefaultArtifactInstaller.java:91)
    at org.apache.maven.plugin.install.InstallMojo.execute(InstallMojo.java:105)
    ... 18 more
Caused by: org.apache.maven.artifact.repository.metadata.RepositoryMetadataInstallationException: Error installing metadata: Error updating group repository metadata
    at org.apache.maven.artifact.repository.metadata.DefaultRepositoryMetadataManager.install(DefaultRepositoryMetadataManager.java:463)
    at org.apache.maven.artifact.installer.DefaultArtifactInstaller.install(DefaultArtifactInstaller.java:79)
    ... 19 more
Caused by: org.apache.maven.artifact.repository.metadata.RepositoryMetadataStoreException: Error updating group repository metadata
    at org.apache.maven.artifact.repository.metadata.AbstractRepositoryMetadata.storeInLocalRepository(AbstractRepositoryMetadata.java:76)
    at org.apache.maven.artifact.repository.metadata.DefaultRepositoryMetadataManager.install(DefaultRepositoryMetadataManager.java:459)
    ... 20 more
Caused by: org.codehaus.plexus.util.xml.pull.XmlPullParserException: expected START_TAG or END_TAG not TEXT (position: TEXT seen ...<extension>war</... @13:25)
    at org.codehaus.plexus.util.xml.pull.MXParser.nextTag(MXParser.java:1083)
    at org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader.parseVersioning(MetadataXpp3Reader.java:513)
    at org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader.parseMetadata(MetadataXpp3Reader.java:352)
    at org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader.read(MetadataXpp3Reader.java:866)
    at org.apache.maven.artifact.repository.metadata.AbstractRepositoryMetadata.updateRepositoryMetadata(AbstractRepositoryMetadata.java:98)
    at org.apache.maven.artifact.repository.metadata.AbstractRepositoryMetadata.storeInLocalRepository(AbstractRepositoryMetadata.java:68)
    ... 21 more
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Thu Jun 27 17:36:23 SGT 2013
[INFO] Final Memory: 9M/16M
[INFO] ------------------------------------------------------------------------

web.xml

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

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Adjustment Tool</display-name>

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

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

Any ideas?


来源: stackexchange

问:
What's the difference between this and super keywords in java?
Check my coolMethod, babes:

```<code>package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}
</code>```

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.

```<code>package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}
</code>```

And my main, that calls my Moo class functionalities.

```<code>package javacert1;

import zoo.Moo;

public class Main {

    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}
</code>```

As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?

答:
Since you have only one coolMethod, it is called in each case, regardless of qualifiers. However, if you override your method in Moo e.g. like this

```<code>public class Moo extends Zoo {
    public String coolMethod() {
        return "Yeah dude!";
    }
    // the rest is the same as above...
}
</code>```

you will notice the difference between the calls to coolMethod() and this.coolMethod() versus the call to super.coolMethod().

ContentLicense: CC BY-SA 2.5

Body:
Check my coolMethod, babes:

package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.

package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}

And my main, that calls my Moo class functionalities.

package javacert1;

import zoo.Moo;

public class Main {

    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}

As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?

Body:
Since you have only one coolMethod, it is called in each case, regardless of qualifiers. However, if you override your method in Moo e.g. like this

public class Moo extends Zoo {
    public String coolMethod() {
        return "Yeah dude!";
    }
    // the rest is the same as above...
}

you will notice the difference between the calls to coolMethod() and this.coolMethod() versus the call to super.coolMethod().


问:
data not going from epic to reducer
if anyone of you see this i've a question i'm new to redux and i'm coming from angular and services logic so i kind of know how redux is working. I'm using only 2 epic listeners(one to call GET method from the service and one for POST) + services(for fetching data from an api). So whenever i've to call any api i make an object with some api configuration including url, param and if include authorization header in the api now the thing is this thing works fine when i dispatch one action at a time but when i've to do multiple actions means multiple get or post it stops in the epic after doing all the service and epic work and doesn't go to reducer to store the data and gives me error.
Actions must be plain objects. Use custom middleware for async actions
I know there's something wrong in my implementation. It would be great if it works this way else i've to move to other services like thunk or something else.

```<code> `
GetEpic = (action$) =>
            action$.ofType(Action.Get)
                .switchMap(({ payload }) => {
                    let { api, param, reqHeader, waitFor } = payload;
                    delete payload.api;
                    delete payload.param;
                    delete payload.reqHeader;
                    return HttpService.post(api, param, reqHeader, payload).then((userInfo) => {
                        if (userInfo.status && userInfo.status != 200) {
                            return {
                                type: 'ERROR'
                            }
                        }
                        return this.translateDataAndReturnType(userInfo, api, 'get', waitFor);
                    }).catch(() => {
                        return {
                            type: 'ERROR'
                        }
                    })
                })

translateDataAndReturnType(data, api, method, waitFor) {
        if (data && api) {
            this.count += 1;
            let actionInfo = this.routesData.find((d, i) => {
                return d.route == api
            })
            let routeAction = Object.assign({}, actionInfo);
            routeAction.payload = data;
            this.localDate[routeAction.route] = data;
            delete routeAction.route;
            if (typeof waitFor == 'number') {
                this.waitFor = waitFor;
                this.count = 0;
                this.count += 1;
            }
            if (this.count == this.waitFor) {
                routeAction.payload = this.localDate;
                if (this.actions) {
                    routeAction.type = this.actions;
                }
                return routeAction;
            }
        }
    }
`
</code>```

Updated with Answer

What i was doing wrong is trying to get response of multiple action shot from my component at once which is not possible so i changed my strategy to use single action with multiple apis for that i created a json with a route and apis

```<code>`this.routeConfig = {
  "countriesCitesTimezone": [
                { route: 'countries', type: 'SUCCESS-COUNTRIES', param: '', reqHeader: false },
                { route: 'cities', param: '', reqHeader: false },
                { route: 'timezone', param: '', reqHeader: false }
            ]
}`
</code>```

so whenever i have to call an action i calls the action with some configuration like

```<code>`var apiInfo = {
      route: 'countriesCitesTimezone',
      params: []
    }
    this.props.registration(apiInfo)`
</code>```

which is then handled by epic

```<code>`GetEpic = (action$) =>
            action$.ofType(Action.Get)
                .switchMap(({ payload }) => {
                   let requests = this.routesConfig[payload.route];
                   return Observable.forkJoin(
                    requests.map((d, ind) => {
                        let param = d.param;
                        if (payload.params.length > 0) {
                            param = payload.params[ind];
                        }
                        return (HttpService.get(d.route, param, d.reqHeader));
                    })
                ).map((x) => {
                    console.log(x);
                    let result = {};
                    requests.map((d, ind) => {
                        result[d.route] = x[ind]
                    })
                    return ({
                        type: requests[0].type,
                        payload: result
                    })
                })
                })`
</code>```

答:
I think what you are looking for is mergeMap instead of switchMap.

switchMap will:

Projects each source value to an Observable which is merged in the output Observable, emitting values only from the most recently projected Observable.

So, when using switchMap(), every new action of type Action.Get will prevent the emission of previous service call's response if it is still pending.

Also, assuming your service call returns a Promise, you should consider wrapping the HttpService.post() call in Observable.fromPromise(). I believe the reason you are getting the Actions must be plain objects... error is because you are emitting a Promise, which is then dispatched to the store.

ContentLicense: CC BY-SA 3.0

Title: data not going from epic to reducer

Body:
if anyone of you see this i've a question i'm new to redux and i'm coming from angular and services logic so i kind of know how redux is working. I'm using only 2 epic listeners(one to call GET method from the service and one for POST) + services(for fetching data from an api). So whenever i've to call any api i make an object with some api configuration including url, param and if include authorization header in the api now the thing is this thing works fine when i dispatch one action at a time but when i've to do multiple actions means multiple get or post it stops in the epic after doing all the service and epic work and doesn't go to reducer to store the data and gives me error.
Actions must be plain objects. Use custom middleware for async actions
I know there's something wrong in my implementation. It would be great if it works this way else i've to move to other services like thunk or something else.

 `
GetEpic = (action$) =>
            action$.ofType(Action.Get)
                .switchMap(({ payload }) => {
                    let { api, param, reqHeader, waitFor } = payload;
                    delete payload.api;
                    delete payload.param;
                    delete payload.reqHeader;
                    return HttpService.post(api, param, reqHeader, payload).then((userInfo) => {
                        if (userInfo.status && userInfo.status != 200) {
                            return {
                                type: 'ERROR'
                            }
                        }
                        return this.translateDataAndReturnType(userInfo, api, 'get', waitFor);
                    }).catch(() => {
                        return {
                            type: 'ERROR'
                        }
                    })
                })

translateDataAndReturnType(data, api, method, waitFor) {
        if (data && api) {
            this.count += 1;
            let actionInfo = this.routesData.find((d, i) => {
                return d.route == api
            })
            let routeAction = Object.assign({}, actionInfo);
            routeAction.payload = data;
            this.localDate[routeAction.route] = data;
            delete routeAction.route;
            if (typeof waitFor == 'number') {
                this.waitFor = waitFor;
                this.count = 0;
                this.count += 1;
            }
            if (this.count == this.waitFor) {
                routeAction.payload = this.localDate;
                if (this.actions) {
                    routeAction.type = this.actions;
                }
                return routeAction;
            }
        }
    }
`

Updated with Answer

What i was doing wrong is trying to get response of multiple action shot from my component at once which is not possible so i changed my strategy to use single action with multiple apis for that i created a json with a route and apis

`this.routeConfig = {
  "countriesCitesTimezone": [
                { route: 'countries', type: 'SUCCESS-COUNTRIES', param: '', reqHeader: false },
                { route: 'cities', param: '', reqHeader: false },
                { route: 'timezone', param: '', reqHeader: false }
            ]
}`

so whenever i have to call an action i calls the action with some configuration like

`var apiInfo = {
      route: 'countriesCitesTimezone',
      params: []
    }
    this.props.registration(apiInfo)`

which is then handled by epic

`GetEpic = (action$) =>
            action$.ofType(Action.Get)
                .switchMap(({ payload }) => {
                   let requests = this.routesConfig[payload.route];
                   return Observable.forkJoin(
                    requests.map((d, ind) => {
                        let param = d.param;
                        if (payload.params.length > 0) {
                            param = payload.params[ind];
                        }
                        return (HttpService.get(d.route, param, d.reqHeader));
                    })
                ).map((x) => {
                    console.log(x);
                    let result = {};
                    requests.map((d, ind) => {
                        result[d.route] = x[ind]
                    })
                    return ({
                        type: requests[0].type,
                        payload: result
                    })
                })
                })`


问:
Filter in MDX query with Date Range filter and Year Filter
I'm trying to filter my MDX query of can someone help me on how this can be done.
My code

```<code>Select
[Measures].[Net_Cost] on 0,
[State].[City] on 1

FROM
[SALES]

WHERE
([Date].[Date.AYearly].[2017]),([Date].[Date.AMonthly].[1] : [Date].[Date.AMonthly].[12])
</code>```

and it throws an error.

I want to accomplish the following:

Where
year = 2017 and month is between 1 and current month.

How can this be done.

Thanks in advance

答:
Maybe try one filter in a subselect and the other in the outer query:</p>

```<code>SELECT
   [Measures].[Net_Cost] on 0,
   [State].[City] on 1
FROM
  (
   SELECT
     [Date].[Date.AYearly].[2017] ON 0
   FROM [SALES]
  )
WHERE
([Date].[Date.AMonthly].[1] : [Date].[Date.AMonthly].[12])
;
</code>```

Body:
I'm trying to filter my MDX query of can someone help me on how this can be done.
My code

Select
[Measures].[Net_Cost] on 0,
[State].[City] on 1

FROM
[SALES]

WHERE
([Date].[Date.AYearly].[2017]),([Date].[Date.AMonthly].[1] : [Date].[Date.AMonthly].[12])

and it throws an error.

I want to accomplish the following:

Where
year = 2017 and month is between 1 and current month.

How can this be done.

Thanks in advance

Body:
Maybe try one filter in a subselect and the other in the outer query:

SELECT
   [Measures].[Net_Cost] on 0,
   [State].[City] on 1
FROM
  (
   SELECT
     [Date].[Date.AYearly].[2017] ON 0
   FROM [SALES]
  )
WHERE
([Date].[Date.AMonthly].[1] : [Date].[Date.AMonthly].[12])
;


问:
Trouble converting php array to json format slightly wrong
I'm having trouble getting the correct json format from the following php array

```<code>Array
(
    [0] => Array
        (
            [name] => name1
            [data] => Array
                (
                    [0] => Array
                        (
                            [5] => 2013-15-6,9
                            [6] => 2013-15-7,9
                            [7] => 2013-15-8,9
                            [8] => 2013-15-9,9
                            [9] => 2013-15-10,9
                            [10] => 2013-15-11,9
                            [11] => 2013-15-12,9
                        )

                )

        )

)
</code>```

Encoding it to json outputs

```<code>[
    {
        "name": "name1",
        "data": [
            {
                "5": "2013-15-6,9",
                "6": "2013-15-7,9",
                "7": "2013-15-8,9",
                "8": "2013-15-9,9",
                "9": "2013-15-10,9",
                "10": "2013-15-11,9",
                "11": "2013-15-12,9"
            }
        ]
    }
]
</code>```

What I need the json output to look like is below, basically removing the curly brackets inside the data array and remove the index numbers thought I don't think that's possible.

```<code>[
    {
        "name": "name1",
        "data": [
            "2013-15-11,9",
            "2013-15-12,9"
        ]
    }
]
</code>```

I've tried different combinations of array() around variables which got me close enough by adding the bracket inside the data array but I can't get rid of the curly brackets. Would really appreciate some help, have been working on this for a few hours. Thanks

Body:
I'm having trouble getting the correct json format from the following php array

Array
(
    [0] => Array
        (
            [name] => name1
            [data] => Array
                (
                    [0] => Array
                        (
                            [5] => 2013-15-6,9
                            [6] => 2013-15-7,9
                            [7] => 2013-15-8,9
                            [8] => 2013-15-9,9
                            [9] => 2013-15-10,9
                            [10] => 2013-15-11,9
                            [11] => 2013-15-12,9
                        )

                )

        )

)

Encoding it to json outputs

[
    {
        "name": "name1",
        "data": [
            {
                "5": "2013-15-6,9",
                "6": "2013-15-7,9",
                "7": "2013-15-8,9",
                "8": "2013-15-9,9",
                "9": "2013-15-10,9",
                "10": "2013-15-11,9",
                "11": "2013-15-12,9"
            }
        ]
    }
]

What I need the json output to look like is below, basically removing the curly brackets inside the data array and remove the index numbers thought I don't think that's possible.

[
    {
        "name": "name1",
        "data": [
            "2013-15-11,9",
            "2013-15-12,9"
        ]
    }
]

I've tried different combinations of array() around variables which got me close enough by adding the bracket inside the data array but I can't get rid of the curly brackets. Would really appreciate some help, have been working on this for a few hours. Thanks

Body:
By overwriting [0]['data'] with a new indexed array of the values in `[0]['data'][0]', you can restructure your data in one line.

Code: (Demo)

$array=[
            ['name'=>'name1',
             'data'=>[
                 [
                     5=>'2013-15-6,9',
                     6=>'2013-15-7,9',
                     7=>'2013-15-8,9',
                     8=>'2013-15-9,9',
                     9=>'2013-15-10,9',
                     10=>'2013-15-11,9',
                     11=>'2013-15-12,9'
                 ]
              ]
            ]
        ];
$array[0]['data']=array_values($array[0]['data'][0]);
echo json_encode($array);

Output:

[
    {
        "name":"name1",
        "data":[
            "2013-15-6,9",
            "2013-15-7,9",
            "2013-15-8,9",
            "2013-15-9,9",
            "2013-15-10,9",
            "2013-15-11,9",
            "2013-15-12,9"
        ]
    }
]


问:
Only display Woocommerce child product categories
I am currently using the following code to fetch WooCommerce product categories:

```<code><?php
    $orderby = 'name';
    $order = 'asc';
    $hide_empty = false ;
    $cat_args = array(
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
    );

    $product_categories = get_terms( 'product_cat', $cat_args );

    if( !empty($product_categories) ){
        echo '<ul>';
        foreach ($product_categories as $key => $category) {
            echo '<li>';
            echo '<a href="'.get_term_link($category).'" >';
            echo $category->name;
            echo '</a>';
            echo '<li>';
        }
        echo '</ul>';
    }
?>
</code>```

This currently displays all categories, however I wish this to only show the child categories.

For example, if you are on the Category 1 page, it should show all children within that category only.

I've looked at many examples on here but have been unable to find something that works for what I need.

答:
Here is a way to get only product subcategories linked list ordered by name ASC:

```<code>// The product category taxonomy
$taxonomy = 'product_cat';

// Get the parent categories IDs
$parent_cat_ids = get_terms( $taxonomy, array(
    'parent'     => 0,
    'hide_empty' => false,
    'fields'     => 'ids'
) );

// Get only "child" WP_Term Product categories
$subcategories = get_terms( $taxonomy, array(
    'exclude'     => $parent_cat_ids,
    'orderby'    => 'name',
    'order'      => 'asc',
    'hide_empty' => false,
) );

if( ! empty( $subcategories ) ){
    echo '<ul>';
    foreach ($subcategories as $subcategory) {
        echo '<li>
            <a href="'. get_term_link($subcategory) .'" >' . $subcategory->name.'</a>
        </li>';
    }
    echo '</ul>';
}
</code>```

The code is tested and works

Body:
I am currently using the following code to fetch WooCommerce product categories:

<?php
    $orderby = 'name';
    $order = 'asc';
    $hide_empty = false ;
    $cat_args = array(
        'orderby'    => $orderby,
        'order'      => $order,
        'hide_empty' => $hide_empty,
    );

    $product_categories = get_terms( 'product_cat', $cat_args );

    if( !empty($product_categories) ){
        echo '
';
        foreach ($product_categories as $key => $category) {
            echo '
';
            echo '';
            echo $category->name;
            echo '';
            echo '
';
        }
        echo '
';
    }
?>

This currently displays all categories, however I wish this to only show the child categories.

For example, if you are on the Category 1 page, it should show all children within that category only.

I've looked at many examples on here but have been unable to find something that works for what I need.

Body:
Here is a way to get only product subcategories linked list ordered by name ASC:

// The product category taxonomy
$taxonomy = 'product_cat';

// Get the parent categories IDs
$parent_cat_ids = get_terms( $taxonomy, array(
    'parent'     => 0,
    'hide_empty' => false,
    'fields'     => 'ids'
) );

// Get only "child" WP_Term Product categories
$subcategories = get_terms( $taxonomy, array(
    'exclude'     => $parent_cat_ids,
    'orderby'    => 'name',
    'order'      => 'asc',
    'hide_empty' => false,
) );

if( ! empty( $subcategories ) ){
    echo '<ul>';
    foreach ($subcategories as $subcategory) {
        echo '<li>
            <a href="'. get_term_link($subcategory) .'" >' . $subcategory->name.'</a>
        </li>';
    }
    echo '</ul>';
}

The code is tested and works


问:
Python error handling two dependent tasks
What's the best way to handle this? I want to create a file and add a record to a database, but if either one fails, I want to undo the other. It looks kind of messy to have a try, except, else with another try, except inside it to handle undoing the first task if the second fails.</p>

```<code>try:
    open and write file
except:
    pass
else:
    try:
        add record to db
    except:
        delete file
</code>```

答:
Using try/except is sufficient:</p>

```<code>try:
    open and write file
    try:
        add record to db
    except:
        delete file
except:
    pass
</code>```

Body:
What's the best way to handle this? I want to create a file and add a record to a database, but if either one fails, I want to undo the other. It looks kind of messy to have a try, except, else with another try, except inside it to handle undoing the first task if the second fails.

try:
    open and write file
except:
    pass
else:
    try:
        add record to db
    except:
        delete file

Body:
Using try/except is sufficient:

try:
    open and write file
    try:
        add record to db
    except:
        delete file
except:
    pass


问:
jquery html($("").attr("src", this.href)); not working in Safari
I'm  using a simple jquery function for an image gallery. There is a div of thumbnails, then the target div where the large images are loaded into after one clicks on a thumbnail.

It's working fine in all browsers, with the exception of Safari, where the image's absolute url is loaded, opposed to being loaded inside of the div.

Here's the jquery code:

```<code>$("#thumbnails a").click(function() {
    $("#work").html($("<img>").attr("src", this.href));

    return false;
});
</code>```

Any thoughts? Thanks

答:
```<code>$("#thumbnails a").click(function() {
      $('#work').empty().append($('<img>', {
           src:   this.href
      }));
      return false;
});
</code>```

Title: jquery html($("<img>").attr("src", this.href)); not working in Safari

Body:
I'm  using a simple jquery function for an image gallery. There is a div of thumbnails, then the target div where the large images are loaded into after one clicks on a thumbnail.

It's working fine in all browsers, with the exception of Safari, where the image's absolute url is loaded, opposed to being loaded inside of the div.

Here's the jquery code:

$("#thumbnails a").click(function() {
    $("#work").html($("").attr("src", this.href));

    return false;
});

Any thoughts? Thanks


问:
Function.name empty in Microsoft Edge
I have some code that works fine in Chrome:

```<code>var someFunc = function(thisIsAFunction) {
   var functionName = thisIsAFunction.name;
}
</code>```

The docs say that this code will work in all browsers except IE 11, for which I have a polyfill method. Recently, Edge is reporting that 'thisIsAFunction.name' is empty. My polyfill doesn't kick in because thisIsAFunction.name is not undefined. The value, of course, should be the functions name.

Any idea of what's going on? Is this just a bug in Edge that hasn't been reported yet? I can code around it by checking for an empty value in name, but I hate doing that (but I will if that's the only option)

答:
So the answer here is that with Edge, you have to name your functions like this:

```<code>var someFunc = function SomeFunc() {}
</code>```

if you want SomeFunc.name to equal 'SomeFunc'. Not ideal, but there it is all the same. What a world.

Title: Function.name empty in Microsoft Edge

Body:
I have some code that works fine in Chrome:

var someFunc = function(thisIsAFunction) {
   var functionName = thisIsAFunction.name;
}

The docs say that this code will work in all browsers except IE 11, for which I have a polyfill method. Recently, Edge is reporting that 'thisIsAFunction.name' is empty. My polyfill doesn't kick in because thisIsAFunction.name is not undefined. The value, of course, should be the functions name.

Any idea of what's going on? Is this just a bug in Edge that hasn't been reported yet? I can code around it by checking for an empty value in name, but I hate doing that (but I will if that's the only option)

Body:
So the answer here is that with Edge, you have to name your functions like this:

var someFunc = function SomeFunc() {}

if you want SomeFunc.name to equal 'SomeFunc'. Not ideal, but there it is all the same. What a world.


问:
Aggregate event log to weekly overview
Suppose I have the following table:

```<code>Table A: Event Log

ID        Step        WeekArrived        WeekCompleted
-------------------------------------------------------
1         A           1                  1
1         B           1                  3
2         B           3                  3
</code>```

So in week 1, case 1 arrives. For this case, step A is completed in week 1, but step B is not. Step B is completed in week 3. Case 2 also arrives in week 3, and step B is completed in the same week (Step A wasn't needed for this case).

I would like to aggregate this event log into a weekly per step overview like this:

```<code>Table B: Weekly Overview

Week      Step        In                 Backlog               Out
------------------------------------------------------------------
1         A           1                  0                     1
1         B           1                  1                     0
2         A           0                  0                     0
2         B           0                  1                     0
3         A           0                  0                     0
3         B           1                  0                     2
</code>```

For each week X and step Y, this table shows:

In: the number of cases that started step Y in week X

Backlog: the number of cases which arrived at step Y in week <= X, and are not yet completed at the end of week X.

Out: the number of cases that completed step Y in week X

How can I get from table A to table B?

答:
First, you need a way to get a list of week_ids, I used Teradata's system calendar. Then it's a Cross Join plus some conditional aggregation:</p>

```<code>SELECT week_id, step,
   Sum(CASE WHEN week_id = WeekArrived THEN 1 ELSE 0 END) AS "in",
   Sum(CASE WHEN week_id >= WeekArrived AND week_id < WeekCompleted THEN 1 ELSE 0 END) as "backlog",
   Sum(CASE WHEN week_id = WeekCompleted THEN 1 ELSE 0 END) AS "out"
FROM
 ( -- get a lsit of week ids
   SELECT day_of_calendar AS week_id
   FROM sys_calendar.CALENDAR
   WHERE week_id
   -- calculate the range of week ids
   BETWEEN (SELECT Min(WeekArrived) FROM event_log)
       AND (SELECT Max(WeekCompleted) FROM event_log)
 ) AS weeks
CROSS JOIN
 (
   SELECT  *
   FROM event_log
 ) AS steps
GROUP BY week_id, step
ORDER BY week_id, step
</code>```

Title: Aggregate event log to weekly overview

Body:
Suppose I have the following table:

Table A: Event Log

ID        Step        WeekArrived        WeekCompleted
-------------------------------------------------------
1         A           1                  1
1         B           1                  3
2         B           3                  3

So in week 1, case 1 arrives. For this case, step A is completed in week 1, but step B is not. Step B is completed in week 3. Case 2 also arrives in week 3, and step B is completed in the same week (Step A wasn't needed for this case).

I would like to aggregate this event log into a weekly per step overview like this:

Table B: Weekly Overview

Week      Step        In                 Backlog               Out
------------------------------------------------------------------
1         A           1                  0                     1
1         B           1                  1                     0
2         A           0                  0                     0
2         B           0                  1                     0
3         A           0                  0                     0
3         B           1                  0                     2

For each week X and step Y, this table shows:

In: the number of cases that started step Y in week X

Backlog: the number of cases which arrived at step Y in week <= X, and are not yet completed at the end of week X.

Out: the number of cases that completed step Y in week X

How can I get from table A to table B?

Body:
First, you need a way to get a list of week_ids, I used Teradata's system calendar. Then it's a Cross Join plus some conditional aggregation:

SELECT week_id, step,
   Sum(CASE WHEN week_id = WeekArrived THEN 1 ELSE 0 END) AS "in",
   Sum(CASE WHEN week_id >= WeekArrived AND week_id < WeekCompleted THEN 1 ELSE 0 END) as "backlog",
   Sum(CASE WHEN week_id = WeekCompleted THEN 1 ELSE 0 END) AS "out"
FROM
 ( -- get a lsit of week ids
   SELECT day_of_calendar AS week_id
   FROM sys_calendar.CALENDAR
   WHERE week_id
   -- calculate the range of week ids
   BETWEEN (SELECT Min(WeekArrived) FROM event_log)
       AND (SELECT Max(WeekCompleted) FROM event_log)
 ) AS weeks
CROSS JOIN
 (
   SELECT  *
   FROM event_log
 ) AS steps
GROUP BY week_id, step
ORDER BY week_id, step


问:
Text input with IF statements
I am creating a very simple story based "game" where there is a question with choices (not radio buttons etc) and the user has to type in the choices that's been given to them. I am not very good with JavaScript as you will see...

```<code><!DOCTYPE HTML>
<html>

<head>
<script type="text/javascript" src="gamescript.js"></script>
</head>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<script>
function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1", "door 1"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else if (door == "Door 2", "door 2"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

</script>

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

I am not getting any errors but when I type in something random/or leave blank, it's meant to say "Choose a door" but it's displaying anything i type into the text box. This code might be wrong, i'm guessing it most likely is..I didn't want to come online for help but have no one else to ask. All help is appreciated. Thank you.

答:
You could make use ot toLowerCase() and then compare door to "door 1", etc.

```<code>function myFunction(){
var door = document.getElementById("myInput").value.toLowerCase();

if (door == "door 1"){
    document.getElementById("door").innerHTML = "You have entered" + door;
}else if (door == "door 2"){
    document.getElementById("door").innerHTML = "You have entered" + door;
}else{
    document.getElementById("door").innerHTML = "You must enter a door!"
}
</code>```

In case you need, you can use || (or) logical operator and evaluate if (door == "Door 1" || door =="door 1")

Title: Text input with IF statements

Body:
I am creating a very simple story based "game" where there is a question with choices (not radio buttons etc) and the user has to type in the choices that's been given to them. I am not very good with JavaScript as you will see...

<!DOCTYPE HTML>

 Which door do you wish to enter? Door 1 or Door 2?

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

I am not getting any errors but when I type in something random/or leave blank, it's meant to say "Choose a door" but it's displaying anything i type into the text box. This code might be wrong, i'm guessing it most likely is..I didn't want to come online for help but have no one else to ask. All help is appreciated. Thank you.

Body:
You could make use ot toLowerCase() and then compare door to "door 1", etc.

function myFunction(){
var door = document.getElementById("myInput").value.toLowerCase();

if (door == "door 1"){
    document.getElementById("door").innerHTML = "You have entered" + door;
}else if (door == "door 2"){
    document.getElementById("door").innerHTML = "You have entered" + door;
}else{
    document.getElementById("door").innerHTML = "You must enter a door!"
}

In case you need, you can use || (or) logical operator and evaluate if (door == "Door 1" || door =="door 1")


问:
How to handle SMTP email verification at scale without getting IPs blocked or SMTP requests rejected?
I hope this question is not completely off-topic.

I've been wondering about SMTP email verification. There are so many services (e.g. Kickbox.io, Email-Validator.net, etc.) that seem to handle SMTP verification without having their IPs blocked or SMTP requests rejected.

As far as I know there is still no other method than to use the SMTP "VRFY" command, and to abort the connection once the target SMTP server has confirmed the existence of the requested user on the given mail server. I've been playing around with a few PHP scripts that claim to do this, but I keep being rejected by some mail servers, especially hotmail (as well as all other Microsoft mail services) seem to be very quickly in rejecting "spammy" SMTP requests.

Now, my question is: How is it possible that services like the ones I mentioned above process thousands of email addresses a day and validate them via what they call "SMTP handshakes", and don't see similar issues like the ones I described?

Thanks for reading.

答: Many of the companies you mention send the email to be verified as part of the RCPT TO command. Most domains will respond to this command with an error if the address is invalid. No email needs to actually be sent. Paid email verification services like Kickbox typically combine a well-respected email sending network that can handshake with many servers with some smart caching in order to achieve their results.

ContentLicense: CC BY-SA 4.0


问:
How to use MySQL indexes
I tried to create an index on MySQL using this query

```<code>CREATE TABLE test (id INT, age INT, INDEX(id,age));
</code>```

DESCRIBE test; gives this:

```<code>+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  | MUL | NULL    |       |
| age   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
</code>```

When i tried to found why just the id was indexed i found 2 more things. That CREATE INDEX query requeires a name for the index and also that there is a USE INDEX () statement.

Now my questions:

Is the first query wrong or did I indexed both the id and the age like a pair and that's why just ID shows to be indexed?

Can I create indexes without providing a name, as I did in the first query (or when setting a column PRIMARY KEY)?

Should I add USE INDEX everytime I want to use the index? If yes, are there situations when the index is used by default (for example, when creating an index without a name, if possible)?

答:
Use SHOW CREATE TABLE; it is more descriptive than DESCRIBE !

The DESCRIBE that you presented disagrees with the existence of INDEX(id,age).

Normally, id is the PRIMARY KEY of a table.  You have broken with tradition; please explain what your intent is.

Do not use USE INDEX or FORCE INDEX -- it may help 'today', but is likely to hurt 'tomorrow'.  Let the Optimizer decide which (if any) index to use.

We can't critique a schema without knowing what SELECTs you will be using against it.

Every table should have a PRIMARY KEY.  Note:  A PK is, by definition (in MySQL) both UNIQUE and INDEX.

There is almost no use for the name of an index.  If you don't name an index, a name will be generated.  A name is necessary when DROPping the index.

Title: How to use MySQL indexes

Body:
I tried to create an index on MySQL using this query

CREATE TABLE test (id INT, age INT, INDEX(id,age));

DESCRIBE test; gives this:

+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  | MUL | NULL    |       |
| age   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+

When i tried to found why just the id was indexed i found 2 more things. That CREATE INDEX query requeires a name for the index and also that there is a USE INDEX () statement.

Now my questions:

Is the first query wrong or did I indexed both the id and the age like a pair and that's why just ID shows to be indexed?

Can I create indexes without providing a name, as I did in the first query (or when setting a column PRIMARY KEY)?

Should I add USE INDEX everytime I want to use the index? If yes, are there situations when the index is used by default (for example, when creating an index without a name, if possible)?


问:
A Singleton with multiple instances?

Background

I have a situation in which I'm developing a program that runs like a thread. Basically, there is a "master" program that runs instances of sub-programs simultaneously.

Due to the nature of this system, the "sub-programs" all run under a single Java Virtual Machine. The most serious implication here is that they share memory spaces.

In my sub-program, I want to create a Logger class so that all the classes within my sub-program can log to a single location. Since this project can include many classes, I want to avoid Dependency Injection and use a Singleton.

But if I use a Singleton, the instance will be stored statically. So if the JVM has 2 instances of my program running, the Logger class will give them the same instance (because they share that memory).

I want each sub-program to have their own logger, without dependency injection.

There exists a unique identifier that I can call for each program to differentiate between them.

My Current Solution

Assume "uniqueID" is an API call that the Master Program receives and then returns what Sub-Program called it. Assume this call produces extremely little computational overhead.

```<code>public class Logger {
    private static HashMap<string,Logger> instances = new Hashmap<>();

    public static Logger instance() {
        if(instances.containsKey(uniqueId)) {
            return instances.get(uniqueId);
        } else {
            Logger newLogger = new Logger();
            instances.put(uniqueId, newLogger);
            return newLogger;
        }
    }

    private Logger(){}
}
</code>```

This solution allows each sub-program to treat the Logger class like a Singleton, but it's not quite a Singleton. It acts as an Instance Manager, that creates and returns instances based on which sub-program is interacting with the method.

My Question(s)

This solution is not technically a Singleton, but each project using it treats it like a singleton. What design pattern is it?

Also, is this the correct approach to my problem? How can I improve it?

答:
If I read correctly, you want a thread-based multiton. Java provides the ThreadLocal class to support that pattern. With a little thought, you can implement a static logMessage() method that uses the ThreadLocal under the covers to retrieve the correct logger instance.

Care should be taken in JEE application server environments to avoid memory leaks when the application context is restarted, but I don't think that applies to your situation.

Title: A Singleton with multiple instances?

Body:
Background

I have a situation in which I'm developing a program that runs like a thread. Basically, there is a "master" program that runs instances of sub-programs simultaneously.

Due to the nature of this system, the "sub-programs" all run under a single Java Virtual Machine. The most serious implication here is that they share memory spaces.

In my sub-program, I want to create a Logger class so that all the classes within my sub-program can log to a single location. Since this project can include many classes, I want to avoid Dependency Injection and use a Singleton.

But if I use a Singleton, the instance will be stored statically. So if the JVM has 2 instances of my program running, the Logger class will give them the same instance (because they share that memory).

I want each sub-program to have their own logger, without dependency injection.

There exists a unique identifier that I can call for each program to differentiate between them.

My Current Solution

Assume "uniqueID" is an API call that the Master Program receives and then returns what Sub-Program called it. Assume this call produces extremely little computational overhead.

public class Logger {
    private static HashMap<string,Logger> instances = new Hashmap<>();

    public static Logger instance() {
        if(instances.containsKey(uniqueId)) {
            return instances.get(uniqueId);
        } else {
            Logger newLogger = new Logger();
            instances.put(uniqueId, newLogger);
            return newLogger;
        }
    }

    private Logger(){}
}

This solution allows each sub-program to treat the Logger class like a Singleton, but it's not quite a Singleton. It acts as an Instance Manager, that creates and returns instances based on which sub-program is interacting with the method.

My Question(s)

This solution is not technically a Singleton, but each project using it treats it like a singleton. What design pattern is it?

Also, is this the correct approach to my problem? How can I improve it?


问:
How to make two left navbars with bootstrap?
I am trying to make a simple design including two left columns each including a navbar and one right column with the content.
I have tried a lot of things but each time I have a problem :

my columns don't stay on the left of my page (I want the two columns left fixed size, and the content column fluid taking the rest of the
page)

my columns overlap

the content overlaps with the content

I can't figure out what is wrong. This is what I desire to obtain :

And this is a sample of my actual code

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

        BRAND

Tralalala1

SubMenu

RSubMenue

BSubMenut

SSubMenu

Tralalala1

SubsubMenu

SubSubMenu

SubSubMenut

SubSubMenu

SubSub Menu4

SubSub Menu5

```

答:
You mixed some of the tags up which weren't closed correctly.

You don't need so many container-elements. You can have one as your outermost element.

Are you using offset on purpose? Have a look which column classes I used.

Second navbar wasn't closed correctly

I tried to keep the example simple. Click „Run code snipped” and try full page to see the result.

  <link href="https://getbootstrap.com/docs/3.3/dist/css/bootstrap.min.css" rel="stylesheet"/>

        BRAND

Tralalala1

SubMenu

RSubMenue

BSubMenut

SSubMenu

         Tralalala1

SubsubMenu

SubSubMenu

SubSubMenut

SubSubMenu

SubSub Menu4

SubSub Menu5

      Content

```

Body:
You mixed some of the tags up which weren't closed correctly.

You don't need so many container-elements. You can have one as your outermost element.

Are you using offset on purpose? Have a look which column classes I used.

Second navbar wasn't closed correctly

I tried to keep the example simple. Click „Run code snipped” and try full page to see the result.

<html>
<head>
  <link href="https://getbootstrap.com/docs/3.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>

<body>

  <div class="container-fluid">

    <div class="row">

    <div class="col-sm-2">

      <div class="navbar navbar-inverse navbar-fixed-left">

        <a class="navbar-brand" href="#">BRAND  </a>

        <ul class="nav navbar-nav">

           <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Tralalala1<span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
              <li><a href="#">SubMenu</a></li>
              <li><a href="#">RSubMenue</a></li>
              <li><a href="#">BSubMenut</a></li>
              <li><a href="#">SSubMenu</a></li>
            </ul>
           </li>

        </ul>

    </div>

    </div>
    <div class="col-sm-2">

      <ul class="nav navbar-nav">

       <li class="dropdown">
         <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tralalala1<span class="caret"></span></a>
          <ul class="dropdown-menu" role="menu">
            <li><a href="#">SubsubMenu</a></li>
            <li><a href="#">SubSubMenu</a></li>
            <li><a href="#">SubSubMenut</a></li>
            <li><a href="#">SubSubMenu</a></li>
            <li class="divider"></li>
            <li><a href="#">SubSub Menu4</a></li>
            <li><a href="#">SubSub Menu5</a></li>
          </ul>
        </li>
      </ul>

    </div>

    <div class="col-sm-8">
      Content
      <img id="TimeLine" src="http://img.playbuzz.com/image/upload/f_auto,fl_lossy,q_auto/cdn/a123d728-dd6e-46b1-85c2-5907d9fbb488/5b3da9cf-d8b7-41cd-ae02-a414dbde71fc.jpg" orgwidth="1008" orgheight="709" usemap="#image-maps-2017-11-27-071035" alt="TimeLine Demande de Ticketing Generale" align="centre" border="0" height="709" width="1008">
    </div>

    </div>

  </div>

</body>

</html>


问:
ListBoxFor is case insensitive
In select I have 2 options with same text, but different case: test and TEST as example.

From server I receive only one selected item test. But on UI I see both test and TEST are selected.

```<code>var tagsList = Model.AllTags.Select(t => new SelectListItem
{
    Value = t,
    Text = t
});

<div id="tags-list-container" class="review-tags__select" style="display: none;">
    @Html.ListBoxFor(m => m.SelectedTags, tagsList, new { id = "tags-list-box" })
</div>
</code>```

Is there any solution to make difference between my options ?

Firstly I thought it is caused by 3rd-party library for multiple select SumoSelect but later I've tried to use native multiple select and same thing happens - in result I have 2 selected options.

UPD:

Currently my thoughts about setting selected values using jquery, something like this:

```<code>$('#tags-list-box').val('test');
</code>```

But it will be better to have this in ListBoxFor extension as for me.

答:
Internally the ListBoxFor() method generates its own IEnumerable<SelectListItem> to set the Selected property based on the value of the property your binding to.

From the source code, you can see that the private static IEnumerable<SelectListItem> GetSelectListWithDefaultValue() compares the values using StringComparer.OrdinalIgnoreCase so a value of "test" and "TEST" both match and both options would be set with the selected="selected" attribute.

If you want to use a HtmlHelper methods to generate the correct html to account for case sensitive values, then you will need to write your extension method (use the source code as a template for your code.

Title: ListBoxFor is case insensitive

Body:
In select I have 2 options with same text, but different case: test and TEST as example.

From server I receive only one selected item test. But on UI I see both test and TEST are selected.

var tagsList = Model.AllTags.Select(t => new SelectListItem
{
    Value = t,
    Text = t
});

    @Html.ListBoxFor(m => m.SelectedTags, tagsList, new { id = "tags-list-box" })

Is there any solution to make difference between my options ?

Firstly I thought it is caused by 3rd-party library for multiple select SumoSelect but later I've tried to use native multiple select and same thing happens - in result I have 2 selected options.

UPD:

Currently my thoughts about setting selected values using jquery, something like this:

$('#tags-list-box').val('test');

But it will be better to have this in ListBoxFor extension as for me.


问:
Mongoose and multiple database error handling
I have 2 Databases, 1: in local and 2: in mlab, and with this Code I Can Check error for one of databases if my Connection has a Problem.

```<code>mongoose.connect('mongodb://localhost/test', { useMongoClient: true });
mongoose.Promise = global.Promise;

const db = mongoose.connection;

db.on('error', console.error);
db.once('open', () => {
    console.log(rangi.green('Connected To MongoDB'));
});

module.exports = db;

cron.schedule('1 * * * *', () => {
    const sync = mongoose.createConnection('mongodb://sync:sync@ds143542.mlab.com:');
    const remoteList = sync.model('User');
    remoteList.find({}, (err, docs) => {
        User.collection.insert(docs, status)
    })

    function status(err, result) {
        if (err && err.code == 11000) {
            console.log(rangi.red(`Err`));
        } else {
            console.info(rangi.magenta(`Sync Successful!`));
        }
    }
});
</code>```

How Can I Check connection for My Second database?

How to add Multi-mongos support or Multiple connections and Error handling for That?

```<code>mongoose.connect('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);
</code>```

答:
You may be looking for something like the following:

```<code>var localConnectStr = 'mongodb://localhost/test'
var mlabConnectStr = 'mongodb://<dbuser>:<dbpassword>@ds123456.mlab.com:25716/<dbname>'

var db = mongoose.createConnection(localConnectStr, { useMongoClient: true });
var mlabdb = mongoose.createConnection(mlabConnectStr, { useMongoClient: true });
</code>```

You'll of course want to use your actual mlab uri and database user/pass. But this is how you would handle multiple connections. See createConnection here.

You could use the code you have, checking your local connection, to check mlab.

```<code>mlabdb.on('error', console.error);
mlabdb.once('open', () => {
    console.log(rangi.green('Connected To Mlab MongoDB'));
});
</code>```

Body:
I have 2 Databases, 1: in local and 2: in mlab, and with this Code I Can Check error for one of databases if my Connection has a Problem.

mongoose.connect('mongodb://localhost/test', { useMongoClient: true });
mongoose.Promise = global.Promise;

const db = mongoose.connection;

db.on('error', console.error);
db.once('open', () => {
    console.log(rangi.green('Connected To MongoDB'));
});

module.exports = db;

cron.schedule('1 * * * *', () => {
    const sync = mongoose.createConnection('mongodb://sync:sync@ds143542.mlab.com:');
    const remoteList = sync.model('User');
    remoteList.find({}, (err, docs) => {
        User.collection.insert(docs, status)
    })

    function status(err, result) {
        if (err && err.code == 11000) {
            console.log(rangi.red(`Err`));
        } else {
            console.info(rangi.magenta(`Sync Successful!`));
        }
    }
});

How Can I Check connection for My Second database?

How to add Multi-mongos support or Multiple connections and Error handling for That?

mongoose.connect('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);

Body:
You may be looking for something like the following:

var localConnectStr = 'mongodb://localhost/test'
var mlabConnectStr = 'mongodb://<dbuser>:<dbpassword>@ds123456.mlab.com:25716/<dbname>'

var db = mongoose.createConnection(localConnectStr, { useMongoClient: true });
var mlabdb = mongoose.createConnection(mlabConnectStr, { useMongoClient: true });

You'll of course want to use your actual mlab uri and database user/pass. But this is how you would handle multiple connections. See createConnection here.

You could use the code you have, checking your local connection, to check mlab.

mlabdb.on('error', console.error);
mlabdb.once('open', () => {
    console.log(rangi.green('Connected To Mlab MongoDB'));
});


问:
eCharts 3 - zoom on geo map onclick
Does anyone know how to click on a country, then have it zoom in on that country/area in a 2D geo world map?

I am using the world 2D map that is provided in eCharts 3.  So my options look like this:

```<code>geo: {
      name: '2D Global Map',
      type: 'map',
      map: 'world',
      roam: true,
      label: {
          emphasis: {
              show: false
          }
      },
...
</code>```

Here is what I have thus far.  When I click it just zooms straight in to 4 rather than where I clicked.

```<code>myChart.on('click', function (params) {
  myChart.setOption({
    geo: {
        zoom: 4
      }
  });
});
    myChart.setOption(option);
</code>```

I have tried to find ways to zoom in on the x and y offsets, but that doesn't work.

I also tried to center the map first like this but you need the latitude and longitude of where to center the map inside the array.  The map uses JSON for the coordinates, and I can see them, but I can't get them to pull into the array.

```<code>myChart.on('click', function (params) {
  myChart.setOption({
    geo: {
        center: [(need to get lat/long of where clicked)],
        zoom: 4
      }
  });
});
    myChart.setOption(option);
</code>```

Any thoughts on ways to do this?

答:
Just in case anyone else is having this same problem, I was able to solve it in this manner:

```<code>myChart.on('click', function(params) {
            if (params.data) {
                myChart.setOption({
                    geo: {
                        center: params.data.value,
                        zoom: 6
                    }
                });
              } else {
                myChart.setOption({
                    geo: {
                        center: [0,0],
                        zoom: 1
                    }
                });
              }
            myChart.setOption(option);
        });
</code>```

It doesn't fully solve the problem where I wanted to be able to zoom in on any country, but it does solve the problem in the fact that I can zoom into a data point inside a country.

If anyone else has suggestions on how to do the country part please let me know.

Title: eCharts 3 - zoom on geo map onclick

Body:
Does anyone know how to click on a country, then have it zoom in on that country/area in a 2D geo world map?

I am using the world 2D map that is provided in eCharts 3.  So my options look like this:

geo: {
      name: '2D Global Map',
      type: 'map',
      map: 'world',
      roam: true,
      label: {
          emphasis: {
              show: false
          }
      },
...

Here is what I have thus far.  When I click it just zooms straight in to 4 rather than where I clicked.

myChart.on('click', function (params) {
  myChart.setOption({
    geo: {
        zoom: 4
      }
  });
});
    myChart.setOption(option);

I have tried to find ways to zoom in on the x and y offsets, but that doesn't work.

I also tried to center the map first like this but you need the latitude and longitude of where to center the map inside the array.  The map uses JSON for the coordinates, and I can see them, but I can't get them to pull into the array.

myChart.on('click', function (params) {
  myChart.setOption({
    geo: {
        center: [(need to get lat/long of where clicked)],
        zoom: 4
      }
  });
});
    myChart.setOption(option);

Any thoughts on ways to do this?

Body:
Just in case anyone else is having this same problem, I was able to solve it in this manner:

myChart.on('click', function(params) {
            if (params.data) {
                myChart.setOption({
                    geo: {
                        center: params.data.value,
                        zoom: 6
                    }
                });
              } else {
                myChart.setOption({
                    geo: {
                        center: [0,0],
                        zoom: 1
                    }
                });
              }
            myChart.setOption(option);
        });

It doesn't fully solve the problem where I wanted to be able to zoom in on any country, but it does solve the problem in the fact that I can zoom into a data point inside a country.

If anyone else has suggestions on how to do the country part please let me know.


问:
react-slick carousel cycle through slides with scroll-event - react js, javascript
Here is the carousel I am using: react-slick

I want to be able to scroll through each slide using the mouse scroll up or down event.

Scroll up to increment, scroll down to decrement.

Found an example online of exactly what I need - just unsure of how to convert this into a react solution.

Example: https://codepen.io/Grawl/pen/mMLQQb

What would be the best way to achieve this in a "react" component based approach?

Here is my react component:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import styles from './styles.css';
import ReactSVG from 'react-svg';
import Slider from 'react-slick';

import MobileSVG from '../../../assets/svg/icons/Mobile_Icon_Option2.svg';
import TabletSVG from '../../../assets/svg/icons/Tablet_Icon_Option2.svg';
import DesktopSVG from '../../../assets/svg/icons/Desktop_Icon_Option2.svg';

const deviceIcons = {'mobile': MobileSVG, 'tablet': TabletSVG, 'desktop': DesktopSVG};

import BackToTopButton from '../BackToTopButton';

export default class ProductComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };

    }

    render() {
        const {productData} = this.props

        //Slider settings
        const settings = {
            dots: true,
            infinite: false,
            speed: 500,
            fade: true,
            arrows: false,
            centerMode: true,
            slidesToShow: 1,
            slidesToScroll: 1
        }

        //Slider items
        const sliderItems = productData.map((obj, i) => {
            return (
                <div className="product-component row" key={i}>
                    <div className="product-component-image-wrap col-xs-12 col-sm-8">
                        <span className="product-heading">{obj.category}</span>
                        <div className="product-detail-wrap">
                            <img className="product-component-image" src={`${process.env.DB_URL}${obj.image}`} />
                            <ul className="list-device-support">
                                {obj.categoryDeviceSupport.map((obj, i) => {
                                    return (<li key={i}>
                                        <span className="svg-icon">
                                            <ReactSVG path={deviceIcons[obj.value]} />
                                        </span>
                                        <span className="product-label">{obj.label}</span>
                                    </li>)
                                })}
                            </ul>
                        </div>
                    </div>
                    <div className="product-component-info col-xs-12 col-sm-3">
                        <span className="align-bottom">{obj.title}</span>
                        <p className="align-bottom">{obj.categoryBrief}</p>
                    </div>
                </div>
            )
        });
        return (
            <div className="product-component-wrap col-xs-12">
                <Slider {...settings}>
                    {sliderItems}
                </Slider>
                <BackToTopButton scrollStepInPx="50" delayInMs="7" />
            </div>
        )
    }
}

ProductComponent.propTypes = {
    productData: PropTypes.array
};

ProductComponent.defaultProps = {
    productData: []
};
</code>```

答:
You'd wanna do something like this:

```<code>constructor(props){
    super(props);
    this.slide = this.slide.bind(this);
}
slide(y){
    y > 0 ? (
       this.slider.slickNext()
    ) : (
       this.slider.slickPrev()
    )
}
componentWillMount(){
    window.addEventListener('wheel', (e) => {
        this.slide(e.wheelDelta);
    })
}
render(){...
</code>```

and add a ref to your slider:

```<code><Slider ref={slider => this.slider = slider }>
</code>```

So when the y value of the wheel event is greater than 0 i.e. scroll up then show next slide, when scrolling down show previous.

Body:
Here is the carousel I am using: react-slick

I want to be able to scroll through each slide using the mouse scroll up or down event.

Scroll up to increment, scroll down to decrement.

Found an example online of exactly what I need - just unsure of how to convert this into a react solution.

Example: https://codepen.io/Grawl/pen/mMLQQb

What would be the best way to achieve this in a "react" component based approach?

Here is my react component:

import React from 'react';
import PropTypes from 'prop-types';
import styles from './styles.css';
import ReactSVG from 'react-svg';
import Slider from 'react-slick';

import MobileSVG from '../../../assets/svg/icons/Mobile_Icon_Option2.svg';
import TabletSVG from '../../../assets/svg/icons/Tablet_Icon_Option2.svg';
import DesktopSVG from '../../../assets/svg/icons/Desktop_Icon_Option2.svg';

const deviceIcons = {'mobile': MobileSVG, 'tablet': TabletSVG, 'desktop': DesktopSVG};

import BackToTopButton from '../BackToTopButton';

export default class ProductComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };

    }

    render() {
        const {productData} = this.props

        //Slider settings
        const settings = {
            dots: true,
            infinite: false,
            speed: 500,
            fade: true,
            arrows: false,
            centerMode: true,
            slidesToShow: 1,
            slidesToScroll: 1
        }

        //Slider items
        const sliderItems = productData.map((obj, i) => {
            return (

                        {obj.category}

                            <img className="product-component-image" src={`${process.env.DB_URL}${obj.image}`} />

                                {obj.categoryDeviceSupport.map((obj, i) => {
                                    return (

                                            <ReactSVG path={deviceIcons[obj.value]} />

                                        {obj.label}

)
                                })}

                        {obj.title}

{obj.categoryBrief}

            )
        });
        return (

                <Slider {...settings}>
                    {sliderItems}
                </Slider>
                <BackToTopButton scrollStepInPx="50" delayInMs="7" />

        )
    }
}

ProductComponent.propTypes = {
    productData: PropTypes.array
};

ProductComponent.defaultProps = {
    productData: []
};

Body:
You'd wanna do something like this:

constructor(props){
    super(props);
    this.slide = this.slide.bind(this);
}
slide(y){
    y > 0 ? (
       this.slider.slickNext()
    ) : (
       this.slider.slickPrev()
    )
}
componentWillMount(){
    window.addEventListener('wheel', (e) => {
        this.slide(e.wheelDelta);
    })
}
render(){...

and add a ref to your slider:

<Slider ref={slider => this.slider = slider }>

So when the y value of the wheel event is greater than 0 i.e. scroll up then show next slide, when scrolling down show previous.


问:
Trying to return "basenames" of filenames with and without version tags
I've been trying to write a regex that will return the base names of versioned files but also return the base name of a non-versioned file in the same list.

```<code>import re

file_list = [
    "ThisFile_v01.ext",
    "ThisFile_v02.ext",
    "ThatFile_v01.ext",
    "ThatFile_v02.ext",
    "NonVersionedFile.ext",
    "Non_VersionedFile.ext",
]

r = re.compile(r"^(?P<basename>.*(?!_v))(?P<version>_v\d+\.)?(?(version).*$|\..*$)")
for f in file_list:
    match = r.match(f)
    print(match.group('basename'))
</code>```

I'm trying to return a list like this:

```<code>ThisFile
ThisFile
ThatFile
ThatFile
NonVersionedFile
Non_VersionedFile
</code>```

I'm currently getting this:

```<code>ThisFile_v01
ThisFile_v02
ThatFile_v01
ThatFile_v02
NonVersionedFile
Non_VersionedFile
</code>```

I'm probably over thinking it but I've been thru a lot of iterations and I can't seem to figure this one out. Any help would be appreciated.

答:
your regex gives me a slight headache. I suppose there's a conflict between all the optional parts.

Why not just remove the v_xxx (optional) & extension using sub?

```<code>r = re.compile("(_v\d+)?(\..*)")
for f in file_list:
    print(r.sub("",f))
</code>```

this is simpler and gives me:

```<code>ThisFile
ThisFile
ThatFile
ThatFile
NonVersionedFile
Non_VersionedFile
</code>```

Body:
I've been trying to write a regex that will return the base names of versioned files but also return the base name of a non-versioned file in the same list.

import re

file_list = [
    "ThisFile_v01.ext",
    "ThisFile_v02.ext",
    "ThatFile_v01.ext",
    "ThatFile_v02.ext",
    "NonVersionedFile.ext",
    "Non_VersionedFile.ext",
]

r = re.compile(r"^(?P<basename>.*(?!_v))(?P<version>_v\d+\.)?(?(version).*$|\..*$)")
for f in file_list:
    match = r.match(f)
    print(match.group('basename'))

I'm trying to return a list like this:

ThisFile
ThisFile
ThatFile
ThatFile
NonVersionedFile
Non_VersionedFile

I'm currently getting this:

ThisFile_v01
ThisFile_v02
ThatFile_v01
ThatFile_v02
NonVersionedFile
Non_VersionedFile

I'm probably over thinking it but I've been thru a lot of iterations and I can't seem to figure this one out. Any help would be appreciated.

Body:
your regex gives me a slight headache. I suppose there's a conflict between all the optional parts.

Why not just remove the v_xxx (optional) & extension using sub?

r = re.compile("(_v\d+)?(\..*)")
for f in file_list:
    print(r.sub("",f))

this is simpler and gives me:

ThisFile
ThisFile
ThatFile
ThatFile
NonVersionedFile
Non_VersionedFile


问:
Modifying a variable in a module imported using from ... import *
Consider the following code:

```<code>#main.py
From toolsmodule import *
database = "foo"

#toolsmodule
database = "mydatabase"
</code>```

As it seems, this creates one variable in each module with different content. How can I modify the variable inside toolsmodule from main? The following does not work:

```<code>toolsmodule.database = "foo"
</code>```

答:
Pythons variable names are just labels on variables. When you import * all those labels are local and when you then set the database, you just replace the local variable, not the one in toolsmodule. Hence, do this:

toolsmodule.py:

```<code>database = "original"

def printdatabase():
   print "Database is", database
</code>```

And then run:

```<code>import toolsmodule
toolsmodule.database = "newdatabase"
toolsmodule.printdatabase()
</code>```

The output is

```<code>Database is newdatabase
</code>```

Note that if you then from ANOTHER module ALSO did an import * the change is not reflected.

In short: NEVER use from x import *. I don't know why all newbies persist in doing this despite all documentation I know of says that it's a bad idea.

Body:
Consider the following code:

#main.py
From toolsmodule import *
database = "foo"

#toolsmodule
database = "mydatabase"

As it seems, this creates one variable in each module with different content. How can I modify the variable inside toolsmodule from main? The following does not work:

toolsmodule.database = "foo"

Body:
Pythons variable names are just labels on variables. When you import * all those labels are local and when you then set the database, you just replace the local variable, not the one in toolsmodule. Hence, do this:

toolsmodule.py:

database = "original"

def printdatabase():
   print "Database is", database

And then run:

import toolsmodule
toolsmodule.database = "newdatabase"
toolsmodule.printdatabase()

The output is

Database is newdatabase

Note that if you then from ANOTHER module ALSO did an import * the change is not reflected.

In short: NEVER use from x import *. I don't know why all newbies persist in doing this despite all documentation I know of says that it's a bad idea.


问:
Using /update-cache requests to update AMP pages
Trying to use /update-cache/ requests to update some AMP pages, but i'm getting 403 errors.

Removed the opening part/protocol from the urls since i don't have the reputation to post this many links, but everything is https.

I have a page at: www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp

From the AMP cache: www-qponverzum-hu.cdn.ampproject.org/c/s/www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp

I've been following the documentation at developers.google.com/amp/cache/update-ping

If i make an /update-ping request, it seems to work fine, returns a 200 no content response, but due to the high amount of urls/pages we would like to use /update-cache since it allows for a higher request rate.

I've created a private and public RSA key and made the public key acessible at www.qponverzum.hu/.well-known/amphtml/apikey.pub

I've been trying to use the following php code to generate the update-cache url

```<code>$ampBaseUrl = "https://www-qponverzum-hu.cdn.ampproject.org";
$signatureUrl = '/update-cache/c/s/www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp?amp_action=flush&_ts='.time();

// opening the private key
$pkeyid = openssl_pkey_get_private("file://private-key.pem");

// generating the signature
openssl_sign($signatureUrl, $signature, $pkeyid)

// urlsafe base64 encoding
$signature = urlsafe_b64encode($signature);

// final url for updating
$ampUrl = $ampBaseUrl.$signatureUrl."&amp_url_signature=".$signature;
</code>```

The urlsafe_b64encode function I'm using:

```<code>function urlsafe_b64encode($string) {
    return str_replace(array('+','/','='),array('-','_',''), base64_encode($string));
}
</code>```

$ampUrl ends up looking like this: https://www-qponverzum-hu.cdn.ampproject.org/update-cache/c/s/www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp?amp_action=flush&amp_ts=1500362660&amp_url_signature=NjTCnmqUGpMY_CokGxchoczSOxnTLQvcQsX4fv2gIhW3H8hVw24mKCpmNoyV-9LND3OAR9ld80KeMH3lip863p_wBorIy1BAag7bRfvWcxsPrbqbox87VMrUWCEsry5epWxKYl2qNCT1GMv8SYAJ5WR0QZR0Qjvw5MXfZjohmbvrxJ7mWlc7fcvWoIXuO_q_yFkhi7A-fOZWm9sy8UDIlq-zNEPkVUwfqfWc_HbNHgvrk9Z6zZSNzB-dWAOT6QYAc1KeEVOIbvQxKkLkGMArTpydj5iLxz0aERvglKRl215Bqh6_jZu95T5yKv7X4R127ylpWYW2YDlTR9bgRE7Faw

If I make a simple GET request to this url(with a browser or curl) i get a 403 error('Your client does not have permission to get URL').

I've checked the webserver logs, but it doesn't seem like there're any requests made to the public keys url.

I think I'm missing something very obvious, so any feedback would be greatly appreciated.

答:
All the other answers have really helped - thanks. I'm adding a little here which may hopefully also help.

As @kul3r4 points out (I missed it first time round) the apikey.pub file needs to be served as plain text.  Here is the Nginx config rule for that;

```<code>    location /.well-known/amphtml/apikey.pub { ## serve amp public key as plain/text
         default_type text/plain;
    }
</code>```

If you are echoing out @Krzysztof Bukowski's answer to the screen, the fact that &amp is in the url parameters means my browser was stripping out the amp part of the amp_ts and amp_url_signature so be aware of that.

If you are struggling with the file paths and syntax of this;

```<code>    $pkeyid = openssl_pkey_get_private("file://amp-private-key.pem");
</code>```

Then just follow this answer here and put the contents of your private key in a variable -> Openssl and PHP

Body:
Trying to use /update-cache/ requests to update some AMP pages, but i'm getting 403 errors.

Removed the opening part/protocol from the urls since i don't have the reputation to post this many links, but everything is https.

I have a page at: www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp

From the AMP cache: www-qponverzum-hu.cdn.ampproject.org/c/s/www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp

I've been following the documentation at developers.google.com/amp/cache/update-ping

If i make an /update-ping request, it seems to work fine, returns a 200 no content response, but due to the high amount of urls/pages we would like to use /update-cache since it allows for a higher request rate.

I've created a private and public RSA key and made the public key acessible at www.qponverzum.hu/.well-known/amphtml/apikey.pub

I've been trying to use the following php code to generate the update-cache url

$ampBaseUrl = "https://www-qponverzum-hu.cdn.ampproject.org";
$signatureUrl = '/update-cache/c/s/www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp?amp_action=flush&_ts='.time();

// opening the private key
$pkeyid = openssl_pkey_get_private("file://private-key.pem");

// generating the signature
openssl_sign($signatureUrl, $signature, $pkeyid)

// urlsafe base64 encoding
$signature = urlsafe_b64encode($signature);

// final url for updating
$ampUrl = $ampBaseUrl.$signatureUrl."&amp_url_signature=".$signature;

The urlsafe_b64encode function I'm using:

function urlsafe_b64encode($string) {
    return str_replace(array('+','/','='),array('-','_',''), base64_encode($string));
}

$ampUrl ends up looking like this: <a href="https://www-qponverzum-hu.cdn.ampproject.org/update-cache/c/s/www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp?amp_action=flush&amp_ts=1500362660&amp_url_signature=NjTCnmqUGpMY_CokGxchoczSOxnTLQvcQsX4fv2gIhW3H8hVw24mKCpmNoyV-9LND3OAR9ld80KeMH3lip863p_wBorIy1BAag7bRfvWcxsPrbqbox87VMrUWCEsry5epWxKYl2qNCT1GMv8SYAJ5WR0QZR0Qjvw5MXfZjohmbvrxJ7mWlc7fcvWoIXuO_q_yFkhi7A-fOZWm9sy8UDIlq-zNEPkVUwfqfWc_HbNHgvrk9Z6zZSNzB-dWAOT6QYAc1KeEVOIbvQxKkLkGMArTpydj5iLxz0aERvglKRl215Bqh6_jZu95T5yKv7X4R127ylpWYW2YDlTR9bgRE7Faw" rel="nofollow noreferrer">https://www-qponverzum-hu.cdn.ampproject.org/update-cache/c/s/www.qponverzum.hu/ajanlat/budapest-elozd-meg-a-hajhullast-mikrokameras-hajdiagnosztika-hajhagyma-es-fejborvizsgalattal-tanacsadas-5000-ft-helyett-2500-ft-ert-biohajklinika-szepsegapolas-egeszseg/amp?amp_action=flush&amp_ts=1500362660&amp_url_signature=NjTCnmqUGpMY_CokGxchoczSOxnTLQvcQsX4fv2gIhW3H8hVw24mKCpmNoyV-9LND3OAR9ld80KeMH3lip863p_wBorIy1BAag7bRfvWcxsPrbqbox87VMrUWCEsry5epWxKYl2qNCT1GMv8SYAJ5WR0QZR0Qjvw5MXfZjohmbvrxJ7mWlc7fcvWoIXuO_q_yFkhi7A-fOZWm9sy8UDIlq-zNEPkVUwfqfWc_HbNHgvrk9Z6zZSNzB-dWAOT6QYAc1KeEVOIbvQxKkLkGMArTpydj5iLxz0aERvglKRl215Bqh6_jZu95T5yKv7X4R127ylpWYW2YDlTR9bgRE7Faw

If I make a simple GET request to this url(with a browser or curl) i get a 403 error('Your client does not have permission to get URL').

I've checked the webserver logs, but it doesn't seem like there're any requests made to the public keys url.

I think I'm missing something very obvious, so any feedback would be greatly appreciated.

Body:
All the other answers have really helped - thanks. I'm adding a little here which may hopefully also help.

As @kul3r4 points out (I missed it first time round) the apikey.pub file needs to be served as plain text.  Here is the Nginx config rule for that;

    location /.well-known/amphtml/apikey.pub { ## serve amp public key as plain/text
         default_type text/plain;
    }

If you are echoing out @Krzysztof Bukowski's answer to the screen, the fact that &amp is in the url parameters means my browser was stripping out the amp part of the amp_ts and amp_url_signature so be aware of that.

If you are struggling with the file paths and syntax of this;

    $pkeyid = openssl_pkey_get_private("file://amp-private-key.pem");

Then just follow this answer here and put the contents of your private key in a variable -> Openssl and PHP