问:
JPA static metamodel classes in EclipseLink throw NullPointerException when accessing attributes
I have a problem with generated static metamodel classes in EclipseLink.
In my project I firstly generated static metamodel classed for my entities using:

1) org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor and IntelliJ IDEA
   and this classes have been generated to: target/generated-sources

Then I try to use such Hibernate generated metamodel classes (ex. below) with EclipseLink (GlassFish embedded), but lines of code that contains references to metamodel attributes throws NullPointerException exception:

```<code> SingularAttribute<Employee, String> descriptionAttr = Employee_.description;
 predicates.add(criteriaBuilder.like(employee.get(descriptionAttr), "%" + description + "%"));
</code>```

Here emploee.get( >> null << ) throws exception.

```<code>@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Employee.class)
public abstract class Employee_ extends pl.salonea.entities.NaturalPerson_ {

    public static volatile SetAttribute<Employee, Skill> skills;
    public static volatile SetAttribute<Employee, ProviderService> suppliedServices;
    public static volatile SetAttribute<Employee, EmployeeRating> receivedRatings;
    public static volatile SingularAttribute<Employee, String> description;
    public static volatile SetAttribute<Employee, Education> educations;
    public static volatile SingularAttribute<Employee, String> jobPosition;
    public static volatile SetAttribute<Employee, TermEmployeeWorkOn> termsOnWorkStation;

}
</code>```

2) Next I thought that this metamodel classes maybe are implementation specific. So I generated them analogically with EclipseLink using
org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor and target/generated-sources-eclipselink (as on picture)

At the end I have something like this directory stracture with metamodel:

3) I am also using in build.gradle such configuration to as I think include this generated sources in project:

```<code>if(hasProperty('jboss')) {
    sourceSets {
        main {
            java {
                srcDir 'target/generated-sources/'
            }
        }
    }
} else {
    sourceSets {
        main {
            java {
                srcDir 'target/generated-sources-eclipselink/'
            }
        }
    }
}
</code>```

This way I want to use Hibernate generated classes with Jboss and EclipseLink generated classes with EclipseLink.

4) Such configuration works only if running on WilfFly/Hibernate but not on GlassFish/EclipseLink here is this NullPointerException

5) In persistence.xml I have more over EclipseLink generation using such property for one Persistence Unit

```<code><property name="eclipselink.canonicalmodel.subpackage" value="metamodel" />
</code>```

and such property for second Persistence Unit (to avoid duplicate conflict)

```<code><property name="eclipselink.canonicalmodel.subpackage" value="metamodel_local" />
</code>```

But I'm trying not to use this generation. It is in subpackage and in my code I only import previously generated metamodel classes.
The reason is that I would like to have in the same namespace metamodel classes generated by Hibernate/Eclipse and use them appropriately.
However if Hibernate generated metamodel classes could be also work with EclipseLink there won't be problem to using only one generation.

6) Moreover I cant use metamodel classes generated by EclipseLink persistence.xml property as they are regenerated each time I run/build my project. And I need in my code to manually modify two metamodel classes as they are inherited from single abstract metamodel class. Here I am overriding in subclasses AbstractType with ConcreteType on SetAttribute of metamodel class.

7) At the end I paste error I'm getting while running integration test with such configuration of metamodel classes

```<code> Caused by: java.lang.NullPointerException
    at org.eclipse.persistence.internal.jpa.querydef.FromImpl.get(FromImpl.java:263)
    at pl.salonea.ejb.stateless.EmployeeFacade.findByMultipleCriteria(EmployeeFacade.java:295)
    at pl.salonea.ejb.stateless.EmployeeFacade.findByMultipleCriteria(EmployeeFacade.java:269)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
    at sun.reflect.GeneratedMethodAccessor113.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.GeneratedMethodAccessor141.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    ... 149 more
</code>```

答:
I know this is an old ticket but i still wanted to let you guys know how we fixed the problem. Especially the last nullpointer exception.

The problem is that your entitimanager is not loaded when you are using your Criteriabuilder for the first time.
To solve this problem you can set following in you persistence.xml

```<code><property name="eclipselink.deploy-on-startup" value="true" />
</code>```

Body:
I have a problem with generated static metamodel classes in EclipseLink.
In my project I firstly generated static metamodel classed for my entities using:

1) org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor and IntelliJ IDEA
   and this classes have been generated to: target/generated-sources

Then I try to use such Hibernate generated metamodel classes (ex. below) with EclipseLink (GlassFish embedded), but lines of code that contains references to metamodel attributes throws NullPointerException exception:

 SingularAttribute<Employee, String> descriptionAttr = Employee_.description;
 predicates.add(criteriaBuilder.like(employee.get(descriptionAttr), "%" + description + "%"));

Here emploee.get( >> null << ) throws exception.

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Employee.class)
public abstract class Employee_ extends pl.salonea.entities.NaturalPerson_ {

    public static volatile SetAttribute<Employee, Skill> skills;
    public static volatile SetAttribute<Employee, ProviderService> suppliedServices;
    public static volatile SetAttribute<Employee, EmployeeRating> receivedRatings;
    public static volatile SingularAttribute<Employee, String> description;
    public static volatile SetAttribute<Employee, Education> educations;
    public static volatile SingularAttribute<Employee, String> jobPosition;
    public static volatile SetAttribute<Employee, TermEmployeeWorkOn> termsOnWorkStation;

}

2) Next I thought that this metamodel classes maybe are implementation specific. So I generated them analogically with EclipseLink using
org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor and target/generated-sources-eclipselink (as on picture)

At the end I have something like this directory stracture with metamodel:

3) I am also using in build.gradle such configuration to as I think include this generated sources in project:

if(hasProperty('jboss')) {
    sourceSets {
        main {
            java {
                srcDir 'target/generated-sources/'
            }
        }
    }
} else {
    sourceSets {
        main {
            java {
                srcDir 'target/generated-sources-eclipselink/'
            }
        }
    }
}

This way I want to use Hibernate generated classes with Jboss and EclipseLink generated classes with EclipseLink.

4) Such configuration works only if running on WilfFly/Hibernate but not on GlassFish/EclipseLink here is this NullPointerException

5) In persistence.xml I have more over EclipseLink generation using such property for one Persistence Unit

<property name="eclipselink.canonicalmodel.subpackage" value="metamodel" />

and such property for second Persistence Unit (to avoid duplicate conflict)

<property name="eclipselink.canonicalmodel.subpackage" value="metamodel_local" />

But I'm trying not to use this generation. It is in subpackage and in my code I only import previously generated metamodel classes.
The reason is that I would like to have in the same namespace metamodel classes generated by Hibernate/Eclipse and use them appropriately.
However if Hibernate generated metamodel classes could be also work with EclipseLink there won't be problem to using only one generation.

6) Moreover I cant use metamodel classes generated by EclipseLink persistence.xml property as they are regenerated each time I run/build my project. And I need in my code to manually modify two metamodel classes as they are inherited from single abstract metamodel class. Here I am overriding in subclasses AbstractType with ConcreteType on SetAttribute of metamodel class.

7) At the end I paste error I'm getting while running integration test with such configuration of metamodel classes

 Caused by: java.lang.NullPointerException
    at org.eclipse.persistence.internal.jpa.querydef.FromImpl.get(FromImpl.java:263)
    at pl.salonea.ejb.stateless.EmployeeFacade.findByMultipleCriteria(EmployeeFacade.java:295)
    at pl.salonea.ejb.stateless.EmployeeFacade.findByMultipleCriteria(EmployeeFacade.java:269)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
    at sun.reflect.GeneratedMethodAccessor113.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    at sun.reflect.GeneratedMethodAccessor141.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    ... 149 more

Body:
I know this is an old ticket but i still wanted to let you guys know how we fixed the problem. Especially the last nullpointer exception.

The problem is that your entitimanager is not loaded when you are using your Criteriabuilder for the first time.
To solve this problem you can set following in you persistence.xml

<property name="eclipselink.deploy-on-startup" value="true" />


来源: stackexchange

问:
Parsing JSON and creating hashmap
I did a function that parse a JSON and create a hashmap to use my data in some operations. The problem that I found, is that my key is repeted several time and in a hashmap there is only one value per key. The way I want it to be, is like this example :

```<code>12345 : 5
12346 : 4
12346 : 3
</code>```

My function return this : { 12345 : 5 , 12346 : 3 }
So to resume, it overload the key with the last value founded.

In my case i need all this value, so I want to have a result like this :

Result =>

```<code>{ 12345 : 5 , 12346 : [4,3] }
</code>```

Objective : if I find another key, I should change the value into an array and not overload it.

Here is my function :

```<code>getFacingCount: function(iSceneGraph){
                var facingArray = {};
                if (iSceneGraph.children.length > 0){
                    for (var i = 0; i < iSceneGraph.children.length; i++){
                        facingArray = Object.assign(facingArray, this.getFacingCount(iSceneGraph.children[i]));
                    }
                }
                if (iSceneGraph.merch.type === "Facing"){
                    facingArray[iSceneGraph.merch.ean] = iSceneGraph.merch.hcount;
                }
                return facingArray;
            }
</code>```

答:
Assuming your JSON looks like an array of objects: [{12345: 5}, {12346: 4}, {12346: 3}] you can use Array.prototype.reduce():

var json = [{12345: 5}, {12346: 4}, {12346: 3}],
    result = json.reduce(function (acc, obj) {
      var key = Object.keys(obj);
      acc[key] = !acc[key] ? obj[key] : [].concat(acc[key], obj[key]);
      return acc;
    }, {});

