问:
#nowarn "2003" doesn't disable FS2003?
The following code, compiled in a fresh console project in VS2017 (v15.2), fails to suppress the FS2003 warning (which the #nowarn directive should suppress). I'm targeting F# 4.1 (FSharp.Core 4.4.1.0). Am I missing something here?

This attribute is to be used in existing generated code, so I want to use #nowarn rather than change every F# project's settings to ignore this warning. We compile with warnings treated as errors.

```<code>open System.Reflection

#nowarn "2003"
[<assembly: AssemblyInformationalVersion("13.3.1.74-g5224f3b")>]

do() // necessary for the assembly attribute

[<EntryPoint>]
let main argv = 0
</code>```

Compiler output in VS is

```<code>1>------ Rebuild All started: Project: ConsoleApplication4, Configuration: Release Any CPU ------
1>  C:\Program Files (x86)\Microsoft SDKs\F#\4.1\Framework\v4.0\fsc.exe -o:obj\Release\ConsoleApplication4.exe
1>--debug:pdbonly
1>--noframework
1>--define:TRACE
1>--doc:bin\Release\ConsoleApplication4.XML
1>--optimize+
1>--platform:anycpu32bitpreferred
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.4.1.0\FSharp.Core.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\mscorlib.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.Core.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.Numerics.dll
1>-r:C:\Users\cnichols\Documents\Visual Studio 2017\Projects\ConsoleApplication4\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Collections.Concurrent.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Collections.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ComponentModel.Annotations.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ComponentModel.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ComponentModel.EventBasedAsync.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Diagnostics.Contracts.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Diagnostics.Debug.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Diagnostics.Tools.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Diagnostics.Tracing.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Dynamic.Runtime.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Globalization.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.IO.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Linq.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Linq.Expressions.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Linq.Parallel.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Linq.Queryable.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Net.NetworkInformation.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Net.Primitives.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Net.Requests.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Net.WebHeaderCollection.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ObjectModel.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.Emit.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.Emit.ILGeneration.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.Emit.Lightweight.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.Extensions.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.Primitives.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Resources.ResourceManager.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Extensions.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Handles.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.InteropServices.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.InteropServices.WindowsRuntime.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Numerics.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Serialization.Json.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Serialization.Primitives.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Serialization.Xml.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Security.Principal.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ServiceModel.Duplex.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ServiceModel.Http.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ServiceModel.NetTcp.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ServiceModel.Primitives.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ServiceModel.Security.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Text.Encoding.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Text.Encoding.Extensions.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Text.RegularExpressions.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Threading.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Threading.Tasks.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Threading.Tasks.Parallel.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Threading.Timer.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Xml.ReaderWriter.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Xml.XDocument.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Xml.XmlSerializer.dll
1>--target:exe
1>--warn:3
1>--warnaserror:76
1>--vserrors
1>--utf8output
1>--fullpaths
1>--flaterrors
1>--subsystemversion:6.00
1>--highentropyva+
1>C:\Users\cnichols\AppData\Local\Temp\.NETFramework,Version=v4.6.2.AssemblyAttributes.fs
1>AssemblyInfo.fs
1>Program.fs
1>
1>FSC: warning FS2003: An System.Reflection.AssemblyInformationalVersionAttribute specified version '13.3.1.74-g5224f3b', but this value is invalid and has been ignored
1>  ConsoleApplication4 -> C:\Users\cnichols\Documents\Visual Studio 2017\Projects\ConsoleApplication4\ConsoleApplication4\bin\Release\ConsoleApplication4.exe
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========
</code>```

Updates

Problem reproduced after a reboot.

Problem reproduced on VS 2017 15.2 26430.4.

Problem reproduced on VS 2017 15.2 26430.6.

Problem reproduced on VS 2015 14.0.25431.01 Update 3.

Problem reproduced on a different PC.

Opened an issue against F#: #nowarn “2003” doesn't disable FS2003 #3139

答:
Microsoft has assigned a priority to this bug and has a proper, working repro.

And again, this warning clearly does get converted to an error when building with "warnings as errors."

Title: #nowarn "2003" doesn't disable FS2003?

Body:
The following code, compiled in a fresh console project in VS2017 (v15.2), fails to suppress the FS2003 warning (which the #nowarn directive should suppress). I'm targeting F# 4.1 (FSharp.Core 4.4.1.0). Am I missing something here?

This attribute is to be used in existing generated code, so I want to use #nowarn rather than change every F# project's settings to ignore this warning. We compile with warnings treated as errors.

open System.Reflection

#nowarn "2003"
[<assembly: AssemblyInformationalVersion("13.3.1.74-g5224f3b")>]

do() // necessary for the assembly attribute

[<EntryPoint>]
let main argv = 0

Compiler output in VS is

1>------ Rebuild All started: Project: ConsoleApplication4, Configuration: Release Any CPU ------
1>  C:\Program Files (x86)\Microsoft SDKs\F#\4.1\Framework\v4.0\fsc.exe -o:obj\Release\ConsoleApplication4.exe
1>--debug:pdbonly
1>--noframework
1>--define:TRACE
1>--doc:bin\Release\ConsoleApplication4.XML
1>--optimize+
1>--platform:anycpu32bitpreferred
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.4.1.0\FSharp.Core.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\mscorlib.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.Core.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.Numerics.dll
1>-r:C:\Users\cnichols\Documents\Visual Studio 2017\Projects\ConsoleApplication4\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Collections.Concurrent.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Collections.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ComponentModel.Annotations.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ComponentModel.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ComponentModel.EventBasedAsync.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Diagnostics.Contracts.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Diagnostics.Debug.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Diagnostics.Tools.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Diagnostics.Tracing.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Dynamic.Runtime.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Globalization.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.IO.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Linq.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Linq.Expressions.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Linq.Parallel.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Linq.Queryable.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Net.NetworkInformation.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Net.Primitives.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Net.Requests.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Net.WebHeaderCollection.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ObjectModel.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.Emit.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.Emit.ILGeneration.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.Emit.Lightweight.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.Extensions.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Reflection.Primitives.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Resources.ResourceManager.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Extensions.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Handles.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.InteropServices.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.InteropServices.WindowsRuntime.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Numerics.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Serialization.Json.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Serialization.Primitives.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Runtime.Serialization.Xml.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Security.Principal.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ServiceModel.Duplex.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ServiceModel.Http.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ServiceModel.NetTcp.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ServiceModel.Primitives.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.ServiceModel.Security.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Text.Encoding.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Text.Encoding.Extensions.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Text.RegularExpressions.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Threading.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Threading.Tasks.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Threading.Tasks.Parallel.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Threading.Timer.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Xml.ReaderWriter.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Xml.XDocument.dll
1>-r:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\Facades\System.Xml.XmlSerializer.dll
1>--target:exe
1>--warn:3
1>--warnaserror:76
1>--vserrors
1>--utf8output
1>--fullpaths
1>--flaterrors
1>--subsystemversion:6.00
1>--highentropyva+
1>C:\Users\cnichols\AppData\Local\Temp\.NETFramework,Version=v4.6.2.AssemblyAttributes.fs
1>AssemblyInfo.fs
1>Program.fs
1>
1>FSC: warning FS2003: An System.Reflection.AssemblyInformationalVersionAttribute specified version '13.3.1.74-g5224f3b', but this value is invalid and has been ignored
1>  ConsoleApplication4 -> C:\Users\cnichols\Documents\Visual Studio 2017\Projects\ConsoleApplication4\ConsoleApplication4\bin\Release\ConsoleApplication4.exe
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

Updates

Problem reproduced after a reboot.

Problem reproduced on VS 2017 15.2 26430.4.

Problem reproduced on VS 2017 15.2 26430.6.

Problem reproduced on VS 2015 14.0.25431.01 Update 3.

Problem reproduced on a different PC.

Opened an issue against F#: #nowarn “2003” doesn't disable FS2003 #3139


来源: stackexchange

问:
Foreach loop, determine which is the last iteration of the loop
I have a foreach loop and need to execute some logic when the last item is chosen from the List, e.g.:

```<code> foreach (Item result in Model.Results)
 {
      //if current result is the last item in Model.Results
      //then do something in the code
 }
</code>```

Can I know which loop is last without using for loop and counters?

答:
How to convert foreach to react to the last element:

```<code>List<int> myList = new List<int>() {1, 2, 3, 4, 5};
Console.WriteLine("foreach version");
{
    foreach (var current in myList)
    {
        Console.WriteLine(current);
    }
}
Console.WriteLine("equivalent that reacts to last element");
{
    var enumerator = myList.GetEnumerator();
    if (enumerator.MoveNext() == true) // Corner case: empty list.
    {
        while (true)
        {
            int current = enumerator.Current;

            // Handle current element here.
            Console.WriteLine(current);

            bool ifLastElement = (enumerator.MoveNext() == false);
            if (ifLastElement)
            {
                // Cleanup after last element
                Console.WriteLine("[last element]");
                break;
            }
        }
    }
    enumerator.Dispose();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a foreach loop and need to execute some logic when the last item is chosen from the List, e.g.:

 foreach (Item result in Model.Results)
 {
      //if current result is the last item in Model.Results
      //then do something in the code
 }

Can I know which loop is last without using for loop and counters?

Body:
How to convert foreach to react to the last element:

List<int> myList = new List<int>() {1, 2, 3, 4, 5};
Console.WriteLine("foreach version");
{
    foreach (var current in myList)
    {
        Console.WriteLine(current);
    }
}
Console.WriteLine("equivalent that reacts to last element");
{
    var enumerator = myList.GetEnumerator();
    if (enumerator.MoveNext() == true) // Corner case: empty list.
    {
        while (true)
        {
            int current = enumerator.Current;

            // Handle current element here.
            Console.WriteLine(current);

            bool ifLastElement = (enumerator.MoveNext() == false);
            if (ifLastElement)
            {
                // Cleanup after last element
                Console.WriteLine("[last element]");
                break;
            }
        }
    }
    enumerator.Dispose();
}


问:
magento installation error - reset.php is missing
Any idea about the below error

Fatal error: require_once(): Failed opening required '/home/inhyshoper/public_html/app/design/frontend/default/default/etc/reset.php' (include_path='/home/inhyshoper/public_html/includes/src:.:/usr/lib/php:/usr/local/lib/php') in /public_html/includes/src/EM_Themeframework_Model_Observer.php on line 287

答:
Magento version?
Which theme installed</p>

Body:
Magento version?
Which theme installed


问:
Is this sieve really O(n)?
Can anyone please tell me how this is working in O(n).

http://www.geeksforgeeks.org/sieve-eratosthenes-0n-time-complexity/

void manipulated_seive(int N)
{
    // 0 and 1 are not prime
    isprime[0] = isprime[1] = false ;

    // Fill rest of the entries
    for (long long int i=2; i<N ; i++)
    {
        // If isPrime[i] == True then i is
        // prime number
        if (isprime[i])
        {
            // put i into prime[] vector
            prime.push_back(i);

            // A prime number is its own smallest
            // prime factor
            SPF[i] = i;
        }

        // Remove all multiples of  i*prime[j] which are
        // not prime by making isPrime[i*prime[j]] = false
        // and put smallest prime factor of i*Prime[j] as prime[j]
        // [ for exp :let  i = 5 , j = 0 , prime[j] = 2 [ i*prime[j] = 10 ]
        // so smallest prime factor of '10' is '2' that is prime[j] ]
        // this loop run only one time for number which are not prime
        for (long long int j=0;
             j < (int)prime.size() &&
             i*prime[j] < N && prime[j] <= SPF[i];
             j++)
        {
            isprime[i*prime[j]]=false;

            // put smallest prime factor of i*prime[j]
            SPF[i*prime[j]] = prime[j] ;
        }
    }
}
```

I think the outer loop will run O(n) time and inner loop will run O(number of primes less than N) in case of prime numbers and O(1) in case of composite. But overall is should be O(n) * O(number of primes less than n). Am i missing something?

Thanks in advance.

答:
The key idea is that each integer between 2 and n is encountered exactly once in the SPF calculation, thus the total number of iterations of the innermost loop is O(n).

The innermost loop fills the SPF array which indicates the smallest prime factor, for each integer between 2 and n.

Indeed, to compute the SPF array, each integer k between 2 and n is represented as k = i*prime[j], where prime[j] is a prime number below all prime factors of i (this is ensured by the prime[j] <= SPF[i] condition which would break the loop otherwise). This means that prime[j] is the smallest prime factor of k. But this representation is unique for each k (i.e. the same k won't be encountered once again, as another k = i2 * prime[j2] factorization, because if prime[j2] is not equal to prime[j] then one of them would not be the smallest prime factor of k). Thus each number k between 2 and n appears exactly once as the product i*prime[j], computed in the innermost loop.

Title: Is this sieve really O(n)?

Body:
Can anyone please tell me how this is working in O(n).

http://www.geeksforgeeks.org/sieve-eratosthenes-0n-time-complexity/

void manipulated_seive(int N)
{
    // 0 and 1 are not prime
    isprime[0] = isprime[1] = false ;

    // Fill rest of the entries
    for (long long int i=2; i<N ; i++)
    {
        // If isPrime[i] == True then i is
        // prime number
        if (isprime[i])
        {
            // put i into prime[] vector
            prime.push_back(i);

            // A prime number is its own smallest
            // prime factor
            SPF[i] = i;
        }

        // Remove all multiples of  i*prime[j] which are
        // not prime by making isPrime[i*prime[j]] = false
        // and put smallest prime factor of i*Prime[j] as prime[j]
        // [ for exp :let  i = 5 , j = 0 , prime[j] = 2 [ i*prime[j] = 10 ]
        // so smallest prime factor of '10' is '2' that is prime[j] ]
        // this loop run only one time for number which are not prime
        for (long long int j=0;
             j < (int)prime.size() &&
             i*prime[j] < N && prime[j] <= SPF[i];
             j++)
        {
            isprime[i*prime[j]]=false;

            // put smallest prime factor of i*prime[j]
            SPF[i*prime[j]] = prime[j] ;
        }
    }
}

I think the outer loop will run O(n) time and inner loop will run O(number of primes less than N) in case of prime numbers and O(1) in case of composite. But overall is should be O(n) * O(number of primes less than n). Am i missing something?

Thanks in advance.


问:
Infinite re-direct loop after AAD Authentication when redirect is specified
If I specify a redirect URI in my OpenIdConnectAuthenticationOptions like so

```<code>app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = Authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = redirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
</code>```

Then I get an infinite re-direct loop. This only happens though when i put it on and standalone IIS Server (our test server).  If i remove all the Replay url's in AAD and leave it only setup for the test server, and remove the "RedirectUri = redirectUri," from the above my problem goes away.

I have a fiddler log here : https://drive.google.com/file/d/0B5Ap95E_wdyAa0RLLWloZ0dCaGM/view?usp=sharing

It appears that when request from AAD comes back to my app, before the token is grabbed and used, the Middle Ware is just bouncing it right back with a 302.  Also what may be important, I have the [Authorize] attribute over the mvc controller that the routing and return uri directs to.  If I remove it i do not get this issue.

[UPDATE]
I tried moving the application to my localhost install of IIS rather than using iisexpress so that i could setup as a SubApplication like it is on my iis server.  On my localhost it does the same infinite loop.  I added in some telemetry custom events on an override of the [Authorize] attribute and have been able to discover that when page is re-directed back to the application after authentication httpContext.user.identity.IsAuthenticated = false.  So somehow the OWIN middle ware is not setting this to true?

Thanks for any help!

答:
I was able to find a solution to my problem.  Originally i was specifying my reply url's to point to the root of the site.  My rout config looks like this:

```<code>routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Welcome", action = "Index", id = UrlParameter.Optional }
        );
</code>```

If I append "Welcome" to the end of my reply url it works.  For some reason if i leave the reply url to the root of the site and have the default route picked up it just goes into an infinite loop.

I found out also that this only applies to a sub application of a site.  I tried moving my application to be a standalone site in iis so   rather than  and I didnt have to add the controller name in the reply url.

Example:

Original reply url:
mysite.mydomain.com/CustomApp

New Reply url:
mysite.mydomain.com/CustomApp/Welcome

Hope someone else can find this useful!

UPDATE

I found out that the root of the problem was still caused from this mvc5 bug: katanaproject.codeplex.com/workitem/197. I thought it had been fixed but it has not, so i will continue to use the well known Kentor Owin Cookie Saver: github.com/Sustainsys/owin-cookie-saver

Body:
If I specify a redirect URI in my OpenIdConnectAuthenticationOptions like so

app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = Authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = redirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });

Then I get an infinite re-direct loop. This only happens though when i put it on and standalone IIS Server (our test server).  If i remove all the Replay url's in AAD and leave it only setup for the test server, and remove the "RedirectUri = redirectUri," from the above my problem goes away.

I have a fiddler log here : https://drive.google.com/file/d/0B5Ap95E_wdyAa0RLLWloZ0dCaGM/view?usp=sharing

It appears that when request from AAD comes back to my app, before the token is grabbed and used, the Middle Ware is just bouncing it right back with a 302.  Also what may be important, I have the [Authorize] attribute over the mvc controller that the routing and return uri directs to.  If I remove it i do not get this issue.

[UPDATE]
I tried moving the application to my localhost install of IIS rather than using iisexpress so that i could setup as a SubApplication like it is on my iis server.  On my localhost it does the same infinite loop.  I added in some telemetry custom events on an override of the [Authorize] attribute and have been able to discover that when page is re-directed back to the application after authentication httpContext.user.identity.IsAuthenticated = false.  So somehow the OWIN middle ware is not setting this to true?

Thanks for any help!

Body:
I was able to find a solution to my problem.  Originally i was specifying my reply url's to point to the root of the site.  My rout config looks like this:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Welcome", action = "Index", id = UrlParameter.Optional }
        );

