Q:

Why use separate load methods instead of the constructor?

OpenTK has a separate Load() method it calls when the game has to load. XNA and MonoGame take it another step further and have the constructor, Initialize and LoadContent. All this seems to do for me as the programmer using the framework is be confused when I'm supposed to load something in and that I can't be 100% sure that a class is initialized when it's constructed. For what reason is this done?

A:

There is a reason that XNA has the constructor, Initialize, and LoadContent(). When you create a new game, such as in
static class Program
    {
        static void Main()
        {
            using (Game1 game = new Game1())
            {
                game.Run();
            }
        }
    }

Game1's constructor is called and takes care of pre-initialize tasks, such as
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
Components.Add(new gamecomponent());

and setting up the class's properties. You can use the constructor like to normally would. After the constructor is called, the Game.Run() method is called. This will start the game and call the initialize method. So in the above Program, once game.Run() is called, several things happen. First, Game1's Initialize method is called. This method usually looks something like:
protected override void Initialize()
    {
        // now that the GraphicsDevice has been created, we can create the projection matrix.
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
            MathHelper.ToRadians(45.0f), GraphicsDevice.Viewport.AspectRatio, 1f, 10000);

        base.Initialize();
    }

As you may notice, the projectionMatrix for this game is created in this method (not the constructor) because the graphicsDevice has been initialized once Game.Run() is called. After the Initialize method completes pre-game tasks Base.Initialize() is called, which does two things. First, any GameComponents you have added to the game are enumerated through and initialized. Second, LoadContent() is called once everything is initialized, both in the game and the gamecomponents, and the graphicsdevice is ready.
Now, you might wonder why LoadContent() isn't part of the initialize method. Well, I believe the main reason for this is so that you can reload the content if needed, "such as when the DeviceReset event occurs", or if you need to reset things like model mesh bones.
So in summary, the constructor creates the class and its properties like it normally would, then once the Initialize method it called, the game starts running after all the GameComponents have been initialized and the Content is loaded.


Q:

NW.js and WebStorm

I am trying to get NW.js to work well with WebStorm. I have it so that It runs the nw.js project. However, WebStorm seems completely unable to resolve any of the dependencies such as nw.Menu().
The documentation says that nw.gui does not require you to require or in my case import. I can not seem to find anything on how to fix this online. So how do I get WebStorm to resolve these?

A:

I'm not too sure about all this myself, but here is how I do it anyway:

Go to settings (ctrl-alt-s), Languages & Frameworks, Libraries.
Click download. Change dropdown from Official libraries to Typescript community stubs.
Find node-webkit. This is the old name for nw.js. There is no stub for nw.js yet that I know of. Download and install.
This is usually enough for other libraries, but for some reason I must fix the scopes for it to work with nw.js.  Therefore click manage scopes.
Choose your project root directory, and click on the space to the right of the directory below Library. Make sure node-webkit is checked.

With that done I was able to resolve dependencies and get code completions for nw.js.  It might be old though but at least it's something.


Q:

Parsing JSON file using Lambda

My main objective is to parse a JSON file and write the content of the JSON file to a scrollable list in the browser. I created a JSON file and stored it in an S3 bucket. I then created the following Lambda function:
// ----receive function----v
function get_json(url, callback) {
    http.get(url, function(res) {
        var body = '';
        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            var response = JSON.parse(body);
            // call function ----v
            callback(response);
        });
    });
}

var mydata = get_json("https://s3.amazonaws.com/scrollablelist/scrollableList.json", function (resp) {
    console.log(resp);
});

I get the following error:
{
  "errorMessage": "http is not defined",
  "errorType": "ReferenceError",
  "stackTrace": [
    "Object.<anonymous> (/var/task/index.js:20:18)",
    "Module._compile (module.js:570:32)",
    "Object.Module._extensions..js (module.js:579:10)",
    "Module.load (module.js:487:32)",
    "tryModuleLoad (module.js:446:12)",
    "Function.Module._load (module.js:438:3)",
    "Module.require (module.js:497:17)",
    "require (internal/module.js:20:19)"
  ]
}

The Log Output says this:
START RequestId: 516f164b-7ee3-11e7-97a7-0373caaf493b Version: $LATEST
module initialization error: ReferenceError
    at get_json (/var/task/index.js:3:9)
    at Object.<anonymous> (/var/task/index.js:20:18)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
END RequestId: 516f164b-7ee3-11e7-97a7-0373caaf493b
REPORT RequestId: 516f164b-7ee3-11e7-97a7-0373caaf493b  Duration: 80.81 ms          Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 19 MB

Any help would be greatly appreciated.

A:

You have to install npm package for http in your project folder. Please follow below steps,
a. Open node command prompt
b. Navigate (CD ) to your project folder
c. Type command "npm init" if you don't have a package.json file already
e. Type command "npm install http --save" (Which will add http module to package.json)
f. At the beggining of you js file you using "http" please refer http moduleas  below,
var http = require("http");
g. Add package.json file as well in the .zip to upload to Lambda (You don't need to include node modules folder)


Q:

Is it true that $L^2$ is compactly embedded in $(W^{1,2}_{0})^{\ast}$?

Is it true that $L^{2}(\mathbb R^{n})$ is compactly embedded in $(W^{1,2}_{0}(\mathbb R^{n}))^{\ast}$?
If so, how can I prove it?
Context
I've just started to study Functional Analysis. I tried to read some articles about embeddings in Sobolev spaces, but all I can find are the standard inequalities (like Sobolev inequality etc).

A:

No, not on $\mathbb R^n$. Take a smooth function $\phi$ with support contained in the unit ball. Consider the sequence $f_n(x) = \phi(x-3ne_1)$ where $e_1$ is a basis vector. This is a sequence of bumps going into infinity. Translation by $3ne_1$ does not change either  $L^2$ norm or $W^{-1,2}$  norm (I write $W^{-1,2}$ for $(W_0^{1,2})^*$ here). Since the supports are separated, for $n\ne m$
$$\|f_n-f_m\|_{W^{-1,2}}\ge \frac{\langle f_n-f_m, f_n\rangle}{\|f_n\|_{W^{1,2}}}
= \frac{\langle f_n , f_n\rangle}{\|f_n\|_{W^{1,2}}} = c
$$
where $c>0$ does not depend on $n$, due  to translation invariance. Thus, $(f_n)$ has no convergent subsequence in $W^{-1,2}$.
Remarks
The argument applies to other Sobolev-type spaces with translation-invariant norms. Pretty much nothing is compactly embedded on $\mathbb R^n$, unless you use a weight decaying at infinity.
On domains where the Rellich-Kondrachov theorem applies, you get compact embedding by dualizing the embedding of $W_0^{1,2}$ into $L^2$. The adjoint of a compact operator is compact.


Q:

Promise Rejection Executed but Not Thrown (Unhandled Promise Rejection)

I'm brand new submitting questions. I've had a good look at all the other questions that have been submitted and struggling to find a similar issue to what I have. If there is a similar question, my apologies.
I've having issues with a very basic Promise I created for this question, where I need to reject a array loop where one iteration is the same:
var array = [1, 2, 3, 4, 5];
var promise = array.forEach(n => {
  new Promise((resolve, reject) => {
    if (n == 5) return reject();
    return resolve();
  });
});

Promise.all(promise).then(() => {
  console.log('true');
}).catch(() => {
  console.log('false');
});

When console logging each iteration, the rejection gets called but doesn't catch in the promise and I can't fathom why. I've spent almost 3 hours finding out the reasoning behind this.

A:

Array.prototype.forEach does not return anything, thus promise is undefined. What you should use instead is Array.prototype.map. Also note that you actually have to return the newly created promises:
var array = [1, 2, 3, 4, 5];
var promise = array.map(n => {
  return new Promise((resolve, reject) => {
    if (n == 5) return reject();
    return resolve();
  });
});

Promise.all(promise).then(() => {
  console.log('true');
}).catch(() => {
  console.log('false');
});

You could even write it like this:
var promise = array.map(n => new Promise((resolve, reject) => (n == 5) ? reject() : resolve()));


Q:

C++ Sort based on other int array

suppose i have two vector
std::vector<int>vec_int = {4,3,2,1,5};

std::vector<Obj*>vec_obj = {obj1,obj2,obj3,obj4,obj5};

How do we sort vec_obj in regard of sorted vec_int position?
So the goal may look like this:
std::vector<int>vec_int = {1,2,3,4,5};

std::vector<Obj*>vec_obj = {obj4,obj3,obj2,obj1,obj5};

I've been trying create new vec_array:
for (int i = 0; i < vec_int.size(); i++) {

    new_vec.push_back(vec_obj[vec_int[i]]);
}

But i think it's not the correct solution. How do we do this? thanks
std library may be the best solution,but i can't find the correct solution to implement std::sort

A:

You don't have to call std::sort, what you need can be done in linear time (provided the indices are from 1 to N and not repeating)
std::vector<Obj*> new_vec(vec_obj.size());
for (size_t i = 0; i < vec_int.size(); ++i) {
    new_vec[i] = vec_obj[vec_int[i] - 1];
}

But of course for this solution you need the additional new_vec vector.
If the indices are arbitrary and/or you don't want to allocate another vector, you have to use a different data structure:
typedef pair<int, Obj*> Item;
vector<Item> vec = {{4, obj1}, {3, obj2}, {2, obj3}, {1, obj4}, {5, obj5}};
std::sort(vec.begin(), vec.end(), [](const Item& l, const Item& r) -> bool {return l.first < r.first;});


Q:

Can't Autowire a Bean which is present in a dependent Jar

I have tried this solution found in the following questions, but none work in my case:
@Configuration
@EnableWebMvc
@ComponentScan("myapp.framework.export")
public class WebConfig extends MyAppWebConfig {

    @Override
    public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {

        super.configureContentNegotiation(configurer);

    }

    @Override
    public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {

        super.configureMessageConverters(converters);

    }

}

Error:
INFO: Initializing Spring FrameworkServlet 'services-rest'
2017-04-11 15:25:52,774|localhost-startStop-1|NO_TID|NO_USER|ERROR|org.springframework.web.servlet.DispatcherServlet.initServletBean|Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xlsHttpMessageConverter': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'myapp.framework.export.ExportXlsModelService<?>[]' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1154)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1041)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4969)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'myapp.framework.export.ExportXlsModelService<?>[]' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:518)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:496)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:627)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)
    ... 29 common frames omitted

Apr 11, 2017 3:25:52 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xlsHttpMessageConverter': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'myapp.framework.export.ExportXlsModelService<?>[]' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1154)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1041)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4969)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'myapp.framework.export.ExportXlsModelService<?>[]' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:518)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:496)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:627)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)
    ... 29 more

Apr 11, 2017 3:25:52 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /myapp threw load() exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'myapp.framework.export.ExportXlsModelService<?>[]' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:518)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:496)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:627)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1241)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1154)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1041)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4969)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Apr 11, 2017 3:25:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Apr 11, 2017 3:25:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Apr 11, 2017 3:25:52 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 10565 ms

