问:
How to add roles to claims in IdentityServer4?
I am new to IdentityServer and I have been struggling with this issue all day. So much so that I'm almost about to give up on this. I know this question has been asked over and over again and I have tried many different solutions but none seem to work. Hopefully you can help me push me in the right direction with this.

First I installed the IdentityServer4 templates by running dotnet new -i identityserver4.templates and created a new project with the is4aspid template by running dotnet new is4aspid -o IdentityServer.

After that i created a new IdentityServer database and ran the migrations. By that time I had a the default Identity database structure.

In Config.cs I changed MVC client to the following:

```<code>new Client
{
    ClientId = "mvc",
    ClientName = "MVC Client",

    AllowedGrantTypes = GrantTypes.Implicit,
    ClientSecrets = { new Secret("47C2A9E1-6A76-3A19-F3C0-S37763QB36D9".Sha256()) },

    RedirectUris = { "https://localhost:44307/signin-oidc" },
    FrontChannelLogoutUri = "https://localhost:44307/signout-oidc",
    PostLogoutRedirectUris = { "https://localhost:44307/signout-callback-oidc" },

    AllowOfflineAccess = true,
    AllowedScopes = { "openid", "profile", "api1", JwtClaimTypes.Role }
},
</code>```

And changed the GetApis method to this:

```<code>public static IEnumerable<ApiResource> GetApis()
{
    return new ApiResource[]
    {
        new ApiResource("api1", "My API #1", new List<string>() { "role" })
    };
}
</code>```

There where of course no users in the database yet so i added a registration form and registered two dummy users, one with the username admin@example.com and one with the username subscriber@example.com.

To assign the roles to these user I created the following method in Startup.cs.

```<code>private async Task CreateUserRoles(IServiceProvider serviceProvider) {
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

    IdentityResult adminRoleResult;
    IdentityResult subscriberRoleResult;

    bool adminRoleExists = await RoleManager.RoleExistsAsync("Admin");
    bool subscriberRoleExists = await RoleManager.RoleExistsAsync("Subscriber");

    if (!adminRoleExists) {
        adminRoleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
    }

    if(!subscriberRoleExists) {
        subscriberRoleResult = await RoleManager.CreateAsync(new IdentityRole("Subscriber"));
    }

    ApplicationUser userToMakeAdmin = await UserManager.FindByNameAsync("admin@example.com");
    await UserManager.AddToRoleAsync(userToMakeAdmin, "Admin");

    ApplicationUser userToMakeSubscriber = await UserManager.FindByNameAsync("subscriber@example.com");
    await UserManager.AddToRoleAsync(userToMakeSubscriber, "Subscriber");
}
</code>```

In the Configure method of the same class I add the the parameter IServiceProvider services and called the above method like so: CreateUserRoles(services).Wait();. By this time my database did have two roles in it.

Next I created a new solution (within the same project) and in the Startup.cs file of that solution I added the following in the ConfigureServices method.

```<code>    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options => {
            options.SaveTokens = true;
            options.ClientId = "mvc";
            options.ClientSecret = "32D7A7W0-0ALN-2Q44-A1H4-A37990NN83BP";
            options.RequireHttpsMetadata = false;
            options.Authority = "http://localhost:5000/";
            options.ClaimActions.MapJsonKey("role", "role");
        });
</code>```

After that I added app.UseAuthentication(); in the Configure method of the same class.

Then I created a new page with the following if statements.

```<code>if(User.Identity.IsAuthenticated) {
 <div>Yes, user is authenticated</div>
}

if(User.IsInRole("ADMIN")) {
 <div>Yes, user is admin</div>
}
</code>```

I logged in with admin@example.com but the second if statement returns False. I inspected all the claims by looping over them like so.

```<code>@foreach (var claim in User.Claims) {
    <dt>@claim.Type</dt>
    <dd>@claim.Value</dd>
}
</code>```

But there was no role claim to be found, only sid, sub, idp, preferred_username and name.

I tried to get the role in there so that the second if statement returns True but after trying and trying I have not yet been able to make it work. Can someone see what I have to do in order to make this work? I am an absolute beginner in IdentityServer4 and trying my best to understand it. Any help will be appreciated. Thanks in advance!

EDIT 1:

Thanks to this question and this question I got the feeling that I'm on the right track. I have made some modifications but I still can not get it to work. I just tried the following.

Created a new ProfileService class in my IdentityServer project with the following content.

```<code>public class MyProfileService : IProfileService {
 public MyProfileService() { }
 public Task GetProfileDataAsync(ProfileDataRequestContext context) {
  var roleClaims = context.Subject.FindAll(JwtClaimTypes.Role);
  List<string> list = context.RequestedClaimTypes.ToList();
  context.IssuedClaims.AddRange(roleClaims);
  return Task.CompletedTask;
 }

 public Task IsActiveAsync(IsActiveContext context) {
  return Task.CompletedTask;
 }
}
</code>```

Next I registered this class in the ConfigureServices method by adding the line services.AddTransient<IProfileService, MyProfileService>();. After that I added a new a new line to the GetIdentityResources method, which looks like this now.

```<code>public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new IdentityResource[]
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
        new IdentityResource("roles", new[] { "role" })
};
}
</code>```

I also added the roles to my Mvc client like so: AllowedScopes = { "openid", "profile", "api1", "roles" }.

Next I switched over to the other project and added the following lines in the .AddOpenIdConnect oidc.

```<code>options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.RoleClaimType = "role";
</code>```

But still, I cannot get it to work like I want it to. Anyone knows what I am missing?

答:
Slightly different question, absolutely matching answer.

With the Edit 1, IdP configuration looks enough to supply both identity and access tokens with roles when requested. The only thing left is to configure the client to request the access token (.Net client doesn't do that by default), or just request the roles scope within the identity token.

To get the roles with id_token, the client side config must include options.Scope.Add("roles");

To get the roles with bearer token, that token must be requested by specifying options.ResponseType = "id_token token"; in client side config.

Body:
I am new to IdentityServer and I have been struggling with this issue all day. So much so that I'm almost about to give up on this. I know this question has been asked over and over again and I have tried many different solutions but none seem to work. Hopefully you can help me push me in the right direction with this.

First I installed the IdentityServer4 templates by running dotnet new -i identityserver4.templates and created a new project with the is4aspid template by running dotnet new is4aspid -o IdentityServer.

After that i created a new IdentityServer database and ran the migrations. By that time I had a the default Identity database structure.

In Config.cs I changed MVC client to the following:

new Client
{
    ClientId = "mvc",
    ClientName = "MVC Client",

    AllowedGrantTypes = GrantTypes.Implicit,
    ClientSecrets = { new Secret("47C2A9E1-6A76-3A19-F3C0-S37763QB36D9".Sha256()) },

    RedirectUris = { "https://localhost:44307/signin-oidc" },
    FrontChannelLogoutUri = "https://localhost:44307/signout-oidc",
    PostLogoutRedirectUris = { "https://localhost:44307/signout-callback-oidc" },

    AllowOfflineAccess = true,
    AllowedScopes = { "openid", "profile", "api1", JwtClaimTypes.Role }
},

And changed the GetApis method to this:

public static IEnumerable<ApiResource> GetApis()
{
    return new ApiResource[]
    {
        new ApiResource("api1", "My API #1", new List<string>() { "role" })
    };
}

There where of course no users in the database yet so i added a registration form and registered two dummy users, one with the username admin@example.com and one with the username subscriber@example.com.

To assign the roles to these user I created the following method in Startup.cs.

private async Task CreateUserRoles(IServiceProvider serviceProvider) {
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

    IdentityResult adminRoleResult;
    IdentityResult subscriberRoleResult;

    bool adminRoleExists = await RoleManager.RoleExistsAsync("Admin");
    bool subscriberRoleExists = await RoleManager.RoleExistsAsync("Subscriber");

    if (!adminRoleExists) {
        adminRoleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
    }

    if(!subscriberRoleExists) {
        subscriberRoleResult = await RoleManager.CreateAsync(new IdentityRole("Subscriber"));
    }

    ApplicationUser userToMakeAdmin = await UserManager.FindByNameAsync("admin@example.com");
    await UserManager.AddToRoleAsync(userToMakeAdmin, "Admin");

    ApplicationUser userToMakeSubscriber = await UserManager.FindByNameAsync("subscriber@example.com");
    await UserManager.AddToRoleAsync(userToMakeSubscriber, "Subscriber");
}

In the Configure method of the same class I add the the parameter IServiceProvider services and called the above method like so: CreateUserRoles(services).Wait();. By this time my database did have two roles in it.

Next I created a new solution (within the same project) and in the Startup.cs file of that solution I added the following in the ConfigureServices method.

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options => {
            options.SaveTokens = true;
            options.ClientId = "mvc";
            options.ClientSecret = "32D7A7W0-0ALN-2Q44-A1H4-A37990NN83BP";
            options.RequireHttpsMetadata = false;
            options.Authority = "http://localhost:5000/";
            options.ClaimActions.MapJsonKey("role", "role");
        });

After that I added app.UseAuthentication(); in the Configure method of the same class.

Then I created a new page with the following if statements.

if(User.Identity.IsAuthenticated) {

Yes, user is authenticated

}

if(User.IsInRole("ADMIN")) {

Yes, user is admin

}

I logged in with admin@example.com but the second if statement returns False. I inspected all the claims by looping over them like so.

@foreach (var claim in User.Claims) {

@claim.Type

@claim.Value

}

But there was no role claim to be found, only sid, sub, idp, preferred_username and name.

I tried to get the role in there so that the second if statement returns True but after trying and trying I have not yet been able to make it work. Can someone see what I have to do in order to make this work? I am an absolute beginner in IdentityServer4 and trying my best to understand it. Any help will be appreciated. Thanks in advance!

EDIT 1:

Thanks to this question and this question I got the feeling that I'm on the right track. I have made some modifications but I still can not get it to work. I just tried the following.

Created a new ProfileService class in my IdentityServer project with the following content.

