问:
Jackson Serialize to Template List
I have a class like this:

```<code>public class Garage<T> {
    private List<T> vehicles;

    public Garage() {
    }

    public Garage(List<T> vehicles) {
        this.vehicles = Collections.unmodifiableList(vehicles);
    }

    public List<T> getVehicles() {
        return vehicles;
    }
}

public class Car {
    private Type type;
    private Make make;
    private Model model;
    private String name;
}

public class Boat {
    private double weight;
    private Make make;
    private Model model;
    private String name;
}
</code>```

And a Spring API endpoint like this:

```<code>@RestController
public class CarController {
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity<List<Vehicles>> addCar(@RequestBody Garage<Car> cars) {
        //logic
    }
}
</code>```

When I try to pass in a JSON input that looks like this:

```<code>{
   "vehicles":[
      {
         "type":SEDAN,
         "make":HONDA,
         "model":ACCORD,
         "name":"My Awesome Car"
      },
      {
         "type":SUV,
         "make":HONDA,
         "model":CRV,
         "name":"My Awesome Car 2"
      }
   ]
}
</code>```

I get the error:

```<code>org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:292) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:231) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:203) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:132) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:380) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:59) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:74) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1193) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.processHandlerException(TestDispatcherServlet.java:112) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1030) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) [tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at net.api.controllers.CarControllerTest.test(CarControllerTest.java:46) [test-classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) [junit-4.12.jar:4.12]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) [junit-4.12.jar:4.12]
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:284) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.SerializerProvider.mappingException(SerializerProvider.java:1110) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.SerializerProvider.reportMappingProblem(SerializerProvider.java:1135) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:69) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:32) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1429) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:951) ~[jackson-databind-2.8.8.jar:2.8.8]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:285) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 67 common frames omitted
</code>```

But if I change the api endpoint @RequestBody to @RequestBody Garage cars then Jackson deserializes just fine but the Garage object contains a list of HashMap instances rather than Car instances.

How do you fix this?

答:
I figured out the issue. It's because the Car and Boat class didn't have a default empty constructor. But after adding:

```<code>public Car() {
}
</code>```

It worked

Title: Jackson Serialize to Template List

Body:
I have a class like this:

public class Garage<T> {
    private List<T> vehicles;

    public Garage() {
    }

    public Garage(List<T> vehicles) {
        this.vehicles = Collections.unmodifiableList(vehicles);
    }

    public List<T> getVehicles() {
        return vehicles;
    }
}

public class Car {
    private Type type;
    private Make make;
    private Model model;
    private String name;
}

public class Boat {
    private double weight;
    private Make make;
    private Model model;
    private String name;
}

And a Spring API endpoint like this:

@RestController
public class CarController {
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResponseEntity<List<Vehicles>> addCar(@RequestBody Garage<Car> cars) {
        //logic
    }
}

When I try to pass in a JSON input that looks like this:

{
   "vehicles":[
      {
         "type":SEDAN,
         "make":HONDA,
         "model":ACCORD,
         "name":"My Awesome Car"
      },
      {
         "type":SUV,
         "make":HONDA,
         "model":CRV,
         "name":"My Awesome Car 2"
      }
   ]
}

I get the error:

