问:
Android DexClassLoader how to use for class with parameters and arguments
I want to load external class from .jar file. It works fine.

Load class with DexClassLoader :

```<code>DexClassLoader classLoader = new DexClassLoader(
                libFile.getAbsolutePath(),
                tmpDir.getAbsolutePath(),
                null,
                ClassLoader.getSystemClassLoader());
        Class<?> customFileClass = null; // extends File class
        try {
            customFileClass = (Class<?>) classLoader.loadClass("test.MyClass");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block

        }
</code>```

i know, how i can use functions defined inside of the class, but how i can use it like:

```<code>File f = new File("/dir/File.txt");
</code>```

答:
After hours of searches and tests, i have found the solution.

Define new DexClassLoader:

```<code>// .jar file must be Dexted. I know 2 ways to do that:
// 1. Through console: dx  --dex --output="output.jar" "input.jar"
// 2. You can import dx.jar from Android-Sdk/build-tools/xx.x.x/lib/dx.jar in your app and convert .jar file with command:
// String[] command = new String[] {"--dex", "--output="output.jar", "input.jar"};
// com.android.dx.command.Main.main(command);
DexClassLoader classLoader = new DexClassLoader(
"absolutePathToJarFile",
"absolutePathToTmpDir",
null,
DexClassLoader.getSystemClassLoader());
</code>```

Define Class to be loaded:

```<code>Class<?> myClass = null;
myClass = classLoader.loadClass("my.test.app.neededClass");
</code>```

If the Class needs Arguments, like new myClass("arg1", "arg2");, we need to create new Arguments Class:

```<code>Class<?>[] args = new Class[1]; // 1 is the number of Arguments
args[0] = String.class; // First Argument of Type "String"
</code>```

To associate Arguments with the Class, we define new Constructor:

```<code>Constructor<?> constructor = null;
try {
    constructor = myClass.getDeclaredConstructor(args);
} catch (NoSuchMethodException e) {
    // TODO Auto-generated catch block
}
Object neededClass = null;
neededClass = constructor.newInstance("First String Argument");`
</code>```

Now we can extract known Functions defined inside of neededClass to Methods, like:

```<code>Method exists = null;
exists = myClass.getMethod("exists"); // exists() is the defined boolean Function inside of neededClass.
exists.setAccessible(true);
if((boolean) exists.invoke(neededClass)){
    // do if true
} else {
    // do if false
}
</code>```

The Problem with Classes like File is, we need to invoke Method inside of AsyncTask. If we try to invoke Method outside of AsyncTask, defined Functions of the Class like File.exists() will be not invoked and we get Error InvocationTargetException.

Body:
I want to load external class from .jar file. It works fine.

Load class with DexClassLoader :

DexClassLoader classLoader = new DexClassLoader(
                libFile.getAbsolutePath(),
                tmpDir.getAbsolutePath(),
                null,
                ClassLoader.getSystemClassLoader());
        Class<?> customFileClass = null; // extends File class
        try {
            customFileClass = (Class<?>) classLoader.loadClass("test.MyClass");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block

        }

i know, how i can use functions defined inside of the class, but how i can use it like:

File f = new File("/dir/File.txt");

Body:
After hours of searches and tests, i have found the solution.

Define new DexClassLoader:

// .jar file must be Dexted. I know 2 ways to do that:
// 1. Through console: dx  --dex --output="output.jar" "input.jar"
// 2. You can import dx.jar from Android-Sdk/build-tools/xx.x.x/lib/dx.jar in your app and convert .jar file with command:
// String[] command = new String[] {"--dex", "--output="output.jar", "input.jar"};
// com.android.dx.command.Main.main(command);
DexClassLoader classLoader = new DexClassLoader(
"absolutePathToJarFile",
"absolutePathToTmpDir",
null,
DexClassLoader.getSystemClassLoader());

Define Class to be loaded:

Class<?> myClass = null;
myClass = classLoader.loadClass("my.test.app.neededClass");

If the Class needs Arguments, like new myClass("arg1", "arg2");, we need to create new Arguments Class:

Class<?>[] args = new Class[1]; // 1 is the number of Arguments
args[0] = String.class; // First Argument of Type "String"

To associate Arguments with the Class, we define new Constructor:

Constructor<?> constructor = null;
try {
    constructor = myClass.getDeclaredConstructor(args);
} catch (NoSuchMethodException e) {
    // TODO Auto-generated catch block
}
Object neededClass = null;
neededClass = constructor.newInstance("First String Argument");`

Now we can extract known Functions defined inside of neededClass to Methods, like:

Method exists = null;
exists = myClass.getMethod("exists"); // exists() is the defined boolean Function inside of neededClass.
exists.setAccessible(true);
if((boolean) exists.invoke(neededClass)){
    // do if true
} else {
    // do if false
}

The Problem with Classes like File is, we need to invoke Method inside of AsyncTask. If we try to invoke Method outside of AsyncTask, defined Functions of the Class like File.exists() will be not invoked and we get Error InvocationTargetException.


来源: stackexchange

问:
Using Swagger with Flask
Is there a way to generate a RESTful API in Flask using Swagger?</p>

答: Flasgger is an extension to make automatic UI for Flask routes  http://github.com/rochacbruno/flasgger</p>

ContentLicense: CC BY-SA 3.0

Title: Using Swagger with Flask


问:
Xml widget Properties won't load
I have a problem with the Properties window in Android Studios. The problem is that the properties won't load. Like in the Picture, it only shows Loading and it's symbol, but nothing happens. I have already waited for more than five minutes but it still happens nothing. All other windows work peferctly. I restarted it many times and also tried the Invalid Caches / Restart option.
Hope you can help me.
Kingsten
Screenshot of the properties window</p>

答: I fixed the problem. I have deleted the C:\Users\S4Kin.AndroidStudio2.3 and started with new Settings(rebuild the settigns)</p>

Title: Xml widget Properties won't load


问:
using dynamic linq to filter a list of objects
I have two class like this

```<code>public class Error{
   public string Code{get;set;}
   public string Description{get;set;}
}

public class Row{
   public List<Error> Errors {get;set;}
   ....
}
</code>```

So, for each row, can exists more errors.
It's possible using dynamic linq select the row that have an error code(for example Code1)?

So, if the row contains Code1 and Code2, i want select the row.

if in the example below query has a list of rows i want a query like this

```<code>query.Where("Errors != null && Errors.Code.contains('Code1')")
</code>```

答:
```<code>IEnumerable<Row> rowCollection = ...; //your rows
var result = rowCollection
    .Where(r => r.Code.Contains("Code1") && r.Code.Contains("Code2"))
    .ToList();
</code>```

Body:
I have two class like this

public class Error{
   public string Code{get;set;}
   public string Description{get;set;}
}

public class Row{
   public List<Error> Errors {get;set;}
   ....
}

So, for each row, can exists more errors.
It's possible using dynamic linq select the row that have an error code(for example Code1)?

So, if the row contains Code1 and Code2, i want select the row.

if in the example below query has a list of rows i want a query like this

query.Where("Errors != null && Errors.Code.contains('Code1')")


问:
How to swap keys and values in a Map elegantly
I already know how to do it the hard way and got it working - iterating over entries and swapping "manually". But i wonder if, like so many tasks,  this one can be solved in a more elegant way.

I have read this post, unfortunately it does not feature elegant solutions. I also have no possibility to use any fancy Guava BiMaps or anything outside the jdk (project stack is already defined).

I can assume that my map is bijective, btw :)

答:
There are some jobs that can be simplified to a certain point and no more. This may be one of them!

If you want to do the job using Java collections apis only then brute force is the way to go - it will be quick (unless the collection is huge) and it will be an obvious piece of code.

ContentLicense: CC BY-SA 2.5


问:
Two different variables getting same value
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.

Here is my custom file class:

```<code>public class MyFile {

    private static String path;
    private static String name;

    private static final String FILE_SEPARATOR = "/";

    public MyFile(String path) {
        System.out.println(path);
        this.path = "";
        this.name = "";
        this.path = /*FILE_SEPARATOR*/path;
        String[] dirs = path.split(FILE_SEPARATOR);
        this.name = dirs[dirs.length - 1];
    }

    public static String getPath() {
        return path;
    }

    public static String getName() {
        return name;
    }

    public String toString() {
        return "Path: " + path + ", Name: " + name;
    }
}
</code>```

Here I am using the variables:

```<code>MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());
</code>```

The output is the following: http://imgur.com/a/Nu3N6

答:
First you want to know about static keyword:

Attributes and methods(member of a class) can be defined as static.

static members do not belongs to an individual object.

static members are common to all the instances(objects of the same class).

static members are stores in static memory(a common memory location which can by everybody).

Becauseof two member variables are static. Each objects share the values of these two variables(values are common for every objects).

```<code>private static String path;
private static String name;
</code>```

Remove the static in both variables. Then each and every object will hold a individual values for these variables.

Body:
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.

Here is my custom file class:

public class MyFile {

    private static String path;
    private static String name;

    private static final String FILE_SEPARATOR = "/";

    public MyFile(String path) {
        System.out.println(path);
        this.path = "";
        this.name = "";
        this.path = /*FILE_SEPARATOR*/path;
        String[] dirs = path.split(FILE_SEPARATOR);
        this.name = dirs[dirs.length - 1];
    }

    public static String getPath() {
        return path;
    }

    public static String getName() {
        return name;
    }

    public String toString() {
        return "Path: " + path + ", Name: " + name;
    }
}

Here I am using the variables:

MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());

The output is the following: http://imgur.com/a/Nu3N6

Body:
First you want to know about static keyword:

Attributes and methods(member of a class) can be defined as static.

static members do not belongs to an individual object.

static members are common to all the instances(objects of the same class).

static members are stores in static memory(a common memory location which can by everybody).

Becauseof two member variables are static. Each objects share the values of these two variables(values are common for every objects).

private static String path;
private static String name;

Remove the static in both variables. Then each and every object will hold a individual values for these variables.


问:
Can Clocks from std::chrono be different on different cores
I like to compare time_points from std::chrono::high_resolution_clock that were measured in threads running on different cores in a processor. Can there be significant differences, such as lags or from faster/slower clocks? What does the standard specify?

答:
The std clocks don't have a processor affinity, in fact, most threads don't either. Two clock measurements from the same thread could well have been made on different cores.

On the lead and lag associated with the measurements - this would be no different from the execution of any other instruction; the usual pipelines etc. may have an impact, but I would not consider it detrimental. If it could be detrimental, the you may need to consider other tools for the job, such as some specialized platform timing tools or CPU specific instructions of some sort.


问:
php script to dump the whole tables from a database and send it to a particular email
i am working on a project, and i will like to run a php script that will run as a backup. that is a script that will extract or export my database and send it to my mail. but what am confuse about is, can it be done using only php or sql or both?.

i will appreciate if you guys can help. Thanks

答:
Yes of course you can do it using php. But it would be good if you will use shell for database exporting an keep the database backup on CDN. I think this link might be useful to export database using php script.

Export MySQL database using PHP only


问:
Add a Character Between Strings in C++
So basically I'm trying to add a character in the middle of a string. Normally in something like Python, this would be pretty straightforward, but I'm really not sure how to achieve this in C++. What I'm trying to achieve is something like this:

```<code>void converter(){
    converted = ":regional_indicator_" + character + ":";

}
</code>```

So basically, I'm trying to add the variable character of a type char in a string. Should I be storing character as a string instead?

For reference here's all of my code:

```<code>#include <iostream>

using namespace std;

string inputLine;
char character;
string converted;

void input(){
    cout << "Please input the text in which you would like to be converted" << endl;
    cin >> inputLine;
}

void converter(){
    converted = ":regional_indicator_" + character + ":";

}
int main(){
    input();
    for (int i = 0; i < inputLine.length(); i++ ){
        character = tolower(inputLine[i]);
    }
    return 0;
}
</code>```

答:
The wasy way to build strings is to use a std::ostringstream like this:

```<code>void converter(){

    std::ostringstream oss;
    oss << ":regional_indicator_" << character << ":";

    converted = oss.str(); // copy the string out

    // ... etc ...
}
</code>```

The added advantage of that method is it converts numbers to string automatically too.

That's not the fastest way so if speed was important I would take advantage of the static nature of this concatenation like this:

```<code>std::string converter(){

    static char* template = ":regional_indicator_X:";
    template[20] = character; // replace the `X` with your character
    converted.assign(template, 21); // assign your string all at once

    // ... etc ...
}
</code>```

That works because your string is of fixed length. If thread safety is required you can use thread_local static char* template....

Title: Add a Character Between Strings in C++

Body:
So basically I'm trying to add a character in the middle of a string. Normally in something like Python, this would be pretty straightforward, but I'm really not sure how to achieve this in C++. What I'm trying to achieve is something like this:

void converter(){
    converted = ":regional_indicator_" + character + ":";

}

So basically, I'm trying to add the variable character of a type char in a string. Should I be storing character as a string instead?

For reference here's all of my code:

#include <iostream>

using namespace std;

string inputLine;
char character;
string converted;

void input(){
    cout << "Please input the text in which you would like to be converted" << endl;
    cin >> inputLine;
}

void converter(){
    converted = ":regional_indicator_" + character + ":";

}
int main(){
    input();
    for (int i = 0; i < inputLine.length(); i++ ){
        character = tolower(inputLine[i]);
    }
    return 0;
}

Body:
The wasy way to build strings is to use a std::ostringstream like this:

void converter(){

    std::ostringstream oss;
    oss << ":regional_indicator_" << character << ":";

    converted = oss.str(); // copy the string out

    // ... etc ...
}

The added advantage of that method is it converts numbers to string automatically too.

That's not the fastest way so if speed was important I would take advantage of the static nature of this concatenation like this:

std::string converter(){

    static char* template = ":regional_indicator_X:";
    template[20] = character; // replace the `X` with your character
    converted.assign(template, 21); // assign your string all at once

    // ... etc ...
}

That works because your string is of fixed length. If thread safety is required you can use thread_local static char* template....


问:
Vim - producing a drop down menu for manual search
I am trying to write my own autocomplete function in Vim which mimics a nice feature of the CTRL-x CTRL-(l,n, or p) autocomplete, namely I want to produce a drop down menu of possible choices to select from.

My issue with the commands above is that they search to complete the current word and I would like to create a search that handles any sequence of consecutive special characters as well.  I have worked out the search feature for my function using regular expressions and the normal command, but I do now know how to produce the menu of choices.

Any tips would be much appreciated.

(Note: I know there are plugins that may offer this feature, but I am more interested in understanding how to accomplish this using the built-in Vim functionality.)