xlsHttpMessageConverter:
package myapp.framework.web.converter;

import myapp.framework.export.ExportXlsModelService;

import java.io.IOException;
import java.io.OutputStream;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Service;
    @Service
    public class XlsHttpMessageConverter<T> extends
                AbstractMyAppHttpMessageConverter<T, ExportXlsModelService<T>> {

        @Resource
        private ExportXlsModelService<T>[] exportServices;

        public XlsHttpMessageConverter() {

            super(MyAppMediaType.APPLICATION_EXCEL);
        }

        @Override
        protected void ecrireFichier(final T toExport, final OutputStream os) throws IOException,
            HttpMessageNotWritableException {

            final ExportXlsModelService<T> exportService = getServiceExport(toExport);

            final HSSFWorkbook model = exportService.construireXlsModel(toExport);
            model.write(os);
        }

        @Override
        protected ExportXlsModelService<T>[] getServicesExport() {

            return exportServices;
        }

    }

A:

Try to add classpath*: Prefix to your scan. (read here)
The * means scan in all jars on classpath
UPDATE:
Your converter has package myapp.framework.web.converter but scan checks myapp.framework.export


Q:

Django QueryDict Result Structure

What is resulting querydict structure from a post in django?  Here is an example for a radio button.
A single key in the QueryDict:
u'Q1', [u' ', u'1', u' ']

In the list for Q1 position 1 is the selected value, what are positions 0 and 2 representing? Here is another example for  "select/drop down" type HTML input.  What do the positions represent here? Position 2 is now the response but what are positions 0 and 1?
u'Q6', [u'1', u'1', u'4']

What about a text field?
u'Q8', [u'', u'', u'Joe']

I've looked through the documentation and haven't found the answer or I'm blinding looking right past it.

A:

Seems like you put three similar django forms inside the single <form> tag:
<form method="POST">
    {% csrf_token %}
    {{ form }}
    {{ form }}
    {{ form }}
</form>

If you want to output several instances of the same form class then consider to use the prefix argument in the form constructor or even the formsets mechanizm.


Q:

How do I hide a div (on the client) is client-side validation fails?

I'm making an asp.net page with asp.net validation controls. If validation fails, I want to show a div (on the client). Where do I do this? I can't find a way to access the OnValidate event on the client. I can do this on the server, but I'd rather do it on the client.

A:

Use an ASP.NET custom validator.
If for some reason you can't/don't want to do that, use a ClientScriptManager.RegisterOnSubmitStatement method,  and ensure to return false in the client-side script if whatever you're validating fails.


Q:

Custom listview section header

I have a list view populated with custom array adapter. I want to add section header to list view items by date which is a value in the object.
My Adapter class is
public class ReceiptAdapter2 extends BaseAdapter {

Context context;
LayoutInflater inflater;
private ArrayList<ReceiptModel> planList;

public ReceiptAdapter2(Context applicationContext, ArrayList<ReceiptModel> planList) {
    this.context = applicationContext;
    this.planList = planList;
    inflater = (LayoutInflater.from(applicationContext));
}

@Override
public int getViewTypeCount() {
    return 2;
}

@Override
public int getItemViewType(int position) {
    if (getItem(position) instanceof SectionItem){
        return 0;
    }else{
        return 1;
    }
}

@Override
public int getCount() {
    return planList.size();
}

@Override
public Object getItem(int i) {
    return  planList.get(i);
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

    ReceiptModel model = planList.get(i);
    view = inflater.inflate(R.layout.snipadapt, null);
    TextView names = (TextView) view.findViewById(R.id.textView);
    names.setText(model.getName());
    return view;
}
}