org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:292) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:231) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:203) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:132) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:380) ~[spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:59) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:74) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1193) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.processHandlerException(TestDispatcherServlet.java:112) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1030) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) [tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.5.6.jar:8.5.6]
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108) [spring-boot-1.5.0.RC1.jar:1.5.0.RC1]
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at net.api.controllers.CarControllerTest.test(CarControllerTest.java:46) [test-classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) [junit-4.12.jar:4.12]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) [junit-4.12.jar:4.12]
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.PushbackInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.http.converter.HttpMessageNotReadableException["cause"]->com.fasterxml.jackson.databind.JsonMappingException["location"]->com.fasterxml.jackson.core.JsonLocation["sourceRef"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:284) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.SerializerProvider.mappingException(SerializerProvider.java:1110) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.SerializerProvider.reportMappingProblem(SerializerProvider.java:1135) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:69) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:32) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1429) ~[jackson-databind-2.8.8.jar:2.8.8]
    at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:951) ~[jackson-databind-2.8.8.jar:2.8.8]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:285) ~[spring-web-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 67 common frames omitted

But if I change the api endpoint @RequestBody to @RequestBody Garage cars then Jackson deserializes just fine but the Garage object contains a list of HashMap instances rather than Car instances.

How do you fix this?

Body:
I figured out the issue. It's because the Car and Boat class didn't have a default empty constructor. But after adding:

public Car() {
}

It worked


来源: stackexchange

问:
How to divide time interval into parts of varying length?
I have a time interval from 0 to t.
I want to divide this interval into a cumulative sequence in a cycle of 2.25, 2.25 and 1.5, in the following manner:

input:

```<code>start = 0
stop = 19
</code>```

output:

```<code>sequence = [0, 2.25, 4.5, 6, 8.25, 10.5, 12, 14.25, 16.5, 18, 19]
</code>```

How can I do this in Python?

The idea is to divide a time period into cycles of 6 hours, each cycle consisting of three sequential operations that last 2.25 h, 2.25 h and 1.5 h respectively. Or is there an alternative to using 'milestones' for this purpose?

答:
You could use a generator:

```<code>def interval(start, stop):
    cur = start
    yield cur                # return the start value
    while cur < stop:
        for increment in (2.25, 2.25, 1.5):
            cur += increment
            if cur >= stop:  # stop as soon as the value is above the stop (or equal)
                break
            yield cur
    yield stop               # also return the stop value
</code>```

It works for the start and stop you proposed:

```<code>>>> list(interval(0, 19))
[0, 2.25, 4.5, 6.0, 8.25, 10.5, 12.0, 14.25, 16.5, 18.0, 19]
</code>```

You could also use itertools.cycle to avoid the outer loop:

```<code>import itertools

def interval(start, stop):
    cur = start
    yield start
    for increment in itertools.cycle((2.25, 2.25, 1.5)):
        cur += increment
        if cur >= stop:
            break
        yield cur
    yield stop
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a time interval from 0 to t.
I want to divide this interval into a cumulative sequence in a cycle of 2.25, 2.25 and 1.5, in the following manner:

input:

start = 0
stop = 19

output:

sequence = [0, 2.25, 4.5, 6, 8.25, 10.5, 12, 14.25, 16.5, 18, 19]

How can I do this in Python?

The idea is to divide a time period into cycles of 6 hours, each cycle consisting of three sequential operations that last 2.25 h, 2.25 h and 1.5 h respectively. Or is there an alternative to using 'milestones' for this purpose?

Body:
You could use a generator:

def interval(start, stop):
    cur = start
    yield cur                # return the start value
    while cur < stop:
        for increment in (2.25, 2.25, 1.5):
            cur += increment
            if cur >= stop:  # stop as soon as the value is above the stop (or equal)
                break
            yield cur
    yield stop               # also return the stop value

It works for the start and stop you proposed:

>>> list(interval(0, 19))
[0, 2.25, 4.5, 6.0, 8.25, 10.5, 12.0, 14.25, 16.5, 18.0, 19]

You could also use itertools.cycle to avoid the outer loop:

import itertools

def interval(start, stop):
    cur = start
    yield start
    for increment in itertools.cycle((2.25, 2.25, 1.5)):
        cur += increment
        if cur >= stop:
            break
        yield cur
    yield stop


问:
Display number of actions by each user, grouped by the action ID
I did the following query for solving this question: Count how many action each user performed (Django admin).

```<code>SELECT Count(l.id),
       u.username,
       u.first_name,
       u.last_name,
       u.is_staff
FROM   django_admin_log l, auth_user u
WHERE  u.id = l.user_id
GROUP  BY u.id
ORDER  BY 1 DESC;
</code>```

Now I want to Display how many actions where performed by each user, grouped by the action ID. The idea is the same of the query above, but knowing they action type.

django_admin_log table structure:

```<code>+-----------------+----------------------+------+-----+---------+----------------+
| Field           | Type                 | Null | Key | Default | Extra          |
+-----------------+----------------------+------+-----+---------+----------------+
| id              | int(11)              | NO   | PRI | NULL    | auto_increment |
| action_time     | datetime             | NO   |     | NULL    |                |
| user_id         | int(11)              | NO   | MUL | NULL    |                |
| content_type_id | int(11)              | YES  | MUL | NULL    |                |
| object_id       | longtext             | YES  |     | NULL    |                |
| object_repr     | varchar(200)         | NO   |     | NULL    |                |
| action_flag     | smallint(5) unsigned | NO   |     | NULL    |                |
| change_message  | longtext             | NO   |     | NULL    |                |
+-----------------+----------------------+------+-----+---------+----------------+
</code>```

Thanks :)

答:
You should group by for the col not in aggregation function
and in your case you should group by for user .. instance</p>

```<code>  SELECT Count(l.id),
         u.username,
         u.first_name,
         u.last_name,
         u.is_staff
  FROM   django_admin_log l, auth_user u
  WHERE  u.id = l.user_id
  GROUP  BY
          u.username,
         u.first_name,
         u.last_name,
         u.is_staff
  ORDER  BY 1 DESC;
</code>```

Body:
I did the following query for solving this question: Count how many action each user performed (Django admin).

SELECT Count(l.id),
       u.username,
       u.first_name,
       u.last_name,
       u.is_staff
FROM   django_admin_log l, auth_user u
WHERE  u.id = l.user_id
GROUP  BY u.id
ORDER  BY 1 DESC;

Now I want to Display how many actions where performed by each user, grouped by the action ID. The idea is the same of the query above, but knowing they action type.

django_admin_log table structure:

+-----------------+----------------------+------+-----+---------+----------------+
| Field           | Type                 | Null | Key | Default | Extra          |
+-----------------+----------------------+------+-----+---------+----------------+
| id              | int(11)              | NO   | PRI | NULL    | auto_increment |
| action_time     | datetime             | NO   |     | NULL    |                |
| user_id         | int(11)              | NO   | MUL | NULL    |                |
| content_type_id | int(11)              | YES  | MUL | NULL    |                |
| object_id       | longtext             | YES  |     | NULL    |                |
| object_repr     | varchar(200)         | NO   |     | NULL    |                |
| action_flag     | smallint(5) unsigned | NO   |     | NULL    |                |
| change_message  | longtext             | NO   |     | NULL    |                |
+-----------------+----------------------+------+-----+---------+----------------+

Thanks :)

Body:
You should group by for the col not in aggregation function
and in your case you should group by for user .. instance

  SELECT Count(l.id),
         u.username,
         u.first_name,
         u.last_name,
         u.is_staff
  FROM   django_admin_log l, auth_user u
  WHERE  u.id = l.user_id
  GROUP  BY
          u.username,
         u.first_name,
         u.last_name,
         u.is_staff
  ORDER  BY 1 DESC;


问:
Troubleshooting TensorFlow input pipeline for CSV file queue
I'm new to TensorFlow and am training a SOM model based on Sachin Joglekar's blog (https://codesachin.wordpress.com/2015/11/28/self-organizing-maps-with-googles-tensorflow/) using multiple CSV files as input. I followed the tutorial at https://www.tensorflow.org/programmers_guide/reading_data for reading from a CSV file queue in minibatches. My code is running, but I want to print out the decoded CSV input from the reader to verify that the input pipeline is working correctly. Since the CSV file input is not part of the graph, I am unable to print it using Tensor.eval(self.sess). When I try to print out the decoded record labels using self.label.eval(session = tf.Session(graph=self.label.graph)), my script hangs and does not give any output. Is there a way for me to verify that my input pipeline is working? Here are the relevant snippets of my code:

Main function

```<code>def main(argv):
    som = SOM(somDim1, somDim2, windowSizes[win], iterations, learningRate,
    neighborhood, fileNameList, batchSize)
    som.train(batchSize, fileNameList, windowSizes[win])
</code>```

Graph

```<code>def __init__(self, m, n, dim, iterations, alpha, sigma, fileNameList, batchSize):

    ##INITIALIZE GRAPH
    self.graph = tf.Graph()

    ##POPULATE GRAPH WITH NECESSARY COMPONENTS
    with self.graph.as_default():

        ##PLACEHOLDERS FOR TRAINING INPUTS
        #These should be placeholders according to the TensorFlow framework,
        #but we are declaring them as variables so that we can assign them directly
        #to values read in from the CSV files.
        batchInputLg = np.zeros((dim, batchSize))
        labelFloat = np.zeros((3, batchSize))
        self.label = tf.cast(labelFloat, "string")
        self.batchInput = tf.cast(batchInputLg, "float32")

        """
        ...the rest of the graph...
        """

        self.trainingOp = tf.assign(self.weightageVects, newWeightagesOp)

        ##INITIALIZE SESSION
        self.sess = tf.Session()

        ##INITIALIZE VARIABLES
        initOp = tf.global_variables_initializer()
        self.sess.run(initOp)
</code>```

Input pipeline functions

```<code>"""
Read in the features and metadata from the CSV files for each chromosome.
"""
def readFromCsv(self, fileNameQ, dim):
    reader = tf.TextLineReader()
    _, csvLine = reader.read(fileNameQ)
    recordDefaults = [["\0"] for cl in range(dim - 1)]
    recordStr = tf.decode_csv(csvLine, record_defaults=recordDefaults)
    self.label = tf.stack(recordStr[0:2])
    #self.label.eval(session = tf.Session(graph=self.label.graph))
    self.features = tf.to_float(tf.stack(recordStr[3:dim - 1]))
    return (self.features, self.label)

"""
Read in the features and metadata from the CSV files for each chromosome.
"""
def inputPipeline(self, batchSize, fileNameList, dim, num_epochs=None):
    fileNameQ = tf.train.string_input_producer(fileNameList, shuffle = True)
    minAfterDequeue = 10000
    capacity = minAfterDequeue + 3 * batchSize
    example, label = self.readFromCsv(fileNameQ, dim)
    exampleBatchStr, labelBatch = tf.train.shuffle_batch([example, label], batch_size=batchSize, capacity=capacity, min_after_dequeue=minAfterDequeue)
    exampleBatch = tf.cast(exampleBatchStr, "float")
    return (exampleBatch, labelBatch)
</code>```

Training function

```<code>def train(self, batchSize, fileNameList, dim):
    #Start the queue runners.
    # Start input enqueue threads.
    coordFile = tf.train.Coordinator()
    self.coord = tf.train.Coordinator()
    threadsFile = tf.train.start_queue_runners(sess=self.sess, coord=coordFile)
    self.threads = tf.train.start_queue_runners(sess=self.sess, coord=self.coord)

    #Training iterations
    self.iterationInput = 0
    try:
        for iter in range(self.iterations):
            #Train with each vector one by one
            self.iterationInput += 1
            while not self.coord.should_stop():
                #Fill in input data.
                [self.batchInput, self.label] = self.inputPipeline(batchSize, fileNameList, dim)
                self.sess.run(self.trainingOp)

    except tf.errors.OutOfRangeError:
        print('Done training -- epoch limit reached')

    # When done, ask the threads to stop.
    self.coord.request_stop()
</code>```

答:
I figured out the solution. Instead of initializing the label and batch input tensors in the graph and assigning them within the train() function, I should have placed the assignment statement inside the graph, like so:

```<code>##TRAINING INPUTS
self.batchInput, self.label = self.inputPipeline(batchSize, fileNameList, dim)
</code>```

Then, the train function becomes:

```<code>def train(self, batchSize, fileNameList, dim):
    with self.sess:
        # Start populating the filename queue.
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)

        #Training iterations
        self.iterationInput = 0
        try:
            for iter in range(self.iterations):
                #Train with each vector one by one
                self.iterationInput += 1
                while not coord.should_stop():
                    #Fill in input data.
                    self.sess.run([self.batchInput, self.label])
                    self.sess.run(self.trainingOp)
                    print self.label.eval(session = self.sess)
        except tf.errors.OutOfRangeError:
            print('Done training -- epoch limit reached')

        # When done, ask the threads to stop.
        coord.request_stop()
        coord.join(threads)
