问:
GWT composite dynamic height resize
I Have a GWT Composite to which some other Composites are added dynamically.
I want to make may Parent composite Resize to fit the height of all its child widgets automatically.
i tried setting setHeight("100%") for Composite but this doesn’t work.
any Idea how to accomplish this functionality?

thanks.
EDIT:

```<code>final DockLayoutPanel dockLayoutPanel = new DockLayoutPanel(Unit.EM);
    dockLayoutPanel.setStyleName("EntryPanel");
    dockLayoutPanel.setSize("142px", "72px");
    initWidget(dockLayoutPanel);

    final VerticalPanel panel = new VerticalPanel();
    panel.setSize("140px", "72px");

    chckbxExport = new CheckBox("Export");
    putField(CommonPresenter.CONSTANTS.EXPORT, chckbxExport);

    dateBox = new DateBox();

    dateBox.addValueChangeHandler(new ValueChangeHandler<Date>() {
        @Override
        public void onValueChange(final ValueChangeEvent<Date> event) {
            dateChanged = true;
        }
    });

    panel.add(dateBox);

    final ListBox visibility = new ListBox();

    final Label lblVisibility = new Label("Visibility:");
    LabeledWidget vis = new LabeledWidget(lblVisibility, visibility);

    for (int i = 0; i < CommonPresenter.CONSTANTS.VISIBILITIES.length; i++) {
        visibility.addItem(CommonPresenter.CONSTANTS.VISIBILITIES[i]);
    }

    putField(CommonPresenter.CONSTANTS.VISIBILITY, visibility);

    panel.add(vis);
    panel.add(chckbxExport);

    dockLayoutPanel.add(panel);
</code>```

UPDATE:
Setting Composite width to fill all available Window horizontal space:

```<code> final int scrollBarWidth = 25;
// editPanel.setHeight("180px");
setWidth(Window.getClientWidth() - scrollBarWidth + "px");
// editPanel.setStyleName("EditorPanel");

Window.addResizeHandler(new ResizeHandler()
{
  public void onResize(ResizeEvent event)
  {
    int width = event.getWidth();
    setWidth(width - scrollBarWidth + "px");
  }
});
</code>```

答:
Here's how to do it generally with HTML+CSS:

Create the parent, and do not set its height (or set it to auto).