If I append "Welcome" to the end of my reply url it works.  For some reason if i leave the reply url to the root of the site and have the default route picked up it just goes into an infinite loop.

I found out also that this only applies to a sub application of a site.  I tried moving my application to be a standalone site in iis so   rather than  and I didnt have to add the controller name in the reply url.

Example:

Original reply url:
mysite.mydomain.com/CustomApp

New Reply url:
mysite.mydomain.com/CustomApp/Welcome

Hope someone else can find this useful!

UPDATE

I found out that the root of the problem was still caused from this mvc5 bug: katanaproject.codeplex.com/workitem/197. I thought it had been fixed but it has not, so i will continue to use the well known Kentor Owin Cookie Saver: github.com/Sustainsys/owin-cookie-saver

ContentLicense: CC BY-SA 4.0


问:
How to delegate interface implementation to other class in C#
Assume the following class:

```<code>public class MyEnum: IEnumerator
{
    private List<SomeObject> _myList = new List<SomeObject>();
...
}
</code>```

It is necessary to implement the IEnumerator methods in MyEnum.
But is it possible to 'delegate' or redirect the implementation for IEnumerator directly to _myList without needing to implement the IEnumerator methods?

答:
Note that thanks to duck-typing, you can use foreach on any object that has a GetEnumerator method - the object type need not actually implement IEnumerable.