</code>```

Body:
I'm new to TensorFlow and am training a SOM model based on Sachin Joglekar's blog (https://codesachin.wordpress.com/2015/11/28/self-organizing-maps-with-googles-tensorflow/) using multiple CSV files as input. I followed the tutorial at https://www.tensorflow.org/programmers_guide/reading_data for reading from a CSV file queue in minibatches. My code is running, but I want to print out the decoded CSV input from the reader to verify that the input pipeline is working correctly. Since the CSV file input is not part of the graph, I am unable to print it using Tensor.eval(self.sess). When I try to print out the decoded record labels using self.label.eval(session = tf.Session(graph=self.label.graph)), my script hangs and does not give any output. Is there a way for me to verify that my input pipeline is working? Here are the relevant snippets of my code:

Main function

def main(argv):
    som = SOM(somDim1, somDim2, windowSizes[win], iterations, learningRate,
    neighborhood, fileNameList, batchSize)
    som.train(batchSize, fileNameList, windowSizes[win])

Graph

def __init__(self, m, n, dim, iterations, alpha, sigma, fileNameList, batchSize):

    ##INITIALIZE GRAPH
    self.graph = tf.Graph()

    ##POPULATE GRAPH WITH NECESSARY COMPONENTS
    with self.graph.as_default():

        ##PLACEHOLDERS FOR TRAINING INPUTS
        #These should be placeholders according to the TensorFlow framework,
        #but we are declaring them as variables so that we can assign them directly
        #to values read in from the CSV files.
        batchInputLg = np.zeros((dim, batchSize))
        labelFloat = np.zeros((3, batchSize))
        self.label = tf.cast(labelFloat, "string")
        self.batchInput = tf.cast(batchInputLg, "float32")

        """
        ...the rest of the graph...
        """

        self.trainingOp = tf.assign(self.weightageVects, newWeightagesOp)

        ##INITIALIZE SESSION
        self.sess = tf.Session()

        ##INITIALIZE VARIABLES
        initOp = tf.global_variables_initializer()
        self.sess.run(initOp)

Input pipeline functions

"""
Read in the features and metadata from the CSV files for each chromosome.
"""
def readFromCsv(self, fileNameQ, dim):
    reader = tf.TextLineReader()
    _, csvLine = reader.read(fileNameQ)
    recordDefaults = [["\0"] for cl in range(dim - 1)]
    recordStr = tf.decode_csv(csvLine, record_defaults=recordDefaults)
    self.label = tf.stack(recordStr[0:2])
    #self.label.eval(session = tf.Session(graph=self.label.graph))
    self.features = tf.to_float(tf.stack(recordStr[3:dim - 1]))
    return (self.features, self.label)

"""
Read in the features and metadata from the CSV files for each chromosome.
"""
def inputPipeline(self, batchSize, fileNameList, dim, num_epochs=None):
    fileNameQ = tf.train.string_input_producer(fileNameList, shuffle = True)
    minAfterDequeue = 10000
    capacity = minAfterDequeue + 3 * batchSize
    example, label = self.readFromCsv(fileNameQ, dim)
    exampleBatchStr, labelBatch = tf.train.shuffle_batch([example, label], batch_size=batchSize, capacity=capacity, min_after_dequeue=minAfterDequeue)
    exampleBatch = tf.cast(exampleBatchStr, "float")
    return (exampleBatch, labelBatch)

Training function

def train(self, batchSize, fileNameList, dim):
    #Start the queue runners.
    # Start input enqueue threads.
    coordFile = tf.train.Coordinator()
    self.coord = tf.train.Coordinator()
    threadsFile = tf.train.start_queue_runners(sess=self.sess, coord=coordFile)
    self.threads = tf.train.start_queue_runners(sess=self.sess, coord=self.coord)

    #Training iterations
    self.iterationInput = 0
    try:
        for iter in range(self.iterations):
            #Train with each vector one by one
            self.iterationInput += 1
            while not self.coord.should_stop():
                #Fill in input data.
                [self.batchInput, self.label] = self.inputPipeline(batchSize, fileNameList, dim)
                self.sess.run(self.trainingOp)

    except tf.errors.OutOfRangeError:
        print('Done training -- epoch limit reached')

    # When done, ask the threads to stop.
    self.coord.request_stop()

Body:
I figured out the solution. Instead of initializing the label and batch input tensors in the graph and assigning them within the train() function, I should have placed the assignment statement inside the graph, like so:

##TRAINING INPUTS
self.batchInput, self.label = self.inputPipeline(batchSize, fileNameList, dim)

Then, the train function becomes:

def train(self, batchSize, fileNameList, dim):
    with self.sess:
        # Start populating the filename queue.
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)

        #Training iterations
        self.iterationInput = 0
        try:
            for iter in range(self.iterations):
                #Train with each vector one by one
                self.iterationInput += 1
                while not coord.should_stop():
                    #Fill in input data.
                    self.sess.run([self.batchInput, self.label])
                    self.sess.run(self.trainingOp)
                    print self.label.eval(session = self.sess)
        except tf.errors.OutOfRangeError:
            print('Done training -- epoch limit reached')

        # When done, ask the threads to stop.
        coord.request_stop()
        coord.join(threads)


问:
What is the difference between var and val in Kotlin?
What is the difference between var and val in Kotlin?

I have gone through this link:

KotlinLang: Properties and Fields

As stated on this link:

The full syntax of a read-only property declaration differs from a
mutable one in two ways: it starts with val instead of var and does
not allow a setter.

But just before there is an example which uses a setter.

```<code>fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}
</code>```

What is the exact difference between var and val?

Why do we need both?

This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.

答:
variables defined with var are mutable(Read and Write)

variables defined with val are immutable(Read only)

Kotlin can remove findViewById and reduce code for setOnClickListener in android studio. For full reference: Kotlin awesome features

value of mutable variables can be changed at anytime, while you can not change value of immutable variables.

where should I use var and where val ?

use var where value is changing frequently. For example while getting location of android device

```<code>var integerVariable : Int? = null
</code>```

use val where there is no change in value in whole class. For example you want set textview or button's text programmatically.

```<code>val stringVariables : String = "Button's Constant or final Text"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What is the difference between var and val in Kotlin?

I have gone through this link:

KotlinLang: Properties and Fields

As stated on this link:

The full syntax of a read-only property declaration differs from a
mutable one in two ways: it starts with val instead of var and does
not allow a setter.

But just before there is an example which uses a setter.

fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}

What is the exact difference between var and val?

Why do we need both?

This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.

Body:
variables defined with var are mutable(Read and Write)

variables defined with val are immutable(Read only)

Kotlin can remove findViewById and reduce code for setOnClickListener in android studio. For full reference: Kotlin awesome features

value of mutable variables can be changed at anytime, while you can not change value of immutable variables.

where should I use var and where val ?

use var where value is changing frequently. For example while getting location of android device

var integerVariable : Int? = null

use val where there is no change in value in whole class. For example you want set textview or button's text programmatically.

val stringVariables : String = "Button's Constant or final Text"


问:
Groovy template engine with parameters matching a Java class name
I'm sure this is a simple one...

We use the Groovy template engine to format XML documents into human-readable form. The code scans the XML and creates a map with an entry for each item in the XML, and then this is passed to the Groovy template engine.

Problem occurs when the XML contains an attribute that matches a class name -
 something like this: <Date>some date</Date>. If the template file specifies Date is $Date (for example), instead of the actual date string, we're getting class java.util.Date. We've tried variations on $Date like ${Date} and ${Date.toString()}, etc with no luck.

We think the issue is that Groovy confuses Date the input variable, and the java.util.Date class, but I'm sure there's some sort of syntax that will make this work properly. Since we feed arbitrary user-defined XML through this, we really can't control things like the attribute names in the XML.

Here's a few lines of code to replicate the problem:

```<code>def map = [:]
map.putAt("Date",  new Date())  // Fails
map.putAt("Date2", new Date())  // Works
def tf = new File("Test.template")
def gte = new GStringTemplateEngine()
def tpl = gte.createTemplate(tf).make(map.withDefault{null})
println tpl.toString()
</code>```

