问:
C++ map customize comparator
I defined a map to count the number of strings while sorting the strings by their length:

```<code>struct cmp {
    bool operator()(const string& a, const string& b) {
        return a.size() > b.size();
    }
};

int main() {
    map<string, int, cmp> mp;
    mp["aaa"] = 1;
    mp["bbb"] = 2;
    cout << mp["aaa"];
}
</code>```

I'm confused as the output is 2. How should I achieve my goal?

答:
If you want to allow strings of identical size in your map but do not care about their relative order, then std::multimap is an alternative solution:

```<code>#include <map>
#include <iostream>
#include <string>

struct cmp {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.size() > b.size();
    }
};

int main() {
    std::multimap<std::string, int, cmp> mp;
    mp.emplace("eee", 5);
    mp.emplace("aaa", 1);
    mp.emplace("bbb", 2);
    mp.emplace("cccc", 3);
    mp.emplace("dd", 4);
    auto const elements_of_size_3 = mp.equal_range("aaa");
    for (auto iter = elements_of_size_3.first; iter != elements_of_size_3.second; ++iter)
    {
        std::cout << iter->first << " -> " << iter->second << '\n';
    }
}
</code>```

Output:

```<code>eee -> 5
aaa -> 1
bbb -> 2
</code>```

From std::multimap<std::string, int, cmp>'s point of view, "eee", "aaa" and "bbb" are all completely equal to each other, and std::multimap allows different keys to be equal. Their relative order is actually guaranteed to be the order of insertion since C++11.

Title: C++ map customize comparator

Body:
I defined a map to count the number of strings while sorting the strings by their length:

struct cmp {
    bool operator()(const string& a, const string& b) {
        return a.size() > b.size();
    }
};

int main() {
    map<string, int, cmp> mp;
    mp["aaa"] = 1;
    mp["bbb"] = 2;
    cout << mp["aaa"];
}

I'm confused as the output is 2. How should I achieve my goal?

Body:
If you want to allow strings of identical size in your map but do not care about their relative order, then std::multimap is an alternative solution:

#include <map>
#include <iostream>
#include <string>

struct cmp {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.size() > b.size();
    }
};

int main() {
    std::multimap<std::string, int, cmp> mp;
    mp.emplace("eee", 5);
    mp.emplace("aaa", 1);
    mp.emplace("bbb", 2);
    mp.emplace("cccc", 3);
    mp.emplace("dd", 4);
    auto const elements_of_size_3 = mp.equal_range("aaa");
    for (auto iter = elements_of_size_3.first; iter != elements_of_size_3.second; ++iter)
    {
        std::cout << iter->first << " -> " << iter->second << '\n';
    }
}

Output:

eee -> 5
aaa -> 1
bbb -> 2

From std::multimap<std::string, int, cmp>'s point of view, "eee", "aaa" and "bbb" are all completely equal to each other, and std::multimap allows different keys to be equal. Their relative order is actually guaranteed to be the order of insertion since C++11.


来源: stackexchange

问:
Make XMLWriter to append data to an existing file
Is there any way to make XMLWriter to append data to an existing file?</p>

答: You can use openMemory to create an XMLWriter that only writes to memory, then outputMemory to get the data that the XMLWriter has collected, and then append it to a file with normal fopen, fwrite, fclose calls.

ContentLicense: CC BY-SA 2.5


问:
How to get the first element of a string split with space
I am trying to get the name of the user after su in a bash script. I used the following code:

```<code>user=`who am i`
#user <- "user4035     pts/0        2017-04-02 05:13 (my-hostname)"
userarray=($user)
#userarray <- ["user4035", "pts/0", "2017-04-02 05:13", "(my-hostname)"]
user=${userarray[0]}
#outputs "user4035"
echo $user
</code>```

It works correctly, but is it possible to achieve the same result with less number of commands?

答:
Use bash parameter-expansion without needing to use arrays,

```<code>myUser=$(who am i)
printf "%s\n" "${myUser%% *}"
user4035
</code>```

(or) just use a simple awk, command,

```<code>who am i | awk '{print $1}'
user4035
</code>```

i.e. in  a variable do,

```<code>myUser=$(who am i | awk '{print $1}')
printf "%s\n" "$myUser"
</code>```

(or) if your script is run with sudo privileges, you can use this bash environment-variable,

```<code>printf "%s\n" "${SUDO_USER}"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get the name of the user after su in a bash script. I used the following code:

user=`who am i`
#user <- "user4035     pts/0        2017-04-02 05:13 (my-hostname)"
userarray=($user)
#userarray <- ["user4035", "pts/0", "2017-04-02 05:13", "(my-hostname)"]
user=${userarray[0]}
#outputs "user4035"
echo $user

It works correctly, but is it possible to achieve the same result with less number of commands?

Body:
Use bash parameter-expansion without needing to use arrays,

myUser=$(who am i)
printf "%s\n" "${myUser%% *}"
user4035

(or) just use a simple awk, command,

who am i | awk '{print $1}'
user4035

i.e. in  a variable do,

myUser=$(who am i | awk '{print $1}')
printf "%s\n" "$myUser"

(or) if your script is run with sudo privileges, you can use this bash environment-variable,

printf "%s\n" "${SUDO_USER}"

ContentLicense: CC BY-SA 4.0


问:
java.lang.ClassNotFoundException: HttpServletRequest
I just got tomcat 7.0.27. I have kept the time to start tomcat 45sec. Also it was running fine with older version on tomcat.
but running it I get the following error :

```<code>SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/VotingApp]]
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
    at java.util.concurrent.FutureTask.get(FutureTask.java:83)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1128)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:680)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/VotingApp]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 7 more
Caused by: java.lang.NoClassDefFoundError: HttpServletRequest
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
    at java.lang.Class.getDeclaredMethods(Class.java:1791)
    at org.apache.catalina.startup.WebAnnotationSet.getDeclaredMethods(WebAnnotationSet.java:470)
    at org.apache.catalina.startup.WebAnnotationSet.loadMethodsAnnotation(WebAnnotationSet.java:275)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:137)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:66)
    at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:381)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:858)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:345)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: java.lang.ClassNotFoundException: HttpServletRequest
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
    ... 21 more
May 11, 2012 10:09:21 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
    at java.util.concurrent.FutureTask.get(FutureTask.java:83)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1128)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:675)
    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:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:450)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:680)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1136)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
May 11, 2012 10:09:21 AM org.apache.catalina.startup.Catalina start
SEVERE: Catalina.start:
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:675)
    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:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:450)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1136)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more
May 11, 2012 10:09:21 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 561 ms
</code>```

How do I resolve the error. I have looked into some similar posts but did not find it useful.

答:
This one is for all the Maven users out there, using their dependencies for the classpath and not copying them into /WEB-INF/lib:
just add this (which copies the dependency libraries) before </plugin>

```<code><plugin>
    <artifactId>maven-dependency-plugin</artifactId>
        <executions>
            <execution>
                <phase>process-sources</phase>
                <goals>
                    <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                    <outputDirectory>WebContent/WEB-INF/lib</outputDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>
</code>```

Body:
I just got tomcat 7.0.27. I have kept the time to start tomcat 45sec. Also it was running fine with older version on tomcat.
but running it I get the following error :

SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/VotingApp]]
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
    at java.util.concurrent.FutureTask.get(FutureTask.java:83)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1128)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:680)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/VotingApp]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 7 more
Caused by: java.lang.NoClassDefFoundError: HttpServletRequest
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
    at java.lang.Class.getDeclaredMethods(Class.java:1791)
    at org.apache.catalina.startup.WebAnnotationSet.getDeclaredMethods(WebAnnotationSet.java:470)
    at org.apache.catalina.startup.WebAnnotationSet.loadMethodsAnnotation(WebAnnotationSet.java:275)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:137)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:66)
    at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:381)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:858)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:345)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: java.lang.ClassNotFoundException: HttpServletRequest
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
    ... 21 more
May 11, 2012 10:09:21 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
    at java.util.concurrent.FutureTask.get(FutureTask.java:83)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1128)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:675)
    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:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:450)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:680)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1136)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:782)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
May 11, 2012 10:09:21 AM org.apache.catalina.startup.Catalina start
SEVERE: Catalina.start:
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:675)
    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:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:450)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1136)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more
May 11, 2012 10:09:21 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 561 ms

How do I resolve the error. I have looked into some similar posts but did not find it useful.

Body:
This one is for all the Maven users out there, using their dependencies for the classpath and not copying them into /WEB-INF/lib:
just add this (which copies the dependency libraries) before </plugin>

<plugin>
    <artifactId>maven-dependency-plugin</artifactId>
        <executions>
            <execution>
                <phase>process-sources</phase>
                <goals>
                    <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                    <outputDirectory>WebContent/WEB-INF/lib</outputDirectory>
                </configuration>
            </execution>
        </executions>
    </plugin>


问:
angular 1 - routing and api
Trying to write a simple SPA. Using MEAN.

API through node are all working.

Have set up routes in my main controller

```<code>    // create the module and name it
var boardingApp = angular.module('boardingApp', ['ngRoute']);

boardingApp.config(function($routeProvider) {

    $routeProvider

        // route for the home page that lists all tenants
        .when('/', {
            templateUrl : 'js/templates/tenants.html',
            controller  : 'tenantsController'
        })
        // route for a specifc tenant
        .when('/tenant/:id', {
            templateUrl : 'js/templates/tenant.html',
            controller  : 'tenantController'
        })

});

