问:
Can this Entity Framework Query be improved for performance?
* UPDATE *

I am unable to delete this question even though it was actually not a problem in the long run... I still had some code from when I was working on it that did separate queries and populated some of these fields... when I stripped out that code... the following query runs very fast (2 seconds):

```<code>public IQueryable<ApplicationUser> QueriableUsersList()
{
    return _context.Users.OrderBy(u => u.UserName)
        .Include(u => u.Accounts.Select(a => a.Broker))
        .Include(u => u.Roles);
}
</code>```

* ORIGINAL QUESTION *

I am trying to load a list of users (about 600 of them) using Entity Framework… I want to preload with the query account records for each user and a broker record for each account (along with roles for each user)… this SQL gets me results very quickly ( < 1 second):

```<code>select ISNULL(ur.RoleId, 0) as IsAdmin, u.*, a.*, b.*
  from AspNetUsers u
 inner join Accounts a on u.Id = a.ClientId
 inner join Brokers b on a.Brokerid = b.BrokerId
 left outer join AspNetUserRoles ur on u.id = ur.UserId and ur.RoleId = 1
order by u.UserName
</code>```

But this Entity Framework query takes a long time (something like 20 - 25 seconds)... especially in production where the database is on a different server:

```<code>public IQueryable<ApplicationUser> QueriableUsersList()
{
    return _context.Users.OrderBy(u => u.UserName)
        .Include(u => u.Accounts.Select(a => a.Broker))
        .Include(u => u.Roles);
}
</code>```

Any thoughts on how the Entity Framework query could be improved and/or what it would take to get it to be faster like the native SQL query is?. (Note: I do need all the data from all the above object for my list so lazy loading isn’t going to help.) I was hoping it would generate a single query along the lines of what I show above… but it is generating several queries (below) for each user it seems.

I eventually want to use this IQueryable to get paginated data as well.

My objects are defined like this:

```<code>public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>/
{
    public List<Account> Accounts { get; set; }
…
    public bool isAdmin { get {  return this.Roles != null && this.Roles.Any(r => r.RoleId == 1); } }
…
}

public class Account
{
    public int AccountId { get; set; }
…
    public int BrokerId { get; set; }
    public virtual Broker Broker { get; set; }
…
}

public class Broker
{
    public int BrokerId { get; set; }
    public string Name { get; set; }
…
}
</code>```

With the entity framework query using SQL Server profiler I see one of these:

```<code>SELECT
[Project1].[Id] AS [Id],
[Project1].[UserName] AS [UserName],
[Project1].[FirstName] AS [FirstName],
[Project1].[LastName] AS [LastName],
[Project1].[PhoneNumber] AS [PhoneNumber],
[Project1].[Email] AS [Email],
[Project1].[Address] AS [Address],
[Project1].[City] AS [City],
[Project1].[State] AS [State],
[Project1].[Zip] AS [Zip],
[Project1].[DateAdded] AS [DateAdded],
[Project1].[IsActive] AS [IsActive],
[Project1].[C1] AS [C1],
[Project1].[AccountId] AS [AccountId],
[Project1].[ClientId] AS [ClientId],
[Project1].[BrokerId] AS [BrokerId],
[Project1].[AccountNumber] AS [AccountNumber],
[Project1].[BrokerUserName] AS [BrokerUserName],
[Project1].[BrokerPasswordHash] AS [BrokerPasswordHash],
[Project1].[EquityCurve] AS [EquityCurve],
[Project1].[CapitalInvested] AS [CapitalInvested],
[Project1].[IsSimulated] AS [IsSimulated],
[Project1].[ClosedProfit] AS [ClosedProfit],
[Project1].[MarketValueTimeStamp] AS [MarketValueTimeStamp],
[Project1].[IsAuthorizedForLiveTrading] AS [IsAuthorizedForLiveTrading],
[Project1].[ActivatedOn] AS [ActivatedOn]
FROM ( SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[FirstName] AS [FirstName],
    [Extent1].[LastName] AS [LastName],
    [Extent1].[Address] AS [Address],
    [Extent1].[Zip] AS [Zip],
    [Extent1].[City] AS [City],
    [Extent1].[State] AS [State],
    [Extent1].[DateAdded] AS [DateAdded],
    [Extent1].[IsActive] AS [IsActive],
    [Extent1].[Email] AS [Email],
    [Extent1].[PhoneNumber] AS [PhoneNumber],
    [Extent1].[UserName] AS [UserName],
    [Extent2].[AccountId] AS [AccountId],
    [Extent2].[ClientId] AS [ClientId],
    [Extent2].[BrokerId] AS [BrokerId],
    [Extent2].[AccountNumber] AS [AccountNumber],
    [Extent2].[BrokerUserName] AS [BrokerUserName],
    [Extent2].[BrokerPasswordHash] AS [BrokerPasswordHash],
    [Extent2].[EquityCurve] AS [EquityCurve],
    [Extent2].[CapitalInvested] AS [CapitalInvested],
    [Extent2].[IsSimulated] AS [IsSimulated],
    [Extent2].[ClosedProfit] AS [ClosedProfit],
    [Extent2].[MarketValueTimeStamp] AS [MarketValueTimeStamp],
    [Extent2].[IsAuthorizedForLiveTrading] AS [IsAuthorizedForLiveTrading],
    [Extent2].[ActivatedOn] AS [ActivatedOn],
    CASE WHEN ([Extent2].[AccountId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    FROM  [dbo].[AspNetUsers] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Accounts] AS [Extent2] ON [Extent1].[Id] = [Extent2].[ClientId]
)  AS [Project1]
ORDER BY [Project1].[UserName] ASC, [Project1].[Id] ASC, [Project1].[C1] ASC
</code>```

Then seemingly one of these for each user:

```<code>SELECT TOP (1)
[Extent1].[BrokerId] AS [BrokerId],
[Extent1].[Name] AS [Name],
[Extent1].[Code] AS [Code],
[Extent1].[IsExternal] AS [IsExternal]
FROM [dbo].[Brokers] AS [Extent1]
WHERE [Extent1].[BrokerId] = @p__linq__0',N'@p__linq__0 int',@p__linq__0=2
</code>```

And also one of these for each user:

```<code>SELECT
[Project2].[Id] AS [Id],
[Project2].[ReferralId] AS [ReferralId],
[Project2].[FirstName] AS [FirstName],
[Project2].[LastName] AS [LastName],
[Project2].[Address] AS [Address],
[Project2].[Address2] AS [Address2],
[Project2].[Zip] AS [Zip],
[Project2].[City] AS [City],
[Project2].[StateProvince] AS [StateProvince],
[Project2].[Country] AS [Country],
[Project2].[State] AS [State],
[Project2].[startPopupChecked] AS [startPopupChecked],
[Project2].[DateAdded] AS [DateAdded],
[Project2].[CurrentPortfolioId] AS [CurrentPortfolioId],
[Project2].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
[Project2].[NotificationMobileNumber] AS [NotificationMobileNumber],
[Project2].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
[Project2].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
[Project2].[IsActive] AS [IsActive],
[Project2].[HasSeen] AS [HasSeen],
[Project2].[Email] AS [Email],
[Project2].[EmailConfirmed] AS [EmailConfirmed],
[Project2].[PasswordHash] AS [PasswordHash],
[Project2].[SecurityStamp] AS [SecurityStamp],
[Project2].[PhoneNumber] AS [PhoneNumber],
[Project2].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project2].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project2].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project2].[LockoutEnabled] AS [LockoutEnabled],
[Project2].[AccessFailedCount] AS [AccessFailedCount],
[Project2].[UserName] AS [UserName],
[Project2].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId],
[Project2].[C1] AS [C1],
[Project2].[UserId] AS [UserId],
[Project2].[RoleId] AS [RoleId]
FROM ( SELECT
    [Limit1].[Id] AS [Id],
    [Limit1].[ReferralId] AS [ReferralId],
    [Limit1].[FirstName] AS [FirstName],
    [Limit1].[LastName] AS [LastName],
    [Limit1].[Address] AS [Address],
    [Limit1].[Address2] AS [Address2],
    [Limit1].[Zip] AS [Zip],
    [Limit1].[City] AS [City],
    [Limit1].[StateProvince] AS [StateProvince],
    [Limit1].[Country] AS [Country],
    [Limit1].[State] AS [State],
    [Limit1].[startPopupChecked] AS [startPopupChecked],
    [Limit1].[DateAdded] AS [DateAdded],
    [Limit1].[CurrentPortfolioId] AS [CurrentPortfolioId],
    [Limit1].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
    [Limit1].[NotificationMobileNumber] AS [NotificationMobileNumber],
    [Limit1].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
    [Limit1].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
    [Limit1].[IsActive] AS [IsActive],
    [Limit1].[HasSeen] AS [HasSeen],
    [Limit1].[Email] AS [Email],
    [Limit1].[EmailConfirmed] AS [EmailConfirmed],
    [Limit1].[PasswordHash] AS [PasswordHash],
    [Limit1].[SecurityStamp] AS [SecurityStamp],
    [Limit1].[PhoneNumber] AS [PhoneNumber],
    [Limit1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
    [Limit1].[TwoFactorEnabled] AS [TwoFactorEnabled],
    [Limit1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
    [Limit1].[LockoutEnabled] AS [LockoutEnabled],
    [Limit1].[AccessFailedCount] AS [AccessFailedCount],
    [Limit1].[UserName] AS [UserName],
    [Limit1].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId],
    [Extent2].[UserId] AS [UserId],
    [Extent2].[RoleId] AS [RoleId],
    CASE WHEN ([Extent2].[UserId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    FROM   (SELECT TOP (1)
        [Extent1].[Id] AS [Id],
        [Extent1].[ReferralId] AS [ReferralId],
        [Extent1].[FirstName] AS [FirstName],
        [Extent1].[LastName] AS [LastName],
        [Extent1].[Address] AS [Address],
        [Extent1].[Address2] AS [Address2],
        [Extent1].[Zip] AS [Zip],
        [Extent1].[City] AS [City],
        [Extent1].[StateProvince] AS [StateProvince],
        [Extent1].[Country] AS [Country],
        [Extent1].[State] AS [State],
        [Extent1].[startPopupChecked] AS [startPopupChecked],
        [Extent1].[DateAdded] AS [DateAdded],
        [Extent1].[CurrentPortfolioId] AS [CurrentPortfolioId],
        [Extent1].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
        [Extent1].[NotificationMobileNumber] AS [NotificationMobileNumber],
        [Extent1].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
        [Extent1].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
        [Extent1].[IsActive] AS [IsActive],
        [Extent1].[HasSeen] AS [HasSeen],
        [Extent1].[Email] AS [Email],
        [Extent1].[EmailConfirmed] AS [EmailConfirmed],
        [Extent1].[PasswordHash] AS [PasswordHash],
        [Extent1].[SecurityStamp] AS [SecurityStamp],
        [Extent1].[PhoneNumber] AS [PhoneNumber],
        [Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
        [Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled],
        [Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
        [Extent1].[LockoutEnabled] AS [LockoutEnabled],
        [Extent1].[AccessFailedCount] AS [AccessFailedCount],
        [Extent1].[UserName] AS [UserName],
        [Extent1].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId]
        FROM [dbo].[AspNetUsers] AS [Extent1]
        WHERE [Extent1].[Id] = @p__linq__0 ) AS [Limit1]
    LEFT OUTER JOIN [dbo].[AspNetUserRoles] AS [Extent2] ON [Limit1].[Id] = [Extent2].[UserId]
)  AS [Project2]
ORDER BY [Project2].[Id] ASC, [Project2].[C1] ASC',N'@p__linq__0 int',@p__linq__0=346
</code>```