The "Test.template" file contains:

```<code>Date is ${Date.toString()}.
Date is ${Date2.toString()}.
</code>```

The output we get is:

```<code>Date is class java.util.Date.
Date is Tue Jun 06 20:22:16 EDT 2017.
</code>```

答:
Answering my own question here, just in case someone else has a similar problem.

We found that the Groovy "getVariable()" method is a solution that works for us. The getVariable() method returns the value of any variable, and it's exposed inside the template engine. Changing the template to in my example above to:

```<code>Date is ${getVariable("Date")}
</code>```

Solved the problem for us.

Body:
I'm sure this is a simple one...

We use the Groovy template engine to format XML documents into human-readable form. The code scans the XML and creates a map with an entry for each item in the XML, and then this is passed to the Groovy template engine.

Problem occurs when the XML contains an attribute that matches a class name -
 something like this: <Date>some date</Date>. If the template file specifies Date is $Date (for example), instead of the actual date string, we're getting class java.util.Date. We've tried variations on $Date like ${Date} and ${Date.toString()}, etc with no luck.

We think the issue is that Groovy confuses Date the input variable, and the java.util.Date class, but I'm sure there's some sort of syntax that will make this work properly. Since we feed arbitrary user-defined XML through this, we really can't control things like the attribute names in the XML.

Here's a few lines of code to replicate the problem:

def map = [:]
map.putAt("Date",  new Date())  // Fails
map.putAt("Date2", new Date())  // Works
def tf = new File("Test.template")
def gte = new GStringTemplateEngine()
def tpl = gte.createTemplate(tf).make(map.withDefault{null})
println tpl.toString()

The "Test.template" file contains:

Date is ${Date.toString()}.
Date is ${Date2.toString()}.

The output we get is:

Date is class java.util.Date.
Date is Tue Jun 06 20:22:16 EDT 2017.

Body:
Answering my own question here, just in case someone else has a similar problem.

We found that the Groovy "getVariable()" method is a solution that works for us. The getVariable() method returns the value of any variable, and it's exposed inside the template engine. Changing the template to in my example above to:

Date is ${getVariable("Date")}

Solved the problem for us.


问:
Using phonegap audio api in gwt
I am wanting to use the phonegap audio api in GWT using JSNI.I cannot figure out how to code the methods in JSNI.

Wondering if anyone know of any tutorials.They javascript methods are really pretty simple.

http://docs.phonegap.com/phonegap_media_media.md.html

答:
I just need the play method really.I am not quite as knowledgeable to do this correctly I guess.That code looks really foreign to me :-)

Still cannot accept your answer.The site does not recognize me it is strange.

I get the following error when trying to use the media in my onModuleLoad

The constructor TESTPHONEGAP.Media(String, new Command(){}) is undefined

```<code>Media m = new Media("test.mp3", new Command() {
           @Override
           public void execute() {

           }
         });
       m.play()
</code>```

Using your class as an "inner class" in same file as my main onModuleLoad

ContentLicense: CC BY-SA 2.5

Title: Using phonegap audio api in gwt

Body:
I just need the play method really.I am not quite as knowledgeable to do this correctly I guess.That code looks really foreign to me :-)

Still cannot accept your answer.The site does not recognize me it is strange.

I get the following error when trying to use the media in my onModuleLoad

The constructor TESTPHONEGAP.Media(String, new Command(){}) is undefined

Media m = new Media("test.mp3", new Command() {
           @Override
           public void execute() {

           }
         });
       m.play()

Using your class as an "inner class" in same file as my main onModuleLoad


问:
Laravel 5.4: Redirect::to not working
I want to redirect the user to another page if a certain condition is not true.

This is my first/index view:

```<code>    <html lang="en">
      <head>
      </head>

      <body>

        <?php
        if(5>4) {
        return Redirect::to('controllername@methodname')->with('status','Condition not true!');
        } else {
        ?>
    <p>It is Working</p>

<?php } ?>

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

If I change the condition to (5<4) then it works fine. but if the condition is true, it shows me a blank page. I want to write the condition in the view not in the controller and route. Please Help

答:
I would to something like this probably:

I would start off by moving you if statement to you controller, as others has pointed out.

Lets say that you render you current view from HomeController@index

I would do, in HomeController

```<code>public function index()
{
   if(5>4){
      return redirect()->action('controllername@methodname')->with('status','Condition not true!');
   }else{
      return view('index');
   }
}
</code>```

This will remove your PHP code from the view, and make full use of Laravel route and controller functions.

Title: Laravel 5.4: Redirect::to not working

Body:
I want to redirect the user to another page if a certain condition is not true.

This is my first/index view:

        <?php
        if(5>4) {
        return Redirect::to('controllername@methodname')->with('status','Condition not true!');
        } else {
        ?>

It is Working

<?php } ?>

If I change the condition to (5<4) then it works fine. but if the condition is true, it shows me a blank page. I want to write the condition in the view not in the controller and route. Please Help

Body:
I would to something like this probably:

I would start off by moving you if statement to you controller, as others has pointed out.

Lets say that you render you current view from HomeController@index

I would do, in HomeController

public function index()
{
   if(5>4){
      return redirect()->action('controllername@methodname')->with('status','Condition not true!');
   }else{
      return view('index');
   }
}

This will remove your PHP code from the view, and make full use of Laravel route and controller functions.


问:
Android Instant App: How to create URL addressable modules?
Google updated their documentation about instant apps recently: Prepare your app

Most of the points are clear except   3. Refactor your app, if necessary.

They suggest for retail modules like browse, search, item detail, and check out.

Question: How do I split up the app into modules which are fully functional & URL addressable?

I do see here several issues:

if we use libraries like dagger, butterknife, ... all modules would be dependent on other modules

if our modules contain (views) as required, how should a transition to another view (from another module) be implemented without importing this module?

Can somebody shed light into the dark? Thanks!

答:
I'm not sure if I'm misunderstanding your question, but I'll try to take a crack at it. For my below explanation, I'll reference this code sample by Google several times. I HIGHLY suggest cloning that repo and playing around with it, since I think it will answer your question.

if we use libraries like dagger, butterknife, ... all modules would be dependent on other modules

As mentioned by others, any libraries that will be used by all of your Features  will go into your Base Feature.

if our modules contain (views) as required, how should a transition to another view (from another module) be implemented without importing this module?

This answer covers the overview of it - but this part seems to be the root of your question so I'll try to dig in a little deeper.

Let's say Feature1 (BrowseActivity) wants to open up Feature2 (ItemDetailActivity). Instead of Feature1 calling startActivity(ItemDetailActivity.class) directly, it will have to use the method call below (this is because Feature1 doesn't have access to Feature2's ItemDetailActivity.class since they do NOT depend on each other).
Here is the code sample provided by Google

```<code>Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com/itemdetail"));
intent.setPackage(getPackageName());
intent.addCategory(Intent.CATEGORY_BROWSABLE);
startActivity(intent);
</code>```

Now the missing part is that in Feature2's AndroidManifest you need to declare that ItemDetailActivity is listening for the https://example.com/itemdetail link. Here is the relevant code sample from Google

```<code><activity android:name=".ItemDetailActivity">
    <intent-filter>
      <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter android:autoVerify="true">
      <action android:name="android.intent.action.VIEW" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
      <data android:scheme="http" />
      <data android:scheme="https" />
      <data android:host="example.com" />
      <!-- IMPORTANT -->
      <data android:pathPrefix="/itemdetail"/>
    </intent-filter>
    <meta-data
      android:name="default-url"
      android:value="https://www.example.com/itemdetail" />