MainActivity code
 if (hstry.length() > 0 && hstry != null) {
            for (int i = 0; i < hstry.length(); i++) {
                try {
                    history_data = hstry.getJSONObject(i);
                    model = new ReceiptModel();
                    model_section = new SectionItem();

                    model.setRid(history_data.optString("ID"));
                    model.setName(history_data.optString("Name"));
                    model.setMobile(history_data.optString("Mobile"));
                    model.setTax(history_data.optString("Tax"));
                    model.setQnt(history_data.optString("T_quantity"));
                    model.setPrice(history_data.optString("T_price"));
                    model.setSub(history_data.optString("Sub_total"));
                    model.setDiscount(history_data.optString("Discount"));
                    model.setType(history_data.optString("Payment_type"));
                    model.setDate(db.getCatColor(history_data.optString("Date")));
                    model_section.setDevice(db.getCatColor(history_data.optString("Date")));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            setAdapter();

        }

Setting adapter
 private void setAdapter() {
    adapter = new ReceiptAdapter2(context,planList);
    category_list.setAdapter(adapter);
}

model class
public class ReceiptModel {

private String id,name,mobile,tax,t_quantity,t_price,s_total,discount,date,type;
private String device;
private String os,location;
private String network,weather,storage,time,internal,cat_id;

public String getRid() {
    return id;
}

public void setRid(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getMobile() {return mobile; }

public void setMobile(String mobile) {this.mobile = mobile; }

public String getTax() {return tax; }

public void setTax(String tax) {this.tax = tax; }

public String getQnt() {return t_quantity; }

public void setQnt(String t_quantity) {this.t_quantity = t_quantity; }

public String getPrice() {return t_price; }

public void setPrice(String t_price) {this.t_price = t_price; }

public String getSub() {return s_total; }

public void setSub(String s_total) {this.s_total = s_total; }

public String getDiscount() {return discount; }

public void setDiscount(String discount) {this.discount = discount; }

public String getDate() {return date; }

public void setDate(String date) {this.date = date; }

}
I referred many tutorials but nothing works for me.How can i pass multiple arraylist as in my case to adapter class? your responses are appreciated

A:

You need to add your both models ReceiptModel() and SelectionItem() as an object of an ArrayList like this
private ArrayList<Object> lpAndAlp=new ArrayList<>();

 lpAndAlp.add("model");
 lpAndAlp.add("model_section");

and then lpAndAlp in your adapter
 private void setAdapter() {
    adapter = new ReceiptAdapter2(context,planList);
    category_list.setAdapter(adapter);
}

and call it your adapter class like this..
private ArrayList<Object> planList;

    public ReceiptAdapter2(Context applicationContext, ArrayList<Object> planList) {
        this.context = applicationContext;
        this.planList = planList;
        inflater = (LayoutInflater.from(applicationContext));
    }

you just check return type of  getItemViewType method in getView
 @Override
        public View getView ( int i, View view, ViewGroup viewGroup){
            int type = getItemViewType(position);
            if (view == null) {
                switch (type) {
                    case 0:
                        view = inflater.inflate(R.layout.snipadapt, parent, false);
                        break;
                    case 1:
                        view = inflater.inflate(R.layout.yourHeaderLayout, parent, false);
                        break;
                }
            }

            switch (type) {
                case 0:
                    ReceiptModel model = planList.get(i);
                    view = inflater.inflate(R.layout.snipadapt, null);
                    TextView names = (TextView) view.findViewById(R.id.textView);
                    names.setText(model.getName());
                    break;
                case 1:
                    SectionItem model_section = planList.get(i);
                    //your header
                    break;
            }

            return view;
        }


Q:

Is there a way to send .ipa generated on a computer, from another to the AppStore

I was wondering if it's possible (already googled it) to generate an .ipa of an application on a computer A, send the .ipa to a computer B, and the send the .ipa from computer B to the AppStore ?
Can't figure out how to do that.

A:

I used the application loader to do that.
I downloaded it on the iTunesConnect portal then I exported my app as an archive.
I then sent it to my mate and he uploaded it with the app.


Q:

Determining if user is actually logged off in a domain - Windows Active Directory

I am writing a windows service which monitors accounts login and logoff events within a domain(Windows 2012). The login event id is 4624 and the logoff event id is 4634. But however I am seeing these two events in pairs i.e the event 4624 immediately followed by the event id 4634. What should be the approach to determine if the user is actually logged off from a machine in a domain?
Note: Interested in only interactive logon sessions (not network, service or others)

A:

You might want to look at event 4647, which is logged whenever a user logs off. If interactive sessions are all you're interested in, you should also limit yourself to relevant logon types (2, 7, 10, 11) in the 4624 event.


Q:

How do I club two string formats, or add a character to a string format

I have been trying to display a double with a '%' sign.
I cant use "P2" string format due to the fact that we want user to enter percentage that is saved as it is.
Hence we did use .DataFormatString = "{0}%" to display a '%' sign at the end of our data.
but this displays data like 1.2300000000%.
Now to  truncate trailing zeros we were tempted to use .DataFormatString = "G29" which would effectively remove all unnecessary zeros but now how do we add a "%" sign at the end of string ?
Can we somehow club two string formats to use "G29" with "%" sign ?
I have made various attempts to format this, but none have been on target, might be very simple one that I am missing..

A:

You were on the right track:
string result = string.Format("{0:G29}%", 1.2300000000);


Q:

Giving free tax advice to a friend. Can this get me in trouble?

Let's assume I am helping a very close friend of mine who owns a small family restaurant. She has 2 people working for her and she treats them as independent contractors. Under current conditions I am quite sure IRS would reclassify them as full time employee's and fine her (sole proprietorship). AFAIK, IRS does not know about this yet, but if they wanted to find out they easily could by expanding the audit.
I am giving her tips on what options she has and what would be pros&cons of each option.
Also I helped her to talk with IRS over phone to solve the other tax audit. IRS agent over phone wrote down my name while I represented her - I guess this is standard procedure.
Can I get into trouble for giving tax advice to a friend (e.g. there is this dreaded Trust Fund recovery Penalty)?
Things to consider:

I am not getting paid for explaining things or giving a tip to her.
I am not licensed and I am not lawyer.
Her business does not make enough money to afford real legal consultation.

A:

31 USC 330 enables the Dept. of Treasury to regulate those who are in the practice of representing persons before the Department. This results in Circular 230 which is a part of the Code of Federal Regulations. Part 10.3 specifies various types who are authorized to engage in the practice. The meaning of "practice" is not defined in the federal regs or the US code, so it has its ordinary meaning. To "practice" something is to habitually do something as a profession (not necessarily for money). The situation you describe does not in any reasonable interpretation constitute being a "practice". Moreover, except for talking to an IRS agent on the phone, the actions could not be construed as "representing" (and if I am correct in surmising that this was a simultaneous conversation with 3 people on the line, this wasn't "representing" since representing meaning to "do in someone's place", not "help someone while they do"). This contrasts with the typically stricter rules about "practicing law", which forbid filling out legal forms and so on.


Q:

RDotNet Dataframe Query

I have just started to use the rdotNet from: http://rdotnet.codeplex.com/.  I have never used R itself before but can do simple arithmetic in it. I have been able to create the instance and do some of the simple numeric calculations in c#. My issue is when i read in a csv file and create the dataframe. The information is all loaded correctly and I can see it when i debug.
When I try to go though the dataframe and print the contents to the screen, the 1st iteration shows me the correct information but after that it seems just to get numbers instead of the actually information.
Since i can do basic calculations in in the solution I will not write the begging code which will create the instance of the REngine. I will show is how I read the file in which i have place in the debug folder of the application:
Location of Downloaded csv file I use: http://www.rqtl.org/sampledata/listeria.csv
engine.Evaluate("library(datasets)");

engine.Evaluate("dataset1 <- read.csv(file = \" listeria.csv\", header = TRUE, sep = ',')");

DataFrame dataset1 = engine.GetSymbol("dataset1").AsDataFrame();

//Here is the problem
for (int row = 0, row < dataset1.RowCount; row++)

{

     for ( int col = 0; col < dataset1.ColumnCount; k++)

     {

        Console.Writeline(dataset1[row,col])

     }

}

My question is can someone tell me if I am doing something wrong or is there another way of going through the Dataframe  in RdotNet to get the information.
Hopefully i have explained everything, If you need more information, please feel free to ask.
Built in :
Visual Studio 2013, using a console Application, framework 4.5.1, RdotNet DLL: Vers 1.5.5 and in Win 7 64 Bit

A:

Try setting stringsAsFactors to FALSE.
engine.Evaluate("dataset1 <- read.csv(file = 'listeria.csv', header = TRUE, sep = ',', stringsAsFactors = FALSE)");


Q:

How can I improve these 8051 arch instructions?

I'm writing to memory space a few address and I need to optimize the code. There is a better way to do the following?
SETB 00h
SETB 01h
SETB 02h
SETB 03h
SETB 04h
SETB 05h
SETB 06h
SETB 07h

A:

I think what you want to do is:
MOV 20h,#0FFh

this should be equivalent to setting each byte


Q:

Processing - exporting a movie or image sequence from kinect data

I'm trying to find the fastest way to export a PNG sequence or movie with processing. I'm capturing Kinect data and currently, in each draw call, I'm using:
saveFrame("output/fames####.png");

but this is too slow. Anything I can do that's faster?
I'm using simple-openni for the kinect feed.

A:

You can try to save to the .oni format and there's already a SimpleOpenNI Sample for recording and playing back. Even though this should use a lot of memory, I imagine it might still be faster than saveFrame()
The advantage of using the .oni format is you can easily process the nodes recorded with SimpleOpeni (for example skeleton/hand tracking or other features can be tested on a .oni recording). If you need images, there should ways to extract/parse .oni files


Q:

Why is it harder to compute nonce for a hash with a certain number zero prefixes than it is for any other hash?

Based on my rudimentary understanding of Bitcoins and altcoins, network difficulty is adjusted by asking the network to target a hash smaller than a specific number, which translates to calculating nonce for a hash with a certain number of zeros prefixed to it.
Since hash values are supposed to be uniformly distributed, I don't understand why targeting a hash value with a specific number of zeroes is any more easy/difficult than targeting any other hash (not the hash value of the content without nonce obviously). I think targeting any of the possible hash values, except what the content already hashes to, should be equally difficult. Why is that not the case?
It's very likely that my understanding of Bitcoin network difficulty itself is wrong, in which case, could you please explain that to me?

A:

A hash is 256 bits long, so there are 2^256 possible hashes in the hash space. But if you assert that the hash has to begin with a 0, that halves the number of hashes that are allowed (and thus doubles the average number of hashes you need to test), and if you say it must start with two 0's, that's now only quarter of the hash space that is valid. The difficulty of finding a valid hash thus grows exponentially with the number of 0's you require at the start.
But as you said, because the hashes are uniformly distributed, there is nothing unique about requiring the hash start with x number of 0's. Requiring the hash to start with x number of 1's would be the same, as would any specific sequence of 1's and 0's be. 0's are just a nice choice and make sense in practice, because like you said, you are then computing a hash less than a specific number.
Just to point out the terminology difference by the way, it's not targeting a specific hash, it's targeting a specific subset of the possible hashes. To find a specific hash would mean SHA-256 is broken, because you are basically reversing the hashing operation.

A:

Finding a hash that is less than the target requires more work (not harder, there is nothing that makes hashing harder to do), i.e. more hashes. This is because there are more numbers with more digits (and thus larger) than there are with less digits. For example, there are 90 numbers with 2 digits, compared to only 10 with 1 digit. This is an exponential distribution. Because of this distribution, more work is required as the target is made smaller because you are significantly reducing the set of all possible valid hashes.


Q:

Отправка формы с последующей заменой value

Проблема в то что при первом клике меняется value с add на delete но форма не отправляется при повторном клике меняется value на add и форма отправляется с add.
Как сделать правильно?   Клик > Отправка > Замена
Форма
<form id="favorite" method="GET" action="" enctype="multipart/form-data" target="iframe">
    <input type="submit" id="fav" name="favorite" value="add"/>
</form>

js
$(function(){$('#fav').click(
    function() {
        $(this).val() == "add" ? delete_item() : add_item();
    });
});
function delete_item() {
    $('#fav').val("delete");
}
function add_item() {
    $('#fav').val("add");
}

A:

по логике скрипта,  если содержимое == "add"(как идет изначально) то менять содержимое на "delete".
а если второй клик, то содержимое уже будет "delete" изменено на "add".
чтобы форма не отправлялась сделай return false
либо: preventDefaul()


Q:

How to find only the exact pattern matches in java?

String "description" has both 5digit, 7digit substrings.  I would like match 5digit, 7digit with 5digit, 7digit respectively only.   But, 5digit substring extracts the whole 5 digit string and first 5 digit of 7 digits.
Pattern 5digitPattern = Pattern.compile("([0-9]{5})");
Pattern 7digitPattern = Pattern.compile("([0-9]{7})");

Matcher 5digitMatcher = 5digitPattern.matcher(description);
Matcher 7digitMatcher = 7digitPattern.matcher(description);

            if (5digitMatcher.find()) {
                for (int i = 0; i < 5digitMatcher.groupCount(); i++) {
                    System.out.print("\t" + 5digitMatcher.group(i));
                }
            }

            if (7digitMatcher.find()) {
                for (int i = 0; i < 7digitMatcher.groupCount(); i++) {
                    System.out.print("\t" + 7digitMatcher.group(i));
                }
            }

Please help me in matching 5digit, 7digit with 5digit, 7digit, respectively.

A:

Use word boundary:
Pattern 5digitPattern = Pattern.compile("\\b([0-9]{5})\\b");
Pattern 7digitPattern = Pattern.compile("\\b([0-9]{7})\\b");

According to comment, if you want to match  digits in abc12345def, use negative lookaround:
Pattern 5digitPattern = Pattern.compile("(?<![0-9])([0-9]{5})(?![0-9])");
Pattern 7digitPattern = Pattern.compile("(?<![0-9])([0-9]{7})(?![0-9])");


Q:

how to parse this xml by using python?

I try a lot of ways,but I still can't extract data from it.
<?xml version="1.0" encoding="UTF-8"?><cwbopendata xmlns="urn:cwb:gov:tw:cwbcommon:0.1">
 <identifier>CWB_ANNUAL_DATA_20161017134902</identifier>
 <sender>weather@cwb.gov.tw</sender>
 <sent>2016-10-17 13:51+08:00</sent>
 <status>Actual</status>
 <msgType>Issue</msgType>
 <dataid>CWB_B0024-002</dataid>
 <scope>Public</scope>
 <dataset>
  <location>
   <locationName>BANQIAO,板橋</locationName>
   <stationId>466880</stationId>
   <weatherElement>
    <elementName>逐時觀測</elementName>
    <time>
     <obsTime>2015-10-17 01:00</obsTime>
     <weatherElement>
      <elementName>測站氣壓</elementName>
      <elementValue>
       <value>1012.9</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>溫度</elementName>
      <elementValue>
       <value>23.2</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>相對濕度</elementName>
      <elementValue>
       <value>68</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>風速</elementName>
      <elementValue>
       <value>3.9</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>風向</elementName>
      <elementValue>
       <value>東北東,ENE</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>降水量</elementName>
      <elementValue>
       <value>0.0</value>
      </elementValue>
     </weatherElement>
    </time>
    <time>
     <obsTime>2015-10-17 02:00</obsTime>
     <weatherElement>
      <elementName>測站氣壓</elementName>
      <elementValue>
       <value>1012.7</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>溫度</elementName>
      <elementValue>
       <value>22.9</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>相對濕度</elementName>
      <elementValue>
       <value>69</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>風速</elementName>
      <elementValue>
       <value>3.3</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>風向</elementName>
      <elementValue>
       <value>東北東,ENE</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>降水量</elementName>
      <elementValue>
       <value>0.0</value>
      </elementValue>
     </weatherElement>
    </time>
    <time>
     <obsTime>2015-10-17 03:00</obsTime>
     <weatherElement>
      <elementName>測站氣壓</elementName>
      <elementValue>
       <value>1012.5</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>溫度</elementName>
      <elementValue>
       <value>22.8</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>相對濕度</elementName>
      <elementValue>
       <value>70</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>風速</elementName>
      <elementValue>
       <value>3.7</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>風向</elementName>
      <elementValue>
       <value>東北東,ENE</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>降水量</elementName>
      <elementValue>
       <value>0.0</value>
      </elementValue>
     </weatherElement>
    </time>
    <time>
     <obsTime>2015-10-17 04:00</obsTime>
     <weatherElement>
      <elementName>測站氣壓</elementName>
      <elementValue>
       <value>1012.4</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>溫度</elementName>
      <elementValue>
       <value>22.7</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>相對濕度</elementName>
      <elementValue>
       <value>70</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>風速</elementName>
      <elementValue>
       <value>3.1</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>風向</elementName>
      <elementValue>
       <value>東北東,ENE</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>降水量</elementName>
      <elementValue>
       <value>0.0</value>
      </elementValue>
     </weatherElement>
    </time>
    <time>
     <obsTime>2015-10-17 05:00</obsTime>
     <weatherElement>
      <elementName>測站氣壓</elementName>
      <elementValue>
       <value>1012.6</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>溫度</elementName>
      <elementValue>
       <value>22.6</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>相對濕度</elementName>
      <elementValue>
       <value>71</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>風速</elementName>
      <elementValue>
       <value>2.2</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>風向</elementName>
      <elementValue>
       <value>東北東,ENE</value>
      </elementValue>
     </weatherElement>
     <weatherElement>
      <elementName>降水量</elementName>
      <elementValue>
       <value>0.0</value>
      </elementValue>
     </weatherElement>
    </time>
    <time>

This was my code tried to extract data from it.
from lxml import objectify
path=r'C:\Users\champion\Desktop\data_science_race\weather\C-B0024-002.xml'
parsed=objectify.parse(open(path,'rb'))
root=parsed.getroot()

This part successfully extracted data from location and stationId.
data=[]
for elt in root.dataset.location:
    el_data={}
    skip_fields=['{urn:cwb:gov:tw:cwbcommon:0.1}weatherElement']
    for child in elt.getchildren():
        if child.tag in skip_fields:
            continue
        el_data[child.tag]=child.text
    data.append(el_data)

This part the obsTime can be extracted,but elmentName and elementValue can't be extracted it.
data=[]
for elt in root.dataset.location.weatherElement.time:
    el_data={}
    skip_field=['{urn:cwb:gov:tw:cwbcommon:0.1}time']
    for child in elt.getchildren():
        if child.tag in skip_field:
            continue
            el_data[child.tag]=child.text
        for descendent in child.getchildren():
            el_data[descendent.tag]=descendent.text
            for next_descendent in descendent.getchildren():
                el_data[next_descendent.tag]=next_descendent.text
    data.append(el_data)

A:

I would recommend using pyxb for this type of task.
What you want to do is:

Generate an xsd schema file from your XML (using Visual Studio or a free online tool)
Generate binding classes using pyxb (see the 30 second example in the docs). For an xsd file, the command is:python pyxbgen cwbopendata.xsd -m cwbopendata
Use the CreateFromDocument method to use the binding classes you generated

The resulting code is clean. As an example, the sample below prints the timestamps of your weather observations:

import cwbopendata
import pyxb

data = cwbopendata.CreateFromDocument(open('cwb_data_example.xml').read())

for t in data.dataset.location.weatherElement.time:
    print(t.obsTime)


Q:

Django UserProfile matching query does not exist

I'm making an forum using this tutorial http://lightbird.net/dbe/forum2.html and I encountered an error .
When I click edit profile , it suppose to point to this page instead I get an error(below)

 DoesNotExist at /forum/profile/1/

 UserProfile matching query does not exist.

 Request Method:    GET
 Request URL:   http://127.0.0.1:8000/forum/profile/1/
 Django Version:    1.4.3
 Exception Type:    DoesNotExist
 Exception Value:

 UserProfile matching query does not exist.

 Traceback Switch to copy-and-paste view

 C:\djcode\mysite\forum\views.py in profile

         profile = UserProfile.objects.get(user=pk)

I think this error mean , django can't receive my admin login .
This is part of my fbase.html
  Edit profile

which point to my URLconf.
  from django.conf.urls import patterns,include,url
  from django.contrib import admin
  from django.conf import settings

  urlpatterns = patterns('forum.views',
                   url(r'^$','main',name='main'),
                   url(r"^forum/(\d+)/$", "forum",name ="forum"),
                   url(r"^thread/(\d+)/$","thread",name = "thread"),
                   url(r"^post/(new_thread|reply)/(\d+)/$", "post",name = "post"),
                   url(r"^reply/(\d+)/$", "reply" , name ="reply"),
                   url(r"^new_thread/(\d+)/$", "new_thread" , name  ="new_thread"),
                   url(r"^profile/(\d+)/$", "profile",name= "profile"),
  )

and into my view function
  def profile(request, pk):
      """Edit user profile."""
      profile = UserProfile.objects.get(user=pk)
      img = None

      if request.method == "POST":
          pf = ProfileForm(request.POST, request.FILES, instance=profile)
          if pf.is_valid():
              pf.save()
              # resize and save image under same filename
              imfn = pjoin(MEDIA_ROOT, profile.avatar.name)
              im = PImage.open(imfn)
              im.thumbnail((160,160), PImage.ANTIALIAS)
              im.save(imfn, "JPEG")
      else:
          pf = ProfileForm(instance=profile)

      if profile.avatar:
          img = "/media/" + profile.avatar.name
      return render_to_response("forum/profile.html", add_csrf(request, pf=pf, img=img))

This is my models.py
  from django.db import models
  from django.contrib.auth.models import User
  from django.contrib import admin
  from string import join
  from mysite.settings import MEDIA_ROOT

  class Forum(models.Model):
      title = models.CharField(max_length=60)
      def __unicode__(self):
          return self.title
      def num_posts(self):
          return sum([t.num_posts() for t in self.thread_set.all()])

      def last_post(self):
          if self.thread_set.count():
              last = None
              for t in self.thread_set.all():
                  l = t.last_post()
                  if l:
                      if not last: last = l
                      elif l.created > last.created: last = l
              return last
  class Thread(models.Model):
      title = models.CharField(max_length=60)
      created = models.DateTimeField(auto_now_add=True)
      creator = models.ForeignKey(User, blank=True, null=True)
      forum = models.ForeignKey(Forum)

      def __unicode__(self):
          return unicode(self.creator) + " - " + self.title
      def num_posts(self):
          return self.post_set.count()

      def num_replies(self):
          return self.post_set.count() - 1

      def last_post(self):
          if self.post_set.count():
              return self.post_set.order_by("created")[0]
  class Post(models.Model):
      title = models.CharField(max_length=60)
      created = models.DateTimeField(auto_now_add=True)
      creator = models.ForeignKey(User, blank=True, null=True)
      thread = models.ForeignKey(Thread)
      body = models.TextField(max_length=10000)

      def __unicode__(self):
          return u"%s - %s - %s" % (self.creator, self.thread, self.title)

      def short(self):
          return u"%s - %s\n%s" % (self.creator, self.title, self.created.strftime("%b %d, %I:%M %p"))
short.allow_tags = True

  ### Admin

  class ForumAdmin(admin.ModelAdmin):
      pass

  class ThreadAdmin(admin.ModelAdmin):
      list_display = ["title", "forum", "creator", "created"]
      list_filter = ["forum", "creator"]

  class PostAdmin(admin.ModelAdmin):
      search_fields = ["title", "creator"]
      list_display = ["title", "thread", "creator", "created"]
  class UserProfile(models.Model):
      avatar = models.ImageField("Profile Pic", upload_to="images/", blank=True, null=True)
      posts = models.IntegerField(default=0)
      user = models.ForeignKey(User, unique=True)

      def __unicode__(self):
          return unicode(self.user)

A:

You forgot to put pk in your render:
return render_to_response("forum/profile.html", add_csrf(request, pf=pf, 'profile': profile, img=img))

In html:
Edit profile


Q:

NSMutableSet allows adding multiple objects with the same hash

I have an NSObject subclass in which I implemented the isEqual: and hash methods as follows for testing purposes:
- (BOOL)isEqual:(id)anObject {
    return YES;
}

- (NSUInteger)hash {
    return 1;
}

For some reason, I can add multiple objects of this class to an NSMutableSet even though they are the "same".  Is there any reason this would not be working?

Update: It turns out I was assigning an NSMutableArray instance to an ivar of type NSMutableSet.  D'oh!

A:

There must be something else in your code that you are not doing right, because overriding methods as you show in the OP causes NSMutableSet to recognize my objects as identical:
Test.h:
#import "Foundation/Foundation.h"
@interface Test : NSObject
@end

Test.m:
#import "Test.h"
@implementation Test
- (BOOL)isEqual:(id)anObject {
    return YES;
}
- (NSUInteger)hash {
    return 1;
}
@end

main.c:
#include <CoreFoundation/CoreFoundation.h>
#import "Test.h"
int main (int argc, const char * argv[]) {
    Test *t1 = [[Test alloc] init];
    Test *t2 = [[Test alloc] init];
    Test *t3 = [[Test alloc] init];
    Test *t4 = [[Test alloc] init];
    NSSet *s = [NSMutableSet setWithObjects:t1, t2, t3, t4, nil];
    NSLog(@"%lu", s.count);
    return 0;
}

This snippet produces 1, as expected.


Q:

Setting various types of properties on a JCR node

This code checks value's type and cast it into appropriate type, then puts it into a javax.jcr.Node.
The checking looks long and boring. Is there a way to refactor it?  I'm using Java 7.
/**
 * Set node's property.
 */
public static void setProperty(Node node, String propertyName, Object propertyValue) throws RepositoryException {
    if (node == null) {
        throw new IllegalArgumentException("Something wrong");
    }
    if (propertyName == null) {
        throw new IllegalArgumentException("Property name is invalid");
    }

    if (propertyValue == null) {
        node.setProperty(propertyName, (Value) null);
    } else if (propertyValue instanceof Value) {
        node.setProperty(propertyName, (Value) propertyValue);
    } else if (propertyValue instanceof Node) {
        node.setProperty(propertyName, (Node) propertyValue);
    } else if (propertyValue instanceof Binary) {
        node.setProperty(propertyName, (Binary) propertyValue);
    } else if (propertyValue instanceof Calendar) {
        node.setProperty(propertyName, (Calendar) propertyValue);
    } else if (propertyValue instanceof Date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime((Date) propertyValue);
        node.setProperty(propertyName, cal);
    } else if (propertyValue instanceof BigDecimal) {
        node.setProperty(propertyName, (BigDecimal) propertyValue);
    } else if (propertyValue instanceof String) {
        node.setProperty(propertyName, (String) propertyValue);
    } else if (propertyValue instanceof Long) {
        node.setProperty(propertyName, ((Long) propertyValue).longValue());
    } else if (propertyValue instanceof Double) {
        node.setProperty(propertyName, (Double) propertyValue);
    } else if (propertyValue instanceof Boolean) {
        node.setProperty(propertyName, (Boolean) propertyValue);
    } else if (propertyValue instanceof InputStream) {
        node.setProperty(propertyName, inputStreamToBinary((InputStream) propertyValue));
    } else if (propertyValue instanceof Collection) {
        CollectionFactory factory = CollectionFactoryImpl.getInstance();
        ArrayList<Value> values = new ArrayList<Value>();
        for (Object value : (Collection<Object>) propertyValue) {
            values.add(createValue(value, factory));
        }
        node.setProperty(propertyName, values.toArray(new Value[values.size()]));
    } else {
        throw new IllegalArgumentException("Something wrong");
    }
}

@Test
public void test() {
    Node node = createNode("test");
    setProperty(node, "name", "name");
}

A:

My idea would be to encapsulate the job of casting and converting into some kind of a Strategy pattern.
I would use an enum for that, namely NodeSettingStrategy:
public static enum NodeSettingValueStrategy {
    UNKNOWN(null) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            throw new IllegalArgumentException("Cannot set property to a value of type " + value.getClass());
        }
    },

    DATE(Date.class) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            node.setProperty(propertyName, (Long) value);
        }

    },

    LONG_PRIMITIVE(long.class) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            node.setProperty(propertyName, (long) value);
        }
    },

    LONG(Long.class) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            node.setProperty(propertyName, (Long) value);
        }
    },

    STRING(String.class) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            node.setProperty(propertyName, (String) value);
        }
    },

    NODE(Node.class) {
        @Override
        public void set(Node node, String propertyName, Object value) {
            node.setProperty(propertyName, (Node) value);
        }
    };

    private final Class<?> supportedType;

    private NodeSettingValueStrategy(Class<?> supportedType) {
        this.supportedType = supportedType;
    }

    public static NodeSettingValueStrategy of(Class<?> type) {
        for (NodeSettingValueStrategy strategy : NodeSettingValueStrategy.values()) {
            if (strategy.supportedType == type) {
                return strategy;
            }

        }
        return NodeSettingValueStrategy.UNKNOWN;
    }

    public abstract void set(Node node, String propertyName, Object value);
}