boardingApp.controller('tenantsController', ['$scope','$http','$log', function($scope, $http,$log) {

        $http.get(URL + "/api/tenants")
            .then(function(response){ $scope.details = response.data; });

}]);

 boardingApp.controller('tenantController', ['$scope','$http','$location','$log', function($scope, $http, $location, $log) {

        if ( $location.search().hasOwnProperty( 'id' ) ) {
            var myid = $location.search()['id'];
            console.log(myid)

            myURL = URL + "/api/tenants/"+myid
            console.log(myURL)

            $http.get(myURL)
            .then(function(response){ $scope.tenant = response.data; });
            console.log($scope.tenant)
        }

}]);

 boardingApp.controller('readmeController', function($scope, $http) {

        $scope.message = "This is the message"

});
</code>```

the root route work finds calls the API generates a table. All good

then main part of that template is this

```<code>  <tbody id="tenantsTable">
                      <tr ng:repeat = "tenant in details | filter :  true: tenant.activeTenant ">
                        <td><a ng-href = "#/tenant.html?id={{tenant._id}}" >View</td>
                        <td>{{tenant.roomNumber}} </td>
                        <td>{{tenant.firstName}} </td>
                        <td>{{tenant.lastName}} </td>
                        <td>{{tenant.paymentFrequency}} </td>
                        <td>${{tenant.rentAmount}} </td>
                        <td> {{tenant.leaseEnd | date: 'dd MMM yyyy'}} </td>
                       </tr>

                      </tbody>
</code>```

I want to click on the "View" link and pull data from DB for each tenant through and API call that just needs the Tenant id - standard stuff.

My controller is not picking up the request and when i click on the link on the Tennants page it just ends up blank.

what am i missing here? the api call s are all good and working fine

答:
You anchor tab is incorrect, it should be in correct pattern like "#/tenant/{{tenant._id}}"

```<code>ng-href="#/tenant/{{tenant._id}}"
</code>```

Additionally you should retrieve a route parameter inside tenantController by using $routeParams.id API instead of $location.search() which would be look for query parameter.

Title: angular 1 - routing and api

Body:
Trying to write a simple SPA. Using MEAN.

API through node are all working.

Have set up routes in my main controller

    // create the module and name it
var boardingApp = angular.module('boardingApp', ['ngRoute']);

boardingApp.config(function($routeProvider) {

    $routeProvider

        // route for the home page that lists all tenants
        .when('/', {
            templateUrl : 'js/templates/tenants.html',
            controller  : 'tenantsController'
        })
        // route for a specifc tenant
        .when('/tenant/:id', {
            templateUrl : 'js/templates/tenant.html',
            controller  : 'tenantController'
        })

});

boardingApp.controller('tenantsController', ['$scope','$http','$log', function($scope, $http,$log) {

        $http.get(URL + "/api/tenants")
            .then(function(response){ $scope.details = response.data; });

}]);

 boardingApp.controller('tenantController', ['$scope','$http','$location','$log', function($scope, $http, $location, $log) {

        if ( $location.search().hasOwnProperty( 'id' ) ) {
            var myid = $location.search()['id'];
            console.log(myid)

            myURL = URL + "/api/tenants/"+myid
            console.log(myURL)

            $http.get(myURL)
            .then(function(response){ $scope.tenant = response.data; });
            console.log($scope.tenant)
        }

}]);

 boardingApp.controller('readmeController', function($scope, $http) {

        $scope.message = "This is the message"

});

the root route work finds calls the API generates a table. All good

then main part of that template is this

                        View
                        {{tenant.roomNumber}}
                        {{tenant.firstName}}
                        {{tenant.lastName}}
                        {{tenant.paymentFrequency}}
                        ${{tenant.rentAmount}}
                         {{tenant.leaseEnd | date: 'dd MMM yyyy'}}

I want to click on the "View" link and pull data from DB for each tenant through and API call that just needs the Tenant id - standard stuff.

My controller is not picking up the request and when i click on the link on the Tennants page it just ends up blank.

what am i missing here? the api call s are all good and working fine

Body:
You anchor tab is incorrect, it should be in correct pattern like "#/tenant/{{tenant._id}}"

ng-href="#/tenant/{{tenant._id}}"

Additionally you should retrieve a route parameter inside tenantController by using $routeParams.id API instead of $location.search() which would be look for query parameter.


问:
Verify empty field Selenium C#
I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:

```<code>var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
                Console.WriteLine("This field can not be empty");
            }
</code>```

Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?

Thank you in advance!

答:
I'm not sure that this way will work in your case. Code:

```<code>var firstName = driver.FindElement(By.Id("name_3_firstname"));
</code>```

will return to You IWebElement object. First you should try to get text of this element. Try something like firstName.Text  or firstName.getAttribute("value");. When u will have this you will able to check
:

```<code>var text = firstName.getAttribute("value");
if(string.IsNullOrEmpty(text)){ // do something }
if(text.length == 20) {// do something}
</code>```

Title: Verify empty field Selenium C#

Body:
I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:

var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
                Console.WriteLine("This field can not be empty");
            }

Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?

Thank you in advance!

Body:
I'm not sure that this way will work in your case. Code:

var firstName = driver.FindElement(By.Id("name_3_firstname"));

will return to You IWebElement object. First you should try to get text of this element. Try something like firstName.Text  or firstName.getAttribute("value");. When u will have this you will able to check
:

var text = firstName.getAttribute("value");
if(string.IsNullOrEmpty(text)){ // do something }
if(text.length == 20) {// do something}


问:
Creating a syntax tree with pushdown automation?
If I were to create a pushdown automation that accepts a state(name) and those states accept transitions(input, pop, push, nextState). How does all this help me construct a parse tree?

I mean a pushdown automata is great for checking if something is in the language, like if a sequence of tokens or whatever is in the correct order... but syntax trees?

I mean consider the following example:

```<code>Foo {
 Woo {
  Hello World
 }
}
</code>```

The pda can only remember the top item in a stack and the current input. How am I supposed to construct the tree? Should I combine PDA with recursion?

答: Broadly, each item on the stack contains a list of syntax subtrees. When you push a new item, its list starts off empty. When you shift (consume) a token, you add it to this list. When you pop, you take all the subtrees in the list of the top item, set them as children of the new node, and add this new subtree to the list of the new top of the item stack. Eventually, when you pop the last item off stack, you'll end up with a single subtree, which will be the entire syntax tree.</p>

Body:
If I were to create a pushdown automation that accepts a state(name) and those states accept transitions(input, pop, push, nextState). How does all this help me construct a parse tree?

I mean a pushdown automata is great for checking if something is in the language, like if a sequence of tokens or whatever is in the correct order... but syntax trees?

I mean consider the following example:

Foo {
 Woo {
  Hello World
 }
}

The pda can only remember the top item in a stack and the current input. How am I supposed to construct the tree? Should I combine PDA with recursion?


问:
Celery: Start Worker Automatically (on boot)
I have tasks (for Celery) defined in /var/tasks/tasks.py.

I have a virtualenv at /var/tasks/venv which should be used to run /var/tasks/tasks.py.

I can manually start a worker to process tasks like this:

```<code>cd /var/tasks
. venv/bin/activate
celery worker -A tasks -Q queue_1
</code>```

Now, I want to daemonize this.

I copied the init.d script from GitHub and am using the following config file in /etc/default/celeryd:

```<code># name(s) of nodes to start
CELERYD_NODES="worker1"

# absolute or relative path to celery binary
CELERY_BIN="/var/tasks/venv/bin/celery"

# app instance
CELERY_APP="tasks"

# change to directory on upstart
CELERYD_CHDIR="/var/tasks"

# options
CELERYD_OPTS="-Q queue_1 --concurrency=8"

# %N will be replaced with the first part of the nodename.
CELERYD_LOG_FILE="/var/log/celery/%N.log"
CELERYD_PID_FILE="/var/run/celery/%N.pid"

# unprivileged user/group
CELERYD_USER="celery"
CELERYD_GROUP="celery"

# create pid and log directories, if missing
CELERY_CREATE_DIRS=1
</code>```

When I start the service (via the init.d script), it says:

```<code>celery init v10.1.
Using config script: /etc/default/celeryd
</code>```

But, it does not process any tasks from the queue, nor is there anything in the log file.

What am I doing wrong?

答:
Supervisor might be a good option but if you want to use Celery Init.d Script will recommend you to copy it from their Github Source.

```<code>sudo vim /etc/init.d/celeryd
</code>```

Copy the code from https://github.com/celery/celery/blob/master/extra/generic-init.d/celeryd in to the file.  See daemonizing tutorial for details.

```<code>sudo chmod 755 /etc/init.d/celeryd
sudo chown root:root /etc/init.d/celeryd
sudo nano /etc/default/celeryd
</code>```

Copy paste the below config and change accordingly

```<code>#Where your Celery is present
CELERY_BIN="/home/shivam/Desktop/deploy/bin/celery"

# App instance to use
CELERY_APP="app.celery"

# Where to chdir at start
CELERYD_CHDIR="/home/shivam/Desktop/Project/demo/"

# Extra command-line arguments to the worker
CELERYD_OPTS="--time-limit=300 --concurrency=8"

# %n will be replaced with the first part of the nodename.
CELERYD_LOG_FILE="/var/log/celery/%n%I.log"
CELERYD_PID_FILE="/var/run/celery/%n.pid"

# Workers should run as an unprivileged user.
# You need to create this user manually (or you can choose
# A user/group combination that already exists (e.g., nobody).
CELERYD_USER="shivam"
CELERYD_GROUP="shivam"

# If enabled pid and log directories will be created if missing,
# and owned by the userid/group configured.
CELERY_CREATE_DIRS=1
export SECRET_KEY="foobar"
</code>```

Save and exit

```<code>sudo /etc/init.d/celeryd start
sudo /etc/init.d/celeryd status
</code>```

This will auto start Celery on Boot

```<code>sudo update-rc.d celeryd defaults
</code>```

Body:
I have tasks (for Celery) defined in /var/tasks/tasks.py.

I have a virtualenv at /var/tasks/venv which should be used to run /var/tasks/tasks.py.

I can manually start a worker to process tasks like this:

cd /var/tasks
. venv/bin/activate
celery worker -A tasks -Q queue_1

Now, I want to daemonize this.

I copied the init.d script from GitHub and am using the following config file in /etc/default/celeryd:

# name(s) of nodes to start
CELERYD_NODES="worker1"

# absolute or relative path to celery binary
CELERY_BIN="/var/tasks/venv/bin/celery"

# app instance
CELERY_APP="tasks"

# change to directory on upstart
CELERYD_CHDIR="/var/tasks"

# options
CELERYD_OPTS="-Q queue_1 --concurrency=8"

# %N will be replaced with the first part of the nodename.
CELERYD_LOG_FILE="/var/log/celery/%N.log"
CELERYD_PID_FILE="/var/run/celery/%N.pid"

# unprivileged user/group
CELERYD_USER="celery"
CELERYD_GROUP="celery"

# create pid and log directories, if missing
CELERY_CREATE_DIRS=1

When I start the service (via the init.d script), it says:

celery init v10.1.
Using config script: /etc/default/celeryd

But, it does not process any tasks from the queue, nor is there anything in the log file.

What am I doing wrong?

Body:
Supervisor might be a good option but if you want to use Celery Init.d Script will recommend you to copy it from their Github Source.

sudo vim /etc/init.d/celeryd

Copy the code from https://github.com/celery/celery/blob/master/extra/generic-init.d/celeryd in to the file.  See daemonizing tutorial for details.

sudo chmod 755 /etc/init.d/celeryd
sudo chown root:root /etc/init.d/celeryd
sudo nano /etc/default/celeryd

Copy paste the below config and change accordingly

#Where your Celery is present
CELERY_BIN="/home/shivam/Desktop/deploy/bin/celery"

# App instance to use
CELERY_APP="app.celery"

# Where to chdir at start
CELERYD_CHDIR="/home/shivam/Desktop/Project/demo/"

# Extra command-line arguments to the worker
CELERYD_OPTS="--time-limit=300 --concurrency=8"

# %n will be replaced with the first part of the nodename.
CELERYD_LOG_FILE="/var/log/celery/%n%I.log"
CELERYD_PID_FILE="/var/run/celery/%n.pid"

# Workers should run as an unprivileged user.
# You need to create this user manually (or you can choose
# A user/group combination that already exists (e.g., nobody).
CELERYD_USER="shivam"
CELERYD_GROUP="shivam"

# If enabled pid and log directories will be created if missing,
# and owned by the userid/group configured.
CELERY_CREATE_DIRS=1
export SECRET_KEY="foobar"

Save and exit

sudo /etc/init.d/celeryd start
sudo /etc/init.d/celeryd status

This will auto start Celery on Boot

sudo update-rc.d celeryd defaults


问:
global function in Ionic 2 / Angular 2
How can I setup a global function that can be accessed throughout all views?

In app.component.ts I added a simple method

```<code>  openShare() {console.log("button clicked")}
</code>```

and then in my nav I have

```<code>  <button ion-button right (click)="openShare()">
  <ion-icon name="md-share"></ion-icon>
</button>
</code>```

When I try to access this from any page I get the following.

```<code>self.context.openShare is not a function
</code>```

It does however execute fine if I put it directly in the constructor (e.g this.openShare(); ), but when calling from any page using a (click) function it just doesn't work.

Is app.component.ts not global? I thought this is where I would place it, but maybe I am missing something.

Basically its a function for a simple button on the nav, I need it to be global though since its used on every page.

Any help would be appreciated, still figuring Ionic 2 out.

答:
You can use Directive.

Try as follows.

Put the following code in separate directive file. (social-sharing.directive.ts);

```<code>import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[socialSharing]'
})
export class SocialSharing {