public class MyProfileService : IProfileService {
 public MyProfileService() { }
 public Task GetProfileDataAsync(ProfileDataRequestContext context) {
  var roleClaims = context.Subject.FindAll(JwtClaimTypes.Role);
  List<string> list = context.RequestedClaimTypes.ToList();
  context.IssuedClaims.AddRange(roleClaims);
  return Task.CompletedTask;
 }

 public Task IsActiveAsync(IsActiveContext context) {
  return Task.CompletedTask;
 }
}

Next I registered this class in the ConfigureServices method by adding the line services.AddTransient<IProfileService, MyProfileService>();. After that I added a new a new line to the GetIdentityResources method, which looks like this now.

public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new IdentityResource[]
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile(),
        new IdentityResource("roles", new[] { "role" })
};
}

I also added the roles to my Mvc client like so: AllowedScopes = { "openid", "profile", "api1", "roles" }.

Next I switched over to the other project and added the following lines in the .AddOpenIdConnect oidc.

options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.RoleClaimType = "role";

But still, I cannot get it to work like I want it to. Anyone knows what I am missing?


来源: stackexchange

问:
Manually get the contents of a file in Spring boot 2
I have a file under src/main/resources/static/css/ called my.css that I'm trying to load as a String, but I can't for the life of me get Spring to find this file that's supposedly statically loaded already in the classpath.

```<code>    private String getCss(String cssFileName) {
        try {
            File file = new ClassPathResource("classpath:" + cssFileName + ".css").getFile();
            return new String(Files.readAllBytes(Paths.get(file.getPath())));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "css not found";
    }
}
</code>```

I've tried various webconfigs, resource loaders, paths and patterns but I just cannot get this to work. How do I find a file in my resources? I'd expect some kind of Resources.getResource("name.type") type of thing which already has a tree with all the resources from the resource folder in it listed.

答:
Using @pandaadb's comment and Spring's auto-wiring functionality to get an instance of the ResourceLoader class:

```<code>@Controller
public class Controller {

    @Autowired private ResourceLoader loader;

    private String getCss(String cssFileName) {
        try {
            File file = loader.getResource("classpath:/static/css/" + cssFileName + ".css").getFile();
            return new String(Files.readAllBytes(Paths.get(file.getPath())));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "css not found";
    }
}
</code>```

The ResourceLoader uses your src/main/resources folder as the root of your "classpath:" search, so simply adding the whole path from that point on works. Don't bother with the classpathloader directly, it gets transformed somehow automatically to one based on the prefix given. This code now finds the file, reads it and converts it to a String.

ContentLicense: CC BY-SA 4.0

Body:
I have a file under src/main/resources/static/css/ called my.css that I'm trying to load as a String, but I can't for the life of me get Spring to find this file that's supposedly statically loaded already in the classpath.

    private String getCss(String cssFileName) {
        try {
            File file = new ClassPathResource("classpath:" + cssFileName + ".css").getFile();
            return new String(Files.readAllBytes(Paths.get(file.getPath())));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "css not found";
    }
}

I've tried various webconfigs, resource loaders, paths and patterns but I just cannot get this to work. How do I find a file in my resources? I'd expect some kind of Resources.getResource("name.type") type of thing which already has a tree with all the resources from the resource folder in it listed.

Body:
Using @pandaadb's comment and Spring's auto-wiring functionality to get an instance of the ResourceLoader class:

@Controller
public class Controller {

    @Autowired private ResourceLoader loader;

    private String getCss(String cssFileName) {
        try {
            File file = loader.getResource("classpath:/static/css/" + cssFileName + ".css").getFile();
            return new String(Files.readAllBytes(Paths.get(file.getPath())));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "css not found";
    }
}

The ResourceLoader uses your src/main/resources folder as the root of your "classpath:" search, so simply adding the whole path from that point on works. Don't bother with the classpathloader directly, it gets transformed somehow automatically to one based on the prefix given. This code now finds the file, reads it and converts it to a String.


问:
Angular Drag and drop is not working if using *ngFor in cdkDropList
I was tried to using angular material drag and drop and I was looping through cdkDropList container. I'm not able to drag the items from Catalogue to (to do )list. If I'm not using any loop then it's working fine.

Here is my stackblitz link

I tried without loop that is working fine

<div cdkDropList #todoList="cdkDropList"  [cdkDropListData]="todo" [cdkDropListConnectedTo]="[done]" [id]="item"
  class="column-list" (cdkDropListDropped)="drop($event)"

    {{item.Name}}

```

<p>but if I'm adding this <code>*ngFor</code> it's not working</p>

<pre class="lang-html prettyprint-override"><code><div cdkDropList #todoList="cdkDropList"  [cdkDropListData]="todo" [cdkDropListConnectedTo]="[done]" [id]="item"
  class="column-list" (cdkDropListDropped)="drop($event)" *ngFor="let item of signalContainer">
  <div class="column-box" [ngClass]="[(item.Name=='R') ?'Red':'',(item.Name=='G') ?'Green':'',(item.Name=='B') ?
  'Blue':'',(item.Name=='Y') ?'Yellow':'',(item.Name=='O') ?'Orange':'']" *ngFor="let item of items3" cdkDrag cdkDragLockAxis="y">
    {{item.Name}}</div>
</div>
</code>```

答:
COMPONENT.TS

```<code>    import {Component} from '@angular/core';
    import {CdkDragDrop, moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';

    @Component({
      selector: 'cdk-drag-drop-connected-sorting-example',
      templateUrl: 'cdk-drag-drop-connected-sorting-example.html',
      styleUrls: ['cdk-drag-drop-connected-sorting-example.css'],
    })
    export class CdkDragDropConnectedSortingExample {

    initialSkeleton = new Array(5);
      done = [
        'A','B','C','D','E'
      ];

      drop(event: CdkDragDrop<string[]>) {
        if (event.previousContainer === event.container) {
          debugger;
         moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
        } else {
          event.container.data[event.currentIndex] =  event.previousContainer.data[event.previousIndex];
        }

      }
    }
</code>```

HTML

```<code> <div class="example-container">
        <h2>To do</h2>
        <div cdkDropList #todoList="cdkDropList" [cdkDropListData]="initialSkeleton" [cdkDropListConnectedTo]="[doneList]" class="example-list"
         (cdkDropListDropped)="drop($event)">
            <div class="example-box" *ngFor="let item of initialSkeleton" cdkDrag>
             <div class="child" >{{item }}</div>
            </div>
        </div>
    </div>
    <div class="example-container">
        <h2>Done</h2>
        <div cdkDropList #doneList="cdkDropList" [cdkDropListData]="done" [cdkDropListConnectedTo]="[todoList]" class="example-list"
         (cdkDropListDropped)="drop($event)">
            <div class="example-box" *ngFor="let item of done" cdkDrag>{{item}}</div>
        </div>
    </div>
</code>```

I've modified the code now you will be able to  drag and drop items in the for loop. Hope it answers your question.

Body:
I was tried to using angular material drag and drop and I was looping through cdkDropList container. I'm not able to drag the items from Catalogue to (to do )list. If I'm not using any loop then it's working fine.

Here is my stackblitz link

I tried without loop that is working fine

<div cdkDropList #todoList="cdkDropList"  [cdkDropListData]="todo" [cdkDropListConnectedTo]="[done]" [id]="item"
  class="column-list" (cdkDropListDropped)="drop($event)"

    {{item.Name}}

but if I'm adding this *ngFor it's not working

    {{item.Name}}

Body:
COMPONENT.TS