答:
With the entity framework query using SQL Server profiler I see one of these:

Then seemingly one of these for each user:

And also one of these for each user:

It's because you're most likely doing a combination of; not executing the query, Entity Framework has Lazy Loading enabled (which I recommend you turn off) and accessing navigation properties in a loop.  It looks very much like the Entity-Framework N+1 Problem.

Non-executed the query:

```<code>var nonexecuted = _context.Users.OrderBy(u => u.UserName)
    .Include(u => u.Accounts.Select(a => a.Broker))
    .Include(u => u.Roles);
</code>```

Executed query:

```<code>var executed = _context.Users.OrderBy(u => u.UserName)
    .Include(u => u.Accounts.Select(a => a.Broker))
    .Include(u => u.Roles)
    .ToList() // .AsEnumerable() etc...
</code>```

With a non-executed query if you do:

```<code>var maxIndex = 4;
for(idx = 0; idx < maxIndex; idx ++)
{
  nonexecuted.Users.Skip(idx).Accounts.First()
}
</code>```

Will execute a query for maxIndex times because it's lazy-loading loading a navigation property.

I highly suggest disabling lazying loading.  It will force you to create good queries that only need what you want.

Depending on the number of Accounts, Users and Roles you have, you could be running into a Cartesian Product problem as well.

Body:
* UPDATE *

I am unable to delete this question even though it was actually not a problem in the long run... I still had some code from when I was working on it that did separate queries and populated some of these fields... when I stripped out that code... the following query runs very fast (2 seconds):

public IQueryable<ApplicationUser> QueriableUsersList()
{
    return _context.Users.OrderBy(u => u.UserName)
        .Include(u => u.Accounts.Select(a => a.Broker))
        .Include(u => u.Roles);
}

* ORIGINAL QUESTION *

I am trying to load a list of users (about 600 of them) using Entity Framework… I want to preload with the query account records for each user and a broker record for each account (along with roles for each user)… this SQL gets me results very quickly ( < 1 second):

select ISNULL(ur.RoleId, 0) as IsAdmin, u.*, a.*, b.*
  from AspNetUsers u
 inner join Accounts a on u.Id = a.ClientId
 inner join Brokers b on a.Brokerid = b.BrokerId
 left outer join AspNetUserRoles ur on u.id = ur.UserId and ur.RoleId = 1
order by u.UserName

But this Entity Framework query takes a long time (something like 20 - 25 seconds)... especially in production where the database is on a different server:

public IQueryable<ApplicationUser> QueriableUsersList()
{
    return _context.Users.OrderBy(u => u.UserName)
        .Include(u => u.Accounts.Select(a => a.Broker))
        .Include(u => u.Roles);
}

Any thoughts on how the Entity Framework query could be improved and/or what it would take to get it to be faster like the native SQL query is?. (Note: I do need all the data from all the above object for my list so lazy loading isn’t going to help.) I was hoping it would generate a single query along the lines of what I show above… but it is generating several queries (below) for each user it seems.

I eventually want to use this IQueryable to get paginated data as well.

My objects are defined like this:

public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>/
{
    public List<Account> Accounts { get; set; }
…
    public bool isAdmin { get {  return this.Roles != null && this.Roles.Any(r => r.RoleId == 1); } }
…
}

public class Account
{
    public int AccountId { get; set; }
…
    public int BrokerId { get; set; }
    public virtual Broker Broker { get; set; }
…
}

public class Broker
{
    public int BrokerId { get; set; }
    public string Name { get; set; }
…
}

With the entity framework query using SQL Server profiler I see one of these:

SELECT
[Project1].[Id] AS [Id],
[Project1].[UserName] AS [UserName],
[Project1].[FirstName] AS [FirstName],
[Project1].[LastName] AS [LastName],
[Project1].[PhoneNumber] AS [PhoneNumber],
[Project1].[Email] AS [Email],
[Project1].[Address] AS [Address],
[Project1].[City] AS [City],
[Project1].[State] AS [State],
[Project1].[Zip] AS [Zip],
[Project1].[DateAdded] AS [DateAdded],
[Project1].[IsActive] AS [IsActive],
[Project1].[C1] AS [C1],
[Project1].[AccountId] AS [AccountId],
[Project1].[ClientId] AS [ClientId],
[Project1].[BrokerId] AS [BrokerId],
[Project1].[AccountNumber] AS [AccountNumber],
[Project1].[BrokerUserName] AS [BrokerUserName],
[Project1].[BrokerPasswordHash] AS [BrokerPasswordHash],
[Project1].[EquityCurve] AS [EquityCurve],
[Project1].[CapitalInvested] AS [CapitalInvested],
[Project1].[IsSimulated] AS [IsSimulated],
[Project1].[ClosedProfit] AS [ClosedProfit],
[Project1].[MarketValueTimeStamp] AS [MarketValueTimeStamp],
[Project1].[IsAuthorizedForLiveTrading] AS [IsAuthorizedForLiveTrading],
[Project1].[ActivatedOn] AS [ActivatedOn]
FROM ( SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[FirstName] AS [FirstName],
    [Extent1].[LastName] AS [LastName],
    [Extent1].[Address] AS [Address],
    [Extent1].[Zip] AS [Zip],
    [Extent1].[City] AS [City],
    [Extent1].[State] AS [State],
    [Extent1].[DateAdded] AS [DateAdded],
    [Extent1].[IsActive] AS [IsActive],
    [Extent1].[Email] AS [Email],
    [Extent1].[PhoneNumber] AS [PhoneNumber],
    [Extent1].[UserName] AS [UserName],
    [Extent2].[AccountId] AS [AccountId],
    [Extent2].[ClientId] AS [ClientId],
    [Extent2].[BrokerId] AS [BrokerId],
    [Extent2].[AccountNumber] AS [AccountNumber],
    [Extent2].[BrokerUserName] AS [BrokerUserName],
    [Extent2].[BrokerPasswordHash] AS [BrokerPasswordHash],
    [Extent2].[EquityCurve] AS [EquityCurve],
    [Extent2].[CapitalInvested] AS [CapitalInvested],
    [Extent2].[IsSimulated] AS [IsSimulated],
    [Extent2].[ClosedProfit] AS [ClosedProfit],
    [Extent2].[MarketValueTimeStamp] AS [MarketValueTimeStamp],
    [Extent2].[IsAuthorizedForLiveTrading] AS [IsAuthorizedForLiveTrading],
    [Extent2].[ActivatedOn] AS [ActivatedOn],
    CASE WHEN ([Extent2].[AccountId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    FROM  [dbo].[AspNetUsers] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Accounts] AS [Extent2] ON [Extent1].[Id] = [Extent2].[ClientId]
)  AS [Project1]
ORDER BY [Project1].[UserName] ASC, [Project1].[Id] ASC, [Project1].[C1] ASC

Then seemingly one of these for each user:

SELECT TOP (1)
[Extent1].[BrokerId] AS [BrokerId],
[Extent1].[Name] AS [Name],
[Extent1].[Code] AS [Code],
[Extent1].[IsExternal] AS [IsExternal]
FROM [dbo].[Brokers] AS [Extent1]
WHERE [Extent1].[BrokerId] = @p__linq__0',N'@p__linq__0 int',@p__linq__0=2

And also one of these for each user:

SELECT
[Project2].[Id] AS [Id],
[Project2].[ReferralId] AS [ReferralId],
[Project2].[FirstName] AS [FirstName],
[Project2].[LastName] AS [LastName],
[Project2].[Address] AS [Address],
[Project2].[Address2] AS [Address2],
[Project2].[Zip] AS [Zip],
[Project2].[City] AS [City],
[Project2].[StateProvince] AS [StateProvince],
[Project2].[Country] AS [Country],
[Project2].[State] AS [State],
[Project2].[startPopupChecked] AS [startPopupChecked],
[Project2].[DateAdded] AS [DateAdded],
[Project2].[CurrentPortfolioId] AS [CurrentPortfolioId],
[Project2].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
[Project2].[NotificationMobileNumber] AS [NotificationMobileNumber],
[Project2].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
[Project2].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
[Project2].[IsActive] AS [IsActive],
[Project2].[HasSeen] AS [HasSeen],
[Project2].[Email] AS [Email],
[Project2].[EmailConfirmed] AS [EmailConfirmed],
[Project2].[PasswordHash] AS [PasswordHash],
[Project2].[SecurityStamp] AS [SecurityStamp],
[Project2].[PhoneNumber] AS [PhoneNumber],
[Project2].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project2].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project2].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project2].[LockoutEnabled] AS [LockoutEnabled],
[Project2].[AccessFailedCount] AS [AccessFailedCount],
[Project2].[UserName] AS [UserName],
[Project2].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId],
[Project2].[C1] AS [C1],
[Project2].[UserId] AS [UserId],
[Project2].[RoleId] AS [RoleId]
FROM ( SELECT
    [Limit1].[Id] AS [Id],
    [Limit1].[ReferralId] AS [ReferralId],
    [Limit1].[FirstName] AS [FirstName],
    [Limit1].[LastName] AS [LastName],
    [Limit1].[Address] AS [Address],
    [Limit1].[Address2] AS [Address2],
    [Limit1].[Zip] AS [Zip],
    [Limit1].[City] AS [City],
    [Limit1].[StateProvince] AS [StateProvince],
    [Limit1].[Country] AS [Country],
    [Limit1].[State] AS [State],
    [Limit1].[startPopupChecked] AS [startPopupChecked],
    [Limit1].[DateAdded] AS [DateAdded],
    [Limit1].[CurrentPortfolioId] AS [CurrentPortfolioId],
    [Limit1].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
    [Limit1].[NotificationMobileNumber] AS [NotificationMobileNumber],
    [Limit1].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
    [Limit1].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
    [Limit1].[IsActive] AS [IsActive],
    [Limit1].[HasSeen] AS [HasSeen],
    [Limit1].[Email] AS [Email],
    [Limit1].[EmailConfirmed] AS [EmailConfirmed],
    [Limit1].[PasswordHash] AS [PasswordHash],
    [Limit1].[SecurityStamp] AS [SecurityStamp],
    [Limit1].[PhoneNumber] AS [PhoneNumber],
    [Limit1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
    [Limit1].[TwoFactorEnabled] AS [TwoFactorEnabled],
    [Limit1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
    [Limit1].[LockoutEnabled] AS [LockoutEnabled],
    [Limit1].[AccessFailedCount] AS [AccessFailedCount],
    [Limit1].[UserName] AS [UserName],
    [Limit1].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId],
    [Extent2].[UserId] AS [UserId],
    [Extent2].[RoleId] AS [RoleId],
    CASE WHEN ([Extent2].[UserId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    FROM   (SELECT TOP (1)
        [Extent1].[Id] AS [Id],
        [Extent1].[ReferralId] AS [ReferralId],
        [Extent1].[FirstName] AS [FirstName],
        [Extent1].[LastName] AS [LastName],
        [Extent1].[Address] AS [Address],
        [Extent1].[Address2] AS [Address2],
        [Extent1].[Zip] AS [Zip],
        [Extent1].[City] AS [City],
        [Extent1].[StateProvince] AS [StateProvince],
        [Extent1].[Country] AS [Country],
        [Extent1].[State] AS [State],
        [Extent1].[startPopupChecked] AS [startPopupChecked],
        [Extent1].[DateAdded] AS [DateAdded],
        [Extent1].[CurrentPortfolioId] AS [CurrentPortfolioId],
        [Extent1].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
        [Extent1].[NotificationMobileNumber] AS [NotificationMobileNumber],
        [Extent1].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
        [Extent1].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
        [Extent1].[IsActive] AS [IsActive],
        [Extent1].[HasSeen] AS [HasSeen],
        [Extent1].[Email] AS [Email],
        [Extent1].[EmailConfirmed] AS [EmailConfirmed],
        [Extent1].[PasswordHash] AS [PasswordHash],
        [Extent1].[SecurityStamp] AS [SecurityStamp],
        [Extent1].[PhoneNumber] AS [PhoneNumber],
        [Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
        [Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled],
        [Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
        [Extent1].[LockoutEnabled] AS [LockoutEnabled],
        [Extent1].[AccessFailedCount] AS [AccessFailedCount],
        [Extent1].[UserName] AS [UserName],
        [Extent1].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId]
        FROM [dbo].[AspNetUsers] AS [Extent1]
        WHERE [Extent1].[Id] = @p__linq__0 ) AS [Limit1]
    LEFT OUTER JOIN [dbo].[AspNetUserRoles] AS [Extent2] ON [Limit1].[Id] = [Extent2].[UserId]
)  AS [Project2]
ORDER BY [Project2].[Id] ASC, [Project2].[C1] ASC',N'@p__linq__0 int',@p__linq__0=346

Body:
With the entity framework query using SQL Server profiler I see one of these:

Then seemingly one of these for each user:

And also one of these for each user:

It's because you're most likely doing a combination of; not executing the query, Entity Framework has Lazy Loading enabled (which I recommend you turn off) and accessing navigation properties in a loop.  It looks very much like the Entity-Framework N+1 Problem.

Non-executed the query:

var nonexecuted = _context.Users.OrderBy(u => u.UserName)
    .Include(u => u.Accounts.Select(a => a.Broker))
    .Include(u => u.Roles);

Executed query:

var executed = _context.Users.OrderBy(u => u.UserName)
    .Include(u => u.Accounts.Select(a => a.Broker))
    .Include(u => u.Roles)
    .ToList() // .AsEnumerable() etc...

With a non-executed query if you do:

var maxIndex = 4;
for(idx = 0; idx < maxIndex; idx ++)
{
  nonexecuted.Users.Skip(idx).Accounts.First()
}

Will execute a query for maxIndex times because it's lazy-loading loading a navigation property.

I highly suggest disabling lazying loading.  It will force you to create good queries that only need what you want.

Depending on the number of Accounts, Users and Roles you have, you could be running into a Cartesian Product problem as well.


来源: stackexchange

问:
Func and List<string>
I have defined the following

```<code>Dictionary<string, Func<string, List<string>>> test1 = new Dictionary<string, Func<string, List<string>>>();
</code>```

also I have

```<code>    private string fred(List<string> Parms)
    {

        return "Test";
    }
</code>```

how do I add fred to the dictionary?
I have tried

```<code>       test1.Add("Test",fred);
</code>```

but I get an error, if I replace the List for a string everything is ok.

答:
You have the arguments around the wrong way. A Func<X,Y> takes an X and returns a Y. Your dictionary should be:

```<code>Dictionary<string, Func<List<string>,string>>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Func and List<string>

Body:
I have defined the following

Dictionary<string, Func<string, List<string>>> test1 = new Dictionary<string, Func<string, List<string>>>();

also I have

    private string fred(List<string> Parms)
    {

        return "Test";
    }

how do I add fred to the dictionary?
I have tried

       test1.Add("Test",fred);

but I get an error, if I replace the List for a string everything is ok.

Body:
You have the arguments around the wrong way. A Func<X,Y> takes an X and returns a Y. Your dictionary should be:

Dictionary<string, Func<List<string>,string>>

ContentLicense: CC BY-SA 2.5


问:
Cyclomatic complexity for some_method is too high
I have following method in controller. When i run lint i get the error
Cyclomatic complexity for some_method is too high

I checked online about it and seems like it is the way i wrote the method. How could i rewrite this method so i dont get the lint error?

```<code>  def customer_order
    if params[:customer_id].present? && !params[:order_id].present?
      render_error :not_found, 'No info found for given customer id' \
      unless @info.customer_id == params[:customer_id]
    elsif params[:order_id].present? && !params[:customer_id].present?
      render_error :not_found, 'No info found for given order id' \
      unless @info.order_id == params[:order_id]
    elsif params[:customer_id].present? && params[:order_id].present?
      render_error :not_found, 'No info found for given customer id and order id’ \
        unless @info.customer_id == params[:customer_id] &&
               @info.order_id == params[:order_id]
    end
  end
</code>```

答:
Yikes! It is too high!

This linting message essentially means you have so many if statements that it's hard for a developer to keep straight.

I would suggest refactoring the contents of each if statement into it's own method.

```<code>def customer_order
  if params[:customer_id].present? && !params[:order_id].present?
    no_order_error
  elsif params[:order_id].present? && !params[:customer_id].present?
    no_info_error
  ...
end

def no_order_error
  return if @info.customer_id == params[:customer_id]
  render_error :not_found, 'No info found for given customer id'
end

def no_info_error
  ...
end
</code>```

Body:
I have following method in controller. When i run lint i get the error
Cyclomatic complexity for some_method is too high

I checked online about it and seems like it is the way i wrote the method. How could i rewrite this method so i dont get the lint error?

  def customer_order
    if params[:customer_id].present? && !params[:order_id].present?
      render_error :not_found, 'No info found for given customer id' \
      unless @info.customer_id == params[:customer_id]
    elsif params[:order_id].present? && !params[:customer_id].present?
      render_error :not_found, 'No info found for given order id' \
      unless @info.order_id == params[:order_id]
    elsif params[:customer_id].present? && params[:order_id].present?
      render_error :not_found, 'No info found for given customer id and order id’ \
        unless @info.customer_id == params[:customer_id] &&
               @info.order_id == params[:order_id]
    end
  end

Body:
Yikes! It is too high!

This linting message essentially means you have so many if statements that it's hard for a developer to keep straight.

I would suggest refactoring the contents of each if statement into it's own method.

def customer_order
  if params[:customer_id].present? && !params[:order_id].present?
    no_order_error
  elsif params[:order_id].present? && !params[:customer_id].present?
    no_info_error
  ...
end

def no_order_error
  return if @info.customer_id == params[:customer_id]
  render_error :not_found, 'No info found for given customer id'
end

def no_info_error
  ...
end


答:
One approach would be to make each of the conditionals their own method. As an example:

```<code>def customer_without_order(params)
  params[:customer_id].present? && !params[:order_id].present?
end
</code>```

You may find that the conditionals that determine when you render an error warrant this treatment as well.

Title: Cyclomatic complexity for some_method is too high

Body:
One approach would be to make each of the conditionals their own method. As an example:

def customer_without_order(params)
  params[:customer_id].present? && !params[:order_id].present?
end

You may find that the conditionals that determine when you render an error warrant this treatment as well.


问:
Ruby/Postgres ActiveRecord without Rails: Undefined Table ERROR: relation "..." does not exist
Working on a small Ruby script to create and store data to a Postgres database. The app works just fine when it comes to creating and dropping the database, or running migrations. However, it fails when I attempt to run rake db:seed. The error message indicates that the table doesn't exist...but meanwhile if I run the same SQL script referenced in the error message, but in pgAdmin, it returns valid results. I'm wondering if there is something going on with the privileges granted to the user named in the database.yml, and if so, how would I address that in the script? Any help understanding this would be appreciated.

Here is the error message I'm getting in the terminal:

```<code>acmecorp$ rake db:seed
rake aborted!
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "applications" does not exist
LINE 8:                WHERE a.attrelid = '"applications"'::regclass
                                          ^
:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
                     c.collname, col_description(a.attrelid, a.attnum) AS comment
                FROM pg_attribute a
                LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                LEFT JOIN pg_type t ON a.atttypid = t.oid
                LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
               WHERE a.attrelid = '"applications"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum
/Users/thisguy/repositories/acmecorp/db/seeds.rb:1:in `<top (required)>'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `require_relative'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `block (2 levels) in <top (required)>'

Caused by:
PG::UndefinedTable: ERROR:  relation "applications" does not exist
LINE 8:                WHERE a.attrelid = '"applications"'::regclass
                                          ^
/Users/thisguy/repositories/acmecorp/db/seeds.rb:1:in `<top (required)>'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `require_relative'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)
</code>```

My database.yml file:

```<code># config/database.yml
default: &default
  host: 'localhost'
  adapter: 'postgresql'
  encoding: utf-8

development:
  <<: *default
  database: 'acmecorp_dev'
  username: 'acmecorpapp'
</code>```

The Gemfile is pretty simple:

```<code># Gemfile
source 'https://rubygems.org'

gem 'activerecord'
gem 'require_all'
gem 'pg'
</code>```

I have a rakefile.rb to control the various tasks (edited to remove irrelevant items):

```<code># rakefile.rb
require "active_record"
require "require_all"
require "yaml"

namespace :db do
  env = 'development' || ENV['env']

  db_config       = YAML::load(File.open('config/database.yml'))[env]
  db_config_admin = db_config.merge({'database' => 'postgres', 'schema_search_path' => 'public'})

  ...

  desc "Seed the database"
  task :seed do
    ActiveRecord::Base.establish_connection(db_config_admin)
    require_all 'models/*.rb'
    require_relative 'db/seeds.rb'
  end

  ...

end
</code>```

As noted, all of the other tasks in the rakefile work without problem--it's just the :seed task that burps. I'm fairly confident it has something to do with the way the script is interacting with the database.

Here is the seed file:

```<code># db/seeds.rb
Application.create({
  ApplicationNumber:  1,
  AccountNumber: 1234,
  ApplVer:  1,
  CreateDateTime:  "1/2/2018",
  ExpirationDateTime:  "1/5/2019",
  ApplicationStatus:  "In process",
  ApprovedAmount:     1992.92,
  AcceptedAmount:     92.92,
  HomeAddressLine1:   "1 Main Street",
  HomeAddressLine2:   "",
  HomeAddressCity:    "Thibodaux",
  HomeAddressState:   "LA",
  HomeAddressZipCode: "12345"
})
</code>```

and finally, I have a simple model for the application, which the seeds.rb file references:

```<code># models/application.rb
class Application < ActiveRecord::Base
end
</code>```

Now the error message noted above is stating that `relation "applications" does not exist"...but when I run the same SQL quoted in the message, directly in pgAdmin, here's what I get (apologies for formatting - couldn't figure out how to get it into a table efficiently):

```<code>attname|format_type|pg_get_expr|attnotnull|atttypid|atttypmod|collname|comment
id|integer|nextval('applications_id_seq'::regclass)|t|23|-1||
ApplicationNumber|integer||f|23|-1||
AccountNumber|integer||f|23|-1||
ApplVer|integer||f|23|-1||
CreateDateTime|timestamp without time zone||f|1114|-1||
ExpirationDateTime|timestamp without time zone||f|1114|-1||
ApplicationStatus|character varying||f|1043|-1||
ApprovedAmount|numeric||f|1700|-1||
AcceptedAmount|numeric||f|1700|-1||
HomeAddressLine1|character varying||f|1043|-1||
HomeAddressLine2|character varying||f|1043|-1||
HomeAddressCity|character varying||f|1043|-1||
HomeAddressState|character varying||f|1043|-1||
HomeAddressZipCode|character varying||f|1043|-1||
FileCreatedDate|timestamp without time zone||f|1114|-1||
created_at|timestamp without time zone||t|1114|-1||
updated_at|timestamp without time zone||t|1114|-1||
</code>```

So the bottom line seems to be:
- the script is properly configured to work with PG - at least as far as creating, dropping, and migrating databases
- the rake db:seed task is failing
- the SQL reported in the error message on the command line works just fine when it is run through pgAdmin

I'm not sure why the issue. Could it have something to do with privileges available to the acmecorpapp user that was assigned to the database in the database.yml..?

答:
Okay, figured this out, after Chivorn Kouch's suggestion above. Solution requires an additional db_config variable, and a modification to the :seed task.

In the rakefile.rb:

```<code># rakefile.rb
namespace :db do
  env = 'development' || ENV['env']

  db_config       = YAML::load(File.open('config/database.yml'))[env]
  db_config_admin = db_config.merge({ 'database' => 'postgres','schema_search_path' => 'public' })
  # add following line to create variable for the :seed task
  db_config_seed = db_config.merge({ 'schema_search_path' => 'public' })

  ...

  desc "Seed the database"
  task :seed do
    # change variable referenced in the connection line below
    ActiveRecord::Base.establish_connection(db_config_seed)
    require_all 'models/*.rb'
    require_relative 'db/seeds.rb'
    puts "Database seeded."
  end

  ...

end
</code>```

With those changes, the commands all work as expected.

Body:
Working on a small Ruby script to create and store data to a Postgres database. The app works just fine when it comes to creating and dropping the database, or running migrations. However, it fails when I attempt to run rake db:seed. The error message indicates that the table doesn't exist...but meanwhile if I run the same SQL script referenced in the error message, but in pgAdmin, it returns valid results. I'm wondering if there is something going on with the privileges granted to the user named in the database.yml, and if so, how would I address that in the script? Any help understanding this would be appreciated.

Here is the error message I'm getting in the terminal:

acmecorp$ rake db:seed
rake aborted!
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "applications" does not exist
LINE 8:                WHERE a.attrelid = '"applications"'::regclass
                                          ^
:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
                     c.collname, col_description(a.attrelid, a.attnum) AS comment
                FROM pg_attribute a
                LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                LEFT JOIN pg_type t ON a.atttypid = t.oid
                LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
               WHERE a.attrelid = '"applications"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum
/Users/thisguy/repositories/acmecorp/db/seeds.rb:1:in `<top (required)>'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `require_relative'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `block (2 levels) in <top (required)>'

Caused by:
PG::UndefinedTable: ERROR:  relation "applications" does not exist
LINE 8:                WHERE a.attrelid = '"applications"'::regclass
                                          ^
/Users/thisguy/repositories/acmecorp/db/seeds.rb:1:in `<top (required)>'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `require_relative'
/Users/thisguy/repositories/acmecorp/rakefile.rb:30:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)

My database.yml file:

# config/database.yml
default: &default
  host: 'localhost'
  adapter: 'postgresql'
  encoding: utf-8

development:
  <<: *default
  database: 'acmecorp_dev'
  username: 'acmecorpapp'

The Gemfile is pretty simple:

# Gemfile
source 'https://rubygems.org'

gem 'activerecord'
gem 'require_all'
gem 'pg'

I have a rakefile.rb to control the various tasks (edited to remove irrelevant items):

# rakefile.rb
require "active_record"
require "require_all"
require "yaml"

namespace :db do
  env = 'development' || ENV['env']

  db_config       = YAML::load(File.open('config/database.yml'))[env]
  db_config_admin = db_config.merge({'database' => 'postgres', 'schema_search_path' => 'public'})

  ...

  desc "Seed the database"
  task :seed do
    ActiveRecord::Base.establish_connection(db_config_admin)
    require_all 'models/*.rb'
    require_relative 'db/seeds.rb'
  end

  ...

end

As noted, all of the other tasks in the rakefile work without problem--it's just the :seed task that burps. I'm fairly confident it has something to do with the way the script is interacting with the database.

Here is the seed file:

# db/seeds.rb
Application.create({
  ApplicationNumber:  1,
  AccountNumber: 1234,
  ApplVer:  1,
  CreateDateTime:  "1/2/2018",
  ExpirationDateTime:  "1/5/2019",
  ApplicationStatus:  "In process",
  ApprovedAmount:     1992.92,
  AcceptedAmount:     92.92,
  HomeAddressLine1:   "1 Main Street",
  HomeAddressLine2:   "",
  HomeAddressCity:    "Thibodaux",
  HomeAddressState:   "LA",
  HomeAddressZipCode: "12345"
})

and finally, I have a simple model for the application, which the seeds.rb file references:

# models/application.rb
class Application < ActiveRecord::Base
end

Now the error message noted above is stating that `relation "applications" does not exist"...but when I run the same SQL quoted in the message, directly in pgAdmin, here's what I get (apologies for formatting - couldn't figure out how to get it into a table efficiently):

attname|format_type|pg_get_expr|attnotnull|atttypid|atttypmod|collname|comment
id|integer|nextval('applications_id_seq'::regclass)|t|23|-1||
ApplicationNumber|integer||f|23|-1||
AccountNumber|integer||f|23|-1||
ApplVer|integer||f|23|-1||
CreateDateTime|timestamp without time zone||f|1114|-1||
ExpirationDateTime|timestamp without time zone||f|1114|-1||
ApplicationStatus|character varying||f|1043|-1||
ApprovedAmount|numeric||f|1700|-1||
AcceptedAmount|numeric||f|1700|-1||
HomeAddressLine1|character varying||f|1043|-1||
HomeAddressLine2|character varying||f|1043|-1||
HomeAddressCity|character varying||f|1043|-1||
HomeAddressState|character varying||f|1043|-1||
HomeAddressZipCode|character varying||f|1043|-1||
FileCreatedDate|timestamp without time zone||f|1114|-1||
created_at|timestamp without time zone||t|1114|-1||
updated_at|timestamp without time zone||t|1114|-1||

So the bottom line seems to be:
- the script is properly configured to work with PG - at least as far as creating, dropping, and migrating databases
- the rake db:seed task is failing
- the SQL reported in the error message on the command line works just fine when it is run through pgAdmin

I'm not sure why the issue. Could it have something to do with privileges available to the acmecorpapp user that was assigned to the database in the database.yml..?

Body:
Okay, figured this out, after Chivorn Kouch's suggestion above. Solution requires an additional db_config variable, and a modification to the :seed task.

In the rakefile.rb:

# rakefile.rb
namespace :db do
  env = 'development' || ENV['env']

  db_config       = YAML::load(File.open('config/database.yml'))[env]
  db_config_admin = db_config.merge({ 'database' => 'postgres','schema_search_path' => 'public' })
  # add following line to create variable for the :seed task
  db_config_seed = db_config.merge({ 'schema_search_path' => 'public' })

  ...

  desc "Seed the database"
  task :seed do
    # change variable referenced in the connection line below
    ActiveRecord::Base.establish_connection(db_config_seed)
    require_all 'models/*.rb'
    require_relative 'db/seeds.rb'
    puts "Database seeded."
  end

  ...

end

With those changes, the commands all work as expected.


答:
Expanding on Jed's answer, in response to Ajinkya's comment:

To get the same old column names, you need to replace "old_cols" with a column list of the newly named indexed columns. See my modified version of the function below

```<code>def add_column_index(df):
    new_cols = df.schema.names + ['ix']
    ix_df = df.rdd.zipWithIndex().map(lambda (row, ix): row + (ix,)).toDF()
    tmp_cols = ix_df.schema.names
    return reduce(lambda data, idx: data.withColumnRenamed(tmp_cols[idx], new_cols[idx]), xrange(len(tmp_cols)), ix_df)
</code>```

Title: Spark: Merge 2 dataframes by adding row index/number on both dataframes

Body:
Q: Is there is any way to merge two dataframes or copy a column of a dataframe to another in PySpark?

For example, I have two Dataframes:

DF1
C1                    C2
23397414             20875.7353
5213970              20497.5582
41323308             20935.7956
123276113            18884.0477
76456078             18389.9269

the seconde dataframe

DF2
C3                       C4
2008-02-04               262.00
2008-02-05               257.25
2008-02-06               262.75
2008-02-07               237.00
2008-02-08               231.00

Then i want to add C3 of DF2 to DF1 like this:

New DF
    C1                    C2          C3
    23397414             20875.7353   2008-02-04
    5213970              20497.5582   2008-02-05
    41323308             20935.7956   2008-02-06
    123276113            18884.0477   2008-02-07
    76456078             18389.9269   2008-02-08

I hope this example was clear.

Body:
Expanding on Jed's answer, in response to Ajinkya's comment:

To get the same old column names, you need to replace "old_cols" with a column list of the newly named indexed columns. See my modified version of the function below

def add_column_index(df):
    new_cols = df.schema.names + ['ix']
    ix_df = df.rdd.zipWithIndex().map(lambda (row, ix): row + (ix,)).toDF()
    tmp_cols = ix_df.schema.names
    return reduce(lambda data, idx: data.withColumnRenamed(tmp_cols[idx], new_cols[idx]), xrange(len(tmp_cols)), ix_df)


问:
Is it possible to read from a PostGIS geospatial index after filtering on un-indexed columns?
Is it possible to coerce the Postgres planner to filter a results set based on a sequential scan of scalar values, and only then perform a GIS function/comparison based on a spatial index? My production use-case is a bit more complicated, but this example illustrates my goal:

Create a table with a geography column and index on that column:

```<code>CREATE TABLE test_table (
id SERIAL,
min INTEGER,
max INTEGER,
active BOOLEAN,
geo GEOGRAPHY(Polygon,4326) );

CREATE INDEX test_table_gidx ON test_table USING gist (geo);
</code>```

I seeded the table with 6000 records, using non-trivial polygon geometries (~10k vertices each).

Performing a simple select based on min and max takes on the order of milliseconds.

```<code>geotest=> SELECT count(*) FROM test_table t WHERE t.min <= 50 AND t.max >= 50 ;
 count
-------
  4000
(1 row)

Time: 3.066 ms
</code>```

An ST_Intersects query against the geo column takes around 10 seconds with my hardware and configuration.

```<code>geotest=> SELECT count(*) FROM test_table t WHERE ST_Intersects(t.geo, ST_GeogFromText('SRID=4326;POINT(-104.70348 38.6661)'));
 count
-------
  1000
(1 row)

Time: 11051.466 ms
</code>```

Combining the WHERE clauses, the query still runs in the time scale of the geometry-only query.

```<code>geotest=> SELECT count(*) FROM test_table t WHERE  t.min <= 50 AND t.max >= 50 AND ST_Intersects(t.geo, ST_GeogFromText('SRID=4326;POINT(-104.70348 38.6661)'));
 count
-------
  1000
(1 row)

Time: 11072.337 ms
</code>```

If it's helpful, here's how the planner is approaching the combined query:

```<code>geotest=> EXPLAIN ANALYZE SELECT count(*) FROM test_table t WHERE  t.min <= 50 AND t.max >= 50 AND ST_Intersects(t.geo, ST_GeogFromText('SRID=4326;POINT(-104.70348 38.6661)'));
                                                                                QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=8.43..8.44 rows=1 width=8) (actual time=10962.332..10962.333 rows=1 loops=1)
   ->  Index Scan using test_table_gidx on test_table t  (cost=0.15..8.42 rows=1 width=0) (actual time=8.199..10961.612 rows=1000 loops=1)
         Index Cond: (geo && '0101000020E6100000F758FAD0052D5AC0CCEEC9C342554340'::geography)
         Filter: ((min <= 50) AND (max >= 50) AND (_st_distance(geo, '0101000020E6100000F758FAD0052D5AC0CCEEC9C342554340'::geography, '0'::double precision, false) < '1e-05'::double precision))
         Rows Removed by Filter: 1000
 Planning time: 0.260 ms
 Execution time: 10962.606 ms
</code>```

Is there a way to only perform the ST_Intersects comparison for records matching the min/max filter of the WHERE clause?

答:
Use a CTE as an optimization fence.</p>

```<code>WITH t1 AS (
  SELECT *
  FROM test_table t
  WHERE t.min <= 50 AND t.max >= 50
)
SELECT *
FROM t1
JOIN test_table AS t2
ON t2.id=t1.id
  AND ST_Intersects(
    t2.geom,
    ST_SetSRID(ST_MakePoint(-104.70348, 38.6661),4326)
  );
</code>```

Body:
Is it possible to coerce the Postgres planner to filter a results set based on a sequential scan of scalar values, and only then perform a GIS function/comparison based on a spatial index? My production use-case is a bit more complicated, but this example illustrates my goal:

Create a table with a geography column and index on that column:

CREATE TABLE test_table (
id SERIAL,
min INTEGER,
max INTEGER,
active BOOLEAN,
geo GEOGRAPHY(Polygon,4326) );

CREATE INDEX test_table_gidx ON test_table USING gist (geo);

I seeded the table with 6000 records, using non-trivial polygon geometries (~10k vertices each).

Performing a simple select based on min and max takes on the order of milliseconds.

geotest=> SELECT count(*) FROM test_table t WHERE t.min <= 50 AND t.max >= 50 ;
 count
-------
  4000
(1 row)

Time: 3.066 ms

An ST_Intersects query against the geo column takes around 10 seconds with my hardware and configuration.

geotest=> SELECT count(*) FROM test_table t WHERE ST_Intersects(t.geo, ST_GeogFromText('SRID=4326;POINT(-104.70348 38.6661)'));
 count
-------
  1000
(1 row)

Time: 11051.466 ms

Combining the WHERE clauses, the query still runs in the time scale of the geometry-only query.

geotest=> SELECT count(*) FROM test_table t WHERE  t.min <= 50 AND t.max >= 50 AND ST_Intersects(t.geo, ST_GeogFromText('SRID=4326;POINT(-104.70348 38.6661)'));
 count
-------
  1000
(1 row)

Time: 11072.337 ms

If it's helpful, here's how the planner is approaching the combined query:

geotest=> EXPLAIN ANALYZE SELECT count(*) FROM test_table t WHERE  t.min <= 50 AND t.max >= 50 AND ST_Intersects(t.geo, ST_GeogFromText('SRID=4326;POINT(-104.70348 38.6661)'));
                                                                                QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=8.43..8.44 rows=1 width=8) (actual time=10962.332..10962.333 rows=1 loops=1)
   ->  Index Scan using test_table_gidx on test_table t  (cost=0.15..8.42 rows=1 width=0) (actual time=8.199..10961.612 rows=1000 loops=1)
         Index Cond: (geo && '0101000020E6100000F758FAD0052D5AC0CCEEC9C342554340'::geography)
         Filter: ((min <= 50) AND (max >= 50) AND (_st_distance(geo, '0101000020E6100000F758FAD0052D5AC0CCEEC9C342554340'::geography, '0'::double precision, false) < '1e-05'::double precision))
         Rows Removed by Filter: 1000
 Planning time: 0.260 ms
 Execution time: 10962.606 ms

Is there a way to only perform the ST_Intersects comparison for records matching the min/max filter of the WHERE clause?

Body:
Use a CTE as an optimization fence.

WITH t1 AS (
  SELECT *
  FROM test_table t
  WHERE t.min <= 50 AND t.max >= 50
)
SELECT *
FROM t1
JOIN test_table AS t2
ON t2.id=t1.id
  AND ST_Intersects(
    t2.geom,
    ST_SetSRID(ST_MakePoint(-104.70348, 38.6661),4326)
  );


问:
Unity 2017.2 2D Tilemap & Tiles
I'm trying to use the new Unity Tilemap introduced in Unity 2017.2 but I'm struggling a bit and wondering if it's worth bothering with. The documentation is a bit thin and examples are lacking. I am making a top down old school RPG and would love to use the new Tilemap features but I've run into a couple issues:

Firstly, as far as I can tell there is no visibility of the individual tile's 'gameObject'. According to the documentation, each tile has it's own 'gameobject' (typo? should be gameObject?). I'm still a bit confused if this is simply the parent gameObject or the tile's 'Instanced Game Object'. The 'Instanced Game Object' for a given tile does show up in the inspector if you click on the tile in the scene but there doesn't seem to be a way to adjust its transform (either in code or inspector) so it's very inflexible. What is the common use case for a tile's instanced game object?

In my game I am making a farming sim where some tiles would be 'tillable' so I thought this new tilemap feature would be a perfect opportunity to try out a new scriptable tile but I could not figure out how to use it properly with the current documentation. I want the tiles to change sprites based on other tiles around them but I struggled to get that to work properly. There is a similar example in the documentation and I believe I could get it working if I spent some more time but even if I did get that working it appears I would have other blockers - each tile is lacking hooks into the normal Unity gameObject lifecycle - Start() OnEnable() OnDisable() etc... So I would have no way to script the tile as I would need. I'm not sure if there is a way around this other than creating a new public game object on the tile and simply scripting that game object to do what I need. If I have to do that, the tilemap feature is basically doing nothing for me and I might as well just add those tiles as game objects myself to the scene. Also, it'd be worse because I cant even see individual tiles easily in the scene inspector. And I also don't believe I'd be able to adjust their transforms.

Has anyone else encountered these issues and is there a guide out there I can read for how to get started using the new Tilemap features?

答:
I agree that examples are thin right now, but this is a feature that you definitely want to get to know.

For one, the tilemap is rendered as a single mesh with each quad textured to whatever you've programmed it to be. This is extremely efficient, and allows much larger maps than you'd be able to achieve with individual game objects for each tile.

Check out the tech demos for tile map on git. There are examples of road tiles, animated tiles, pipe tiles, etc. They should be able to get you started. When I get off work I'll write up the road tile example, as that's the one which most directly fits how you intend to use them.

https://github.com/Unity-Technologies/2d-extras/tree/master/Assets/Tilemap/Tiles

Title: Unity 2017.2 2D Tilemap & Tiles


问:
getElementByID.readOnly in array
Im trying to create a list of input ID's and use it in array, to make them readOnly - but the result is error -> "cannot read property 'readOnly' of null".
Can you give me a hint what I should change?

```<code>script language="javascript" type="text/javascript">
 $(document).ready(function () {
 $(function(){
     var index, len;
        $.get('/SomeList.txt', function(data){
            var SomeList = data.split('\n');
            for (index = 0, len = SomeList.length; index < len; index++) {
           document.getElementById(SomeList[index]).readOnly = true;
}
        });

    });

     });
     </script>
</code>```

and txt file contains name of input ID:

```<code>TextFieldName
TextFieldEmail
TextFieldDepartment
TextFieldOffice
</code>```

答:
Assuming you have some elements with the given IDs you must check if the element exists first before doing

```<code>document.getElementById(SomeList[index]).readOnly = true;
</code>```

so replace that line with

```<code>var myElement = document.getElementById(SomeList[index]);
if(myElement == null) {
    return;
}
myElement.readOnly = true;
</code>```

That should work like following example where the IDs come from an array and the second one will not mach because of xxxxx so it's not readonly. But all the others are.

var dataArray = [
  'TextFieldName',
  'TextFieldEmailxxxxx',
  'TextFieldDepartment',
  'TextFieldOffice'
];

dataArray.forEach(function(id){
    var myElement = document.getElementById(id);
    if(myElement == null) {
        return;
    }
    myElement.readOnly = true;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="TextFieldName" type="text">
<input id="TextFieldEmail" type="text">
<input id="TextFieldDepartment" type="text">
<input id="TextFieldOffice" type="text"></code>```

Title: getElementByID.readOnly in array

Body:
Im trying to create a list of input ID's and use it in array, to make them readOnly - but the result is error -> "cannot read property 'readOnly' of null".
Can you give me a hint what I should change?

script language="javascript" type="text/javascript">
 $(document).ready(function () {
 $(function(){
     var index, len;
        $.get('/SomeList.txt', function(data){
            var SomeList = data.split('\n');
            for (index = 0, len = SomeList.length; index < len; index++) {
           document.getElementById(SomeList[index]).readOnly = true;
}
        });

    });

     });
     </script>

and txt file contains name of input ID:

TextFieldName
TextFieldEmail
TextFieldDepartment
TextFieldOffice

Body:
Assuming you have some elements with the given IDs you must check if the element exists first before doing

document.getElementById(SomeList[index]).readOnly = true;

so replace that line with

var myElement = document.getElementById(SomeList[index]);
if(myElement == null) {
    return;
}
myElement.readOnly = true;

That should work like following example where the IDs come from an array and the second one will not mach because of xxxxx so it's not readonly. But all the others are.

var dataArray = [
  'TextFieldName',
  'TextFieldEmailxxxxx',
  'TextFieldDepartment',
  'TextFieldOffice'
];

dataArray.forEach(function(id){
    var myElement = document.getElementById(id);
    if(myElement == null) {
        return;
    }
    myElement.readOnly = true;
});

<input id="TextFieldName" type="text">
<input id="TextFieldEmail" type="text">
<input id="TextFieldDepartment" type="text">
<input id="TextFieldOffice" type="text">


问:
What is the meaning of ":"?
I have been watching some LinkedList videos to try and understand what it is. But I see a lot of people having code like

```<code>for(String x : model)
</code>```

Can anyone help me understand what ":" does in this code besides attaching x to "model" or is that all it does?

答:
It means the loop will iterate through each object of the list

String x declares a String named x

model is the list of String you want to iterate through

: is the operator making the compiler doing this operation.

You can read the for like this : For each String in model, use x as variable and do the following operations.

you can then use x to do the operations you want on each elements of the list

Title: What is the meaning of ":"?

Body:
I have been watching some LinkedList videos to try and understand what it is. But I see a lot of people having code like

for(String x : model)

Can anyone help me understand what ":" does in this code besides attaching x to "model" or is that all it does?


问:
Looks like hoisting is working in React Native with const
I noticed one interesting thing in react native. I thought that const and let does not support hoisting in ES6.
How is it possible to use const styles above its define?

```<code>    render() {
        const { repos } = this.state;
        const reposList = repos.map((rep, index) => {
            return (
                    <Text>{rep.name}</Text>
            )
        });

        return (
                <View style={styles.container}>  <-- styles should not be defined
                    {reposList}
                </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});
</code>```

Is it because of hoisting mechanism in React Native?

答: you have render defined in a class, the class is just defined not executed so it can see the styles you create below it. it's not really hoisting.</p>

Body:
I noticed one interesting thing in react native. I thought that const and let does not support hoisting in ES6.
How is it possible to use const styles above its define?

    render() {
        const { repos } = this.state;
        const reposList = repos.map((rep, index) => {
            return (
                    <Text>{rep.name}</Text>
            )
        });

        return (
                <View style={styles.container}>  <-- styles should not be defined
                    {reposList}
                </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});

Is it because of hoisting mechanism in React Native?


问:
Delayed messages in JMS queue
I have a question about a delay that happens intermittently in one queue. I'm using JMS over Weblogic 10.0.

So, the client sends a message to the server through the queue called RequestQueue.
The server responses to the client through the queue called ResponseQueue.
The response message is a 12-character Java String, a simple answer.

The average response time is 3 seconds. But, sometimes the response message is delayed and it arrives in... 2 minutes! The message seems to remain in the queue.
There is no error in logs, the response message always arrives, but about 10%, this delay happens, and I don't know why. I can't identify any pattern that explain this situation.

Could you tell me any suggestion about this?

Thanks in advance

答: The first thing i would check is whether the messages are produced later, or the messaging system does delay the messages after the sent operation. Therefor you can check the JMSTimestamp field in the Message header. Maybe you can just log the JMSTimestamp file of the Request and the Response message then you can focus your analysing on the part of the system where the delay seems to occur.

Title: Delayed messages in JMS queue


问:
Remove prefix of each line in a file and output to another file using sed
I have a source code file in which comments are prefixed with // (ie. double slashes and an empty space), I want to convert the source code into a document so I tried to cat file.c and pipe it to sed, the thinking is to replace "double slash and a space" if a line starts with it, with empty string, but it looks like the slash has some special meaning in sed, so what's the best way of constructing the sed arguments?

Thanks!

答:
If you want to remove the special meaning of / from sed then following may help you in same.

```<code>sed 's/^\/\/ //g'  Input_file
</code>```

So I am escaping / here by using \ before it, so it will be taken as a literal character rather than it's special meaning in code. Also if you are happy with above command's result then use -i to save the changes in Input_file itself. Hope this helps.

Body:
If you want to remove the special meaning of / from sed then following may help you in same.

sed 's/^\/\/ //g'  Input_file

So I am escaping / here by using \ before it, so it will be taken as a literal character rather than it's special meaning in code. Also if you are happy with above command's result then use -i to save the changes in Input_file itself. Hope this helps.


问:
How to bind OpenCV-contribute-modules to MATLAB?
I want to use OpenCV class(from contribute_modules) in MATLAB. I am trying to perform binding of OpenCV to MATLAB. It is ok when I use standard opencv interface. But I need to use a class xphoto from contribute modules. I have already built OpenCV with contribute-modules in CMake & Visual Studio 2010. It is working fine. I checked use MATLAB. MATLAB paths were found well.
I followed a tutorial  from Github.

I still have this error in MATLAB:

Building with 'Microsoft Visual C++ 2010'.
Error using mexOpenCV (line 120)
bm3d.cpp
C:\Users\Desktop\bm3d\bm3d.cpp(11) : fatal error C1083: Cannot open include file: 'opencv2/xphoto.hpp': No such file or directory

Could anyone help me please how I can do it ?

I would appreciate any help please.

答:
I'm several months late, but I'll answer here for posterity. mexOpenCV allows for -I , -l and -L flags, like what gcc allows. So, all you really need to do is to point to the libraries that you need in your CPP file using these flags. For example,

```<code>mexOpenCV getaruco.cpp -L~/opencv310/lib/ -lopencv_aruco.3.1.0 -I/usr/local/include
</code>```

will link against the aruco module that lives in ~/opencv310/lib and the corresponding header is in /usr/local/include. I'm sure there are equivalent flags on Windows as well.

See help mexOpenCV in MATLAB for more details.

Body:
I'm several months late, but I'll answer here for posterity. mexOpenCV allows for -I , -l and -L flags, like what gcc allows. So, all you really need to do is to point to the libraries that you need in your CPP file using these flags. For example,

mexOpenCV getaruco.cpp -L~/opencv310/lib/ -lopencv_aruco.3.1.0 -I/usr/local/include

will link against the aruco module that lives in ~/opencv310/lib and the corresponding header is in /usr/local/include. I'm sure there are equivalent flags on Windows as well.

See help mexOpenCV in MATLAB for more details.


问:
Is print in Haskell a pure function?
Is print in Haskell a pure function; why or why not? I'm thinking it's not, because it does not always return the same value as pure functions should.

答:
If you just read the Tag of pure-function (A function that always evaluates to the same result value given the same argument value(s) and that does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.) and then Think in the type of print:

```<code>putStrLn :: String -> IO ()
</code>```

You will find a trick there, it always returns IO (), so... No, it produces effects. So in terms of Referential Transparency is not pure
 For example, getLine returns IO String but it is also a pure function. (@interjay contribution), What I'm trying to say, is that the answer depends very close of the question:

On matter of value, IO () will always be the same IO () value for  the same input.

And

On matter of execution, it is not pure because the execution of that
IO () could have side effects (put an string in the screen, in this
case looks so innocent, but some IO could lunch nuclear bombs, and
then return the Int 42)

You could understand better with the nice approach of @Ben here:

"There are several ways to explain how you're "purely" manipulating
  the real world. One is to say that IO is just like a state monad, only
  the state being threaded through is the entire world outside your
  program;= (so your Stuff -> IO DBThing function really has an extra
  hidden argument that receives the world, and actually returns a
  DBThing along with another world; it's always called with different
  worlds, and that's why it can return different DBThing values even
  when called with the same Stuff). Another explanation is that an IO
  DBThing value is itself an imperative program; your Haskell program is
  a totally pure function doing no IO, which returns an impure program
  that does IO, and the Haskell runtime system (impurely) executes the
  program it returns."

And @Erik Allik:

So Haskell functions that return values of type IO a, are actually not
  the functions that are being executed at runtime — what gets executed
  is the IO a value itself. So these functions actually are pure but
  their return values represent non-pure computations.

You can found them here Understanding pure functions in Haskell with IO

ContentLicense: CC BY-SA 4.0

Title: Is print in Haskell a pure function?

Body:
If you just read the Tag of pure-function (A function that always evaluates to the same result value given the same argument value(s) and that does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.) and then Think in the type of print:

putStrLn :: String -> IO ()

You will find a trick there, it always returns IO (), so... No, it produces effects. So in terms of Referential Transparency is not pure
 For example, getLine returns IO String but it is also a pure function. (@interjay contribution), What I'm trying to say, is that the answer depends very close of the question:

On matter of value, IO () will always be the same IO () value for  the same input.

And

On matter of execution, it is not pure because the execution of that
IO () could have side effects (put an string in the screen, in this
case looks so innocent, but some IO could lunch nuclear bombs, and
then return the Int 42)

You could understand better with the nice approach of @Ben here:

"There are several ways to explain how you're "purely" manipulating
  the real world. One is to say that IO is just like a state monad, only
  the state being threaded through is the entire world outside your
  program;= (so your Stuff -> IO DBThing function really has an extra
  hidden argument that receives the world, and actually returns a
  DBThing along with another world; it's always called with different
  worlds, and that's why it can return different DBThing values even
  when called with the same Stuff). Another explanation is that an IO
  DBThing value is itself an imperative program; your Haskell program is
  a totally pure function doing no IO, which returns an impure program
  that does IO, and the Haskell runtime system (impurely) executes the
  program it returns."

And @Erik Allik:

So Haskell functions that return values of type IO a, are actually not
  the functions that are being executed at runtime — what gets executed
  is the IO a value itself. So these functions actually are pure but
  their return values represent non-pure computations.

You can found them here Understanding pure functions in Haskell with IO


问:
What exactly do pointers store? (C++)
I know that pointers store the address of the value that they point to, but if you display the value of a pointer directly to the screen, you get a hexadecimal number.  If the number is exactly what the pointer stores, then when saying

```<code>pA = pB; //both are pointers
</code>```

you're copying the address.  Then wouldn't there be a bigger overhead to using pointers when working with very small items like ints and bools?

答:
Let me start from the basics. First of all, you will have to know what variable are and how they are used.

Variables are basically memory locations(usually containing some values) and we use some identifier(i.e., variable names) to refer to that memory location and use the value present at that location.

For understanding it better, suppose we want the information from memory cells present at some location relative to the current variable. Can we use the identifier to extract information from nearby cells?
No. Because the identifier(variable name) will only give the value contained in that particular cell.

But, If somehow we can get the memory address at which this variable is present then we can easily move to nearby locations and use their information as well(at runtime).

This is where pointers come into play. They are used to store the location of that variable so that we can use the additional address information whenever required.

Syntax: To store the address of a variable we can simply use & (address-of) operator.

```<code>foo = &bar
</code>```

Here foo stores the address of variable bar.

Now, what if we want to know the value present at that address?

For that, we can simply use the * (dereference) operator.

```<code>value = *foo
</code>```

Now that we have to store the address of a variable, we'll be needing the memory the same way as we need in case of a variable. This means pointers are also stored in the memory the same way as other variables, so just like in case of variables, we can also store the address of a pointer into yet another pointer.

Title: What exactly do pointers store? (C++)

Body:
I know that pointers store the address of the value that they point to, but if you display the value of a pointer directly to the screen, you get a hexadecimal number.  If the number is exactly what the pointer stores, then when saying

pA = pB; //both are pointers

you're copying the address.  Then wouldn't there be a bigger overhead to using pointers when working with very small items like ints and bools?

Body:
Let me start from the basics. First of all, you will have to know what variable are and how they are used.

Variables are basically memory locations(usually containing some values) and we use some identifier(i.e., variable names) to refer to that memory location and use the value present at that location.

For understanding it better, suppose we want the information from memory cells present at some location relative to the current variable. Can we use the identifier to extract information from nearby cells?
No. Because the identifier(variable name) will only give the value contained in that particular cell.

But, If somehow we can get the memory address at which this variable is present then we can easily move to nearby locations and use their information as well(at runtime).

This is where pointers come into play. They are used to store the location of that variable so that we can use the additional address information whenever required.

Syntax: To store the address of a variable we can simply use & (address-of) operator.

foo = &bar

Here foo stores the address of variable bar.

Now, what if we want to know the value present at that address?

For that, we can simply use the * (dereference) operator.

value = *foo

Now that we have to store the address of a variable, we'll be needing the memory the same way as we need in case of a variable. This means pointers are also stored in the memory the same way as other variables, so just like in case of variables, we can also store the address of a pointer into yet another pointer.


问:
Using libraries in Eclipse without altering classpath
Edit:

How can I included packages in the .classpath that are downloaded at compile-time by gradlew and use them in Eclipse before compile-time such that my .classpath doesnt include local file paths from my personal computer?

I would like to use the org.apache.commons.cli package, but do so without altering the .classpath file. I'm using the gradlew to build my project, and in the build.gradle file is:

```<code>dependencies {
    compile 'commons-cli:commons-cli:20040117.000000'
    compile 'com.google.code.gson:gson:2.8.2'
    testCompile "junit:junit:4.11"
}
</code>```

So at compile-time, the necessary libraries are managed. However, without them added to Eclipse, using them seems to be impossible as they cannot be resolved.

Question:

If using build.gradle to manage project dependencies, is there a way to use them in Eclipse without going to the project's build path and adding external jar's? If not, what is the general practice for situations like this, where a library is needed to be use, but I dont want my local file path stored in the .classpath, where a user may not have the same jar in the same file path?

答: You should install and use Eclipse BuildShip to properly work with gradle projects.</p>

Body:
Edit:

How can I included packages in the .classpath that are downloaded at compile-time by gradlew and use them in Eclipse before compile-time such that my .classpath doesnt include local file paths from my personal computer?

I would like to use the org.apache.commons.cli package, but do so without altering the .classpath file. I'm using the gradlew to build my project, and in the build.gradle file is:

dependencies {
    compile 'commons-cli:commons-cli:20040117.000000'
    compile 'com.google.code.gson:gson:2.8.2'
    testCompile "junit:junit:4.11"
}

So at compile-time, the necessary libraries are managed. However, without them added to Eclipse, using them seems to be impossible as they cannot be resolved.

Question:

If using build.gradle to manage project dependencies, is there a way to use them in Eclipse without going to the project's build path and adding external jar's? If not, what is the general practice for situations like this, where a library is needed to be use, but I dont want my local file path stored in the .classpath, where a user may not have the same jar in the same file path?


问:
wsimport creates unexpected rest code
I have a wsdl with the following type fragment modeling a self association on an organisationunit:

```<code>...<xs:complexType name="OrganisationUnitBIAssocType">
 <xs:complexContent>
  <xs:extension base = "tns:OrgUnitBIType">
   <xs:sequence>
     <xs:element name ="ParentUnit" minOccurs="0" type="tns:OrgUnitBIType"/>
   </xs:sequence>
  </xs:extension>
 </xs:complexContent>
</xs:complexType>
<xs:complexType name="OrgUnitBIType">
 <xs:complexContent>
    <xs:extension base="tns:refableWebServiceParameterType">
      <xs:sequence>
       <xs:element name="Oid" type="xs:long"/>
       <xs:element name="NAme" type="xs:String"/>
      </xs:sequence>
    </xs:extension>
   </xs:complexContent>
</xs:complexType>...
</code>```

The wsimport tool generates the following two Java classes for the organisationunit and the association:

```<code>@XmlAccessorType(XmlAccessType.Field)
@XmlType(name = "OrgUnitBIType", porpOrder = {"rest"})
@XmlSeeAlso({OrganisationUnitBIAssocType.class})

public class OrgUnitBIType extends RefableWebServiceParameterType
{
 @XmlElementRefs({
   @XmlElementRefs(name = "Name", type =JAXBElement.class, required = false),
   @XmlElementRefs(name = "Oid", type =JAXBElement.class, required = false)
    })
 protected List<JAXBElement<? extends Serializable>> rest;
 if(rest == null) {`
    rest = new ArrayList<JAXBElement<? extends Serializable>>();`
 }
 return this.rest;`
 }
}
@XmlAccessorType(XmlAccessType.Field)
@XmlType(name = "OrganisationUnitBIAssocType", porpOrder = {"rest"})
public class OrganisationUnitBIAssocType extends OrgUnitBIType {}
</code>```

I am wondering why these JAXBElements appear. I would prefer code having
getters and setters in a JAX-WS style without the getRest methods.

Does anybody know how to achieve this?

答:
```<code>protected List<JAXBElement<? extends Serializable>> rest;
</code>```

Check for duplicate elements with the same name. wsimport generates a list instead of individual getter and setter if any of the elements are repeated.

Title: wsimport creates unexpected rest code

Body:
I have a wsdl with the following type fragment modeling a self association on an organisationunit:

...<xs:complexType name="OrganisationUnitBIAssocType">
 <xs:complexContent>
  <xs:extension base = "tns:OrgUnitBIType">
   <xs:sequence>
     <xs:element name ="ParentUnit" minOccurs="0" type="tns:OrgUnitBIType"/>
   </xs:sequence>
  </xs:extension>
 </xs:complexContent>
</xs:complexType>
<xs:complexType name="OrgUnitBIType">
 <xs:complexContent>
    <xs:extension base="tns:refableWebServiceParameterType">
      <xs:sequence>
       <xs:element name="Oid" type="xs:long"/>
       <xs:element name="NAme" type="xs:String"/>
      </xs:sequence>
    </xs:extension>
   </xs:complexContent>
</xs:complexType>...

The wsimport tool generates the following two Java classes for the organisationunit and the association:

@XmlAccessorType(XmlAccessType.Field)
@XmlType(name = "OrgUnitBIType", porpOrder = {"rest"})
@XmlSeeAlso({OrganisationUnitBIAssocType.class})

public class OrgUnitBIType extends RefableWebServiceParameterType
{
 @XmlElementRefs({
   @XmlElementRefs(name = "Name", type =JAXBElement.class, required = false),
   @XmlElementRefs(name = "Oid", type =JAXBElement.class, required = false)
    })
 protected List<JAXBElement<? extends Serializable>> rest;
 if(rest == null) {`
    rest = new ArrayList<JAXBElement<? extends Serializable>>();`
 }
 return this.rest;`
 }
}
@XmlAccessorType(XmlAccessType.Field)
@XmlType(name = "OrganisationUnitBIAssocType", porpOrder = {"rest"})
public class OrganisationUnitBIAssocType extends OrgUnitBIType {}

