问:
Load Balancing of values into 8 "silos"
I've got a problem I can't seem to crack. It's not that easy to explain so I'll do my best :

I have a really big array of values I have already sorted :

[ 2, 8, 26, ..., 1456, 1879, ..., 7812, 9614, ..., 20 408, 26 584 ]

I have 8 empty "silos" (kind of like an array) with unlimited capacity.

My goal is to fill those silo with all my values in order to make them as balanced as possible.
When I say "balanced", I mean that I want the sum of all the values in a silo to be almost equal to one another.

For example, if my silo 1 has a total sum of 52 000 and my silo 8 has a sum of 30 000 then it's not good. I'd rather have something like 41 000 and 43 500 if possible.

I've already done a round Robin, but it doesn't seem precise enough because I get a quite big difference between my silos.
I've looked up bin-packing also but it doesn't seem appropriate to me.

Thank you for any help or advice you may provide!

答:
Optimization problems are never easy, but since you want to minimize the deviation from the average you simply iterate your values from highest to lowest value and add it to the silo with the lowest sum. That way you don't waste too much time on optimization and should (depending on your values) have a relatively good result.

```<code>// Generate some random data
int[] values = new int[1000];

Random r = new Random();

for (int i = 0; i < values.Length; i++)
{
    values[i] = r.Next(1, 30000);
}

// Initialize silos
const int siloCount = 8;
List<int>[] result = new List<int>[siloCount];
for (int i = 0; i < siloCount; i++)
{
    result[i] = new List<int>();
}

int[] sums = new int[siloCount];
int[] indices = Enumerable.Range(0, siloCount).ToArray();

// Iterate all values in descending order
foreach (int value in values.OrderByDescending(i => i).ToList())
{
    // Find silo with lowest sum (or one of them)
    int siloIndex = indices.First(i => sums[i] == sums.Min());

    // Add to collection and sum - so we don't have to call .Sum() every iteration
    sums[siloIndex] += value;
    result[siloIndex].Add(value);
}

Debug.WriteLine(String.Join("\r\n", result.Select(s => s.Sum())));
</code>```

.Net Fiddle

Title: Load Balancing of values into 8 "silos"

Body:
Optimization problems are never easy, but since you want to minimize the deviation from the average you simply iterate your values from highest to lowest value and add it to the silo with the lowest sum. That way you don't waste too much time on optimization and should (depending on your values) have a relatively good result.

// Generate some random data
int[] values = new int[1000];

Random r = new Random();

for (int i = 0; i < values.Length; i++)
{
    values[i] = r.Next(1, 30000);
}

// Initialize silos
const int siloCount = 8;
List<int>[] result = new List<int>[siloCount];
for (int i = 0; i < siloCount; i++)
{
    result[i] = new List<int>();
}

int[] sums = new int[siloCount];
int[] indices = Enumerable.Range(0, siloCount).ToArray();

// Iterate all values in descending order
foreach (int value in values.OrderByDescending(i => i).ToList())
{
    // Find silo with lowest sum (or one of them)
    int siloIndex = indices.First(i => sums[i] == sums.Min());

    // Add to collection and sum - so we don't have to call .Sum() every iteration
    sums[siloIndex] += value;
    result[siloIndex].Add(value);
}

Debug.WriteLine(String.Join("\r\n", result.Select(s => s.Sum())));

.Net Fiddle


来源: stackexchange

问:
Error MSB4019 when using the MSBuild API while MSBuild.exe works fine
I'm developing a C# application that will use the MSBuild API to build a C++ project. The C++ project I am testing with is a completely empty project. When I try to compile it with MSBuild.exe via the command line it works fine. I use

```<code>MSBuild.exe C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj /p:Platform=x86
</code>```

But when I instead use the MSBuild API as such:

```<code>Dictionary<string, string> globalProperty = new Dictionary<string, string> { { "Configuration", "Debug" }, { "Platform", "x86" } };
BuildParameters buildParameters = new BuildParameters(new ProjectCollection()) { Loggers = new List<ILogger> { new ConsoleLogger(LoggerVerbosity.Detailed) } };
BuildRequestData buildRequest = new BuildRequestData(@"C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj", globalProperty, "4.0", new[] { "Build" }, null);
BuildResult buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);
</code>```

I get the following error:

```<code>Building with tools version "15.0".
C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj(27,3): error MSB4019: The imported project "C:\Microsoft.Cpp.Default.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.

Done building project "Project1.vcxproj" -- FAILED.
</code>```

Furthermore, when I try this with the MSBuild in Windows\Framework64\v4.0* I do get the same error as opposed to when I use the MSBuild located in Program Files (x86)\Microsoft Visual Studio 2017\Community\MSBuild\15.0\Bin\amd64

To make sure I'm using 15.0 I have added he following to my app.config but it does not seem to make any difference:

```<code><runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.Build.Framework" culture="neutral"/>
      <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="15.0.0.0"/>
    </dependentAssembly>
  </assemblyBinding>
</runtime>
</code>```

What might I be doing wrong/misunderstanding here?

Update: I found I had references to Microsoft.Build.x of version 4.x. Deleted the references and replaced them with v15.x. The build now fails with 0 errors and 0 warnings. See output:

```<code>Build started 09/11/2017 16:36:04.
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual
Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Trying to import C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\$(MSBuildToolsVersion)\Microsoft.Common.props using extensions path C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild
Property reassignment: $(MSBuildProjectExtensionsPath)="C:\Users\MyName\source\repos\Project1\Project1\obj\" (previous value: "obj\") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Microsoft.Common.props (58,5)
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Trying to import C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\$(MSBuildToolsVersion)\Imports\Microsoft.Common.props\ImportBefore\* using extensions path C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Property reassignment: $(Platform)="Win32" (previous value: "x86") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Default.props (30,5)
Property reassignment: $(PlatformToolset)="v100" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Platforms\Win32\Platform.default.props (26,5)
Property reassignment: $(PlatformToolset)="v141" (previous value: "v100") at C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj (31,5)
Property reassignment: $(_PlatformFolder)="C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Platforms\Win32\" (previous value: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\\Platforms\Win32\") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Platforms\Win32\Platform.props (15,5)
Property reassignment: $(WindowsSdkDir_10)="C:\Program Files (x86)\Windows Kits\10\" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.WindowsSDK.props (18,5)
Property reassignment: $(TargetExt)=".exe" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (29,5)
Property reassignment: $(WindowsSdkDir_81)="C:\Program Files (x86)\Windows Kits\8.1\" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (55,5)
Property reassignment: $(NETFXKitsDir)="C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (163,5)
Property reassignment: $(NETFXSDKDir)="C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (165,5)
Property reassignment: $(WindowsSDK_ExecutablePath_x86)="C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x86;;C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools" (previous value: "C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x86;") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (169,5)
Property reassignment: $(WindowsSDK_ExecutablePath_x64)="C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x64;;C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64" (previous value: "C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x64;") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (170,5)
Property reassignment: $(_PropertySheetDisplayName)="Multi-byte Character Support" (previous value: "Core Windows Libraries") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.MultiByteCharSupport.props (15,5)
Property reassignment: $(_PropertySheetDisplayName)="Application" (previous value: "Multi-byte Character Support") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Application.props (15,5)
Property reassignment: $(ExtensionsToDeleteOnClean)="*.cdf;*.cache;*.obj;*.obj.enc;*.ilk;*.ipdb;*.iobj;*.resources;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pgc;*.pgd;*.meta;*.tlog;*.manifest;*.res;*.pch;*.exp;*.idb;*.rep;*.xdc;*.pdb;*_manifest.rc;*.bsc;*.sbr;*.xml;*.metagen;*.bi;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.exe.manifest;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.tlb;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.pdb;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.exe;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.bsc;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.ilk;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.exe.intermediate.manifest" (previous value: "*.cdf;*.cache;*.obj;*.obj.enc;*.ilk;*.ipdb;*.iobj;*.resources;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pgc;*.pgd;*.meta;*.tlog;*.manifest;*.res;*.pch;*.exp;*.idb;*.rep;*.xdc;*.pdb;*_manifest.rc;*.bsc;*.sbr;*.xml;*.metagen;*.bi") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.CppCommon.targets (35,5)
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Trying to import C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\$(MSBuildToolsVersion)\Microsoft.Common.targets\ImportBefore\* using extensions path C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Property reassignment: $(MSBuildAllProjects)=";C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.Common.targets;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.NETFramework.CurrentVersion.props" (previous value: ";C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.Common.targets") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.NETFramework.CurrentVersion.props (29,5)
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
__________________________________________________
Project "C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj"
(Build target(s)):

Building with tools version "15.0".

Done building project "Project1.vcxproj" -- FAILED.
The thread 0x219c has exited with code 0 (0x0).

Build FAILED.
    0 Warning(s)
    0 Error(s)
</code>```