    import {Component} from '@angular/core';
    import {CdkDragDrop, moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';

    @Component({
      selector: 'cdk-drag-drop-connected-sorting-example',
      templateUrl: 'cdk-drag-drop-connected-sorting-example.html',
      styleUrls: ['cdk-drag-drop-connected-sorting-example.css'],
    })
    export class CdkDragDropConnectedSortingExample {

    initialSkeleton = new Array(5);
      done = [
        'A','B','C','D','E'
      ];

      drop(event: CdkDragDrop<string[]>) {
        if (event.previousContainer === event.container) {
          debugger;
         moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
        } else {
          event.container.data[event.currentIndex] =  event.previousContainer.data[event.previousIndex];
        }

      }
    }

HTML

 <div class="example-container">
        <h2>To do</h2>
        <div cdkDropList #todoList="cdkDropList" [cdkDropListData]="initialSkeleton" [cdkDropListConnectedTo]="[doneList]" class="example-list"
         (cdkDropListDropped)="drop($event)">
            <div class="example-box" *ngFor="let item of initialSkeleton" cdkDrag>
             <div class="child" >{{item }}</div>
            </div>
        </div>
    </div>
    <div class="example-container">
        <h2>Done</h2>
        <div cdkDropList #doneList="cdkDropList" [cdkDropListData]="done" [cdkDropListConnectedTo]="[todoList]" class="example-list"
         (cdkDropListDropped)="drop($event)">
            <div class="example-box" *ngFor="let item of done" cdkDrag>{{item}}</div>
        </div>
    </div>

I've modified the code now you will be able to  drag and drop items in the for loop. Hope it answers your question.


问:
db.collection('name').find({something: "1"}) not returning the document
I am trying to retrieve a document from a collection in mongodb.
I am using the following command

db.collection('audioFile').find({format: 1})

But this is not returning me the format document ({format : "wav"})
instead is returning a large json file.

I tried running the same command in mongo shell, and it gives me correct output. But I am trying to do it in JS(node.js) it doesn't work.

How can this be solved?

答:
You can use projection for this.

```<code>db.collection('audioFile').find({}, {projection: {format: 1}})

</code>```

you can put 0 if _id still persists like this

```<code>db.collection('audioFile').find({}, {projection: {_id: 0, format: 1}})

</code>```

Body:
You can use projection for this.

db.collection('audioFile').find({}, {projection: {format: 1}})

you can put 0 if _id still persists like this

db.collection('audioFile').find({}, {projection: {_id: 0, format: 1}})


问:
How to get particular key value of a document using mongoose
Hello I am new in mongoose , express and I want to GET a particular key value from  all the object of a document array and show in response.

I have following data in a document.

```<code>[{
    "admins": {
        "email": "rrg_gg@infomail.com",
        "password": "$2a$10$VNS6RraM5GDh.EU/KJuVle8Qjntog0eSPW3Zup6XDvlDR25Jor/56",
        "firstName": "hjjh",
        "lastName": "ZY",
    },
    "_id": "5cefa5d0531e6b597dceb6d0",
    "companyName": "XYZ",
    "address": "World",
    "contactDetails": "54534454",
    "companyID": "044025",
    "__v": 0
},
{
    "admins": {
        "email": "beans-gg@merok.com",
        "password": "$2a$10M5GDh.EU/KJuVle8Qjntog0eSPWDR25Jor/56",
        "firstName": "gg",
        "lastName": "yu",
    },
    "_id": "5cefa5d0531e6b5678dceb6e8",
    "companyName": "gY",
    "address": "World",
    "contactDetails": "534454",
    "companyID": "984556",
    "__v": 0
}]
</code>```

I want to get  list of all companyID from the document. How can I query this ?

I tried this in route but getting empty response:-

```<code> router.get('/getCid', function(req, res, next){
    Admin.find({}, function(err, admin) {
    res.json(admin.companyID);
  });
});
</code>```

How can I get list of companyIDs ?

答:
you have to map the output

```<code>router.get('/getCid', function(req, res, next){
    Admin.find({}, function(err, data){
    let companyIDS = data.map((admin)=>{return admin.companyID});
    res.json(companyIDS);
  });
});
</code>```

or you can change your query to select only companyID field from collection

```<code> router.get('/getCid', function(req, res, next){
        Admin.find({},'companyID',function(err, data){
        res.json(data);
      });
    });
</code>```

see more here about select specific columns: Mongoose, Select a specific field with find

Body:
Hello I am new in mongoose , express and I want to GET a particular key value from  all the object of a document array and show in response.

I have following data in a document.

[{
    "admins": {
        "email": "rrg_gg@infomail.com",
        "password": "$2a$10$VNS6RraM5GDh.EU/KJuVle8Qjntog0eSPW3Zup6XDvlDR25Jor/56",
        "firstName": "hjjh",
        "lastName": "ZY",
    },
    "_id": "5cefa5d0531e6b597dceb6d0",
    "companyName": "XYZ",
    "address": "World",
    "contactDetails": "54534454",
    "companyID": "044025",
    "__v": 0
},
{
    "admins": {
        "email": "beans-gg@merok.com",
        "password": "$2a$10M5GDh.EU/KJuVle8Qjntog0eSPWDR25Jor/56",
        "firstName": "gg",
        "lastName": "yu",
    },
    "_id": "5cefa5d0531e6b5678dceb6e8",
    "companyName": "gY",
    "address": "World",
    "contactDetails": "534454",
    "companyID": "984556",
    "__v": 0
}]

I want to get  list of all companyID from the document. How can I query this ?

I tried this in route but getting empty response:-

 router.get('/getCid', function(req, res, next){
    Admin.find({}, function(err, admin) {
    res.json(admin.companyID);
  });
});

How can I get list of companyIDs ?

Body:
you have to map the output

router.get('/getCid', function(req, res, next){
    Admin.find({}, function(err, data){
    let companyIDS = data.map((admin)=>{return admin.companyID});
    res.json(companyIDS);
  });
});

or you can change your query to select only companyID field from collection

 router.get('/getCid', function(req, res, next){
        Admin.find({},'companyID',function(err, data){
        res.json(data);
      });
    });

see more here about select specific columns: Mongoose, Select a specific field with find


问:
How to position two absolute positioned div's side by side in the mobile device,?
I wanna position two absolute div's side by side in the mobile device,
but there is a gap between the two divs.

I want to position them side by side if the size of the mobile device changes(flexible)

Thanks In Advance!

#header {
  position: relative;
}

#menu {
  background-color: green;
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
background-color:pink;
  position: absolute;
  overflow: auto;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 10;
  padding: 1.2rem;
  width: 70%;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div id="menu">menu</div>
  <div id="search"></div>
  <div id="tab">tab</div>
</div></code>```

答:
That already aligned, i add just background color and top CSS properties to shows you and I remove padding so you clearly show that.

#header {
  position: relative;
}

#menu {
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
  width: 50vw;
  height: 100vh;
  background-color: skyblue;
}

#tab {
  position: absolute;
  top: 0;
  left:50vw;
  z-index: 10;
  /*padding: 1.2rem;*/
  width: 50vw;
  height: 100vh;
  background-color: teal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div id="menu">menu</div>
  <div id="search"></div>
  <div id="tab">tab</div>
</div></code>```

Body:
I wanna position two absolute div's side by side in the mobile device,
but there is a gap between the two divs.

I want to position them side by side if the size of the mobile device changes(flexible)

Thanks In Advance!

#header {
  position: relative;
}

#menu {
  background-color: green;
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
background-color:pink;
  position: absolute;
  overflow: auto;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 10;
  padding: 1.2rem;
  width: 70%;
  display: block;
}

menu

tab

Body:
That already aligned, i add just background color and top CSS properties to shows you and I remove padding so you clearly show that.

#header {
  position: relative;
}

#menu {
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
  width: 50vw;
  height: 100vh;
  background-color: skyblue;
}

#tab {
  position: absolute;
  top: 0;
  left:50vw;
  z-index: 10;
  /*padding: 1.2rem;*/
  width: 50vw;
  height: 100vh;
  background-color: teal;
}

<div class="header">
  <div id="menu">menu</div>
  <div id="search"></div>
  <div id="tab">tab</div>
</div>


问:
Separation of Runtime and History
I whould like to use separate databases for runtime and history data without implementing a custom HistoryEventHandler. Does someone know how this is possible?

I read the camunda user guides but this did not help much because it only hints the custom implementation way.

Currently, everytime I query history data (about 2mil activity entries) the performance of the system drops as it kind of blocks the runtime, too. I'd like to avoid this without loosing the ability to query historic data.

答: Camunda BPM offers Optimize, which pulls the history data from the Engine to an Elastic Search database. If you are using the Enterprise version, it may be a way to solve it.</p>

Title: Separation of Runtime and History


问:
How to extract duplicate values in each column separately?
I want to extract only values with two or more occurrence in each column separately and write them in separate file with column header.

Example file: (actual csv file is 1.5 Gb, here including summary of it)
First row is the header row of each column

```<code>AO1,BO1,CO1,DO1,EO1,FO1
pep2,red2,ter3,typ3,ghl4,rtf5
ghp2,asd2,ghj3,typ3,ghj3,ert4
typ2,sdf2,rty3,ert4,asd2,sdf2
pep2,xcv2,bnm3,wer3,vbn3,wer2
dfg4,fgh3,uio2,wer3,ghj2,rtf5
dfg6,xcv4,dfg3,ret5,ytu2,rtf5
pep2,xcv4,ert1,dgf2,ert3,fgh3
okj2,xcv4,jkl3,ghr4,cvb3,rtf5
poi2,tyu2,iop3,cvb3,hjk5,rtf5
qwe2,wer2,iop3,typ3,ert3,cvb3
</code>```

I have tried to write code in R and even Python panda but failed to get the result.

Expected outcome:

```<code>AO1 BO1 CO1 DO1 EO1 FO1
pep2    xcv4    iop3    typ3    ert3    rtf5
pep2    xcv4    iop3    typ3    ert3    rtf5
pep2    xcv4        typ3        rtf5
            wer3        rtf5
            wer3        rtf5
</code>```

答:
```<code>df <- data.table::fread('AO1,BO1,CO1,DO1,EO1,FO1
pep2,red2,ter3,typ3,ghl4,rtf5
ghp2,asd2,ghj3,typ3,ghj3,ert4
typ2,sdf2,rty3,ert4,asd2,sdf2
pep2,xcv2,bnm3,wer3,vbn3,wer2
dfg4,fgh3,uio2,wer3,ghj2,rtf5
dfg6,xcv4,dfg3,ret5,ytu2,rtf5
pep2,xcv4,ert1,dgf2,ert3,fgh3
okj2,xcv4,jkl3,ghr4,cvb3,rtf5
poi2,tyu2,iop3,cvb3,hjk5,rtf5
qwe2,wer2,iop3,typ3,ert3,cvb3'
                  , data.table = FALSE)

lapply(df, function (x) x[duplicated(x) | duplicated(x, fromLast = T)])
</code>```

You could write a csv directly in the lapply call as well

Body:
I want to extract only values with two or more occurrence in each column separately and write them in separate file with column header.

Example file: (actual csv file is 1.5 Gb, here including summary of it)
First row is the header row of each column

AO1,BO1,CO1,DO1,EO1,FO1
pep2,red2,ter3,typ3,ghl4,rtf5
ghp2,asd2,ghj3,typ3,ghj3,ert4
typ2,sdf2,rty3,ert4,asd2,sdf2
pep2,xcv2,bnm3,wer3,vbn3,wer2
dfg4,fgh3,uio2,wer3,ghj2,rtf5
dfg6,xcv4,dfg3,ret5,ytu2,rtf5
pep2,xcv4,ert1,dgf2,ert3,fgh3
okj2,xcv4,jkl3,ghr4,cvb3,rtf5
poi2,tyu2,iop3,cvb3,hjk5,rtf5
qwe2,wer2,iop3,typ3,ert3,cvb3

I have tried to write code in R and even Python panda but failed to get the result.

Expected outcome:

AO1 BO1 CO1 DO1 EO1 FO1
pep2    xcv4    iop3    typ3    ert3    rtf5
pep2    xcv4    iop3    typ3    ert3    rtf5
pep2    xcv4        typ3        rtf5
            wer3        rtf5
            wer3        rtf5

Body:
df <- data.table::fread('AO1,BO1,CO1,DO1,EO1,FO1
pep2,red2,ter3,typ3,ghl4,rtf5
ghp2,asd2,ghj3,typ3,ghj3,ert4
typ2,sdf2,rty3,ert4,asd2,sdf2
pep2,xcv2,bnm3,wer3,vbn3,wer2
dfg4,fgh3,uio2,wer3,ghj2,rtf5
dfg6,xcv4,dfg3,ret5,ytu2,rtf5
pep2,xcv4,ert1,dgf2,ert3,fgh3
okj2,xcv4,jkl3,ghr4,cvb3,rtf5
poi2,tyu2,iop3,cvb3,hjk5,rtf5
qwe2,wer2,iop3,typ3,ert3,cvb3'
                  , data.table = FALSE)