答:
I believe this example from the documentation of complete() does exactly what you are asking to do.  Copied here from :help complete(:

```<code>inoremap <F5> <C-R>=ListMonths()<CR>

func! ListMonths()
    call complete(col('.'), ['January', 'February', 'March',
        \ 'April', 'May', 'June', 'July', 'August', 'September',
        \ 'October', 'November', 'December'])
    return ''
endfunc
</code>```

Body:
I believe this example from the documentation of complete() does exactly what you are asking to do.  Copied here from :help complete(:

inoremap <F5> <C-R>=ListMonths()<CR>

func! ListMonths()
    call complete(col('.'), ['January', 'February', 'March',
        \ 'April', 'May', 'June', 'July', 'August', 'September',
        \ 'October', 'November', 'December'])
    return ''
endfunc


问:
How to add event listener to element created dynamically within prototype?
HTML

```<code><div id="main"></div>
</code>```

JS

```<code>var TestClass = function() {};
TestClass.prototype = {
    addElement: function(parentId) {
    var parent = document.querySelector('#' + parentId);
    var a = document.createElement('a');
    a.textContent = '+';
    a.href = '#';
    a.addEventListener('click', this.onElementClick, false); //nothing happens on click
    parent.innerHTML = a.outerHTML;
  },

  onElementClick: function() {
    console.log('dynamic element clicked');
  }
};

new TestClass().addElement('main'); // on DOM ready
</code>```

Output

```<code><div id="main"><a href="#">+</a></div>
</code>```

答:
You are adding the event listener, correctly, however you are forgetting to add the element.

I have added document.body.append(a) to the addElement method.

This leads to the following code:

```<code>var TestClass = function() {};
TestClass.prototype = {
    addElement: function(parentId) {
    var parent = document.querySelector('#' + parentId);
    var a = document.createElement('a');
    a.textContent = '+';
    a.href = '#';
    a.addEventListener('click', this.onElementClick, false);
    document.body.append(a);
    parent.innerHTML = a.outerHTML;
  },

  onElementClick: function() {
    console.log('dynamic element clicked');
  }
};

new TestClass().addElement('main'); // on DOM ready
</code>```

Test it out here

Body:
HTML

JS

var TestClass = function() {};
TestClass.prototype = {
    addElement: function(parentId) {
    var parent = document.querySelector('#' + parentId);
    var a = document.createElement('a');
    a.textContent = '+';
    a.href = '#';
    a.addEventListener('click', this.onElementClick, false); //nothing happens on click
    parent.innerHTML = a.outerHTML;
  },

  onElementClick: function() {
    console.log('dynamic element clicked');
  }
};

new TestClass().addElement('main'); // on DOM ready

Output

+

Body:
You are adding the event listener, correctly, however you are forgetting to add the element.

I have added document.body.append(a) to the addElement method.

This leads to the following code:

var TestClass = function() {};
TestClass.prototype = {
    addElement: function(parentId) {
    var parent = document.querySelector('#' + parentId);
    var a = document.createElement('a');
    a.textContent = '+';
    a.href = '#';
    a.addEventListener('click', this.onElementClick, false);
    document.body.append(a);
    parent.innerHTML = a.outerHTML;
  },

  onElementClick: function() {
    console.log('dynamic element clicked');
  }
};

new TestClass().addElement('main'); // on DOM ready

Test it out here


问:
Can't create map in velocity
In my velocity template i am creating map like this :

```<code>#set($mymap.Map={"key":"value","key2":"value2"})
</code>```

I think it must work according to the documentation of velocity, but there is next error:

```<code>HTTP Status 500 - Could not load Velocity template for URL [editEmployee.vsl]; nested exception is org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 44, column 36. Encountered: "{" (123), after : ""

type Exception report

message Could not load Velocity template for URL [editEmployee.vsl]; nested exception is org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 44, column 36. Encountered: "{" (123), after : ""

description The server encountered an internal error (Could not load Velocity template for URL [editEmployee.vsl]; nested exception is org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 44, column 36. Encountered: "{" (123), after : "") that prevented it from fulfilling this request.

exception

org.springframework.core.NestedIOException: Could not load Velocity template for URL [editEmployee.vsl]; nested exception is org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 44, column 36.  Encountered: "{" (123), after : ""
    org.springframework.web.servlet.view.velocity.VelocityView.checkResource(VelocityView.java:270)
    org.springframework.web.servlet.view.UrlBasedViewResolver.loadView(UrlBasedViewResolver.java:421)
    org.springframework.web.servlet.view.AbstractCachingViewResolver.createView(AbstractCachingViewResolver.java:158)
    org.springframework.web.servlet.view.UrlBasedViewResolver.createView(UrlBasedViewResolver.java:384)
    org.springframework.web.servlet.view.AbstractCachingViewResolver.resolveViewName(AbstractCachingViewResolver.java:77)
    org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1078)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1027)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:369)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:168)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

root cause

org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 44, column 36.  Encountered: "{" (123), after : ""
    org.apache.velocity.Template.process(Template.java:141)
    org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:423)
    org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:341)
    org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:831)
    org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:813)
    org.apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.java:470)
    org.springframework.web.servlet.view.velocity.VelocityView.getTemplate(VelocityView.java:501)
    org.springframework.web.servlet.view.velocity.VelocityView.checkResource(VelocityView.java:260)
    org.springframework.web.servlet.view.UrlBasedViewResolver.loadView(UrlBasedViewResolver.java:421)
    org.springframework.web.servlet.view.AbstractCachingViewResolver.createView(AbstractCachingViewResolver.java:158)
    org.springframework.web.servlet.view.UrlBasedViewResolver.createView(UrlBasedViewResolver.java:384)
    org.springframework.web.servlet.view.AbstractCachingViewResolver.resolveViewName(AbstractCachingViewResolver.java:77)
    org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1078)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1027)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:369)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:168)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
</code>```

There is my pom with velocity:

```<code><dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.6.2</version>
        </dependency>
        <dependency>
            <groupId>velocity-tools</groupId>
            <artifactId>velocity-tools</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>velocity-tools</groupId>
            <artifactId>velocity-tools-generic</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.1</version>
        </dependency>
</code>```

答:
try</p>

```<code>#set($mymap={"key":"value","key2":"value2"})
$mymap
</code>```

Title: Can't create map in velocity

Body:
In my velocity template i am creating map like this :

#set($mymap.Map={"key":"value","key2":"value2"})

I think it must work according to the documentation of velocity, but there is next error:

HTTP Status 500 - Could not load Velocity template for URL [editEmployee.vsl]; nested exception is org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 44, column 36. Encountered: "{" (123), after : ""

type Exception report

message Could not load Velocity template for URL [editEmployee.vsl]; nested exception is org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 44, column 36. Encountered: "{" (123), after : ""

description The server encountered an internal error (Could not load Velocity template for URL [editEmployee.vsl]; nested exception is org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 44, column 36. Encountered: "{" (123), after : "") that prevented it from fulfilling this request.

exception

org.springframework.core.NestedIOException: Could not load Velocity template for URL [editEmployee.vsl]; nested exception is org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 44, column 36.  Encountered: "{" (123), after : ""
    org.springframework.web.servlet.view.velocity.VelocityView.checkResource(VelocityView.java:270)
    org.springframework.web.servlet.view.UrlBasedViewResolver.loadView(UrlBasedViewResolver.java:421)
    org.springframework.web.servlet.view.AbstractCachingViewResolver.createView(AbstractCachingViewResolver.java:158)
    org.springframework.web.servlet.view.UrlBasedViewResolver.createView(UrlBasedViewResolver.java:384)
    org.springframework.web.servlet.view.AbstractCachingViewResolver.resolveViewName(AbstractCachingViewResolver.java:77)
    org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1078)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1027)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:369)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:168)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

root cause

org.apache.velocity.exception.ParseErrorException: Lexical error: org.apache.velocity.runtime.parser.TokenMgrError: Lexical error at line 44, column 36.  Encountered: "{" (123), after : ""
    org.apache.velocity.Template.process(Template.java:141)
    org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:423)
    org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:341)
    org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:831)
    org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:813)
    org.apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.java:470)
    org.springframework.web.servlet.view.velocity.VelocityView.getTemplate(VelocityView.java:501)
    org.springframework.web.servlet.view.velocity.VelocityView.checkResource(VelocityView.java:260)
    org.springframework.web.servlet.view.UrlBasedViewResolver.loadView(UrlBasedViewResolver.java:421)
    org.springframework.web.servlet.view.AbstractCachingViewResolver.createView(AbstractCachingViewResolver.java:158)
    org.springframework.web.servlet.view.UrlBasedViewResolver.createView(UrlBasedViewResolver.java:384)
    org.springframework.web.servlet.view.AbstractCachingViewResolver.resolveViewName(AbstractCachingViewResolver.java:77)
    org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1078)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1027)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:369)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:119)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:168)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