Then I want to hide this NodeSettingStrategy by a thin abstraction, namely NodeSetter:
public static class NodeValueSetter {
    private final NodeSettingValueStrategy strategy;
    private final String propertyName;
    private final Object value;

    private NodeValueSetter(NodeSettingValueStrategy strategy, String propertyName, Object value) {
        this.strategy = strategy;
        this.propertyName = propertyName;
        this.value = value;
    }

    public void setTo(Node node) {
        strategy.set(node, propertyName, value);
    }

    public static NodeValueSetter of(final String propertyName, final Object value) {
        NodeSettingValueStrategy settingStrategy = NodeSettingValueStrategy.of(value.getClass());
        return new NodeValueSetter(settingStrategy, propertyName, value);
    }

}

Combine them together:
@Test
public void should_able_to_set_property() throws Exception {
        Node node = new Node();

        Node givenNode = new Node();
        String someString = "The brown fox jumps over a lazy dog";
        long givenLong = 234234234234L;

        for (NodeValueSetter setter : Arrays.asList(
                NodeValueSetter.of("a-string", someString),
                NodeValueSetter.of("a-number", givenLong),
                NodeValueSetter.of("a-node", givenNode))) {
            setter.setTo(node);
        }

        assertThat(node.getProperty("a-string"), is(someString));
        assertThat(node.getProperty("a-number"), is(givenLong));
        assertThat(node.getProperty("a-node"), is(givenNode));
    }