  constructor() { }

  @HostListener('click') onClick() {
    // Your click functionality
  }
}
</code>```

Import it into app.module.ts and than add to declarations.

In HTML, just add attribute to any element which is the selector in your directive file.

```<code><button ion-button right socialSharing>
 <ion-icon name="md-share"></ion-icon>
</button>
</code>```

Additional Info:

Passing values from component to directive.

home.html

```<code>  <button ion-button right [socialSharing]="property">
    <ion-icon name="md-share"></ion-icon>
  </button>
</code>```

home.component.ts

```<code> export class HomePage {

   property: string = 'some url';
    constructor() {}
 }
</code>```

social-sharing.directive.ts

Import Input along with others from @angular/core.

```<code>import { Directive, Input, HostListener } from '@angular/core';

@Directive({
   selector: '[socialSharing]'
})

export class SocialSharing {
  @Input('socialSharing') str: string;

  constructor() {}

  @HostListener('click') onClick() {
     console.log(this.str);
  }
};

  ngAfterInit() {
     console.log(this.str);
  };
}
</code>```

Using Element in Directive:

social-sharing.directive.ts

Import ElementRef along with others from @angular/core

```<code> import { Directive, ElementRef, HostListener } from '@angular/core';

 @Directive({
   selector: '[socialSharing]'
 })

 export class SocialSharing {

   // Add ElementRef to constructor

   constructor(el: ElementRef) {};

   ngOnInit() {
      let elRef = this.el.nativeElement;
      console.log(elRef.innerHTML);
   };
 }
</code>```

Title: global function in Ionic 2 / Angular 2

Body:
How can I setup a global function that can be accessed throughout all views?

In app.component.ts I added a simple method

  openShare() {console.log("button clicked")}

and then in my nav I have

  <button ion-button right (click)="openShare()">
  <ion-icon name="md-share"></ion-icon>
</button>

When I try to access this from any page I get the following.

self.context.openShare is not a function

It does however execute fine if I put it directly in the constructor (e.g this.openShare(); ), but when calling from any page using a (click) function it just doesn't work.

Is app.component.ts not global? I thought this is where I would place it, but maybe I am missing something.

Basically its a function for a simple button on the nav, I need it to be global though since its used on every page.

Any help would be appreciated, still figuring Ionic 2 out.

Body:
You can use Directive.

Try as follows.

Put the following code in separate directive file. (social-sharing.directive.ts);

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[socialSharing]'
})
export class SocialSharing {

  constructor() { }

  @HostListener('click') onClick() {
    // Your click functionality
  }
}

Import it into app.module.ts and than add to declarations.

In HTML, just add attribute to any element which is the selector in your directive file.

<button ion-button right socialSharing>
 <ion-icon name="md-share"></ion-icon>
</button>

Additional Info:

Passing values from component to directive.

home.html

  <button ion-button right [socialSharing]="property">
    <ion-icon name="md-share"></ion-icon>
  </button>

home.component.ts

 export class HomePage {

   property: string = 'some url';
    constructor() {}
 }

social-sharing.directive.ts

Import Input along with others from @angular/core.

import { Directive, Input, HostListener } from '@angular/core';

@Directive({
   selector: '[socialSharing]'
})

export class SocialSharing {
  @Input('socialSharing') str: string;

  constructor() {}

  @HostListener('click') onClick() {
     console.log(this.str);
  }
};

  ngAfterInit() {
     console.log(this.str);
  };
}

Using Element in Directive:

social-sharing.directive.ts

Import ElementRef along with others from @angular/core

 import { Directive, ElementRef, HostListener } from '@angular/core';

 @Directive({
   selector: '[socialSharing]'
 })

 export class SocialSharing {

   // Add ElementRef to constructor

   constructor(el: ElementRef) {};

   ngOnInit() {
      let elRef = this.el.nativeElement;
      console.log(elRef.innerHTML);
   };
 }


问:
How to write string array to a HDF5 dataset with Fortran API?
A string array is defined using fortran language:

```<code>character(len = 20), dimension(5) :: strings = (/"hello", "world", "Hello", "HDF5", "fortran"/)
</code>```

Now I want to save this array into a dataset using h5ltmake_dataset_string_f() interface illustrated by HDF5 API reference documentation

Fortran90 Interface: h5ltmake_dataset_string_f

subroutine h5ltmake_dataset_string_f(loc_id,dset_name,buf,errcode )

```<code>    implicit none
</code>```

integer(HID_T), intent(IN) :: loc_id           ! file or group identifier

character(LEN=*), intent(IN) :: dset_name      ! name of the dataset

character(LEN=*), intent(IN), dimension(:) :: buf  ! data buffer

integer :: errcode                             ! error code

end subroutine h5ltmake_dataset_string_f

My calling code below

```<code>h5ltmake_dataset_string_f(group_id, dset_name, strings, error)
</code>```

and group_id, dset_name and error have been defined before subroutine call.

But when I compile and build this code, compile error occurs says

h5ltmake_dataset_string_f(): the actual arguments and dummy arguments have been violated!

So how to write the strings into one dataset?

答:
Although the issue was opened several years ago, here goes a solution to write an array of strings ("hello", "world", "Hello", "HDF5", "fortran") into an HDF5 dataset in Fortran using HDFql (http://www.hdfql.com). Posting this in case others find themselves struggling with HDF5 low-level details when performing this type of operation:

PROGRAM Example

    ! use HDFql module (make sure it can be found by the Fortran compiler)
    USE HDFql

    ! declare variables
    CHARACTER(LEN = 20), DIMENSION(5) :: strings = [CHARACTER(LEN = 20) :: "hello", "world", "Hello", "HDF5", "fortran"]
    CHARACTER :: variable_number
    INTEGER :: state

    ! create an HDF file named "example.h5" and use (i.e. open) it
    state = hdfql_execute("CREATE AND USE FILE example.h5")

    ! create a dataset named "my_dataset" of type char (size 20) of one dimension (size 5)
    state = hdfql_execute("CREATE DATASET my_dataset AS CHAR(5, 20)");

    ! register variable "strings" for subsequent use (by HDFql)
    state = hdfql_variable_transient_register(strings)
    WRITE(variable_number, "(I0)") state

    ! insert (i.e. write) content of variable "strings" into dataset "my_dataset"
    state = hdfql_execute("INSERT INTO my_dataset VALUES FROM MEMORY " // variable_number)

END PROGRAM
```