console.log(result);```

ContentLicense: CC BY-SA 3.0

Title: Parsing JSON and creating hashmap

Body:
I did a function that parse a JSON and create a hashmap to use my data in some operations. The problem that I found, is that my key is repeted several time and in a hashmap there is only one value per key. The way I want it to be, is like this example :

12345 : 5
12346 : 4
12346 : 3

My function return this : { 12345 : 5 , 12346 : 3 }
So to resume, it overload the key with the last value founded.

In my case i need all this value, so I want to have a result like this :

Result =>

{ 12345 : 5 , 12346 : [4,3] }

Objective : if I find another key, I should change the value into an array and not overload it.

Here is my function :

getFacingCount: function(iSceneGraph){
                var facingArray = {};
                if (iSceneGraph.children.length > 0){
                    for (var i = 0; i < iSceneGraph.children.length; i++){
                        facingArray = Object.assign(facingArray, this.getFacingCount(iSceneGraph.children[i]));
                    }
                }
                if (iSceneGraph.merch.type === "Facing"){
                    facingArray[iSceneGraph.merch.ean] = iSceneGraph.merch.hcount;
                }
                return facingArray;
            }


问:
Send value from function to an other VC, swift3
I have this function, which is called when the user clicks on the image on the collectionView. There is a variable url (in the line print("IMAGE CLICKED:", url)) I want to send the value of the url to another viewController and set url in a UIImage.

Here is my unfinished function in the firstVC. From here I'd like to send the url to the secondVC.

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedCommunity = (liveCommunities?[indexPath.row].communityId)!
    let home = HomeViewController()
    home.showCommunityDetail()

    //url is the source for a image in another viewController
    //TODO: Send url to other viewController
    //There is no relation between the thwo viewControllers (only via tabbar)

    print("--------")
    print("IMAGE CLICKED:", url)
    print("--------")

}
</code>```

Is that possible? Thanks for your help in advance!

答:
You can do this easily via a custom notification. Set up an observer in the second view controller and post a notification with an userInfo containing the variable in the first one. You can easily handle the URL in the second view controller by retrieving the userInfo.

First view controller:

```<code>NotificationCenter.default.post(name: Notification.Name.init(rawValue: "imagePressed"), object: nil, userInfo: ["imageUrl": url])
</code>```

Second view controller:

```<code>NotificationCenter.default.addObserver(self, selector: #selector(imagePressed(_:)), name: Notification.Name.init(rawValue: "imagePressed"), object: nil)

func imagePressed(_ notification: Notification) {
    let url = notification.userInfo!["imageUrl"] as! URL
}
</code>```

Body:
I have this function, which is called when the user clicks on the image on the collectionView. There is a variable url (in the line print("IMAGE CLICKED:", url)) I want to send the value of the url to another viewController and set url in a UIImage.

Here is my unfinished function in the firstVC. From here I'd like to send the url to the secondVC.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedCommunity = (liveCommunities?[indexPath.row].communityId)!
    let home = HomeViewController()
    home.showCommunityDetail()

    //url is the source for a image in another viewController
    //TODO: Send url to other viewController
    //There is no relation between the thwo viewControllers (only via tabbar)

    print("--------")
    print("IMAGE CLICKED:", url)
    print("--------")

}

Is that possible? Thanks for your help in advance!

Body:
You can do this easily via a custom notification. Set up an observer in the second view controller and post a notification with an userInfo containing the variable in the first one. You can easily handle the URL in the second view controller by retrieving the userInfo.

First view controller:

NotificationCenter.default.post(name: Notification.Name.init(rawValue: "imagePressed"), object: nil, userInfo: ["imageUrl": url])

Second view controller:

NotificationCenter.default.addObserver(self, selector: #selector(imagePressed(_:)), name: Notification.Name.init(rawValue: "imagePressed"), object: nil)

func imagePressed(_ notification: Notification) {
    let url = notification.userInfo!["imageUrl"] as! URL
}

ContentLicense: CC BY-SA 4.0


问:
fatal error: numpy/arrayobject.h: No such file or directory
I am limited on what I can share as this is part of a huge stack of code that I am porting from Ubuntu 14.04 to 16.04.

It should be trivial, but somehow I am struggling with this. It doesn't find numpy/arrayobject.h that I am referencing in my source file with #include <numpy/arrayobject.h>

I will try to share as much as I can, see if someone can guide me through a resolution.

Ubuntu

```<code>$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.2 LTS
Release:    16.04
Codename:   xenial
</code>```

make

```<code>$ make --version
GNU Make 4.1
Built for x86_64-pc-linux-gnu
</code>```

g++

```<code>$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
</code>```

upgraded to

```<code># g++ --version
g++ (Ubuntu 5.4.1-2ubuntu1~16.04) 5.4.1 20160904
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

python

```<code>$ python --version
Python 2.7.12
</code>```

Some environment variables

```<code>PYTHON       /usr/bin/python2.7
ARCH         x86_64
OS           Linux
VERSION      4.4.071generic
PLATFORM     linux2
HOSTNAME     deploy
USER         myUser
WUSS_BUILD   NO
CCVER        gcc
PYLIBDIR     build.x86_64-linux2
LIBDIR       build.x86_64-linux2
BINDIR       build.x86_64-linux2
ODIR         build.x86_64-linux2-gcc
STATICLIBDIR build-static.x86_64-linux2
</code>```

Error

The make command leads to

```<code>+++ Compile mycore/boost_numpy.cc to build.x86_64-linux2-gcc
anycore/boost_numpy.cc:2:31: fatal error: numpy/arrayobject.h: No such file or directory
</code>```

My source file

```<code>user@deploy:~/my-linux$ vim mycore/boost_numpy.cc

#include "anycore/boost_python_headers.h"
#include <numpy/arrayobject.h>           <====== DECLARATION
#include <numpy/ufuncobject.h>
#include "mycore/boost_numpy.h"
#include "mycore/numerical.h"
#include "mycore/vec3.h"

using namespace boost::python;

PyObject *
read_numeric_file_ficii(FILE *fp, int ncols, char arrtype, int headlines, int taillines)
{
  if (!(arrtype=='d' || arrtype=='f' || arrtype=='i')) {
    PyErr_SetString(PyExc_ValueError, "Unknown array type for read_numeric_file");
    return NULL;
  }
...FILTERED...
</code>```

Declaration file numpy/arrayobject.h on disk

```<code>root@deploy:/home#  find / -name arrayobject.h
/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h
</code>```

Please let me know how I can improve the question. Directions or pointers are most welcome

UPDATE

```<code>$ ls -l /usr/include/numpy
ls: cannot access '/usr/include/numpy': No such file or directory
</code>```

RESOLVED WITH

```<code>sudo ln -s  /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy /usr/include/numpy
</code>```

答:
How did you install numpy?

If you install python-numpy correctly, e.g. by sudo apt-get install python-numpy, you will have /usr/include/numpy linked to the correct path:

```<code>$ ls -l /usr/include/numpy
lrwxrwxrwx 1 root root 55 Sep 17  2014 /usr/include/numpy -> ../lib/python2.7/dist-packages/numpy/core/include/numpy
</code>```

It looks like you may build your numpy manually, then you can manually create a soft link accordingly.

Body:
I am limited on what I can share as this is part of a huge stack of code that I am porting from Ubuntu 14.04 to 16.04.

It should be trivial, but somehow I am struggling with this. It doesn't find numpy/arrayobject.h that I am referencing in my source file with #include <numpy/arrayobject.h>

I will try to share as much as I can, see if someone can guide me through a resolution.

Ubuntu

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.2 LTS
Release:    16.04
Codename:   xenial

make

$ make --version
GNU Make 4.1
Built for x86_64-pc-linux-gnu

g++

$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

upgraded to

# g++ --version
g++ (Ubuntu 5.4.1-2ubuntu1~16.04) 5.4.1 20160904
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

python

$ python --version
Python 2.7.12

Some environment variables

PYTHON       /usr/bin/python2.7
ARCH         x86_64
OS           Linux
VERSION      4.4.071generic
PLATFORM     linux2
HOSTNAME     deploy
USER         myUser
WUSS_BUILD   NO
CCVER        gcc
PYLIBDIR     build.x86_64-linux2
LIBDIR       build.x86_64-linux2
BINDIR       build.x86_64-linux2
ODIR         build.x86_64-linux2-gcc
STATICLIBDIR build-static.x86_64-linux2

Error

The make command leads to

+++ Compile mycore/boost_numpy.cc to build.x86_64-linux2-gcc
anycore/boost_numpy.cc:2:31: fatal error: numpy/arrayobject.h: No such file or directory

My source file

user@deploy:~/my-linux$ vim mycore/boost_numpy.cc

#include "anycore/boost_python_headers.h"
#include <numpy/arrayobject.h>           <====== DECLARATION
#include <numpy/ufuncobject.h>
#include "mycore/boost_numpy.h"
#include "mycore/numerical.h"
#include "mycore/vec3.h"

using namespace boost::python;

PyObject *
read_numeric_file_ficii(FILE *fp, int ncols, char arrtype, int headlines, int taillines)
{
  if (!(arrtype=='d' || arrtype=='f' || arrtype=='i')) {
    PyErr_SetString(PyExc_ValueError, "Unknown array type for read_numeric_file");
    return NULL;
  }
...FILTERED...

Declaration file numpy/arrayobject.h on disk

root@deploy:/home#  find / -name arrayobject.h
/usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h

Please let me know how I can improve the question. Directions or pointers are most welcome

UPDATE

$ ls -l /usr/include/numpy
ls: cannot access '/usr/include/numpy': No such file or directory

RESOLVED WITH

sudo ln -s  /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy /usr/include/numpy

Body:
How did you install numpy?

If you install python-numpy correctly, e.g. by sudo apt-get install python-numpy, you will have /usr/include/numpy linked to the correct path:

$ ls -l /usr/include/numpy
lrwxrwxrwx 1 root root 55 Sep 17  2014 /usr/include/numpy -> ../lib/python2.7/dist-packages/numpy/core/include/numpy

It looks like you may build your numpy manually, then you can manually create a soft link accordingly.


问:
The request was aborted: Could not create SSL/TLS secure channel for HttpWebRequest
I am using an asmx webservice client to connect to a backend web service and we have multiple environments .In one of the server ,am getting error "The request was aborted: Could not create SSL/TLS secure channel" but every other environments it works fine. I referred  below articles already and none of it helped.

The request was aborted: Could not create SSL/TLS secure channel.

The request was aborted: Could not create SSL/TLS secure

HttpWebRequest: The request was aborted: Could not create SSL/TLS secure channel

HttpWebRequest The request was aborted: Could not create SSL/TLS secure channel

答:
If the issue is server specific ,you may be running into any issue
  with Server Certification validation check (because of the Root
  Certificate missing) or CRL check failure ,then following code might
  help.Add this to your project and verify

```<code>ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
</code>```

Please note that this is not a good way as we are just making all the ServerCertificateValidation always true .

If server validation is the issue,the correct way to do is to make sure your you can successfully access the https url from the machine.You can browse to the URL using any browser and it should be successfully be able to browse without any warning.if any warning comes(e.g. certificate not trusted),verify the error and make sure you have the required root certificate installed etc

Hope this helps!

Body:
If the issue is server specific ,you may be running into any issue
  with Server Certification validation check (because of the Root
  Certificate missing) or CRL check failure ,then following code might
  help.Add this to your project and verify

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;

Please note that this is not a good way as we are just making all the ServerCertificateValidation always true .

If server validation is the issue,the correct way to do is to make sure your you can successfully access the https url from the machine.You can browse to the URL using any browser and it should be successfully be able to browse without any warning.if any warning comes(e.g. certificate not trusted),verify the error and make sure you have the required root certificate installed etc

Hope this helps!


问:
How to change the ImageIO write Endianness
Im writing the RenderedImage of PDF to a tiff file using

```<code>javax.imageio.ImageIO.write(RenderedImage,"tif" ,file)
</code>```

Im expecting my tiff file endian is little-endian, However it writes in big-endian, can help to explain how to change it to little-endian ?

Can also explain why the data written using big-endian take more size than original file size ?
I tried to convert the data to little-endian outside of my java code ,and the file size reduced drastically from 16 MB to 943 bytes.

答:
The ImageIO API doesn't have a standardized way to specify endianness (byte order). How to do this, or whether or not it is supported at all, is plugin-dependent.

For the TIFF format, there exists multiple plugins (JAI, GeoTIFF, TwelveMonkeys, JDK9). All of the mentioned plugins (to my knowledge) supports setting the endianness using the stream metadata sent to ImageWriter.write(...). The byte order is the only field you can set in the TIFF stream metadata.

```<code>ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
writer.setOutput(stream);

IIOMetadata streamMetadata = writer.getDefaultStreamMetadata();

IIOMetadataNode root = new IIOMetadataNode("com_sun_media_imageio_plugins_tiff_stream_1.0");
IIOMetadataNode byteOrder = new IIOMetadataNode("ByteOrder");
byteOrder.setAttribute("value", order == LITTLE_ENDIAN ? "LITTLE_ENDIAN" : "BIG_ENDIAN");
root.appendChild(byteOrder);

streamMetadata .mergeTree("com_sun_media_imageio_plugins_tiff_stream_1.0", root);

// ...

writer.write(streamMetadata, new IIOImage(image, null, null), param);
</code>```

In addition, if not specified using the stream metadata, the TwelveMonkeys TIFF plugin will use the byte order from the ImageOutputStream it is writing to. Specifying the byte order this way is in my mind more straight forward, but obviously less compatible between plugins.

```<code>try (ImageOutputStream stream = ImageIO.createImageOutputStream(out)) {
    stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);

    ImageIO.write(image, "TIFF", stream);
}
</code>```

Regarding the file size, most known TIFF plugins will write uncompressed image data by default. There is, unfortunately, no way to specify the compression settings directly using the ImageIO convenience methods, so any TIFF you write using these methods will be uncompressed.

The ImageIO API instead requires you to obtain an ImageWriter for the format you want to write to, and pass in an ImageWriteParam to specify the compression settings. Note that the types of compression supported may vary by plugin. Also note that which compression type that yield the best compression rate, varies depending on the image data you are trying to compress.

```<code>ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
writer.setOutput(stream);

ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("LZW"); // "Zlib", "PackBits", "JPEG", "CCITT T.4", "CCITT T.6" etc.
param.setCompressionQuality(0.5f); // Applies only to some compression types. Generally:
                                   // * 0.0 means highest compression
                                   // * 1.0 means best quality
</code>```

You can query what compression types are available in the current plugin, using:

```<code>String[] types = param.getCompressionTypes();
</code>```

Body:
Im writing the RenderedImage of PDF to a tiff file using

javax.imageio.ImageIO.write(RenderedImage,"tif" ,file)

Im expecting my tiff file endian is little-endian, However it writes in big-endian, can help to explain how to change it to little-endian ?

Can also explain why the data written using big-endian take more size than original file size ?
I tried to convert the data to little-endian outside of my java code ,and the file size reduced drastically from 16 MB to 943 bytes.

Body:
The ImageIO API doesn't have a standardized way to specify endianness (byte order). How to do this, or whether or not it is supported at all, is plugin-dependent.

For the TIFF format, there exists multiple plugins (JAI, GeoTIFF, TwelveMonkeys, JDK9). All of the mentioned plugins (to my knowledge) supports setting the endianness using the stream metadata sent to ImageWriter.write(...). The byte order is the only field you can set in the TIFF stream metadata.

ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
writer.setOutput(stream);

IIOMetadata streamMetadata = writer.getDefaultStreamMetadata();

IIOMetadataNode root = new IIOMetadataNode("com_sun_media_imageio_plugins_tiff_stream_1.0");
IIOMetadataNode byteOrder = new IIOMetadataNode("ByteOrder");
byteOrder.setAttribute("value", order == LITTLE_ENDIAN ? "LITTLE_ENDIAN" : "BIG_ENDIAN");
root.appendChild(byteOrder);

streamMetadata .mergeTree("com_sun_media_imageio_plugins_tiff_stream_1.0", root);

// ...

writer.write(streamMetadata, new IIOImage(image, null, null), param);

In addition, if not specified using the stream metadata, the TwelveMonkeys TIFF plugin will use the byte order from the ImageOutputStream it is writing to. Specifying the byte order this way is in my mind more straight forward, but obviously less compatible between plugins.

try (ImageOutputStream stream = ImageIO.createImageOutputStream(out)) {
    stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);

    ImageIO.write(image, "TIFF", stream);
}

Regarding the file size, most known TIFF plugins will write uncompressed image data by default. There is, unfortunately, no way to specify the compression settings directly using the ImageIO convenience methods, so any TIFF you write using these methods will be uncompressed.

The ImageIO API instead requires you to obtain an ImageWriter for the format you want to write to, and pass in an ImageWriteParam to specify the compression settings. Note that the types of compression supported may vary by plugin. Also note that which compression type that yield the best compression rate, varies depending on the image data you are trying to compress.

ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
writer.setOutput(stream);

ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("LZW"); // "Zlib", "PackBits", "JPEG", "CCITT T.4", "CCITT T.6" etc.
param.setCompressionQuality(0.5f); // Applies only to some compression types. Generally:
                                   // * 0.0 means highest compression
                                   // * 1.0 means best quality

You can query what compression types are available in the current plugin, using:

String[] types = param.getCompressionTypes();


问:
virtual url representing page contents but not a different .html file
I have a website that consists of a single page coded in html that uses jquery to load web albums from picasa into a container depending on the link that the user clicks on.  This works fine, but I want the content loaded into the page to coincide with a url.  At the moment, when one of the album links is clicked, the photos load and a '#' is appended to the url.  How can I append the album name to the url instead, and have the browser understand that this album name coincides with the content loaded on the page by jquery.

Additionally, I want to be able to send someone a link to my website: kornweissphotography.com/steven/albumname where albumname is the name of one of my web albums and have the appropriate images load into the page.

website: www.kornweissphotography.com/steven

Thank you!

答:
You could append a category to the end of the # on the links.

So you when you click on on people, the url is http://www.kornweissphotography.com/steven/#people

You could then look at the url in with javascript to figure out what to load.

ContentLicense: CC BY-SA 2.5


问:
VBA : how to get the rows data while comparing to workbooks and copy the data in third workbook
Hi i am trying to copy the differences  while comparing the two workbooks and past the differences in third workbook. the below code is working upto copying the first differences(row). the code not working for copying all differences (rows) of the two workbooks. please suggest how to copy the all differences</p>

```<code>Sub findingdiff()
Dim FileSys, objFile, myFolder, c As Object
Dim wb1, wb2 As Workbook
Dim wb3 As ThisWorkbook
Set wb3 = ThisWorkbook
FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)
'loop through each file and get date last modified. If largest date then store Filename
        dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".xls") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename = objFile.Name
                End If
            End If
        Next objFile
'opening of latest file in the folder

                Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)
                Set FileSys = Nothing
                Set myFolder = Nothing
With wb2.Sheets("Sheet1")
Sh1LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh1Range = .Range("C1:C" & Sh1LastRow)
End With
 Set wb1 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\do\AR_Report_Excel_Version_06042017.xls")