Q:

Local/Inhouse Ads using AdMob

How can I show inhouse and local ads using AdMob? I want to show them among those retrieved from the Internet.
Should I put the inhouse Ads on the mobile, or should it be uploaded somewhere?

A:

If you are using admob you should use the Admob House Ads Feature. This allows you to show one of your in house ads every time admob fails to load a relevant ad to show into you app. In this way you will not loose a single impression that could convert to a click on an ad but you are using your ad space for useful things if no ad can be displayed.


Q:

Iterating to figure out combinations of variable number of elements

I'm making a program that uses dynamic programming to decide how to distribute some files (Movies) among DVDs so that it uses the least number of DVDs.
After much thought I decided that a good way to do it is to look at every possible combination of movies that is less than 4.38 GB (The actual size of a DVD ) and pick the largest one (i.e. the one that wastes the least space) and remove the movies in the most efficient combination and repeat until it run out of movies.
The problem is that I don't know how to loop so I can figure out every possible combination, given that movies vary in size, so a specific number of nested loops cannot be used.
pseudo-code:
Some kind of loop:
    best_combination=[]
    best_combination_size=0
    if current_combination<4.38 and current_combination>best_combination_size:
        best_combination=current_combination
        best_combination_size=best_combination_size
print(best_combination)
delete best_combination from list_of_movies