I am wondering why these JAXBElements appear. I would prefer code having
getters and setters in a JAX-WS style without the getRest methods.

Does anybody know how to achieve this?

Body:
protected List<JAXBElement<? extends Serializable>> rest;

Check for duplicate elements with the same name. wsimport generates a list instead of individual getter and setter if any of the elements are repeated.


问:
How can I display the single record from a list of records

this my model class.  yes my model class have collection properties

I want to iterate loop only once when user login and only display the of that loggedin user

Blockquote

```<code>    [Table("Booking")]
    public partial class Booking
    {
     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Booking()
    {
        Cancels = new HashSet<Cancel>();
    }

    [Key]
    [Column("BookingId")]
    [Display(Name = "Booking Id")]
    [Required(ErrorMessage = "Booking Id is required...")]
    public int BookingId { get; set; }

    [Column("BookingStartDateandTime")]
    [Display(Name = "Booking Start Date and Time"), Required(ErrorMessage = "Booking Start Date and Time is reqired...")]
    public DateTime BookingStartDateandTime { get; set; }

    [Column("BookingEndDateandTime")]
    [Display(Name = "Booking End Date and Time"), Required(ErrorMessage = "Booking End Date and Time is reqired...")]
    public DateTime BookingEndDateandTime { get; set; }

    [Column("UserContactNo")]
    [Required(ErrorMessage = "User Contact No is required..."), Display(Name = "User Contact No")]
    [StringLength(50)]
    public string UserContactNo { get; set; }

    [Column("UserStartingLoaction")]
    [Required(ErrorMessage = "User Starting Loaction is required..."), Display(Name = "User Starting Loaction")]
    public string UserStartingLoaction { get; set; }

    [Column("UserDistination")]
    [Required(ErrorMessage = "User Distination is required..."), Display(Name = "User Distination")]
    public string UserDistination { get; set; }

    [Column("StatusId")]
    [Display(Name = "StatusId")]
    public int? StatusId { get; set; }

    public virtual BookingStatus BookingStatus { get; set; }

    [Column("TaxiId")]
    [Display(Name = "Taxi Name")]
    public int? TaxiId { get; set; }

    public virtual Taxi Taxi { get; set; }

    [Column("UserId")]
    [Display(Name = "User Id")]
    public int? UserId { get; set; }

    public virtual UserAccount UserAccount { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Cancel> Cancels { get; set; }
}
</code>```

}