With wb1.Sheets("Sheet1")
Sh2LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh2Range = .Range("C2:C" & Sh2LastRow)
End With

'compare latest workbook with old workbook
For Each cell In Sh1Range
Set c = Sh2Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 5
cell.Offset(0, 1).Interior.ColorIndex = 5
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

End If
Next cell
'compare  with sheet 1

For Each cell In Sh2Range
Set c = Sh1Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 4
cell.Offset(0, 1).Interior.ColorIndex = 4
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

End If
Next cell

End Sub
</code>```

答:
It appears that you are pasting the differences to the same row in wb3 each time so they are just overwriting each other (assuming you have no data in column A for wb1 and wb2)

If you change the lastrow to lookup from column C and then offset by 1 this should then paste to a new row each time

```<code>With wb2.Sheets("Sheet1")
Sh1LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh1Range = .Range("C1:C" & Sh1LastRow)
End With

Set wb1 = Workbooks.Open "C:\Users\ashokkumar.d\Desktop\Test\do\AR_Report_Excel_Version_06042017.xls")
With wb1.Sheets("Sheet1")
Sh2LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh2Range = .Range("C1:C" & Sh2LastRow)
End With

'compare latest workbook with old workbook
For Each cell In Sh1Range
Set c = Sh2Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 5
cell.Offset(0, 1).Interior.ColorIndex = 5
Sh3LastRow = wb3.Sheets("Sheet3").Range("C" & Rows.Count).End(xlUp).Row
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Sh3LastRow).Offset(1, 0)
End If

Next cell
'compare  with sheet 1

For Each cell In Sh2Range
Set c = Sh1Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 4
cell.Offset(0, 1).Interior.ColorIndex = 4
Sh3LastRow = wb3.Sheets("Sheet3").Range("C" & Rows.Count).End(xlUp).Row
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Sh3LastRow).Offset(1, 0)
End If
</code>```

*Also you were setting sh1Range to start from row 1 but sh2Range starts from row 2. I am unsure if this was deliberate but have amended both to start from row 1

Body:
Hi i am trying to copy the differences  while comparing the two workbooks and past the differences in third workbook. the below code is working upto copying the first differences(row). the code not working for copying all differences (rows) of the two workbooks. please suggest how to copy the all differences

Sub findingdiff()
Dim FileSys, objFile, myFolder, c As Object
Dim wb1, wb2 As Workbook
Dim wb3 As ThisWorkbook
Set wb3 = ThisWorkbook
FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)
'loop through each file and get date last modified. If largest date then store Filename
        dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".xls") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename = objFile.Name
                End If
            End If
        Next objFile
'opening of latest file in the folder

                Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)
                Set FileSys = Nothing
                Set myFolder = Nothing
With wb2.Sheets("Sheet1")
Sh1LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh1Range = .Range("C1:C" & Sh1LastRow)
End With
 Set wb1 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\do\AR_Report_Excel_Version_06042017.xls")
With wb1.Sheets("Sheet1")
Sh2LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh2Range = .Range("C2:C" & Sh2LastRow)
End With

'compare latest workbook with old workbook
For Each cell In Sh1Range
Set c = Sh2Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 5
cell.Offset(0, 1).Interior.ColorIndex = 5
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

End If
Next cell
'compare  with sheet 1

For Each cell In Sh2Range
Set c = Sh1Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 4
cell.Offset(0, 1).Interior.ColorIndex = 4
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

End If
Next cell

End Sub

Body:
It appears that you are pasting the differences to the same row in wb3 each time so they are just overwriting each other (assuming you have no data in column A for wb1 and wb2)

If you change the lastrow to lookup from column C and then offset by 1 this should then paste to a new row each time

With wb2.Sheets("Sheet1")
Sh1LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh1Range = .Range("C1:C" & Sh1LastRow)
End With

Set wb1 = Workbooks.Open "C:\Users\ashokkumar.d\Desktop\Test\do\AR_Report_Excel_Version_06042017.xls")
With wb1.Sheets("Sheet1")
Sh2LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh2Range = .Range("C1:C" & Sh2LastRow)
End With

'compare latest workbook with old workbook
For Each cell In Sh1Range
Set c = Sh2Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 5
cell.Offset(0, 1).Interior.ColorIndex = 5
Sh3LastRow = wb3.Sheets("Sheet3").Range("C" & Rows.Count).End(xlUp).Row
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Sh3LastRow).Offset(1, 0)
End If

Next cell
'compare  with sheet 1

For Each cell In Sh2Range
Set c = Sh1Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 4
cell.Offset(0, 1).Interior.ColorIndex = 4
Sh3LastRow = wb3.Sheets("Sheet3").Range("C" & Rows.Count).End(xlUp).Row
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Sh3LastRow).Offset(1, 0)
End If

*Also you were setting sh1Range to start from row 1 but sh2Range starts from row 2. I am unsure if this was deliberate but have amended both to start from row 1


问:
What is the best programming language to implement neural networks?
I'm not looking for a Neural Networks library, since I'm creating new kinds of networks. For that I need a good "dataflow" language.

Of course you can do this in C, C++, Java and co. but dealing from scratch with the multithreading etc. would be a nightmare.

At the other extremity, languages like Oz or Erlang seem more adapted, but they don't have many libraries, and they are harder to master (it's easy to play with them, but is it OK to create complete software ?).

What would you suggest ?

答: It all depends on your application. C++, Python are some good programming languages for machine learning</p>


问:
IE11 returns status 0 during Ajax POST operation from an iFrame (XMLHttpRequest: Network Error 0x2ee4)
It seems that IE11 version 11.0.7 (KB2929437 on Win7, KB2919355 on Win 8.1) has a problem when performing an Ajax POST operation. The operation returns status 0 and on an F12 console, the following error appears:

```<code>SCRIPT7002: XMLHttpRequest: Network Error 0x2ee4, Could not complete the operation due to error 00002ee4.
</code>```

The conditions to reproduce this issue are as follows:

Happens only on specific IE11, i.e. version 11.0.7 (KB2929437 on
Win7, KB2919355 on Win 8.1)

iframe is used to load external page with https protocol (parent page is using http protocol)

ajax with method 'POST' is used

More frequently happens with Connection: Keep-Alive header set on by IIS

More frequently happens on Win32 version of IE11

I created the following jsfiddle to reproduce this issue: http://jsfiddle.net/VJ2D6/12/

```<code>$(document).ready(function () {
     $('#frame').attr('src', 'https://54.249.142.247/ie11/test.html');
});
</code>```

Please note that the iframe retrieves its source from another site 54.249.142.247 (hosted by EC2 node using IIS7), because jsfiddle doesn't host https.
And, because I am using Self-Sign SSL Certificate, please first install the certificate to the Trusted Root, and turn off "Warn about certificate address mismatch" from Internet Options - Advanced Tab.

Inside 54.249.142.247/ie11/test.html, I created a button which initiates an Ajax POST operation to a non-existing location. Normally this request should return status 404 error (Not found). But in case of IE11 version 11.0.7, it often returns status 0 error and shows Network Error 0x2ee4 inside F12 console, "

I posted the same issue to Microsoft Connect here: https://connect.microsoft.com/IE/feedback/details/877525/ie11-returns-status-0-during-ajax-post-operation-from-an-iframe-xmlhttprequest-network-error-0x2ee4#tabs

I think this is an IE11 bug, but I am not 100% sure and there is no confirmation yet from the IE team. Please help me to confirm whether this is an IE bug, or if there is any problem in my JavaScript code.

UPDATE:

Microsoft said that they can reproduce the problem and will investigate it.

答:
I have the same issue too. at first i use make a get request before post. it solve the issue. but when i deep in, i find it's the in the internet option -》 Advanced options

cancel check for server certificate revocation*

cancel check for publisher certificate revocation*

click ok

restart your browser

i resolved the issue

enter image description here

Body:
It seems that IE11 version 11.0.7 (KB2929437 on Win7, KB2919355 on Win 8.1) has a problem when performing an Ajax POST operation. The operation returns status 0 and on an F12 console, the following error appears:

SCRIPT7002: XMLHttpRequest: Network Error 0x2ee4, Could not complete the operation due to error 00002ee4.

The conditions to reproduce this issue are as follows:

Happens only on specific IE11, i.e. version 11.0.7 (KB2929437 on
Win7, KB2919355 on Win 8.1)

iframe is used to load external page with https protocol (parent page is using http protocol)

ajax with method 'POST' is used

More frequently happens with Connection: Keep-Alive header set on by IIS

More frequently happens on Win32 version of IE11

I created the following jsfiddle to reproduce this issue: http://jsfiddle.net/VJ2D6/12/

$(document).ready(function () {
     $('#frame').attr('src', 'https://54.249.142.247/ie11/test.html');
});

Please note that the iframe retrieves its source from another site 54.249.142.247 (hosted by EC2 node using IIS7), because jsfiddle doesn't host https.
And, because I am using Self-Sign SSL Certificate, please first install the certificate to the Trusted Root, and turn off "Warn about certificate address mismatch" from Internet Options - Advanced Tab.

Inside 54.249.142.247/ie11/test.html, I created a button which initiates an Ajax POST operation to a non-existing location. Normally this request should return status 404 error (Not found). But in case of IE11 version 11.0.7, it often returns status 0 error and shows Network Error 0x2ee4 inside F12 console, "

I posted the same issue to Microsoft Connect here: https://connect.microsoft.com/IE/feedback/details/877525/ie11-returns-status-0-during-ajax-post-operation-from-an-iframe-xmlhttprequest-network-error-0x2ee4#tabs

I think this is an IE11 bug, but I am not 100% sure and there is no confirmation yet from the IE team. Please help me to confirm whether this is an IE bug, or if there is any problem in my JavaScript code.

UPDATE:

Microsoft said that they can reproduce the problem and will investigate it.


问:
How to change theme background color and text color on selection
Is there any way to change the style of the web page on by user selection using CSS in angular js.

I tried in google but nothing is working for me.

I have a CSS file which will have style. I need to rewrite the style in all divs wherever needed by changing the background colour, text colour, font style.

```<code>    $scope.model.webPageSkin = 'Default';

    // create the list of themes
    $scope.bootstraps = [
        { name: 'Plain', url: 'Plain' },
        { name: 'Blue', url: 'Blue' },
        { name: 'Green', url: 'Green' } ,
        { name: 'Default', url: 'default' } ,
    ];