Body:
A string array is defined using fortran language:

character(len = 20), dimension(5) :: strings = (/"hello", "world", "Hello", "HDF5", "fortran"/)

Now I want to save this array into a dataset using h5ltmake_dataset_string_f() interface illustrated by HDF5 API reference documentation

Fortran90 Interface: h5ltmake_dataset_string_f

subroutine h5ltmake_dataset_string_f(loc_id,dset_name,buf,errcode )

    implicit none

integer(HID_T), intent(IN) :: loc_id           ! file or group identifier

character(LEN=*), intent(IN) :: dset_name      ! name of the dataset

character(LEN=*), intent(IN), dimension(:) :: buf  ! data buffer

integer :: errcode                             ! error code

end subroutine h5ltmake_dataset_string_f

My calling code below

h5ltmake_dataset_string_f(group_id, dset_name, strings, error)

and group_id, dset_name and error have been defined before subroutine call.

But when I compile and build this code, compile error occurs says

h5ltmake_dataset_string_f(): the actual arguments and dummy arguments have been violated!

So how to write the strings into one dataset?


问:
Looping javascript function on time intervals
I a script, in JavaScript, that makes a typewriting effect. I've tried to loop it, so that it executes in a loop after 10 seconds from the end of execution. In other words there is a typewriting effect and when the text is written after ten second code will execute once again. I've tried with setTimeout(), however it did not work.

Thanks for help in advance.

```<code>function setupTypewriter(t) {
  var HTML = t.innerHTML;

  t.innerHTML = "";

  var cursorPosition = 0,
      tag = "",
      writingTag = false,
      tagOpen = false,
      typeSpeed = 50,
      tempTypeSpeed = 0;

  var type = function() {

    if (writingTag === true) {
      tag += HTML[cursorPosition];
    }

    if (HTML[cursorPosition] === "<") {
      tempTypeSpeed = 0;
      if (tagOpen) {
        tagOpen = false;
        writingTag = true;
      } else {
        tag = "";
        tagOpen = true;
        writingTag = true;
        tag += HTML[cursorPosition];
      }
    }
    if (!writingTag && tagOpen) {
      tag.innerHTML += HTML[cursorPosition];
    }
    if (!writingTag && !tagOpen) {
      if (HTML[cursorPosition] === " ") {
        tempTypeSpeed = 0;
      }
      else {
        tempTypeSpeed = (Math.random() * typeSpeed) + 50;
      }
      t.innerHTML += HTML[cursorPosition];
    }
    if (writingTag === true && HTML[cursorPosition] === ">") {
      tempTypeSpeed = (Math.random() * typeSpeed) + 50;
      writingTag = false;
      if (tagOpen) {
        var newSpan = document.createElement("span");
        t.appendChild(newSpan);
        newSpan.innerHTML = tag;
        tag = newSpan.firstChild;
      }
    }

    cursorPosition += 1;
    if (cursorPosition < HTML.length - 1) {
      setTimeout(type, tempTypeSpeed);
    }

  };

  return {
    type: type
  };
}

var typer = document.getElementById('typewriter');

typewriter = setupTypewriter(typewriter);

typewriter.type();
</code>```

答:
```<code>typewriter = setupTypewriter(typewriter);
</code>```

You pass typewriter variable to setupTypewriter, but it doesn't exist yet. Here you want to use

```<code>typewriter = setupTypewriter(typer);
</code>```

BTW, I can't understand how you print tags. You print <, d, i, v, > with zero delay, but the parser still may break. You should print the tag at once:

 and then append div's contents to it.

Body:
I a script, in JavaScript, that makes a typewriting effect. I've tried to loop it, so that it executes in a loop after 10 seconds from the end of execution. In other words there is a typewriting effect and when the text is written after ten second code will execute once again. I've tried with setTimeout(), however it did not work.

Thanks for help in advance.

function setupTypewriter(t) {
  var HTML = t.innerHTML;

  t.innerHTML = "";

  var cursorPosition = 0,
      tag = "",
      writingTag = false,
      tagOpen = false,
      typeSpeed = 50,
      tempTypeSpeed = 0;

  var type = function() {

    if (writingTag === true) {
      tag += HTML[cursorPosition];
    }

    if (HTML[cursorPosition] === "<") {
      tempTypeSpeed = 0;
      if (tagOpen) {
        tagOpen = false;
        writingTag = true;
      } else {
        tag = "";
        tagOpen = true;
        writingTag = true;
        tag += HTML[cursorPosition];
      }
    }
    if (!writingTag && tagOpen) {
      tag.innerHTML += HTML[cursorPosition];
    }
    if (!writingTag && !tagOpen) {
      if (HTML[cursorPosition] === " ") {
        tempTypeSpeed = 0;
      }
      else {
        tempTypeSpeed = (Math.random() * typeSpeed) + 50;
      }
      t.innerHTML += HTML[cursorPosition];
    }
    if (writingTag === true && HTML[cursorPosition] === ">") {
      tempTypeSpeed = (Math.random() * typeSpeed) + 50;
      writingTag = false;
      if (tagOpen) {
        var newSpan = document.createElement("span");
        t.appendChild(newSpan);
        newSpan.innerHTML = tag;
        tag = newSpan.firstChild;
      }
    }

    cursorPosition += 1;
    if (cursorPosition < HTML.length - 1) {
      setTimeout(type, tempTypeSpeed);
    }

  };

  return {
    type: type
  };
}

var typer = document.getElementById('typewriter');

typewriter = setupTypewriter(typewriter);

typewriter.type();

Body:
typewriter = setupTypewriter(typewriter);

You pass typewriter variable to setupTypewriter, but it doesn't exist yet. Here you want to use

typewriter = setupTypewriter(typer);

BTW, I can't understand how you print tags. You print <, d, i, v, > with zero delay, but the parser still may break. You should print the tag at once: <div></div> and then append div's contents to it.


问:
Visual Studio 2017 – Enterprise restarts on .Net Core Projects
Just installed Visual Studio 2017 – Enterprise Edition with the following workloads:

Universal Windows Platform Development

ASP.Net and Web Development

.Net Desktop Development

.Net Core cross-platform Development

After this installation, when I create a new .net core or .net standard project, the visual studio restarts while loading the project template.
Steps to create the behavior:

File ⇒ New Project ⇒ .Net Core ⇒ Asp.Net Core Application (.Net Core)

Visual Studio tries to load the selected template then suddenly it disappears and the windows show the dialogue box to Check online help, debug or close it.
Next, visual studio reboots to the start page.

This only happens when I select any .Net Core or .Net Standard project templates.
Much appreciate your help in advance.

答:
I had the exact same issue. It turned out that when a .Net core or .Net standard project template is selected, it tries to restore the packages from NuGet and somehow it was unable to do that or clear the NuGet’s local cache.
Here are the steps to fix it:

Download NuGet

https://dist.nuget.org/win-x86-commandline/latest/nuget.exe

Open the command prompt as “Administrator” – this is important other
cache may not get cleared due to permission issues.

Navigate to the folder where the NuGet is downloaded

Run the following command to clear the cache

nuget locals all -clear

Open Visual Studio 2017

Create a new ASP.Net core project with default templates

Hope this helps!


问:
Insert an element inside a choice option to his 'father' everytime from a target mssage in mapping node
I am using a mapping node in my messageflow in IBM esb/wmb and there is a part where i need to insert a specific element from the target message to his "father" in the target message, this element is inside a 'choice' option.

For example:

```<code><xs:element name="JOB">
     <xs:complexType>
        <xs:choice>
           <xs:element name="YES"/>
           <xs:element name="NO"/>
        </xs:choice>
      </xs:complexType>
  </xs:element>
</code>```

I want the 'JOB' element in the target message to always get the 'YES' element.

Is there any way to do this with some build function(s) in mapping node in wmb ?

答: You can set static values by the assign function. Just right click on the target element and select Create Assign.</p>

Body:
I am using a mapping node in my messageflow in IBM esb/wmb and there is a part where i need to insert a specific element from the target message to his "father" in the target message, this element is inside a 'choice' option.

For example:

<xs:element name="JOB">
     <xs:complexType>
        <xs:choice>
           <xs:element name="YES"/>
           <xs:element name="NO"/>
        </xs:choice>
      </xs:complexType>
  </xs:element>

I want the 'JOB' element in the target message to always get the 'YES' element.

Is there any way to do this with some build function(s) in mapping node in wmb ?


问:
Rails auto_complete with a subset of objects
Here are my models:

```<code>class User < ActiveRecord::Base
  has_many    :artists
end

class Artist < ActiveRecord::Base
  belongs_to    :user
end
</code>```

I am trying to implement an auto_complete text field where artist names are auto completed:

```<code><%= text_field_with_auto_complete :artist, :name, { :size => 60}, {:skip_style => false, :tokens => ','} %>
</code>```