I Want to display the booking record of that user who is currently loggedIn    not the booking record of all users

What can I do with foreach loop to display the loggedin user record

```<code>     if (Session["LoginRole"].ToString() == "User"
      &&Session["UserId"].ToString() ==
   Model.FirstOrDefault().UserId.ToString())
  {
   <table class="table">
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.BookingStatus.Status)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Taxi.TaxiName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UserAccount.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.BookingStartDateandTime)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.BookingEndDateandTime)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UserContactNo)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UserStartingLoaction)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UserDistination)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.BookingId})|
            @Html.ActionLink("Details", "Details", new { id = item.BookingId }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.BookingId })
         </td>
     </tr>
 }

</table>
}
</code>```

this is the controller

```<code>public ActionResult Index()
{
    var bookings = db.Bookings.Include(u => u.UserAccount).Include(t =>
t.Taxi).Include(s => s.BookingStatus);
    return View(db.Bookings.ToList());
</code>```

答:
An Index() action is typically used to display a collection. You've got a link to a Details() action which is typically where you display a single record. So you should have a details action:

```<code>public ActionResult Details(int bookingId)
{
    var booking = db.Bookings
        .Include(u => u.UserAccount)
        .Include(t => t.Taxi)
        .Include(s => s.BookingStatus)
        .Single(b => b.BookingId = bookingId);
    return View(booking);
}
</code>```