**Plain.css**

ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #ddd;
}

**default.css**

.ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #3c8dbc;
}

<div class="wrapper>
     <header class="main-header">
          <nav class="navbar navbar-static-top" ng-class="{ChangeColor:
           model.webPageSkin !important;}">
          </nav>
     </header>

<div class="row">
<select  ng-model="model.webPageSkin" ng-options="bootstrap.url as bootstrap.name for bootstrap in bootstraps">
                </select>
</div>
</div>
</code>```

Can anyone suggest me how to do this.

答:
you have to change your code like this:

```<code>ng-class="{'ChangeColor': model.webPageSkin==='Default'}">
</code>```

ng-class only works for true and false if there is true value the class will be applied

Body:
Is there any way to change the style of the web page on by user selection using CSS in angular js.

I tried in google but nothing is working for me.

I have a CSS file which will have style. I need to rewrite the style in all divs wherever needed by changing the background colour, text colour, font style.

    $scope.model.webPageSkin = 'Default';

    // create the list of themes
    $scope.bootstraps = [
        { name: 'Plain', url: 'Plain' },
        { name: 'Blue', url: 'Blue' },
        { name: 'Green', url: 'Green' } ,
        { name: 'Default', url: 'default' } ,
    ];

**Plain.css**

ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #ddd;
}

**default.css**

.ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #3c8dbc;
}

<select  ng-model="model.webPageSkin" ng-options="bootstrap.url as bootstrap.name for bootstrap in bootstraps">
                </select>

Can anyone suggest me how to do this.

Body:
you have to change your code like this:

ng-class="{'ChangeColor': model.webPageSkin==='Default'}">

ng-class only works for true and false if there is true value the class will be applied


问:
Android background task with main class
I've run in to one little problem while working with the android API, this is it:

Is possible to make a BACKGROUND TASK (always running like a alarmtimer) that can read from common settings, I have problems with this since the main task gets unloaded when the app is closed (task keeps running but all the commands return null)

Is it even possible? if so, how?

Even more important, in my main class i have SyncMaster = new SyncMaster(this); and is there a way to talk to it via my background task?

答: Try using BroadCast receiver that listens to system components and notifiy your MainClass </p>

Title: Android background task with main class


问:
Switch md-sidenav mode (Angular Material 2)
I'm interested in changing the md-sidenav - from Angular Material 2 - mode from side (for desktops) to over (mobile). Is there a way to change it programmatically?
Thanks

答:
I found the solution by ObservableMedia.

Component:

```<code>import {Component, OnInit, ViewEncapsulation} from "@angular/core";
import {ObservableMedia} from "@angular/flex-layout";