答:
As Leo-MSFT pointed out in a comment to my question, there is a bug in Microsoft.Build version 15.x (see https://github.com/Microsoft/msbuild/issues/2369). The solution - or rather, temporary work-around - is to add the following to the config file as linked in the post (from: https://github.com/IntelliTect/Coalesce/commit/4d9024ba441af39c8e77e5d30174e67317ed91e0):

```<code><runtime>
<!-- TODO: We can probably remove this once MSBuild issue 2369 is fixed: https://github.com/Microsoft/msbuild/issues/2369#issuecomment-323139518-->
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Build.Utilities.Core" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" />
    <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="15.1.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Build.Framework" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" />
    <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="15.1.0.0" />
  </dependentAssembly>
</assemblyBinding>
</code>```

This fix works for Visual Studio 2017 version 15.3.

ContentLicense: CC BY-SA 3.0

Body:
I'm developing a C# application that will use the MSBuild API to build a C++ project. The C++ project I am testing with is a completely empty project. When I try to compile it with MSBuild.exe via the command line it works fine. I use

MSBuild.exe C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj /p:Platform=x86

But when I instead use the MSBuild API as such:

Dictionary<string, string> globalProperty = new Dictionary<string, string> { { "Configuration", "Debug" }, { "Platform", "x86" } };
BuildParameters buildParameters = new BuildParameters(new ProjectCollection()) { Loggers = new List<ILogger> { new ConsoleLogger(LoggerVerbosity.Detailed) } };
BuildRequestData buildRequest = new BuildRequestData(@"C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj", globalProperty, "4.0", new[] { "Build" }, null);
BuildResult buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);

I get the following error:

Building with tools version "15.0".
C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj(27,3): error MSB4019: The imported project "C:\Microsoft.Cpp.Default.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.

Done building project "Project1.vcxproj" -- FAILED.

Furthermore, when I try this with the MSBuild in Windows\Framework64\v4.0* I do get the same error as opposed to when I use the MSBuild located in Program Files (x86)\Microsoft Visual Studio 2017\Community\MSBuild\15.0\Bin\amd64

To make sure I'm using 15.0 I have added he following to my app.config but it does not seem to make any difference:

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.Build.Framework" culture="neutral"/>
      <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="15.0.0.0"/>
    </dependentAssembly>
  </assemblyBinding>
</runtime>

What might I be doing wrong/misunderstanding here?

Update: I found I had references to Microsoft.Build.x of version 4.x. Deleted the references and replaced them with v15.x. The build now fails with 0 errors and 0 warnings. See output:

Build started 09/11/2017 16:36:04.
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual
Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Trying to import C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\$(MSBuildToolsVersion)\Microsoft.Common.props using extensions path C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild
Property reassignment: $(MSBuildProjectExtensionsPath)="C:\Users\MyName\source\repos\Project1\Project1\obj\" (previous value: "obj\") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Microsoft.Common.props (58,5)
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Trying to import C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\$(MSBuildToolsVersion)\Imports\Microsoft.Common.props\ImportBefore\* using extensions path C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Property reassignment: $(Platform)="Win32" (previous value: "x86") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Default.props (30,5)
Property reassignment: $(PlatformToolset)="v100" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Platforms\Win32\Platform.default.props (26,5)
Property reassignment: $(PlatformToolset)="v141" (previous value: "v100") at C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj (31,5)
Property reassignment: $(_PlatformFolder)="C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Platforms\Win32\" (previous value: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\\Platforms\Win32\") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Platforms\Win32\Platform.props (15,5)
Property reassignment: $(WindowsSdkDir_10)="C:\Program Files (x86)\Windows Kits\10\" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.WindowsSDK.props (18,5)
Property reassignment: $(TargetExt)=".exe" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (29,5)
Property reassignment: $(WindowsSdkDir_81)="C:\Program Files (x86)\Windows Kits\8.1\" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (55,5)
Property reassignment: $(NETFXKitsDir)="C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (163,5)
Property reassignment: $(NETFXSDKDir)="C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\" (previous value: "") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (165,5)
Property reassignment: $(WindowsSDK_ExecutablePath_x86)="C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x86;;C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools" (previous value: "C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x86;") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (169,5)
Property reassignment: $(WindowsSDK_ExecutablePath_x64)="C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x64;;C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64" (previous value: "C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\x64;") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Common.props (170,5)
Property reassignment: $(_PropertySheetDisplayName)="Multi-byte Character Support" (previous value: "Core Windows Libraries") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.MultiByteCharSupport.props (15,5)
Property reassignment: $(_PropertySheetDisplayName)="Application" (previous value: "Multi-byte Character Support") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Application.props (15,5)
Property reassignment: $(ExtensionsToDeleteOnClean)="*.cdf;*.cache;*.obj;*.obj.enc;*.ilk;*.ipdb;*.iobj;*.resources;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pgc;*.pgd;*.meta;*.tlog;*.manifest;*.res;*.pch;*.exp;*.idb;*.rep;*.xdc;*.pdb;*_manifest.rc;*.bsc;*.sbr;*.xml;*.metagen;*.bi;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.exe.manifest;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.tlb;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.pdb;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.exe;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.bsc;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.ilk;C:\Users\MyName\source\repos\Project1\Project1\Debug\Project1.exe.intermediate.manifest" (previous value: "*.cdf;*.cache;*.obj;*.obj.enc;*.ilk;*.ipdb;*.iobj;*.resources;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pgc;*.pgd;*.meta;*.tlog;*.manifest;*.res;*.pch;*.exp;*.idb;*.rep;*.xdc;*.pdb;*_manifest.rc;*.bsc;*.sbr;*.xml;*.metagen;*.bi") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.CppCommon.targets (35,5)
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Trying to import C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\$(MSBuildToolsVersion)\Microsoft.Common.targets\ImportBefore\* using extensions path C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
Property reassignment: $(MSBuildAllProjects)=";C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.Common.targets;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.NETFramework.CurrentVersion.props" (previous value: ";C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.Common.targets") at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.NETFramework.CurrentVersion.props (29,5)
Search paths being used for $(MSBuildExtensionsPath) are C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild;$(MSBuildProgramFiles32)\MSBuild
__________________________________________________
Project "C:\Users\MyName\source\repos\Project1\Project1\Project1.vcxproj"
(Build target(s)):

Building with tools version "15.0".

Done building project "Project1.vcxproj" -- FAILED.
The thread 0x219c has exited with code 0 (0x0).

Build FAILED.
    0 Warning(s)
    0 Error(s)