There is my pom with velocity:

<dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.6.2</version>
        </dependency>
        <dependency>
            <groupId>velocity-tools</groupId>
            <artifactId>velocity-tools</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>velocity-tools</groupId>
            <artifactId>velocity-tools-generic</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.1</version>
        </dependency>

Body:
try

#set($mymap={"key":"value","key2":"value2"})
$mymap


答:
Like this:

var TestClass = function() {};
TestClass.prototype = {
    addElement: function(parentId) {
    var parent = document.getElementById(parentId); //Changed to getElementById
    var a = document.createElement('a');
    a.textContent = '+';
    a.href = '#';
    a.addEventListener('click', this.onElementClick, false);
    parent.append(a); //Changed
  },

  onElementClick: function() {
    console.log('dynamic element clicked');
  }
};

new TestClass().addElement('main'); // on DOM ready```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main"></div></code>```

You did not add your a to parent, instead you just added its HTML.

Title: How to add event listener to element created dynamically within prototype?

Body:
Like this:

var TestClass = function() {};
TestClass.prototype = {
    addElement: function(parentId) {
    var parent = document.getElementById(parentId); //Changed to getElementById
    var a = document.createElement('a');
    a.textContent = '+';
    a.href = '#';
    a.addEventListener('click', this.onElementClick, false);
    parent.append(a); //Changed
  },

  onElementClick: function() {
    console.log('dynamic element clicked');
  }
};

new TestClass().addElement('main'); // on DOM ready

<div id="main"></div>

You did not add your a to parent, instead you just added its HTML.


问:
Rails Active record null after passed to class
I want to be able to pass my user object to another class for validation. Basically I do something like

My Controller:

```<code>def new

  user = User.find(1)
  logger.info "#{user.id}, #{user.name}, #{user.isadmin}"
  #The above is logged with 1, test, true
  uhelper = UserHelper.new(user)
  if !uhelper.isAdmin
    #Only admins can access this page
    redirect_to root_path
  end

end
</code>```

in app/models

```<code>Class UserHelper

def initialize(user)
  @user = user
end

def isAdmin
  if @user.isadmin
    true
  end
    nil
end
</code>```

The if statement in the controller is always resolving to nil even though I know the record is correct. Can I not pass ActiveRecords to classes like that correctly?

Does anyone have any ideas why this might be happening?

Edit

```<code>undefined method `isadmin' for nil:NilClass
app/models/userfnc.rb:14:in `isAdmin'
app/controllers/rosters_controller.rb:12:in `index'

sqlite> select * from users;
1|testuser|test@test.com|20170601|20170601|1

sqlite> .schema users
CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar DEFAULT NULL, "email" varchar DEFAULT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "isadmin" boolean);
</code>```

答:
There are quite a bit of code improvements you could use to your code.

As to your problem, it's possible that your casing is getting you.  Check your table.  your field might be called isadmin not isAdmin.

As for your code improvements, here's what could help you:

```<code>def isAdmin
  if @user.isAdmin
    true
  end
    nil
end
</code>```

you could accomplish this with one line:

```<code>def isAdmin
  @user.isAdmin
end
</code>```

This bit,

```<code>uhelper = UserHelper.new(user)
if !uhelper.isAdmin
  #Only admins can access this page
  redirect_to root_path
end
</code>```

When you have a simple expression like this, sometimes it's easier to also reduce this to one line:

```<code>uhelper = UserHelper.new(user)
redirect_to root_path unless uhelper.isAdmin
</code>```

However...  Rails standards are to use filters in this case.  Instead of that bit at all, put this in a filter method.

```<code>class MyController
  before_filter :check_admin
  ...
  ...
  private
  def check_admin
    redirect_to root_path unless user.isAdmin
  end
end
</code>```

Body:
I want to be able to pass my user object to another class for validation. Basically I do something like

My Controller:

def new

  user = User.find(1)
  logger.info "#{user.id}, #{user.name}, #{user.isadmin}"
  #The above is logged with 1, test, true
  uhelper = UserHelper.new(user)
  if !uhelper.isAdmin
    #Only admins can access this page
    redirect_to root_path
  end

end

in app/models

Class UserHelper

def initialize(user)
  @user = user
end

def isAdmin
  if @user.isadmin
    true
  end
    nil
end

The if statement in the controller is always resolving to nil even though I know the record is correct. Can I not pass ActiveRecords to classes like that correctly?

Does anyone have any ideas why this might be happening?

Edit

undefined method `isadmin' for nil:NilClass
app/models/userfnc.rb:14:in `isAdmin'
app/controllers/rosters_controller.rb:12:in `index'

sqlite> select * from users;
1|testuser|test@test.com|20170601|20170601|1

sqlite> .schema users
CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar DEFAULT NULL, "email" varchar DEFAULT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "isadmin" boolean);

Body:
There are quite a bit of code improvements you could use to your code.

As to your problem, it's possible that your casing is getting you.  Check your table.  your field might be called isadmin not isAdmin.

As for your code improvements, here's what could help you:

def isAdmin
  if @user.isAdmin
    true
  end
    nil
end

you could accomplish this with one line:

def isAdmin
  @user.isAdmin
end

This bit,

uhelper = UserHelper.new(user)
if !uhelper.isAdmin
  #Only admins can access this page
  redirect_to root_path
end

When you have a simple expression like this, sometimes it's easier to also reduce this to one line:

uhelper = UserHelper.new(user)
redirect_to root_path unless uhelper.isAdmin

However...  Rails standards are to use filters in this case.  Instead of that bit at all, put this in a filter method.

class MyController
  before_filter :check_admin
  ...
  ...
  private
  def check_admin
    redirect_to root_path unless user.isAdmin
  end
end


问:
How to call remote object in controller(MVC) c#
As title, I have a class Services implement interface IServices. And when create a web application C#(using mvc) i want to using IServices but i don't know how to make Controller understand IServices is definitive by Services.
 Can anyone help me?

Any help really appreciated

Thanks

答:
there are a number of approaches to this dependent upon your solution set up. If you implement something like the below, then is should give you a degree of flexibility.

```<code>    public class TestController : Controller
    {
        private IService _myService;

        public TestController (IServices myService)
        {
            _myService = service;
        }

        public TestController() : this (new ServiceImplementation)
        {

        }
    }
</code>```

In the controller we provide a mechanism for constructor dependency injection where a concrete implementation of the interface is provided usually via a DI container or in some cases a custom controller factory. We then also allow the controller to control the default instantiation of the implementation it needs itself if no injection is provided. We achieve this by having a parameter less constructor that passes a concrete implementation to the DI constructor.

NOTE: The above is just one approach and is open to interpretation.

Hope that helps.

Body:
there are a number of approaches to this dependent upon your solution set up. If you implement something like the below, then is should give you a degree of flexibility.

    public class TestController : Controller
    {
        private IService _myService;

        public TestController (IServices myService)
        {
            _myService = service;
        }

        public TestController() : this (new ServiceImplementation)
        {

        }
    }

In the controller we provide a mechanism for constructor dependency injection where a concrete implementation of the interface is provided usually via a DI container or in some cases a custom controller factory. We then also allow the controller to control the default instantiation of the implementation it needs itself if no injection is provided. We achieve this by having a parameter less constructor that passes a concrete implementation to the DI constructor.

NOTE: The above is just one approach and is open to interpretation.

Hope that helps.


问:
Performing A Query On Field Generated From Sub Query
I have two tables, Clients and Jobs.

I am doing a report on clients, and as part of the query, I also return a count of how many jobs we have done for each client. The code is as follows:

```<code>SELECT * ,
(SELECT COUNT(*) FROM Jobs WHERE ClientID = Clients.ID) AS JobsCount
FROM Clients
</code>```

I now need to modify this to allow conditional queries based on the JobsCount, such as "return all clients with more than 100 jobs". Simply adding a where clause on JobsCount doesnt seem to work - Invalid column name 'JobsCount'.