@Component({
  moduleId: module.id,
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class SidebarComponent implements OnInit {

  constructor(public media:ObservableMedia ) {
  }

  ngOnInit(): void {
  }

}
</code>```

template:

```<code><md-sidenav-container>
    <md-sidenav #sidenav  mode="{{media.isActive('gt-sm') ? 'side' : 'over'}}" align="begin" class="md-whiteframe-4dp" opened >
      <md-nav-list>
        ...
      </md-nav-list>
    </md-sidenav>

</md-sidenav-container>
</code>```

Body:
I found the solution by ObservableMedia.

Component:

import {Component, OnInit, ViewEncapsulation} from "@angular/core";
import {ObservableMedia} from "@angular/flex-layout";

@Component({
  moduleId: module.id,
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class SidebarComponent implements OnInit {

  constructor(public media:ObservableMedia ) {
  }

  ngOnInit(): void {
  }

}

template:

<md-sidenav-container>
    <md-sidenav #sidenav  mode="{{media.isActive('gt-sm') ? 'side' : 'over'}}" align="begin" class="md-whiteframe-4dp" opened >
      <md-nav-list>
        ...
      </md-nav-list>
    </md-sidenav>

</md-sidenav-container>


问:
Design an expandable list with recycler view and supporting grid layout for child views in android
I am trying to design a recycler view with expandable design , it will have groups which on click would open and show child views. But the child views need to support linear layout and grid layout as well.

Currently I am using a recycler view within another recycler view to achieve the same, and used expandable layout for expanding collapsing items. This does get me the desired effect but neither is it a good programming practice and nor is it bug free. It does some unexpected things at all times, which is really annoying and a bad UX experience.

Please tell me other reliable and bug free ways to do it.

This image is approximately what I am trying to achieve. Cannot show the actual work I have done because of company policy.

I am not asking to source code to solve my problem, but some general design directions to achieve the same goal. As mentioned before, what I did, using recycler view inside another did do the trick, but also created other problems(unpredicatble behaviour to say the least.)

答: It seems like using nested scroll view and setting the inner recycler views to 'setNestedScrollingEnabled(false)' did the trick. Now I can make what I wanted to after all.</p>


问:
Zk spreadsheet zssjsp jar
Hi I'm new to zk spreadsheet. I'm following this tutorial for starting with zk spreadsheet with jsp.

In the tutorial it has been mentioned to use zssjsp jar but I cannot find the jar In the download links provided. It's basically used for tags in Jsp. I want to use "Windows" tag in Jsp. Any help is greatly appreciated. Thanks

答:
I followed the link you provided and clicked on the download link and then downloaded the first file in the list (zssee-bin-eval-3.9.1.zip at the moment). In it, the zssjsp.jar is at

```<code>zssee-bin-eval-3.9.1.zip\zssee-bin-eval-3.9.1\dist\lib
</code>```

Title: Zk spreadsheet zssjsp jar

Body:
I followed the link you provided and clicked on the download link and then downloaded the first file in the list (zssee-bin-eval-3.9.1.zip at the moment). In it, the zssjsp.jar is at

zssee-bin-eval-3.9.1.zip\zssee-bin-eval-3.9.1\dist\lib


问:
How to check whether app is succesfully connected to Google Nearby Api key?
Our apps can connect to GoogleAPIClient even though the KEY is wrong or not supplied.

```<code><meta-data
 android:name="com.google.android.nearby.messages.API_KEY"
 android:value="ourapikey" />
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
  mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Nearby.MESSAGES_API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .enableAutoManage(this, this) //enable auto manage
                    .build();
  @Override
        public void onConnected(@Nullable Bundle bundle) {
      //THIS method is called -> we assume the GoogleApiClient therefore is  successfully connected
      backgroundSubscribe();
    }
</code>```

答: The failure will occur if you try to publish or subscribe. Connecting the GoogleApiClient doesn't result in a call to our servers, so the key isn't used.</p>

Body:
Our apps can connect to GoogleAPIClient even though the KEY is wrong or not supplied.

<meta-data
 android:name="com.google.android.nearby.messages.API_KEY"
 android:value="ourapikey" />

MainActivity.java

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
  mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Nearby.MESSAGES_API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .enableAutoManage(this, this) //enable auto manage
                    .build();
  @Override
        public void onConnected(@Nullable Bundle bundle) {
      //THIS method is called -> we assume the GoogleApiClient therefore is  successfully connected
      backgroundSubscribe();
    }


问:
Autofilter to remove all EXCEPT a set of values
I am using a macro in Excel which applies a filter to a column, selects the values I no longer wish to keep and then deletes them. The problem I have is my macro requires me to know all of the values I do not want. In reality, I have a defined list of the ones that I want to keep, and all others should be removed. Can anyone help me switch this macro around so I can pass it the list of values to keep, and all others are removed? Here's what I have so far...</p>

```<code>    Columns("C:C").Select
    Selection.AutoFilter
    Dim LR As Long
    LR = ActiveSheet.UsedRange.Rows.Count
    ActiveSheet.Range("B2:B" & LR).AutoFilter Field:=1, Criteria1:=Array( _
        "A1", "AC", "AV", "BF", "BK", "BR", "C8", "CB", "CG", "CI", "CJ", "CM", "CO", "CR", "CS", "CT" _
        , "DR", "DN", "DS", "DU", "EF", "FC", "FE", "FI", "FO", "GD", "GE", "GO", "GR", "GW", "HA", "HD", _
        "HI", "KH", "KU", "LV", "MI", "MS", "MV", "MZ", "NE", "NO", "P4", "PI", "RS", "RT", "S9", "SC", "SU" _
        , "SY", "TO", "TX", "UR", "VN", "VR", "WI", "WN", "YA", "YO", "ZZ", "AO", "GS", "KR", "F5", "A2", _
        "LD", "ZE", "TG", "MX", "JI", "A9"), _
        Operator:=xlFilterValues
    Rows("2:" & LR).Select
    Selection.Delete Shift:=xlUp
    Selection.AutoFilter
    Range("A1").Select
</code>```

答:
As already showed, you can use a temporary sheet to store the right values. Other than that you could just go trough it with a select case.

```<code>Sub Filter()
Dim lRow As Long
Dim sht As Worksheet

Set sht = Worksheets("Sheet1")
lRow = sht.Cells(sht.Rows.Count, 2).End(xlUp).Row

If lRow > 1 Then
For i = lRow To 2 Step -1
    Select Case sht.Cells(i, 2).Value
    Case "A1", "AC", "AV", "BF", "BK", "BR", "C8", "CB", "CG", "CI", "CJ", "CM", "CO", "CR", "CS", "CT" _
        , "DR", "DN", "DS", "DU", "EF", "FC", "FE", "FI", "FO", "GD", "GE", "GO", "GR", "GW", "HA", "HD", _
        "HI", "KH", "KU", "LV", "MI", "MS", "MV", "MZ", "NE", "NO", "P4", "PI", "RS", "RT", "S9", "SC", "SU" _
        , "SY", "TO", "TX", "UR", "VN", "VR", "WI", "WN", "YA", "YO", "ZZ", "AO", "GS", "KR", "F5", "A2", _
        "LD", "ZE", "TG", "MX", "JI", "A9"
    Case Else
        sht.Rows(i).Delete
    End Select
Next
End If
End Sub
</code>```

Body:
I am using a macro in Excel which applies a filter to a column, selects the values I no longer wish to keep and then deletes them. The problem I have is my macro requires me to know all of the values I do not want. In reality, I have a defined list of the ones that I want to keep, and all others should be removed. Can anyone help me switch this macro around so I can pass it the list of values to keep, and all others are removed? Here's what I have so far...

    Columns("C:C").Select
    Selection.AutoFilter
    Dim LR As Long
    LR = ActiveSheet.UsedRange.Rows.Count
    ActiveSheet.Range("B2:B" & LR).AutoFilter Field:=1, Criteria1:=Array( _
        "A1", "AC", "AV", "BF", "BK", "BR", "C8", "CB", "CG", "CI", "CJ", "CM", "CO", "CR", "CS", "CT" _
        , "DR", "DN", "DS", "DU", "EF", "FC", "FE", "FI", "FO", "GD", "GE", "GO", "GR", "GW", "HA", "HD", _
        "HI", "KH", "KU", "LV", "MI", "MS", "MV", "MZ", "NE", "NO", "P4", "PI", "RS", "RT", "S9", "SC", "SU" _
        , "SY", "TO", "TX", "UR", "VN", "VR", "WI", "WN", "YA", "YO", "ZZ", "AO", "GS", "KR", "F5", "A2", _
        "LD", "ZE", "TG", "MX", "JI", "A9"), _
        Operator:=xlFilterValues
    Rows("2:" & LR).Select
    Selection.Delete Shift:=xlUp
    Selection.AutoFilter
    Range("A1").Select

Body:
As already showed, you can use a temporary sheet to store the right values. Other than that you could just go trough it with a select case.

Sub Filter()
Dim lRow As Long
Dim sht As Worksheet

Set sht = Worksheets("Sheet1")
lRow = sht.Cells(sht.Rows.Count, 2).End(xlUp).Row

If lRow > 1 Then
For i = lRow To 2 Step -1
    Select Case sht.Cells(i, 2).Value
    Case "A1", "AC", "AV", "BF", "BK", "BR", "C8", "CB", "CG", "CI", "CJ", "CM", "CO", "CR", "CS", "CT" _
        , "DR", "DN", "DS", "DU", "EF", "FC", "FE", "FI", "FO", "GD", "GE", "GO", "GR", "GW", "HA", "HD", _
        "HI", "KH", "KU", "LV", "MI", "MS", "MV", "MZ", "NE", "NO", "P4", "PI", "RS", "RT", "S9", "SC", "SU" _
        , "SY", "TO", "TX", "UR", "VN", "VR", "WI", "WN", "YA", "YO", "ZZ", "AO", "GS", "KR", "F5", "A2", _
        "LD", "ZE", "TG", "MX", "JI", "A9"
    Case Else
        sht.Rows(i).Delete
    End Select
Next
End If
End Sub


问:
Sceneview freezes when present web view controller
I'm using Safari Services kit to present a web view when an SCNode is clicked. However, when I go back from the safariVC to my VC with the sceneView, the sceneView is frozen even though I restart the session by re-running the session.

I read on this website that presenting another VC kills the scene view thread and I would just like confirmation. Basically I want to know whether it is possible to present another VC and be able to go back to the sceneView and "resume" the scenView

Note:

VC = ViewController

Code

How I present my safari web VC

```<code>func presentWebView(){
    if let url = URL(string: "https://www.amazon.com/"){
        let safariVC = SFSafariViewController(url: url)
        self.present(safariVC, animated: true, completion: nil)
    }
}
</code>```

How I restart my session

```<code>if let worldSessionConfig = sessionConfig as? ARWorldTrackingSessionConfiguration {
    worldSessionConfig.planeDetection = .horizontal
    session.run(worldSessionConfig, options: [.resetTracking, .removeExistingAnchors])
}
</code>```

答: Use sceneView.session.pause() when you present safariVC and then use sceneView.session.run to restart session when safariVC is dismissed.

Body:
I'm using Safari Services kit to present a web view when an SCNode is clicked. However, when I go back from the safariVC to my VC with the sceneView, the sceneView is frozen even though I restart the session by re-running the session.

I read on this website that presenting another VC kills the scene view thread and I would just like confirmation. Basically I want to know whether it is possible to present another VC and be able to go back to the sceneView and "resume" the scenView

Note:

VC = ViewController

Code

How I present my safari web VC

func presentWebView(){
    if let url = URL(string: "https://www.amazon.com/"){
        let safariVC = SFSafariViewController(url: url)
        self.present(safariVC, animated: true, completion: nil)
    }
}

How I restart my session

if let worldSessionConfig = sessionConfig as? ARWorldTrackingSessionConfiguration {
    worldSessionConfig.planeDetection = .horizontal
    session.run(worldSessionConfig, options: [.resetTracking, .removeExistingAnchors])
}


问:
How to return binary data instead of base64 encoded byte[] in spring mvc rest controller
I want to return a generated pdf file via spring-mvc-rest controller. This is a shortened version of the code I'm currently using:

```<code>@RestController
@RequestMapping("/x")
public class XController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<byte[]> find() throws IOException {
        byte[] pdf = createPdf();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType("application", "pdf"));
        headers.setContentDispositionFormData("attachment", "x.pdf");
        headers.setContentLength(pdf.length);
        return new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
    }
}
</code>```

This works almost fine, it just to return the actual byte array as base64 encoded :(

```<code>curl -i 'http://127.0.0.1:8080/app/x'

Server: Apache-Coyote/1.1
Content-Disposition: form-data; name="attachment"; filename=x.pdf"
Content-Type: application/pdf
Content-Length: 138654
Date: Fri, 08 Jan 2016 11:25:38 GMT

"JVBERi0xLjYNJeLjz9MNCjMyNCAwIG9iag [...]
</code>```

(btw. the response doesn't even contain a closing " :)

Any hints appreciated!

答:
The problem is caused by Spring trying to encode the response as Json.

Your request probably specifies Accepts = "*/*" and since Spring ignores the ResponseEntity's ContentType, the best encoding is found to be application/json.

The simplest fix to this is to add a produces to your request mapping, so your code becomes:

```<code>@RestController
@RequestMapping(value = "/x",
                produces = "application/pdf") // <-- Add this