</activity>
</code>```

For any more info, read up on Digital Asset Links as well as general Deep Linking

Body:
I'm not sure if I'm misunderstanding your question, but I'll try to take a crack at it. For my below explanation, I'll reference this code sample by Google several times. I HIGHLY suggest cloning that repo and playing around with it, since I think it will answer your question.

if we use libraries like dagger, butterknife, ... all modules would be dependent on other modules

As mentioned by others, any libraries that will be used by all of your Features  will go into your Base Feature.

if our modules contain (views) as required, how should a transition to another view (from another module) be implemented without importing this module?

This answer covers the overview of it - but this part seems to be the root of your question so I'll try to dig in a little deeper.

Let's say Feature1 (BrowseActivity) wants to open up Feature2 (ItemDetailActivity). Instead of Feature1 calling startActivity(ItemDetailActivity.class) directly, it will have to use the method call below (this is because Feature1 doesn't have access to Feature2's ItemDetailActivity.class since they do NOT depend on each other).
Here is the code sample provided by Google

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com/itemdetail"));
intent.setPackage(getPackageName());
intent.addCategory(Intent.CATEGORY_BROWSABLE);
startActivity(intent);

Now the missing part is that in Feature2's AndroidManifest you need to declare that ItemDetailActivity is listening for the https://example.com/itemdetail link. Here is the relevant code sample from Google

<activity android:name=".ItemDetailActivity">
    <intent-filter>
      <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter android:autoVerify="true">
      <action android:name="android.intent.action.VIEW" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
      <data android:scheme="http" />
      <data android:scheme="https" />
      <data android:host="example.com" />
      <!-- IMPORTANT -->
      <data android:pathPrefix="/itemdetail"/>
    </intent-filter>
    <meta-data
      android:name="default-url"
      android:value="https://www.example.com/itemdetail" />
</activity>

For any more info, read up on Digital Asset Links as well as general Deep Linking


问:
How to check if there is an item in an array that exists in another array?
I have the following React code that I want to use to disable a button:

```<code>todos.filter(todo => todo.completed === true)
  .map(todo => todo.id)
  .includes(this.state.checkedIds)
</code>```

My problem is it always returns false. I want to compare two arrays here. If there is an item present in both arrays of this.state.checkedIds and todo.ids it should return true or else false.

答:
Make checkedIds into a set and then compare them.

```<code>var checkedIds = new Set(this.state.checkedIds)
todos.filter( todo => todo.completed === true )
  .map( todo => todo.id )
  .filter( id => checkedIds.has(id) )
</code>```

Body:
I have the following React code that I want to use to disable a button:

todos.filter(todo => todo.completed === true)
  .map(todo => todo.id)
  .includes(this.state.checkedIds)

My problem is it always returns false. I want to compare two arrays here. If there is an item present in both arrays of this.state.checkedIds and todo.ids it should return true or else false.

Body:
Make checkedIds into a set and then compare them.

var checkedIds = new Set(this.state.checkedIds)
todos.filter( todo => todo.completed === true )
  .map( todo => todo.id )
  .filter( id => checkedIds.has(id) )


答:
Not the cleanest. But it works.

```<code>>>> start = 0
>>> stop = 19
>>> step = [2.25, 2.25, 1.5]
>>> L = [start]
>>> while L[-1] <= stop:
...    L.append(L[-1] + step[i % 3])
...    i += 1
...
>>> L[-1] = stop
>>> L
[0, 2.25, 4.5, 6.0, 8.25, 10.5, 12.0, 14.25, 16.5, 18.0, 19]
</code>```

Keep your step values in a list. Just iterate over and keep adding them in rotation till you hit the cap.

Title: How to divide time interval into parts of varying length?

Body:
Not the cleanest. But it works.

>>> start = 0
>>> stop = 19
>>> step = [2.25, 2.25, 1.5]
>>> L = [start]
>>> while L[-1] <= stop:
...    L.append(L[-1] + step[i % 3])
...    i += 1
...
>>> L[-1] = stop
>>> L
[0, 2.25, 4.5, 6.0, 8.25, 10.5, 12.0, 14.25, 16.5, 18.0, 19]

Keep your step values in a list. Just iterate over and keep adding them in rotation till you hit the cap.


问:
Adding Cordova/Phonegap plugins behind a proxy
I've successfully installed Cordova (clean install, under Windows), and I'm able to deploy a small app to Android, but unable to add any plugins behind my company's proxy. I've already tried setting every possible npm and git variable I could think of via:

```<code>npm config set proxy url:port
npm config set http-proxy url:port
npm config set https-proxy url:port
</code>```

(replaced url:port with the actual proxy) and

```<code>git config --system --add http.proxy url:port
git config --global --add http.proxy url:port
</code>```

but to no avail.

Every time I run something as simple as

```<code>cordova plugin add org.apache.cordova.splashscreen
</code>```

I get the following:

```<code>Fetching plugin "org.apache.cordova.splashscreen" via plugin registry
Error: Fetching plugin failed: Error: read ECONNRESET
at C:\Users\x\AppData\Roaming\npm\node_modules\cordova\src\plugin.js:105:41
at _rejected  (C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:808:24)
at C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:834:30
at Promise.when (C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:1079:31)
at Promise.promise.promiseDispatch (C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:752:41)
at C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:574:44
at flush (C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:108:17)
at process._tickCallback (node.js:415:13)
</code>```

Any help would be much appreciated!

答:
This solution work form me in windows.
In your user folder:
C:\Users\your_user_name.gradle
If exists a file called
gradle.properties
Edit & add

```<code>systemProp.http.proxyHost=[Proxy_IP]
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=[your_username]
systemProp.http.proxyPassword=[your_password]
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost
systemProp.https.proxyHost=[Proxy_IP]
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=[your_username]
systemProp.https.proxyPassword=[your_password]
systemProp.https.nonProxyHosts=*.nonproxyrepos.com|localhost
</code>```

If the file does not exists, create it.
Replace the text between [] with your right data. Obviously, the [] must be deleted. I left the "proxyPort" with 8080 because is the default in the most of cases.

Body:
I've successfully installed Cordova (clean install, under Windows), and I'm able to deploy a small app to Android, but unable to add any plugins behind my company's proxy. I've already tried setting every possible npm and git variable I could think of via:

npm config set proxy url:port
npm config set http-proxy url:port
npm config set https-proxy url:port

(replaced url:port with the actual proxy) and

git config --system --add http.proxy url:port
git config --global --add http.proxy url:port

but to no avail.

Every time I run something as simple as

cordova plugin add org.apache.cordova.splashscreen

I get the following:

Fetching plugin "org.apache.cordova.splashscreen" via plugin registry
Error: Fetching plugin failed: Error: read ECONNRESET
at C:\Users\x\AppData\Roaming\npm\node_modules\cordova\src\plugin.js:105:41
at _rejected  (C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:808:24)
at C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:834:30
at Promise.when (C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:1079:31)
at Promise.promise.promiseDispatch (C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:752:41)
at C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:574:44
at flush (C:\Users\x\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js:108:17)
at process._tickCallback (node.js:415:13)

Any help would be much appreciated!

Body:
This solution work form me in windows.
In your user folder:
C:\Users\your_user_name.gradle
If exists a file called
gradle.properties
Edit & add

systemProp.http.proxyHost=[Proxy_IP]
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=[your_username]
systemProp.http.proxyPassword=[your_password]
systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost
systemProp.https.proxyHost=[Proxy_IP]
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=[your_username]
systemProp.https.proxyPassword=[your_password]
systemProp.https.nonProxyHosts=*.nonproxyrepos.com|localhost

If the file does not exists, create it.
Replace the text between [] with your right data. Obviously, the [] must be deleted. I left the "proxyPort" with 8080 because is the default in the most of cases.


问:
C++ zlib inflate failing - translation of c# fixup?
I'm trying to inflate a string using zlib's deflate, but it's failing, apparently because it doesn't have the right header. I read elsewhere that the C# solution to this problem is:

```<code>public static byte[] FlateDecode(byte[] inp, bool strict) {
    MemoryStream stream = new MemoryStream(inp);
    InflaterInputStream zip = new InflaterInputStream(stream);
    MemoryStream outp = new MemoryStream();
    byte[] b = new byte[strict ? 4092 : 1];
    try {
        int n;
        while ((n = zip.Read(b, 0, b.Length)) > 0) {
            outp.Write(b, 0, n);
        }
        zip.Close();
        outp.Close();
        return outp.ToArray();
    }
    catch {
        if (strict)
            return null;
        return outp.ToArray();
    }
}
</code>```

But I know nothing about C#. I can surmise that all it's doing is adding a prefix to the string, but what that prefix is, I have no idea. Would someone be able to phrase this function (or even just the header creation and string concatenation) in C++?

The data which I'm trying to inflate is taken from a PDF using zlib deflation.

Thanks a million,
Wyatt

答: I've had better luck using SharpZipLib for zlib interop than with the native .Net Framework classes.  This correctly handles streams from C++ (zlib native) and from Java's compression classes without any funny business being needed.

Body:
I'm trying to inflate a string using zlib's deflate, but it's failing, apparently because it doesn't have the right header. I read elsewhere that the C# solution to this problem is:

public static byte[] FlateDecode(byte[] inp, bool strict) {
    MemoryStream stream = new MemoryStream(inp);
    InflaterInputStream zip = new InflaterInputStream(stream);
    MemoryStream outp = new MemoryStream();
    byte[] b = new byte[strict ? 4092 : 1];
    try {
        int n;
        while ((n = zip.Read(b, 0, b.Length)) > 0) {
            outp.Write(b, 0, n);
        }
        zip.Close();
        outp.Close();
        return outp.ToArray();
    }
    catch {
        if (strict)
            return null;
        return outp.ToArray();
    }
}

But I know nothing about C#. I can surmise that all it's doing is adding a prefix to the string, but what that prefix is, I have no idea. Would someone be able to phrase this function (or even just the header creation and string concatenation) in C++?

The data which I'm trying to inflate is taken from a PDF using zlib deflation.

Thanks a million,
Wyatt


问:
Lock out user with maxInvalidPasswordAttempts not work
I try to do research about Lock out users after three unsuccessful attempts without using a database, and I found the answer that use it with SQLMemberShipProvider. I modify th Web.config :

```<code> <authentication mode="Forms">
  <forms loginUrl="~/Account/LogOnCust" timeout="2880" />
 </authentication>