This works but autocompletes over all Artists defined in the database. What do I need to do to limit the returned auto_complete results to only the Artists belonging to the logged in User?

Thanks a lot!

答:
Presumably you've got something like this in your controller:

```<code>def auto_complete_for_artist_name
  @artists = Artist.find(:all,
   :conditions => "name LIKE (?)", params[:artist][:name])
end
</code>```

You'll need to change that to either add the current user to the conditions or use the association like this:

```<code>def auto_complete_for_artist_name
  # assumes you have a 'current_user' method
  # which returns the current logged in user
  @artists = current_user.artists.find(:all,
     :conditions => "name LIKE (?)", params[:artist][:name])
end
</code>```

That will give you just the artists belonging to the current user.

Body:
Here are my models:

class User < ActiveRecord::Base
  has_many    :artists
end

class Artist < ActiveRecord::Base
  belongs_to    :user
end

I am trying to implement an auto_complete text field where artist names are auto completed:

<%= text_field_with_auto_complete :artist, :name, { :size => 60}, {:skip_style => false, :tokens => ','} %>

This works but autocompletes over all Artists defined in the database. What do I need to do to limit the returned auto_complete results to only the Artists belonging to the logged in User?

Thanks a lot!

Body:
Presumably you've got something like this in your controller:

def auto_complete_for_artist_name
  @artists = Artist.find(:all,
   :conditions => "name LIKE (?)", params[:artist][:name])
end

You'll need to change that to either add the current user to the conditions or use the association like this:

def auto_complete_for_artist_name
  # assumes you have a 'current_user' method
  # which returns the current logged in user
  @artists = current_user.artists.find(:all,
     :conditions => "name LIKE (?)", params[:artist][:name])
end

That will give you just the artists belonging to the current user.


问:
JavaScript - Function to change display of popup box
If the form is valid, a pop up appears.

However, it only appears for a second before it dissapears. Im guessing the display is defaulting back to 'none'. It should only close via a button that changes the display back to none (located on the popup).

How come it is only appearing for second? And not waiting for it to be closed via the button?

HTML

```<code><div class="fixedBasketHoldingDiv">
    <div id="cardSubmission">
        <h2>Order form</h2>
        <div id="form">
            <h3>Enter your card details:</h3>
            <form onsubmit="submitDetails()">
                <input type="text" id="name" placeholder="Name" onfocus="focusFunction('name')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <input type="text" id="cardNo" placeholder="Card Number" onfocus="focusFunction('16 digit card number')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <input class="month" type="text" id="expMonth" placeholder="MM" onfocus="focusFunction('expiry month (MM)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required">
                <input class ="year" type="text" id="expYear" placeholder="YYYY" onfocus="focusFunction('expiry year (YYYY)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required"><br />
                <input type="text" id="secCode" placeholder="Security Code" onfocus="focusFunction('security code')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <h3 id="contactDetails">Enter you contact details here:</h3>
                <input type="text" id="addressFirstLine" placeholder="Address Line 1" onfocus="focusFunction('address line 1')" onblur="blurFunction()" required="required"><br />
                <input type="text" id="addressSecondLine" placeholder="Address Line 2" onfocus="focusFunction('address line 2')" onblur="blurFunction()"><br />
                <input type="text" id="addressThirdLine" placeholder="Address Line 3" onfocus="focusFunction('address line 3')" onblur="blurFunction()"><br />
                <input type="text" id="Town" placeholder="Town" required="required" onfocus="focusFunction('town')" onblur="blurFunction()">
                <input type="text" id="County" placeholder="County" required="required" onfocus="focusFunction('county')" onblur="blurFunction()"><br />
                <input type="text" id="postCode" placeholder="Post Code" required="required" onfocus="focusFunction('post code')" onblur="blurFunction()"><br />
                <h3><?php echo "£" . number_format($total, 2) ?></h3>
                <input class="submit" type="submit" id="submit" value="Order Now!"><br />
            </form>
            <p class="help" id="help"></p>
        </div>
    </div>
</div>

<div id="popupBox" class="popupPosition">
    <div id="popupBoxWrapper">
        <div id="popupBoxContainer">
            <h3>Order Conformation</h3>
            <p>Congratulations your order is on its way!</p>
            <button id="popupBoxClose" onclick="document.getElementById('popupBox').style.display = 'none';">Close</button>
        </div>
    </div>
</div>
</code>```

JS

```<code>function submitDetails() {
    var errorMsg = "";
    var name = document.getElementById('name').value;
    var cardNo = document.getElementById('cardNo').value;
    var expMonth = document.getElementById('expMonth').value;
    var expYear = document.getElementById('expYear').value;
    var secCode = document.getElementById('secCode').value;

    if ((cardNo.toString().length != 16) || isNaN(cardNo) || cardNo != parseInt(cardNo)){
        errorMsg += "\n\u2022 Enter a Card Number of 16 digits.\n"
    }
    if (name == "") {
        errorMsg += "\n\u2022 Enter a Name.\n"
    }
    if (expMonth == "" || expYear == "") {
        errorMsg += "\n\u2022 Enter an Expiry Date.\n"
    }
    else if ((1 > parseInt(expMonth)) || parseInt(expMonth) > 12 || (parseInt(expYear) < 2017) || (isNaN(expMonth)) || (expMonth != parseInt(expMonth)) || (isNaN(expYear)) || (expYear != parseInt(expYear))){
        errorMsg += "\n\u2022 Enter month between 1-12 & a year after 2017.\n"
    }
    if ((secCode.toString().length != 3) || isNaN(secCode) || secCode != parseInt(secCode)){
        errorMsg += "\n\u2022 Enter a Security Code of 3 digits.\n"
    }
    if (errorMsg != ""){
        alert(errorMsg);
    }
    else {
        document.getElementById('popupBox').style.display = 'block';
    }
}
</code>```

答:
Don't forget to add jquery to your page!

Example (this goes in the head or before your  tag:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</code>```

Here is an example (not tested) :

```<code><div class="fixedBasketHoldingDiv">
    <div id="cardSubmission">
        <h2>Order form</h2>
        <div id="form">
            <h3>Enter your card details:</h3>
            <form id="myform" onsubmit="submitDetails()">
                <input type="text" id="name" placeholder="Name" onfocus="focusFunction('name')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <input type="text" id="cardNo" placeholder="Card Number" onfocus="focusFunction('16 digit card number')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <input class="month" type="text" id="expMonth" placeholder="MM" onfocus="focusFunction('expiry month (MM)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required">
                <input class ="year" type="text" id="expYear" placeholder="YYYY" onfocus="focusFunction('expiry year (YYYY)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required"><br />
                <input type="text" id="secCode" placeholder="Security Code" onfocus="focusFunction('security code')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <h3 id="contactDetails">Enter you contact details here:</h3>
                <input type="text" id="addressFirstLine" placeholder="Address Line 1" onfocus="focusFunction('address line 1')" onblur="blurFunction()" required="required"><br />
                <input type="text" id="addressSecondLine" placeholder="Address Line 2" onfocus="focusFunction('address line 2')" onblur="blurFunction()"><br />
                <input type="text" id="addressThirdLine" placeholder="Address Line 3" onfocus="focusFunction('address line 3')" onblur="blurFunction()"><br />
                <input type="text" id="Town" placeholder="Town" required="required" onfocus="focusFunction('town')" onblur="blurFunction()">
                <input type="text" id="County" placeholder="County" required="required" onfocus="focusFunction('county')" onblur="blurFunction()"><br />
                <input type="text" id="postCode" placeholder="Post Code" required="required" onfocus="focusFunction('post code')" onblur="blurFunction()"><br />
                <h3><?php echo "£" . number_format($total, 2) ?></h3>
                <input class="submit" type="submit" id="submit" value="Order Now!"><br />
            </form>
            <p class="help" id="help"></p>
        </div>
    </div>
</div>
<div id="popupBox" class="popupPosition">
    <div id="popupBoxWrapper">
        <div id="popupBoxContainer">
            <h3>Order Conformation</h3>
            <p>Congratulations your order is on its way!</p>
            <button id="popupBoxClose" onclick="document.getElementById('popupBox').style.display = 'none';">Close</button>
        </div>
    </div>
</div>
<script>
    function submitDetails(evt) {
        // Prevent default behavior (submiting the form)
        evt.preventDefault();
        // Get the form action url
        var url = evt.currentTarget.action;

        var errorMsg = "";
        var name = document.getElementById('name').value;
        var cardNo = document.getElementById('cardNo').value;
        var expMonth = document.getElementById('expMonth').value;
        var expYear = document.getElementById('expYear').value;
        var secCode = document.getElementById('secCode').value;

        if ((cardNo.toString().length != 16) || isNaN(cardNo) || cardNo != parseInt(cardNo)){
            errorMsg += "\n\u2022 Enter a Card Number of 16 digits.\n"
        }
        if (name == "") {
            errorMsg += "\n\u2022 Enter a Name.\n"
        }
        if (expMonth == "" || expYear == "") {
            errorMsg += "\n\u2022 Enter an Expiry Date.\n"
        }
        else if ((1 > parseInt(expMonth)) || parseInt(expMonth) > 12 || (parseInt(expYear) < 2017) || (isNaN(expMonth)) || (expMonth != parseInt(expMonth)) || (isNaN(expYear)) || (expYear != parseInt(expYear))){
            errorMsg += "\n\u2022 Enter month between 1-12 & a year after 2017.\n"
        }
        if ((secCode.toString().length != 3) || isNaN(secCode) || secCode != parseInt(secCode)){
            errorMsg += "\n\u2022 Enter a Security Code of 3 digits.\n"
        }
        if (errorMsg != ""){
            alert(errorMsg);
        }
        else {
            document.getElementById('popupBox').style.display = 'block';
        }

        // Do your own request an handle the results
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data: $("#myform").serialize(),
            success: function(data) {
                // do something with the response data...
                console.log(data);
            }
        });
        // Same as preventDefault - but for older browsers
        return false;
    }