So if you do this:

```<code>class SomeObject
{
}

 class MyEnum
 {
    private List<SomeObject> _myList = new List<SomeObject>();

    public IEnumerator<SomeObject> GetEnumerator()
    {
        return _myList.GetEnumerator();
    }
 }
</code>```

Then this works just fine:

```<code>MyEnum objects = new MyEnum();
// ... add some objects
foreach (SomeObject obj in objects)
{
    Console.WriteLine(obj.ToString());
}
</code>```

OwnerDisplayName: Willem

ContentLicense: CC BY-SA 2.5

Body:
Assume the following class:

public class MyEnum: IEnumerator
{
    private List<SomeObject> _myList = new List<SomeObject>();
...
}

It is necessary to implement the IEnumerator methods in MyEnum.
But is it possible to 'delegate' or redirect the implementation for IEnumerator directly to _myList without needing to implement the IEnumerator methods?

Body:
Note that thanks to duck-typing, you can use foreach on any object that has a GetEnumerator method - the object type need not actually implement IEnumerable.

So if you do this:

class SomeObject
{
}

 class MyEnum
 {
    private List<SomeObject> _myList = new List<SomeObject>();

    public IEnumerator<SomeObject> GetEnumerator()
    {
        return _myList.GetEnumerator();
    }
 }

Then this works just fine:

MyEnum objects = new MyEnum();
// ... add some objects
foreach (SomeObject obj in objects)
{
    Console.WriteLine(obj.ToString());
}


问:
Can't get my Ranges set up from my spreadsheet using VBA
My overall goal here is to grab the values and row indices of three different columns on the original spreadsheet, evaluate them, and then save them to a new spreadsheet. I am wanted to accomplish this by using a macro initiated by a button on the original spreadsheet.

The plan to accomplish this was to

create a Range for each column

Loop through the most significant Range to grab and evaluate the each cell      value

perform nested loops within the first loop to further evaluate the other two Ranges and grab their values

assign values to variables

create the new spreadsheet from a template

write the values to the respective columns

save the new spreadsheet

When I run the code below I get the error listed below. I'm confused because I thought this is how you reference an entire column:

```<code>Sub Transfer2NewWorkbook()
  Dim currentsheet As String
  Dim newsheet As String
  Dim analysisDate As String
  Dim initial As String
  Dim aInitial() As String
  Dim analystInit As String
  Dim batchNo As String

  Dim wb As Object
  Dim dataRangeA As Range, dataRangeB As Range, dataRangeI As Range
  Set dataA = CreateObject("Scripting.Dictionary")

  ' Grab and Create filenames
  currentsheet = ActiveWorkbook.Name
  newsheet = currentsheet & "-" & "uploadable"

  ' Grab data from original spreadsheet
  analysisDate = ActiveWorkbook.Sheets(1).Cells(1, 9).Value

  initial = ActiveWorkbook.Sheets(1).Cells(1, 2).Value
  aInitial = Split(initial, "/")
  analystInit = aInitial(1)

  Set dataRangeA = Range("A4:A").Select ' <-- Line causing error
  Set dataRangeB = Range("B4:B").Select
  Set dataRangeI = Range("I4:I").Select

  For i = 1 To dataRangeA.Rows.Count
    dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
  Next i

  Set wb = Workbooks.Add("C:\Users\dalythe\documents\uploadtemp.xlsx")

  ActiveWorkbook.Sheets(1).Cells(3, 2).Value = analysisDate
  ActiveWorkbook.Sheets(1).Cells(3, 4).Value = analystInit

  ActiveWorkbook.SaveAs (newsheet & ".xlsx")

End Sub
</code>```

答:
After removing the .Select, my ranges were accepted.

```<code>Set dataRangeA = Range("A:A")
Set dataRangeB = Range("B:B")
Set dataRangeI = Range("I:I")

For i = 4 To dataRangeA.Rows.Count
   dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
Next i
</code>```

Thanks for the input YowE3k. Now I have to think on how I want my loop to end. Because doing it the way I have it above will cause it to run out of memory. The spreadsheet will not have a "predefined" number of rows. I guess I will have to have the user type "End" in the cell of the last row or something.

Body:
My overall goal here is to grab the values and row indices of three different columns on the original spreadsheet, evaluate them, and then save them to a new spreadsheet. I am wanted to accomplish this by using a macro initiated by a button on the original spreadsheet.

The plan to accomplish this was to

create a Range for each column

Loop through the most significant Range to grab and evaluate the each cell      value

perform nested loops within the first loop to further evaluate the other two Ranges and grab their values

assign values to variables

create the new spreadsheet from a template

write the values to the respective columns

save the new spreadsheet

When I run the code below I get the error listed below. I'm confused because I thought this is how you reference an entire column:

Sub Transfer2NewWorkbook()
  Dim currentsheet As String
  Dim newsheet As String
  Dim analysisDate As String
  Dim initial As String
  Dim aInitial() As String
  Dim analystInit As String
  Dim batchNo As String

  Dim wb As Object
  Dim dataRangeA As Range, dataRangeB As Range, dataRangeI As Range
  Set dataA = CreateObject("Scripting.Dictionary")

  ' Grab and Create filenames
  currentsheet = ActiveWorkbook.Name
  newsheet = currentsheet & "-" & "uploadable"

  ' Grab data from original spreadsheet
  analysisDate = ActiveWorkbook.Sheets(1).Cells(1, 9).Value

  initial = ActiveWorkbook.Sheets(1).Cells(1, 2).Value
  aInitial = Split(initial, "/")
  analystInit = aInitial(1)

  Set dataRangeA = Range("A4:A").Select ' <-- Line causing error
  Set dataRangeB = Range("B4:B").Select
  Set dataRangeI = Range("I4:I").Select

  For i = 1 To dataRangeA.Rows.Count
    dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
  Next i

  Set wb = Workbooks.Add("C:\Users\dalythe\documents\uploadtemp.xlsx")

  ActiveWorkbook.Sheets(1).Cells(3, 2).Value = analysisDate
  ActiveWorkbook.Sheets(1).Cells(3, 4).Value = analystInit

  ActiveWorkbook.SaveAs (newsheet & ".xlsx")

End Sub

Body:
After removing the .Select, my ranges were accepted.

Set dataRangeA = Range("A:A")
Set dataRangeB = Range("B:B")
Set dataRangeI = Range("I:I")

For i = 4 To dataRangeA.Rows.Count
   dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
Next i

Thanks for the input YowE3k. Now I have to think on how I want my loop to end. Because doing it the way I have it above will cause it to run out of memory. The spreadsheet will not have a "predefined" number of rows. I guess I will have to have the user type "End" in the cell of the last row or something.


问:
In firefox, how to change color of text in a treecell using javascript
BACKGROUND:
I have the following XUL fragment

```<code><tree id="treeToChange" flex="1">
  <treecols>
    <treecol label = "First Column" id="c1" flex="1"/>
    <treecol label = "Second Column" id="c2" flex="1"/>
  </treecols>
  <treechildren>
    <treeitem>
      <treerow>
        <treecell label="Data for Column 1"/>
        <treecell label="Data for Column 2"/>
      </treerow>
    </treeitem>
  </treechildren>
</tree>
</code>```

and the following css fragment

```<code>tree {  font-size: 120%; color: green;}
</code>```

This causes my column data to be displayed in green text.

I have many such tree objects on the XUL page

QUESTION:
In firefox, in response to a click event, which calls a javascript routine, how do I set the data for the object "treeToChange" in column 1 red and the data in column blue?

答:
The style property of a DOM element contains all the CSS declarations for that element. The naming scheme is slightly different (camelCaps instead of dashes), but otherwise exactly the same.

```<code> element.style.color = 'blue';
</code>```

You can read more on the style property in the Mozilla javascript manual.

OwnerDisplayName: Noah

Body:
BACKGROUND:
I have the following XUL fragment

<tree id="treeToChange" flex="1">
  <treecols>
    <treecol label = "First Column" id="c1" flex="1"/>
    <treecol label = "Second Column" id="c2" flex="1"/>
  </treecols>
  <treechildren>
    <treeitem>
      <treerow>
        <treecell label="Data for Column 1"/>
        <treecell label="Data for Column 2"/>
      </treerow>
    </treeitem>
  </treechildren>
</tree>

and the following css fragment

tree {  font-size: 120%; color: green;}

This causes my column data to be displayed in green text.

I have many such tree objects on the XUL page

QUESTION:
In firefox, in response to a click event, which calls a javascript routine, how do I set the data for the object "treeToChange" in column 1 red and the data in column blue?

LastEditorDisplayName: Noah

Body:
The style property of a DOM element contains all the CSS declarations for that element. The naming scheme is slightly different (camelCaps instead of dashes), but otherwise exactly the same.

 element.style.color = 'blue';