first time to post a question..so go easy on me guys!!
Thanks in advance
P.S. I figured out a way to do it using Dijkstra's which I think would be fast but not memory friendly. If anybody is interested i would gladly discuss it.

A:

You should really stick to common bin-packing heuristics. The wikipedia article gives a good overview of approaches including links to problem-tailored exact approaches. But always keep in mind: it's an np-complete problem!
I will show you some example supporting my hint, that you should stick to heuristics.
The following python-code:

creates parameterized random-problems (normal-distribution on multiple means/stds; acceptance-sampling to make sure that no movie is bigger than a DVD)
uses some random binpacking-library which implements some greedy-heuristic (i didn't try or test this lib before; so no guarantees!; no idea which heuristic is used)
uses a naive mixed-integer programming implementation (which is solved by a commercial solver; open-source solvers like cbc struggle, but might be used for good approximate solutions)

Code
import numpy as np
from cvxpy import *
from time import time

""" Generate some test-data """
np.random.seed(1)
N = 150  # movies
means = [700, 1400, 4300]
stds = [100, 300, 500]
DVD_SIZE = 4400

movies = []
for movie in range(N):
    while True:
        random_mean_index = np.random.randint(low=0, high=len(means))
        random_size = np.random.randn() * stds[random_mean_index] + means[random_mean_index]
        if random_size <= DVD_SIZE:
            movies.append(random_size)
            break

""" HEURISTIC SOLUTION """
import binpacking
start = time()
bins = binpacking.to_constant_volume(movies, DVD_SIZE)
end = time()
print('Heuristic solution: ')
for b in bins:
    print(b)
print('used bins: ', len(bins))
print('used time (seconds): ', end-start)

""" Preprocessing """
movie_sizes_sorted = sorted(movies)
max_movies_per_dvd = 0
occupied = 0
for i in range(N):
    if occupied + movie_sizes_sorted[i] <= DVD_SIZE:
        max_movies_per_dvd += 1
        occupied += movie_sizes_sorted[i]
    else:
        break

""" Solve problem """
# Variables
X = Bool(N, N)  # N * number-DVDS
I = Bool(N)     # indicator: DVD used

# Constraints
constraints = []
# (1) DVDs not overfilled
for dvd in range(N):
    constraints.append(sum_entries(mul_elemwise(movies, X[:, dvd])) <= DVD_SIZE)
# (2) All movies distributed exactly once
for movie in range(N):
    constraints.append(sum_entries(X[movie, :]) == 1)
# (3) Indicators
for dvd in range(N):
    constraints.append(sum_entries(X[:, dvd]) <= I[dvd] * (max_movies_per_dvd + 1))

# Objective
objective = Minimize(sum_entries(I))

# Problem
problem = Problem(objective, constraints)
start = time()
problem.solve(solver=GUROBI, MIPFocus=1, verbose=True)
#problem.solve(solver=CBC, CliqueCuts=True)#, GomoryCuts=True, KnapsackCuts=True, verbose=True)#, GomoryCuts=True, MIRCuts=True, ProbingCuts=True,
              #CliqueCuts=True, FlowCoverCuts=True, LiftProjectCuts=True,
              #verbose=True)
end = time()

""" Print solution """
for dvd in range(N):
    movies_ = []
    for movie in range(N):
        if np.isclose(X.value[movie, dvd], 1):
            movies_.append(movies[movie])
    if movies_:
        print('DVD')
        for movie in movies_:
            print('     movie with size: ', movie)

print('Distributed ', N, ' movies to ', int(objective.value), ' dvds')
print('Optimizatio took (seconds): ', end-start)

Partial Output
Heuristic solution:
-------------------
('used bins: ', 60)
('used time (seconds): ', 0.0045168399810791016)

MIP-approach:
-------------
Root relaxation: objective 2.142857e+01, 1921 iterations, 0.10 seconds

    Nodes    |    Current Node    |     Objective Bounds      |     Work
 Expl Unexpl |  Obj  Depth IntInf | Incumbent    BestBd   Gap | It/Node Time

     0     0   21.42857    0  120  106.00000   21.42857  79.8%     -    0s
H    0     0                      68.0000000   21.42857  68.5%     -    0s
H    0     0                      63.0000000   21.42857  66.0%     -    0s
     0     0   21.42857    0  250   63.00000   21.42857  66.0%     -    1s
H    0     0                      62.0000000   21.42857  65.4%     -    2s
     0     0   21.42857    0  256   62.00000   21.42857  65.4%     -    2s
     0     0   21.42857    0  304   62.00000   21.42857  65.4%     -    2s
     0     0   21.42857    0  109   62.00000   21.42857  65.4%     -    3s
     0     2   21.42857    0  108   62.00000   21.42857  65.4%     -    4s
    40     2   27.61568   20   93   62.00000   27.61568  55.5%   110    5s
H  156    10                      61.0000000   58.00000  4.92%  55.3    8s
   262     4   59.00000   84   61   61.00000   59.00000  3.28%  44.2   10s
   413    81 infeasible  110        61.00000   59.00000  3.28%  37.2   15s
H  417    78                      60.0000000   59.00000  1.67%  36.9   15s
  1834  1212   59.00000  232   40   60.00000   59.00000  1.67%  25.7   20s
...
...
 57011 44660 infeasible  520        60.00000   59.00000  1.67%  27.1  456s
 57337 44972   59.00000  527   34   60.00000   59.00000  1.67%  27.1  460s
 58445 45817   59.00000   80   94   60.00000   59.00000  1.67%  26.9  466s
 59387 46592   59.00000  340   65   60.00000   59.00000  1.67%  26.8  472s

Analysis
Some observations regarding the example above:

the heuristic obtains some solution of value 60 instantly
the commercial-solver needs more time but also find a solution of value 60 (15 secs)

also tries to find a better solution or proof that there is no one (MIP-solvers are complete = find optimal solution or proof there is none given infinite time!)
no progress for some time!
but: we got proof, that there is at best a solution of size 59
= maybe you will save one DVD by solving the problem optimally; but it's hard to find a solution and we don't know if this solution exists (yet)!

Remarks

The observations above are heavily dependent on data-statistics
It's easy to try other problems (maybe smaller) where the commercial MIP-solver finds a solution which uses 1 less DVD (e.g. 49 vs. 50)

It's not worth it (remember: open-source solvers are struggling even more)
The formulation is very simple and not tuned at all (don't blame only the solvers)

There are exact algorithms (which might be much more complex to implement) which could be appropriate

Conclusion
Heuristics are very easy to implement and provide very good solutions in general. Most of these also come with very good theoretical guarantees (e.g. at most 11/9 opt + 1 #DVDs compared to optimal solution are used = first fit decreasing heuristic). Despite the fact, that i'm keen on optimization in general, i probably would use the heuristics-approach here.
The general problem is also very popular, so that there should exist some good library for this problem in many programming-languages!


Q:

How to convert image in to binary image using Image processing with Emgu CV

Any suggestions to convert image into binary and remove noise from it. Submit the coding plz. I'm trying to read characters in the image using tesseract function in Emgu CV.

A:

You can transform image into binary by converting it to grayscale and then apllying threshold after that:
var bwImage = colorImg.Convert<Gray, byte>().ThresholdBinary(new Gray(yourThrehold), new Gray(255));

if you have small blobs (salt and pepper noise) you can use median filter -function Median or erode the image (function Erode and that dilating it - funcrtion Dilate)


Q:

How to handle duplicate parameters in a POST request in Jersey

I'm using Jersey 2.22.1 to implement a REST API.
I would like to know how to handle duplicate parameters in a POST request.
This is my resource class:
public class MyResource
{
    @NotNull(message = "Missing parameter 'param1'")
    @FormParam("param1")
    private String m_param1;

    @NotNull(message = "Missing parameter 'param2'")
    @FormParam("param2")
    private String m_param2;

    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes("application/x-www-form-urlencoded")
    public Response test(String body)
    {
        // at this point...
        // the value of `body` is the full request body
        // the value of `m_param1` is the 1st value of param1 in the request body
        // the value of `m_param2` is the value of param2 in the request body
        ...
    }
}

E.g. if I send a POST request with the following body:
param1=00000001&param2=00000002&param1=00000003
then the value of m_param1 is 00000001.
Can the Jersey framework detect the presence of a duplicate parameter in the request body? Or do I need add code to parse the request body to look for duplicates?

A:

You can use a filter to check the parameters to make sure there are no duplicates. If there are, just send a 400 status.
public class DuplicateFormParamsFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        ContainerRequest cr = (ContainerRequest) requestContext;
        cr.bufferEntity();
        Form form = cr.readEntity(Form.class);
        MultivaluedMap<String, String> asMap = form.asMap();
        for (String key: asMap.keySet()) {
            if (asMap.get(key).size() > 1) {
                throw new BadRequestException("Duplicate param: " + key);
            }
        }
    }
}

Here you are reading the request entity, but first buffering it, so that Jersey can re-read it.
Here is a complete example, using Jersey Test Framework.
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.NameBinding;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.client.Entity;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * @author Paul Samsotha
 */
public class DuplicateFormParamsTest extends JerseyTest {

    @Path("test")
    public static class TestResource {

        @POST
        @NoDuplicateParams
        @Consumes("application/x-www-form-urlencoded")
        public String post(@FormParam("param") String param) {
            return param;
        }
    }

    @NoDuplicateParams
    public static class DuplicateFormParamsFilter implements ContainerRequestFilter {

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            ContainerRequest cr = (ContainerRequest) requestContext;
            cr.bufferEntity();
            Form form = cr.readEntity(Form.class);
            MultivaluedMap<String, String> asMap = form.asMap();
            for (String key: asMap.keySet()) {
                if (asMap.get(key).size() > 1) {
                    throw new BadRequestException("Duplicate param: " + key);
                }
            }
        }
    }

    @NameBinding
    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public static @interface NoDuplicateParams {
    }

    @Override
    public ResourceConfig configure() {
        enable(TestProperties.DUMP_ENTITY);
        enable(TestProperties.LOG_TRAFFIC);
        return new ResourceConfig(TestResource.class)
                .register(DuplicateFormParamsFilter.class);
    }

    @Test
    public void sdhoul_get_400_with_dup() {
        final Form form = new Form()
                .param("param", "value1")
                .param("param", "value2");
        final Response response = target("test").request().post(Entity.form(form));
        assertThat(response.getStatus(), is(400));
    }

    @Test
    public void sdhoul_get_200_with_single() {
        final Form form = new Form()
                .param("param", "value1");
        final Response response = target("test").request().post(Entity.form(form));
        assertThat(response.getStatus(), is(200));
        assertThat(response.readEntity(String.class), is("value1"));
    }
}