</script>
</code>```

EDIT - Here is pure Javascript implementation:

```<code><div class="fixedBasketHoldingDiv">
    <div id="cardSubmission">
        <h2>Order form</h2>
        <div id="form">
            <h3>Enter your card details:</h3>
            <form id="myform" onsubmit="submitDetails()">
                <input type="text" id="name" placeholder="Name" onfocus="focusFunction('name')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <input type="text" id="cardNo" placeholder="Card Number" onfocus="focusFunction('16 digit card number')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <input class="month" type="text" id="expMonth" placeholder="MM" onfocus="focusFunction('expiry month (MM)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required">
                <input class ="year" type="text" id="expYear" placeholder="YYYY" onfocus="focusFunction('expiry year (YYYY)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required"><br />
                <input type="text" id="secCode" placeholder="Security Code" onfocus="focusFunction('security code')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <h3 id="contactDetails">Enter you contact details here:</h3>
                <input type="text" id="addressFirstLine" placeholder="Address Line 1" onfocus="focusFunction('address line 1')" onblur="blurFunction()" required="required"><br />
                <input type="text" id="addressSecondLine" placeholder="Address Line 2" onfocus="focusFunction('address line 2')" onblur="blurFunction()"><br />
                <input type="text" id="addressThirdLine" placeholder="Address Line 3" onfocus="focusFunction('address line 3')" onblur="blurFunction()"><br />
                <input type="text" id="Town" placeholder="Town" required="required" onfocus="focusFunction('town')" onblur="blurFunction()">
                <input type="text" id="County" placeholder="County" required="required" onfocus="focusFunction('county')" onblur="blurFunction()"><br />
                <input type="text" id="postCode" placeholder="Post Code" required="required" onfocus="focusFunction('post code')" onblur="blurFunction()"><br />
                <h3><?php echo "£" . number_format($total, 2) ?></h3>
                <input class="submit" type="submit" id="submit" value="Order Now!"><br />
            </form>
            <p class="help" id="help"></p>
        </div>
    </div>
</div>
<div id="popupBox" class="popupPosition">
    <div id="popupBoxWrapper">
        <div id="popupBoxContainer">
            <h3>Order Conformation</h3>
            <p>Congratulations your order is on its way!</p>
            <button id="popupBoxClose" onclick="document.getElementById('popupBox').style.display = 'none';">Close</button>
        </div>
    </div>
</div>
<script>
    function submitDetails(evt) {
        // Prevent default behavior (submiting the form)
        evt.preventDefault();
        // Get the form action url
        var url = evt.currentTarget.action;

        var errorMsg = "";
        var name = document.getElementById('name').value;
        var cardNo = document.getElementById('cardNo').value;
        var expMonth = document.getElementById('expMonth').value;
        var expYear = document.getElementById('expYear').value;
        var secCode = document.getElementById('secCode').value;

        if ((cardNo.toString().length != 16) || isNaN(cardNo) || cardNo != parseInt(cardNo)){
            errorMsg += "\n\u2022 Enter a Card Number of 16 digits.\n"
        }
        if (name == "") {
            errorMsg += "\n\u2022 Enter a Name.\n"
        }
        if (expMonth == "" || expYear == "") {
            errorMsg += "\n\u2022 Enter an Expiry Date.\n"
        }
        else if ((1 > parseInt(expMonth)) || parseInt(expMonth) > 12 || (parseInt(expYear) < 2017) || (isNaN(expMonth)) || (expMonth != parseInt(expMonth)) || (isNaN(expYear)) || (expYear != parseInt(expYear))){
            errorMsg += "\n\u2022 Enter month between 1-12 & a year after 2017.\n"
        }
        if ((secCode.toString().length != 3) || isNaN(secCode) || secCode != parseInt(secCode)){
            errorMsg += "\n\u2022 Enter a Security Code of 3 digits.\n"
        }
        if (errorMsg != ""){
            alert(errorMsg);
        }
        else {
            document.getElementById('popupBox').style.display = 'block';
        }

        var query = [];
        // Extract all input names and their values
        document.querySelectorAll('#myform input[type=text]').forEach(function(field) {
            query.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
        }
        // Join key/values together (format for sending form-encoded data)
        query = query.join('&');

        // Use proper request handler (older IE doesn't support XMLHttpRequest)
        var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

        // Add event change handler
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            {
                console.log(xmlHttp.responseText);
            }
        }

        // Open request
        xmlHttp.open("post", url);

        // Send the data
        xmlHttp.send(query);

        // Same as preventDefault - but for older browsers
        return false;
    }