You can read more on the style property in the Mozilla javascript manual.

OwnerDisplayName: Eran Galperin


问:
How to select first item as default in Angular JS dropdown?
I'm trying to use a dropdown, but I'm not able to select 1st value as selected by default. It showing blank.
master_data.sch_files has 4 items, but it shows 5 in dropdown in which 1st time is blank.</p>

```<code><select ng-init="item.file_range_unit = master_data.sch_files[0].ref_key" ng-model="item.file_range_unit"
                        ng-options="x.ref_key as x.ref_value for x in master_data.sch_files" required style="height: 33px;
                       width: 140px; padding-left:5px">
                  </select>
</code>```

答:
Reference: Why does AngularJS include an empty option in select?

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.

In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.

All you need to do is to give a default value to:

```<code>item.file_range_unit
</code>```

Body:
I'm trying to use a dropdown, but I'm not able to select 1st value as selected by default. It showing blank.
master_data.sch_files has 4 items, but it shows 5 in dropdown in which 1st time is blank.

<select ng-init="item.file_range_unit = master_data.sch_files[0].ref_key" ng-model="item.file_range_unit"
                        ng-options="x.ref_key as x.ref_value for x in master_data.sch_files" required style="height: 33px;
                       width: 140px; padding-left:5px">
                  </select>

Body:
Reference: Why does AngularJS include an empty option in select?

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.

In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.

All you need to do is to give a default value to:

item.file_range_unit


问:
Excel VBA for Unhiding or Hiding a Worksheet Conditionally Based on Cell Value
I have attempted many different times to formulate a code for this and even tried a few strings of code I found on this site, but I have been unable to find a resolution.

My goal is to have a hidden worksheet pop up as unhidden when the user selects "yes" from the dropdown in a cell on another worksheet for the user to enter their notes on then if the cell is populated at N/A or (Select) have the sheet remain hidden.

Could anyone help with this?

Here is the most recent code I attempted:

```<code>Sheets("Prop. Pres. Notes 206-261").Activate
If Range("G39").Value = "YES" Then
Sheets("Prop. Pres. Notes 206-261").Visible = True
Else
Sheets("Prop. Pres. Notes 206-261").Visible = False
End If
</code>```

答:
Place this under your main sheet in Microsoft Excel Objects</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$G$39" Then
        'Change Sheet1 to the name of your main sheet
        If ActiveWorkbook.Worksheets("Sheet1").Range("G39").Value = "YES" Then
            Sheets("Prop. Pres. Notes 206-261").Visible = True
        Else
            Sheets("Prop. Pres. Notes 206-261").Visible = False
        End If
    End If
End Sub
</code>```

Body:
I have attempted many different times to formulate a code for this and even tried a few strings of code I found on this site, but I have been unable to find a resolution.

My goal is to have a hidden worksheet pop up as unhidden when the user selects "yes" from the dropdown in a cell on another worksheet for the user to enter their notes on then if the cell is populated at N/A or (Select) have the sheet remain hidden.

Could anyone help with this?

Here is the most recent code I attempted:

Sheets("Prop. Pres. Notes 206-261").Activate
If Range("G39").Value = "YES" Then
Sheets("Prop. Pres. Notes 206-261").Visible = True
Else
Sheets("Prop. Pres. Notes 206-261").Visible = False
End If

Body:
Place this under your main sheet in Microsoft Excel Objects

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$G$39" Then
        'Change Sheet1 to the name of your main sheet
        If ActiveWorkbook.Worksheets("Sheet1").Range("G39").Value = "YES" Then
            Sheets("Prop. Pres. Notes 206-261").Visible = True
        Else
            Sheets("Prop. Pres. Notes 206-261").Visible = False
        End If
    End If
End Sub


问:
Python logging to MemoryHandler initialised in configuration file
I am trying to add the python MemoryHandler into a logging configuration file. I am using a similar structure to a file handler that worked previously. I am a bit confused as to the error I am receiving and can't figure out what I am missing in order to get the logging to go to memory. The necessary information has been included below.In assistance would be greatly appreciated.

log_settings.conf

```<code>[loggers]
keys=root

[handlers]
keys=memHandler, consoleHandler

[formatters]
keys=fileFormatter, consoleFormatter

[logger_root]
level=DEBUG
handlers=memHandler, consoleHandler