The example used Name Binding, so that only methods annotated with @NoDuplicateParams will go through the filter. Or you can forget the name binding, and let all requests go through the filter, and just check the Content-Type in the filter for application/x-www-form-urlencoded. This way you don't need to annotate everywhere.

UPDATE
One thing I should mention is that I think I remember a case where this would not work (trying the extract the form as done above). I forgot exactly the case, but it had to do with a servlet environment, and the form params being read prior, so the attempted read above won't work.
What I had to do was use a Jersey internal property, where Jersey stores the parameters. So you would need to retrieve the form this way
Form form = (Form) requestContext.getProperty(
        InternalServerProperties.FORM_DECODED_PROPERTY);


Q:

dplyr+purr: n() refers to map() groups, not local groups?

I have a parent dataset nesting multiple datasets (i.e. a tibble where each cell is a tibble) , where I want for each dataset, to find the number of rows of each group. Standard way, using a single dataset, would simply be to do group_by(var) %>% mutate(nrow=n()).
But now that I do this for multiple datasets with a map() call, it looks like the n() call refers to the (implicit) grouping made by map(), not the explicit grouping within my local dataset made by group_by?
Standard way for one single dataset, n() returns 50:
iris %>%
  group_by(., Species) %>%
  mutate(nrow=n())

Dataset of datasets:
 df <- data_frame(name=c("a", "b"), Data=list(iris, iris))
 df2 <- df %>%
          mutate(Data2=map(Data, ~group_by(., Species) %>%
                 mutate(nrow=n()) %>%
                 ungroup()))

but now n() returned 2?
df2[1,]$Data2[[1]]

A:

If you define the function outside of mutate it works fine (I assume this output is what you have in mind...)
fun <- function(x) {
  df <- group_by(x, Species) %>%
    summarise(nrow = n())
}
df2 <- df %>%
  mutate(Data2=map(Data, fun))

df2$Data2
# [[1]]
# # A tibble: 3 x 2
# Species  nrow
# <fctr> <int>
# 1     setosa    50
# 2 versicolor    50
# 3  virginica    50
#
# [[2]]
# # A tibble: 3 x 2
# Species  nrow
# <fctr> <int>
# 1     setosa    50
# 2 versicolor    50
# 3  virginica    50


Q:

What are the more advanced rules needed for your code to become CLS-complaint?

Here is a specific example which is not CLS-complaint according to VS.NET 2005.
Public Interface IDbId

    Function GetNativeObject() As Object
    Function Equals(ByVal compObj As IDbId) As Boolean
    Function CompareTo(ByVal compObj As IDbId) As Integer
    Function ToString() As String

End Interface

This is an interface I implement with classes such as DbId32, DbId64, DbIdString, etc. It is a way to abstract the native database primary key type into one common .Net type.
What I'm not displaying is the factory method which instantiates the correct concrete type (ie new DbId32 for a SQL Server type 'int', for example) given a native database type.
Now let's say I go to use this interface like so:
Public MustOverride ReadOnly Property ID() As IDbId

VS now outputs this warning message:

Return type of function 'ID' is not CLS-complaint.

I can stop these warnings by adding this attribute to my interface like so:
<CLSCompliant(True)> _
  Public Interface IDbId
  ...

None of the functions this interface defines seem to break the rules documented here. So why is VS displaying these warnings?

A:

I think it's due to the MustOverride keyword modifier in your example.
Check this out:
Non-CLS-compliant 'MustOverride' member is not allowed in a CLS-compliant class


Q:

Multiple Alerts in one view can only the last alert works always in swiftui