<membership>
  <providers>
    <clear />
    <add name="AspNetSqlMembershipProvider"
    type="System.Web.Security.SqlMembershipProvider"
    connectionStringName="WebDBConnection"
    maxInvalidPasswordAttempts="3"
    minRequiredPasswordLength="6"
    passwordAttemptWindow="10"
    applicationName="/" />
  </providers>
</membership>
</code>```

But it doesn't work, I don't know why. What modifications do I need to make more?

答: I had the same problem. My cause was that user had not been approved. After user is approved, than "FailedPasswordAttemptCount" is incremented after each fail attempt.</p>

Body:
I try to do research about Lock out users after three unsuccessful attempts without using a database, and I found the answer that use it with SQLMemberShipProvider. I modify th Web.config :

 <authentication mode="Forms">
  <forms loginUrl="~/Account/LogOnCust" timeout="2880" />
 </authentication>
<membership>
  <providers>
    <clear />
    <add name="AspNetSqlMembershipProvider"
    type="System.Web.Security.SqlMembershipProvider"
    connectionStringName="WebDBConnection"
    maxInvalidPasswordAttempts="3"
    minRequiredPasswordLength="6"
    passwordAttemptWindow="10"
    applicationName="/" />
  </providers>
</membership>

But it doesn't work, I don't know why. What modifications do I need to make more?


问:
Grails WAR can't find file in java class
In my project i need to use libav to convert videos and audios. So i need to include libav tools in my project.
This is my project structure :

```<code>grails-project
 |
 |-- .classpath
 |-- .groovy
 |-- .project
 |-- .settings
 |-- application.properties
 |-- grails-app
 |-- lib
 |   |-- avconv -->>> `This is the folder which contains libav tools`
 |-- scripts
 |-- src
 |   |-- groovy
 |   |-- java
 |   |   |-- Converter.class -->>> `This is my converter class`
 |-- target
 |-- test
 |-- web-app
</code>```

Also i use java interface for libav which is avconv4java.
It runs a process to execute libav commands and I set libav path like this:

```<code>AVCommand command = new AVCommand();
command.setToolPath("lib/avconv/bin/avconv.exe");
</code>```

Inside the java interface it passes the path as argument to ProcessBuilder and it starts it etc.

In development environment it runs very well. However when I deploy war and try to convert a video I got the following error:

```<code>java.io.IOException: Cannot run program "lib/avconv/bin/avconv.exe": CreateProcess error=2, The system cannot find the file specified
</code>```

I looked my deployed structure and found out that avconv folder is not in the lib folder. So i added these lines to BuildConfig:

```<code>grails.war.resources = { stagingDir, args ->
   copy(todir: "${stagingDir}/WEB-INF/lib/avconv") {
       fileset(dir: "lib/avconv", includes:"**")
   }
}
</code>```

Now avconv is in lib folder -like development environment- However, I still get the same error. What should I do to make it work?

Any help is appreciated.
Thanks in advance.

GRAILS VERSION: 2.4.5
Developing in intelliJ
Deployed to Tomcat 7

答: Relative paths will be expected to start from the root of the tomcat folder. Assuming the file in question is on your classpath, you can call getResource to access it and pass the absolute path to AVCommand.

Body:
In my project i need to use libav to convert videos and audios. So i need to include libav tools in my project.
This is my project structure :

grails-project
 |
 |-- .classpath
 |-- .groovy
 |-- .project
 |-- .settings
 |-- application.properties
 |-- grails-app
 |-- lib
 |   |-- avconv -->>> `This is the folder which contains libav tools`
 |-- scripts
 |-- src
 |   |-- groovy
 |   |-- java
 |   |   |-- Converter.class -->>> `This is my converter class`
 |-- target
 |-- test
 |-- web-app

Also i use java interface for libav which is avconv4java.
It runs a process to execute libav commands and I set libav path like this:

AVCommand command = new AVCommand();
command.setToolPath("lib/avconv/bin/avconv.exe");

Inside the java interface it passes the path as argument to ProcessBuilder and it starts it etc.

In development environment it runs very well. However when I deploy war and try to convert a video I got the following error:

java.io.IOException: Cannot run program "lib/avconv/bin/avconv.exe": CreateProcess error=2, The system cannot find the file specified

I looked my deployed structure and found out that avconv folder is not in the lib folder. So i added these lines to BuildConfig:

grails.war.resources = { stagingDir, args ->
   copy(todir: "${stagingDir}/WEB-INF/lib/avconv") {
       fileset(dir: "lib/avconv", includes:"**")
   }
}

Now avconv is in lib folder -like development environment- However, I still get the same error. What should I do to make it work?

Any help is appreciated.
Thanks in advance.

GRAILS VERSION: 2.4.5
Developing in intelliJ
Deployed to Tomcat 7


问:
VR View (Web) grabbing invalid URL
I'm trying to use VR View for the web to display a 360 degree image. I created a basic sample locally and it works without issue but once I got the code into my project, I'm getting a 404 error saying the resource couldn't be found.

The vrview.min.js file is converting my image path, entered like image: 'images/myImage.jpg', to something like:

```<code>http://localhost:80/Project/index.html?image=http://localhost/Project/images/myImage.jpg&is_stereo=false&
</code>```

IIS is not finding the image and the whole thing is throwing a big fat 404 server error.

Here's my code:

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>View 360 Image</title>

        <script type="text/javascript">
            window.addEventListener('load', onVrViewLoad);

            function onVrViewLoad() {
                var vrView = new VRView.Player('#vrview', {
                    image: 'images/myImage.jpg',
                    width: 800,
                    height: 700,
                    is_stereo: false
                });
            }
        </script>
    </head>

    <body>
        <form id="form1" runat="server">
            <div id="vrview"></div> <!-- Placeholder where the VR player will display -->
        </form>

        <script src="includes/vrview.min.js"></script>
    </body>
</html>
</code>```

Any help would be fantastic. Thanks!

答:
I found my answer. I was only including the vrview.min.js file that you import on the page you want to display the VR player. There was a whole directory of files that were included in the archive downloaded from github. I mistakenly assumed most of the files were for a sample demo.

All my initial code was correct, I just was missing files that vrview.min.js linked to. Once I dropped the extra files into the correct folder, the 360 degree photo appeared as intended.

Title: VR View (Web) grabbing invalid URL