[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=consoleFormatter
args=(sys.stdout,)

[handler_memHandler]
class=handlers.MemoryHandler
formatter=fileFormatter
args=(10, DEBUG, '%(logfilename)s')

[formatter_fileFormatter]
format=[%(asctime)s] [%(levelname)8s] --- (%(filename)15s:%(lineno)4s) %(message)s
datefmt=%Y-%m-%d %H:%M:%S

[formatter_consoleFormatter]
format=%(message)s
</code>```

Error Traceback

```<code>Traceback (most recent call last):
  File "E:\BuildScript\proj_tcl\blr_sbz\blr_sbz_build.py", line 22, in <module>
    main(args.jenkins, args.revision, args.jenkins_num)
  File "E:\BuildScript\proj_tcl\blr_sbz\blr_sbz_build.py", line 10, in main
    build(jenkins, revision, jenkins_num)
  File "../scripts\build.py", line 17, in build
    logging.info('Starting the FGPA build script')
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 1870, in info
    root.info(msg, *args, **kwargs)
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 1301, in info
    self._log(INFO, msg, args, **kwargs)
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 1437, in _log
    self.handle(record)
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 1447, in handle
    self.callHandlers(record)
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 1509, in callHandlers
    hdlr.handle(record)
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 858, in handle
    self.emit(record)
  File "C:\Program Files\Python36\lib\logging\handlers.py", line 1213, in emit
    self.flush()
  File "C:\Program Files\Python36\lib\logging\handlers.py", line 1289, in flush
    self.target.handle(record)
AttributeError: 'str' object has no attribute 'handle'
</code>```

build.py

```<code>logging.config.fileConfig('../scripts/logging/log_settings.conf', defaults={'logfilename': '../scripts/logging/log.log'})
logging.info('Starting the FGPA build script')
</code>```

答:
Use this configuration file instead:

```<code>[loggers]
keys=root

[handlers]
keys=memHandler, consoleHandler

[formatters]
keys=fileFormatter, consoleFormatter

[logger_root]
level=DEBUG
handlers=memHandler

[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=consoleFormatter
args=(sys.stdout,)

[handler_memHandler]
class=handlers.MemoryHandler
formatter=fileFormatter
args=(10, DEBUG)
target=consoleHandler

[formatter_fileFormatter]
format=[%(asctime)s] [%(levelname)8s] --- (%(filename)15s:%(lineno)4s) %(message)s
datefmt=%Y-%m-%d %H:%M:%S

[formatter_consoleFormatter]
format=%(message)s
</code>```

Note that you shouldn't include the consoleHandler in the list of handlers for the root logger. Also, you need to set the target using a target= line, and it needs to reference the key for the target handler. Use the following to configure:

```<code>logging.config.fileConfig('logging.ini')
</code>```

Body:
I am trying to add the python MemoryHandler into a logging configuration file. I am using a similar structure to a file handler that worked previously. I am a bit confused as to the error I am receiving and can't figure out what I am missing in order to get the logging to go to memory. The necessary information has been included below.In assistance would be greatly appreciated.

log_settings.conf

[loggers]
keys=root

[handlers]
keys=memHandler, consoleHandler

[formatters]
keys=fileFormatter, consoleFormatter

[logger_root]
level=DEBUG
handlers=memHandler, consoleHandler

[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=consoleFormatter
args=(sys.stdout,)

[handler_memHandler]
class=handlers.MemoryHandler
formatter=fileFormatter
args=(10, DEBUG, '%(logfilename)s')

[formatter_fileFormatter]
format=[%(asctime)s] [%(levelname)8s] --- (%(filename)15s:%(lineno)4s) %(message)s
datefmt=%Y-%m-%d %H:%M:%S

[formatter_consoleFormatter]
format=%(message)s

Error Traceback

Traceback (most recent call last):
  File "E:\BuildScript\proj_tcl\blr_sbz\blr_sbz_build.py", line 22, in <module>
    main(args.jenkins, args.revision, args.jenkins_num)
  File "E:\BuildScript\proj_tcl\blr_sbz\blr_sbz_build.py", line 10, in main
    build(jenkins, revision, jenkins_num)
  File "../scripts\build.py", line 17, in build
    logging.info('Starting the FGPA build script')
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 1870, in info
    root.info(msg, *args, **kwargs)
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 1301, in info
    self._log(INFO, msg, args, **kwargs)
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 1437, in _log
    self.handle(record)
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 1447, in handle
    self.callHandlers(record)
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 1509, in callHandlers
    hdlr.handle(record)
  File "C:\Program Files\Python36\lib\logging\__init__.py", line 858, in handle
    self.emit(record)
  File "C:\Program Files\Python36\lib\logging\handlers.py", line 1213, in emit
    self.flush()
  File "C:\Program Files\Python36\lib\logging\handlers.py", line 1289, in flush
    self.target.handle(record)
AttributeError: 'str' object has no attribute 'handle'

build.py

logging.config.fileConfig('../scripts/logging/log_settings.conf', defaults={'logfilename': '../scripts/logging/log.log'})
logging.info('Starting the FGPA build script')

Body:
Use this configuration file instead:

[loggers]
keys=root

[handlers]
keys=memHandler, consoleHandler

[formatters]
keys=fileFormatter, consoleFormatter

[logger_root]
level=DEBUG
handlers=memHandler

[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=consoleFormatter
args=(sys.stdout,)

[handler_memHandler]
class=handlers.MemoryHandler
formatter=fileFormatter
args=(10, DEBUG)
target=consoleHandler

[formatter_fileFormatter]
format=[%(asctime)s] [%(levelname)8s] --- (%(filename)15s:%(lineno)4s) %(message)s
datefmt=%Y-%m-%d %H:%M:%S

[formatter_consoleFormatter]
format=%(message)s

Note that you shouldn't include the consoleHandler in the list of handlers for the root logger. Also, you need to set the target using a target= line, and it needs to reference the key for the target handler. Use the following to configure:

logging.config.fileConfig('logging.ini')


问:
iOS - Floating Single Button
I need a floating button in my iPhone app, I saw many libraries online like this one: https://cocoapods.org/pods/LiquidFloatingActionButton

But I need it to be just a single button, not a menu - Do you know of any other libraries that do this? Or a way to customise one of the current libraries to do what I need?

Thanks!

答:
There is an approach to this by using KCFloating action button and adding a tapGestureRecognizer to a view containing this button.

So, just adding KCFloatingActionButton's pod and adding another view containing it it's possible to have a single floating action button just as androids.

If you require more detail to solve this issue tell me and I'll try to help

Sample image

Title: iOS - Floating Single Button


问:
can I use subquery in the inner join condition sql
table (Trips)

```<code>| Id | Client_Id | Driver_Id | City_Id |     Status      |Request_at|

| 1  |     1     |    10     |    1    |     completed      |2013-10-01|

| 2  |     2     |    10     |    1    |     completed      |2013-10-02|

| 3  |     3     |    11     |    6    |     completed      |2013-10-03|
</code>```

table ( users)

```<code>Users_Id    | Banned |  Role  |

|    1     |   No   | client |

|    2     |   Yes  | client |

|    3     |   No   | client |

|    4     |   No      | driver|
</code>```

How can I join these 2 tables (trips, users) on the condition that the user role needs to be client and these clients should be unbanned.
I am trying to use a subquery but I got "single-row subquery returns more than one row"error and not sure what went wrong.

```<code>SELECT * FROM Trips
INNER JOIN users
ON client_id = (SELECT users_id from users
                  where
                  role = 'Client' and  banned = 'No');
</code>```

答:
No need for a sub-select, just put those conditions into the join condition.

```<code>SELECT *
FROM Trips
  JOIN users ON trips.client_id = users.users_id
            and users.role = 'Client'
            and users.banned = 'No';
</code>```

As that is an inner join, this is equivalent to:

```<code>SELECT *
FROM Trips
  JOIN users ON trips.client_id = users.users_id
WHERE users.role = 'Client'
  and users.banned = 'No';
</code>```

This would not be different if you had used an outer join

Body:
table (Trips)

| Id | Client_Id | Driver_Id | City_Id |     Status      |Request_at|

| 1  |     1     |    10     |    1    |     completed      |2013-10-01|

| 2  |     2     |    10     |    1    |     completed      |2013-10-02|

| 3  |     3     |    11     |    6    |     completed      |2013-10-03|

table ( users)

Users_Id    | Banned |  Role  |

|    1     |   No   | client |

|    2     |   Yes  | client |

|    3     |   No   | client |

|    4     |   No      | driver|

How can I join these 2 tables (trips, users) on the condition that the user role needs to be client and these clients should be unbanned.
I am trying to use a subquery but I got "single-row subquery returns more than one row"error and not sure what went wrong.

SELECT * FROM Trips
INNER JOIN users
ON client_id = (SELECT users_id from users
                  where
                  role = 'Client' and  banned = 'No');

Body:
No need for a sub-select, just put those conditions into the join condition.

SELECT *
FROM Trips
  JOIN users ON trips.client_id = users.users_id
            and users.role = 'Client'
            and users.banned = 'No';

As that is an inner join, this is equivalent to:

SELECT *
FROM Trips
  JOIN users ON trips.client_id = users.users_id
WHERE users.role = 'Client'
  and users.banned = 'No';

This would not be different if you had used an outer join


问:
Heroku Python Django App Deployment Failure: No module named 'oauth2_provider'
I am following the Django OAuth Toolkit tutorial.  I have the app running successfully on my local server with Django OAuth Toolkit installed.

When I try to deploy to Heroku I get a "ModuleNotFoundError: No module named 'oauth2_provider'" error while running '$ python manage.py collectstatic --noinput'.

I have attempted to search Stack Overflow for similar questions but was unable to find one.  I saw many questions on Stack Overflow relating to collectstatic but I do not think that is my problem.

My backtrace is as so:

```<code>remote: -----> Python app detected
remote: -----> Installing requirements with pip
remote:
remote: -----> $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 10, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute
remote:            django.setup()
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
remote:            apps.populate(settings.INSTALLED_APPS)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate
remote:            app_config = AppConfig.create(entry)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 94, in create
remote:            module = import_module(entry)
remote:          File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
remote:            return _bootstrap._gcd_import(name[level:], package, level)
remote:          File "<frozen importlib._bootstrap>", line 978, in _gcd_import
remote:          File "<frozen importlib._bootstrap>", line 961, in _find_and_load
remote:          File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
remote:        ModuleNotFoundError: No module named 'oauth2_provider'
remote:
remote:  !     Error while running '$ python manage.py collectstatic --noinput'.
remote:        See traceback above for details.
</code>```

My settings.py Installed Apps is as so:

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    # Disable Django's own staticfiles handling in favour of WhiteNoise, for
    # greater consistency between gunicorn and `./manage.py runserver`. See:
    # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'oauth2_provider',
    'corsheaders',
]
</code>```

I am using Python 3.6.1 and my requirements.txt is as so:

```<code>dj-database-url==0.4.1
Django==1.11.1
gunicorn==19.6.0
psycopg2==2.6.2
whitenoise==3.2
</code>```

答: You're missing this package in your requirements.txt file. So add django-oauth-toolkit there and it should work

Body:
I am following the Django OAuth Toolkit tutorial.  I have the app running successfully on my local server with Django OAuth Toolkit installed.

When I try to deploy to Heroku I get a "ModuleNotFoundError: No module named 'oauth2_provider'" error while running '$ python manage.py collectstatic --noinput'.

I have attempted to search Stack Overflow for similar questions but was unable to find one.  I saw many questions on Stack Overflow relating to collectstatic but I do not think that is my problem.

My backtrace is as so:

remote: -----> Python app detected
remote: -----> Installing requirements with pip
remote:
remote: -----> $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 10, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute
remote:            django.setup()
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
remote:            apps.populate(settings.INSTALLED_APPS)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate
remote:            app_config = AppConfig.create(entry)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 94, in create
remote:            module = import_module(entry)
remote:          File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
remote:            return _bootstrap._gcd_import(name[level:], package, level)
remote:          File "<frozen importlib._bootstrap>", line 978, in _gcd_import
remote:          File "<frozen importlib._bootstrap>", line 961, in _find_and_load
remote:          File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
remote:        ModuleNotFoundError: No module named 'oauth2_provider'
remote:
remote:  !     Error while running '$ python manage.py collectstatic --noinput'.
remote:        See traceback above for details.

My settings.py Installed Apps is as so:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    # Disable Django's own staticfiles handling in favour of WhiteNoise, for
    # greater consistency between gunicorn and `./manage.py runserver`. See:
    # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'oauth2_provider',
    'corsheaders',
]

I am using Python 3.6.1 and my requirements.txt is as so:

dj-database-url==0.4.1
Django==1.11.1
gunicorn==19.6.0
psycopg2==2.6.2
whitenoise==3.2


问:
Using a variable containing doublequotes with subprocess
I am having some trouble with the subprocess module. I would like the module to run the shell command equivalent to 'ls -l "/path/to/file/with possible space in directory/or with space in name"'. Subprocess works fine when the filename is not a variable. If the filename is a variable that contains the quotes, then it doesn't work.

Code that doesn't work:

```<code>import subprocess

archive_file_list = "/var/tmp/list"
archive = open(archive_file_list, "r")

for line in archive:
    noreturnline = line[:-1]
    quotedline = "\"" + noreturnline + "\""
    if extension == "zip":
        print quotedline
        archivelist = subprocess.check_output(['ls', '-l', quotedline])
        print archivelist
</code>```

Code that works:

```<code>archivelist = subprocess.check_output(['ls', '-l', "/path/to/file/with possible space in directory/or with space in name"])
</code>```

Here is the output for the code that doesn't work:

```<code>"/path/to/file/with possible space in directory/or with space in name"
ls: cannot access "/path/to/file/with possible space in directory/or with space in name" No such file or directory
Traceback (most recent call last):
File "./archive_test.py", line 12, in <module>
archivelist = subprocess.check_output(['ls', '-l', quotedline])
File "/usr/lib64/python2.7/subprocess.py", line 575, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['ls', '-l', '"/path/to/file/with possible space in directory/or with space in name"']' returned non-zero exit status 2
</code>```

Before you ask - yes, I have already verified that "/path/to/file/with possible space in directory/or with space in name" does in fact exist by running 'ls -l' from the command line.

Any help would be appreciated. Thanks in advance.

答:
in the first command (which is the best option there is):

```<code>archivelist = subprocess.check_output(['ls', '-l', "/path/to/file/with possible space in directory/or with space in name"])
</code>```

the third argument is actually /path/to/file/with possible space in directory/or with space in name (without quotes) which is the filename that exists, and the command works.

Since shell=True isn't even set, the command is directly passed to exec, with the arguments passed as-is: the spaces & other chars are preserved.

If you add more quotes, they're not removed and they're passed literally to ls.

Since there's no such file called "/path/to/file/with possible space in directory/or with space in name" (with quotes), the file/dir isn't found.

There's another (dirty) way of calling a command: passing the full command as a string (not as a list of parameters). In that case, that would work (without shell=True at least on Windows, subprocess seems to handle the argument splitting, shell=True seems to be required on Unix-like systems):

```<code>subprocess.check_output('ls -l "/path/to/file/with possible space in directory/or with space in name"')
</code>```

but your first approach is cleaner, specially if you don't know the directory name because it's a parameter. Let subprocess do the heavy lifting for you.

On Unix-like systems, using this last approach requires shell=True, but then you're exposing your program to malicious attacks like any open system call (appending ;rm -rf / to the filename, evaluating sub-shells for instance)

Final note: if you're really planning to use ls and parse its output, don't do it (http://mywiki.wooledge.org/ParsingLs), use standard os.listdir, os.path.getsize/getmtime & os.stat calls to get the information you need.

Body:
I am having some trouble with the subprocess module. I would like the module to run the shell command equivalent to 'ls -l "/path/to/file/with possible space in directory/or with space in name"'. Subprocess works fine when the filename is not a variable. If the filename is a variable that contains the quotes, then it doesn't work.

Code that doesn't work:

import subprocess

archive_file_list = "/var/tmp/list"
archive = open(archive_file_list, "r")

for line in archive:
    noreturnline = line[:-1]
    quotedline = "\"" + noreturnline + "\""
    if extension == "zip":
        print quotedline
        archivelist = subprocess.check_output(['ls', '-l', quotedline])
        print archivelist

Code that works:

archivelist = subprocess.check_output(['ls', '-l', "/path/to/file/with possible space in directory/or with space in name"])

Here is the output for the code that doesn't work:

"/path/to/file/with possible space in directory/or with space in name"
ls: cannot access "/path/to/file/with possible space in directory/or with space in name" No such file or directory
Traceback (most recent call last):
File "./archive_test.py", line 12, in <module>
archivelist = subprocess.check_output(['ls', '-l', quotedline])
File "/usr/lib64/python2.7/subprocess.py", line 575, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['ls', '-l', '"/path/to/file/with possible space in directory/or with space in name"']' returned non-zero exit status 2

Before you ask - yes, I have already verified that "/path/to/file/with possible space in directory/or with space in name" does in fact exist by running 'ls -l' from the command line.

Any help would be appreciated. Thanks in advance.

Body:
in the first command (which is the best option there is):

archivelist = subprocess.check_output(['ls', '-l', "/path/to/file/with possible space in directory/or with space in name"])

the third argument is actually /path/to/file/with possible space in directory/or with space in name (without quotes) which is the filename that exists, and the command works.

Since shell=True isn't even set, the command is directly passed to exec, with the arguments passed as-is: the spaces & other chars are preserved.

If you add more quotes, they're not removed and they're passed literally to ls.

Since there's no such file called "/path/to/file/with possible space in directory/or with space in name" (with quotes), the file/dir isn't found.

There's another (dirty) way of calling a command: passing the full command as a string (not as a list of parameters). In that case, that would work (without shell=True at least on Windows, subprocess seems to handle the argument splitting, shell=True seems to be required on Unix-like systems):

subprocess.check_output('ls -l "/path/to/file/with possible space in directory/or with space in name"')

but your first approach is cleaner, specially if you don't know the directory name because it's a parameter. Let subprocess do the heavy lifting for you.

On Unix-like systems, using this last approach requires shell=True, but then you're exposing your program to malicious attacks like any open system call (appending ;rm -rf / to the filename, evaluating sub-shells for instance)

Final note: if you're really planning to use ls and parse its output, don't do it (http://mywiki.wooledge.org/ParsingLs), use standard os.listdir, os.path.getsize/getmtime & os.stat calls to get the information you need.


问:
Internal CSS function is not working
I have this code sample for a drop down list. I want to change the Hovering color when I hover over the name Our Softwares (which is under the class dropdown-toggle)

Here's the code sample:

```<code>                   <li class="dropdown" >
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" style="color:white;" >Our Softwares<span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Software 1</a></li>
                            <li><a href="#">Software 2</a></li>
                            <li><a href="#">Software 3</a></li>

                        </ul>
                    </li>
</code>```

And here's the Internal CSS I used to achieve the above mentioned function:

```<code>.dropdown .dropdown-toggle a:hover{
            background-color: red;
            color: blue;
        }
</code>```

But it is not working. Can anyone please tell me what Am I doing wrong?

答:
You just have to put the a before the class .dropdown-toggle as the class is for the a rather than an element containing it.

I also added !important to the color because it's declared as white in the inline css (which takes priority).

```<code>.dropdown  a.dropdown-toggle:hover {
  background-color: red;
  color: blue!important;
}
</code>```

You can test it out here:

.dropdown a.dropdown-toggle:hover {
  background-color: red;
  color: blue!important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li class="dropdown">
  Our Softwares<span class="caret"></span>
  <ul class="dropdown-menu">
    <li>Software 1</li>
    <li>Software 2</li>
    <li>Software 3</li>

  </ul>
</li></code>```

Title: Internal CSS function is not working

Body:
I have this code sample for a drop down list. I want to change the Hovering color when I hover over the name Our Softwares (which is under the class dropdown-toggle)

Here's the code sample:

                        Our Softwares

Software 1

Software 2

Software 3

And here's the Internal CSS I used to achieve the above mentioned function:

.dropdown .dropdown-toggle a:hover{
            background-color: red;
            color: blue;
        }

But it is not working. Can anyone please tell me what Am I doing wrong?

Body:
You just have to put the a before the class .dropdown-toggle as the class is for the a rather than an element containing it.

I also added !important to the color because it's declared as white in the inline css (which takes priority).

.dropdown  a.dropdown-toggle:hover {
  background-color: red;
  color: blue!important;
}

You can test it out here:

.dropdown a.dropdown-toggle:hover {
  background-color: red;
  color: blue!important;
}

<li class="dropdown">
  <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" style="color:white;">Our Softwares<span class="caret"></span></a>
  <ul class="dropdown-menu">
    <li><a href="#">Software 1</a></li>
    <li><a href="#">Software 2</a></li>
    <li><a href="#">Software 3</a></li>

  </ul>
</li>


问:
Axios: chaining multiple API requests
I need to chain a few API requests from the Google Maps API, and I'm trying to do it with Axios.

Here is the first request, which is in componentWillMount()

```<code>axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1)
  .then(response => this.setState({ p1Location: response.data }))  }
</code>```

Here is the second request:

```<code>axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2)
  .then(response => this.setState({ p2Location: response.data }))
</code>```

Then we have a third request, which is dependent on the first two being completed:

```<code>axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + this.state.p1Location.results.place_id + '&destination=place_id:' + this.state.p2Location.results.place_id + '&key=' + 'API-KEY-HIDDEN')
  .then(response => this.setState({ route: response.data }))