I have two alert which is called if the boolean is true.
Alert - 1 - It is called if there is any issues with the bluetooth state other than powered on.This is called directly from a swift package named BLE. The code snippet is below.
Alert - 2 - It is called when you want to unpair the peripheral giving the user two options.Unpair or remain on the same page.
Issue :
Both the alert seems to be working fine but if they are not placed in the same view. When I place the alert in the same view the last displayed alert is called from the sequence top to bottom.
The OS reads the first alert but only activates the second alert if it's called.
Is there a way to make both alert functional if they are called.
I referred to below solution but i was getting the same results.
Solution 1   and Solution 2
There are 2 Code snippets
1. Main Application
import SwiftUI
import BLE

struct Dashboard: View {

    @EnvironmentObject var BLE: BLE
    @State private var showUnpairAlert: Bool = false

    private var topLayer: HeatPeripheral {
        self.BLE.peripherals.baseLayer.top
    }

    var body: some View {
        VStack(alignment: .center, spacing: 0) {
            // MARK: - Menu Bar
            VStack(alignment: .center, spacing: 4) {
                Button(action: {
                    print("Unpair tapped!")
                    self.showUnpairAlert = true
                }) {
                    HStack {
                        Text("Unpair")
                            .fontWeight(.bold)
                            .font(.body)
                    }
                    .frame(minWidth: 85, minHeight: 35)
                    .cornerRadius(30)
                }
            }

        }
        .onAppear(perform: {
            self.BLE.update()
        })

            // Alert 1 - It is called if it meets one of the cases and returns the alert
            // It is presented in the function centralManagerDidUpdateState
            .alert(isPresented: $BLE.showStateAlert, content: { () -> Alert in

                let state = self.BLE.centralManager!.state
                var message = ""

                switch state {
                case .unknown:
                    message = "Bluetooth state is unknown"
                case .resetting:
                    message = "Bluetooth is resetting..."
                case .unsupported:
                    message = "This device doesn't have a bluetooth radio."
                case .unauthorized:
                    message = "Turn On Bluetooth In The Settings App to Allow Battery to Connect to App."
                case .poweredOff:
                    message = "Turn On Bluetooth to Allow Battery to Connect to App."
                    break
                @unknown default:
                    break
                }

                return Alert(title: Text("Bluetooth is \(self.BLE.getStateString())"), message: Text(message), dismissButton: .default(Text("OK")))
            })

            // Alert 2 - It is called when you tap the unpair button

            .alert(isPresented: $showUnpairAlert) {
                Alert(title: Text("Unpair from \(checkForDeviceInformation())"), message: Text("*Your peripheral command will stay on."), primaryButton: .destructive(Text("Unpair")) {
                    self.unpairAndSetDefaultDeviceInformation()
                    }, secondaryButton: .cancel())
        }
    }
    func unpairAndSetDefaultDeviceInformation() {
        defaults.set(defaultDeviceinformation, forKey: Keys.deviceInformation)
        disconnectPeripheral()
        print("Pod unpaired and view changed to Onboarding")
        self.presentationMode.wrappedValue.dismiss()
        DispatchQueue.main.async {
            self.activateLink = true
        }

    }
    func disconnectPeripheral(){
        if skiinBLE.peripherals.baseLayer.top.cbPeripheral != nil {
            self.skiinBLE.disconnectPeripheral()
        }
    }

}

2. BLE Package
import SwiftUI
import Combine
import CoreBluetooth

public class BLE: NSObject, ObservableObject {

    public var centralManager: CBCentralManager? = nil
    public let baseLayerServices = "XXXXXXXXXXXXXXX"
    let defaults = UserDefaults.standard
    @Published public var showStateAlert: Bool = false

    public func start() {
        self.centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)
        self.centralManager?.delegate = self
    }

    public func getStateString() -> String {
        guard let state = self.centralManager?.state else { return String() }
        switch state {
        case .unknown:
            return "Unknown"
        case .resetting:
            return "Resetting"
        case .unsupported:
            return "Unsupported"
        case .unauthorized:
            return "Unauthorized"
        case .poweredOff:
            return "Powered Off"
        case .poweredOn:
            return "Powered On"
        @unknown default:
            return String()
        }
    }

}

extension BLE: CBCentralManagerDelegate {

    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        print("state: \(self.getStateString())")
        if central.state == .poweredOn {
            self.showStateAlert = false

            if let connectedPeripherals =  self.centralManager?.retrieveConnectedPeripherals(withServices: self.baseLayerServices), connectedPeripherals.count > 0 {
                print("Already connected: \(connectedPeripherals.map{$0.name}), self.peripherals: \(self.peripherals)")
                self.centralManager?.stopScan()

            }
            else {
                print("scanForPeripherals")
                self.centralManager?.scanForPeripherals(withServices: self.baseLayerServices, options: nil)
            }
        }
        else {
            self.showStateAlert = true // Alert is called if there is any issue with the state.
        }
    }
}

Thank You !!!

A:

The thing to remember is that view modifiers don't really just modify a view, they return a whole new view. So the first alert modifier returns a new view that handles alerts in the first way.  The second alert modifier returns a new view that modifies alerts the second way (overwriting the first method) and that's the only one that ultimately is in effect. The outermost modifier is what matters.
There are couple things you can try, first try attaching the different alert modifiers to two different view, not the same one.
Second you can try the alternate form of alert that takes a Binding of an optional Identifiable and passes that on to the closure. When value is nil, nothing happens. When the state of changes to something other than nil, the alert should appear.
Here's an example using the alert(item:) form as opposed to the Bool based alert(isPresented:).
enum Selection: Int, Identifiable {
  case a, b, c
  var id: Int { rawValue }
}

struct MultiAlertView: View {

  @State private var selection: Selection? = nil

  var body: some View {

    HStack {
      Button(action: {
        self.selection = .a
      }) { Text("a") }

      Button(action: {
        self.selection = .b
      }) { Text("b") }

    }.alert(item: $selection) { (s: Selection) -> Alert in
      Alert(title: Text("selection: \(s.rawValue)"))
    }
  }
}


Q:

What is new "Reset on new activity" option about on Google Analytics?

Google analitycs announced today their new policy about data retention
Google Analytics Data Retention
Along with the option for choosing how long data will be stored (I chose do not delete data, obviously), there is an option "Reset on new activity".
I cannot find info about what is this option about. What they mean by 'activity'? If I don't switch it off, the option could be reset and data deleted?

A:

It means that the counter for data retention is reset when the user visits the page again.
Image your retention period is set to 15 months.
User visits once = after 15 months the data is purged.
User visits. One month later the user visits a second time = second visit resets the counter, effectively user data is retained for 16 months in total.


Q:

Первый раз отправляется get запрос, 2 раз нет

    public interface OAuthServerIntf {

    @GET("drive/v2/files")
    Call<GDriveFiles> listFiles1(
        @Query("q") String q
    );
    }

Вот, где обрабатывается запрос и при выборе элемента в списке снова запускается с новым параметром q:
    private void listGDriveUserFiles(String q){
    OAuthServerIntf server=RetrofitBuilder.getOAuthClient(this);
    Call<GDriveFiles> listFilesCall=server.listFiles(q);
    listFilesCall.enqueue(new Callback<GDriveFiles>() {
        @Override
        public void onResponse(Call<GDriveFiles> call, Response<GDriveFiles> response) {
            Log.e(TAG,"The call listFilesCall succeed with [code="+response.code()+" and has body = "+response.body()+" and message = "+response.message()+" ]");
            //ok we have the list of files on GDrive
            if(response.code()==200&&response.body()!=null){
                // txvResult.setText(response.body().toString());

                for (GDriveFile file : response.body().getFiles()) {
                    // txvResult.setText(txvResult.getText()+file.getName()+" ");
                    gdriveFiles.add(file);
                }
                adapter = new Data_Adapter(context, R.layout.list_item, gdriveFiles);
                txvResult.setAdapter(adapter);
                txvResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        GDriveFile selectedItem = gdriveFiles.get(position);
                        listGDriveUserFiles(selectedItem.getId());
                    }
                });

            }else if(response.code()==400){

            }else if(response.code()==401){

            }else if(response.code()==403){

            }else if(response.code()==404){

            }
        }

        @Override
        public void onFailure(Call<GDriveFiles> call, Throwable t) {
            Log.e(TAG,"The call listFilesCall failed",t);
        }
    });
}

В первый раз запрос обрабатывается, а второй раз проходит Callback метод и выходит полностью из метода. Используется GOOGLE API. В чем причина?

A:

Метод, в принципе, работает . Нужно очищать gdriveFiles перед заполнение в него данными. Тогда все будет наглядно видно.
Встречный вопрос: как лучше организовать проход по папкам Гугл драйв? Сделать для этого стэк и записывать в него id предыдущей папки, от которой был осуществлён переход. Или есть какой-то более эффективный способ?