Body:
As Leo-MSFT pointed out in a comment to my question, there is a bug in Microsoft.Build version 15.x (see https://github.com/Microsoft/msbuild/issues/2369). The solution - or rather, temporary work-around - is to add the following to the config file as linked in the post (from: https://github.com/IntelliTect/Coalesce/commit/4d9024ba441af39c8e77e5d30174e67317ed91e0):

<runtime>
<!-- TODO: We can probably remove this once MSBuild issue 2369 is fixed: https://github.com/Microsoft/msbuild/issues/2369#issuecomment-323139518-->
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Build.Utilities.Core" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" />
    <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="15.1.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Build.Framework" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" />
    <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="15.1.0.0" />
  </dependentAssembly>
</assemblyBinding>

This fix works for Visual Studio 2017 version 15.3.


问:
How to create two colors gradient effect from center using css?
In excel I created this effect with a plus sign in it.
I have been looking to create this with CSS, but I am not getting close!
How can I do this? Is there any good web site that teaches how to work with gradients?

Regards,
Elio Fernandes

答:
If you want to achieve this particluar effect, using CSS gradients may not be the way to go since it's quite complex.

You could try this :

.gradient {
  width: 60px;
  height: 60px;
  background: radial-gradient(#fff, #000)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="gradient"></div></code>```

Here are some CSS references :

CSS Gradients

MDN - CSS Gradients

Body:
If you want to achieve this particluar effect, using CSS gradients may not be the way to go since it's quite complex.

You could try this :

.gradient {
  width: 60px;
  height: 60px;
  background: radial-gradient(#fff, #000)
}

<div class="gradient"></div>

Here are some CSS references :

CSS Gradients

MDN - CSS Gradients


问:
Javamail, Weblogic, IMAP, SSL and Exchange 2010
first of all, sorry for my english (I'm from Spain)

I'm trying to connect to an Exchange 2010 mail server with IMAP and SSL from Javamail inside a Weblogic 8.1 server.

This is my code

```<code>Properties prop = new Properties();

// IMAP
// Disable TLS
prop.setProperty("mail.imap.starttls.enable", "false");

// Use SSL
prop.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.imap.socketFactory.fallback", "false");

// Use port 993
prop.setProperty("mail.imap.port", "993");
prop.setProperty("mail.imap.socketFactory.port", "993");

prop.setProperty("mail.imaps.class", "com.sun.mail.imap.IMAPSSLStore");

Session session = Session.getDefaultInstance(prop);
session.setDebug(true);
Store store = session.getStore("imap");
store.connect(host, user, password);
</code>```

At this point, I get  javax.mail.AuthenticationFailedException: Command received in Invalid state.
The user parameter is a combination of "domain\user-login\mail-box-alias". I use this because I saw it in this way in a how-to guide.
I already installed a valid SSL certificade in my Weblogic Server.

I don't know where the error is.

With debug I get this:

DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]

OK The Microsoft Exchange IMAP4 service is ready.

A0 CAPABILITY

CAPABILITY IMAP4 IMAP4rev1 LOGINDISABLED STARTTLS CHILDREN IDLE NAMESPACE LITERAL+

A0 OK CAPABILITY completed.

A1 LOGIN "domain\user\mailbox-alias" password

A1 BAD Command received in Invalid state.

ERROR 2: javax.mail.AuthenticationFailedException: Command received in Invalid state.

答: Make sure Exchange 2010 is set up to allow user/pwd based logins.</p>

ContentLicense: CC BY-SA 2.5

Body:
first of all, sorry for my english (I'm from Spain)

I'm trying to connect to an Exchange 2010 mail server with IMAP and SSL from Javamail inside a Weblogic 8.1 server.

This is my code

Properties prop = new Properties();

// IMAP
// Disable TLS
prop.setProperty("mail.imap.starttls.enable", "false");

// Use SSL
prop.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.imap.socketFactory.fallback", "false");

// Use port 993
prop.setProperty("mail.imap.port", "993");
prop.setProperty("mail.imap.socketFactory.port", "993");

prop.setProperty("mail.imaps.class", "com.sun.mail.imap.IMAPSSLStore");

Session session = Session.getDefaultInstance(prop);
session.setDebug(true);
Store store = session.getStore("imap");
store.connect(host, user, password);

At this point, I get  javax.mail.AuthenticationFailedException: Command received in Invalid state.
The user parameter is a combination of "domain\user-login\mail-box-alias". I use this because I saw it in this way in a how-to guide.
I already installed a valid SSL certificade in my Weblogic Server.

I don't know where the error is.

With debug I get this:

DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]

OK The Microsoft Exchange IMAP4 service is ready.

A0 CAPABILITY

CAPABILITY IMAP4 IMAP4rev1 LOGINDISABLED STARTTLS CHILDREN IDLE NAMESPACE LITERAL+

A0 OK CAPABILITY completed.

A1 LOGIN "domain\user\mailbox-alias" password

A1 BAD Command received in Invalid state.

ERROR 2: javax.mail.AuthenticationFailedException: Command received in Invalid state.


问:
How to copy top and remaining values to different cell in Excel VBA

I would like to select the top 10 Values from Main table and paste in different range (E3) and REMAINING all values and PASTE and SUM in another range(I3)
I used the code below. It is working for Top 10 values, BUT for remaining,
when i am adding one more row in Main table, it is not working. Help me.

```<code>Private Sub CommandButton1_Click()

'Calculation for Top 10 Countries
Sheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Offset(-9, -2).Resize(10, 3).Copy Sheets("Sheet1").Range("E3")

'Calculation for Remaining Countries
Range("A3:C14").Copy Range("I3")
Range("I15").Select
ActiveCell.FormulaR1C1 = "Remaining"
Range("J15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
Range("K15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
End Sub
</code>```

答:
Please try this code.</p>

```<code>Option Explicit

Private Sub CommandButton1_Click()

    Dim Rng As Range
    Dim R As Long, Rl As Long                      ' last row

    With Worksheets("Sheet1")
        Rl = .Cells(.Rows.Count, "A").End(xlUp).Row
        R = Application.Max(Rl - 9, 3)
        ' pick Top 10 Countries
        Set Rng = Range(.Cells(R, "A"), .Cells(Rl, "C"))
        Rng.Copy Destination:=.Cells(3, "E")

        ' pick remaining countries
        If R > 3 Then
            Set Rng = Range(.Cells(3, "A"), .Cells(R - 1, "C"))
            Rng.Copy Destination:=.Cells(3, "I")

            ' write totals
            Rl = .Cells(.Rows.Count, "I").End(xlUp).Row
            Set Rng = Range(.Cells(3, "J"), .Cells(Rl, "J"))
            Rl = Rl + 1
            With .Cells(Rl, "I")
                .Value = "Remaining"
                .HorizontalAlignment = xlRight
                .Font.Bold = True
            End With
            With .Cells(Rl, "J")
                .Value = Application.Sum(Rng)
                .HorizontalAlignment = xlCenter
                .Font.Bold = True
            End With
            With .Cells(Rl, "K")
                .Value = Application.Sum(Rng.Offset(0, 1))
                .HorizontalAlignment = xlCenter
                .Font.Bold = True
            End With
        End If
    End With
End Sub
</code>```

Body:
I would like to select the top 10 Values from Main table and paste in different range (E3) and REMAINING all values and PASTE and SUM in another range(I3)
I used the code below. It is working for Top 10 values, BUT for remaining,
when i am adding one more row in Main table, it is not working. Help me.

Private Sub CommandButton1_Click()

'Calculation for Top 10 Countries
Sheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Offset(-9, -2).Resize(10, 3).Copy Sheets("Sheet1").Range("E3")

'Calculation for Remaining Countries
Range("A3:C14").Copy Range("I3")
Range("I15").Select
ActiveCell.FormulaR1C1 = "Remaining"
Range("J15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
Range("K15").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
End Sub

Body:
Please try this code.

Option Explicit

Private Sub CommandButton1_Click()

    Dim Rng As Range
    Dim R As Long, Rl As Long                      ' last row

    With Worksheets("Sheet1")
        Rl = .Cells(.Rows.Count, "A").End(xlUp).Row
        R = Application.Max(Rl - 9, 3)
        ' pick Top 10 Countries
        Set Rng = Range(.Cells(R, "A"), .Cells(Rl, "C"))
        Rng.Copy Destination:=.Cells(3, "E")

        ' pick remaining countries
        If R > 3 Then
            Set Rng = Range(.Cells(3, "A"), .Cells(R - 1, "C"))
            Rng.Copy Destination:=.Cells(3, "I")

            ' write totals
            Rl = .Cells(.Rows.Count, "I").End(xlUp).Row
            Set Rng = Range(.Cells(3, "J"), .Cells(Rl, "J"))
            Rl = Rl + 1
            With .Cells(Rl, "I")
                .Value = "Remaining"
                .HorizontalAlignment = xlRight
                .Font.Bold = True
            End With
            With .Cells(Rl, "J")
                .Value = Application.Sum(Rng)
                .HorizontalAlignment = xlCenter
                .Font.Bold = True
            End With
            With .Cells(Rl, "K")
                .Value = Application.Sum(Rng.Offset(0, 1))
                .HorizontalAlignment = xlCenter
                .Font.Bold = True
            End With
        End If
    End With
End Sub


问:
Custom action page Sonata Admin
I'm looking to create a new action page for my sonata admin project. I want to make a page where to upload files, but I want this page to be different than create page. I tried to change configureRoutes function and I added '/upload/ path just like in Sonata tutorial, but they are telling me to use getRouterIdParameter() and I don't want something like /app/class/<ID>/upload. I just want to something like /app/class/upload.

It's that possible ?

答:
CRUD - Create, Read, Update, Delete. So, CRUD controllers work with defined object. When you create actions in your CRUD controller you have to get the object, otherwise - your action won't know which object to create, update, delete, etc.

That's why you should to put object's id to your route.

```<code>public function superAction(Request $request, $id = null)
{
    try {
        if ($id !== null) {
            $yourObject = $this->admin->getObject($id);
        }
    } catch (NotFoundHttpException $e) {
        error_log($e->getMessage());
    }

    //... your logic

}
</code>```

But! If your action doesn't supposed to use particular object - you can avoid object $id in your route. Also you are able to pass the variables with GET method. As many as you wish.

Imagine, that you want to update all your objects. Then you can create updateAllAction() and then add this route:

```<code>/**
 * @param RouteCollection $collection
 */
protected function configureRoutes(RouteCollection $collection)
{
    $collection->add('updateAll', 'update/all');
}
</code>```

As long as your action doesn't care of the particular object you can avoid $this->getRouterIdParameter() in your uri.

Hope it is helpful.

Title: Custom action page Sonata Admin

Body:
CRUD - Create, Read, Update, Delete. So, CRUD controllers work with defined object. When you create actions in your CRUD controller you have to get the object, otherwise - your action won't know which object to create, update, delete, etc.

That's why you should to put object's id to your route.

public function superAction(Request $request, $id = null)
{
    try {
        if ($id !== null) {
            $yourObject = $this->admin->getObject($id);
        }
    } catch (NotFoundHttpException $e) {
        error_log($e->getMessage());
    }

    //... your logic

}

But! If your action doesn't supposed to use particular object - you can avoid object $id in your route. Also you are able to pass the variables with GET method. As many as you wish.

Imagine, that you want to update all your objects. Then you can create updateAllAction() and then add this route:

/**
 * @param RouteCollection $collection
 */
protected function configureRoutes(RouteCollection $collection)
{
    $collection->add('updateAll', 'update/all');
}

As long as your action doesn't care of the particular object you can avoid $this->getRouterIdParameter() in your uri.

Hope it is helpful.


问:
How to convert Java ArrayList to Apache Spark Dataset?
I have a list like this:

```<code>List<String> dataList = new ArrayList<>();
dataList.add("A");
dataList.add("B");
dataList.add("C");
</code>```

I need to convert Dataset<Row> dataDs = Seq(dataList).toDs();

答:
```<code>List<String> data = Arrays.asList("abc", "abc", "xyz");
Dataset<String> dataDs = spark.createDataset(data, Encoders.STRING());
Dataset<String> dataListDs = spark.createDataset(dataList,    Encoders.STRING());
dataDs.show();
</code>```

Body:
I have a list like this:

List<String> dataList = new ArrayList<>();
dataList.add("A");
dataList.add("B");
dataList.add("C");

I need to convert Dataset<Row> dataDs = Seq(dataList).toDs();


答:
```<code>DROP TABLE IF EXISTS amenities;

CREATE TABLE amenities
(unit_id INT NOT NULL
,amenity VARCHAR(50) NOT NULL
,PRIMARY KEY(unit_id,amenity)
);

INSERT INTO amenities VALUES
(1,'Air conditions'),
(1,'Internet'),
(1,'Water heaters'),
(1,'TV'),
(2,'TV'),
(2,'pool'),
(2,'Internet'),
(3,'Internet'),
(4,'Internet');

SELECT unit_id
  FROM amenities
 WHERE amenity IN ('TV','Internet')
 GROUP
    BY unit_id
HAVING COUNT(*) = 2;
+---------+
| unit_id |
+---------+
|       1 |
|       2 |
+---------+
</code>```

Obviously, you'd never have a table like the one you describe. Instead, you'd have a table of unit, a table of amenities, and a table which says which amenity belongs to which unit.

Title: MYSQL select query based on another tables multiple values

Body:
I have two tables one for units and one for Amenities

Table units
+---------+---------------------+---------------------+-----------+----------+
| unit_id |     date added      |     date modified   | unit name |   user   |
+---------+---------------------+---------------------+-----------+----------+
|       1 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 |  Villa 1  | Smith    |
|       2 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 |  Villa 2  | Smith    |
|       3 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 |  Villa 3  | Jones    |
|       4 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 | Apartment | Smith    |
+---------+---------------------+---------------------+-----------+----------+

Table Amenities
+---------+-----------+-------------------+
|      id |  Unit_id  |   Amenity         |
+---------+-----------+-------------------+
|       1 |         1 |   Air conditions  |
|       2 |         1 |   Internet        |
|       3 |         1 |   Water heaters   |
|       4 |         1 |   TV              |
|       5 |         2 |   TV              |
|       6 |         2 |   pool            |
|       7 |         2 |   Internet        |
|       8 |         3 |   Internet        |
|       9 |         4 |   Internet        |
+---------+-----------+-------------------+

i want to select units where it has both TV and Internet

I try

select units.* from units left join Amenities  on units.unit_id=Amenities.Unit_id

where Amenities.Amenity='TV' and  Amenities.Amenity='Internet'

but not work

Body:
DROP TABLE IF EXISTS amenities;

CREATE TABLE amenities
(unit_id INT NOT NULL
,amenity VARCHAR(50) NOT NULL
,PRIMARY KEY(unit_id,amenity)
);

INSERT INTO amenities VALUES
(1,'Air conditions'),
(1,'Internet'),
(1,'Water heaters'),
(1,'TV'),
(2,'TV'),
(2,'pool'),
(2,'Internet'),
(3,'Internet'),
(4,'Internet');

SELECT unit_id
  FROM amenities
 WHERE amenity IN ('TV','Internet')
 GROUP
    BY unit_id
HAVING COUNT(*) = 2;
+---------+
| unit_id |
+---------+
|       1 |
|       2 |
+---------+

Obviously, you'd never have a table like the one you describe. Instead, you'd have a table of unit, a table of amenities, and a table which says which amenity belongs to which unit.


问:
Movable Type: Error running CRON
I have Movable Type 5.031 running on RHEL5.5
Im trying to run periodic tasks but I run into these errors.

```<code>root@sv cd /home/user/public_html/mt; ./tools/run-periodic-tasks
Out of memory (Needed 8160 bytes)
DBD::mysql::st execute warning:  at extlib/Data/ObjectDriver/Driver/DBI.pm line 153.
</code>```

I have no idea what it is. Anyone?

答: What periodic tasks are you running? Just publishing posts in the que? It looks like the query result is too big for the memory available on the server.</p>

Title: Movable Type: Error running CRON

Body:
I have Movable Type 5.031 running on RHEL5.5
Im trying to run periodic tasks but I run into these errors.

root@sv cd /home/user/public_html/mt; ./tools/run-periodic-tasks
Out of memory (Needed 8160 bytes)
DBD::mysql::st execute warning:  at extlib/Data/ObjectDriver/Driver/DBI.pm line 153.

I have no idea what it is. Anyone?


问:
how bind correctly in react-native?
I'm try to update the state from a function, but I don't find the correct form to bind the scope. My code (I am working with native-base components):</p>
```<code>export default class MenuScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  _renderRow() {
    return (
      <ListItem avatar onPress={() =>
         ActionSheet.show(
           {options: BUTTONS
           }, buttonIndex => { setState({ clicked:  BUTTONS[buttonIndex]})}
         )}
       >
      </ListItem>
    );
  }

  render() {
    return (
         <SectionList
          sections={[...]}
          renderItem={this._renderRow}
        />
    );
  }
</code>```

答:
My recommendation would be to read this:
https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56
Helps a lot with understanding binding options you have and why one or other might be better in your case.

I suggest to go with binding in constructor:

```<code>export default class MenuScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.handleChange = this.handlePress.bind(this);
  }
...
</code>```

ContentLicense: CC BY-SA 4.0

Title: how bind correctly in react-native?

Body:
I'm try to update the state from a function, but I don't find the correct form to bind the scope. My code (I am working with native-base components):

export default class MenuScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  _renderRow() {
    return (
      <ListItem avatar onPress={() =>
         ActionSheet.show(
           {options: BUTTONS
           }, buttonIndex => { setState({ clicked:  BUTTONS[buttonIndex]})}
         )}
       >
      </ListItem>
    );
  }

  render() {
    return (
         <SectionList
          sections={[...]}
          renderItem={this._renderRow}
        />
    );
  }

Body:
My recommendation would be to read this:
https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56
Helps a lot with understanding binding options you have and why one or other might be better in your case.

I suggest to go with binding in constructor:

export default class MenuScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.handleChange = this.handlePress.bind(this);
  }
...


问:
Change columns order in opencv mat without copying data
I have an opencv mat which has M rows and 3 columns, is there a way to reorder the mat such that the first and last (i.e., third) columns are switched while the middle column kept in place without copying the data?

答:
You can use the OpenCV function flip for that. As an example the following code flips an image about the mid column.

```<code>int main ()

{
    Mat img, flipped;       //your mat

    img =imread("lena.jpg");

    flip(img,flipped ,1);  // flipped is the output

    imshow("img",flipped);
    waitKey(0);

}
</code>```

Body:
You can use the OpenCV function flip for that. As an example the following code flips an image about the mid column.

int main ()

{
    Mat img, flipped;       //your mat

    img =imread("lena.jpg");

    flip(img,flipped ,1);  // flipped is the output

    imshow("img",flipped);
    waitKey(0);

}


问:
Travis CI + NuGet yields Invalid certificate error
I'm trying to use NuGet on Travis.

```<code>- sudo apt-get -qq -y update
- sudo apt-get -qq -y install mono-complete gtk-sharp2
- wget https://dist.nuget.org/win-x86-commandline/latest/nuget.exe
- mono ./nuget.exe install ILMerge -Version 2.14.1208
</code>```

Unfortunately, I get the following error:

```<code>  https://api.nuget.org/v3/index.json

Attempting to gather dependency information for package 'ILMerge.2.14.1208' with respect to project '/home/travis/build/craftr-build/craftr/build/.nuget-artifacts', targeting 'Any,Version=v0.0'
Invalid certificate received from server. Error code: 0xffffffff800b0109
</code>```

I have tried various recommendations from what I found on Google, for example using the following before trying to use NuGet:

```<code>- mozroots --import --sync
- yes | certmgr -ssl -m https://go.microsoft.com
- yes | certmgr -ssl -m https://nugetgallery.blob.core.windows.net
- yes | certmgr -ssl -m https://nuget.org
</code>```

Unfortunately the mozroot command gives

```<code>Downloading from 'http://mxr.mozilla.org/seamonkey/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1'...
Couldn't retrieve the file using the supplied information.
</code>```

Leaving out the mozroots command gives the same NuGet error.

How can I get NuGet to work on Travis?

答:
I just used the APT Addon now. I found the sourcelinse and key_urls in another Mono project here</p>

```<code>addons:
  apt:
    sources:
      - sourceline: deb http://download.mono-project.com/repo/debian trusty/snapshots/5.2.0.224 main
        key_url: http://keyserver.ubuntu.com/pks/lookup?op=get&search=0xA6A19B38D3D831EF
      - sourceline: deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-trusty-prod trusty main
        key_url: https://packages.microsoft.com/keys/microsoft.asc
      - packages:
    packages:
      - mono-devel
      - ca-certificates-mono
</code>```

Body:
I'm trying to use NuGet on Travis.

- sudo apt-get -qq -y update
- sudo apt-get -qq -y install mono-complete gtk-sharp2
- wget https://dist.nuget.org/win-x86-commandline/latest/nuget.exe
- mono ./nuget.exe install ILMerge -Version 2.14.1208

Unfortunately, I get the following error:

  https://api.nuget.org/v3/index.json

Attempting to gather dependency information for package 'ILMerge.2.14.1208' with respect to project '/home/travis/build/craftr-build/craftr/build/.nuget-artifacts', targeting 'Any,Version=v0.0'
Invalid certificate received from server. Error code: 0xffffffff800b0109

I have tried various recommendations from what I found on Google, for example using the following before trying to use NuGet:

- mozroots --import --sync
- yes | certmgr -ssl -m https://go.microsoft.com
- yes | certmgr -ssl -m https://nugetgallery.blob.core.windows.net
- yes | certmgr -ssl -m https://nuget.org

Unfortunately the mozroot command gives

Downloading from 'http://mxr.mozilla.org/seamonkey/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1'...
Couldn't retrieve the file using the supplied information.

Leaving out the mozroots command gives the same NuGet error.

How can I get NuGet to work on Travis?

Body:
I just used the APT Addon now. I found the sourcelinse and key_urls in another Mono project here

addons:
  apt:
    sources:
      - sourceline: deb http://download.mono-project.com/repo/debian trusty/snapshots/5.2.0.224 main
        key_url: http://keyserver.ubuntu.com/pks/lookup?op=get&search=0xA6A19B38D3D831EF
      - sourceline: deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-trusty-prod trusty main
        key_url: https://packages.microsoft.com/keys/microsoft.asc
      - packages:
    packages:
      - mono-devel
      - ca-certificates-mono


问:
Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit
I have just installed Java SE Development Kit 8u91 on my 64 bit Windows-10 OS. I set my path variables . I tried java --version in my command prompt it gave me an error.

```<code>c:\Users\Onlymanu>java --version
Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
</code>```

But when i tried java -version it worked.

I tried initializing _JAVA_OPTIONS  environment variable and ever tried re-installation none of them worked. Can any one help me please?

答: the command should be java -version

Body:
I have just installed Java SE Development Kit 8u91 on my 64 bit Windows-10 OS. I set my path variables . I tried java --version in my command prompt it gave me an error.

c:\Users\Onlymanu>java --version
Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

But when i tried java -version it worked.

I tried initializing _JAVA_OPTIONS  environment variable and ever tried re-installation none of them worked. Can any one help me please?

Body: the command should be java -version


答:
```<code>Private Sub CommandButton1_Click()

    Dim lr As Long
    Dim pr As Long

    With Sheets("Sheet1")
        lr = .Range("A" & Rows.Count).End(xlUp).Row

        'Calculation for Top 10 Countries
        .Range("A" & (lr - 10) & ":C" & lr).Copy .Range("E3")

        'Calculation for Remaining Countries
        .Range("A3:C" & (lr - 11)).Copy .Range("I3")
        pr = .Range("A3:C" & (lr - 11)).Rows.Count + 3
        .Range("I" & pr).Value = "Remaining"
        .Range("J" & pr).FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
        .Range("K" & pr).FormulaR1C1 = "=SUM(R[-12]C:R[-1]C)"
    End With
End Sub
</code>```

Title: How to copy top and remaining values to different cell in Excel VBA


问:
Receiving "Cannot GET /" error when trying to connect using Node.js/Express
Recently I started trying to get into Node.js/React and am using this tutorial https://auth0.com/blog/build-a-chat-app-with-react/.

However, even though I have followed the steps, I seem to be encountering an error. My page is displayed as "Cannot GET /" after hitting yarn start. I've found answers here NodeJS w/Express Error: Cannot GET /
and here "Cannot GET /" with Connect on Node.js

Neither of these made sense to me though, as my code seems to differ from theirs slightly. I understand that the page doesnt know where to look for my GET request, and therefore what information to pull, but im not sure how to fix it.

The code in question, GET request at the end. Thanks.

```<code>// server.js
const express = require('express');
const path = require('path');
const bodyParser = require("body-parser");
const app = express();
const Pusher = require('pusher');

//initialize Pusher with your appId, key and secret
const pusher = new Pusher({
    appId: 'APP_ID',
    key: 'APP_KEY',
    secret: 'SECRET',
    cluster: 'YOUR CLUSTER',
    encrypted: true
});

// Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// API route which the chat messages will be sent to
app.post('/message/send', (req, res) => {
  // 'private' is prefixed to indicate that this is a private channel
    pusher.trigger( 'private-reactchat', 'messages', {
        message: req.body.message,
        username: req.body.username
    });
    res.sendStatus(200);
});

// API route used by Pusher as a way of authenticating users
app.post('/pusher/auth', (req, res) => {
    const socketId = req.body.socket_id;
    const channel = req.body.channel_name;
    const auth = pusher.authenticate(socketId, channel);
    res.send(auth);
});

// Set port to be used by Node.js
app.set('port', (process.env.PORT || 5000));

app.listen(app.get('port'), function(req, res) {
    console.log('Node app is running on port', app.get('port'));
});
</code>```

答: I assume that you are sending get request to localhost:5000 which isn't defined in your server so it can't send response back, because you are using react you want to send request on port on which react is running(3000 by default) so try accessing using localhost:3000 and it should work.

Body:
Recently I started trying to get into Node.js/React and am using this tutorial https://auth0.com/blog/build-a-chat-app-with-react/.

However, even though I have followed the steps, I seem to be encountering an error. My page is displayed as "Cannot GET /" after hitting yarn start. I've found answers here NodeJS w/Express Error: Cannot GET /
and here "Cannot GET /" with Connect on Node.js

Neither of these made sense to me though, as my code seems to differ from theirs slightly. I understand that the page doesnt know where to look for my GET request, and therefore what information to pull, but im not sure how to fix it.

The code in question, GET request at the end. Thanks.

// server.js
const express = require('express');
const path = require('path');
const bodyParser = require("body-parser");
const app = express();
const Pusher = require('pusher');

//initialize Pusher with your appId, key and secret
const pusher = new Pusher({
    appId: 'APP_ID',
    key: 'APP_KEY',
    secret: 'SECRET',
    cluster: 'YOUR CLUSTER',
    encrypted: true
});

// Body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// API route which the chat messages will be sent to
app.post('/message/send', (req, res) => {
  // 'private' is prefixed to indicate that this is a private channel
    pusher.trigger( 'private-reactchat', 'messages', {
        message: req.body.message,
        username: req.body.username
    });
    res.sendStatus(200);
});

// API route used by Pusher as a way of authenticating users
app.post('/pusher/auth', (req, res) => {
    const socketId = req.body.socket_id;
    const channel = req.body.channel_name;
    const auth = pusher.authenticate(socketId, channel);
    res.send(auth);
});

// Set port to be used by Node.js
app.set('port', (process.env.PORT || 5000));

app.listen(app.get('port'), function(req, res) {
    console.log('Node app is running on port', app.get('port'));
});


问:
WordPress domain redirection
Beginner question:
I need to perform a 301 redirect from one Wordpress site (domain), to another Wordpress domain, like this:
From:
http://mycompany.com
To:
http://mycompany.se

A problem is that I have no FTP credentials for my From-site. I can't reach the .htaccess file.

Is there a plugin to use? I have studied the Redirection plugin, but this one seems working on pages within the same domain only(?)

I guess I need to be careful, because if some plugin edits the .htaccess file and something breaks, I can't reach the file...
Thankful for any help!

答:
Whit Redirection Plugin you can redirect a url from old to new website.

You can create and manage redirects quickly and easily without needing Apache or Nginx knowledge. If your WordPress supports permalinks then you can use Redirection to redirect any URL.

There is full support for regular expressions so you can create redirect patterns to match any number of URLs.

The plugin can also be configured to monitor when post or page permalinks are changed and automatically create a redirect to the new URL.

Title: WordPress domain redirection


问:
PostgreSQL query joining with view has poor performance
I am trying to create an API that returns the list of files/folders that the user owns, similar to Google Drive. The information about user's files/folders/other is stored in the PostgreSQL tables.

I have created a view called gc_drive that gets the file list from these tables. Yes, I call them tables because there are different tables for files, folders, and virtual files so I use a view to join all these records together so they effectively appear as a file system, even though they are not 100% a file system.

The view performance looks fine, I have indexed the necessary columns and even though the view has more than 2.7 million records with all the data combined, it filters by ID and it returns the filtered records by a parent in milliseconds. However, if I try to select count(*) from gc_drive it takes 69 seconds because the base tables that contain the list of files, folders, resources and other have more than 7 million records each.

I want to join the gc_drive view with the fn_resource_permissions table that has info on whether the user has access to the resource.

When I use the following query to get the current logged in user's permissions the records return almost instantly:

```<code>select*from
fn_resource_permissions
WHERE ((fn_resource_permissions.permission_id IN (23,
                                                  24,
                                                  25,
                                                  37,
                                                  36)
AND (fn_resource_permissions.user_id = 2
     OR fn_resource_permissions.user_id = 1)))

--59 records returned
</code>```

The query above returns me all the permissions to the resources that the user has. I will use those records to filter the gc_drive view.

When I try to use these 59 records in the following query to filter out the gc_drive view the records also return instantly:

```<code>SELECT gc_drive.id,
       "fn_resources"."owner_id" AS "fn_resources.owner_id",
       "gc_drive".*
FROM "gc_drive"
JOIN "fn_resources" ON ("gc_drive"."resource_id" = "fn_resources"."id")
WHERE "fn_resources"."archived" = 0
AND   gc_drive.id IN(
    1234,
    1235,
    1236,
    ...
);
</code>```

The problem is when I try to join the 2 queries above together:

```<code>SELECT gc_drive.id,
       "fn_resources"."owner_id" AS "fn_resources.owner_id",
       "gc_drive".*
FROM "gc_drive"
JOIN "fn_resources" ON ("gc_drive"."resource_id" = "fn_resources"."id")
JOIN "fn_resource_permissions" ON ("fn_resource_permissions"."resource_id" = fn_resources.id)
WHERE "fn_resources"."archived" = 0
AND ((fn_resource_permissions.permission_id IN (23,
                                                24,
                                                25,
                                                37,
                                                36)
          AND (fn_resource_permissions.user_id = 2
               OR fn_resource_permissions.user_id = 1)))
LIMIT 101;
</code>```

When I look in the Explain plan, I can see that the PostgreSQL is materializing the whole gc_drive view, and only then is trying to filter by resource permissions. This makes the query run in minutes, not in milliseconds. I have also tried to put the resource permissions in with clause and it does the same. I know that one of the solutions could be to separate each user's content in its own schema but I want to know if there is a better more efficient way to join the gc_drive view and other tables without PostgreSQL first materializing the whole view. Is there a way to modify the query so that PostgreSQL can filter only on the whole set of records.

Explain analyze plan on the above query:

```<code>    ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                                                QUERY PLAN                                                                                │
├───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ Limit  (cost=4845.56..57547586.51 rows=101 width=722) (actual time=201371.236..201371.236 rows=0 loops=1)                                                                             │
│   ->  Hash Join  (cost=4845.56..681971785.33 rows=1197 width=722) (actual time=201371.234..201371.234 rows=0 loops=1)                                                                 │
│         Hash Cond: ("*SELECT* 1".resource_id = fn_resources.id)                                                                                │
│         ->  Append  (cost=36.10..681748786.17 rows=15867640 width=247) (actual time=17521.979..200235.975 rows=2737742 loops=1)                                                       │
│               ->  Subquery Scan on "*SELECT* 1"  (cost=36.10..533636.75 rows=11252 width=150) (actual time=0.004..0.004 rows=0 loops=1)                                               │
│                     ->  Hash Join  (cost=36.10..533524.23 rows=11252 width=150) (actual time=0.003..0.003 rows=0 loops=1)                                                             │
│                           Hash Cond: (fnr_child.type = fnrt.type)                                                                                │
│                           ->  Nested Loop  (cost=0.00..66613.04 rows=1940 width=122) (actual time=0.003..0.003 rows=0 loops=1)                                                        │
│                                 ->  Nested Loop  (cost=0.00..49607.76 rows=1940 width=100) (actual time=0.002..0.002 rows=0 loops=1)                                                  │
│                                       ->  Nested Loop  (cost=0.00..32602.48 rows=1940 width=104) (actual time=0.002..0.002 rows=0 loops=1)                                            │
│                                             ->  Nested Loop  (cost=0.00..16315.94 rows=1940 width=12) (actual time=0.002..0.002 rows=0 loops=1)                                       │
│                                                   ->  Seq Scan on gc_virtual_file gvf  (cost=0.00..29.40 rows=1940 width=8) (actual time=0.001..0.001 rows=0 loops=1)                 │
│                                                   ->  Index Scan using gc_file_resource_id_key on gc_file gf_child  (cost=0.00..8.38 rows=1 width=4) (never executed)                 │
│                                                         Index Cond: (resource_id = gvf.resource_id)                                                                                │
│                                             ->  Index Scan using gc_file_resource_id_key on gc_file gf_parent  (cost=0.00..8.38 rows=1 width=92) (never executed)                     │
│                                                   Index Cond: (resource_id = gvf.parent_id)                                                                                │
│                                       ->  Index Scan using fn_resources_pkey on fn_resources fnr_parent  (cost=0.00..8.75 rows=1 width=4) (never executed)                            │
│                                             Index Cond: (id = gvf.parent_id)                                                                                │
│                                 ->  Index Scan using fn_resources_pkey on fn_resources fnr_child  (cost=0.00..8.75 rows=1 width=30) (never executed)                                  │
│                                       Index Cond: (id = gvf.resource_id)                                                                                │
│                           ->  Hash  (cost=21.60..21.60 rows=1160 width=36) (never executed)                                                                                │
│                                 ->  Seq Scan on fn_resource_types fnrt  (cost=0.00..21.60 rows=1160 width=36) (never executed)                                                        │
│                           SubPlan 6                                                                                │
│                             ->  Index Scan using users_pkey on fn_users  (cost=0.00..8.28 rows=1 width=13) (never executed)                                                           │
│                                   Index Cond: (id = fnr_child.owner_id)                                                                                │
│                           SubPlan 7                                                                                │
│                             ->  Index Scan using gc_tables_resource_id_key on gc_tables gt  (cost=0.00..8.28 rows=1 width=18) (never executed)                                        │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 8                                                                                │
│                             ->  Index Scan using gc_webmapservices_resource_id_key on gc_webmapservices gwms  (cost=0.00..8.27 rows=1 width=418) (never executed)                     │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 9                                                                                │
│                             ->  Index Scan using gc_tables_resource_id_key on gc_tables gt  (cost=0.00..8.31 rows=1 width=14) (never executed)                                        │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 10                                                                                │
│                             ->  Index Scan using gc_webmapservices_resource_id_key on gc_webmapservices gwms  (cost=0.00..8.30 rows=1 width=267) (never executed)                     │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│               ->  Subquery Scan on "*SELECT* 2"  (cost=580092.62..681215149.42 rows=15856388 width=247) (actual time=17521.724..199482.039 rows=2737742 loops=1)                      │
│                     ->  Hash Join  (cost=580092.62..681056585.54 rows=15856388 width=247) (actual time=17521.668..198482.521 rows=2737742 loops=1)                                    │
│                           Hash Cond: (fnr_child.type = fnrt.type)                                                                                │
│                           ->  Hash Join  (cost=580056.53..1189954.39 rows=2733860 width=219) (actual time=16768.431..88474.618 rows=2737742 loops=1)                                  │
│                                 Hash Cond: (gf_parent.resource_id = fnr_parent.id)                                                                                │
│                                 ->  Hash Join  (cost=388738.70..943959.36 rows=2733860 width=219) (actual time=13619.604..72625.523 rows=2737742 loops=1)                             │
│                                       Hash Cond: (gf_child.path = gf_parent.pathname)                                                                                │
│                                       ->  Hash Join  (cost=202378.85..538142.64 rows=2733860 width=168) (actual time=6429.263..53255.517 rows=2737743 loops=1)                        │
│                                             Hash Cond: (fnr_child.id = gf_child.resource_id)                                                                                │
│                                             ->  Seq Scan on fn_resources fnr_child  (cost=0.00..114415.70 rows=6152170 width=30) (actual time=21.243..19364.289 rows=6119914 loops=1) │
│                                             ->  Hash  (cost=112139.60..112139.60 rows=2733860 width=142) (actual time=5666.626..5666.626 rows=2737743 loops=1)                        │
│                                                   Buckets: 262144  Batches: 2  Memory Usage: 240441kB                                                                                │
│                                                   ->  Seq Scan on gc_file gf_child  (cost=0.00..112139.60 rows=2733860 width=142) (actual time=0.015..3442.788 rows=2737751 loops=1)  │
│                                       ->  Hash  (cost=112139.60..112139.60 rows=2733860 width=92) (actual time=7173.094..7173.094 rows=2737751 loops=1)                               │
│                                             Buckets: 262144  Batches: 2  Memory Usage: 169423kB                                                                                │
│                                             ->  Seq Scan on gc_file gf_parent  (cost=0.00..112139.60 rows=2733860 width=92) (actual time=0.007..5057.412 rows=2737751 loops=1)        │
│                                 ->  Hash  (cost=114415.70..114415.70 rows=6152170 width=4) (actual time=3145.424..3145.424 rows=6119914 loops=1)                                      │
│                                       Buckets: 1048576  Batches: 1  Memory Usage: 215154kB                                                                                │
│                                       ->  Seq Scan on fn_resources fnr_parent  (cost=0.00..114415.70 rows=6152170 width=4) (actual time=0.008..1186.819 rows=6119914 loops=1)         │
│                           ->  Hash  (cost=21.60..21.60 rows=1160 width=36) (actual time=0.021..0.021 rows=21 loops=1)                                                                 │
│                                 Buckets: 1024  Batches: 1  Memory Usage: 1kB                                                                                │
│                                 ->  Seq Scan on fn_resource_types fnrt  (cost=0.00..21.60 rows=1160 width=36) (actual time=0.005..0.012 rows=21 loops=1)                              │
│                           SubPlan 1                                                                                │
│                             ->  Index Scan using users_pkey on fn_users  (cost=0.00..8.28 rows=1 width=13) (actual time=0.009..0.009 rows=1 loops=2737742)                            │
│                                   Index Cond: (id = fnr_child.owner_id)                                                                                │
│                           SubPlan 2                                                                                │
│                             ->  Index Scan using gc_file_resource_id_key on gc_file gf  (cost=0.00..8.62 rows=1 width=47) (never executed)                                            │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 3                                                                                │
│                             ->  Index Scan using gc_file_resource_id_key on gc_file gf  (cost=0.00..8.62 rows=1 width=47) (actual time=0.025..0.025 rows=1 loops=2665337)             │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 4                                                                                │
│                             ->  Index Scan using gc_file_resource_id_key on gc_file gf  (cost=0.00..8.63 rows=1 width=129) (never executed)                                           │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 5                                                                                │
│                             ->  Index Scan using gc_file_resource_id_key on gc_file gf  (cost=0.00..8.66 rows=1 width=145) (actual time=0.003..0.003 rows=1 loops=2665337)            │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│         ->  Hash  (cost=4804.79..4804.79 rows=374 width=12) (actual time=412.434..412.434 rows=59 loops=1)                                                                            │
│               Buckets: 1024  Batches: 1  Memory Usage: 3kB                                                                                │
│               ->  Nested Loop  (cost=13.32..4804.79 rows=374 width=12) (actual time=156.510..412.313 rows=59 loops=1)                                                                 │
│                     ->  Bitmap Heap Scan on fn_resource_permissions  (cost=13.32..1454.38 rows=374 width=4) (actual time=155.407..402.734 rows=59 loops=1)                            │
│                           Recheck Cond: ((user_id = 2) OR (user_id = 1))                                                                                │
│                           Filter: (permission_id = ANY ('{23,24,25,37,36}'::integer[]))                                                                                │
│                           ->  BitmapOr  (cost=13.32..13.32 rows=391 width=0) (actual time=88.402..88.402 rows=0 loops=1)                                                              │
│                                 ->  Bitmap Index Scan on resource_permissions_user  (cost=0.00..6.57 rows=196 width=0) (actual time=88.380..88.380 rows=61 loops=1)                   │
│                                       Index Cond: (user_id = 2)                                                                                │
│                                 ->  Bitmap Index Scan on resource_permissions_user  (cost=0.00..6.57 rows=196 width=0) (actual time=0.016..0.016 rows=0 loops=1)                      │
│                                       Index Cond: (user_id = 1)                                                                                │
│                     ->  Index Scan using fn_resources_pkey on fn_resources  (cost=0.00..8.95 rows=1 width=8) (actual time=0.154..0.155 rows=1 loops=59)                               │
│                           Index Cond: (id = fn_resource_permissions.resource_id)                                                                                │
│                           Filter: (archived = 0)                                                                                │
│ Total runtime: 201373.236 ms                                                                                │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
</code>```

Many thanks.

答:
Your query is structured so thatfn_resources is filtered by fn_resource_permissions and then joined onto gc_drive, despite the same data being present in gc_drive.

This is a little bit of a hunch, but try filtering gc_drive by fn_resource_permissions early with the where clause, rather than a join on a join.

```<code>select
    gc_drive.id,
    fn_resources.owner_id,
    gc_drive.*
from
    gc_drive
    join fn_resources on(
        gc_drive.resource_id = fn_resources.id
    )
where
    gc_drive.resource_id in(
        select
            fn_resource_permissions.resource_id
        from
            fn_resource_permissions
        where
            fn_resource_permissions.permission_id in (23, 24, 25, 37, 36)
            and fn_resource_permissions.user_id in(1, 2)
    )
    and fn_resources.archived = 0
limit 101;
</code>```

Alternativley, try filtering fn_resources before the join

```<code>select
    gc_drive.id,
    fn_resources.owner_id,
    gc_drive.*
from
    gc_drive
    join fn_resources on(
        gc_drive.resource_id = fn_resources.id
        and fn_resources.id in(
            select
                fn_resource_permissions.resource_id
            from
                fn_resource_permissions
            where
                fn_resource_permissions.permission_id in (23, 24, 25, 37, 36)
                and fn_resource_permissions.user_id in(1, 2)
        )
    )
where
    fn_resources.archived = 0
limit 101;
</code>```

Body:
I am trying to create an API that returns the list of files/folders that the user owns, similar to Google Drive. The information about user's files/folders/other is stored in the PostgreSQL tables.

I have created a view called gc_drive that gets the file list from these tables. Yes, I call them tables because there are different tables for files, folders, and virtual files so I use a view to join all these records together so they effectively appear as a file system, even though they are not 100% a file system.

The view performance looks fine, I have indexed the necessary columns and even though the view has more than 2.7 million records with all the data combined, it filters by ID and it returns the filtered records by a parent in milliseconds. However, if I try to select count(*) from gc_drive it takes 69 seconds because the base tables that contain the list of files, folders, resources and other have more than 7 million records each.

I want to join the gc_drive view with the fn_resource_permissions table that has info on whether the user has access to the resource.

When I use the following query to get the current logged in user's permissions the records return almost instantly:

select*from
fn_resource_permissions
WHERE ((fn_resource_permissions.permission_id IN (23,
                                                  24,
                                                  25,
                                                  37,
                                                  36)
AND (fn_resource_permissions.user_id = 2
     OR fn_resource_permissions.user_id = 1)))

--59 records returned

The query above returns me all the permissions to the resources that the user has. I will use those records to filter the gc_drive view.

When I try to use these 59 records in the following query to filter out the gc_drive view the records also return instantly:

SELECT gc_drive.id,
       "fn_resources"."owner_id" AS "fn_resources.owner_id",
       "gc_drive".*
FROM "gc_drive"
JOIN "fn_resources" ON ("gc_drive"."resource_id" = "fn_resources"."id")
WHERE "fn_resources"."archived" = 0
AND   gc_drive.id IN(
    1234,
    1235,
    1236,
    ...
);

The problem is when I try to join the 2 queries above together:

SELECT gc_drive.id,
       "fn_resources"."owner_id" AS "fn_resources.owner_id",
       "gc_drive".*
FROM "gc_drive"
JOIN "fn_resources" ON ("gc_drive"."resource_id" = "fn_resources"."id")
JOIN "fn_resource_permissions" ON ("fn_resource_permissions"."resource_id" = fn_resources.id)
WHERE "fn_resources"."archived" = 0
AND ((fn_resource_permissions.permission_id IN (23,
                                                24,
                                                25,
                                                37,
                                                36)
          AND (fn_resource_permissions.user_id = 2
               OR fn_resource_permissions.user_id = 1)))
LIMIT 101;

When I look in the Explain plan, I can see that the PostgreSQL is materializing the whole gc_drive view, and only then is trying to filter by resource permissions. This makes the query run in minutes, not in milliseconds. I have also tried to put the resource permissions in with clause and it does the same. I know that one of the solutions could be to separate each user's content in its own schema but I want to know if there is a better more efficient way to join the gc_drive view and other tables without PostgreSQL first materializing the whole view. Is there a way to modify the query so that PostgreSQL can filter only on the whole set of records.

Explain analyze plan on the above query:

    ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                                                QUERY PLAN                                                                                │
├───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ Limit  (cost=4845.56..57547586.51 rows=101 width=722) (actual time=201371.236..201371.236 rows=0 loops=1)                                                                             │
│   ->  Hash Join  (cost=4845.56..681971785.33 rows=1197 width=722) (actual time=201371.234..201371.234 rows=0 loops=1)                                                                 │
│         Hash Cond: ("*SELECT* 1".resource_id = fn_resources.id)                                                                                │
│         ->  Append  (cost=36.10..681748786.17 rows=15867640 width=247) (actual time=17521.979..200235.975 rows=2737742 loops=1)                                                       │
│               ->  Subquery Scan on "*SELECT* 1"  (cost=36.10..533636.75 rows=11252 width=150) (actual time=0.004..0.004 rows=0 loops=1)                                               │
│                     ->  Hash Join  (cost=36.10..533524.23 rows=11252 width=150) (actual time=0.003..0.003 rows=0 loops=1)                                                             │
│                           Hash Cond: (fnr_child.type = fnrt.type)                                                                                │
│                           ->  Nested Loop  (cost=0.00..66613.04 rows=1940 width=122) (actual time=0.003..0.003 rows=0 loops=1)                                                        │
│                                 ->  Nested Loop  (cost=0.00..49607.76 rows=1940 width=100) (actual time=0.002..0.002 rows=0 loops=1)                                                  │
│                                       ->  Nested Loop  (cost=0.00..32602.48 rows=1940 width=104) (actual time=0.002..0.002 rows=0 loops=1)                                            │
│                                             ->  Nested Loop  (cost=0.00..16315.94 rows=1940 width=12) (actual time=0.002..0.002 rows=0 loops=1)                                       │
│                                                   ->  Seq Scan on gc_virtual_file gvf  (cost=0.00..29.40 rows=1940 width=8) (actual time=0.001..0.001 rows=0 loops=1)                 │
│                                                   ->  Index Scan using gc_file_resource_id_key on gc_file gf_child  (cost=0.00..8.38 rows=1 width=4) (never executed)                 │
│                                                         Index Cond: (resource_id = gvf.resource_id)                                                                                │
│                                             ->  Index Scan using gc_file_resource_id_key on gc_file gf_parent  (cost=0.00..8.38 rows=1 width=92) (never executed)                     │
│                                                   Index Cond: (resource_id = gvf.parent_id)                                                                                │
│                                       ->  Index Scan using fn_resources_pkey on fn_resources fnr_parent  (cost=0.00..8.75 rows=1 width=4) (never executed)                            │
│                                             Index Cond: (id = gvf.parent_id)                                                                                │
│                                 ->  Index Scan using fn_resources_pkey on fn_resources fnr_child  (cost=0.00..8.75 rows=1 width=30) (never executed)                                  │
│                                       Index Cond: (id = gvf.resource_id)                                                                                │
│                           ->  Hash  (cost=21.60..21.60 rows=1160 width=36) (never executed)                                                                                │
│                                 ->  Seq Scan on fn_resource_types fnrt  (cost=0.00..21.60 rows=1160 width=36) (never executed)                                                        │
│                           SubPlan 6                                                                                │
│                             ->  Index Scan using users_pkey on fn_users  (cost=0.00..8.28 rows=1 width=13) (never executed)                                                           │
│                                   Index Cond: (id = fnr_child.owner_id)                                                                                │
│                           SubPlan 7                                                                                │
│                             ->  Index Scan using gc_tables_resource_id_key on gc_tables gt  (cost=0.00..8.28 rows=1 width=18) (never executed)                                        │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 8                                                                                │
│                             ->  Index Scan using gc_webmapservices_resource_id_key on gc_webmapservices gwms  (cost=0.00..8.27 rows=1 width=418) (never executed)                     │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 9                                                                                │
│                             ->  Index Scan using gc_tables_resource_id_key on gc_tables gt  (cost=0.00..8.31 rows=1 width=14) (never executed)                                        │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 10                                                                                │
│                             ->  Index Scan using gc_webmapservices_resource_id_key on gc_webmapservices gwms  (cost=0.00..8.30 rows=1 width=267) (never executed)                     │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│               ->  Subquery Scan on "*SELECT* 2"  (cost=580092.62..681215149.42 rows=15856388 width=247) (actual time=17521.724..199482.039 rows=2737742 loops=1)                      │
│                     ->  Hash Join  (cost=580092.62..681056585.54 rows=15856388 width=247) (actual time=17521.668..198482.521 rows=2737742 loops=1)                                    │
│                           Hash Cond: (fnr_child.type = fnrt.type)                                                                                │
│                           ->  Hash Join  (cost=580056.53..1189954.39 rows=2733860 width=219) (actual time=16768.431..88474.618 rows=2737742 loops=1)                                  │
│                                 Hash Cond: (gf_parent.resource_id = fnr_parent.id)                                                                                │
│                                 ->  Hash Join  (cost=388738.70..943959.36 rows=2733860 width=219) (actual time=13619.604..72625.523 rows=2737742 loops=1)                             │
│                                       Hash Cond: (gf_child.path = gf_parent.pathname)                                                                                │
│                                       ->  Hash Join  (cost=202378.85..538142.64 rows=2733860 width=168) (actual time=6429.263..53255.517 rows=2737743 loops=1)                        │
│                                             Hash Cond: (fnr_child.id = gf_child.resource_id)                                                                                │
│                                             ->  Seq Scan on fn_resources fnr_child  (cost=0.00..114415.70 rows=6152170 width=30) (actual time=21.243..19364.289 rows=6119914 loops=1) │
│                                             ->  Hash  (cost=112139.60..112139.60 rows=2733860 width=142) (actual time=5666.626..5666.626 rows=2737743 loops=1)                        │
│                                                   Buckets: 262144  Batches: 2  Memory Usage: 240441kB                                                                                │
│                                                   ->  Seq Scan on gc_file gf_child  (cost=0.00..112139.60 rows=2733860 width=142) (actual time=0.015..3442.788 rows=2737751 loops=1)  │
│                                       ->  Hash  (cost=112139.60..112139.60 rows=2733860 width=92) (actual time=7173.094..7173.094 rows=2737751 loops=1)                               │
│                                             Buckets: 262144  Batches: 2  Memory Usage: 169423kB                                                                                │
│                                             ->  Seq Scan on gc_file gf_parent  (cost=0.00..112139.60 rows=2733860 width=92) (actual time=0.007..5057.412 rows=2737751 loops=1)        │
│                                 ->  Hash  (cost=114415.70..114415.70 rows=6152170 width=4) (actual time=3145.424..3145.424 rows=6119914 loops=1)                                      │
│                                       Buckets: 1048576  Batches: 1  Memory Usage: 215154kB                                                                                │
│                                       ->  Seq Scan on fn_resources fnr_parent  (cost=0.00..114415.70 rows=6152170 width=4) (actual time=0.008..1186.819 rows=6119914 loops=1)         │
│                           ->  Hash  (cost=21.60..21.60 rows=1160 width=36) (actual time=0.021..0.021 rows=21 loops=1)                                                                 │
│                                 Buckets: 1024  Batches: 1  Memory Usage: 1kB                                                                                │
│                                 ->  Seq Scan on fn_resource_types fnrt  (cost=0.00..21.60 rows=1160 width=36) (actual time=0.005..0.012 rows=21 loops=1)                              │
│                           SubPlan 1                                                                                │
│                             ->  Index Scan using users_pkey on fn_users  (cost=0.00..8.28 rows=1 width=13) (actual time=0.009..0.009 rows=1 loops=2737742)                            │
│                                   Index Cond: (id = fnr_child.owner_id)                                                                                │
│                           SubPlan 2                                                                                │
│                             ->  Index Scan using gc_file_resource_id_key on gc_file gf  (cost=0.00..8.62 rows=1 width=47) (never executed)                                            │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 3                                                                                │
│                             ->  Index Scan using gc_file_resource_id_key on gc_file gf  (cost=0.00..8.62 rows=1 width=47) (actual time=0.025..0.025 rows=1 loops=2665337)             │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 4                                                                                │
│                             ->  Index Scan using gc_file_resource_id_key on gc_file gf  (cost=0.00..8.63 rows=1 width=129) (never executed)                                           │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│                           SubPlan 5                                                                                │
│                             ->  Index Scan using gc_file_resource_id_key on gc_file gf  (cost=0.00..8.66 rows=1 width=145) (actual time=0.003..0.003 rows=1 loops=2665337)            │
│                                   Index Cond: (resource_id = fnr_child.id)                                                                                │
│         ->  Hash  (cost=4804.79..4804.79 rows=374 width=12) (actual time=412.434..412.434 rows=59 loops=1)                                                                            │
│               Buckets: 1024  Batches: 1  Memory Usage: 3kB                                                                                │
│               ->  Nested Loop  (cost=13.32..4804.79 rows=374 width=12) (actual time=156.510..412.313 rows=59 loops=1)                                                                 │
│                     ->  Bitmap Heap Scan on fn_resource_permissions  (cost=13.32..1454.38 rows=374 width=4) (actual time=155.407..402.734 rows=59 loops=1)                            │
│                           Recheck Cond: ((user_id = 2) OR (user_id = 1))                                                                                │
│                           Filter: (permission_id = ANY ('{23,24,25,37,36}'::integer[]))                                                                                │
│                           ->  BitmapOr  (cost=13.32..13.32 rows=391 width=0) (actual time=88.402..88.402 rows=0 loops=1)                                                              │
│                                 ->  Bitmap Index Scan on resource_permissions_user  (cost=0.00..6.57 rows=196 width=0) (actual time=88.380..88.380 rows=61 loops=1)                   │
│                                       Index Cond: (user_id = 2)                                                                                │
│                                 ->  Bitmap Index Scan on resource_permissions_user  (cost=0.00..6.57 rows=196 width=0) (actual time=0.016..0.016 rows=0 loops=1)                      │
│                                       Index Cond: (user_id = 1)                                                                                │
│                     ->  Index Scan using fn_resources_pkey on fn_resources  (cost=0.00..8.95 rows=1 width=8) (actual time=0.154..0.155 rows=1 loops=59)                               │
│                           Index Cond: (id = fn_resource_permissions.resource_id)                                                                                │
│                           Filter: (archived = 0)                                                                                │
│ Total runtime: 201373.236 ms                                                                                │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

Many thanks.

Body:
Your query is structured so thatfn_resources is filtered by fn_resource_permissions and then joined onto gc_drive, despite the same data being present in gc_drive.

This is a little bit of a hunch, but try filtering gc_drive by fn_resource_permissions early with the where clause, rather than a join on a join.

select
    gc_drive.id,
    fn_resources.owner_id,
    gc_drive.*
from
    gc_drive
    join fn_resources on(
        gc_drive.resource_id = fn_resources.id
    )
where
    gc_drive.resource_id in(
        select
            fn_resource_permissions.resource_id
        from
            fn_resource_permissions
        where
            fn_resource_permissions.permission_id in (23, 24, 25, 37, 36)
            and fn_resource_permissions.user_id in(1, 2)
    )
    and fn_resources.archived = 0
limit 101;

Alternativley, try filtering fn_resources before the join

select
    gc_drive.id,
    fn_resources.owner_id,
    gc_drive.*
from
    gc_drive
    join fn_resources on(
        gc_drive.resource_id = fn_resources.id
        and fn_resources.id in(
            select
                fn_resource_permissions.resource_id
            from
                fn_resource_permissions
            where
                fn_resource_permissions.permission_id in (23, 24, 25, 37, 36)
                and fn_resource_permissions.user_id in(1, 2)
        )
    )
where
    fn_resources.archived = 0
limit 101;


答:
You need to have the route available in the code. Try reading up on Express Basic Routing

Try the below and take it from there. I'm assuming that you're running on port 5000, if not, point to whatever port is set in process.env.PORT

```<code>app.get('/', function (req, res) {
  res.send('hello world');
})
</code>```

Title: Receiving "Cannot GET /" error when trying to connect using Node.js/Express

Body:
You need to have the route available in the code. Try reading up on Express Basic Routing

Try the below and take it from there. I'm assuming that you're running on port 5000, if not, point to whatever port is set in process.env.PORT

app.get('/', function (req, res) {
  res.send('hello world');
})