How can i query on a column that is generated through a sub query?

答:
The problem with the correlated subquery you are currently using to find the number of jobs per client, other than that it won't run fast or scale well, is that it is difficult to apply a restriction on the number of jobs.  Instead, you can rephrase your query as a join between Clients and a subquery which finds the number of jobs per each client.  Then, a simple WHERE clause restriction can restrict clients based on how many jobs they have.

```<code>SELECT
    t1.*,
    COALESCE(t2.jobCount, 0) AS jobCount
FROM Clients t1
INNER JOIN
(
    SELECT t1.ID, COUNT(*) AS jobCount
    FROM Clients t1
    INNER JOIN Jobs t2
        ON t1.ID = t2.ClientID
    GROUP BY t1.ID
) t2
    ON t1.ID = t2.ID
WHERE t2.jobCount > 100    -- or whatever restrictions you want
</code>```

Body:
I have two tables, Clients and Jobs.

I am doing a report on clients, and as part of the query, I also return a count of how many jobs we have done for each client. The code is as follows:

SELECT * ,
(SELECT COUNT(*) FROM Jobs WHERE ClientID = Clients.ID) AS JobsCount
FROM Clients

I now need to modify this to allow conditional queries based on the JobsCount, such as "return all clients with more than 100 jobs". Simply adding a where clause on JobsCount doesnt seem to work - Invalid column name 'JobsCount'.

How can i query on a column that is generated through a sub query?

Body:
The problem with the correlated subquery you are currently using to find the number of jobs per client, other than that it won't run fast or scale well, is that it is difficult to apply a restriction on the number of jobs.  Instead, you can rephrase your query as a join between Clients and a subquery which finds the number of jobs per each client.  Then, a simple WHERE clause restriction can restrict clients based on how many jobs they have.

SELECT
    t1.*,
    COALESCE(t2.jobCount, 0) AS jobCount
FROM Clients t1
INNER JOIN
(
    SELECT t1.ID, COUNT(*) AS jobCount
    FROM Clients t1
    INNER JOIN Jobs t2
        ON t1.ID = t2.ClientID
    GROUP BY t1.ID
) t2
    ON t1.ID = t2.ID
WHERE t2.jobCount > 100    -- or whatever restrictions you want


问:
Bigquery - How to zip two arrays into one?
If I have two arrays in BigQuery that I know are of equal size. How can i zip them into one array of structs or an array of two element arrays or similar?

The following query gives me all possible combinations of x and y which is not what I want.

```<code>WITH test AS (
  SELECT
    ['a', 'b', 'c'] as xs,
    [1, 2, 3] as ys
)
SELECT struct(x, y) as pairs
FROM test, unnest(xs) as x, unnest(ys) as y
</code>```

I would like to get something like this:

```<code>+--------+--------+
| pair.x | pair.y |
+--------+--------+
| a      | 1      |
| b      | 2      |
| c      | 3      |
+--------+--------+
</code>```

答:
Use WITH OFFSET and the bracket operator:

```<code>WITH test AS (
  SELECT
    ['a', 'b', 'c'] as xs,
    [1, 2, 3] as ys
)
SELECT struct(x, ys[OFFSET(off)] as y) as pairs
FROM test, unnest(xs) as x WITH OFFSET off;
</code>```

Body:
If I have two arrays in BigQuery that I know are of equal size. How can i zip them into one array of structs or an array of two element arrays or similar?

The following query gives me all possible combinations of x and y which is not what I want.

WITH test AS (
  SELECT
    ['a', 'b', 'c'] as xs,
    [1, 2, 3] as ys
)
SELECT struct(x, y) as pairs
FROM test, unnest(xs) as x, unnest(ys) as y

I would like to get something like this:

+--------+--------+
| pair.x | pair.y |
+--------+--------+
| a      | 1      |
| b      | 2      |
| c      | 3      |
+--------+--------+

Body:
Use WITH OFFSET and the bracket operator:

WITH test AS (
  SELECT
    ['a', 'b', 'c'] as xs,
    [1, 2, 3] as ys
)
SELECT struct(x, ys[OFFSET(off)] as y) as pairs
FROM test, unnest(xs) as x WITH OFFSET off;


问:
Get Location Permissions from User in Android Application
I´m trying to get the users actual location with the typicaly permissions box:
like this:

If anyone knows how to make it , pleas answer.

答:
You can do it like this

In Manifest:

```<code><uses-feature android:name="android.hardware.location.gps" />
</code>```

In Activity where you want this permission request:

```<code>ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
</code>```

Then get the user answer by using this function :

```<code>public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
    case 1: {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        } else {
            // permission denied, boo! Disable the
            // functionality that depends on this permission.
        }
    return;
    }
        // other 'case' lines to check for other
        // permissions this app might request
}
}
</code>```

If the user accept it once, then your app will remember it and you won't need to send this DialogBox anymore. Note that the user could disable it later if he decided to. Then before requesting the location, you would have to test if the permission is still granted :

```<code> public boolean checkLocationPermission()
{
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = this.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
</code>```

Body:
You can do it like this

In Manifest:

<uses-feature android:name="android.hardware.location.gps" />

In Activity where you want this permission request:

ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

Then get the user answer by using this function :

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
    case 1: {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        } else {
            // permission denied, boo! Disable the
            // functionality that depends on this permission.
        }
    return;
    }
        // other 'case' lines to check for other
        // permissions this app might request
}
}

If the user accept it once, then your app will remember it and you won't need to send this DialogBox anymore. Note that the user could disable it later if he decided to. Then before requesting the location, you would have to test if the permission is still granted :

 public boolean checkLocationPermission()
{
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = this.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}


问:
Select a set of cells in one column based on value in another
I have a big set of data in excel of the following form

```<code>A   B
1   stuff1
6   stuff2
3   stuff3
1   stuff4
1   stuff5
7   stuff6
3   stuff7
2   stuff8
.   .
.   .
.   .
5   stuffn
</code>```

and what i would like is some vba code that will select all the cells in B that have a "1" in column A - I will be using this set to do some tasks in another part of my code

any ideas?

Thanks

答:
There is always ADO.</p>

```<code>'Reference: Microsost ActiveX n.n Object Library '
'but it is not necessary, Dim rs and cn as object '
'if you do not wish to use a reference '

Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection

'From: http://support.microsoft.com/kb/246335 '

strFile = Workbooks(1).FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

'Substitute a name range for [Sheet1$] '
'or include a range of cells : [Sheet1&A1:C7] '
'F1 is field 1, because we have no header (HDR: No) '
strSQL = "SELECT * FROM [Sheet3$] " _
       & "WHERE F1=1"

rs.Open strSQL, cn

'Write out to another sheet '
Worksheets(2).Cells(2, 1).CopyFromRecordset rs
</code>```

OwnerDisplayName: mish

Body:
I have a big set of data in excel of the following form

A   B
1   stuff1
6   stuff2
3   stuff3
1   stuff4
1   stuff5
7   stuff6
3   stuff7
2   stuff8
.   .
.   .
.   .
5   stuffn

and what i would like is some vba code that will select all the cells in B that have a "1" in column A - I will be using this set to do some tasks in another part of my code

any ideas?

Thanks

Body:
There is always ADO.

'Reference: Microsost ActiveX n.n Object Library '
'but it is not necessary, Dim rs and cn as object '
'if you do not wish to use a reference '

Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection

'From: http://support.microsoft.com/kb/246335 '

strFile = Workbooks(1).FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

'Substitute a name range for [Sheet1$] '
'or include a range of cells : [Sheet1&A1:C7] '
'F1 is field 1, because we have no header (HDR: No) '
strSQL = "SELECT * FROM [Sheet3$] " _
       & "WHERE F1=1"

rs.Open strSQL, cn

'Write out to another sheet '
Worksheets(2).Cells(2, 1).CopyFromRecordset rs

OwnerDisplayName: Remou