</code>```

How can I chain these three calls so that the third happens after the first two?

答:
Have you used axios.all ? You can try with something similar:

```<code>axios.all([axios.get(`firstrequest`),
           axios.get(`secondrequest`),
           axios.get(`thirdrequest`)])
     .then(axios.spread((firstResponse, secondResponse, thirdResponse) => {
         console.log(firstResponse.data,secondResponse.data, thirdResponse.data);
     }))
     .catch(error => console.log(error));
</code>```

This will take all your get and will put it inside a response that has to be called with .data  like:
    firstResponse.data

Title: Axios: chaining multiple API requests

Body:
I need to chain a few API requests from the Google Maps API, and I'm trying to do it with Axios.

Here is the first request, which is in componentWillMount()

axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1)
  .then(response => this.setState({ p1Location: response.data }))  }

Here is the second request:

axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2)
  .then(response => this.setState({ p2Location: response.data }))

Then we have a third request, which is dependent on the first two being completed:

axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + this.state.p1Location.results.place_id + '&destination=place_id:' + this.state.p2Location.results.place_id + '&key=' + 'API-KEY-HIDDEN')
  .then(response => this.setState({ route: response.data }))

How can I chain these three calls so that the third happens after the first two?

Body:
Have you used axios.all ? You can try with something similar:

axios.all([axios.get(`firstrequest`),
           axios.get(`secondrequest`),
           axios.get(`thirdrequest`)])
     .then(axios.spread((firstResponse, secondResponse, thirdResponse) => {
         console.log(firstResponse.data,secondResponse.data, thirdResponse.data);
     }))
     .catch(error => console.log(error));

This will take all your get and will put it inside a response that has to be called with .data  like:
    firstResponse.data


问:
CSS - Make a div "clickable"
I'd like to know how i can render a div clickable (like a link, with the small hand when i go over with the mouse).

I have some elements like this:

```<code><div class="teamSelector">Some</div>
</code>```

With this jQuery:

```<code>$('.teamSelector').click(function() {
    // some functions
});
</code>```

Cheers

答: Can't you just, y'know, make it a link and style it? It would be easier and accessible.</p>

Title: CSS - Make a div "clickable"

Body:
I'd like to know how i can render a div clickable (like a link, with the small hand when i go over with the mouse).

I have some elements like this:

Some

With this jQuery:

$('.teamSelector').click(function() {
    // some functions
});

Cheers


问:
Navigation Bar click event - Android Application
I'm trying to handle a onClick event on the Navigation Bar in an Android Application.

Exactlyer, when the user clicks on the return button the Application must go back to the Main Activity ( in my case "Start" ) and not to the previous Activity.

In my application I have more Activities, which are all callable from every Activity, so when, for example, I'm in "Start", I click a Button and I come to "Karte", then from "Karte" I want to go to "Einstellungen", then from "Einstellungen" I want return to the Main Activity "Start", but I can't because when I click on the return button on the Nav. Bar I come only back to the previous Activity ("Karte").

If anyone knows how to handle this, please answer.

答:
Try this:

On your "Einstellungen" activity, override the onBackPressed method to handle navigation:

```<code>@Override
public void onBackPressed() {
    Intent i = new Intent(this, Start.class);
    startActivity(i);
    finish();
}
</code>```

When you navigate from "Karte" to "Einstellungen" and from "Start" to "Karte" you should finish() your activity too to avoid navigation issues.

Body:
Try this:

On your "Einstellungen" activity, override the onBackPressed method to handle navigation:

@Override
public void onBackPressed() {
    Intent i = new Intent(this, Start.class);
    startActivity(i);
    finish();
}

When you navigate from "Karte" to "Einstellungen" and from "Start" to "Karte" you should finish() your activity too to avoid navigation issues.


问:
Checkbox function for checking if input is "checked" or not "checked"
I want some elements to have a class applied to them if a checkbox is checked, and to have the class removed if they are not checked (or un-checked). I've tried writing this a few different ways but I'm only ever able to give apply the class to the elements once the checkbox is clicked, but re-clicking doesn't remove the class from the elements even though I expect it would.

```<code>jQuery(document).ready(function($) {

  $('input[type="checkbox"]').on("click", function() {

    if($('#filter-Acting').prop('checked') == true) {

      $('.filter-item.Acting').addClass("hidden");

    } else if ($('#filter-Acting').prop('checked') == false) {

      $('.filter-item.Acting').removeClass("hidden");

    }

  }
});
</code>```

What's the easiest way to accomplish what I'm after? Thanks.

*EDIT: None of the provided examples have worked for me so here is relevant markup for the form and a form item...

```<code><form>
  <fieldset>
    <div class="row">
      <div class="col-sm-12">
        <div class="checkbox" id="check-Acting">
          <input type="checkbox" id="filter-Acting" name="Acting" value="1" class="form-checkbox"/>
          <label for="filter-Acting" data-toggle="tooltip" data-placement="top"><span>Acting</span></label>
        </div>
      </div>
    </div>
  </fieldset>
</form>

<div class="container">
  <div class="panel filter-item Acting">
    --
  </div>
</div>
</code>```

答:
Without your html I may only assume it and propose you to use:

.toggleClass( className, state ): one or more class to be toggled according to the state value

$('input[type="checkbox"]').on("change", function (e) {
    $('.filter-Acting').toggleClass("hidden", !$('#filter-item.Acting').is(':checked'));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  display: none;
}</code>```

<form action="....">
    <input type="checkbox" name="vehicle" value="Bike" id="filter-item" class="Acting"> Click me

    <input type="text" class="filter-Acting hidden">

    <input type="submit"  value="Submit">
</form>```

Body:
I want some elements to have a class applied to them if a checkbox is checked, and to have the class removed if they are not checked (or un-checked). I've tried writing this a few different ways but I'm only ever able to give apply the class to the elements once the checkbox is clicked, but re-clicking doesn't remove the class from the elements even though I expect it would.

jQuery(document).ready(function($) {

  $('input[type="checkbox"]').on("click", function() {

    if($('#filter-Acting').prop('checked') == true) {

      $('.filter-item.Acting').addClass("hidden");

    } else if ($('#filter-Acting').prop('checked') == false) {

      $('.filter-item.Acting').removeClass("hidden");

    }

  }
});

What's the easiest way to accomplish what I'm after? Thanks.

*EDIT: None of the provided examples have worked for me so here is relevant markup for the form and a form item...

<form>
  <fieldset>

          <input type="checkbox" id="filter-Acting" name="Acting" value="1" class="form-checkbox"/>
          Acting

  </fieldset>
</form>

    --

Body:
Without your html I may only assume it and propose you to use:

.toggleClass( className, state ): one or more class to be toggled according to the state value

$('input[type="checkbox"]').on("change", function (e) {
    $('.filter-Acting').toggleClass("hidden", !$('#filter-item.Acting').is(':checked'));
});

.hidden {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="....">
    <input type="checkbox" name="vehicle" value="Bike" id="filter-item" class="Acting"> Click me<br>
    <input type="text" class="filter-Acting hidden"><br>
    <input type="submit"  value="Submit">
</form>


问:
Redux store does not have a valid reducer, with combineReducers and valid reducer
```<code>import { createStore, combineReducers } from 'redux'
const reducer = (state = {}, action) => state
const rootReducer = combineReducers(reducer)
let store = createStore(rootReducer)
export default store
</code>```

A warning is triggered when the store is created:

```<code>Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.
</code>```

This warning comes up again when I attempt to use any of the store methods.

答:
The error is simple - you did not pass an object to combineReducers:

```<code>const rootReducer = combineReducers({ reducer })
</code>```

This will fix the problem.

Body:
import { createStore, combineReducers } from 'redux'
const reducer = (state = {}, action) => state
const rootReducer = combineReducers(reducer)
let store = createStore(rootReducer)
export default store

A warning is triggered when the store is created:

Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

This warning comes up again when I attempt to use any of the store methods.

Body:
The error is simple - you did not pass an object to combineReducers:

const rootReducer = combineReducers({ reducer })

This will fix the problem.


问:
How to run Python Script in Pyspark
I'm trying to run Python Script in Pyspark on cloudera VM

First I run pyspark by

```<code>$ which pyspark
$ pyspark
</code>```

After launching the spark, i tried:

```<code>$ spark-submit /home/cloudera/test.py
</code>```

Gives me "name 'spark' is not defined"

```<code>$ ./bin/spark-submit /home/cloudera/test.py
</code>```

Gives me "SyntaxError: invalid syntax"

I know there are many similiar questions online but I still can't figure it out. Can someone please help?

答:
You will have to run the spark-submit shell from the cluster itself. You do not have to pyspark into it.

If you want to run the code interactively (type line by line or copy/paste)then you would use pyspark.

Title: How to run Python Script in Pyspark

Body:
I'm trying to run Python Script in Pyspark on cloudera VM

First I run pyspark by

$ which pyspark
$ pyspark

After launching the spark, i tried:

$ spark-submit /home/cloudera/test.py

Gives me "name 'spark' is not defined"

$ ./bin/spark-submit /home/cloudera/test.py

Gives me "SyntaxError: invalid syntax"

I know there are many similiar questions online but I still can't figure it out. Can someone please help?


问:
unable to install mongodb properly on Ubuntu 17.04
Hello i'm getting errors in my terminal everytime i try to apt-get install something or update , i guess it has something to do with installing mongodb , i'm new to linux , i followed this guide exactly on how to install it , i couldnt find a guide for 17.04 version so i did the 16.10 , now everytime i try to apt-get something i get this error

Reading package lists... Done

  W: GPG error:
  http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.0

  Release: The
  following signatures couldn't be verified because the public key is
  not available: NO_PUBKEY 9ECBEC467F0CEB10
  W: The repository
  'http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.0 Release' is
  not signed.

  N: Data from such a repository can't be authenticated and
  is therefore potentially dangerous to use.

  N: See apt-secure(8)
  manpage for repository creation and user configuration details.

plus i have an alert in my top bar:

an error occured please run package manager from the right-click menu
  or apt-get in a terminal to see what is wrong

the error message was :

Error brokenCount > 0. this usually means that your installed packages
  have unmet dependencies.

答:
I think the problem is that the mongodb repository is not signed. You need to signed using apt-key adv ...

In the URL https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/ there're some ubuntu repositories for mongodb, last available version is 16.04 . Tutorial for setup is also available.

Best luck


答:
You don't need  the subquery

the join should be between Trips and Users eg  :

```<code>SELECT *
FROM Trips
INNER JOIN users ON Trips.client_id = usres.users_id
        and users.role = 'Client'
        and  users.banned = 'No';
</code>```

Title: can I use subquery in the inner join condition sql

Body:
You don't need  the subquery

the join should be between Trips and Users eg  :

SELECT *
FROM Trips
INNER JOIN users ON Trips.client_id = usres.users_id
        and users.role = 'Client'
        and  users.banned = 'No';


问:
How to maximise ChromeDriver while setting up GEB/SPOCK/GROOVY Selenium tests
I am having some issues with ChromeDriver maximising when setting up my tests. The screen just doesn't get any bigger unlike FireFox driver. This is how I have it set up:

```<code>chrome {
        driver = {
            System.setProperty('webdriver.chrome.driver', '.....)
            def chromeDriver = new ChromeDriver()
            chromeDriver.switchTo().window(chromeDriver.getWindowHandle());
            chromeDriver.manage().window().maximize()
            chromeDriver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS)
            chromeDriver
        }
</code>```

Is there something I am missing or doing wrong?

Thanks

答:
You don't need to use </p>

```<code>chromeDriver.switchTo().window(chromeDriver.getWindowHandle());
</code>```

<p>has there will be only one window opened </p>

Body:
I am having some issues with ChromeDriver maximising when setting up my tests. The screen just doesn't get any bigger unlike FireFox driver. This is how I have it set up:

chrome {
        driver = {
            System.setProperty('webdriver.chrome.driver', '.....)
            def chromeDriver = new ChromeDriver()
            chromeDriver.switchTo().window(chromeDriver.getWindowHandle());
            chromeDriver.manage().window().maximize()
            chromeDriver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS)
            chromeDriver
        }

Is there something I am missing or doing wrong?

Thanks

Body:
You don't need to use

chromeDriver.switchTo().window(chromeDriver.getWindowHandle());

has there will be only one window opened


问:
values in a table. js jquery
I am trying to get data in a table (from db) if they fall between the table header dates. Everything is working except that I am not able to get data between certain dates. Please look on the comments n pic for more info. Help will be greatly appreciated.

//please look at the comments for more information

  //this is the info from table header which shows current week dates (in the pic)
  var wkly = document.getElementById("test1").innerHTML; //06/04/2017

  var wkend = document.getElementById("test2").innerHTML; //06/10/2017

   //values from db "testvalues" which is an array (strings)
    //testvalues[i+2] is a date from db
    for (var i = 0; i < (testvalues.length-1); i = i + 5) {

    //this is logic i am trying to show: if dates matches show all the data between those two dates(wkly and wkend) in a table
    if(testvalues[i+2]==wkly && testvalues[i+2]==wkend){ //this is not working

    //my code to show data in a table
    }

    }```

答:
At a high level, you can try something like this. You need to convert your strings into Date objects and compare them. I would HIGHLY recommend using a library like momentjs instead though if you are doing any serious date usage in your application.

var wkly = new Date("06/04/2017");
var wknd = new Date("06/10/2017");
var test = new Date("06/07/2017");

function dateInRange(d, start, end){
  return end >= d && start <= end;
}

if(dateInRange(test, wkly,wknd)){
  console.log("in range");
  //...
}else{
  console.log("not in range")
  //...
}```
</div>
</div>
</p>

<p>If it were me, I would use momentjs and do something like this instead. You can make use of the handy <code>ìsBetween</code> function, and explicitly declaring the expected date format is safer(for example, I assumed your dates are in June since it's June right now and you're in America, but in my country I would naturally read them as being in April/October- the format isn't clear. So it helps avoid problems to just declare it).</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var wkly = moment("06/04/2017", "MM/DD/YYY");
var wknd = moment("06/10/2017", "MM/DD/YYY");
var test = moment("06/07/2017", "MM/DD/YYY");

if(test.isBetween(wkly, wknd)){
  console.log("in range");
  //...
}else{
  console.log("not in range")
  //...
}</code>```

```

Title: values in a table. js jquery

Body:
At a high level, you can try something like this. You need to convert your strings into Date objects and compare them. I would HIGHLY recommend using a library like momentjs instead though if you are doing any serious date usage in your application.

var wkly = new Date("06/04/2017");
var wknd = new Date("06/10/2017");
var test = new Date("06/07/2017");

function dateInRange(d, start, end){
  return end >= d && start <= end;
}

if(dateInRange(test, wkly,wknd)){
  console.log("in range");
  //...
}else{
  console.log("not in range")
  //...
}

If it were me, I would use momentjs and do something like this instead. You can make use of the handy ìsBetween function, and explicitly declaring the expected date format is safer(for example, I assumed your dates are in June since it's June right now and you're in America, but in my country I would naturally read them as being in April/October- the format isn't clear. So it helps avoid problems to just declare it).

var wkly = moment("06/04/2017", "MM/DD/YYY");
var wknd = moment("06/10/2017", "MM/DD/YYY");
var test = moment("06/07/2017", "MM/DD/YYY");

if(test.isBetween(wkly, wknd)){
  console.log("in range");
  //...
}else{
  console.log("not in range")
  //...
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
Is importing headers bad?
What are your opinions on #importing header files?

If I import:

```<code>#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
</code>```

and many more headers, and only use them once in a while, is it a waste?  Does it slow down my app in any way?  More importantly, does it increase the size of my app?

Thanks.

答:
Adding to quixoto's answer, Objective-C added the

```<code>#import
</code>```

Header.  The original C header was:

```<code>#include
</code>```

The difference is that #import actually checks to see if you have already included the header in your code.  If you have, the #import statement does nothing.

Title: Is importing headers bad?

Body:
What are your opinions on #importing header files?

If I import:

#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

and many more headers, and only use them once in a while, is it a waste?  Does it slow down my app in any way?  More importantly, does it increase the size of my app?

Thanks.

Body:
Adding to quixoto's answer, Objective-C added the

#import

Header.  The original C header was:

#include

The difference is that #import actually checks to see if you have already included the header in your code.  If you have, the #import statement does nothing.


问:
Two Tabstrips with Two Kendo Grids
i want to load two kendogrid respective with two tabstrips. The requirement is when i click the tab then only grid should load. It should not load two grids when page loads</p>

答:
I accomplish that similar to what Supersnake describes by calling an Action on my Controller that returns a partial view:

```<code>@(Html.Kendo().TabStrip().Name("myTabStrip")
    .Items(tabs =>
    {
        tabs.Add().Text("Tab1").LoadContentFrom("Tab1Load", "MyController", new { id = Model.ID }).Selected(true);
        tabs.Add().Text("Tab2").LoadContentFrom("Tab2Load", "MyController", new { id = Model.ID });
    })
    .Events(e => e.Select("onTabSelect"))
</code>```

)

My controller action:

```<code>[HttpGet]
public PartialViewResult Tab1Load(int id)
{
    // load view model (vm) for partial
    return PartialView("_Tab1Content", vm);
}
</code>```

You could also just load the partial directly. Word of caution: when the tabs are loaded via AJAX it can affect jquery issues like validation. Grids should be fine though.

Title: Two Tabstrips with Two Kendo Grids

Body:
I accomplish that similar to what Supersnake describes by calling an Action on my Controller that returns a partial view:

@(Html.Kendo().TabStrip().Name("myTabStrip")
    .Items(tabs =>
    {
        tabs.Add().Text("Tab1").LoadContentFrom("Tab1Load", "MyController", new { id = Model.ID }).Selected(true);
        tabs.Add().Text("Tab2").LoadContentFrom("Tab2Load", "MyController", new { id = Model.ID });
    })
    .Events(e => e.Select("onTabSelect"))

)

My controller action:

[HttpGet]
public PartialViewResult Tab1Load(int id)
{
    // load view model (vm) for partial
    return PartialView("_Tab1Content", vm);
}

You could also just load the partial directly. Word of caution: when the tabs are loaded via AJAX it can affect jquery issues like validation. Grids should be fine though.


问:
How to use a PowerShell variable as command parameter?
I'm trying to use a variable as a command's parameter but can't quite figure it out.  Let's say MyCommand will accept two parameters: option1 and option2 and they accept boolean values.  How would I use $newVar to substitute option 1 or 2?  For example:

```<code>$newVar = "option1"
MyCommand -$newVar:$true
</code>```

I keep getting something along the lines of 'A positional parameter cannot be found that accepts argument '-System.String option1'.

More Specifically:

Here, the CSV file is an output of a different policy.  The loop goes through each property in the file and sets that value in my policy asdf; so  -$_.name:$_.value should substitute as -AllowBluetooth:true.

```<code>Import-Csv $file | foreach-object {
    $_.psobject.properties | where-object {
    # for testing I'm limiting this to 'AllowBluetooth' option
    if($_.name -eq "AllowBluetooth"){
    Set-ActiveSyncMailboxPolicy -Identity "asdf" -$_.name:$_.value
    }}
}
</code>```

答:
I had the same Problem and just found out how to resolve it. Solution is to use invoke-Expression: invoke-Expression $mycmd
This uses the $mycmd-string, replaces variables and executes it as cmdlet with  given parameters</p>

Body:
I'm trying to use a variable as a command's parameter but can't quite figure it out.  Let's say MyCommand will accept two parameters: option1 and option2 and they accept boolean values.  How would I use $newVar to substitute option 1 or 2?  For example:

$newVar = "option1"
MyCommand -$newVar:$true

I keep getting something along the lines of 'A positional parameter cannot be found that accepts argument '-System.String option1'.

More Specifically:

Here, the CSV file is an output of a different policy.  The loop goes through each property in the file and sets that value in my policy asdf; so  -$_.name:$_.value should substitute as -AllowBluetooth:true.

Import-Csv $file | foreach-object {
    $_.psobject.properties | where-object {
    # for testing I'm limiting this to 'AllowBluetooth' option
    if($_.name -eq "AllowBluetooth"){
    Set-ActiveSyncMailboxPolicy -Identity "asdf" -$_.name:$_.value
    }}
}