lapply(df, function (x) x[duplicated(x) | duplicated(x, fromLast = T)])

You could write a csv directly in the lapply call as well


问:
How to return a number of objects in Javascript?
I have a function which receives an array of person objects. The function should return the number of persons who lives in the city of Syndey. But,  I am getting problem in returning a number of the person who lives in Sydney. What should I do? Anyone can help me, please?

This is the code that I have created:

```<code>function numberOfPeopleInSydney(person) {

   people.forEach(function (arrayItem) {
    if(arrayItem.lives.city==="Sydney")

        return arrayItem.name;
});

}
</code>```

答:
forEach just calls the function you pass it with every element of the array but doesn't use the returned values.

If you want to keep count of the people who pass your condition, you'll have to increment some kind of counter in the if-block, also fix the argument name and add a return in the actual function, like barbsan mentioned:

function tallyPeopleInSyndey(people) {
    var count = 0
    people.forEach(function (arrayItem) {
        if(arrayItem.lives.city==="Syndey")
            count++
    })
    return count
}
```

<p>Personally, I'd just filter <code>people</code> by the condition and get the length of the resulting array:</p>

<pre class="lang-js prettyprint-override"><code>people.filter(function(person) {
    return person.lives.city === "Syndey"
}).length
</code>```

Body:
I have a function which receives an array of person objects. The function should return the number of persons who lives in the city of Syndey. But,  I am getting problem in returning a number of the person who lives in Sydney. What should I do? Anyone can help me, please?

This is the code that I have created:

function numberOfPeopleInSydney(person) {

   people.forEach(function (arrayItem) {
    if(arrayItem.lives.city==="Sydney")

        return arrayItem.name;
});

}

Body:
forEach just calls the function you pass it with every element of the array but doesn't use the returned values.

If you want to keep count of the people who pass your condition, you'll have to increment some kind of counter in the if-block, also fix the argument name and add a return in the actual function, like barbsan mentioned:

function tallyPeopleInSyndey(people) {
    var count = 0
    people.forEach(function (arrayItem) {
        if(arrayItem.lives.city==="Syndey")
            count++
    })
    return count
}

Personally, I'd just filter people by the condition and get the length of the resulting array:

people.filter(function(person) {
    return person.lives.city === "Syndey"
}).length


问:
Date time conversion issue in sql server
I have this query:

```<code>declare @a datetime = '20/05/2019 9:22:07'
</code>```

I want output as:

```<code>2019-05-20 9:22:07
</code>```

I tried :

```<code>SELECT CONVERT(CHAR(10),CONVERT(DATETIME,LEFT(@a,10),103),101);

SELECT convert(varchar, convert(date, @a, 105), 101)
</code>```

But it gives me an error:

```<code>The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
</code>```

How to convert this type of data?

I want to get the standard date time conversion which will work in all languages

答:
Your conversion problem is occurring here:

```<code>declare @a datetime = '20/05/2019 9:22:07';
</code>```

I think you intend this as a string:

```<code>declare @a varchar(255) = '20/05/2019 9:22:07';
</code>```

To get the time with only one digit for the hour, you can use:

```<code>SELECT CONVERT(VARCHAR(10), CONVERT(DATETIME, LEFT(@a, 10), 103), 120) + ' ' + TRIM(RIGHT(@a, 8))
</code>```

More commonly, you would use:

```<code>SELECT CONVERT(VARCHAR(20), CONVERT(DATETIME, @a, 103), 120)
</code>```

This produces:

```<code>2019-05-20 09:22:07
</code>```

Body:
I have this query:

declare @a datetime = '20/05/2019 9:22:07'

I want output as:

2019-05-20 9:22:07

I tried :

SELECT CONVERT(CHAR(10),CONVERT(DATETIME,LEFT(@a,10),103),101);

SELECT convert(varchar, convert(date, @a, 105), 101)

But it gives me an error:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

How to convert this type of data?

I want to get the standard date time conversion which will work in all languages

Body:
Your conversion problem is occurring here:

declare @a datetime = '20/05/2019 9:22:07';

I think you intend this as a string:

declare @a varchar(255) = '20/05/2019 9:22:07';

To get the time with only one digit for the hour, you can use:

SELECT CONVERT(VARCHAR(10), CONVERT(DATETIME, LEFT(@a, 10), 103), 120) + ' ' + TRIM(RIGHT(@a, 8))

More commonly, you would use:

SELECT CONVERT(VARCHAR(20), CONVERT(DATETIME, @a, 103), 120)

This produces:

2019-05-20 09:22:07


问:
Cannot resolve method 'setAllowNewEmailAccounts(boolean)'
```<code>AuthUI.getInstance()
      .createSignInIntentBuilder()
      .setAllowNewEmailAccounts(true)
      .build(), LOGIN_PERMISSION
</code>```

答:
To kick off the FirebaseUI sign in flow, create a sign in intent with your preferred sign-in methods:
Insted of using .setAllowNewEmailAcounts(true) used .setAvailableProviders(providers) and declare the provider Array before create method like this

```<code>        List<AuthUI.IdpConfig> providers = Arrays.asList(
        new AuthUI.IdpConfig.EmailBuilder().build(),
        new AuthUI.IdpConfig.PhoneBuilder().build(),
        new AuthUI.IdpConfig.GoogleBuilder().build(),
        new AuthUI.IdpConfig.FacebookBuilder().build(),
        new AuthUI.IdpConfig.TwitterBuilder().build());
</code>```

And Then within create method used startActivityForResult Like This

```<code>           startActivityForResult(
            AuthUI.getInstance()
                    .createSignInIntentBuilder()
                    .setAvailableProviders(providers)
                    .build(),
            PER_LOGIN);
</code>```

I hope this will solve your problem

Body:
To kick off the FirebaseUI sign in flow, create a sign in intent with your preferred sign-in methods:
Insted of using .setAllowNewEmailAcounts(true) used .setAvailableProviders(providers) and declare the provider Array before create method like this

        List<AuthUI.IdpConfig> providers = Arrays.asList(
        new AuthUI.IdpConfig.EmailBuilder().build(),
        new AuthUI.IdpConfig.PhoneBuilder().build(),
        new AuthUI.IdpConfig.GoogleBuilder().build(),
        new AuthUI.IdpConfig.FacebookBuilder().build(),
        new AuthUI.IdpConfig.TwitterBuilder().build());

And Then within create method used startActivityForResult Like This

           startActivityForResult(
            AuthUI.getInstance()
                    .createSignInIntentBuilder()
                    .setAvailableProviders(providers)
                    .build(),
            PER_LOGIN);

I hope this will solve your problem


问:
error: Unable to load contents of file list: '/Target Support Files/Pods-xx/Pods-xx-frameworks-Debug-input-files.xcfilelist' (in target 'xx')
XCode Version 10.2.1

error: Unable to load contents of file list: '/Target Support Files/Pods-SMarket/Pods-SMarket-frameworks-Debug-input-files.xcfilelist' (in target 'SMarket')

error: Unable to load contents of file list: '/Target Support Files/Pods-SMarket/Pods-SMarket-frameworks-Debug-output-files.xcfilelist' (in target 'SMarket')

error: Unable to load contents of file list: '/Target Support Files/Pods-SMarket/Pods-SMarket-resources-Debug-input-files.xcfilelist' (in target 'SMarket')

error: Unable to load contents of file list: '/Target Support Files/Pods-SMarket/Pods-SMarket-resources-Debug-output-files.xcfilelist' (in target 'SMarket')

I tried this solution, not working.

I tried to clean, rebuild the project, still failed.

No idea which part generates these errors, please comment if I need to show details of specific files.

My Target -> Build Phases:

[CP] Embed Pods Frameworks

[CP] Copy Pods Resources

答:
```<code>pod deintegrate
</code>```

then

```<code>pod update
</code>```

Body:
pod deintegrate

then

pod update


问:
Break iteration (each) in Svelte?
Is it possible to break iteration in Svelte or limit like in angular (ng-repeat="items in item | limitTo:4")?
For example:

```<code>{#each items as item, i}
  ...
  {#if i > 4}
    {:break}  <--- break here
  {/if}
  ...
{/each}
</code>```

答:
There is no {:break} block, but you could slice out the first 4 elements in the array before you iterate over it.

```<code>{#each items.slice(0, 4) as item, i} ... {/each}
</code>```

Title: Break iteration (each) in Svelte?

Body:
Is it possible to break iteration in Svelte or limit like in angular (ng-repeat="items in item | limitTo:4")?
For example:

{#each items as item, i}
  ...
  {#if i > 4}
    {:break}  <--- break here
  {/if}
  ...
{/each}

Body:
There is no {:break} block, but you could slice out the first 4 elements in the array before you iterate over it.

{#each items.slice(0, 4) as item, i} ... {/each}


问:
R exact selection based on %in%
I am having some trouble doing a simple operation.

What I want is to simply select the rows, grouped by id, that have all of the values (-1, -2, -3, -4), and apply a tag based on this condition.

```<code>   id time
1   1   -4
2   1   -3
3   1   -2
4   1   -1
5   2   -1
6   2   -2
7   3   -1
8   3   -3
9   4   -1
10  4   -2
11  4   -3
12  4   -4
</code>```

Intuitively I was going for

```<code>rb[rb$time %in% c(-1, -2, -3, -4), ]
</code>```

However, when I do that, all id are selected. So, the %in% operator uses the OR | operator.

So, I thought I could do this then, to use the AND & operator

```<code>rb[rb$time == -1 &
 rb$time == -2 &
 rb$time == -3 &
 rb$time == -4, ]
</code>```

But it does not work.

Any clue how I could tag or subset these id, such that

```<code>   id time tag
1   1   -4   1
2   1   -3   1
3   1   -2   1
4   1   -1   1
5   2   -1   0
6   2   -2   0
7   3   -1   0
8   3   -3   0
9   4   -1   1
10  4   -2   1
11  4   -3   1
12  4   -4   1
</code>```

答:
To add more options, here is a data.table one, which should have significant performance benefits:

```<code>dt <- as.data.table(df)[, tag := all(-1:-4 %in% time), by = id]
</code>```

Result:

```<code>dt
#     id time   tag
#  1:  1   -4  TRUE
#  2:  1   -3  TRUE
#  3:  1   -2  TRUE
#  4:  1   -1  TRUE
#  5:  2   -1 FALSE
#  6:  2   -2 FALSE
#  7:  2   -1 FALSE
#  8:  2   -3 FALSE
#  9:  3   -1  TRUE
# 10:  3   -2  TRUE
# 11:  3   -3  TRUE
# 12:  3   -4  TRUE
</code>```

Title: R exact selection based on %in%

Body:
I am having some trouble doing a simple operation.

What I want is to simply select the rows, grouped by id, that have all of the values (-1, -2, -3, -4), and apply a tag based on this condition.

   id time
1   1   -4
2   1   -3
3   1   -2
4   1   -1
5   2   -1
6   2   -2
7   3   -1
8   3   -3
9   4   -1
10  4   -2
11  4   -3
12  4   -4

Intuitively I was going for

rb[rb$time %in% c(-1, -2, -3, -4), ]

However, when I do that, all id are selected. So, the %in% operator uses the OR | operator.

So, I thought I could do this then, to use the AND & operator

rb[rb$time == -1 &
 rb$time == -2 &
 rb$time == -3 &
 rb$time == -4, ]

But it does not work.

Any clue how I could tag or subset these id, such that

   id time tag
1   1   -4   1
2   1   -3   1
3   1   -2   1
4   1   -1   1
5   2   -1   0
6   2   -2   0
7   3   -1   0
8   3   -3   0
9   4   -1   1
10  4   -2   1
11  4   -3   1
12  4   -4   1

Body:
To add more options, here is a data.table one, which should have significant performance benefits:

dt <- as.data.table(df)[, tag := all(-1:-4 %in% time), by = id]

Result:

dt
#     id time   tag
#  1:  1   -4  TRUE
#  2:  1   -3  TRUE
#  3:  1   -2  TRUE
#  4:  1   -1  TRUE
#  5:  2   -1 FALSE
#  6:  2   -2 FALSE
#  7:  2   -1 FALSE
#  8:  2   -3 FALSE
#  9:  3   -1  TRUE
# 10:  3   -2  TRUE
# 11:  3   -3  TRUE
# 12:  3   -4  TRUE


问:
Issues Running JSON File in Python Environment and Setting up NLP Project
I am having issues figuring out how to complete a beginner NLP chatbot. I created a JSON file within my Python virtual environment, though it seems I am unable to confirm if the file is being utilized properly. Please help me figure out how to import the JSON file and well as determine which tools I can utilize to best complete my project.

The tutorial I am following instructs me to do the following in the Jupyter notes:

How to import our chat-bot intents file-

```<code>import json
with open('intents.json') as json_data:
    intents = json.load(json_data)
</code>```

Per my Python interpreter:

```<code>Python 2.7.10 (default, Aug 17 2018, 19:45:58)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> with open('chatbotIntents.json') as json_data:
...     intents = json.load(json_data)
...
</code>```

I believe I would be performing this action utilizing the Python interpreter, correct? When I have done this, the interpreter seems to be anticipating more code to follow and I seem receive no feedback as to whether the request is completed.

The tutorial continues by demonstrating python code in the Jupyter notebook, but I've only used the Python interpreter for single lines of code thusfar. To organize the documents, words and classification classes in my NLP project, would you all recommend running my code in Jupyter on my mac to run the code as I follow along the tutorial? Are there any other alternatives you all would suggest?

Link to tutorial and notebooks: https://chatbotsmagazine.com/contextual-chat-bots-with-tensorflow-4391749d0077

答:
I believe I would be performing this action utilizing the Python interpreter, correct?

Yes.

When I have done this, the interpreter seems to be anticipating more code to follow and I seem receive no feedback as to whether the request is completed.

This is because in programming silence is often the Ok/Yes answer. The interpreter didn't raise an error hence everything is ok and you can continue,

would you all recommend

That part of your question is not suitable for StackOverflow. See https://stackoverflow.com/help/dont-ask and https://stackoverflow.com/help/asking

Body:
I am having issues figuring out how to complete a beginner NLP chatbot. I created a JSON file within my Python virtual environment, though it seems I am unable to confirm if the file is being utilized properly. Please help me figure out how to import the JSON file and well as determine which tools I can utilize to best complete my project.

The tutorial I am following instructs me to do the following in the Jupyter notes:

How to import our chat-bot intents file-

import json
with open('intents.json') as json_data:
    intents = json.load(json_data)

Per my Python interpreter:

Python 2.7.10 (default, Aug 17 2018, 19:45:58)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> with open('chatbotIntents.json') as json_data:
...     intents = json.load(json_data)
...

I believe I would be performing this action utilizing the Python interpreter, correct? When I have done this, the interpreter seems to be anticipating more code to follow and I seem receive no feedback as to whether the request is completed.

The tutorial continues by demonstrating python code in the Jupyter notebook, but I've only used the Python interpreter for single lines of code thusfar. To organize the documents, words and classification classes in my NLP project, would you all recommend running my code in Jupyter on my mac to run the code as I follow along the tutorial? Are there any other alternatives you all would suggest?

Link to tutorial and notebooks: https://chatbotsmagazine.com/contextual-chat-bots-with-tensorflow-4391749d0077


问:
VBA: cannot work with PivotTable (error 1004)
Okay, I really am frustrated right now. For the past hour or so I have been trying to get data from a simple Pivot. I cannot get it to work.

My really simple code:

```<code>Sub getXXFromPivot()

     Dim test As PivotTable

     Set Sheet1 = ActiveWorkbook.Sheets("Sheet5")
     Set test = Sheet1.PivotTables("PivotTable1")
     Set test2 = test.ClearAllFilters

     MsgBox test2

End Sub
</code>```

I am trying to use the "GetPivotData" method to get data, but no matter what I use after test. (ClearAllFilters was just a test) I always end up with error 1004. What is my mistake here? I cannot figure it out.
"PivotTable1" definitely exists. I can MsgBox test and get "PivotTable1" back.

答:
Adding to my comment, please see bellow an adaptation of your code:

Option Explicit 'Is recommended to use this always
Sub getXXFromPivot()

    Dim sht As Worksheet
    Dim pTbl As PivotTable

    Set sht = ActiveWorkbook.Sheets("Sheet5")
    Set pTbl = sht.PivotTables("PivotTable1")
    pTbl.ClearAllFilters

    MsgBox pTbl.Name

End Sub
```

As a pretty good source on how to work with pivot tables, see The VBA Guide To Excel Pivot Tables

Body:
Okay, I really am frustrated right now. For the past hour or so I have been trying to get data from a simple Pivot. I cannot get it to work.

My really simple code:

Sub getXXFromPivot()

     Dim test As PivotTable

     Set Sheet1 = ActiveWorkbook.Sheets("Sheet5")
     Set test = Sheet1.PivotTables("PivotTable1")
     Set test2 = test.ClearAllFilters

     MsgBox test2

End Sub

I am trying to use the "GetPivotData" method to get data, but no matter what I use after test. (ClearAllFilters was just a test) I always end up with error 1004. What is my mistake here? I cannot figure it out.
"PivotTable1" definitely exists. I can MsgBox test and get "PivotTable1" back.

Body:
Adding to my comment, please see bellow an adaptation of your code:

Option Explicit 'Is recommended to use this always
Sub getXXFromPivot()

    Dim sht As Worksheet
    Dim pTbl As PivotTable

    Set sht = ActiveWorkbook.Sheets("Sheet5")
    Set pTbl = sht.PivotTables("PivotTable1")
    pTbl.ClearAllFilters

    MsgBox pTbl.Name

End Sub

As a pretty good source on how to work with pivot tables, see The VBA Guide To Excel Pivot Tables


问:
Trying to read multiple lines from txt file separated with :, but I'm getting imbRecoverableException caught from worker -> parseNext
As I'm new to IBM MQ and IIB I'm trying to experiment around with online tutorials. At the moment I'm trying to make a simple app that reads several lines in txt file separated by colon and writes them into XML file. Currently I'm stuck at reading multiple lines from file. I know how to make it work with only one line, but can't with more than one. I do know that there should be a parent-child relationship  between two complex types but can't configure them properly. Also im using RFHUtil to send message file into queue.

Since I can't find much googling it, I hope someone with right knowledge could help around.

Don't have any code, but got my message definition picture: http://prnt.sc/nv9npr

Here is the error I'm getting: http://prnt.sc/nv9nyi

答:
So two things I can see in your current screen shots.

In the first screenshot I can see \r\n i.e. CRLF which indicates that your separator needs to either be CRLF or your model needs to deal with the CRLF.

In the second you've got a partially parsed message. Try setting the Advanced Parser options on your Input node to ParseComplete things will still blow up but you should get some better diagnostic information in the ExceptionList.

Looks like you are trying use the MRM parser which has been replaced by the DFDL parser. I suggest you find some tutorials on the DFDL parser, it's much more efficient. Also there is support built into the Toolkit which will let you debug the Message Model you create Testing a DFDL schema by parsing test input data


问:
Replace all occurrences of a string in JSON object regardless of key
I have a JSON object in Python created through requests built in .json() function.

Here is a simplified sample of what I'm doing:

```<code>data = session.get(url)

obj = data.json()

s3object = s3.Object(s3_bucket, output_file)
s3object.put(Body=(bytes(json.dumps(obj).encode('UTF-8'))))
</code>```

Example obj:

```<code>{'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': null, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}
</code>```

I need to replace any occurrence of the string "N/A" with "Not Applicable" anywhere it appears regardless of its key or location before I upload the JSON to S3. I cannot use local disk writes hence the reason this is done this way.

Is this possible?

My original plan was to turn it to a string and just replace before turning back, is this inefficient?

Thanks,

答:
I guess the Object you've pasted here must be of dict type, you can check it as if "type(json_object) is class dict". With that assumption youcan do it as:-

```<code>keys = json_object.keys()
for i in keys:
    if json_object[i]=="N/A":
        json_object[i]="Not Available"
</code>```

Hope it helps!

Body:
I have a JSON object in Python created through requests built in .json() function.

Here is a simplified sample of what I'm doing:

data = session.get(url)

obj = data.json()

s3object = s3.Object(s3_bucket, output_file)
s3object.put(Body=(bytes(json.dumps(obj).encode('UTF-8'))))

Example obj:

{'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': null, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}

I need to replace any occurrence of the string "N/A" with "Not Applicable" anywhere it appears regardless of its key or location before I upload the JSON to S3. I cannot use local disk writes hence the reason this is done this way.

Is this possible?

My original plan was to turn it to a string and just replace before turning back, is this inefficient?

Thanks,

Body:
I guess the Object you've pasted here must be of dict type, you can check it as if "type(json_object) is class dict". With that assumption youcan do it as:-

keys = json_object.keys()
for i in keys:
    if json_object[i]=="N/A":
        json_object[i]="Not Available"

Hope it helps!


问:
Error: read ECONNRESET when inserting data into table
I followed this tutorial (Tutorial Insert multiple rows at a time) to insert multiple rows data into a MySQL table (chapter 'Insert multiple rows at a time').

I did the same with my code but I got an ECONNRESET error instead of my connection if good enough with the database.

The error details below:

```<code>{ Error: read ECONNRESET
    at _errnoException (util.js:1022:11)
    at TCP.onread (net.js:628:25)
    --------------------
    at Protocol._enqueue (C:\Users\frederic.fayet\Desktop\DEV\NodeJS\TER_V1 - Reprise après pause\node_modules\mysql\lib\protocol\Protocol.js:144:48)
    at Connection.query (C:\Users\frederic.fayet\Desktop\DEV\NodeJS\TER_V1 - Reprise après pause\node_modules\mysql\lib\Connection.js:200:25)
    at C:\Users\frederic.fayet\Desktop\DEV\NodeJS\TER_V1 - Reprise après pause\app.js:340:24
    at handlePromises (C:\Users\frederic.fayet\Desktop\DEV\NodeJS\TER_V1 - Reprise après pause\app.js:242:9)
    at promise.then (C:\Users\frederic.fayet\Desktop\DEV\NodeJS\TER_V1 - Reprise après pause\app.js:251:20)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
  code: 'ECONNRESET',
  errno: 'ECONNRESET',
  syscall: 'read',
  fatal: true }
</code>```

My code is below for querying the database:

```<code>db.query(sqlSchedules, [sqlDataSchedules], function (err, result) {
                        if (err) {
                            console.log(err);
                            return; //throw err;
                        }
                        //Get the number of inserted lines:
                        nbLinesSchedulesInserted = result.affectedRows;
                        console.log("Nombre d'éléments insérés : " + result.affectedRows);
                    });
</code>```

And the database connection is:

```<code>db.connect(function(err) {
        if (err) console.error('Error occured during the DB connection.');
        console.log("DB connection: OK");
    });
</code>```

The sqlDataSchedules is an array that looks like:

```<code>[ [ '848633',
    'Amiens',
    '162700',
    '162700',
    '20190509',
    '20190702',
    2019-05-31T07:27:09.710Z ],
  [ '848633',
    'Villers-Bretonneux',
    '163800',
    '163900',
    '20190509',
    '20190702',
    2019-05-31T07:27:09.710Z ],
  [ '849401',
    'St Quentin',
    '074500',
    '074500',
    '20190527',
    '20190528',
    2019-05-31T07:27:09.711Z ],
  ... 141377 more items ]
</code>```

And the SQL request is:

```<code>INSERT INTO schedules (trainNumber, stopName, baseArrivalTime, baseDepartureTime, beginDate, endDate, updatedOn) VALUES ?
</code>```

答:
I finally found a solution using for loop and async function:</p>

```<code>async function loopOverRequests(data, sqlRequest, tableName) {
    let nbRequests = 0;
    for (var i = 0; i<data.length; i++) {
        nbRequests = nbRequests + await makeTheRequest(data[i], sqlRequest);
    }
    console.log(nbRequests + ' imported in the table `'+ tableName + '`.');
    return new Promise((resolve, reject) => {
        resolve(nbRequests);
    });
}

function makeTheRequest(el, sqlRequest) {
    return new Promise((resolve, reject) => {
        db.query(sqlRequest, el, function (err, result) {
            if (err) {
                console.log(err);
                reject(err); //throw err;
            } else {
                resolve(result.affectedRows);
            }
        });
    });
}
</code>```

Body:
I followed this tutorial (Tutorial Insert multiple rows at a time) to insert multiple rows data into a MySQL table (chapter 'Insert multiple rows at a time').

I did the same with my code but I got an ECONNRESET error instead of my connection if good enough with the database.

The error details below:

{ Error: read ECONNRESET
    at _errnoException (util.js:1022:11)
    at TCP.onread (net.js:628:25)
    --------------------
    at Protocol._enqueue (C:\Users\frederic.fayet\Desktop\DEV\NodeJS\TER_V1 - Reprise après pause\node_modules\mysql\lib\protocol\Protocol.js:144:48)
    at Connection.query (C:\Users\frederic.fayet\Desktop\DEV\NodeJS\TER_V1 - Reprise après pause\node_modules\mysql\lib\Connection.js:200:25)
    at C:\Users\frederic.fayet\Desktop\DEV\NodeJS\TER_V1 - Reprise après pause\app.js:340:24
    at handlePromises (C:\Users\frederic.fayet\Desktop\DEV\NodeJS\TER_V1 - Reprise après pause\app.js:242:9)
    at promise.then (C:\Users\frederic.fayet\Desktop\DEV\NodeJS\TER_V1 - Reprise après pause\app.js:251:20)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
  code: 'ECONNRESET',
  errno: 'ECONNRESET',
  syscall: 'read',
  fatal: true }

My code is below for querying the database:

db.query(sqlSchedules, [sqlDataSchedules], function (err, result) {
                        if (err) {
                            console.log(err);
                            return; //throw err;
                        }
                        //Get the number of inserted lines:
                        nbLinesSchedulesInserted = result.affectedRows;
                        console.log("Nombre d'éléments insérés : " + result.affectedRows);
                    });

And the database connection is:

db.connect(function(err) {
        if (err) console.error('Error occured during the DB connection.');
        console.log("DB connection: OK");
    });

The sqlDataSchedules is an array that looks like:

[ [ '848633',
    'Amiens',
    '162700',
    '162700',
    '20190509',
    '20190702',
    2019-05-31T07:27:09.710Z ],
  [ '848633',
    'Villers-Bretonneux',
    '163800',
    '163900',
    '20190509',
    '20190702',
    2019-05-31T07:27:09.710Z ],
  [ '849401',
    'St Quentin',
    '074500',
    '074500',
    '20190527',
    '20190528',
    2019-05-31T07:27:09.711Z ],
  ... 141377 more items ]

And the SQL request is:

INSERT INTO schedules (trainNumber, stopName, baseArrivalTime, baseDepartureTime, beginDate, endDate, updatedOn) VALUES ?

Body:
I finally found a solution using for loop and async function:

async function loopOverRequests(data, sqlRequest, tableName) {
    let nbRequests = 0;
    for (var i = 0; i<data.length; i++) {
        nbRequests = nbRequests + await makeTheRequest(data[i], sqlRequest);
    }
    console.log(nbRequests + ' imported in the table `'+ tableName + '`.');
    return new Promise((resolve, reject) => {
        resolve(nbRequests);
    });
}

function makeTheRequest(el, sqlRequest) {
    return new Promise((resolve, reject) => {
        db.query(sqlRequest, el, function (err, result) {
            if (err) {
                console.log(err);
                reject(err); //throw err;
            } else {
                resolve(result.affectedRows);
            }
        });
    });
}


答:
As mentioned in the comments, obj is a dict. One way to replace N/A with Not Applicable regardless of location is to convert it to a string, use string.replace and convert it back to dict for further processing

```<code>import json

#Original dict with N/A
obj = {'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': None, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}

#Convert to string and replace
obj_str = json.dumps(obj).replace('N/A', 'Not Applicable')

#Get obj back with replacement
obj = json.loads(obj_str)
</code>```

Title: Replace all occurrences of a string in JSON object regardless of key

Body:
As mentioned in the comments, obj is a dict. One way to replace N/A with Not Applicable regardless of location is to convert it to a string, use string.replace and convert it back to dict for further processing

import json

#Original dict with N/A
obj = {'id': 'fab779b7-2586-4895-9f3b-c9518f34e028', 'project_id': 'a1a73e68-9943-4584-9d59-cc84a0d3e92b', 'created_at': '2017-10-23 02:57:03 -0700', 'sections': [{'section_name': '', 'items': [{'id': 'ffadc652-dd36-4b9f-817c-6539a4b462ab', 'created_at': '2017-10-23 03:36:13 -0700', 'updated_at': '2017-10-23 03:38:32 -0700', 'created_by': 'paul', 'question_text': 'Drawing Ref(s)', 'spec_ref': '', 'display_number': None, 'response': '', 'comment': 'see attached mh309', 'position': 1, 'is_conforming': 'N/A', 'display_type': 'text'}]}]}

#Convert to string and replace
obj_str = json.dumps(obj).replace('N/A', 'Not Applicable')

#Get obj back with replacement
obj = json.loads(obj_str)


问:
reading a file in hdfs from pyspark
I'm trying to read a file in my hdfs. Here's a showing of my hadoop file structure.

```<code>hduser@GVM:/usr/local/spark/bin$ hadoop fs -ls -R /
drwxr-xr-x   - hduser supergroup          0 2016-03-06 17:28 /inputFiles
drwxr-xr-x   - hduser supergroup          0 2016-03-06 17:31 /inputFiles/CountOfMonteCristo
-rw-r--r--   1 hduser supergroup    2685300 2016-03-06 17:31 /inputFiles/CountOfMonteCristo/BookText.txt
</code>```

Here's my pyspark code:

```<code>from pyspark import SparkContext, SparkConf

conf = SparkConf().setAppName("myFirstApp").setMaster("local")
sc = SparkContext(conf=conf)

textFile = sc.textFile("hdfs://inputFiles/CountOfMonteCristo/BookText.txt")
textFile.first()
</code>```

The error I get is:

```<code>Py4JJavaError: An error occurred while calling o64.partitions.
: java.lang.IllegalArgumentException: java.net.UnknownHostException: inputFiles
</code>```

Is this because I'm setting my sparkContext incorrectly? I'm running this in a ubuntu 14.04 virtual machine through virtual box.

I'm not sure what I'm doing wrong here....

答:
First, you need to run

```<code>export PYSPARK_PYTHON=python3.4 #what so ever is your python version
</code>```

code

```<code>from pyspark.sql import SparkSession
from pyspark import SparkConf, SparkContext

spark = SparkSession.builder.appName("HDFS").getOrCreate()
sparkcont = SparkContext.getOrCreate(SparkConf().setAppName("HDFS"))
logs = sparkcont.setLogLevel("ERROR")

data = [('First', 1), ('Second', 2), ('Third', 3), ('Fourth', 4), ('Fifth', 5)]
df = spark.createDataFrame(data)

df.write.csv("hdfs:///mnt/data/")
print("Data Written")
</code>```

To execute the code

```<code>spark-submit --master yarn --deploy-mode client <py file>
</code>```

ContentLicense: CC BY-SA 3.0

Title: reading a file in hdfs from pyspark

Body:
I'm trying to read a file in my hdfs. Here's a showing of my hadoop file structure.

hduser@GVM:/usr/local/spark/bin$ hadoop fs -ls -R /
drwxr-xr-x   - hduser supergroup          0 2016-03-06 17:28 /inputFiles
drwxr-xr-x   - hduser supergroup          0 2016-03-06 17:31 /inputFiles/CountOfMonteCristo
-rw-r--r--   1 hduser supergroup    2685300 2016-03-06 17:31 /inputFiles/CountOfMonteCristo/BookText.txt

Here's my pyspark code:

from pyspark import SparkContext, SparkConf

conf = SparkConf().setAppName("myFirstApp").setMaster("local")
sc = SparkContext(conf=conf)

textFile = sc.textFile("hdfs://inputFiles/CountOfMonteCristo/BookText.txt")
textFile.first()

The error I get is:

Py4JJavaError: An error occurred while calling o64.partitions.
: java.lang.IllegalArgumentException: java.net.UnknownHostException: inputFiles

Is this because I'm setting my sparkContext incorrectly? I'm running this in a ubuntu 14.04 virtual machine through virtual box.

I'm not sure what I'm doing wrong here....

Body:
First, you need to run

export PYSPARK_PYTHON=python3.4 #what so ever is your python version

code

from pyspark.sql import SparkSession
from pyspark import SparkConf, SparkContext

spark = SparkSession.builder.appName("HDFS").getOrCreate()
sparkcont = SparkContext.getOrCreate(SparkConf().setAppName("HDFS"))
logs = sparkcont.setLogLevel("ERROR")

data = [('First', 1), ('Second', 2), ('Third', 3), ('Fourth', 4), ('Fifth', 5)]
df = spark.createDataFrame(data)

df.write.csv("hdfs:///mnt/data/")
print("Data Written")

To execute the code

spark-submit --master yarn --deploy-mode client <py file>


问:
How can I edit a pdf on the web (mysql database and php). Pdf should be edited online and the client is not required to have a pdf editor
I need an online pdf editor so that when I pull the pdf name using php It automatically opens the pdf in the editor and the user can edit the pdf. By edit I mean to chage text, images,etc.... and I want to know how to link php and mysql to it so that when clicking on the pdf name in the database, the pdf is automatically opened via the online editor.
Any recommendation and guides on how to do this ?</p>

答:
I don't know your full requirement here,

but my suggestion is to store HTML versions of the same, this way its gives the flexibility to edit,

also provide a WYSIWYG editor to edit,

and at the time of download, use an HTML to PDF generator.

Also note, you can store the HTML content to DB, or to files, uploads like Image can also be stored into DB (as binary), S3 or somewhere, but decide all that according to your requirement. ~Happy Coding~


问:
splitting long long
How could one "split" i.e. long long type, so that first part of it is in var of type long and second part is also in var of type long.

```<code>long long long_type = 0xaaaabbbbccccdddd;
</code>```

and in first int I would like to have first half(doesn't matter from what side) of the long_type var and in second var int second half.

答:
Your question is ambiguous. It depends on what you mean by "split". You can split the value representation of your original long long or you can split the object representation of your long long.

If you want to split the value representation, then your question is even more ambiguous due to the fact that your original value is signed. How do you intend to split a signed value? What kind of result do you expect? Signed? Unsigned? High-order part signed, low-order part unsigned? Or something else?

For an unsigned value it would look as follows (assuming that the recipient type long has the right size for your purposes)

```<code>unsigned long long long_type = ...;

unsigned long hi = long_type / ULONG_MAX;
unsigned long lo = long_type;
</code>```

If you want to split the object representation, the proper way to do it would be to use memcpy (in this case the signedness of the original value is not of importance)

```<code>long long long_type = ...;

unsigned long hi, lo;

memcpy(&lo, &long_type, sizeof lo);
memcpy(&hi, (char *) &long_type + sizeof lo, sizeof hi);
</code>```

In this case, of course, which part is actually the low-order one and which part is the high-order one will depend on the platform.

Title: splitting long long

Body:
How could one "split" i.e. long long type, so that first part of it is in var of type long and second part is also in var of type long.

long long long_type = 0xaaaabbbbccccdddd;

and in first int I would like to have first half(doesn't matter from what side) of the long_type var and in second var int second half.

Body:
Your question is ambiguous. It depends on what you mean by "split". You can split the value representation of your original long long or you can split the object representation of your long long.

If you want to split the value representation, then your question is even more ambiguous due to the fact that your original value is signed. How do you intend to split a signed value? What kind of result do you expect? Signed? Unsigned? High-order part signed, low-order part unsigned? Or something else?

For an unsigned value it would look as follows (assuming that the recipient type long has the right size for your purposes)

unsigned long long long_type = ...;

unsigned long hi = long_type / ULONG_MAX;
unsigned long lo = long_type;

If you want to split the object representation, the proper way to do it would be to use memcpy (in this case the signedness of the original value is not of importance)

long long long_type = ...;

unsigned long hi, lo;

memcpy(&lo, &long_type, sizeof lo);
memcpy(&hi, (char *) &long_type + sizeof lo, sizeof hi);

In this case, of course, which part is actually the low-order one and which part is the high-order one will depend on the platform.


问:
Known differences in boost random output from 1.58 to 1.67?
I am working with some legacy code I didn't write that generates random data.  The output has changed after it was updated to 1.67 boost from 1.58. Normally reproducible output happens by a fixed seed key. But they are now different between new and old versions.

The boost random distributions used include uniform_int, uniform_real, exponential_distribution and normal_distribution. Does anyone have specific knowledge that one of those or more is now different wrt the boost versions I've mentioned?

I may have to write a simple test prog to ascertain this for sure.

答: At least the normal and exponential distributions where changed to use (an improved version) of the Ziggurat method in July 2016, c.f. https://github.com/boostorg/random/commit/c7d1b4f3516098b3e2fc8f8531d716881ab5834e. This particular change first appeared in version 1.62 (released October 2016). I did not check further back in time.</p>


问:
Firebase Complex Queries In Flutter
I am working with a collection in Firebase that stores information about products. Previously, I was just fetching all of the products and then applying filters to them on the client side. I was told that I need to apply these filters through the query in order to reduce the number of reads that Firebase will need since there will be a very large number of products.

I have tried chaining together multiple .where() statements, but this does not product the effect that I need, I read in another post that multiple .orderBy() statements will break the query, but in order to check the other fields such as price the output tells me I need to orderBy() price first. Any number of these filters could be applied, or none of them could depending on settings. I am using the lastVisible variable at the bottom for a .startAfter in a separate function for getting more products. Is there any way to product the kind of queries I want to make this way? I would also like to know if it is possible to do something like .where('field', isEqualTo: x or y or z).

    Query productQuery = Firestore.instance.collection('Products');

    if(selectedCategories != null)
    for(int i = 0; i < selectedCategories.length; i++)
      productQuery = productQuery.where('category', isEqualTo: selectedCategories[i]);

    if(minPrice > 0 && maxPrice > 0)
    {
      productQuery = productQuery.orderBy('price').where('price', isGreaterThanOrEqualTo: minPrice).where('price', isLessThanOrEqualTo: minPrice);
    }
    else if(minPrice > 0)
      productQuery = productQuery.orderBy('price').where('price', isGreaterThanOrEqualTo: minPrice);

    else if(maxPrice > 0)
      productQuery = productQuery.orderBy('price').where('price', isLessThanOrEqualTo: maxPrice);

    if(!showUnavailableItems)
      productQuery = productQuery.where('status', isEqualTo: 'available');

    switch(selectedCondition)
    {
      case 'Acceptable':
        productQuery = productQuery
                      .where('condition', isEqualTo: 'Acceptable')
                      .where('condition', isEqualTo: 'Good')
                      .where('condition', isEqualTo: 'Very Good');
        break;
      case 'Good':
        productQuery = productQuery
                      .where('condition', isEqualTo: 'Acceptable')
                      .where('condition', isEqualTo: 'Good');
        break;
      case 'Very Good':
        productQuery = productQuery
                      .where('condition', isEqualTo: 'Acceptable');

        break;
      default:
        break;
    }

    productQuery = productQuery.orderBy('id');

    QuerySnapshot myQuery = await productQuery.getDocuments();
    List<DocumentSnapshot> productSnaps = myQuery.documents;
    print("INITIAL PRODUCT SNAPS LENGTH: ${myQuery.documents.length}");

    if(productSnaps.length != 0)
      lastVisible = productSnaps[productSnaps.length -1].data['id'];
```

When the condition or category filters are applied, the result is always 0 documents. Using the minPrice and maxPrice filters separately works, but together also returns 0 products. I have not gotten any errors besides ones for creating the indexes in Firebase.

答:
I was told that I need to apply these filters through the query in order to reduce the number of reads

That's correct since in Firestore everything is about the number of reads and writes.

I have tried chaining together multiple .where() statements, but this does not produce the effect that I need

Why do you say that? I have used many times the where() function to filter data within a Cloud Firestore database and never failed.

I read in another post that multiple .orderBy() statements will break the query

Is not true! Please check my answer from the following post:

How to implement multiple order by in android firestore based on different if conditions?

Please also remember that if you are using multiple orderBy() method calls, you get a warning similar to this:

Status{code=FAILED_PRECONDITION, description=The query requires an index.

So don't forget to create an index in your Firebase console.

Is there any way to product the kind of queries I want to make this way?

Yes, you can use all options you already mentioned.

I would also like to know if it is possible to do something like .where('field', isEqualTo: x or y or z).

No, it is not possible but there is a workaround that can help you achieve the same thing. For that, please see my answer from the following post:

How to access array index of Cloud Firestore using query in Flutter?

So instead of using an array, use a map and chain multiple where() calls.

Title: Firebase Complex Queries In Flutter

Body:
I am working with a collection in Firebase that stores information about products. Previously, I was just fetching all of the products and then applying filters to them on the client side. I was told that I need to apply these filters through the query in order to reduce the number of reads that Firebase will need since there will be a very large number of products.

I have tried chaining together multiple .where() statements, but this does not product the effect that I need, I read in another post that multiple .orderBy() statements will break the query, but in order to check the other fields such as price the output tells me I need to orderBy() price first. Any number of these filters could be applied, or none of them could depending on settings. I am using the lastVisible variable at the bottom for a .startAfter in a separate function for getting more products. Is there any way to product the kind of queries I want to make this way? I would also like to know if it is possible to do something like .where('field', isEqualTo: x or y or z).

    Query productQuery = Firestore.instance.collection('Products');

    if(selectedCategories != null)
    for(int i = 0; i < selectedCategories.length; i++)
      productQuery = productQuery.where('category', isEqualTo: selectedCategories[i]);

    if(minPrice > 0 && maxPrice > 0)
    {
      productQuery = productQuery.orderBy('price').where('price', isGreaterThanOrEqualTo: minPrice).where('price', isLessThanOrEqualTo: minPrice);
    }
    else if(minPrice > 0)
      productQuery = productQuery.orderBy('price').where('price', isGreaterThanOrEqualTo: minPrice);

    else if(maxPrice > 0)
      productQuery = productQuery.orderBy('price').where('price', isLessThanOrEqualTo: maxPrice);

    if(!showUnavailableItems)
      productQuery = productQuery.where('status', isEqualTo: 'available');

    switch(selectedCondition)
    {
      case 'Acceptable':
        productQuery = productQuery
                      .where('condition', isEqualTo: 'Acceptable')
                      .where('condition', isEqualTo: 'Good')
                      .where('condition', isEqualTo: 'Very Good');
        break;
      case 'Good':
        productQuery = productQuery
                      .where('condition', isEqualTo: 'Acceptable')
                      .where('condition', isEqualTo: 'Good');
        break;
      case 'Very Good':
        productQuery = productQuery
                      .where('condition', isEqualTo: 'Acceptable');

        break;
      default:
        break;
    }

    productQuery = productQuery.orderBy('id');

    QuerySnapshot myQuery = await productQuery.getDocuments();
    List<DocumentSnapshot> productSnaps = myQuery.documents;
    print("INITIAL PRODUCT SNAPS LENGTH: ${myQuery.documents.length}");

    if(productSnaps.length != 0)
      lastVisible = productSnaps[productSnaps.length -1].data['id'];

When the condition or category filters are applied, the result is always 0 documents. Using the minPrice and maxPrice filters separately works, but together also returns 0 products. I have not gotten any errors besides ones for creating the indexes in Firebase.


问:
how to set a background image as colorWithPatternImage in swift
My questions is, is it possible to have a UIView display an image, and if so, how so I do it? All I can find is the colorwithpatternImage which no longer works with swift.

The code I am trying to use now is:

```<code>self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];
</code>```

答:
Swift

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "YourImage.png")!)

Body:
My questions is, is it possible to have a UIView display an image, and if so, how so I do it? All I can find is the colorwithpatternImage which no longer works with swift.

The code I am trying to use now is:

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];


问:
Simple mongodb search with python
I've got a very small script that's trying to find some docs in mongodb where a certain field has today's date.

To me, as a noob, it looks like I have a good connection - but I get no results.

Wondering if it has something to do with my date formatting?

Here's my script:

```<code>import pymongo
from datetime import date

thedate = date.today().isoformat()

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["hotels"]
collection = db["grand_native_test"]

query = {"skaptdato": {"$gt": thedate} }

doit = collection.find(query)

print(query)
print(collection)

for x in doit:
    print(x)
</code>```

And the result is simply:

```<code>{'skaptdato': {'$gt': '2019-05-30'}}
Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'hotels'), u'grand_native_test')
</code>```

I've spent like 4 hours on this, really basic, script - but I can't for the life of me figure it out.

BTW: Running mongodb 3.6.3, the latest pymongo-release and python 2.7.15.

BTW-2: The formatting of the db-fields also includes minutes and seconds --> 2019-05-30 13:54:00.645Z ...

I sure hope one of you smart folks have a hint for a poor noob.

答:
I assume the problem is in data types. For example, the DB's field contains ISODate type and compare with string type. Use the next code for MongoDB:

```<code>{skaptdato: {'$gt': ISODate('2019-05-30')}}
</code>```

Use the next code for pymongo:

from datetime import datetime
...
your_date_string = '2019-05-30'
date_string_to_date = datetime.strptime(your_date_string, '%Y-%m-%d')
...
{'skaptdato': {'$gt': date_string_to_date}}
```

Title: Simple mongodb search with python

Body:
I've got a very small script that's trying to find some docs in mongodb where a certain field has today's date.

To me, as a noob, it looks like I have a good connection - but I get no results.

Wondering if it has something to do with my date formatting?

Here's my script:

import pymongo
from datetime import date

thedate = date.today().isoformat()

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["hotels"]
collection = db["grand_native_test"]

query = {"skaptdato": {"$gt": thedate} }

doit = collection.find(query)

print(query)
print(collection)

for x in doit:
    print(x)

And the result is simply:

{'skaptdato': {'$gt': '2019-05-30'}}
Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'hotels'), u'grand_native_test')

I've spent like 4 hours on this, really basic, script - but I can't for the life of me figure it out.

BTW: Running mongodb 3.6.3, the latest pymongo-release and python 2.7.15.

BTW-2: The formatting of the db-fields also includes minutes and seconds --> 2019-05-30 13:54:00.645Z ...

I sure hope one of you smart folks have a hint for a poor noob.

Body:
I assume the problem is in data types. For example, the DB's field contains ISODate type and compare with string type. Use the next code for MongoDB:

{skaptdato: {'$gt': ISODate('2019-05-30')}}

Use the next code for pymongo:

from datetime import datetime
...
your_date_string = '2019-05-30'
date_string_to_date = datetime.strptime(your_date_string, '%Y-%m-%d')
...
{'skaptdato': {'$gt': date_string_to_date}}


问:
Spread operator used in conjuction with a function in ES6 , inside Vue.js
I was just going through habitica code (a vue.js app) and came across the below spread operator usage like so HERE. Inside computed you have the following:

```<code>computed: {
  ...mapState({
    user: 'user.data',
    castingSpell: 'spellOptions.castingSpell',
    isRunningYesterdailies: 'isRunningYesterdailies',
  }),
}
</code>```

Now i've never seem the spread operator used in conjuction with a function , not sure whats happning here, the mapState happnens to be a function present in another file, that looks like so:

```<code>export function mapState (states) {
  const res = {};

  normalizeMap(states).forEach(({ key, val }) => {
    res[key] = function mappedState () {
      return typeof val === 'function' ?
        val.call(this, this.$store.state, this.$store.getters) :
        get(this.$store.state, val);
    };
  });

  return res;
}
</code>```

I understand the spread operator when used with an Array or an Object, but what exactly is happening here with a function ?

答:
Your function is returning an Object which is being getting spread-ed,

You can understand with a simple example

Here func is a function which creates an object based on value passed to it

inside me object i have one property called info which i want to set as an object, so i simply call func with name and age and spread

let func = (name,age)=> ({name,age})

let me = {
  info: {...func('code maniac', 24)}
}

console.log(me)```

Body:
I was just going through habitica code (a vue.js app) and came across the below spread operator usage like so HERE. Inside computed you have the following:

computed: {
  ...mapState({
    user: 'user.data',
    castingSpell: 'spellOptions.castingSpell',
    isRunningYesterdailies: 'isRunningYesterdailies',
  }),
}

Now i've never seem the spread operator used in conjuction with a function , not sure whats happning here, the mapState happnens to be a function present in another file, that looks like so:

export function mapState (states) {
  const res = {};

  normalizeMap(states).forEach(({ key, val }) => {
    res[key] = function mappedState () {
      return typeof val === 'function' ?
        val.call(this, this.$store.state, this.$store.getters) :
        get(this.$store.state, val);
    };
  });

  return res;
}

I understand the spread operator when used with an Array or an Object, but what exactly is happening here with a function ?


问:
How to identify the reports type from Google Analytics Reporting API v4 batch request?
Google Analytics Reporting API's batch request feature is really great. We can request multiple reports in a single HTTP request. But results are returned as an array. How do we get the specific report type from that array?

```<code>$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( $requests );
$reports = $this->analytics->reports->batchGet( $body )->getReports();
</code>```

Above batch request consists of top countries, top pages reports. But how do I identify the top countries report from the array?

答: Ok. I ended up setting custom prefix for metric alias in different requests and then identify the requests based on the prefix.</p>

Body:
Google Analytics Reporting API's batch request feature is really great. We can request multiple reports in a single HTTP request. But results are returned as an array. How do we get the specific report type from that array?

$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( $requests );
$reports = $this->analytics->reports->batchGet( $body )->getReports();

Above batch request consists of top countries, top pages reports. But how do I identify the top countries report from the array?