Then you would create a Details view similar to this:

```<code>@model Booking
@{
    ViewBag.Title = "Booking Details";
}
<h2>Booking Details</h2>
     <div>
        <dt>Status</dt>
        <dd>
           @Html.DisplayFor(model=> model.BookingStatus.Status)
        </dd>
        <dt>Taxi Name</dt>
        <dd>
            @Html.DisplayFor(model=> model.Taxi.TaxiName)
        </dd>

        [repeat for other fields]

        </dl>
    </div>
}
</code>```

Body:
this my model class.  yes my model class have collection properties

I want to iterate loop only once when user login and only display the of that loggedin user

Blockquote

    [Table("Booking")]
    public partial class Booking
    {
     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Booking()
    {
        Cancels = new HashSet<Cancel>();
    }

    [Key]
    [Column("BookingId")]
    [Display(Name = "Booking Id")]
    [Required(ErrorMessage = "Booking Id is required...")]
    public int BookingId { get; set; }

    [Column("BookingStartDateandTime")]
    [Display(Name = "Booking Start Date and Time"), Required(ErrorMessage = "Booking Start Date and Time is reqired...")]
    public DateTime BookingStartDateandTime { get; set; }

    [Column("BookingEndDateandTime")]
    [Display(Name = "Booking End Date and Time"), Required(ErrorMessage = "Booking End Date and Time is reqired...")]
    public DateTime BookingEndDateandTime { get; set; }

    [Column("UserContactNo")]
    [Required(ErrorMessage = "User Contact No is required..."), Display(Name = "User Contact No")]
    [StringLength(50)]
    public string UserContactNo { get; set; }

    [Column("UserStartingLoaction")]
    [Required(ErrorMessage = "User Starting Loaction is required..."), Display(Name = "User Starting Loaction")]
    public string UserStartingLoaction { get; set; }

    [Column("UserDistination")]
    [Required(ErrorMessage = "User Distination is required..."), Display(Name = "User Distination")]
    public string UserDistination { get; set; }

    [Column("StatusId")]
    [Display(Name = "StatusId")]
    public int? StatusId { get; set; }

    public virtual BookingStatus BookingStatus { get; set; }

    [Column("TaxiId")]
    [Display(Name = "Taxi Name")]
    public int? TaxiId { get; set; }

    public virtual Taxi Taxi { get; set; }

    [Column("UserId")]
    [Display(Name = "User Id")]
    public int? UserId { get; set; }

    public virtual UserAccount UserAccount { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Cancel> Cancels { get; set; }
}

}