public class XController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<byte[]> find() throws IOException {
        byte[] pdf = createPdf();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setContentDispositionFormData("attachment", "x.pdf");
        headers.setContentLength(pdf.length);
        return new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
    }
}
</code>```

Body:
I want to return a generated pdf file via spring-mvc-rest controller. This is a shortened version of the code I'm currently using:

@RestController
@RequestMapping("/x")
public class XController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<byte[]> find() throws IOException {
        byte[] pdf = createPdf();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType("application", "pdf"));
        headers.setContentDispositionFormData("attachment", "x.pdf");
        headers.setContentLength(pdf.length);
        return new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
    }
}

This works almost fine, it just to return the actual byte array as base64 encoded :(

curl -i 'http://127.0.0.1:8080/app/x'

Server: Apache-Coyote/1.1
Content-Disposition: form-data; name="attachment"; filename=x.pdf"
Content-Type: application/pdf
Content-Length: 138654
Date: Fri, 08 Jan 2016 11:25:38 GMT

"JVBERi0xLjYNJeLjz9MNCjMyNCAwIG9iag [...]

(btw. the response doesn't even contain a closing " :)

Any hints appreciated!

Body:
The problem is caused by Spring trying to encode the response as Json.

Your request probably specifies Accepts = "*/*" and since Spring ignores the ResponseEntity's ContentType, the best encoding is found to be application/json.

The simplest fix to this is to add a produces to your request mapping, so your code becomes:

@RestController
@RequestMapping(value = "/x",
                produces = "application/pdf") // <-- Add this
public class XController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<byte[]> find() throws IOException {
        byte[] pdf = createPdf();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setContentDispositionFormData("attachment", "x.pdf");
        headers.setContentLength(pdf.length);
        return new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
    }
}


问:
appointment scheduling with jquery
I'm going to create a simple appointment scheduling to set appointment for doctor, some thing like this : http://arshaw.com/fullcalendar/

I almost know anything about jQuery and JavaScript but I hope this be a commence to learn more and of course my boss has asked me to do that. Because the created appointment scheduling plugins don't support Persian date, they're useless for me, where should I start from? I wanna set appointment be done bye drag and drop on the surface, like google calendar:

http://jquery-week-calendar.googlecode.com/svn/trunk/jquery.weekcalendar/full_demo/weekcalendar_full_demo.html

please suggest me references and some required steps to study and do this.

I appreciate any help

答: If the problem is Persian date\calendar, momentjs.com which is the lib on which fullcalendar is based has it supported already

Title: appointment scheduling with jquery


问:
Does assigning objects to null in Java impact garbage collection?
Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?

My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?

答:
I assume the OP is referring to things like this:

```<code>private void Blah()
{
    MyObj a;
    MyObj b;

    try {
        a = new MyObj();
        b = new MyObj;

        // do real work
    } finally {
        a = null;
        b = null;
    }
}
</code>```

In this case, wouldn't the VM mark them for GC as soon as they leave scope anyway?

Or, from another perspective, would explicitly setting the items to null cause them to get GC'd before they would if they just went out of scope? If so, the VM may spend time GC'ing the object when the memory isn't needed anyway, which would actually cause worse performance CPU usage wise because it would be GC'ing more earlier.

OwnerDisplayName: nemo

LastEditorDisplayName: nemo

Body:
I assume the OP is referring to things like this:

private void Blah()
{
    MyObj a;
    MyObj b;

    try {
        a = new MyObj();
        b = new MyObj;

        // do real work
    } finally {
        a = null;
        b = null;
    }
}

In this case, wouldn't the VM mark them for GC as soon as they leave scope anyway?

Or, from another perspective, would explicitly setting the items to null cause them to get GC'd before they would if they just went out of scope? If so, the VM may spend time GC'ing the object when the memory isn't needed anyway, which would actually cause worse performance CPU usage wise because it would be GC'ing more earlier.


问:
Validation on name TextBoxes
I have a grid where in insert/edit mode you can update the item for a person's names.

I've been asked to provide validation to ensure only alphanumerics are added.

After talking with a colleague we were thinking only validation for length should be done.

The user should be able to enter any characters they like.

Does this sound correct? I understand some names could contain special characters etc.

答: From a security point of view, it would be recommended to constrain user input in order to prevent cross-site scripting attacks MSDN </p>

Title: Validation on name TextBoxes


问:
Reversing the letters in words in a String
I have coded the following solution, and it works, except for when there is punctuation. I was wondering if there are O(1) space complexity and O(length of string) time complexity solutions, without using reverse() method, or anything similar that makes this task too easy. Any answer that can also handle punctuation correctly would be great.

Example:

Given string: "I love chocolate"

Return string should be: "I evol etalocohc"

For clarity, when I say handle punctuation correctly, I mean punctuation should not move around.

```<code> // reverse the letters of every word in a sentence (string), and return the result

 public static String reverse(String x)
 {
     String[] str = x.split(" ");

     StringBuilder rev = new StringBuilder("");

     for (int i = 0; i < str.length; i++)
     {
         for (int s = str[i].length()-1; s >= 0; s--)
         {
             rev.append(str[i].charAt(s));
         }
         rev.append(" ");
     }

     return rev.toString();
 }
</code>```

Here is my output for some tests of mine:

```<code>     public static void main(String[] args)
     {
         System.out.println(reverse("I love chocolate"));//this passes
         System.out.println(reverse("Geeks for Geeks"));//this passes
         System.out.println(reverse("You, are awesome"));//not handling puncutation mark correctly, gives me ",uoY era emosewa", instead of "uoY, era emosewa"
         System.out.println(reverse("Geeks! for Geeks."));//not handling puncutation marks correctly, gives me "!skeeG rof .skeeG", instead of "skeeG! rof skeeG."
     }
</code>```

答:
Here is an implementation which uses in-place reversing of words requiring only O(1) storage.  In addition, the reversing algorithm itself is O(N) with the length of the string.

The basic algorithm is to walk down the string until hitting a space.  Then, the swap() method is called to reverse that particular word in place.  It only needs at any moment one extra character.

This approach may not be as performant as the accepted answer due to its heavy use of StringBuilder manipulations.  But this might something to consider in an environment like an Android application where space is very precious.

```<code> public static void swap(StringBuilder input, int start, int end) {
    for (int i=0; i <= (end - start) / 2; ++i) {
        char ch = input.charAt(start + i);
        input.setCharAt(start + i, input.charAt(end - i));
        input.setCharAt(end - i, ch);
    }
}

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("I love chocolate");

    int start = 0;
    int end = 0;

    while (true) {
        while (end <= sb.length() - 1 && sb.charAt(end) != ' ') {
            ++end;
        }
        swap(sb, start, end - 1);
        start = end + 1;
        end = start;
        if (end > sb.length() - 1) {
            break;
        }
    }

    System.out.println(sb);
}
</code>```

Demo here:

Rextester

Body:
I have coded the following solution, and it works, except for when there is punctuation. I was wondering if there are O(1) space complexity and O(length of string) time complexity solutions, without using reverse() method, or anything similar that makes this task too easy. Any answer that can also handle punctuation correctly would be great.

Example:

Given string: "I love chocolate"

Return string should be: "I evol etalocohc"

For clarity, when I say handle punctuation correctly, I mean punctuation should not move around.

 // reverse the letters of every word in a sentence (string), and return the result

 public static String reverse(String x)
 {
     String[] str = x.split(" ");

     StringBuilder rev = new StringBuilder("");

     for (int i = 0; i < str.length; i++)
     {
         for (int s = str[i].length()-1; s >= 0; s--)
         {
             rev.append(str[i].charAt(s));
         }
         rev.append(" ");
     }

     return rev.toString();
 }

Here is my output for some tests of mine:

     public static void main(String[] args)
     {
         System.out.println(reverse("I love chocolate"));//this passes
         System.out.println(reverse("Geeks for Geeks"));//this passes
         System.out.println(reverse("You, are awesome"));//not handling puncutation mark correctly, gives me ",uoY era emosewa", instead of "uoY, era emosewa"
         System.out.println(reverse("Geeks! for Geeks."));//not handling puncutation marks correctly, gives me "!skeeG rof .skeeG", instead of "skeeG! rof skeeG."
     }

Body:
Here is an implementation which uses in-place reversing of words requiring only O(1) storage.  In addition, the reversing algorithm itself is O(N) with the length of the string.

The basic algorithm is to walk down the string until hitting a space.  Then, the swap() method is called to reverse that particular word in place.  It only needs at any moment one extra character.

This approach may not be as performant as the accepted answer due to its heavy use of StringBuilder manipulations.  But this might something to consider in an environment like an Android application where space is very precious.

 public static void swap(StringBuilder input, int start, int end) {
    for (int i=0; i <= (end - start) / 2; ++i) {
        char ch = input.charAt(start + i);
        input.setCharAt(start + i, input.charAt(end - i));
        input.setCharAt(end - i, ch);
    }
}

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("I love chocolate");

    int start = 0;
    int end = 0;

    while (true) {
        while (end <= sb.length() - 1 && sb.charAt(end) != ' ') {
            ++end;
        }
        swap(sb, start, end - 1);
        start = end + 1;
        end = start;
        if (end > sb.length() - 1) {
            break;
        }
    }

    System.out.println(sb);
}

Demo here:

Rextester


问:
How to set fixed view position across different locals?
I'm currently working on an app and set up another local in strings.xml

I have a list view with three elements two text views and an image view

when I change the language to something like Arabic the items positions change and they appear from right to left.

that messes up the whole layout.

My question is how to set the position to fixed value so they don't change

 I tried searching for solutions for this problem but didn't get any.

答:
I don't know why you should do it. Because people in other parts of the world read from right to left. For them it is totally normal and fine.

Anyway. To have always a LTR (Left-To-Right) layout you have to disabled the RTL (Right-To-Left) attribute in your AndroidManifest.

```<code><application supportrtl="false" />
</code>```

See also the documentation or this blogpost for more.

Body:
I don't know why you should do it. Because people in other parts of the world read from right to left. For them it is totally normal and fine.

Anyway. To have always a LTR (Left-To-Right) layout you have to disabled the RTL (Right-To-Left) attribute in your AndroidManifest.

<application supportrtl="false" />

See also the documentation or this blogpost for more.


问:
click event on a input text box does not work
here is my input :

```<code><input name="DeviceIP" class="k-input k-textbox" type="text" data-bind="value:DeviceIP">
</code>```

here is my js which is not working

```<code>$('input[name="DeviceIP"]').click(function () {  alert("test") });
</code>```

答:
The code should work fine,

The common reason for this kind of errors are the misconsception of binding events via JS/JQuery.

When you use $('some selector').click(fn) syntax this means :

```<code>JQuery will bind "fn" click event to the Elements
that have already been attached to the DOM (to HTML)
</code>```

It will not attach events to the newly/dynamically created/attached elements. You still have to bind related events to those after they are attached to dom or to their JS reference.

Body:
here is my input :

<input name="DeviceIP" class="k-input k-textbox" type="text" data-bind="value:DeviceIP">

here is my js which is not working

$('input[name="DeviceIP"]').click(function () {  alert("test") });

Body:
The code should work fine,

The common reason for this kind of errors are the misconsception of binding events via JS/JQuery.

When you use $('some selector').click(fn) syntax this means :

JQuery will bind "fn" click event to the Elements
that have already been attached to the DOM (to HTML)

It will not attach events to the newly/dynamically created/attached elements. You still have to bind related events to those after they are attached to dom or to their JS reference.


问:
Scala tuple function composition
Let's say we have a 3 functions with Tuple3 result:

```<code>def foo(a: String, b: String, c: String): (String, String, String) = {
  (s"foo_$a", s"foo_$b", s"foo_$c")
}

def bar(a: String, b: String, c: String): (String, String, String) = {
  (s"bar_$a", s"bar_$b", s"bar_$c")
}