</script>
</code>```

Body:
If the form is valid, a pop up appears.

However, it only appears for a second before it dissapears. Im guessing the display is defaulting back to 'none'. It should only close via a button that changes the display back to none (located on the popup).

How come it is only appearing for second? And not waiting for it to be closed via the button?

HTML

Order form

Enter your card details:

            <form onsubmit="submitDetails()">
                <input type="text" id="name" placeholder="Name" onfocus="focusFunction('name')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required">

                <input type="text" id="cardNo" placeholder="Card Number" onfocus="focusFunction('16 digit card number')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required">

                <input class="month" type="text" id="expMonth" placeholder="MM" onfocus="focusFunction('expiry month (MM)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required">
                <input class ="year" type="text" id="expYear" placeholder="YYYY" onfocus="focusFunction('expiry year (YYYY)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required">

                <input type="text" id="secCode" placeholder="Security Code" onfocus="focusFunction('security code')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required">

Enter you contact details here:

                <input type="text" id="addressFirstLine" placeholder="Address Line 1" onfocus="focusFunction('address line 1')" onblur="blurFunction()" required="required">

                <input type="text" id="addressSecondLine" placeholder="Address Line 2" onfocus="focusFunction('address line 2')" onblur="blurFunction()">

                <input type="text" id="addressThirdLine" placeholder="Address Line 3" onfocus="focusFunction('address line 3')" onblur="blurFunction()">

                <input type="text" id="Town" placeholder="Town" required="required" onfocus="focusFunction('town')" onblur="blurFunction()">
                <input type="text" id="County" placeholder="County" required="required" onfocus="focusFunction('county')" onblur="blurFunction()">

                <input type="text" id="postCode" placeholder="Post Code" required="required" onfocus="focusFunction('post code')" onblur="blurFunction()">

<?php echo "£" . number_format($total, 2) ?>

                <input class="submit" type="submit" id="submit" value="Order Now!">

            </form>

Order Conformation

Congratulations your order is on its way!

            <button id="popupBoxClose" onclick="document.getElementById('popupBox').style.display = 'none';">Close</button>

JS

function submitDetails() {
    var errorMsg = "";
    var name = document.getElementById('name').value;
    var cardNo = document.getElementById('cardNo').value;
    var expMonth = document.getElementById('expMonth').value;
    var expYear = document.getElementById('expYear').value;
    var secCode = document.getElementById('secCode').value;

    if ((cardNo.toString().length != 16) || isNaN(cardNo) || cardNo != parseInt(cardNo)){
        errorMsg += "\n\u2022 Enter a Card Number of 16 digits.\n"
    }
    if (name == "") {
        errorMsg += "\n\u2022 Enter a Name.\n"
    }
    if (expMonth == "" || expYear == "") {
        errorMsg += "\n\u2022 Enter an Expiry Date.\n"
    }
    else if ((1 > parseInt(expMonth)) || parseInt(expMonth) > 12 || (parseInt(expYear) < 2017) || (isNaN(expMonth)) || (expMonth != parseInt(expMonth)) || (isNaN(expYear)) || (expYear != parseInt(expYear))){
        errorMsg += "\n\u2022 Enter month between 1-12 & a year after 2017.\n"
    }
    if ((secCode.toString().length != 3) || isNaN(secCode) || secCode != parseInt(secCode)){
        errorMsg += "\n\u2022 Enter a Security Code of 3 digits.\n"
    }
    if (errorMsg != ""){
        alert(errorMsg);
    }
    else {
        document.getElementById('popupBox').style.display = 'block';
    }
}

Body:
Don't forget to add jquery to your page!

Example (this goes in the head or before your  tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Here is an example (not tested) :

<div class="fixedBasketHoldingDiv">
    <div id="cardSubmission">
        <h2>Order form</h2>
        <div id="form">
            <h3>Enter your card details:</h3>
            <form id="myform" onsubmit="submitDetails()">
                <input type="text" id="name" placeholder="Name" onfocus="focusFunction('name')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <input type="text" id="cardNo" placeholder="Card Number" onfocus="focusFunction('16 digit card number')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <input class="month" type="text" id="expMonth" placeholder="MM" onfocus="focusFunction('expiry month (MM)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required">
                <input class ="year" type="text" id="expYear" placeholder="YYYY" onfocus="focusFunction('expiry year (YYYY)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required"><br />
                <input type="text" id="secCode" placeholder="Security Code" onfocus="focusFunction('security code')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <h3 id="contactDetails">Enter you contact details here:</h3>
                <input type="text" id="addressFirstLine" placeholder="Address Line 1" onfocus="focusFunction('address line 1')" onblur="blurFunction()" required="required"><br />
                <input type="text" id="addressSecondLine" placeholder="Address Line 2" onfocus="focusFunction('address line 2')" onblur="blurFunction()"><br />
                <input type="text" id="addressThirdLine" placeholder="Address Line 3" onfocus="focusFunction('address line 3')" onblur="blurFunction()"><br />
                <input type="text" id="Town" placeholder="Town" required="required" onfocus="focusFunction('town')" onblur="blurFunction()">
                <input type="text" id="County" placeholder="County" required="required" onfocus="focusFunction('county')" onblur="blurFunction()"><br />
                <input type="text" id="postCode" placeholder="Post Code" required="required" onfocus="focusFunction('post code')" onblur="blurFunction()"><br />
                <h3><?php echo "£" . number_format($total, 2) ?></h3>
                <input class="submit" type="submit" id="submit" value="Order Now!"><br />
            </form>
            <p class="help" id="help"></p>
        </div>
    </div>
</div>
<div id="popupBox" class="popupPosition">
    <div id="popupBoxWrapper">
        <div id="popupBoxContainer">
            <h3>Order Conformation</h3>
            <p>Congratulations your order is on its way!</p>
            <button id="popupBoxClose" onclick="document.getElementById('popupBox').style.display = 'none';">Close</button>
        </div>
    </div>
</div>
<script>
    function submitDetails(evt) {
        // Prevent default behavior (submiting the form)
        evt.preventDefault();
        // Get the form action url
        var url = evt.currentTarget.action;

        var errorMsg = "";
        var name = document.getElementById('name').value;
        var cardNo = document.getElementById('cardNo').value;
        var expMonth = document.getElementById('expMonth').value;
        var expYear = document.getElementById('expYear').value;
        var secCode = document.getElementById('secCode').value;

        if ((cardNo.toString().length != 16) || isNaN(cardNo) || cardNo != parseInt(cardNo)){
            errorMsg += "\n\u2022 Enter a Card Number of 16 digits.\n"
        }
        if (name == "") {
            errorMsg += "\n\u2022 Enter a Name.\n"
        }
        if (expMonth == "" || expYear == "") {
            errorMsg += "\n\u2022 Enter an Expiry Date.\n"
        }
        else if ((1 > parseInt(expMonth)) || parseInt(expMonth) > 12 || (parseInt(expYear) < 2017) || (isNaN(expMonth)) || (expMonth != parseInt(expMonth)) || (isNaN(expYear)) || (expYear != parseInt(expYear))){
            errorMsg += "\n\u2022 Enter month between 1-12 & a year after 2017.\n"
        }
        if ((secCode.toString().length != 3) || isNaN(secCode) || secCode != parseInt(secCode)){
            errorMsg += "\n\u2022 Enter a Security Code of 3 digits.\n"
        }
        if (errorMsg != ""){
            alert(errorMsg);
        }
        else {
            document.getElementById('popupBox').style.display = 'block';
        }

        // Do your own request an handle the results
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data: $("#myform").serialize(),
            success: function(data) {
                // do something with the response data...
                console.log(data);
            }
        });
        // Same as preventDefault - but for older browsers
        return false;
    }
</script>

EDIT - Here is pure Javascript implementation:

<div class="fixedBasketHoldingDiv">
    <div id="cardSubmission">
        <h2>Order form</h2>
        <div id="form">
            <h3>Enter your card details:</h3>
            <form id="myform" onsubmit="submitDetails()">
                <input type="text" id="name" placeholder="Name" onfocus="focusFunction('name')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <input type="text" id="cardNo" placeholder="Card Number" onfocus="focusFunction('16 digit card number')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <input class="month" type="text" id="expMonth" placeholder="MM" onfocus="focusFunction('expiry month (MM)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required">
                <input class ="year" type="text" id="expYear" placeholder="YYYY" onfocus="focusFunction('expiry year (YYYY)')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;size: 10;" required="required"><br />
                <input type="text" id="secCode" placeholder="Security Code" onfocus="focusFunction('security code')" onblur="blurFunction()" style="font-family: 'Raleway', sans-serif;" required="required"><br />
                <h3 id="contactDetails">Enter you contact details here:</h3>
                <input type="text" id="addressFirstLine" placeholder="Address Line 1" onfocus="focusFunction('address line 1')" onblur="blurFunction()" required="required"><br />
                <input type="text" id="addressSecondLine" placeholder="Address Line 2" onfocus="focusFunction('address line 2')" onblur="blurFunction()"><br />
                <input type="text" id="addressThirdLine" placeholder="Address Line 3" onfocus="focusFunction('address line 3')" onblur="blurFunction()"><br />
                <input type="text" id="Town" placeholder="Town" required="required" onfocus="focusFunction('town')" onblur="blurFunction()">
                <input type="text" id="County" placeholder="County" required="required" onfocus="focusFunction('county')" onblur="blurFunction()"><br />
                <input type="text" id="postCode" placeholder="Post Code" required="required" onfocus="focusFunction('post code')" onblur="blurFunction()"><br />
                <h3><?php echo "£" . number_format($total, 2) ?></h3>
                <input class="submit" type="submit" id="submit" value="Order Now!"><br />
            </form>
            <p class="help" id="help"></p>
        </div>
    </div>
</div>
<div id="popupBox" class="popupPosition">
    <div id="popupBoxWrapper">
        <div id="popupBoxContainer">
            <h3>Order Conformation</h3>
            <p>Congratulations your order is on its way!</p>
            <button id="popupBoxClose" onclick="document.getElementById('popupBox').style.display = 'none';">Close</button>
        </div>
    </div>
</div>
<script>
    function submitDetails(evt) {
        // Prevent default behavior (submiting the form)
        evt.preventDefault();
        // Get the form action url
        var url = evt.currentTarget.action;

        var errorMsg = "";
        var name = document.getElementById('name').value;
        var cardNo = document.getElementById('cardNo').value;
        var expMonth = document.getElementById('expMonth').value;
        var expYear = document.getElementById('expYear').value;
        var secCode = document.getElementById('secCode').value;

        if ((cardNo.toString().length != 16) || isNaN(cardNo) || cardNo != parseInt(cardNo)){
            errorMsg += "\n\u2022 Enter a Card Number of 16 digits.\n"
        }
        if (name == "") {
            errorMsg += "\n\u2022 Enter a Name.\n"
        }
        if (expMonth == "" || expYear == "") {
            errorMsg += "\n\u2022 Enter an Expiry Date.\n"
        }
        else if ((1 > parseInt(expMonth)) || parseInt(expMonth) > 12 || (parseInt(expYear) < 2017) || (isNaN(expMonth)) || (expMonth != parseInt(expMonth)) || (isNaN(expYear)) || (expYear != parseInt(expYear))){
            errorMsg += "\n\u2022 Enter month between 1-12 & a year after 2017.\n"
        }
        if ((secCode.toString().length != 3) || isNaN(secCode) || secCode != parseInt(secCode)){
            errorMsg += "\n\u2022 Enter a Security Code of 3 digits.\n"
        }
        if (errorMsg != ""){
            alert(errorMsg);
        }
        else {
            document.getElementById('popupBox').style.display = 'block';
        }

        var query = [];
        // Extract all input names and their values
        document.querySelectorAll('#myform input[type=text]').forEach(function(field) {
            query.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
        }
        // Join key/values together (format for sending form-encoded data)
        query = query.join('&');

        // Use proper request handler (older IE doesn't support XMLHttpRequest)
        var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

        // Add event change handler
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            {
                console.log(xmlHttp.responseText);
            }
        }

        // Open request
        xmlHttp.open("post", url);

        // Send the data
        xmlHttp.send(query);

        // Same as preventDefault - but for older browsers
        return false;
    }
</script>


问:
How can I start a socket REPL in Clojure 1.8 from leiningen or boot?
In the following link
http://clojure.org/reference/repl_and_main#_launching_a_socket_server

it has detailed info about how to start socket REPL form java, but since I am using lein, so how to start from lein. If start from boot is good to run, I could also try to use boot.

答:
boot has an upcoming socket-server task. As of boot 2.7.1, a version that includes this task hasn't been released yet.

In the meantime you can use the following commands to launch Socket REPLs. To launch a Clojure process with a Socket REPL listening on port 50505 using boot, use:

```<code>boot -i "(do (require 'clojure.core.server) (clojure.core.server/start-server {:port 50505 :name :repl :accept 'clojure.core.server/repl}))" wait
</code>```

Using Leiningen:

```<code>JVM_OPTS='-Dclojure.server.myrepl={:port,50505,:accept,clojure.core.server/repl}' lein repl
</code>```

Using a pain Clojure jar:

```<code>java -Dclojure.server.myrepl="{:port 50505 :accept clojure.core.server/repl}" -jar ~/.m2/repository/org/clojure/clojure/1.8.0/clojure-1.8.0.jar
</code>```

Body:
boot has an upcoming socket-server task. As of boot 2.7.1, a version that includes this task hasn't been released yet.

In the meantime you can use the following commands to launch Socket REPLs. To launch a Clojure process with a Socket REPL listening on port 50505 using boot, use:

boot -i "(do (require 'clojure.core.server) (clojure.core.server/start-server {:port 50505 :name :repl :accept 'clojure.core.server/repl}))" wait

Using Leiningen:

JVM_OPTS='-Dclojure.server.myrepl={:port,50505,:accept,clojure.core.server/repl}' lein repl

Using a pain Clojure jar:

java -Dclojure.server.myrepl="{:port 50505 :accept clojure.core.server/repl}" -jar ~/.m2/repository/org/clojure/clojure/1.8.0/clojure-1.8.0.jar


问:
R to Python pandas numpy.where conversion
what is the best way to write the following R code in Python (pandas dataframe) using numpy.where syntax.</p>

```<code>Data$new = ifelse(Data$Diff > 1.652*Data$Diff10, 1,
                         ifelse(Data$Diff < 3.95*Data$Diff10, -1, 0 ))