Then add the children (just make sure, that you don't use absolute/fixed positioning for the children).

Set the height of the children, if required.

The height of the parent will then be adjusted automatically. This is the same for GWT Composites - just make sure, which CSS (including style attributes) applies to your elements! If unsure, use Firebug.

If you need more specifics, then you'd have to post some code which shows how you construct the parent composite (UiBinder, ...?)

Title: GWT composite dynamic height resize

Body:
I Have a GWT Composite to which some other Composites are added dynamically.
I want to make may Parent composite Resize to fit the height of all its child widgets automatically.
i tried setting setHeight("100%") for Composite but this doesn’t work.
any Idea how to accomplish this functionality?

thanks.
EDIT:

final DockLayoutPanel dockLayoutPanel = new DockLayoutPanel(Unit.EM);
    dockLayoutPanel.setStyleName("EntryPanel");
    dockLayoutPanel.setSize("142px", "72px");
    initWidget(dockLayoutPanel);

    final VerticalPanel panel = new VerticalPanel();
    panel.setSize("140px", "72px");

    chckbxExport = new CheckBox("Export");
    putField(CommonPresenter.CONSTANTS.EXPORT, chckbxExport);

    dateBox = new DateBox();

    dateBox.addValueChangeHandler(new ValueChangeHandler<Date>() {
        @Override
        public void onValueChange(final ValueChangeEvent<Date> event) {
            dateChanged = true;
        }
    });

    panel.add(dateBox);

    final ListBox visibility = new ListBox();

    final Label lblVisibility = new Label("Visibility:");
    LabeledWidget vis = new LabeledWidget(lblVisibility, visibility);

    for (int i = 0; i < CommonPresenter.CONSTANTS.VISIBILITIES.length; i++) {
        visibility.addItem(CommonPresenter.CONSTANTS.VISIBILITIES[i]);
    }

    putField(CommonPresenter.CONSTANTS.VISIBILITY, visibility);

    panel.add(vis);
    panel.add(chckbxExport);

    dockLayoutPanel.add(panel);

UPDATE:
Setting Composite width to fill all available Window horizontal space:

 final int scrollBarWidth = 25;
// editPanel.setHeight("180px");
setWidth(Window.getClientWidth() - scrollBarWidth + "px");
// editPanel.setStyleName("EditorPanel");

Window.addResizeHandler(new ResizeHandler()
{
  public void onResize(ResizeEvent event)
  {
    int width = event.getWidth();
    setWidth(width - scrollBarWidth + "px");
  }
});


来源: stackexchange

问:
Angular, idiomatic string replacement?
For some condition, I would like replace a String in my model when displaying it in html. I could do this my modifying my model, but is there a more idiomatic option? Possibly this should be done with a filter?</p>

```<code>  <tr ng-repeat="i in ctrl.data" >
      <td>
         <div ng-show="i.category == 'default'">
             none
         </div>
         <div ng-show="i.category != 'default'">
            {{ i.category }}
         </div>
      </td>
  </tr>
</code>```

答:
```<code>{{ i.category == 'default' ? 'none' : i.category }}
</code>```

Or, if you have that in several places, use a filter.

ContentLicense: CC BY-SA 3.0

Title: Angular, idiomatic string replacement?

Body:
For some condition, I would like replace a String in my model when displaying it in html. I could do this my modifying my model, but is there a more idiomatic option? Possibly this should be done with a filter?

             none

            {{ i.category }}

Body:
{{ i.category == 'default' ? 'none' : i.category }}

Or, if you have that in several places, use a filter.


问:
T-SQL ORDER BY several clauses
I'm currently working on a stored procedure in TSQL on SQL Server 2014. I need to write a query to order a list of Projects by different StatusIds.

Table Project:

ProjectId

Label

ProjectDataId

Table ProjectData:

ProjectDataId

StatusId

Table Project is linked to ProjectData via ProjectDataId.

Demo Data Table Project:

```<code> ProjectId  | Label |  ProjectDataId |
------------+-------+----------------+
1           | Pro22 |      2         |
2           | Pro54 |      3         |
3           | Pro87 |      4         |
4           | Pro77 |      5         |
5           | Pro28 |      6         |
</code>```

Demo Data Table ProjectData:

```<code> ProjectDataId  |  StatusId   |
----------------+-------------+
2               |      1      |
3               |      2      |
4               |      3      |
5               |      4      |
6               |      4      |
</code>```

My current result looks like this:

```<code> ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
3           | Pro87 |      3      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
</code>```

My current query looks like this:

```<code>SELECT ROW_NUMBER() OVER(ORDER BY StatusId ASC)  AS [RowNumber], *
FROM (SELECT DISTINCT
        [P].ProjectId
      , [P].Label
      , [PD].StatusId
      , [P].ProjectDataId
     FROM [MySchema].[Project] [P]
     INNER JOIN [MyProject].[ProjectData] [PD]
     ON [PD].ProjectDataId = [P].ProjectDataId) dt
</code>```

This query works to order by statusId asc 1, 2, 3, 4 but not to bring it into the right order of statusId 1, 2, 4, 3.

Actually, the desired output should be:

```<code> ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
3           | Pro87 |      3      |
</code>```

Thus, I need to alter my sort query to achieve this.

My question, do you know how to solve this problem? To order by status more or less dynamically?

Thanks!

答:
This is actually very simple.  All you need to do is add a CASE statement to the order by, and replace 3 with 4 - and 4 with 3 - and use the StatusID for all other cases.  Very easy.

CODE:

```<code>DECLARE @Project TABLE (ProjectID int, Label varchar(50), ProjectDataID int)
DECLARE @ProjectData TABLE (ProjectDataID int, StatusID int)

INSERT INTO @Project
VALUES
(1, 'Pro22', 2),
(2, 'Pro54', 3),
(3, 'Pro87', 4),
(4, 'Pro77', 5),
(5, 'Pro28', 6)

INSERT INTO @ProjectData
VALUES
(2, 1),
(3, 2),
(4, 3),
(5, 4),
(6, 4)

SELECT  P.ProjectID,
        P.Label,
        PD.StatusID
FROM @Project P
JOIN @ProjectData PD
    ON P.ProjectDataID = PD.ProjectDataID
ORDER BY
    CASE WHEN PD.StatusID = 4 THEN 3
         WHEN PD.StatusID = 3 THEN 4
         ELSE PD.StatusID
    END
</code>```

OUTPUT:

```<code>ProjectID   Label                                              StatusID
----------- -------------------------------------------------- -----------
1           Pro22                                              1
2           Pro54                                              2
4           Pro77                                              4
5           Pro28                                              4
3           Pro87                                              3

(5 row(s) affected)
</code>```

Title: T-SQL ORDER BY several clauses

Body:
I'm currently working on a stored procedure in TSQL on SQL Server 2014. I need to write a query to order a list of Projects by different StatusIds.

Table Project:

ProjectId

Label

ProjectDataId

Table ProjectData:

ProjectDataId

StatusId

Table Project is linked to ProjectData via ProjectDataId.

Demo Data Table Project:

 ProjectId  | Label |  ProjectDataId |
------------+-------+----------------+
1           | Pro22 |      2         |
2           | Pro54 |      3         |
3           | Pro87 |      4         |
4           | Pro77 |      5         |
5           | Pro28 |      6         |

Demo Data Table ProjectData:

 ProjectDataId  |  StatusId   |
----------------+-------------+
2               |      1      |
3               |      2      |
4               |      3      |
5               |      4      |
6               |      4      |

My current result looks like this:

 ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
3           | Pro87 |      3      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |

My current query looks like this:

SELECT ROW_NUMBER() OVER(ORDER BY StatusId ASC)  AS [RowNumber], *
FROM (SELECT DISTINCT
        [P].ProjectId
      , [P].Label
      , [PD].StatusId
      , [P].ProjectDataId
     FROM [MySchema].[Project] [P]
     INNER JOIN [MyProject].[ProjectData] [PD]
     ON [PD].ProjectDataId = [P].ProjectDataId) dt

This query works to order by statusId asc 1, 2, 3, 4 but not to bring it into the right order of statusId 1, 2, 4, 3.

Actually, the desired output should be:

 ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
3           | Pro87 |      3      |

Thus, I need to alter my sort query to achieve this.

My question, do you know how to solve this problem? To order by status more or less dynamically?

Thanks!

Body:
This is actually very simple.  All you need to do is add a CASE statement to the order by, and replace 3 with 4 - and 4 with 3 - and use the StatusID for all other cases.  Very easy.

CODE:

DECLARE @Project TABLE (ProjectID int, Label varchar(50), ProjectDataID int)
DECLARE @ProjectData TABLE (ProjectDataID int, StatusID int)

INSERT INTO @Project
VALUES
(1, 'Pro22', 2),
(2, 'Pro54', 3),
(3, 'Pro87', 4),
(4, 'Pro77', 5),
(5, 'Pro28', 6)

INSERT INTO @ProjectData
VALUES
(2, 1),
(3, 2),
(4, 3),
(5, 4),
(6, 4)

SELECT  P.ProjectID,
        P.Label,
        PD.StatusID
FROM @Project P
JOIN @ProjectData PD
    ON P.ProjectDataID = PD.ProjectDataID
ORDER BY
    CASE WHEN PD.StatusID = 4 THEN 3
         WHEN PD.StatusID = 3 THEN 4
         ELSE PD.StatusID
    END

OUTPUT:

ProjectID   Label                                              StatusID
----------- -------------------------------------------------- -----------
1           Pro22                                              1
2           Pro54                                              2
4           Pro77                                              4
5           Pro28                                              4
3           Pro87                                              3

(5 row(s) affected)


问:
How to migrate a file and all its commit history to a new repo in git?
I have a repo (repoA) and a file in that repo has 20-30 commits; I want to move that file to repoB with all of the commit history; how do I do that?</p>

答:
If what you want to move is the whole branch as it is, just add a new remote pointing to the new repo and push the branch to it. If you have 30 commits with say 50 files and you want to move the history of a "single" file, as if the file was always alone you will have to rewrite the history of the branch so that you get only the history of that file, no more and then you will add the remote and then push to it.

https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History


问:
Getting error while trying to use paramMap for getting route parameters
```<code>export class HeroDetailComponent {
    heroes;
    constructor(private route: ActivatedRoute, private router: Router, private hs : HeroService){
    }
    ngOnInit(){
        this.route.paramMap
            .switchMap((params : ParamMap) =>
                this.hs.getHeroes(params.get('id')))
            .subscribe((heroes) => {
                console.log("checking for heroes n subscribe",heroes);
                this.heroes = heroes})
    }

}
</code>```

Getting following error

paramMap doesn't exist on type 'ActivatedRoute'

答:
In your switchmap paramMap type is wrong.

It should be

```<code>.switchMap((params : ParamMap) =>
</code>```

Body:
export class HeroDetailComponent {
    heroes;
    constructor(private route: ActivatedRoute, private router: Router, private hs : HeroService){
    }
    ngOnInit(){
        this.route.paramMap
            .switchMap((params : ParamMap) =>
                this.hs.getHeroes(params.get('id')))
            .subscribe((heroes) => {
                console.log("checking for heroes n subscribe",heroes);
                this.heroes = heroes})
    }

}

Getting following error

paramMap doesn't exist on type 'ActivatedRoute'

Body:
In your switchmap paramMap type is wrong.

It should be

.switchMap((params : ParamMap) =>


问:
How to execute tasks sequentially? Swift3
Inside @IBaction func login in else statement I call startObserving(). Why is it not executed on the main thread?

This statement    print("executed") is executed before the code inside self.startObservingDB(callback: { (snapValue) in is evaluated in the else statement.
I don't want startObservingDB to return before it receives snapValue from Firebase. How can I make startObservingDB in the else statement wait for Firebase to complete its tasks and then continue execution?

```<code>@IBAction func logIn(_ sender: AnyObject) {

    FIRAuth.auth()?.signIn(withEmail: email.text!, password: password.text!, completion: { (authData, error) in

   if error != nil {
            //
        } else {
       self.startObservingDB(callback: { (snapValue) in
        if snapValue != nil {
           print("should segue")
               self.performSegue(withIdentifier: "LogInToTabBarController", sender: self)
                    }
                })//end of startObservingDB

//prints before code in else statement, inside self.startObservingDB(callback: { (snapValue)   is evaluated
print("executed")
        }
    })
}

 func startObservingDB(callback:@escaping ((_ snapShot:FIRDataSnapshot?) -> Void)){
    // check if user is singed in
     guard let uid = FIRAuth.auth()?.currentUser?.uid  else {
         return
     }

   dbRef.child(uid).child("profile").observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in

        //pass snapshot vale to callback closure so as to make the values available when calling startObservingDB
        callback(snapshot.value as? FIRDataSnapshot)

    }, withCancel: { (Error:Any) in
        print("Error firebase \(Error)")
        print("You are not a cleaner")

    })
    dbRef.removeAllObservers()
}  // end of startObserving
</code>```

答:
The call to startObservingDB IS happening on the same thread.

However, you'll notice that the call to observeSingleEvent takes a callback. This is because internally that call kicks off a new background thread.  That method, once it completes, will comeback and then call your callback.

So the sequence of events you're seeing is:

Thread A: startObservingDB starts

Thread A: observeSingleEvent starts

Thread B: starts doing internal work for observeSingleEvent

Thread A: observeSingleEvent returns

Thread A: startObservingDB returns

Thread A: print("executed")

Thread B: Finishes doing internal work for observeSingleEvent

Thread B: Executes the callback from the "with" on observeSingleEvent

Thread B: Executes callback(snapshot.value as? FIRDataSnapshot)

Thread B: print("should segue")

Thread B: performSegue

Body:
Inside @IBaction func login in else statement I call startObserving(). Why is it not executed on the main thread?

This statement    print("executed") is executed before the code inside self.startObservingDB(callback: { (snapValue) in is evaluated in the else statement.
I don't want startObservingDB to return before it receives snapValue from Firebase. How can I make startObservingDB in the else statement wait for Firebase to complete its tasks and then continue execution?

@IBAction func logIn(_ sender: AnyObject) {

    FIRAuth.auth()?.signIn(withEmail: email.text!, password: password.text!, completion: { (authData, error) in

   if error != nil {
            //
        } else {
       self.startObservingDB(callback: { (snapValue) in
        if snapValue != nil {
           print("should segue")
               self.performSegue(withIdentifier: "LogInToTabBarController", sender: self)
                    }
                })//end of startObservingDB

//prints before code in else statement, inside self.startObservingDB(callback: { (snapValue)   is evaluated
print("executed")
        }
    })
}

 func startObservingDB(callback:@escaping ((_ snapShot:FIRDataSnapshot?) -> Void)){
    // check if user is singed in
     guard let uid = FIRAuth.auth()?.currentUser?.uid  else {
         return
     }

   dbRef.child(uid).child("profile").observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in

        //pass snapshot vale to callback closure so as to make the values available when calling startObservingDB
        callback(snapshot.value as? FIRDataSnapshot)

    }, withCancel: { (Error:Any) in
        print("Error firebase \(Error)")
        print("You are not a cleaner")

    })
    dbRef.removeAllObservers()
}  // end of startObserving


问:
ServiceMix 4.2 - Using Endorsed Libraries
I was wondering whether SMX 4.2 has a concept of endorsed libraries?

My use-case is as follows:

There is a certain set of classes which need to be visible to all Java classes executing within the framework/SMX runtime. You might suggest to simply create a bundle out of the classes and export the relevant packages. However, in my SMX runtime, even WAR files can be deployed.
I don't think WAR's installed within the SMX framework can also utilise the Import/Export-Package feature. So I basically need to have this set of classes available to all other classes in a manner similar to say java.util.List is available.

In Tomcat, this can be done by placing the JAR within the lib/endorsed directory. However, I believe SMX doesn't declare any endorsed directories. So I created an endorsed directory within the %JAVA_HOME%\jre\lib\ folder. But my classes fail to get resolved.

Any assistance is greatly appreciated.

Thanks a lot!

答: Well, you can copy your jars into SMX_HOME/system and add declarations to SMX_HOME/etc/startup.properties with appropriate startup priority (I have used 30)</p>

ContentLicense: CC BY-SA 2.5


问:
Building Maven project with company internal repositories
I maintain project at my company which uses legacy dependencies. Most of them are in provided scope, because they are present on my JBoss classpath. I need them only for compilation.

I have also declared in my pom.xml two additional repositories - Jboss Releases and Jboss Thirdparty Releases. Despite the fact, I do not declare explicitly OSS Sonatype Repository some dependencies are also downloaded from there. It confuses me a lot.

Now, I have to change this project to use with my company internal Nexus repositories, but some transitive dependencies are missing.

What in your opinion would be the easiest way to fill with jars my internal Nexus and to change my project to use only company internal  repos?

Two approaches comes to my mind:
1. Create empty local repository, and then import it into Nexus.
2. Retrieve from build log what repositories are downloaded and then to create mirror of all that places.

答: In your internal repository manager, you can add proxy repositories and point your pom.xml to use only your internal repository.


问:
No qualifying bean of type 'javax.persistence.EntityManager' available: expected single matching bean but found 2
I have two entity manager configurations for two separate databases but when I try to auto-wire an entity manager in to configure my GraphQLExecutor bean I get an exception stating that there are two beans that match the criteria even though I've specified a unit name in the PersistenceContext.

Exception

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'graphQLExecutor': Injection of resource
  dependencies failed; nested exception is
  org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
  qualifying bean of type 'javax.persistence.EntityManager' available:
  expected single matching bean but found 2:
  org.springframework.orm.jpa.SharedEntityManagerCreator#0,org.springframework.orm.jpa.SharedEntityManagerCreator#1
  at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
  ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  com.ogl.JpaDemoApplication.main(JpaDemoApplication.java:15)
  [classes/:na] Caused by:
  org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
  qualifying bean of type 'javax.persistence.EntityManager' available:
  expected single matching bean but found 2:
  org.springframework.orm.jpa.SharedEntityManagerCreator#0,org.springframework.orm.jpa.SharedEntityManagerCreator#1
    at
  org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:518)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:496)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:627)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     ... 17 common
  frames omitted

Entity Manager 1

```<code>package com.ogl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.ogl.system", entityManagerFactoryRef = "companyEntityManagerFactory", transactionManagerRef = "companyTransactionManager")
public class SystemJpaConfig {

  private final Environment environment;

  @Autowired
  public SystemJpaConfig(Environment environment) {
    this.environment = environment;
  }

  @Bean("systemEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean systemEntityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setPackagesToScan("com.ogl.system");
    entityManagerFactoryBean.setPersistenceUnitName("system");
    entityManagerFactoryBean.setDataSource(systemDataSource());

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.POSTGRESQL);
    adapter.setShowSql(true);
    adapter.setGenerateDdl(false);

    entityManagerFactoryBean.setJpaVendorAdapter(adapter);

    return entityManagerFactoryBean;
  }

  @Bean
  DataSource systemDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getProperty("p4.datasource.driver"));
    dataSource.setUrl(environment.getProperty("p4.system.url"));
    dataSource.setUsername(environment.getProperty("p4.system.user"));
    dataSource.setPassword(environment.getProperty("p4.system.password"));

    return dataSource;
  }

  @Bean
  public PlatformTransactionManager systemTransactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory((systemEntityManagerFactory().getObject()));

    return transactionManager;
  }
}
</code>```

Entity Manager 2

```<code>package com.ogl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.ogl.company", entityManagerFactoryRef = "companyEntityManagerFactory", transactionManagerRef = "companyTransactionManager")
public class CompanyJpaConfig {

  private final Environment environment;

  @Autowired
  public CompanyJpaConfig(Environment environment) {
    this.environment = environment;
  }

  @Primary
  @Bean("companyEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean companyEntityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setPackagesToScan("com.ogl.company");
    entityManagerFactoryBean.setPersistenceUnitName("company");
    entityManagerFactoryBean.setDataSource(companyDataSource());

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.POSTGRESQL);
    adapter.setShowSql(true);
    adapter.setGenerateDdl(false);

    entityManagerFactoryBean.setJpaVendorAdapter(adapter);

    return entityManagerFactoryBean;
  }

  @Bean
  DataSource companyDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getProperty("p4.datasource.driver"));
    dataSource.setUrl(environment.getProperty("p4.company.url"));
    dataSource.setUsername(environment.getProperty("p4.company.user"));
    dataSource.setPassword(environment.getProperty("p4.company.password"));

    return dataSource;
  }

  @Primary
  @Bean
  public PlatformTransactionManager companyTransactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory((companyEntityManagerFactory().getObject()));

    return transactionManager;
  }
}
</code>```

Injection

```<code>package com.ogl;

import org.crygier.graphql.GraphQLExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Configuration
@ComponentScan
public class GraphQLJpaConfig {

  @PersistenceContext(unitName = "company")
  private EntityManager entityManager;

  @Bean
  public GraphQLExecutor graphQLExecutor() {
    return new GraphQLExecutor(entityManager);
  }
}
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ogl</groupId>
    <artifactId>jpa-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jpa-demo</name>
    <description>Demo project for JPA</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-java</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.crygier</groupId>
            <artifactId>graphql-jpa</artifactId>
            <version>0.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答:
Found a solution by marking the class I was injecting with the EntityManager with @Component and then auto-wiring that class into the class that uses the GraphQLExecutor:

New class marked @Component

```<code>package p4;

import org.crygier.graphql.GraphQLExecutor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Component
public class CompanyGraphQLComponent {

  @PersistenceContext(unitName = "company")
  private EntityManager entityManager;

  public GraphQLExecutor graphQLExecutor() {
    return new GraphQLExecutor(entityManager);
  }
}
</code>```

Class auto-wiring CompanyGraphQLComponent

```<code>package p4.rest.controllers;

import core_services.persistence.CompanyContextHolder;
import core_services.records.system.Company;
import graphql.ExecutionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import p4.CompanyGraphQLComponent;
import p4.records.GraphQLQuery;

@RestController
public class GraphQLController {
  @Autowired
  private CompanyGraphQLComponent companyGraphQLComponent;

  @RequestMapping(value = "/graphql", consumes = MediaType.APPLICATION_JSON_VALUE)
  public ExecutionResult postJson(@RequestBody GraphQLQuery graphQLQuery) {
    return companyGraphQLComponent.graphQLExecutor().execute(graphQLQuery.getQuery(), graphQLQuery.getVariables());
  }
}
</code>```

Body:
I have two entity manager configurations for two separate databases but when I try to auto-wire an entity manager in to configure my GraphQLExecutor bean I get an exception stating that there are two beans that match the criteria even though I've specified a unit name in the PersistenceContext.

Exception

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'graphQLExecutor': Injection of resource
  dependencies failed; nested exception is
  org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
  qualifying bean of type 'javax.persistence.EntityManager' available:
  expected single matching bean but found 2:
  org.springframework.orm.jpa.SharedEntityManagerCreator#0,org.springframework.orm.jpa.SharedEntityManagerCreator#1
  at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
  ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  com.ogl.JpaDemoApplication.main(JpaDemoApplication.java:15)
  [classes/:na] Caused by:
  org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
  qualifying bean of type 'javax.persistence.EntityManager' available:
  expected single matching bean but found 2:
  org.springframework.orm.jpa.SharedEntityManagerCreator#0,org.springframework.orm.jpa.SharedEntityManagerCreator#1
    at
  org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:518)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:496)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:627)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     ... 17 common
  frames omitted

Entity Manager 1

package com.ogl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.ogl.system", entityManagerFactoryRef = "companyEntityManagerFactory", transactionManagerRef = "companyTransactionManager")
public class SystemJpaConfig {

  private final Environment environment;

  @Autowired
  public SystemJpaConfig(Environment environment) {
    this.environment = environment;
  }

  @Bean("systemEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean systemEntityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setPackagesToScan("com.ogl.system");
    entityManagerFactoryBean.setPersistenceUnitName("system");
    entityManagerFactoryBean.setDataSource(systemDataSource());

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.POSTGRESQL);
    adapter.setShowSql(true);
    adapter.setGenerateDdl(false);

    entityManagerFactoryBean.setJpaVendorAdapter(adapter);

    return entityManagerFactoryBean;
  }

  @Bean
  DataSource systemDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getProperty("p4.datasource.driver"));
    dataSource.setUrl(environment.getProperty("p4.system.url"));
    dataSource.setUsername(environment.getProperty("p4.system.user"));
    dataSource.setPassword(environment.getProperty("p4.system.password"));

    return dataSource;
  }

  @Bean
  public PlatformTransactionManager systemTransactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory((systemEntityManagerFactory().getObject()));

    return transactionManager;
  }
}

Entity Manager 2

package com.ogl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.ogl.company", entityManagerFactoryRef = "companyEntityManagerFactory", transactionManagerRef = "companyTransactionManager")
public class CompanyJpaConfig {

  private final Environment environment;

  @Autowired
  public CompanyJpaConfig(Environment environment) {
    this.environment = environment;
  }

  @Primary
  @Bean("companyEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean companyEntityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setPackagesToScan("com.ogl.company");
    entityManagerFactoryBean.setPersistenceUnitName("company");
    entityManagerFactoryBean.setDataSource(companyDataSource());

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.POSTGRESQL);
    adapter.setShowSql(true);
    adapter.setGenerateDdl(false);

    entityManagerFactoryBean.setJpaVendorAdapter(adapter);

    return entityManagerFactoryBean;
  }

  @Bean
  DataSource companyDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getProperty("p4.datasource.driver"));
    dataSource.setUrl(environment.getProperty("p4.company.url"));
    dataSource.setUsername(environment.getProperty("p4.company.user"));
    dataSource.setPassword(environment.getProperty("p4.company.password"));

    return dataSource;
  }

  @Primary
  @Bean
  public PlatformTransactionManager companyTransactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory((companyEntityManagerFactory().getObject()));

    return transactionManager;
  }
}

Injection

package com.ogl;

import org.crygier.graphql.GraphQLExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Configuration
@ComponentScan
public class GraphQLJpaConfig {

  @PersistenceContext(unitName = "company")
  private EntityManager entityManager;

  @Bean
  public GraphQLExecutor graphQLExecutor() {
    return new GraphQLExecutor(entityManager);
  }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ogl</groupId>
    <artifactId>jpa-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jpa-demo</name>
    <description>Demo project for JPA</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-java</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.crygier</groupId>
            <artifactId>graphql-jpa</artifactId>
            <version>0.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Body:
Found a solution by marking the class I was injecting with the EntityManager with @Component and then auto-wiring that class into the class that uses the GraphQLExecutor:

New class marked @Component

package p4;

import org.crygier.graphql.GraphQLExecutor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Component
public class CompanyGraphQLComponent {

  @PersistenceContext(unitName = "company")
  private EntityManager entityManager;

  public GraphQLExecutor graphQLExecutor() {
    return new GraphQLExecutor(entityManager);
  }
}

Class auto-wiring CompanyGraphQLComponent

package p4.rest.controllers;

import core_services.persistence.CompanyContextHolder;
import core_services.records.system.Company;
import graphql.ExecutionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import p4.CompanyGraphQLComponent;
import p4.records.GraphQLQuery;

@RestController
public class GraphQLController {
  @Autowired
  private CompanyGraphQLComponent companyGraphQLComponent;

  @RequestMapping(value = "/graphql", consumes = MediaType.APPLICATION_JSON_VALUE)
  public ExecutionResult postJson(@RequestBody GraphQLQuery graphQLQuery) {
    return companyGraphQLComponent.graphQLExecutor().execute(graphQLQuery.getQuery(), graphQLQuery.getVariables());
  }
}


问:
XMLHttpRequest is not defined when testing react-native app with jest
i am trying to test a apiwrapper in a react-native based app using jest (integration testing).
When i run it in the iOs simulator everything runs fine however it wont run my jest tests correctly - i always get:

```<code>ReferenceError: XMLHttpRequest is not defined
</code>```

when i try to run tests using my api wrapper, eg.:

```<code>it('Login successful with correct data', () => {
  let api = Api.getInstance();
  return api.login("test", "testpass")
         .then(result => expect(result).toEqual('login_successful'));
});
</code>```

the api class i am trying to test here does use the fetch api (not vanilla xhr). I assume its something related to jest trying to mock something but have not found a way to make it work yet.

Thanks in advance.

答:
In my case, I'm not testing the search code but only importing it somewhere in my code path, so I decided to just mock it at the global level in a setup.js file (loaded using --require at test run). The following works for me:

```<code>// needed in react-instantsearch
class XMLHttpRequest {}
global.XMLHttpRequest = XMLHttpRequest;
</code>```

Body:
i am trying to test a apiwrapper in a react-native based app using jest (integration testing).
When i run it in the iOs simulator everything runs fine however it wont run my jest tests correctly - i always get:

ReferenceError: XMLHttpRequest is not defined

when i try to run tests using my api wrapper, eg.:

it('Login successful with correct data', () => {
  let api = Api.getInstance();
  return api.login("test", "testpass")
         .then(result => expect(result).toEqual('login_successful'));
});

the api class i am trying to test here does use the fetch api (not vanilla xhr). I assume its something related to jest trying to mock something but have not found a way to make it work yet.

Thanks in advance.

Body:
In my case, I'm not testing the search code but only importing it somewhere in my code path, so I decided to just mock it at the global level in a setup.js file (loaded using --require at test run). The following works for me:

// needed in react-instantsearch
class XMLHttpRequest {}
global.XMLHttpRequest = XMLHttpRequest;


问:
How to write this kind of documentation easily?
I love pure ascii text documentation, like this one:
http://www.catonmat.net/download/sed.stream.editor.cheat.sheet.txt

But I don't know how to write it easily. There are lots of tables in it. Anyone can explain it please?

Thanks.

答: Try the Emacs Table Mode: http://www.emacswiki.org/emacs/TableMode (http://table.sourceforge.net)</p>


问:
How to fight unresolved variables warning in WebStorm
I have a function which takes a data from ajax:

```<code>function test(str){
   var obj=JSON.parse(str);
   console.log(obj.xxx);
}
</code>```

WebStorm says that xxx - is unresolved variable.
I can't use @namespace. So how can I do?

答: In cases when the actual data is only known at runtime (for example, when data is a value set through ajax call), it can't re resolved during static analysis, so the warnings are expected. See https://youtrack.jetbrains.com/issue/WEB-17419#comment=27-1058451, http://devnet.jetbrains.com/message/5504337#5504337 for possible workarounds.</p>

Body:
I have a function which takes a data from ajax:

function test(str){
   var obj=JSON.parse(str);
   console.log(obj.xxx);
}

WebStorm says that xxx - is unresolved variable.
I can't use @namespace. So how can I do?


问:
Terse way to intersperse element between all elements in JavaScript array?
Say I have an array var arr = [1, 2, 3], and I want to separate each element by an element eg. var sep = "&", so the output is [1, "&", 2, "&", 3].

Another way to think about it is I want to do Array.prototype.join (arr.join(sep)) without the result being a string (because the elements and separator I am trying to use are Objects, not strings).

Is there a functional/nice/elegant way to do this in either es6/7 or lodash without something that feels clunky like:

```<code>_.flatten(arr.map((el, i) => [el, i < arr.length-1 ? sep : null])) // too complex
</code>```

or

```<code>_.flatten(arr.map(el => [el, sep]).slice(0,-1) // extra sep added, memory wasted
</code>```

or even

```<code>arr.reduce((prev,curr) => { prev.push(curr, sep); return prev; }, []).slice(0,-1)
// probably the best out of the three, but I have to do a map already
// and I still have the same problem as the previous two - either
// inline ternary or slice
</code>```

Edit: Haskell has this function, called intersperse

答:
If you have Ramda in your dependencies or if willing to add it, there is intersperse method there.

From the docs:

Creates a new list with the separator interposed between elements.

Dispatches to the intersperse method of the second argument, if present.

```<code>R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a']
</code>```

Or you can check out the source for one of the ways to do it in your codebase. https://github.com/ramda/ramda/blob/v0.24.1/src/intersperse.js

Body:
Say I have an array var arr = [1, 2, 3], and I want to separate each element by an element eg. var sep = "&", so the output is [1, "&", 2, "&", 3].

Another way to think about it is I want to do Array.prototype.join (arr.join(sep)) without the result being a string (because the elements and separator I am trying to use are Objects, not strings).

Is there a functional/nice/elegant way to do this in either es6/7 or lodash without something that feels clunky like:

_.flatten(arr.map((el, i) => [el, i < arr.length-1 ? sep : null])) // too complex

or

_.flatten(arr.map(el => [el, sep]).slice(0,-1) // extra sep added, memory wasted

or even

arr.reduce((prev,curr) => { prev.push(curr, sep); return prev; }, []).slice(0,-1)
// probably the best out of the three, but I have to do a map already
// and I still have the same problem as the previous two - either
// inline ternary or slice

Edit: Haskell has this function, called intersperse

Body:
If you have Ramda in your dependencies or if willing to add it, there is intersperse method there.

From the docs:

Creates a new list with the separator interposed between elements.

Dispatches to the intersperse method of the second argument, if present.

R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a']

Or you can check out the source for one of the ways to do it in your codebase. https://github.com/ramda/ramda/blob/v0.24.1/src/intersperse.js


问:
Does Beta by Crashlytics Support iOS's On-Demand Resources?
I am fairly certain that the answer to this question is "No", but I am asking anyway. My evidence that Beta by Crashlytics does not support iOS's on-demand-resources is an app build that works fine when downloaded from TestFlight, but throws the following iOS error when downloaded from Beta:

Error Domain = NSCocoaErrorDomain Code = 4994 “The requested
  application data doesn’t exist.” UserInfo = {
      NSLocalizedFailureReason = Request code not be completed. Invalid tag in set ‘{(cardImage, cardAudio)}.’ }

答: I have received confirmation from Fabric that they currently "don't support apps via Beta using on-demand resources."</p>


问:
Can admob banner ads be applied on Dialog? Or its against google ads placement policies
I have custom dialog in my app, they popup when some event occur.
I am thinking to put banner ads on my app dialog popups.
Will that be a good practice ,or its against google banner ads placement policy ?</p>

答:
This could work (you can display an AdView in a PopupWindow, for example), but if the dialogs come up quickly and disappear quickly, it doesn't give the user much time to see and interact with the banner, which can lead to lower clickthrough rates and less revenue for you.

I'd recommend looking at our Interstitial format. You could load them in advance, and display them when the user closes a dialog. If the dialogs are really frequent, you could only show an ad every fifth time, etc.


问:
How to link commands between user control and main in MVVM
I have a user control which have one TextBox and one Button called View. The TextBox takes index values.

On my Main view, I have one list view which will display all lines in a file.
An ObservableCollection is Bind to this.

What I need is, when index value is entered in the TextBox and View Button is clicked(in the user control), the SelecedIndex of the ListView(in the Main) should be changed to the index value.

How can I achieve this using MVVM?

Also, Please provide the proper approach to do this if I am doing it wrong.

Here is my UserControl Code:

XAML

```<code><UserControl.DataContext>
    <VM:IndexView_VM ></VM:IndexView_VM>
</UserControl.DataContext>
<Grid Background="White">
    <TextBlock Margin="10,12,168,9" Text="Index : "/>
    <TextBox Text="{Binding Index}" x:Name="TB_Index" Margin="53,11,90,8" />
    <Button Command="{Binding View_CMD}" x:Name="BT_View" Content="View" Margin="136,11,10,8" />
</Grid>
</code>```

ViewModel

```<code>public class IndexView_VM : ViewModelBase
{
    public IndexView_VM()
    {
        View_CMD = new RelayCommand(_View_CMD);
    }

    int _Index;
    public int Index
    {
        get { return _Index; }
        set
        {
            _Index = value;
            RaisePropertyChanged();
        }
    }

    public RelayCommand View_CMD { get; set; }
    internal void _View_CMD(object Parameter)
    {
        // What to write here?
    }
}
</code>```

Here is the Main View:

XAML

```<code><UserControl.DataContext>
        <VM:MainView_VM></VM:MainView_VM>
    </UserControl.DataContext>
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="111*"/>
            <ColumnDefinition Width="100*"/>
        </Grid.ColumnDefinitions>
        <StackPanel>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
        </StackPanel>
        <ListView ItemsSource="{Binding FileData}" x:Name="listView" Grid.Column="1" >
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Data" Width="100"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</code>```

View Model

```<code>public class MainView_VM : ViewModelBase
{
    public MainView_VM()
    {
        ReadFile();
    }

    public ObservableCollection<string> FileData { get; set; }

    void ReadFile()
    {
        //I will read file here.
    }
}
</code>```

答:
Here is a very basic example of what you want to do:

Window XAML

```<code><Window.Resources>
    <local:StringToIntConverter x:Key="StringToIntConverter" />
</Window.Resources>
<StackPanel>
    <TextBlock>Select Index</TextBlock>
    <TextBox x:Name="theTextBox" Text="{Binding SelectedIndex,ElementName=theList,Converter={StaticResource StringToIntConverter},Mode=OneWayToSource,UpdateSourceTrigger=Explicit}" />
    <Button Click="Button_Click">Select Now</Button>
    <ListBox x:Name="theList">
        <ListBoxItem>First</ListBoxItem>
        <ListBoxItem>Second</ListBoxItem>
        <ListBoxItem>Third</ListBoxItem>
    </ListBox>
</StackPanel>
</code>```

Window CodeBehind

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    theTextBox.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
}
</code>```

Explanation

You were asking to set the index on a list from a textbox by clicking a button. We bind the TextBox to the selected index with a couple of settings:

Source: SelectedIndex

ElementName: The List/Target UI Element

Converter: Required to get from String to Int (i wrote on myself)

Mode: OneWayToSource, we force the textbox to only send values to the list and not the other way round

UpdateSourceTrigger: We do not want the binding to auto-update, we want to do this ourselves

To update the binding we use the Click Event of the button.

But what about the view model?
The operation is a View-Only operation, the ViewModel doesn't need to know anything about it, so we should leave it out of the operation. That's why I'm not using a CommandBinding.

Whoops, forgot about the UserControl
If you want to put this in a user control then i suggest that you don't create a ViewModel at all. Also in the user control you don't need DataBinding, only on the outside. Keep it simple:

UserControl XAML

```<code><TextBlock>Select Index</TextBlock>
<TextBox x:Name="theTextBox" />
<Button Click="Button_Click">Select Now</Button>
</code>```

UserControl CodeBehind

```<code>public int Index
{
    get { return (int)GetValue(IndexProperty); }
    set { SetValue(IndexProperty, value); }
}

public static readonly DependencyProperty IndexProperty =
        DependencyProperty.Register("Index", typeof(int), typeof(ListViewIndexSelectorControl), new PropertyMetadata(0));
private void Button_Click(object sender, RoutedEventArgs e)
{
    if(int.TryParse(theTextBox.Text, out int result))
    {
        Index = result;
    }
}
</code>```

MainWindow Usage XAML

```<code><local:ListViewIndexSelectorControl Index="{Binding SelectedIndex,ElementName=theList,Mode=OneWayToSource}" />
<ListBox x:Name="theList">
    <ListBoxItem>First</ListBoxItem>
    <ListBoxItem>Second</ListBoxItem>
    <ListBoxItem>Third</ListBoxItem>
</ListBox>
</code>```

If you later on need a ViewModel, you can also use the View as the ViewModel for simple controls, just set DataContext = this; in the View's constructor or use a Name on the XAML element and bind the DataContext by ElementName.

Body:
I have a user control which have one TextBox and one Button called View. The TextBox takes index values.

On my Main view, I have one list view which will display all lines in a file.
An ObservableCollection is Bind to this.

What I need is, when index value is entered in the TextBox and View Button is clicked(in the user control), the SelecedIndex of the ListView(in the Main) should be changed to the index value.

How can I achieve this using MVVM?

Also, Please provide the proper approach to do this if I am doing it wrong.

Here is my UserControl Code:

XAML

<UserControl.DataContext>
    <VM:IndexView_VM ></VM:IndexView_VM>
</UserControl.DataContext>
<Grid Background="White">
    <TextBlock Margin="10,12,168,9" Text="Index : "/>
    <TextBox Text="{Binding Index}" x:Name="TB_Index" Margin="53,11,90,8" />
    <Button Command="{Binding View_CMD}" x:Name="BT_View" Content="View" Margin="136,11,10,8" />
</Grid>

ViewModel

public class IndexView_VM : ViewModelBase
{
    public IndexView_VM()
    {
        View_CMD = new RelayCommand(_View_CMD);
    }

    int _Index;
    public int Index
    {
        get { return _Index; }
        set
        {
            _Index = value;
            RaisePropertyChanged();
        }
    }

    public RelayCommand View_CMD { get; set; }
    internal void _View_CMD(object Parameter)
    {
        // What to write here?
    }
}

Here is the Main View:

XAML

<UserControl.DataContext>
        <VM:MainView_VM></VM:MainView_VM>
    </UserControl.DataContext>
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="111*"/>
            <ColumnDefinition Width="100*"/>
        </Grid.ColumnDefinitions>
        <StackPanel>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
            <local:IndexView/>
        </StackPanel>
        <ListView ItemsSource="{Binding FileData}" x:Name="listView" Grid.Column="1" >
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Data" Width="100"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

View Model

public class MainView_VM : ViewModelBase
{
    public MainView_VM()
    {
        ReadFile();
    }

    public ObservableCollection<string> FileData { get; set; }

    void ReadFile()
    {
        //I will read file here.
    }
}

Body:
Here is a very basic example of what you want to do:

Window XAML

<Window.Resources>
    <local:StringToIntConverter x:Key="StringToIntConverter" />
</Window.Resources>
<StackPanel>
    <TextBlock>Select Index</TextBlock>
    <TextBox x:Name="theTextBox" Text="{Binding SelectedIndex,ElementName=theList,Converter={StaticResource StringToIntConverter},Mode=OneWayToSource,UpdateSourceTrigger=Explicit}" />
    <Button Click="Button_Click">Select Now</Button>
    <ListBox x:Name="theList">
        <ListBoxItem>First</ListBoxItem>
        <ListBoxItem>Second</ListBoxItem>
        <ListBoxItem>Third</ListBoxItem>
    </ListBox>
</StackPanel>

Window CodeBehind

private void Button_Click(object sender, RoutedEventArgs e)
{
    theTextBox.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
}

Explanation

You were asking to set the index on a list from a textbox by clicking a button. We bind the TextBox to the selected index with a couple of settings:

Source: SelectedIndex

ElementName: The List/Target UI Element

Converter: Required to get from String to Int (i wrote on myself)

Mode: OneWayToSource, we force the textbox to only send values to the list and not the other way round

UpdateSourceTrigger: We do not want the binding to auto-update, we want to do this ourselves

To update the binding we use the Click Event of the button.

But what about the view model?
The operation is a View-Only operation, the ViewModel doesn't need to know anything about it, so we should leave it out of the operation. That's why I'm not using a CommandBinding.

Whoops, forgot about the UserControl
If you want to put this in a user control then i suggest that you don't create a ViewModel at all. Also in the user control you don't need DataBinding, only on the outside. Keep it simple:

UserControl XAML

<TextBlock>Select Index</TextBlock>
<TextBox x:Name="theTextBox" />
<Button Click="Button_Click">Select Now</Button>

UserControl CodeBehind

public int Index
{
    get { return (int)GetValue(IndexProperty); }
    set { SetValue(IndexProperty, value); }
}

public static readonly DependencyProperty IndexProperty =
        DependencyProperty.Register("Index", typeof(int), typeof(ListViewIndexSelectorControl), new PropertyMetadata(0));
private void Button_Click(object sender, RoutedEventArgs e)
{
    if(int.TryParse(theTextBox.Text, out int result))
    {
        Index = result;
    }
}

MainWindow Usage XAML

<local:ListViewIndexSelectorControl Index="{Binding SelectedIndex,ElementName=theList,Mode=OneWayToSource}" />
<ListBox x:Name="theList">
    <ListBoxItem>First</ListBoxItem>
    <ListBoxItem>Second</ListBoxItem>
    <ListBoxItem>Third</ListBoxItem>
</ListBox>

If you later on need a ViewModel, you can also use the View as the ViewModel for simple controls, just set DataContext = this; in the View's constructor or use a Name on the XAML element and bind the DataContext by ElementName.


问:
If I import my module, my services aren't singleton, but if I don't, my controllers don't work
I've set up my project as follows:

app

app.module (imports: [])

shared

shared.module (declarations: [sharedComponent], providers: [sharedService])

sharedService

sharedComponent

module1

module1.module (imports: [sharedModule])

module1.component (routing child uses sharedComponent)

module2

module2.module (imports: [sharedModule])

module2.component (routing child uses sharedComponent)

This doesn't throw any errors, but setting a breakpoint in the sharedService constructor reveals that it's not singleton.

I can change my imports to this instead:

app

app.module (imports: [sharedModule])

shared

shared.module (declarations: [sharedComponent], providers: [sharedService])

sharedService

sharedComponent

module1

module1.module (imports: [])

module1.component (routing child uses sharedComponent)

module2

module2.module (imports: [])

module2.component (routing child uses sharedComponent)

sharedService appears to be singleton now, but I get an error

Component sharedComponentis not part of any NgModule or the module has not been imported into your module

I want my shared services to be singleton, but need access to shared components. What am I doing wrong?

答:
For anyone else that runs across this issue, I had a core misunderstanding of what my shared module should contain. The docs say:

Create a SharedModule with the components, directives, and pipes that
  you use everywhere in your app. This module should consist entirely of
  declarations, most of them exported.

The SharedModule may re-export other widget modules, such as
  CommonModule, FormsModule, and modules with the UI controls that you
  use most widely.

The SharedModule should not have providers for reasons explained
  previously. Nor should any of its imported or re-exported modules have
  providers. If you deviate from this guideline, know what you're doing
  and why.

Import the SharedModule in your feature modules, both those loaded
  when the app starts and those you lazy load later.

Create a CoreModule with providers for the singleton services you load
  when the application starts.

Import CoreModule in the root AppModule only. Never import CoreModule
  in any other module.

Consider making CoreModule a pure services module with no
  declarations.

Moving my shared services out of SharedModule and into CoreModule is the solution.


问:
The trait `FnMut<(char,)>` is not implemented for `String` when trying to split a string
I need to split a String (not &str) by another String:

```<code>use std::str::Split;

fn main() {
    let x = "".to_string().split("".to_string());
}
</code>```

Why do I get this error and how to avoid it if I already have to operate on strings?

error[E0277]: the trait bound `std::string::String: std::ops::FnMut<(char,)>` is not satisfied
 --> src/main.rs:4:32
  |
4 |         let x = "".to_string().split("".to_string());
  |                                ^^^^^ the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
  |
  = note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `std::string::String`
```

According to the #rust-beginners IRC channel, this might be an example of Deref failing in 1.20.0-nightly. How to split a string in Rust? doesn't address the problem of splitting by String, not &str.

答:
I talked about this with #rust-beginners IRC channel and heard the following:

15:12:15           achird | d33tah: split accepts a Pattern, where Pattern can be &str or char, but you're passing a String (no idea why deref is not working)
15:13:01           d33tah | achird: thanks! how can I convert string to str?
15:13:03           achird | i think a simple split(&delimiter2) should fix the problem
15:16:26           calops | why isn't deref working though?
15:21:33        @mbrubeck | calops, d33tah: Deref coercions only work if one exact "expected" type is known.  For a generic type like
, coercion doesn't kick in.
15:24:11        @mbrubeck | d33tah: The error should definitely be improved...  It should complain that `String` doesn't impl `Pattern`, instead of jumping straight to `FnMut(char)`
```

<p>So basically, the solution is to add & before the delimiter string, like this:</p>

```fn main() {
    let s1 = "".to_string();
    let s2 = "".to_string();
    let x = s1.split(&s2);
}
```

Body:
I need to split a String (not &str) by another String:

use std::str::Split;

fn main() {
    let x = "".to_string().split("".to_string());
}

Why do I get this error and how to avoid it if I already have to operate on strings?

error[E0277]: the trait bound `std::string::String: std::ops::FnMut<(char,)>` is not satisfied
 --> src/main.rs:4:32
  |
4 |         let x = "".to_string().split("".to_string());
  |                                ^^^^^ the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
  |
  = note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `std::string::String`

According to the #rust-beginners IRC channel, this might be an example of Deref failing in 1.20.0-nightly. How to split a string in Rust? doesn't address the problem of splitting by String, not &str.

Body:
I talked about this with #rust-beginners IRC channel and heard the following:

15:12:15           achird | d33tah: split accepts a Pattern, where Pattern can be &str or char, but you're passing a String (no idea why deref is not working)
15:13:01           d33tah | achird: thanks! how can I convert string to str?
15:13:03           achird | i think a simple split(&delimiter2) should fix the problem
15:16:26           calops | why isn't deref working though?
15:21:33        @mbrubeck | calops, d33tah: Deref coercions only work if one exact "expected" type is known.  For a generic type like <P: Pattern>, coercion doesn't kick in.
15:24:11        @mbrubeck | d33tah: The error should definitely be improved...  It should complain that `String` doesn't impl `Pattern`, instead of jumping straight to `FnMut(char)`

So basically, the solution is to add & before the delimiter string, like this:

fn main() {
    let s1 = "".to_string();
    let s2 = "".to_string();
    let x = s1.split(&s2);
}


问:
how to automatically invoke my application in android
I want to automatically invoke my application  at 12.00 am,This kind of process ,how to implement in android,is it possible?</p>

答:
ReminderBootUp.java file have the code to schedule your activity at particular time

```<code>     package com.app.reminder;

        import java.text.SimpleDateFormat;
        import java.util.Date;

        import android.app.AlarmManager;
        import android.app.PendingIntent;
        import android.content.BroadcastReceiver;
        import android.content.Context;
        import android.content.Intent;
        import android.database.Cursor;
        import android.database.sqlite.SQLiteDatabase;
        import android.util.Log;

        public class ReminderBootUp extends BroadcastReceiver {
            private SQLiteDatabase myDataBase = null;
            private Cursor rs = null;

            @Override
            public void onReceive(Context context, Intent arg1) {
                // TODO Auto-generated method stub
                try {
                    long alarmTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(
                            "2010-12-21 12:00").getTime();
                    int id = 1;
                    Date date = new Date();
                    if (date.getTime() <= alarmTime) {
                        Intent notifyIntent = new Intent(context, youractivity.class);
                        PendingIntent intent = PendingIntent.getBroadcast(context, id,
                                notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        AlarmManager am = (AlarmManager) context
                                .getSystemService(Context.ALARM_SERVICE);
                        am.set(AlarmManager.RTC_WAKEUP, alarmTime, intent);
                    }

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage(), e);
                }
            }

        }
</code>```

you should add this line in Manifest.xml file

```<code><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
<receiver android:name="ReminderBootUp" android:permission="android.permission.RECEIVE_BOOT_COMPLETED" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>
</code>```

this code will work after booting the device...

if you want to start your application as normal statup activity,
write as our normal code

Body:
ReminderBootUp.java file have the code to schedule your activity at particular time

     package com.app.reminder;

        import java.text.SimpleDateFormat;
        import java.util.Date;

        import android.app.AlarmManager;
        import android.app.PendingIntent;
        import android.content.BroadcastReceiver;
        import android.content.Context;
        import android.content.Intent;
        import android.database.Cursor;
        import android.database.sqlite.SQLiteDatabase;
        import android.util.Log;

        public class ReminderBootUp extends BroadcastReceiver {
            private SQLiteDatabase myDataBase = null;
            private Cursor rs = null;

            @Override
            public void onReceive(Context context, Intent arg1) {
                // TODO Auto-generated method stub
                try {
                    long alarmTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(
                            "2010-12-21 12:00").getTime();
                    int id = 1;
                    Date date = new Date();
                    if (date.getTime() <= alarmTime) {
                        Intent notifyIntent = new Intent(context, youractivity.class);
                        PendingIntent intent = PendingIntent.getBroadcast(context, id,
                                notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        AlarmManager am = (AlarmManager) context
                                .getSystemService(Context.ALARM_SERVICE);
                        am.set(AlarmManager.RTC_WAKEUP, alarmTime, intent);
                    }

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage(), e);
                }
            }

        }

you should add this line in Manifest.xml file

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
<receiver android:name="ReminderBootUp" android:permission="android.permission.RECEIVE_BOOT_COMPLETED" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>

this code will work after booting the device...

if you want to start your application as normal statup activity,
write as our normal code


问:
Accesing elements in a dictionary in python
I am very new in python. I am trying to acces data in a xml file.
my xml file and code is as below:

```<code> import xmltodict

#from xml.dom import minidom

#doc = minidom.parse("staff.xml")

data = """<Azimuth>
      <COL_STEP unit="m">5000</COL_STEP>
      <ROW_STEP unit="m">5000</ROW_STEP>
      <Values_List>
        <VALUES>59.9563 53.0871 44.4595 33.8743 21.5482 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>58.4469 51.1869 42.099 31.0545 18.418 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>56.8537 49.1809 39.623 28.139 15.2538 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>55.1672 47.0649 37.0345 25.1409 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>53.3851 44.8373 34.3343 22.0718 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>51.5013 42.4952 31.5308 18.9484 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>49.5128 40.0378 28.6308 15.7878 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>47.4157 37.4668 25.6447 12.609 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>45.2056 34.7844 22.5855 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>42.8812 31.9968 19.4688 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>40.442 29.1107 16.3121 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>37.8884 26.1373 13.134 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>35.2231 23.0883 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>32.4513 19.9792 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>29.5804 16.8268 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>26.6194 13.6499 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>23.5805 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>20.479 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>17.3318 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>14.1568 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
      </Values_List>
    </Azimuth>"""

data = xmltodict.parse(data, encoding='utf-8')
p=data['Azimuth']['Values_List']
print(type(p))

import dict_digger

print(dict_digger.dig(data, 'Values_List'))
</code>```

What I am trying to acces the 23*23 array inside the 'Values List' but I am struggling. Is there any way I can acces those values?

Thanks

答:
Try

```<code>p=data['Azimuth']['Values_List']['VALUES']
</code>```

You'll probably want the matrix as a numpy array:

```<code>import numpy as np
parsedMatrix = np.array([line.split(' ') for line in p]).astype(float)
</code>```

Body:
I am very new in python. I am trying to acces data in a xml file.
my xml file and code is as below:

 import xmltodict

#from xml.dom import minidom

#doc = minidom.parse("staff.xml")

data = """<Azimuth>
      <COL_STEP unit="m">5000</COL_STEP>
      <ROW_STEP unit="m">5000</ROW_STEP>
      <Values_List>
        <VALUES>59.9563 53.0871 44.4595 33.8743 21.5482 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>58.4469 51.1869 42.099 31.0545 18.418 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>56.8537 49.1809 39.623 28.139 15.2538 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>55.1672 47.0649 37.0345 25.1409 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>53.3851 44.8373 34.3343 22.0718 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>51.5013 42.4952 31.5308 18.9484 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>49.5128 40.0378 28.6308 15.7878 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>47.4157 37.4668 25.6447 12.609 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>45.2056 34.7844 22.5855 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>42.8812 31.9968 19.4688 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>40.442 29.1107 16.3121 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>37.8884 26.1373 13.134 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>35.2231 23.0883 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>32.4513 19.9792 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>29.5804 16.8268 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>26.6194 13.6499 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>23.5805 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>20.479 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>17.3318 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>14.1568 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
        <VALUES>NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN</VALUES>
      </Values_List>
    </Azimuth>"""

data = xmltodict.parse(data, encoding='utf-8')
p=data['Azimuth']['Values_List']
print(type(p))

import dict_digger

print(dict_digger.dig(data, 'Values_List'))

What I am trying to acces the 23*23 array inside the 'Values List' but I am struggling. Is there any way I can acces those values?

Thanks

Body:
Try

p=data['Azimuth']['Values_List']['VALUES']

You'll probably want the matrix as a numpy array:

import numpy as np
parsedMatrix = np.array([line.split(' ') for line in p]).astype(float)


答:
It is better to agree on a fixed format for outputObject and write aggregation query accordingly.

You can now process the outputObject to inject the query operators and transform the keys to match the fields.

Something like below.

```<code>{
    "top": {
      "place": {
        "$in": [
          "A"
        ]
      }
    },
    "testing": {
      "tests.name": {
        "$in": [
          "1"
        ]
      },
      "tests.thing": {
        "$in": [
          "X",
          "Y"
        ]
      }
    }
  }
</code>```

JS Code

```<code>var top = outputObject.top;
Object.keys(top).forEach(function(a) {
    top[a] = {
        "$in": top[a]
    };
});

var testing = outputObject.testing;
Object.keys(testing).forEach(function(a) {
    Object.keys(testing[a]).forEach(function(b) {
        var c = [a + "." + b];
        testing[c] = {
            "$in": testing[a][b]
        };
    })
    delete testing[a];
});
</code>```

You can now use your aggregation query

```<code>db.test.aggregate([{
        $match: top
    },
    {
        $unwind: "$tests"
    },
    {
        $match: testing
    },
    {
        $unwind: "$tests.evaluation"
    },
    {
        $group: {
            _id: null,
            uniqueValues: {
                $addToSet: "$tests.evaluation._id"
            }
        }
    }
])
</code>```

You can refactor your code to use below aggregation pipeline in 3.4

Process your output object ( includes $in operator )  to

```<code>{
  "top": {
    "place": {
      "$in": [
        "A"
      ]
    }
  },
  "testing": {
    "tests": {
      "name": [
        "1"
      ],
      "thing": [
        "X",
        "Y"
      ]
    }
  }
};
</code>```

JS Code

```<code>var top = outputObject.top;
Object.keys(top).forEach(function(a) {top[a] = {"$in":top[a]};});
</code>```

Aggregation:

```<code>[
  {
    "$match": top
  },
  {
    "$addFields": {
      "tests": {
        "$filter": {
          "input": "$$tests",
          "as": "res",
          "cond": {
            "$and": [
              {
                "$in": [
                  "$$res.name",
                  outputObject.testing.tests.name
                ]
              },
              {
                "$in": [
                  "$$res.thing",
                  outputObject.testing.tests.thing
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    "$unwind": "$tests.evaluation"
  },
  {
    "$group": {
      "_id": null,
      "uniqueValues": {
        "$addToSet": "$tests.evaluation._id"
      }
    }
  }
]
</code>```

Title: Dynamically Querying From an Input Object

Body:
I'm trying to dynamically query a database that looks like this:

db.test.insert({
    "_id" : ObjectId("58e574a768afb6085ec3a388"),
    "place": "A",
    "tests" : [
        {
            "name" : "1",
            "thing" : "X",
            "evaluation" : [
                {
                    "_id": ObjectId("58f782fbbebac50d5b2ae558"),
                    "aHigh" : [1,2],
                    "aLow" : [ ],
                    "zHigh" : [ ],
                    "zLow" : [1,3]
                },
                {
                    "_id": ObjectId("58f78525bebac50d5b2ae5c9"),
                    "aHigh" : [1,4],
                    "aLow" : [2],
                    "zHigh" : [ 3],
                    "zLow" : [ ]
                },
                {
                    "_id": ObjectId("58f78695bebac50d5b2ae60e"),
                    "aHigh" : [ ],
                    "aLow" : [1,2,3],
                    "zHigh" : [1,2,3,4],
                    "zLow" : [ ]
                },]
            },
            {
            "name" : "1",
            "thing" : "Y",
            "evaluation" : [
                {
                    "_id": ObjectId("58f78c37bebac50d5b2ae704"),
                    "aHigh" : [1,3],
                    "aLow" : [4],
                    "zHigh" : [ ],
                    "zLow" : [3]
                },
                {
                    "_id": ObjectId("58f79159bebac50d5b2ae75c"),
                    "aHigh" : [1,3,4],
                    "aLow" : [2],
                    "zHigh" : [2],
                    "zLow" : [ ]
                },
                {
                    "_id": ObjectId("58f79487bebac50d5b2ae7f1"),
                    "aHigh" : [1,2,3],
                    "aLow" : [ ],
                    "zHigh" : [ ],
                    "zLow" : [1,2,3,4]
                },]
            }
            ]
        })
db.test.insert({
    "_id" : ObjectId("58eba09e51f7f631dd24aa1c"),
    "place": "B",
    "tests" : [
        {
            "name" : "2",
            "thing" : "Y",
            "evaluation" : [
                {
                    "_id": ObjectId("58f7879abebac50d5b2ae64f"),
                    "aHigh" : [2],
                    "aLow" : [3 ],
                    "zHigh" : [ ],
                    "zLow" : [1,2,3,4]
                },
                {
                    "_id": ObjectId("58f78ae1bebac50d5b2ae6db"),
                    "aHigh" : [ ],
                    "aLow" : [ ],
                    "zHigh" : [ ],
                    "zLow" : [3,4]
                },
                {
                    "_id": ObjectId("58f78ae1bebac50d5b2ae6dc"),
                    "aHigh" : [1,2],
                    "aLow" : [3,4],
                    "zHigh" : [ ],
                    "zLow" : [1,2,3,4]
                },]
            }
            ]
        })

In order to query the database, I have an object that is created by another part of my program. It comes in the form of:

var outputObject = {
    "top": {
        "place": [
        "A"
        ]
    },
    "testing": {
        "tests": {
            "name": [
                "1",
            ],
            "thing": [
                "X",
                "Y"
            ]
        }
    }
    }

I then use that outputObject and $match statements within the aggregate framework to execute the query. I have included two queries which do not seem to work.

db.test.aggregate([
        {$match: {outputObject.top}},
        {$unwind: '$tests'},
        {$match: {outputObject.testing}},
        {$unwind: '$tests.evaluation'},
        {$group: {_id: null, uniqueValues: {$addToSet: "$tests.evaluation._id"}}}
    ])

db.test.aggregate([
        {$match: {$and: [outputObject.top]}},
        {$unwind: '$tests'},
        {$match: {$and: [outputObject.testing]}},
        {$unwind: '$tests.evaluation'},
        {$group: {_id: null, uniqueValues: {$addToSet: "$tests.evaluation._id"}}}
    ])

However, this approach does not seem to be functioning. I have a couple questions:

Do I need to modify the object outputObject before applying it to the $match statement?

Are my queries correct?

Should I be using $and or $in in combination with the $match statement?

What code will produce the desired result?

Currently using mongoDB 3.4.4

Body:
It is better to agree on a fixed format for outputObject and write aggregation query accordingly.

You can now process the outputObject to inject the query operators and transform the keys to match the fields.

Something like below.

{
    "top": {
      "place": {
        "$in": [
          "A"
        ]
      }
    },
    "testing": {
      "tests.name": {
        "$in": [
          "1"
        ]
      },
      "tests.thing": {
        "$in": [
          "X",
          "Y"
        ]
      }
    }
  }

JS Code

var top = outputObject.top;
Object.keys(top).forEach(function(a) {
    top[a] = {
        "$in": top[a]
    };
});

var testing = outputObject.testing;
Object.keys(testing).forEach(function(a) {
    Object.keys(testing[a]).forEach(function(b) {
        var c = [a + "." + b];
        testing[c] = {
            "$in": testing[a][b]
        };
    })
    delete testing[a];
});

You can now use your aggregation query

db.test.aggregate([{
        $match: top
    },
    {
        $unwind: "$tests"
    },
    {
        $match: testing
    },
    {
        $unwind: "$tests.evaluation"
    },
    {
        $group: {
            _id: null,
            uniqueValues: {
                $addToSet: "$tests.evaluation._id"
            }
        }
    }
])

You can refactor your code to use below aggregation pipeline in 3.4

Process your output object ( includes $in operator )  to

{
  "top": {
    "place": {
      "$in": [
        "A"
      ]
    }
  },
  "testing": {
    "tests": {
      "name": [
        "1"
      ],
      "thing": [
        "X",
        "Y"
      ]
    }
  }
};

JS Code

var top = outputObject.top;
Object.keys(top).forEach(function(a) {top[a] = {"$in":top[a]};});

Aggregation:

[
  {
    "$match": top
  },
  {
    "$addFields": {
      "tests": {
        "$filter": {
          "input": "$$tests",
          "as": "res",
          "cond": {
            "$and": [
              {
                "$in": [
                  "$$res.name",
                  outputObject.testing.tests.name
                ]
              },
              {
                "$in": [
                  "$$res.thing",
                  outputObject.testing.tests.thing
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    "$unwind": "$tests.evaluation"
  },
  {
    "$group": {
      "_id": null,
      "uniqueValues": {
        "$addToSet": "$tests.evaluation._id"
      }
    }
  }
]