I Want to display the booking record of that user who is currently loggedIn    not the booking record of all users

What can I do with foreach loop to display the loggedin user record

     if (Session["LoginRole"].ToString() == "User"
      &&Session["UserId"].ToString() ==
   Model.FirstOrDefault().UserId.ToString())
  {

@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.BookingStatus.Status)

            @Html.DisplayFor(modelItem => item.Taxi.TaxiName)

            @Html.DisplayFor(modelItem => item.UserAccount.FirstName)

            @Html.DisplayFor(modelItem => item.BookingStartDateandTime)

            @Html.DisplayFor(modelItem => item.BookingEndDateandTime)

            @Html.DisplayFor(modelItem => item.UserContactNo)

            @Html.DisplayFor(modelItem => item.UserStartingLoaction)

            @Html.DisplayFor(modelItem => item.UserDistination)

            @Html.ActionLink("Edit", "Edit", new { id = item.BookingId})|
            @Html.ActionLink("Details", "Details", new { id = item.BookingId }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.BookingId })

 }

}

this is the controller

public ActionResult Index()
{
    var bookings = db.Bookings.Include(u => u.UserAccount).Include(t =>
t.Taxi).Include(s => s.BookingStatus);
    return View(db.Bookings.ToList());

Body:
An Index() action is typically used to display a collection. You've got a link to a Details() action which is typically where you display a single record. So you should have a details action:

public ActionResult Details(int bookingId)
{
    var booking = db.Bookings
        .Include(u => u.UserAccount)
        .Include(t => t.Taxi)
        .Include(s => s.BookingStatus)
        .Single(b => b.BookingId = bookingId);
    return View(booking);
}

Then you would create a Details view similar to this:

@model Booking
@{
    ViewBag.Title = "Booking Details";
}
<h2>Booking Details</h2>
     <div>
        <dt>Status</dt>
        <dd>
           @Html.DisplayFor(model=> model.BookingStatus.Status)
        </dd>
        <dt>Taxi Name</dt>
        <dd>
            @Html.DisplayFor(model=> model.Taxi.TaxiName)
        </dd>

        [repeat for other fields]

        </dl>
    </div>
}