Body:
I'm trying to use VR View for the web to display a 360 degree image. I created a basic sample locally and it works without issue but once I got the code into my project, I'm getting a 404 error saying the resource couldn't be found.

The vrview.min.js file is converting my image path, entered like image: 'images/myImage.jpg', to something like:

http://localhost:80/Project/index.html?image=http://localhost/Project/images/myImage.jpg&is_stereo=false&

IIS is not finding the image and the whole thing is throwing a big fat 404 server error.

Here's my code:

<!DOCTYPE html>

        <title>View 360 Image</title>

        <form id="form1" runat="server">

        </form>

Any help would be fantastic. Thanks!


问:
Angular Material Dialogs fixed height issues across browsers
I've been pulling my hair out trying to get to a solution that works with all my use cases and think I finally found one that I wanted to share.

What I wanted was a sticky header, sticky footer and scrollable content that worked in and out of fullscreen mode. It also needed to work across all browsers (Yes, you too Safari!).

Finally, I didn't want to resort to CSS overrides because I know Angular Material 1.x.x hasn't been playing nicely with Safari.

The following template is what I arrived at. Shout if you have improvements or if it helps!

```<code><md-dialog flex-xl="25"
           flex-lg="30"
           flex-md="40"
           layout="column">
  <md-toolbar class="md-toolbar-tools" flex="none">
    <h2>Add Friends</h2>
    <span flex></span>
    <md-button ng-click="vm.cancel()">
      <md-icon>clear</md-icon>
    </md-button>
  </md-toolbar>

  <md-content flex-xs="100" flex-sm="100">
    <!--Your content here-->
  </md-content>

  <md-dialog-actions flex="none">
    <span flex></span>
    <md-button ng-click="vm.cancel()">
      Close
    </md-button>
  </md-dialog-actions>
</md-dialog>
</code>```

You'll note the flex-xs="100" and flex-sm="100". I fullscreen in those scenarios so adjust accordingly.

答:
I don't know if this is exactly what you want, but I recently came across a similar problem where I needed the md-dialog to have a sticky toolbar (with sticky tabs below) and a sticky footer on the bottom of the modal. (I am using the dialog for user comments.) I ended up wrapping the dialog content that I needed to scroll into an md-content div and wrote some custom css for the overflow-y behavior.

Here is my HTML:

```<code><md-dialog>
    <md-dialog-toolbar>
    </md-dialog-toolbar>
    <md-tabs>
        <md-tab>
            <md-tab-body>
                <div id="comments">
                    <div class="comments-list-wrapper">
                        <md-content class="chat">
                        </md-content>
                    </div>
                    <md-dialog-actions id="footer">
                    </md-dialog-actions>
                </div>
            </md-tab-body>
        </md-tab>
    </md-tabs>
</md-dialog>
</code>```

Here is my CSS:

```<code>#comments {
    .comments-list-wrapper {
        min-height: 200px;
    }
    md-dialog-actions#footer {
        order: 1;
        flex-shrink: 0;
    }
    .chat {
        max-height: 320px;
        overflow-y: scroll;
    }
}
</code>```

I don't know if this is what you were looking for precisely, but in action it does this.

Body:
I've been pulling my hair out trying to get to a solution that works with all my use cases and think I finally found one that I wanted to share.

What I wanted was a sticky header, sticky footer and scrollable content that worked in and out of fullscreen mode. It also needed to work across all browsers (Yes, you too Safari!).

Finally, I didn't want to resort to CSS overrides because I know Angular Material 1.x.x hasn't been playing nicely with Safari.

The following template is what I arrived at. Shout if you have improvements or if it helps!

<md-dialog flex-xl="25"
           flex-lg="30"
           flex-md="40"
           layout="column">
  <md-toolbar class="md-toolbar-tools" flex="none">

Add Friends

    <md-button ng-click="vm.cancel()">
      <md-icon>clear</md-icon>
    </md-button>
  </md-toolbar>

  <md-content flex-xs="100" flex-sm="100">

  </md-content>

  <md-dialog-actions flex="none">

    <md-button ng-click="vm.cancel()">
      Close
    </md-button>
  </md-dialog-actions>
</md-dialog>

You'll note the flex-xs="100" and flex-sm="100". I fullscreen in those scenarios so adjust accordingly.

Body:
I don't know if this is exactly what you want, but I recently came across a similar problem where I needed the md-dialog to have a sticky toolbar (with sticky tabs below) and a sticky footer on the bottom of the modal. (I am using the dialog for user comments.) I ended up wrapping the dialog content that I needed to scroll into an md-content div and wrote some custom css for the overflow-y behavior.

Here is my HTML:

<md-dialog>
    <md-dialog-toolbar>
    </md-dialog-toolbar>
    <md-tabs>
        <md-tab>
            <md-tab-body>
                <div id="comments">
                    <div class="comments-list-wrapper">
                        <md-content class="chat">
                        </md-content>
                    </div>
                    <md-dialog-actions id="footer">
                    </md-dialog-actions>
                </div>
            </md-tab-body>
        </md-tab>
    </md-tabs>
</md-dialog>

Here is my CSS:

#comments {
    .comments-list-wrapper {
        min-height: 200px;
    }
    md-dialog-actions#footer {
        order: 1;
        flex-shrink: 0;
    }
    .chat {
        max-height: 320px;
        overflow-y: scroll;
    }
}

I don't know if this is what you were looking for precisely, but in action it does this.


问:
Hit detection implementation for Processing JS
I am having some trouble with programming hit detection in Processing.JS. I have tried to make a function that checks if something is touching an object and returns true and otherwise returns false. This is that here.

```<code>`Box.prototype.checkTouching = function(v){
if(v.position.x > this.position.x - this.width/2 && v.position <
this.position.x + this.width/2 && v.position.y > this.positon.y -
this.height/2 && v.position.y < this.position.y + this.height/2){
    return true;
}else{
    return false;
}
};`
</code>```

I am implementing it by creating a new variable "b" in my draw function that holds the value the function returned then using an if statement to check if the value "b" is holding is true. Like so

var b = box3.checkTouching(mos);
    if(b === true){
        println("It works");
    }

What should happen when the two objects touch is that a message saying "it works" gets printed in to the console. Unfortunately even when the object the function is running on is touching the object that is running it nothing happens. I have already checked to see if the logic works and it is valid so I know it has to be my implementation I just can not seem to find out what is wrong with my implementation. Can anyone tell what I am doing wrong? Full program here

答:
You need to check whether the rectangles overlap. You'd do this by checking each side, like this:

```<code>if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
   //collision
}
</code>```

Shameless self-promotion: I've written a tutorial on collision detection in Processing (including rectangle-rectangle collision) available here.

Body:
I am having some trouble with programming hit detection in Processing.JS. I have tried to make a function that checks if something is touching an object and returns true and otherwise returns false. This is that here.

`Box.prototype.checkTouching = function(v){
if(v.position.x > this.position.x - this.width/2 && v.position <
this.position.x + this.width/2 && v.position.y > this.positon.y -
this.height/2 && v.position.y < this.position.y + this.height/2){
    return true;
}else{
    return false;
}
};`

I am implementing it by creating a new variable "b" in my draw function that holds the value the function returned then using an if statement to check if the value "b" is holding is true. Like so

var b = box3.checkTouching(mos);
    if(b === true){
        println("It works");
    }

What should happen when the two objects touch is that a message saying "it works" gets printed in to the console. Unfortunately even when the object the function is running on is touching the object that is running it nothing happens. I have already checked to see if the logic works and it is valid so I know it has to be my implementation I just can not seem to find out what is wrong with my implementation. Can anyone tell what I am doing wrong? Full program here

Body:
You need to check whether the rectangles overlap. You'd do this by checking each side, like this:

if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
   //collision
}

Shameless self-promotion: I've written a tutorial on collision detection in Processing (including rectangle-rectangle collision) available here.


问:
Controlling Visibility Of Imported Categories
I am writing a program to turn off certain "sub-categories" from imported AutoCAD files (such as "DEFPOINTS", which arguably should automatically be hidden or not plot in Revit).  The following code seems like it should work, but instead kicks back an odd error.