def buz(a: String, b: String, c: String): (String, String, String) = {
  (s"buz_$a", s"buz_$b", s"buz_$c")
}
</code>```

And I can compose them like this:

```<code>val (a, b, c) = foo("1", "2", "3")
val (d, e, f) = bar(a, b, c)
val (g, h, i) = buz(d, e, f)
</code>```

But I want something like this:

```<code>val (x, y, z) = foo(bar(buz("1", "2", "3")))
</code>```

How can I achieve this?

答:
For ease of typing, imagine that we have the following type alias defined:

```<code>type String3 = (String, String, String)
</code>```

You can use andThen or compose as sheunis said, and you can turn a Function3[String, String, String, String3] into a Function1[String3, String3] using the tupled function.
Then when combined with eta expansion you get this:

```<code>val buzBarFoo = (buz _ tupled) andThen (bar _ tupled) andThen (foo _ tupled)
</code>```

or this:

```<code>val buzBarFoo = (foo _ tupled) compose (bar _ tupled) compose (buz _ tupled)
</code>```

Which both have the aforementioned type of Function1[String3, String3]

You can then use the function like you used before:

```<code>val (x, y, z) = buzBarFoo("1", "2", "3")
</code>```

Title: Scala tuple function composition

Body:
Let's say we have a 3 functions with Tuple3 result:

def foo(a: String, b: String, c: String): (String, String, String) = {
  (s"foo_$a", s"foo_$b", s"foo_$c")
}

def bar(a: String, b: String, c: String): (String, String, String) = {
  (s"bar_$a", s"bar_$b", s"bar_$c")
}

def buz(a: String, b: String, c: String): (String, String, String) = {
  (s"buz_$a", s"buz_$b", s"buz_$c")
}

And I can compose them like this:

val (a, b, c) = foo("1", "2", "3")
val (d, e, f) = bar(a, b, c)
val (g, h, i) = buz(d, e, f)

But I want something like this:

val (x, y, z) = foo(bar(buz("1", "2", "3")))

How can I achieve this?

Body:
For ease of typing, imagine that we have the following type alias defined:

type String3 = (String, String, String)

You can use andThen or compose as sheunis said, and you can turn a Function3[String, String, String, String3] into a Function1[String3, String3] using the tupled function.
Then when combined with eta expansion you get this:

val buzBarFoo = (buz _ tupled) andThen (bar _ tupled) andThen (foo _ tupled)

or this:

val buzBarFoo = (foo _ tupled) compose (bar _ tupled) compose (buz _ tupled)

Which both have the aforementioned type of Function1[String3, String3]

You can then use the function like you used before:

val (x, y, z) = buzBarFoo("1", "2", "3")


问:
Include functions
EDIT
Due to the overwhelming amount of advice I have received, I have fixed my problem. (After realizing the horrible php code I had written.) :D

Thanks to all!

Is there a reason that a function that is inside an included php file won't work on the parent page? I have two functions inside a php file that is included at the top of the page. However, when I try to call the function, it doesn't do anything. Here's the basic layout:

Main page:

```<code><?php include 'includes/header.php'; ?>
<?php getPosts();?>
<div>Some HTML Code</div>
<?php endPosts(); ?>
</code>```

Header.php

```<code>function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
     while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*End while statement */
};
</code>```

Any idea why this won't work? I'm getting a blank white screen right now.

答: That code is so not valid.  Why are you declaring a function inside of another function?  And there aren't supposed to be semicolons on the end of function declarations/loops.  The first thing to do is to enable error reporting.

Title: Include functions

Body:
EDIT
Due to the overwhelming amount of advice I have received, I have fixed my problem. (After realizing the horrible php code I had written.) :D

Thanks to all!

Is there a reason that a function that is inside an included php file won't work on the parent page? I have two functions inside a php file that is included at the top of the page. However, when I try to call the function, it doesn't do anything. Here's the basic layout:

Main page:

<?php include 'includes/header.php'; ?>
<?php getPosts();?>

Some HTML Code

<?php endPosts(); ?>

Header.php

function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
     while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*End while statement */
};

Any idea why this won't work? I'm getting a blank white screen right now.


问:
Can I specifically disable PATCH in spring-data-rest repository?
Client of our API's don't use patch and I want to avoid it for maintenance overhead. I don't want to disable POST or PUT.</p>

答:
It can be handled at the security level, by extending WebSecurityConfigurerAdapter (available in spring-security-config) and overriding configure(HttpSecurity http) to deny PATCH requests to the target url :

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpMethod.PATCH, "/path_to_target_url").denyAll();
    }

}
</code>```

Any attempt to PATCH to the target URL will fail with a 401 Unauthorized error.

Body:
It can be handled at the security level, by extending WebSecurityConfigurerAdapter (available in spring-security-config) and overriding configure(HttpSecurity http) to deny PATCH requests to the target url :

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpMethod.PATCH, "/path_to_target_url").denyAll();
    }

}

Any attempt to PATCH to the target URL will fail with a 401 Unauthorized error.


问:
How to read External Sqllite Database in xamirin android in Visual Studio C#
My Code :

```<code>var dbpath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "ot.db3");
Context myContext = null;
try
{
      var dbcon = new SQLiteConnection(dbpath);
         var db=   dbcon.Query<records>("SELECT * FROM records WHERE sno = ? ", "1");
            int count = db.Count;
}
catch (IOException ex)
{
    var reason = string.Format("The database failed to create - reason {0}", ex.Message);
    Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}
</code>```

I Create a Sqlite Database from my SQL Server Database.

Now I save it to my Phone on this path (Android/Data/Application/File)

Now using Sqlite-net-pcl nugget package for Sqlite Connection the connection works fine showing have no error.

When I try to read a table from database this Give any error that "No Such Table exist in database". And the table exists in the database and is populated with data.

What can I do?

Thanks in advance

答:
You need to check in your DB file if the table really exists.

Extract the database from your Android device/simulator with ADB
Example: adb pull //.db .

It will download the DB file to your computer.

Then, use a tool such as "DB Browser for SQLite" (http://sqlitebrowser.org/) to open your DB file and check if your table exists.

Other common mistakes when using SQLite with Android are:

the file is not found (the path in your connectionstring is not good)

the name is not the one your think (maybe in your case, it is "Record" and not "Records")

Hope it will help.

Body:
My Code :

var dbpath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "ot.db3");
Context myContext = null;
try
{
      var dbcon = new SQLiteConnection(dbpath);
         var db=   dbcon.Query<records>("SELECT * FROM records WHERE sno = ? ", "1");
            int count = db.Count;
}
catch (IOException ex)
{
    var reason = string.Format("The database failed to create - reason {0}", ex.Message);
    Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}

I Create a Sqlite Database from my SQL Server Database.

Now I save it to my Phone on this path (Android/Data/Application/File)

Now using Sqlite-net-pcl nugget package for Sqlite Connection the connection works fine showing have no error.

When I try to read a table from database this Give any error that "No Such Table exist in database". And the table exists in the database and is populated with data.

What can I do?

Thanks in advance


问:
Google OAuth Redirect Uri Mismatch (authorization_code)
I am having a problem to understand the correct purpose of the redirect uri. Following the Google tutorial the javascript API allows me to get a authorizationCode without any redirect URI at all.

Then I send this code to my server and try to call the /token endpoint with this code. But then it will return a "redirect URI mismatch" which probably means that I need to define the same redirect_uri for this endpoint than I did with the javascript API. My only problem is that I dont specify any on my website.

Anyone knows how to correctly use them?

The flow I am trying to achieve is the following:
- Javascript website asks user for permission, getting the authorization code
- Code is sent to my server
- Server receives access/refresh token with this code and stores it safely

答:
The point of a redirect uri is to tell the authentication server where to return the authentication code.

Installed Application

If i have an installed application Windows for example it knows to just return it to the same place it came from.

```<code>https://accounts.google.com/o/oauth2/auth?client_id={clientid}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code
</code>```

The above link will display an auth window to the user and the authentication code it returns will be sent back to exactly where the request came from.

Web Application

In the case of a web application. What is the location the request is coming from? Its the clients pc? Which is just a web browser running your web application. The client cant handle the authentication code your web-server must have a file on it which can handle the authentication code.

Adding a redirect uri of http://webapplication120170125114757.azurewebsites.net/authorize/ tells the authentication sever to return the authentication code to your website so it can be dealt with.

redirect URI mismatch

Miss match means that the redirect uri that you put in the link above is not one that you have registered in Google developer console.  It must match exactly including any port numbers.

Js Origin

If you're using the JavaScript client, you need to set a valid JavaScript origin for google to authorize you.

Authorized redirect URIs are the endpoints they going to call as a callback if you're using 3-legged OAuth 2.0 flow. https://developers.google.com/accounts/docs/OAuth2#webserver

Body:
The point of a redirect uri is to tell the authentication server where to return the authentication code.

Installed Application

If i have an installed application Windows for example it knows to just return it to the same place it came from.

https://accounts.google.com/o/oauth2/auth?client_id={clientid}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code

The above link will display an auth window to the user and the authentication code it returns will be sent back to exactly where the request came from.

Web Application

In the case of a web application. What is the location the request is coming from? Its the clients pc? Which is just a web browser running your web application. The client cant handle the authentication code your web-server must have a file on it which can handle the authentication code.

Adding a redirect uri of http://webapplication120170125114757.azurewebsites.net/authorize/ tells the authentication sever to return the authentication code to your website so it can be dealt with.

redirect URI mismatch

Miss match means that the redirect uri that you put in the link above is not one that you have registered in Google developer console.  It must match exactly including any port numbers.

Js Origin

If you're using the JavaScript client, you need to set a valid JavaScript origin for google to authorize you.

Authorized redirect URIs are the endpoints they going to call as a callback if you're using 3-legged OAuth 2.0 flow. https://developers.google.com/accounts/docs/OAuth2#webserver