问:
Application user and relation between other tables (entities)
I'm trying to associate Application user with UserTask application table. But I get the bellow error

InvalidOperationException: Unable to determine the relationship represented by navigation property 'ApplicationUser.UserTask' of type 'UserTask'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'

I use NetCore 2.0.3

```<code>public class UserTask
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int UserTaskID { get; set; }

        public string Description { get; set; }

        [ForeignKey("OwnerUserID")]
        public string TaskOwnerId { get; set; }

        [ForeignKey("ExecutorUserID")]
        public string TaskExecutorId { get; set; }

        public virtual ApplicationUser OwnerUserID { get; set; }
        public virtual ApplicationUser ExecutorUserID { get; set; }
    }

 public class ApplicationUser : IdentityUser
    {
       [ForeignKey("UserTaskID")]
       public int UserTaskID { get; set; }

       public UserTask UserTask { get; set; }
    }
</code>```

controler

```<code>public IActionResult Create()
        {
            ViewData["TaskOwnerId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name");

            ViewData["TaskExecutorId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name");

            return View();
        }

        // POST: UserTasks/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("UserTaskID,Description,TaskOwnerId,TaskExecutorId")] UserTask userTask)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userTask);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["TaskOwnerId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name", userTask.TaskOwnerId);

            ViewData["TaskExecutorId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name", userTask.TaskExecutorId);

            return View(userTask);
        }
</code>```

and the view

```<code><div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TaskOwnerId" class="control-label"></label>
                 <select asp-for="TaskOwnerId" class="form-control" asp-items="ViewBag.TaskOwnerId"></select>
            </div>
            <div class="form-group">
                <label asp-for="TaskExecutorId" class="control-label"></label>
                <select asp-for="TaskExecutorId" class="form-control" asp-items="ViewBag.TaskExecutorId"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TaskOwnerId" class="control-label"></label>
                 <select asp-for="TaskOwnerId" class="form-control" asp-items="ViewBag.TaskOwnerId"></select>
            </div>
            <div class="form-group">
                <label asp-for="TaskExecutorId" class="control-label"></label>
                <select asp-for="TaskExecutorId" class="form-control" asp-items="ViewBag.TaskExecutorId"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>
</code>```

Could you help me?

答:
Try like

```<code>public class UserTask
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserTaskID { get; set; }

    public string Description { get; set; }

    public ApplicationUser ApplicationUser {get; set; }
}
public class ApplicationUser : IdentityUser
{
   public ICollection<UserTask> UserTask { get; set; }
}
</code>```

And in ApplicationDbContext class

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder){
modelBuilder.Entity<ApplicationUser>()
    .HasMany(a => a.UserTask)
    .WithOne(b => b.ApplicationUser);}
</code>```

Body:
I'm trying to associate Application user with UserTask application table. But I get the bellow error

InvalidOperationException: Unable to determine the relationship represented by navigation property 'ApplicationUser.UserTask' of type 'UserTask'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'

I use NetCore 2.0.3

public class UserTask
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int UserTaskID { get; set; }

        public string Description { get; set; }

        [ForeignKey("OwnerUserID")]
        public string TaskOwnerId { get; set; }

        [ForeignKey("ExecutorUserID")]
        public string TaskExecutorId { get; set; }

        public virtual ApplicationUser OwnerUserID { get; set; }
        public virtual ApplicationUser ExecutorUserID { get; set; }
    }

 public class ApplicationUser : IdentityUser
    {
       [ForeignKey("UserTaskID")]
       public int UserTaskID { get; set; }

       public UserTask UserTask { get; set; }
    }

controler

public IActionResult Create()
        {
            ViewData["TaskOwnerId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name");

            ViewData["TaskExecutorId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name");

            return View();
        }

        // POST: UserTasks/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("UserTaskID,Description,TaskOwnerId,TaskExecutorId")] UserTask userTask)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userTask);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["TaskOwnerId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name", userTask.TaskOwnerId);

            ViewData["TaskExecutorId"] = new SelectList(_userManager.Users.ToList(), "Id", "Name", userTask.TaskExecutorId);

            return View(userTask);
        }

and the view

        <form asp-action="Create">

                <input asp-for="Description" class="form-control" />

                 <select asp-for="TaskOwnerId" class="form-control" asp-items="ViewBag.TaskOwnerId"></select>

                <select asp-for="TaskExecutorId" class="form-control" asp-items="ViewBag.TaskExecutorId"></select>

                <input type="submit" value="Create" class="btn btn-default" />

        </form>

        <form asp-action="Create">

                <input asp-for="Description" class="form-control" />

                 <select asp-for="TaskOwnerId" class="form-control" asp-items="ViewBag.TaskOwnerId"></select>

                <select asp-for="TaskExecutorId" class="form-control" asp-items="ViewBag.TaskExecutorId"></select>

                <input type="submit" value="Create" class="btn btn-default" />

        </form>

Could you help me?

Body:
Try like

public class UserTask
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserTaskID { get; set; }

    public string Description { get; set; }

    public ApplicationUser ApplicationUser {get; set; }
}
public class ApplicationUser : IdentityUser
{
   public ICollection<UserTask> UserTask { get; set; }
}

And in ApplicationDbContext class

protected override void OnModelCreating(ModelBuilder modelBuilder){
modelBuilder.Entity<ApplicationUser>()
    .HasMany(a => a.UserTask)
    .WithOne(b => b.ApplicationUser);}