</code>```

答:
You can use:

```<code>Data['new'] = np.where(Data['Diff'] > 1.652*Data['Diff10'], 1,
              np.where(Data['Diff'] < 3.95*Data['Diff10'], -1, 0 ))
</code>```

EDIT:

It seems code above have logic error, because never return 0.

Maybe need:

```<code>Data = pd.DataFrame({'Diff':[2,4,.5],
                   'Diff10':[1,1,1]})

print (Data)
   Diff  Diff10
0   2.0       1
1   4.0       1
2   0.5       1

Data['new'] = np.where(Data['Diff'] < 1.652*Data['Diff10'], 2,
              np.where(Data['Diff'] > 3.95*Data['Diff10'], 3, 4 ))

print (Data)
   Diff  Diff10  new
0   2.0       1    4
1   4.0       1    3
2   0.5       1    2
</code>```

Body:
what is the best way to write the following R code in Python (pandas dataframe) using numpy.where syntax.

Data$new = ifelse(Data$Diff > 1.652*Data$Diff10, 1,
                         ifelse(Data$Diff < 3.95*Data$Diff10, -1, 0 ))

Body:
You can use:

Data['new'] = np.where(Data['Diff'] > 1.652*Data['Diff10'], 1,
              np.where(Data['Diff'] < 3.95*Data['Diff10'], -1, 0 ))

EDIT:

It seems code above have logic error, because never return 0.

Maybe need:

Data = pd.DataFrame({'Diff':[2,4,.5],
                   'Diff10':[1,1,1]})

print (Data)
   Diff  Diff10
0   2.0       1
1   4.0       1
2   0.5       1

Data['new'] = np.where(Data['Diff'] < 1.652*Data['Diff10'], 2,
              np.where(Data['Diff'] > 3.95*Data['Diff10'], 3, 4 ))

print (Data)
   Diff  Diff10  new
0   2.0       1    4
1   4.0       1    3
2   0.5       1    2


问:
How to fix java.lang.NumberFormatException?
```<code>contactField = new JTextField();
contactField.setBounds(165, 336, 100, 30);
contactField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();

if(!((c >= '0') && (c <= '9') || (c ==
KeyEvent.VK_BACK_SPACE) ||(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
int contactvalue=Integer.parseInt(contactField.getText());
</code>```

By running this code I am getting:

```<code>java.lang.NumberFormatException:Forinput string: ""
</code>```

答:
The msg is descriptive:

java.lang.NumberFormatException:Forinput string: ""

```<code>Integer.parseInt(contactField.getText());
</code>```

is throwing the exception because contactField is empty..

you just can not convert an empty string into an integer.

Body:
contactField = new JTextField();
contactField.setBounds(165, 336, 100, 30);
contactField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();

if(!((c >= '0') && (c <= '9') || (c ==
KeyEvent.VK_BACK_SPACE) ||(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
int contactvalue=Integer.parseInt(contactField.getText());

By running this code I am getting:

java.lang.NumberFormatException:Forinput string: ""

Body:
The msg is descriptive:

java.lang.NumberFormatException:Forinput string: ""

Integer.parseInt(contactField.getText());

is throwing the exception because contactField is empty..

you just can not convert an empty string into an integer.


问:
How to count cells that reply to a condition
Lets say I have this kind of spreadsheet:

P1A | P2A | P3A| RA

1 | 2 | 3 | 1

2 | 4 | 2 | 4

1 | 3 | 3 | 3

Where each row represents answers to a question.
First row is title row. P1A - P3A is player1 through player3 answers and RA is the right answer.

Is it possible to add subtotal row which will show number of right answers for each player without adding extra columns for making "IF" tests.

So the total will look like this:
1 | 2 | 1

答:
You can use sum product to find this. Use the formula like below</p>

```<code>=SUMPRODUCT((A2:A4=$D2:$D4)*1)
</code>```

Body:
You can use sum product to find this. Use the formula like below

=SUMPRODUCT((A2:A4=$D2:$D4)*1)


问:
Spring Boot JOOQ sql dialect not picked up from application.properties
Background: i am hosting the trial version of jooq 3.9.1 (proprietary eg oracle db compatible) in my nexus repository - all the dependencies in my pom relating to jooq point to that.

i have this line in my application.properties

```<code>jooq.sql-dialect=ORACLE
</code>```

but when i inspect the injected dslContext the dialect is set to "DEFAULT" and not ORACLE as expected/desired.

I am currently getting round it by autowiring the datasource rather than the dslcontext and then setting the sql dialect (as shown below) - but wondering why autowiring the dslcontext directly doesnt work as expected

```<code>@Autowired
private DataSourceConnectionProvider dataSource;

public static final SQLDialect sqlDialect = SQLDialect.ORACLE;

public DSLContext getDSL(){
    return DSL.using(dataSource, sqlDialect);
}
</code>```

答:
Lukas' comment Spring Boot JOOQ sql dialect not picked up from application.properties is correct.

Here is an example how to do it and test:

Inside application.properties

```<code>spring.jooq.sql-dialect = Postgres
</code>```

And tested with an integration test ConfigIT:

```<code>@RunWith(SpringRunner.class)
@JdbcTest
@ImportAutoConfiguration(JooqAutoConfiguration.class)
public class ConfigIT {

    @Autowired
    private DSLContext dSLContext;

    @Test
    public void dialectShouldBePickedUp() {
        assertThat(dSLContext.configuration().dialect(), is(SQLDialect.POSTGRES));
    }
}
</code>```

You'll find the working and tested example in the repositories of http://springbootbuch.de here: https://github.com/springbootbuch/database_examples

What's important ist to choose the right, case sensitive name. In my example, it's Postgres, in your example it should be Oracle and you must use the right property. Sadly, those names vary across different tool sets. For jOOQ you'll find the constants in org.jooq.SQLDialect

Body:
Background: i am hosting the trial version of jooq 3.9.1 (proprietary eg oracle db compatible) in my nexus repository - all the dependencies in my pom relating to jooq point to that.

i have this line in my application.properties

jooq.sql-dialect=ORACLE

but when i inspect the injected dslContext the dialect is set to "DEFAULT" and not ORACLE as expected/desired.

I am currently getting round it by autowiring the datasource rather than the dslcontext and then setting the sql dialect (as shown below) - but wondering why autowiring the dslcontext directly doesnt work as expected

@Autowired
private DataSourceConnectionProvider dataSource;

public static final SQLDialect sqlDialect = SQLDialect.ORACLE;

public DSLContext getDSL(){
    return DSL.using(dataSource, sqlDialect);
}

Body:
Lukas' comment Spring Boot JOOQ sql dialect not picked up from application.properties is correct.

Here is an example how to do it and test:

Inside application.properties

spring.jooq.sql-dialect = Postgres

And tested with an integration test ConfigIT:

@RunWith(SpringRunner.class)
@JdbcTest
@ImportAutoConfiguration(JooqAutoConfiguration.class)
public class ConfigIT {

    @Autowired
    private DSLContext dSLContext;

    @Test
    public void dialectShouldBePickedUp() {
        assertThat(dSLContext.configuration().dialect(), is(SQLDialect.POSTGRES));
    }
}

You'll find the working and tested example in the repositories of http://springbootbuch.de here: https://github.com/springbootbuch/database_examples

What's important ist to choose the right, case sensitive name. In my example, it's Postgres, in your example it should be Oracle and you must use the right property. Sadly, those names vary across different tool sets. For jOOQ you'll find the constants in org.jooq.SQLDialect


问:
How to draw a triangle using Path in Android?
I need to draw a triangle as similar to attached below image using Path in Android. Can you please the valuable suggestion on this?

I have tried with following code snippet. Correct me if am wrong in below code snippet.

```<code>        Android.Graphics.Point a = new Android.Graphics.Point(0, 0);
        Android.Graphics.Point b = new Android.Graphics.Point(0, 100);
        Android.Graphics.Point c = new Android.Graphics.Point(87, 100);

        _path = new Path();
        _path.Reset();
        _path.LineTo(b.X, b.Y);
        _path.LineTo(c.X, c.Y);
        _path.LineTo(a.X, a.Y);
        _path.Close();
</code>```

Expected output:

答:
I think just the coordinates are not right.

Try this

```<code> Path _path = new Path();
    _path.reset();
    _path.moveTo(0,100);
    _path.lineTo(87, 100);
    _path.lineTo(87, 0);
    _path.close();

    Paint paint = new Paint();
    paint.setColor(Color.RED);
    canvas.drawPath(_path, paint);
</code>```

Body:
I need to draw a triangle as similar to attached below image using Path in Android. Can you please the valuable suggestion on this?

I have tried with following code snippet. Correct me if am wrong in below code snippet.

        Android.Graphics.Point a = new Android.Graphics.Point(0, 0);
        Android.Graphics.Point b = new Android.Graphics.Point(0, 100);
        Android.Graphics.Point c = new Android.Graphics.Point(87, 100);

        _path = new Path();
        _path.Reset();
        _path.LineTo(b.X, b.Y);
        _path.LineTo(c.X, c.Y);
        _path.LineTo(a.X, a.Y);
        _path.Close();

Expected output:

Body:
I think just the coordinates are not right.

Try this

 Path _path = new Path();
    _path.reset();
    _path.moveTo(0,100);
    _path.lineTo(87, 100);
    _path.lineTo(87, 0);
    _path.close();

    Paint paint = new Paint();
    paint.setColor(Color.RED);
    canvas.drawPath(_path, paint);