问:
Pythonic difference between two dates in years?
Is there a more efficient way of doing this below? I want to have the difference in years between two dates as a single scalar. Any suggestions are welcome.</p>

```<code>from datetime import datetime
start_date = datetime(2010,4,28,12,33)
end_date = datetime(2010,5,5,23,14)
difference  = end_date - start_date
difference_in_years = (difference.days + difference.seconds/86400)/365.2425
</code>```

答: If you mean efficient in terms of code space then no, that's about the most efficient way to do that.</p>

Body:
Is there a more efficient way of doing this below? I want to have the difference in years between two dates as a single scalar. Any suggestions are welcome.

from datetime import datetime
start_date = datetime(2010,4,28,12,33)
end_date = datetime(2010,5,5,23,14)
difference  = end_date - start_date
difference_in_years = (difference.days + difference.seconds/86400)/365.2425


问:
How to loop through the inner nodes in xml using xslt
I need to loop through the XML which will have multiple inner nodes. I have a sample xml given below

```<code>    <?xml version ="1.0" encoding ="utf-8" ?>
    <TestUser>
      <Users>
        <UserData name="test123" address="USA"/>
        <UserCommunication>
          <Communication mode="Te" value="123456879"/>
          <Qualification>
            <PG value="No"></PG>
          </Qualification>
            <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
      <Users>
        <UserData name="test124" address="UK"/>
        <UserCommunication>
          <Communication mode="Te" value="1567894525"/>
          <Qualification>
            <PG value="No"></PG>
          </Qualification>
           <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
      <Users>
        <UserData name="test125" address="INDIA"/>
        <UserCommunication>
          <Communication mode="Te" value="5465897845"/>
          <Qualification>
            <PG value="YES"></PG>
          </Qualification>
           <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
    </TestUser>
</code>```

The Output should be in text view as below

```<code>test123 USA Te 123456879 No YES
test124 UK Te 1567894525 No YES
test125 INDIA Te 5465897845 YES No
</code>```

I also required it in HTML View.

Can anyone help me to get this?

Thanks in advance.

答:
Assuming XSLT 2.0 you can simply use

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output method="text"/>

    <xsl:template match="/">
        <xsl:value-of select="//Users/string-join(.//@*, ' ')" separator="
"/>
    </xsl:template>

</xsl:stylesheet>
</code>```

and the result is

```<code>test123 USA Te 123456879 No YES
test124 UK Te 1567894525 No YES
test125 INDIA Te 5465897845 YES YES
</code>```

If you want HTML output then you can use

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output method="html"/>

    <xsl:template match="/">
      <html>
        <body>
           ```
             <xsl:value-of select="//Users/string-join(.//@*, ' ')" separator="
"/>
           ```
         </body>
       </html>
    </xsl:template>

</xsl:stylesheet>
</code>```

to use the same approach or of course write a template to match and map Users to HTML tr elements and a template to match and map Users//*/@* to HTML td elements.

Body:
I need to loop through the XML which will have multiple inner nodes. I have a sample xml given below

    <?xml version ="1.0" encoding ="utf-8" ?>
    <TestUser>
      <Users>
        <UserData name="test123" address="USA"/>
        <UserCommunication>
          <Communication mode="Te" value="123456879"/>
          <Qualification>
            <PG value="No"></PG>
          </Qualification>
            <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
      <Users>
        <UserData name="test124" address="UK"/>
        <UserCommunication>
          <Communication mode="Te" value="1567894525"/>
          <Qualification>
            <PG value="No"></PG>
          </Qualification>
           <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
      <Users>
        <UserData name="test125" address="INDIA"/>
        <UserCommunication>
          <Communication mode="Te" value="5465897845"/>
          <Qualification>
            <PG value="YES"></PG>
          </Qualification>
           <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
    </TestUser>

The Output should be in text view as below

test123 USA Te 123456879 No YES
test124 UK Te 1567894525 No YES
test125 INDIA Te 5465897845 YES No

I also required it in HTML View.

Can anyone help me to get this?

Thanks in advance.

Body:
Assuming XSLT 2.0 you can simply use

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output method="text"/>

    <xsl:template match="/">
        <xsl:value-of select="//Users/string-join(.//@*, ' ')" separator="&#10;"/>
    </xsl:template>

</xsl:stylesheet>

and the result is

test123 USA Te 123456879 No YES
test124 UK Te 1567894525 No YES
test125 INDIA Te 5465897845 YES YES

If you want HTML output then you can use

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:output method="html"/>

    <xsl:template match="/">
      <html>
        <body>
           <pre>
             <xsl:value-of select="//Users/string-join(.//@*, ' ')" separator="&#10;"/>
           </pre>
         </body>
       </html>
    </xsl:template>

</xsl:stylesheet>

to use the same approach or of course write a template to match and map Users to HTML tr elements and a template to match and map Users//*/@* to HTML td elements.


问:
How to add a loader to a page till I get the data in the background from API in xamarin android MVVM/mono
I am able to get the data from the API which I am using it to bind the data in different ways but when getting the data is going slow, black screen is displayed for some time and then the data is getting loaded so I was trying to rectify that and make the data getting in background(async await) and then bind that to the view when the data is available locally.
How to do that?</p>

答:
Follow this sample layout skeleton for those screens where you need to show the activity indicator (Loader):

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:id="@+id/parent_layout">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">
        <TextView
            android:id="@+id/txt1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Text 1"
            android:textSize="18dp"
            android:textColor="@android:color/black"
            android:paddingTop="20dp" />
        <TextView
            android:id="@+id/txt2"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Text 2"
            android:textSize="18dp"
            android:textColor="@android:color/black"
            android:paddingTop="20dp" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/loader"
        android:visibility="invisible">
        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:indeterminate="true"/>
    </FrameLayout>

</RelativeLayout>
</code>```

Accordingly you need to control the FrameLayout from it's id containing the progress bar from your code end either in activity or if you are using fragment to make it visible during the service call and set the visibility to invisible once you received the response.

ContentLicense: CC BY-SA 4.0

Body:
Follow this sample layout skeleton for those screens where you need to show the activity indicator (Loader):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:id="@+id/parent_layout">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">
        <TextView
            android:id="@+id/txt1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Text 1"
            android:textSize="18dp"
            android:textColor="@android:color/black"
            android:paddingTop="20dp" />
        <TextView
            android:id="@+id/txt2"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Text 2"
            android:textSize="18dp"
            android:textColor="@android:color/black"
            android:paddingTop="20dp" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/loader"
        android:visibility="invisible">
        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:indeterminate="true"/>
    </FrameLayout>

</RelativeLayout>

Accordingly you need to control the FrameLayout from it's id containing the progress bar from your code end either in activity or if you are using fragment to make it visible during the service call and set the visibility to invisible once you received the response.


问:
chosen:update not working in $.ajax success call
I am going to try to be as clear as possible. My issue is that Chosen isn’t updating my dropdown at all. I am not having an issue with it working correctly. The issue is within my $.ajax success call I am pulling data from the database to on an update to repopulate the Chosen dropdown with the previously selected items. My first screen shot shows that the data does come back and populates the dropdown but at the first and second images shows it doesn’t do it correctly because of the chosen:update not working correctly, based on what I understand at this point.

I am including the code and the rendered HTML for your review. Any insight and/or assistance that you can provide would be most appreciated.

--js--

$('#ddlDistributionStates').chosen();

$.ajax...
success: function (data) {

$(data).each(function (index, item) {
    var ds = item.DistributionStates.split(",");
    $.each(ds, function (i, p) {
      $("#ddlDistributionStates_chosen ul").prepend('
' + p + '
');
      });

      $("#ddlDistributionStates").trigger("chosen:updated");
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>--HTML--

<div class="row top-buffer">
 <div class="col-xs-6">
  <div class="input-group">
  <span class="input-group-addon">Current States Distribution</span>
   <select name="DistributionStates" id="ddlDistributionStates" multiple="multiple" class="form-control chosen-select" data-placeholder="Select State(s)">
   <option>Alabama </option>
   <option>Alaska </option>
   <option>Arizona </option>
   <option>Arkansas </option>
   <option>California </option>
   <option>Colorado </option>
   <option>Connecticut </option>
   <option>Delaware </option>
  </select>
  </div>
 </div>
</div>

--Rendered HTML--

<div class="col-xs-6">
 <div class="input-group">
  <span class="input-group-addon">Current States Distribution</span>
   <select name="DistributionStates" id="ddlDistributionStates" multiple="multiple" class="form-control chosen-select" data-placeholder="Select State(s)" style="display: none;">
   <option>Alabama </option>
   <option>Alaska </option>
   <option>Arizona </option>
   <option>Arkansas </option>
   <option>California </option>
   <option>Colorado </option>
   <option>Connecticut </option>
   <option>Delaware </option>
  </select>
  <div class="chosen-container chosen-container-multi chosen-with-drop chosen-container-active" style="width: 364px;" title="" id="ddlDistributionStates_chosen">
   <ul class="chosen-choices">
    <li class="search-choice"><span>Arkansas</span></li>
    <li class="search-choice"><span>Alaska</span></li>
    <li class="search-field"><input type="text" value="Select State(s)" class="default valid" autocomplete="off" style="width: 118px;" aria-invalid="false"></li>
   </ul>
   <div class="chosen-drop">
     <ul class="chosen-results"><li class="active-result" data-option-array-index="0">Alabama </li>
     <li class="active-result" data-option-array-index="1">Alaska </li>
     <li class="active-result" data-option-array-index="2">Arizona </li>
     <li class="active-result" data-option-array-index="3">Arkansas </li>
     <li class="active-result" data-option-array-index="4">California </li>
     <li class="active-result" data-option-array-index="5">Colorado </li>
     <li class="active-result" data-option-array-index="6">Connecticut </li>
     <li class="active-result" data-option-array-index="7">Delaware </li>
    </ul>
   </div>
  </div>
 </div>
</div></code>```