```<code>Transaction Do_Filtered_VG = new Transaction(doc, "FilteredVG")
Autodesk.Revit.DB.View CurrentView = doc.ActiveView;
Categories categories = doc.Settings.Categories; string CatUp = string.Empty;
List<Category> ToBeOff = new List<Category>();
List<string> myCategories = new List<string>();
foreach (Category c in categories)
{
    if (c.Name.ToLower().EndsWith("dwg"))
    {
        List<Category> SubCategories = new List<Category>();
        foreach (Category One_Cat in c.SubCategories)
        {
            CatUp = One_Cat.Name.ToUpper();
            if (CatUp.Contains("DEFPOINTS") || CatUp.Contains("NPLT") || CatUp.Contains("RDFF") || CatUp.Contains("SDFF") || CatUp.Contains("DUCT"))//or other pattern;
            {
                 myCategories.Add(One_Cat.Name); ToBeOff.Add(One_Cat);
            }
        }
    }
}
Do_Filtered_VG.Start();
foreach (Category One_Cat in ToBeOff)
{
    CurrentView.SetVisibility(One_Cat, false);
}
Do_Filtered_VG.Commit();
TestCodeX.If_Tony("Would Turn Off Layers:", TestCodeX.List_To_Dialog(myCategories));
</code>```

The error given is: Cannot set the visible attribute of the category Level 3 because it is user hiddenA transaction or sub-transaction was opened but not closed".  This is odd, because "Level 3" is not a category, but is the ActiveView.

But my transaction is opened and closed.  I was not able to find hiddenA in an online search.  I also tried using the construction:  One_Cat.get_Visibility(CurrentView) (to try to at least see if the category is visible), and this resulted in the same error.  I also changed my references from RevitAPI (2014) to (2015) and (2016), with no change in the error.  My code properly filtered the layer names I wanted to turn off, as evidenced in my "Would Turn Off Layers:" TaskDialog echo of myCategories.  But whenever the .SetVisibility line was not commented out, I get the error described.

Is there some other method of turning off(on) visibility of Categories in the RevitAPI?  Or is there some other Transaction method required other than the one I am using?

答:
I see one problem with transactions in your code: you create a new transaction, but never call either Start or Commit on it.

Please read The Building Coder topic group on Handling Transactions and Transaction Groups about using transactions and enclosing them in a using statement.

Body:
I am writing a program to turn off certain "sub-categories" from imported AutoCAD files (such as "DEFPOINTS", which arguably should automatically be hidden or not plot in Revit).  The following code seems like it should work, but instead kicks back an odd error.

Transaction Do_Filtered_VG = new Transaction(doc, "FilteredVG")
Autodesk.Revit.DB.View CurrentView = doc.ActiveView;
Categories categories = doc.Settings.Categories; string CatUp = string.Empty;
List<Category> ToBeOff = new List<Category>();
List<string> myCategories = new List<string>();
foreach (Category c in categories)
{
    if (c.Name.ToLower().EndsWith("dwg"))
    {
        List<Category> SubCategories = new List<Category>();
        foreach (Category One_Cat in c.SubCategories)
        {
            CatUp = One_Cat.Name.ToUpper();
            if (CatUp.Contains("DEFPOINTS") || CatUp.Contains("NPLT") || CatUp.Contains("RDFF") || CatUp.Contains("SDFF") || CatUp.Contains("DUCT"))//or other pattern;
            {
                 myCategories.Add(One_Cat.Name); ToBeOff.Add(One_Cat);
            }
        }
    }
}
Do_Filtered_VG.Start();
foreach (Category One_Cat in ToBeOff)
{
    CurrentView.SetVisibility(One_Cat, false);
}
Do_Filtered_VG.Commit();
TestCodeX.If_Tony("Would Turn Off Layers:", TestCodeX.List_To_Dialog(myCategories));

The error given is: Cannot set the visible attribute of the category Level 3 because it is user hiddenA transaction or sub-transaction was opened but not closed".  This is odd, because "Level 3" is not a category, but is the ActiveView.

But my transaction is opened and closed.  I was not able to find hiddenA in an online search.  I also tried using the construction:  One_Cat.get_Visibility(CurrentView) (to try to at least see if the category is visible), and this resulted in the same error.  I also changed my references from RevitAPI (2014) to (2015) and (2016), with no change in the error.  My code properly filtered the layer names I wanted to turn off, as evidenced in my "Would Turn Off Layers:" TaskDialog echo of myCategories.  But whenever the .SetVisibility line was not commented out, I get the error described.

Is there some other method of turning off(on) visibility of Categories in the RevitAPI?  Or is there some other Transaction method required other than the one I am using?


问:
Why The do_upload is not working, and showing the error image is not selected?
This is myView  along codes.

```<code> <?=form_open_multipart('test/uploadimage/add_image',['class'=>'']);?>
<?=form_upload(['name'=>'img1','class'=>'form-control']); ?>
 <?=form_input(['name'=>'add','type'=>'submit','value'=>'Add']);?>
<?php if(isset($upload_error)) echo $upload_error?>
 <?=form_close(); ?>
</code>```

This is my Controller in which I want to upload the image in add_image function.

```<code><?php
  class  Uploadimage extends MY_Controller{
  function index(){
    $this->load->view('test/upload_image');
       }
 function  add_image(){
    $config=[
             'upload_path'=>'./uploads',
             'allowed_types'=>'png|gif|jpg',

          ];
    $this->load->library('upload',$config);
    if($this->upload->do_upload()){
        echo 'succee';
    }
   else {
        echo 'failled';
        $upload_error= $this->upload->display_errors();
        $this->load->view('test/upload_image',compact('upload_error'));
      }
   }
  }
 ?>
</code>```

Showing this error:

答:
Change this line in your code.

```<code>$this->upload->do_upload();
</code>```

with

```<code>$this->upload->do_upload('img1');
</code>```

Body:
This is myView  along codes.

 <?=form_open_multipart('test/uploadimage/add_image',['class'=>'']);?>
<?=form_upload(['name'=>'img1','class'=>'form-control']); ?>
 <?=form_input(['name'=>'add','type'=>'submit','value'=>'Add']);?>
<?php if(isset($upload_error)) echo $upload_error?>
 <?=form_close(); ?>

This is my Controller in which I want to upload the image in add_image function.

<?php
  class  Uploadimage extends MY_Controller{
  function index(){
    $this->load->view('test/upload_image');
       }
 function  add_image(){
    $config=[
             'upload_path'=>'./uploads',
             'allowed_types'=>'png|gif|jpg',

          ];
    $this->load->library('upload',$config);
    if($this->upload->do_upload()){
        echo 'succee';
    }
   else {
        echo 'failled';
        $upload_error= $this->upload->display_errors();
        $this->load->view('test/upload_image',compact('upload_error'));
      }
   }
  }
 ?>

Showing this error:

Body:
Change this line in your code.

$this->upload->do_upload();

with

$this->upload->do_upload('img1');


问:
How to generate random meaningless, but at the same time easy to remember words?
I need to figure out an algorithm or, even better, if there is an implementation in php/java to generate words which will be suggested to user to choose like some identifiers but I want them to be somewhat easy to remember, eg 'wonifuxa', 'thonqi', 'oqriman' and so on but not something like 'nxdFgtqI'</p>

答:
C#

```<code>    private static string RandomWord(int length)
    {
        var consonants = new[] { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "v", "w", "x", "y", "z" };
        var vowels = new[] { "a", "e", "i", "o", "u" };
        var word = "";
        var b = true;
        for (var i = 0; i < length; i++)
        {
            word += b ? consonants[Rng.Next(consonants.Length)] : vowels[Rng.Next(vowels.Length)];
            b = !b;
        }
        return word;
    }
</code>```

Body:
C#

    private static string RandomWord(int length)
    {
        var consonants = new[] { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "v", "w", "x", "y", "z" };
        var vowels = new[] { "a", "e", "i", "o", "u" };
        var word = "";
        var b = true;
        for (var i = 0; i < length; i++)
        {
            word += b ? consonants[Rng.Next(consonants.Length)] : vowels[Rng.Next(vowels.Length)];
            b = !b;
        }
        return word;
    }