答:
In your code you are trying to append new data to the rendered html.Instead of that append the new options to the select and call $("#ddlDistributionStates").trigger("chosen:updated");.

Check this sample code.In this code i'm updating the chosen on button click.You can use the same method after the ajax call

$(function(){

 $('#ddlDistributionStates').chosen();

 $('#updateSelect').click(function(){
   $('#ddlDistributionStates option').remove();

   var html ='';
   for(var i=0; i<= 10;i++){
     html += "<option value='"+i+"' selected>"+i+"</option>";
   }

     $('#ddlDistributionStates').append($(html));

     $("#ddlDistributionStates").trigger("chosen:updated");

  })

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.min.css" rel="stylesheet"/>

<button id="updateSelect">Click to update select</button>
<div class="row top-buffer">
 <div class="col-xs-6">
  <div class="input-group">
  <span class="input-group-addon">Current States Distribution</span>
   <select name="DistributionStates" id="ddlDistributionStates" multiple="multiple" class="form-control chosen-select" data-placeholder="Select State(s)">
   <option selected>Alabama </option>
   <option selected>Alaska </option>
   <option selected>Arizona </option>
   <option selected>Arkansas </option>
   <option>California </option>
   <option>Colorado </option>
   <option>Connecticut </option>
   <option>Delaware </option>
  </select>
  </div>
 </div>
</div></code>```

Body:
I am going to try to be as clear as possible. My issue is that Chosen isn’t updating my dropdown at all. I am not having an issue with it working correctly. The issue is within my $.ajax success call I am pulling data from the database to on an update to repopulate the Chosen dropdown with the previously selected items. My first screen shot shows that the data does come back and populates the dropdown but at the first and second images shows it doesn’t do it correctly because of the chosen:update not working correctly, based on what I understand at this point.

I am including the code and the rendered HTML for your review. Any insight and/or assistance that you can provide would be most appreciated.

--js--

$('#ddlDistributionStates').chosen();

$.ajax...
success: function (data) {

$(data).each(function (index, item) {
    var ds = item.DistributionStates.split(",");
    $.each(ds, function (i, p) {
      $("#ddlDistributionStates_chosen ul").prepend('
' + p + '
');
      });

      $("#ddlDistributionStates").trigger("chosen:updated");
    }
}

--HTML--

  Current States Distribution
   <select name="DistributionStates" id="ddlDistributionStates" multiple="multiple" class="form-control chosen-select" data-placeholder="Select State(s)">
   <option>Alabama </option>
   <option>Alaska </option>
   <option>Arizona </option>
   <option>Arkansas </option>
   <option>California </option>
   <option>Colorado </option>
   <option>Connecticut </option>
   <option>Delaware </option>
  </select>

--Rendered HTML--

  Current States Distribution
   <select name="DistributionStates" id="ddlDistributionStates" multiple="multiple" class="form-control chosen-select" data-placeholder="Select State(s)" style="display: none;">
   <option>Alabama </option>
   <option>Alaska </option>
   <option>Arizona </option>
   <option>Arkansas </option>
   <option>California </option>
   <option>Colorado </option>
   <option>Connecticut </option>
   <option>Delaware </option>
  </select>

Arkansas

Alaska

<input type="text" value="Select State(s)" class="default valid" autocomplete="off" style="width: 118px;" aria-invalid="false">

Alabama

Alaska

Arizona

Arkansas

California

Colorado

Connecticut

Delaware

Body:
In your code you are trying to append new data to the rendered html.Instead of that append the new options to the select and call $("#ddlDistributionStates").trigger("chosen:updated");.

Check this sample code.In this code i'm updating the chosen on button click.You can use the same method after the ajax call

$(function(){

 $('#ddlDistributionStates').chosen();

 $('#updateSelect').click(function(){
   $('#ddlDistributionStates option').remove();

   var html ='';
   for(var i=0; i<= 10;i++){
     html += "<option value='"+i+"' selected>"+i+"</option>";
   }

     $('#ddlDistributionStates').append($(html));

     $("#ddlDistributionStates").trigger("chosen:updated");

  })

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.min.css" rel="stylesheet"/>

<button id="updateSelect">Click to update select</button>
<div class="row top-buffer">
 <div class="col-xs-6">
  <div class="input-group">
  <span class="input-group-addon">Current States Distribution</span>
   <select name="DistributionStates" id="ddlDistributionStates" multiple="multiple" class="form-control chosen-select" data-placeholder="Select State(s)">
   <option selected>Alabama </option>
   <option selected>Alaska </option>
   <option selected>Arizona </option>
   <option selected>Arkansas </option>
   <option>California </option>
   <option>Colorado </option>
   <option>Connecticut </option>
   <option>Delaware </option>
  </select>
  </div>
 </div>
</div>


问:
Get the latest date from grouped MySQL data
I have the following data in my database:

```<code>|NO | model | date     |
+---+-------+----------+
|1  | bee   |2011-12-01|
|2  | bee   |2011-12-05|
|3  | bee   |2011-12-12|
|4  | tar   |2011-12-13|
</code>```

I want to get the latest date of each model group:

```<code>| model | date     |
+-------+----------+
| bee   |2011-12-12|
| tar   |2011-12-13|
</code>```

I tried:

```<code>SELECT model, date
FROM doc
WHERE date ........????? //what is the next?
GROUP BY model
</code>```

答:
Subquery giving dates. We are not linking with the model. So below query solves the problem.

If there are duplicate dates/model can be avoided by the following query.

```<code>select t.model, t.date
from doc t
inner join (select model, max(date) as MaxDate from doc  group by model)
tm on t.model = tm.model and t.date = tm.MaxDate
</code>```

Body:
I have the following data in my database:

|NO | model | date     |
+---+-------+----------+
|1  | bee   |2011-12-01|
|2  | bee   |2011-12-05|
|3  | bee   |2011-12-12|
|4  | tar   |2011-12-13|

I want to get the latest date of each model group:

| model | date     |
+-------+----------+
| bee   |2011-12-12|
| tar   |2011-12-13|

I tried:

SELECT model, date
FROM doc
WHERE date ........????? //what is the next?
GROUP BY model

Body:
Subquery giving dates. We are not linking with the model. So below query solves the problem.

If there are duplicate dates/model can be avoided by the following query.

select t.model, t.date
from doc t
inner join (select model, max(date) as MaxDate from doc  group by model)
tm on t.model = tm.model and t.date = tm.MaxDate


问:
Rails - ActiveAdmin create relationship count column sortable
I am working on ActiveAdmin and I am trying to display a column name Active Jobs with a count

There are three models involved in getting this count

```<code> 1. Staffroom
 2. StaffroomPage
 3. Job

class StaffroomPage < ActiveRecord::Base
  belongs_to :staffroom

class Staffroom < ActiveRecord::Base
  has_one :staffroom_page
  has_many :jobs

class Job < ActiveRecord::Base
  belongs_to :staffroom
</code>```

Now inside the admin/staffroom_pages.rb I am able to display the column and the count

```<code>column :active_jobs, sortable: 'active_jobs' do |staffroom_page|
  staffroom_page.staffroom.jobs.where(:state=> 'active').count
end
</code>```

However I am not able to sort the data via active_jobs and I see the following error

PG::UndefinedColumn: ERROR:  column "active_jobs" does not exist

So the question is how to make the sort to work for column active_jobs, please note that this is not the only sortable column on page, almost all columns are sortable and this is the only one not working.

答:
From this post on the activeadmin github a possible workaround to this problem would be</p>

```<code>index do
  column :active_jobs, sortable: 'active_jobs' do |staffroom_page|
    staffroom_page.staffroom.jobs.where(:state=> 'active').count
  end
end

controller do

def scoped_collection
  super.joins(
    %(LEFT JOIN "jobs" ON "staffroom_pages"."staffroom_id" = "jobs"."staffroom_id"
        AND "jobs"."state" = 'active'))
      .select('staffroom_pages.*, COUNT(jobs.id) as active_jobs')
      .group('staffroom_pages.id')
  end
end
</code>```

Body:
I am working on ActiveAdmin and I am trying to display a column name Active Jobs with a count

There are three models involved in getting this count

 1. Staffroom
 2. StaffroomPage
 3. Job

class StaffroomPage < ActiveRecord::Base
  belongs_to :staffroom

class Staffroom < ActiveRecord::Base
  has_one :staffroom_page
  has_many :jobs

class Job < ActiveRecord::Base
  belongs_to :staffroom

Now inside the admin/staffroom_pages.rb I am able to display the column and the count

column :active_jobs, sortable: 'active_jobs' do |staffroom_page|
  staffroom_page.staffroom.jobs.where(:state=> 'active').count
end

However I am not able to sort the data via active_jobs and I see the following error

PG::UndefinedColumn: ERROR:  column "active_jobs" does not exist

So the question is how to make the sort to work for column active_jobs, please note that this is not the only sortable column on page, almost all columns are sortable and this is the only one not working.

Body:
From this post on the activeadmin github a possible workaround to this problem would be

index do
  column :active_jobs, sortable: 'active_jobs' do |staffroom_page|
    staffroom_page.staffroom.jobs.where(:state=> 'active').count
  end
end

controller do

def scoped_collection
  super.joins(
    %(LEFT JOIN "jobs" ON "staffroom_pages"."staffroom_id" = "jobs"."staffroom_id"
        AND "jobs"."state" = 'active'))
      .select('staffroom_pages.*, COUNT(jobs.id) as active_jobs')
      .group('staffroom_pages.id')
  end
end


问:
How to hack an input field to fire md-datepicker when I click on it
How can I turn an input text to fire md-datepicker ? and get something like this:

答:
You can use md-input-container and md-datepicker and customize the skin with classes. Hope this helps..</p>

```<code><div class="form-group form-group-sm row">
    <div class="col-md-6">
        <div ng-class="{ 'has-error': ....}">
            <label for="startDate" class="required-field">Start Date</label>
            <md-input-container class="custom-md-container">
                <md-datepicker class="customDatePicker" id="startDate" md-placeholder="Start Date" name="startDate" md-open-on-focus="true" ng-model=".." required></md-datepicker>
            </md-input-container>
        </div>
    </div>
</div>
</code>```

Body:
You can use md-input-container and md-datepicker and customize the skin with classes. Hope this helps..

<div class="form-group form-group-sm row">
    <div class="col-md-6">
        <div ng-class="{ 'has-error': ....}">
            <label for="startDate" class="required-field">Start Date</label>
            <md-input-container class="custom-md-container">
                <md-datepicker class="customDatePicker" id="startDate" md-placeholder="Start Date" name="startDate" md-open-on-focus="true" ng-model=".." required></md-datepicker>
            </md-input-container>
        </div>
    </div>
</div>


问:
Java Exception java.lang.AbstractMethodError
How can I solve this exception:

```<code>Exception in thread "main" java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
    at org.apache.commons.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:914)
...
</code>```

I read that this error is something about libraries/ jdk but I can't find a good way to solve it. I need some help from you. Thank you!

答: If you provide a validation query, you can avoid upgrading your driver.</p>

Body:
How can I solve this exception:

Exception in thread "main" java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
    at org.apache.commons.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:914)
...

I read that this error is something about libraries/ jdk but I can't find a good way to solve it. I need some help from you. Thank you!


问:
using dynamic linq to filter a list of objects
I have two class like this

```<code>public class Error{
   public string Code{get;set;}
   public string Description{get;set;}
}

public class Row{
   public List<Error> Errors {get;set;}
   ....
}
</code>```

So, for each row, can exists more errors.
It's possible using dynamic linq select the row that have an error code(for example Code1)?

So, if the row contains Code1 and Code2, i want select the row.

if in the example below query has a list of rows i want a query like this

```<code>query.Where("Errors != null && Errors.Code.contains('Code1')")
</code>```

答:
I think this is what you are looking for:

```<code>var codes=new List<string>{"Code1","Code2"};
// given a list of codes you want those rows that contains all codes
var result= rows.Where(r=> codes.All(c=>r.Errors.Any(e=>e.Code==c)));
</code>```

To avoid the null checking of the error list, I suggest you initialize the list in an empty constructor:

```<code>public Row()
{
   Errors=new List<Error>();
}
</code>```

Body:
I have two class like this

public class Error{
   public string Code{get;set;}
   public string Description{get;set;}
}

public class Row{
   public List<Error> Errors {get;set;}
   ....
}

So, for each row, can exists more errors.
It's possible using dynamic linq select the row that have an error code(for example Code1)?

So, if the row contains Code1 and Code2, i want select the row.

if in the example below query has a list of rows i want a query like this

query.Where("Errors != null && Errors.Code.contains('Code1')")

Body:
I think this is what you are looking for:

var codes=new List<string>{"Code1","Code2"};
// given a list of codes you want those rows that contains all codes
var result= rows.Where(r=> codes.All(c=>r.Errors.Any(e=>e.Code==c)));

To avoid the null checking of the error list, I suggest you initialize the list in an empty constructor:

public Row()
{
   Errors=new List<Error>();
}


问:
Wordpress: isHome function
is there any native function in wordpress to check if the page is home page?

because i want to make some script like this

```<code>if (isHome){
    include 'somescript.php';
}
</code>```

PS:
i use wordpress 3.0.1

thanks,

GusDe

答:
There is a is_home() function, but you may need to use is_front_page() instead.

See this page for details on page-identifying functions.

Title: Wordpress: isHome function

Body:
is there any native function in wordpress to check if the page is home page?

because i want to make some script like this

if (isHome){
    include 'somescript.php';
}

PS:
i use wordpress 3.0.1

thanks,

GusDe