问:
Making 10 it write 1.0*10 with javascript
In this code that I wrote I want to show the words like this :
if we put 10000 it write 1.0*104
but it is not working.
In this code, we  write the number to the input file and after that we should click on the button it must show us the new number with that kind of thing.
but this code has a problem but I don't know where is it.
How can I solve the problem?

function check() {
  var K = 9 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10;
  var q1 = document.getElementById('q1').value;
  var q2 = document.getElementById('q2').value;
  var r = document.getElementById('r').value;
  var F = K * (q1 * q2) / (r * r);

  if (F >= 0) || (F <= 9) {
    document.getElementById('end2').innerHTML = F;
  }
  if
  else(F >= 10) || (F <= 99) {
    document.getElementById('end2').innerHTML = F / 10 + " * 10";
  }
  if
  else(F >= 100) || (F <= 999) {
    document.getElementById('end2').innerHTML = F / 100 + " * 102";
  }
  if
  else(F >= 1000) || (F <= 9999) {
    document.getElementById('end2').innerHTML = F / 1000 + " * 103";
  }
  if
  else(F >= 10000) || (F <= 99999) {
    document.getElementById('end2').innerHTML = F / 10000 + " * 104";
  }
  if
  else(F >= 100000) || (F <= 999999) {
    document.getElementById('end2').innerHTML = F / 100000 + " * 105";
  }
  if
  else(F >= 1000000) || (F <= 9999999) {
    document.getElementById('end2').innerHTML = F / 1000000 + " * 106";
  }
  if
  else(F >= 10000000) || (F <= 99999999) {
    document.getElementById('end2').innerHTML = F / 10000000 + " * 107";
  }
  if
  else(F >= 100000000) || (F <= 999999999) {
    document.getElementById('end2').innerHTML = F / 100000000 + " * 108";
  }
  if
  else(F >= 1000000000) || (F <= 9999999999) {
    document.getElementById('end2').innerHTML = F / 1000000000 + " * 109";
  }
  if
  else(F >= 10000000000) || (F <= 99999999999) {
    document.getElementById('end2').innerHTML = F / 10000000000 + " * 1010";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="q1" placeholder="q1">
<input type="text" id="q2" placeholder="q2">
<input type="text" id="r" placeholder="r">
<input type="submit" onClick="check()">
<p id="end2"></p></code>```

答:
You have some syntax errors in your codes:

```<code>if else(F>=10)||(F<=99) {
//...
}
</code>```

is

```<code>else if ( F>=10 || F<=99 ) {
//...
}
</code>```

since the statement is

```<code>if( conditionA ) {
// block
}
else if( conditionB ) {
 // block
}
else {
 // block
}
</code>```

It's not clear from your question which is the right output, by the way this is the working code (correct syntax):

<!doctype html>

  <meta charset="utf-8">
  <title>Untitled Document</title>

  <input type="text" id="q1" placeholder="q1">
  <input type="text" id="q2" placeholder="q2">
  <input type="text" id="r" placeholder="r">
  <input type="submit" onclick="check()">

```
</div>
</div>
</p>

<p>By the way I suggest to you this solution that avoid all the checks and makes use of <code>toExponential()</code> function:</p>

```var q1=3,q2=4,r=2;
var K = 9*10*10*10*10*10*10*10*10*10;
var F = K*(q1*q2)/(r*r);
F.toExponential()
```

<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 q1 = 3,
  q2 = 4,
  r = 2;
var K = 9 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10;
var F = K * (q1 * q2) / (r * r);
//2.7 * 10<sup>9</sup>
var exponential = F.toExponential();
var base=parseFloat( exponential.split('e')[0] )
var exponent=parseInt( exponential.split('e')[1] )
console.log("%f * 10<sup>%f</sup>",base,exponent) </code>```

Body:
In this code that I wrote I want to show the words like this :
if we put 10000 it write 1.0*104
but it is not working.
In this code, we  write the number to the input file and after that we should click on the button it must show us the new number with that kind of thing.
but this code has a problem but I don't know where is it.
How can I solve the problem?

function check() {
  var K = 9 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10;
  var q1 = document.getElementById('q1').value;
  var q2 = document.getElementById('q2').value;
  var r = document.getElementById('r').value;
  var F = K * (q1 * q2) / (r * r);

  if (F >= 0) || (F <= 9) {
    document.getElementById('end2').innerHTML = F;
  }
  if
  else(F >= 10) || (F <= 99) {
    document.getElementById('end2').innerHTML = F / 10 + " * 10";
  }
  if
  else(F >= 100) || (F <= 999) {
    document.getElementById('end2').innerHTML = F / 100 + " * 102";
  }
  if
  else(F >= 1000) || (F <= 9999) {
    document.getElementById('end2').innerHTML = F / 1000 + " * 103";
  }
  if
  else(F >= 10000) || (F <= 99999) {
    document.getElementById('end2').innerHTML = F / 10000 + " * 104";
  }
  if
  else(F >= 100000) || (F <= 999999) {
    document.getElementById('end2').innerHTML = F / 100000 + " * 105";
  }
  if
  else(F >= 1000000) || (F <= 9999999) {
    document.getElementById('end2').innerHTML = F / 1000000 + " * 106";
  }
  if
  else(F >= 10000000) || (F <= 99999999) {
    document.getElementById('end2').innerHTML = F / 10000000 + " * 107";
  }
  if
  else(F >= 100000000) || (F <= 999999999) {
    document.getElementById('end2').innerHTML = F / 100000000 + " * 108";
  }
  if
  else(F >= 1000000000) || (F <= 9999999999) {
    document.getElementById('end2').innerHTML = F / 1000000000 + " * 109";
  }
  if
  else(F >= 10000000000) || (F <= 99999999999) {
    document.getElementById('end2').innerHTML = F / 10000000000 + " * 1010";
  }
}

<input type="text" id="q1" placeholder="q1">
<input type="text" id="q2" placeholder="q2">
<input type="text" id="r" placeholder="r">
<input type="submit" onClick="check()">

Body:
You have some syntax errors in your codes:

if else(F>=10)||(F<=99) {
//...
}

is

else if ( F>=10 || F<=99 ) {
//...
}

since the statement is

if( conditionA ) {
// block
}
else if( conditionB ) {
 // block
}
else {
 // block
}

It's not clear from your question which is the right output, by the way this is the working code (correct syntax):

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Untitled Document</title>
<script>
   function check()
   {
    var K = 9*10*10*10*10*10*10*10*10*10;
    var q1 = document.getElementById('q1').value;
    var q2 = document.getElementById('q2').value;
    var r = document.getElementById('r').value;
    var F = K*(q1*q2)/(r*r);

    if(F>=0&&F<=9){
     document.getElementById('end2').innerHTML = F;
    }
    else if(F>=10&&F<=99){
     document.getElementById('end2').innerHTML = parseFloat(F/10) + " * 10";
    }
    else if(F>=100&&F<=999){
     document.getElementById('end2').innerHTML = parseFloat(F/100) + " * 10<sup>2</sup>";
    }
    else if(F>=1000&&F<=9999){
     document.getElementById('end2').innerHTML = parseFloat(F/1000) + " * 10<sup>3</sup>";
    }
    else if(F>=10000&&F<=99999){
     document.getElementById('end2').innerHTML = parseFloat(F/10000) + " * 10<sup>4</sup>";
    }
    else if(F>=100000&&F<=999999){
     document.getElementById('end2').innerHTML = parseFloat(F/100000) + " * 10<sup>5</sup>";
    }
    else if(F>=1000000&&F<=9999999){
     document.getElementById('end2').innerHTML = parseFloat(F/1000000) + " * 10<sup>6</sup>";
    }
    else if(F>=10000000&&F<=99999999){
     document.getElementById('end2').innerHTML = parseFloat(F/10000000) + " * 10<sup>7</sup>";
    }
    else if(F>=100000000&&F<=999999999){
     document.getElementById('end2').innerHTML = parseFloat(F/100000000) + " * 10<sup>8</sup>";
    }
    else if(F>=1000000000&&F<=9999999999){
     document.getElementById('end2').innerHTML = parseFloat(F/1000000000) + " * 10<sup>9</sup>";
    }
    else if(F>=10000000000&&F<=99999999999){
     document.getElementById('end2').innerHTML = parseFloat(F/10000000000) + " * 10<sup>10</sup>";
    }
   }

  </script>
 </head>

 <body>

  <input type="text" id="q1" placeholder="q1">
  <input type="text" id="q2" placeholder="q2">
  <input type="text" id="r" placeholder="r">
  <input type="submit" onclick="check()">
  <p id="end2"></p>
 </body>
</html>

By the way I suggest to you this solution that avoid all the checks and makes use of toExponential() function:

var q1=3,q2=4,r=2;
var K = 9*10*10*10*10*10*10*10*10*10;
var F = K*(q1*q2)/(r*r);
F.toExponential()

var q1 = 3,
  q2 = 4,
  r = 2;
var K = 9 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10;
var F = K * (q1 * q2) / (r * r);
//2.7 * 10<sup>9</sup>
var exponential = F.toExponential();
var base=parseFloat( exponential.split('e')[0] )
var exponent=parseInt( exponential.split('e')[1] )
console.log("%f * 10<sup>%f</sup>",base,exponent)


来源: stackexchange

问:
Swift class: Fatal error: Use of unimplemented initializer 'init()' for class
I created a little convenience class for haptics and I try to reference the class in my Objc code:

self.haptics = [[Haptics new] initWithStyle:UIImpactFeedbackStyleLight];

```<code>@objc final class Haptics: NSObject {

    private var feedbackGenerator: UIImpactFeedbackGenerator? = nil

    init?(style: UIImpactFeedbackStyle) {
        guard UserFeedback.soundsAndVibrationsEnabled() else { return nil }

        self.feedbackGenerator = UIImpactFeedbackGenerator(style: style)
    }

    func prepare() {
        feedbackGenerator?.prepare()
    }

    func hit() {
        feedbackGenerator?.impactOccurred()
    }

}
</code>```

I get a crash on the Haptics class declaration:

Fatal error: Use of unimplemented initializer 'init()' for class 'MyProject.Haptics'

Not quite sure what I'm doing wrong here

答:
```<code>[Haptics new]
</code>```

is a short form for

```<code>[[Haptics alloc] init]
</code>```

therefor init() without parameter is called, but it doesn't exist.

do

```<code>self.haptics = [[Haptics alloc] initWithStyle:UIImpactFeedbackStyleLight];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created a little convenience class for haptics and I try to reference the class in my Objc code:

self.haptics = [[Haptics new] initWithStyle:UIImpactFeedbackStyleLight];

@objc final class Haptics: NSObject {

    private var feedbackGenerator: UIImpactFeedbackGenerator? = nil

    init?(style: UIImpactFeedbackStyle) {
        guard UserFeedback.soundsAndVibrationsEnabled() else { return nil }

        self.feedbackGenerator = UIImpactFeedbackGenerator(style: style)
    }

    func prepare() {
        feedbackGenerator?.prepare()
    }

    func hit() {
        feedbackGenerator?.impactOccurred()
    }

}

I get a crash on the Haptics class declaration:

Fatal error: Use of unimplemented initializer 'init()' for class 'MyProject.Haptics'

Not quite sure what I'm doing wrong here

Body:
[Haptics new]

is a short form for

[[Haptics alloc] init]

therefor init() without parameter is called, but it doesn't exist.

do

self.haptics = [[Haptics alloc] initWithStyle:UIImpactFeedbackStyleLight];


问:
Android: Problems debugging with the emulator from eclipse
This is driving me crazy.  Like these people, slow-android-emulator, I'm finding running the emulator from eclipse is slow and problematic.  As suggested, I've tried running the emulator seperately.  But then I don't get my latest changes.  I don't know eclipse that well, but I would like something like 'build' and then somehow load the latest image into the emulator.

Also, I've tried keeping the emulator open and the continually use run->debug, but after 2 or 3 times, I get errors like the following:

```<code>Failed to install HelloAndroid.apk on device 'emulator-5554': timeout
Launch canceled!

emulator: ERROR: the user data image is used by another emulator. aborting

Waiting for HOME ('android.process.acore') to be launched...
emulator-5554 disconnected! Cancelling 'com.example.helloandroid.HelloAndroid activity launch'!

java.lang.NullPointerException
at com.android.ddmlib.Client.sendAndConsume(Client.java:571)
at com.android.ddmlib.HandleHello.sendHELO(HandleHello.java:142)
at com.android.ddmlib.HandleHello.sendHelloCommands(HandleHello.java:65)
at com.android.ddmlib.Client.getJdwpPacket(Client.java:670)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:317)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
</code>```

I've tried killing and restarting the adb server to no avail.

Once again, briefly, I would just like a 'system' where I can effectively make changes, load them into the emulator and test.

答:
The emulator is usually slow, but once started usually I never had to restart.

If you feel that running emulator from outside eclipse is faster, then you can run the emulator outside eclipse and in the android application Run --> Configuration, you can choose "preferred avd" and uncheck automatic target mode. (Also it tells me that your eclipse probably does not have enough memory. You need to change vmargs if you have allocated very little memory. More on that later).

Also when you want to debug again after making some code change, are you closing the debugging session (The red button in your debug window) and starting a new one. The emulator does not handle hot swapping all that well.

(Note: Please try using Jconsole or some other profiler and paste the memory usage or at least check memory usage in task manager.)

Body:
This is driving me crazy.  Like these people, slow-android-emulator, I'm finding running the emulator from eclipse is slow and problematic.  As suggested, I've tried running the emulator seperately.  But then I don't get my latest changes.  I don't know eclipse that well, but I would like something like 'build' and then somehow load the latest image into the emulator.

Also, I've tried keeping the emulator open and the continually use run->debug, but after 2 or 3 times, I get errors like the following:

Failed to install HelloAndroid.apk on device 'emulator-5554': timeout
Launch canceled!

emulator: ERROR: the user data image is used by another emulator. aborting

Waiting for HOME ('android.process.acore') to be launched...
emulator-5554 disconnected! Cancelling 'com.example.helloandroid.HelloAndroid activity launch'!

java.lang.NullPointerException
at com.android.ddmlib.Client.sendAndConsume(Client.java:571)
at com.android.ddmlib.HandleHello.sendHELO(HandleHello.java:142)
at com.android.ddmlib.HandleHello.sendHelloCommands(HandleHello.java:65)
at com.android.ddmlib.Client.getJdwpPacket(Client.java:670)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:317)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)

I've tried killing and restarting the adb server to no avail.

Once again, briefly, I would just like a 'system' where I can effectively make changes, load them into the emulator and test.

ContentLicense: CC BY-SA 2.5


问:
How to deal with List properties
The list doesn't add anything when the method is called, it throws an exception.
How should it be done and is it possible to do without writing this:

```<code>public List<string> Mark = new List<string>();
</code>```

I've done like this and this gives an exception

```<code>public class Student
{
    protected List<string> _mark;

    public List<string> Mark
    {
        get { return _mark; }
        set { _mark = value; }
    }

    public void Get()
    {
        Mark.Add("Hello");
    }
}
 static void Main(string[] args)
    {
       Student a = new Student();
        a.Get();
    }
</code>```

答:
That's cause you haven't created an instance of the list and so the error. It should be

```<code>private List<string> _mark = new List<string>();
</code>```

Your property should just return it and no setter needed

```<code>public List<string> Mark
{
    get { return _mark; }
}
</code>```

Title: How to deal with List properties

Body:
The list doesn't add anything when the method is called, it throws an exception.
How should it be done and is it possible to do without writing this:

public List<string> Mark = new List<string>();

I've done like this and this gives an exception

public class Student
{
    protected List<string> _mark;

    public List<string> Mark
    {
        get { return _mark; }
        set { _mark = value; }
    }

    public void Get()
    {
        Mark.Add("Hello");
    }
}
 static void Main(string[] args)
    {
       Student a = new Student();
        a.Get();
    }

Body:
That's cause you haven't created an instance of the list and so the error. It should be

private List<string> _mark = new List<string>();

Your property should just return it and no setter needed

public List<string> Mark
{
    get { return _mark; }
}


问:
How can i print a multi line code with built in variables?
Hey I keep getting this Syntax Error with this code in the last line of the print statement. Did I miss something obvious or am i just doing it wrong. Radar() is supposed to get distances in steps of 18 degrees, which it does. Visual_radar() is then supposed to display them in a half circle. if there's any more information you need let me know.</p>

```<code>def radar():
    measures = {}
    angle = 18
    servo(0)
    for x in range(9):
        servo(angle)
        dist = distance()
        measures[angle] = dist
        angle += 18

    for number in measures:
        if number < min_distance:
            print('Too close!', number)
            can_move_forward = False

def visual_radar():

    print """
                     %f              %f
           %f                                %f

       %f                                       %f

    """ %(measures[90]), %(measures[108]),%(measures[72]),measures[126]),%(measures[54]))

radar()
visual_radar()
</code>```

答:
The multiple % are what's causing your syntax error. You also seem to have an extra parenthesis in there. You might as well just get rid of superfluous parenthesis while you're at it.

Try this:

```<code>print("""
                     %f              %f
           %f                                %f

       %f                                       %f

    """ % (measures[90], measures[108], measures[72] ,measures[126], measures[54]))
</code>```

Looks like you haven't fully understood how the formatting operator works, you might wanna read through this

Also note that you'll get another error after that. You have 6 format strings but only 5 format arguments. It should look like this:

```<code>TypeError: not enough arguments for format string
</code>```

Body:
Hey I keep getting this Syntax Error with this code in the last line of the print statement. Did I miss something obvious or am i just doing it wrong. Radar() is supposed to get distances in steps of 18 degrees, which it does. Visual_radar() is then supposed to display them in a half circle. if there's any more information you need let me know.

def radar():
    measures = {}
    angle = 18
    servo(0)
    for x in range(9):
        servo(angle)
        dist = distance()
        measures[angle] = dist
        angle += 18

    for number in measures:
        if number < min_distance:
            print('Too close!', number)
            can_move_forward = False

def visual_radar():

    print """
                     %f              %f
           %f                                %f

       %f                                       %f

    """ %(measures[90]), %(measures[108]),%(measures[72]),measures[126]),%(measures[54]))

radar()
visual_radar()

Body:
The multiple % are what's causing your syntax error. You also seem to have an extra parenthesis in there. You might as well just get rid of superfluous parenthesis while you're at it.

Try this:

print("""
                     %f              %f
           %f                                %f

       %f                                       %f

    """ % (measures[90], measures[108], measures[72] ,measures[126], measures[54]))

Looks like you haven't fully understood how the formatting operator works, you might wanna read through this

Also note that you'll get another error after that. You have 6 format strings but only 5 format arguments. It should look like this:

TypeError: not enough arguments for format string


答:
You don't initialize _mark. Mark.Add("Hello") causes Mark's getter to return _mark, and calling .Add on that null object causes an exception to be thrown.

You should do eg.

```<code>protected List<string> _mark = new List<string>();
</code>```

Title: How to deal with List properties

Body:
You don't initialize _mark. Mark.Add("Hello") causes Mark's getter to return _mark, and calling .Add on that null object causes an exception to be thrown.

You should do eg.

protected List<string> _mark = new List<string>();


问:
VS 2017 not recognizing boost/thread
I am using VS 2017 and i installed boost/thread NuGet(even reinstalled it a few times). Code shows no error, but when i run it, i get this :

Error   LNK1104 cannot open file 'libboost_thread-vc141-mt-gd-1_65_1.lib'

Any ideas? Thanks!

答:
Boost Nuget package contains only header files. For binaries you will need to add Boost Thread vc141. See also a list of precompiled Boost NuGet packages. Similar issue LNK1104 Visual studio 2015.

Don't install Boost Thread Src.

Title: VS 2017 not recognizing boost/thread


问:
Visual Studio for Mac broken
I am trying to open different Xamarin Solutions that worked before, e.g. the ones from https://github.com/xamarin/dev-days-labs (before vs update), now when I try to open the solution, I get the following fatal exception:

Ide.log says:

ERROR [2017-11-15 08:37:44Z]:ERROR [2017-11-15 08:37:44Z]: Error while

trying to load the project /Users/hoppentt/Documents/Projects/XamarinDevDays/dev-days-labs/Demos/app-tasks/DevDaysTasks.iOS/DevDaysTasks.iOS.csproj
System.TypeInitializationException: The type initializer for 'MonoDevelop.CSharp.Project.CSharpProject' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MonoDevelop.Ide.TypeSystem.MonoDevelopWorkspace' threw an exception. ---> System.TypeLoadException: Type Microsoft.CodeAnalysis.VisualBasic.CaseCorrection.VisualBasicCaseCorrectionService has invalid vtable method slot 6 with method none
  at (wrapper managed-to-native) System.RuntimeType:GetPropertiesByName_native (System.RuntimeType,intptr,System.Reflection.BindingFlags,bool)
  at System.RuntimeType.GetPropertiesByName (System.String name, System.Reflection.BindingFlags bindingAttr, System.Boolean icase, System.RuntimeType reflectedType) [0x00011] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/corlib/ReferenceSources/RuntimeType.cs:516
  at System.RuntimeType.GetPropertyCandidates (System.String name, System.Reflection.BindingFlags bindingAttr, System.Type[] types, System.Boolean allowPrefixLookup) [0x00010] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/referencesource/mscorlib/system/rttype.cs:2881
  at System.RuntimeType.GetProperties (System.Reflection.BindingFlags bindingAttr) [0x00000] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/referencesource/mscorlib/system/rttype.cs:3089
  at System.Reflection.RuntimeReflectionExtensions.GetRuntimeProperties (System.Type type) [0x00006] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/referencesource/mscorlib/system/reflection/RuntimeReflectionExtensions.cs:25
  at System.Composition.TypedParts.Discovery.TypeInspector+d__7.MoveNext () [0x00030] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.TypedParts.Discovery.TypeInspector+d__5.MoveNext () [0x000dc] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.TypedParts.Discovery.TypeInspector.InspectTypeForPart (System.Reflection.TypeInfo type, System.Composition.TypedParts.Discovery.DiscoveredPart& part) [0x00061] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.TypedParts.TypedPartExportDescriptorProvider..ctor (System.Collections.Generic.IEnumerable1[T] types, System.Composition.Convention.AttributedModelProvider attributeContext) [0x00037] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.Hosting.ContainerConfiguration.CreateContainer () [0x00042] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at Microsoft.CodeAnalysis.Host.Mef.MefHostServices.Create (System.Collections.Generic.IEnumerable1[T] assemblies) [0x0001e] in :0
  at MonoDevelop.Ide.TypeSystem.MonoDevelopWorkspace..cctor () [0x001f9] in /Users/builder/data/lanes/5144/b604c37c/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/MonoDevelopWorkspace.cs:121
   --- End of inner exception stack trace ---
  at MonoDevelop.CSharp.ProjectSearchCategory.Init () [0x00000] in /Users/builder/data/lanes/5144/b604c37c/source/monodevelop/main/src/addins/CSharpBinding/MonoDevelop.CSharp/ProjectSearchCategory.cs:53
  at MonoDevelop.CSharp.Project.CSharpProject.get_TargetRuntime () [0x0002b] in /Users/builder/data/lanes/5144/b604c37c/source/monodevelop/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpProjectExtension.cs:56
   --- End of inner exception stack trace ---
  at (wrapper managed-to-native) System.Reflection.MonoCMethod:InternalInvoke (System.Reflection.MonoCMethod,object,object[],System.Exception&)
  at System.Reflection.MonoCMethod.InternalInvoke (System.Object obj, System.Object[] parameters) [0x00002] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/corlib/System.Reflection/MonoMethod.cs:661
 Error while trying to load the project /Users/hoppentt/Documents/Projects/XamarinDevDays/dev-days-labs/Demos/app-tasks/DevDaysTasks.Droid/DevDaysTasks.Droid.csproj
System.TypeInitializationException: The type initializer for 'MonoDevelop.CSharp.Project.CSharpProject' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MonoDevelop.Ide.TypeSystem.MonoDevelopWorkspace' threw an exception. ---> System.TypeLoadException: Type Microsoft.CodeAnalysis.VisualBasic.CaseCorrection.VisualBasicCaseCorrectionService has invalid vtable method slot 6 with method none
  at (wrapper managed-to-native) System.RuntimeType:GetPropertiesByName_native (System.RuntimeType,intptr,System.Reflection.BindingFlags,bool)
  at System.RuntimeType.GetPropertiesByName (System.String name, System.Reflection.BindingFlags bindingAttr, System.Boolean icase, System.RuntimeType reflectedType) [0x00011] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/corlib/ReferenceSources/RuntimeType.cs:516
  at System.RuntimeType.GetPropertyCandidates (System.String name, System.Reflection.BindingFlags bindingAttr, System.Type[] types, System.Boolean allowPrefixLookup) [0x00010] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/referencesource/mscorlib/system/rttype.cs:2881
  at System.RuntimeType.GetProperties (System.Reflection.BindingFlags bindingAttr) [0x00000] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/referencesource/mscorlib/system/rttype.cs:3089
  at System.Reflection.RuntimeReflectionExtensions.GetRuntimeProperties (System.Type type) [0x00006] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/referencesource/mscorlib/system/reflection/RuntimeReflectionExtensions.cs:25
  at System.Composition.TypedParts.Discovery.TypeInspector+d__7.MoveNext () [0x00030] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.TypedParts.Discovery.TypeInspector+d__5.MoveNext () [0x000dc] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.TypedParts.Discovery.TypeInspector.InspectTypeForPart (System.Reflection.TypeInfo type, System.Composition.TypedParts.Discovery.DiscoveredPart& part) [0x00061] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.TypedParts.TypedPartExportDescriptorProvider..ctor (System.Collections.Generic.IEnumerable1[T] types, System.Composition.Convention.AttributedModelProvider attributeContext) [0x00037] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.Hosting.ContainerConfiguration.CreateContainer () [0x00042] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at Microsoft.CodeAnalysis.Host.Mef.MefHostServices.Create (System.Collections.Generic.IEnumerable1[T] assemblies) [0x0001e] in :0
  at MonoDevelop.Ide.TypeSystem.MonoDevelopWorkspace..cctor () [0x001f9] in /Users/builder/data/lanes/5144/b604c37c/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/MonoDevelopWorkspace.cs:121
   --- End of inner exception stack trace ---
  at MonoDevelop.CSharp.ProjectSearchCategory.Init () [0x00000] in /Users/builder/data/lanes/5144/b604c37c/source/monodevelop/main/src/addins/CSharpBinding/MonoDevelop.CSharp/ProjectSearchCategory.cs:53
  at MonoDevelop.CSharp.Project.CSharpProject.get_TargetRuntime () [0x0002b] in /Users/builder/data/lanes/5144/b604c37c/source/monodevelop/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpProjectExtension.cs:56
   --- End of inner exception stack trace ---
  at (wrapper managed-to-native) System.Reflection.MonoCMethod:InternalInvoke (System.Reflection.MonoCMethod,object,object[],System.Exception&)
  at System.Reflection.MonoCMethod.InternalInvoke (System.Object obj, System.Object[] parameters) [0x00002] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/corlib/System.Reflection/MonoMethod.cs:661
FATAL ERROR [2017-11-15 08:37:44Z]: Can't create roslyn workspace
System.TypeInitializationException: The type initializer for 'MonoDevelop.Ide.TypeSystem.MonoDevelopWorkspace' threw an exception. ---> System.TypeLoadException: Type Microsoft.CodeAnalysis.VisualBasic.CaseCorrection.VisualBasicCaseCorrectionService has invalid vtable method slot 6 with method none
  at (wrapper managed-to-native) System.RuntimeType:GetPropertiesByName_native (System.RuntimeType,intptr,System.Reflection.BindingFlags,bool)
  at System.RuntimeType.GetPropertiesByName (System.String name, System.Reflection.BindingFlags bindingAttr, System.Boolean icase, System.RuntimeType reflectedType) [0x00011] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/corlib/ReferenceSources/RuntimeType.cs:516
  at System.RuntimeType.GetPropertyCandidates (System.String name, System.Reflection.BindingFlags bindingAttr, System.Type[] types, System.Boolean allowPrefixLookup) [0x00010] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/referencesource/mscorlib/system/rttype.cs:2881
  at System.RuntimeType.GetProperties (System.Reflection.BindingFlags bindingAttr) [0x00000] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/referencesource/mscorlib/system/rttype.cs:3089
  at System.Reflection.RuntimeReflectionExtensions.GetRuntimeProperties (System.Type type) [0x00006] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/referencesource/mscorlib/system/reflection/RuntimeReflectionExtensions.cs:25
  at System.Composition.TypedParts.Discovery.TypeInspector+d__7.MoveNext () [0x00030] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.TypedParts.Discovery.TypeInspector+d__5.MoveNext () [0x000dc] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.TypedParts.Discovery.TypeInspector.InspectTypeForPart (System.Reflection.TypeInfo type, System.Composition.TypedParts.Discovery.DiscoveredPart& part) [0x00061] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.TypedParts.TypedPartExportDescriptorProvider..ctor (System.Collections.Generic.IEnumerable1[T] types, System.Composition.Convention.AttributedModelProvider attributeContext) [0x00037] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at System.Composition.Hosting.ContainerConfiguration.CreateContainer () [0x00042] in <9aac21a4a3f24063b2b8b59143acddfc>:0
  at Microsoft.CodeAnalysis.Host.Mef.MefHostServices.Create (System.Collections.Generic.IEnumerable1[T] assemblies) [0x0001e] in :0
  at MonoDevelop.Ide.TypeSystem.MonoDevelopWorkspace..cctor () [0x001f9] in /Users/builder/data/lanes/5144/b604c37c/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/MonoDevelopWorkspace.cs:121
   --- End of inner exception stack trace ---
  at (wrapper managed-to-native) System.Object:__icall_wrapper_mono_generic_class_init (intptr)
  at MonoDevelop.Ide.TypeSystem.TypeSystemService..cctor () [0x0009f] in /Users/builder/data/lanes/5144/b604c37c/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/TypeSystemService.cs:86

答: It was MFractor in my case - disabled it and now it works just fine - thanks a ton to @SushiHangover !!!</p>

Title: Visual Studio for Mac broken


问:
For selecting lower case boolean data type in selectOneMenu tag, how to bypass default value as false?
When this tag was rendered, I expected "--Select one--" would be displayed as default selection however itemLabel as "False" was chosen. My guess is it may have to do with lower case boolean in java defaults to false but I am not too sure.

This tag is inside of dataTable and each record represented by variable "foo" is an instance of java entity domain object. I am trying to understand why this is happening and how to correct it. I'd appreciate your advice in this matter.

```<code><p:selectOneMenu value="#{foo.answer}">
    <f:selectItem itemLabel="--Select one--" itemValue="" />
    <f:selectItem itemLabel="True" itemValue="true" />
    <f:selectItem itemLabel="False" itemValue="false" />
</p:selectOneMenu>
</code>```

The "foo" entity domain object.

```<code>@Entity
@Table(name="FOO")
public class Foo {

     @Type(type="org.hibernate.type.NumericBooleanType")
     @Column(name="answer", nullable=false)
     private boolean answer;
     ...
}
</code>```

答: A boolean indeed defaults to false. Make it a Boolean... your nullable=false prevents a NULL submission to be stored...</p>

Body:
When this tag was rendered, I expected "--Select one--" would be displayed as default selection however itemLabel as "False" was chosen. My guess is it may have to do with lower case boolean in java defaults to false but I am not too sure.

This tag is inside of dataTable and each record represented by variable "foo" is an instance of java entity domain object. I am trying to understand why this is happening and how to correct it. I'd appreciate your advice in this matter.

    <f:selectItem itemLabel="--Select one--" itemValue="" />
    <f:selectItem itemLabel="True" itemValue="true" />
    <f:selectItem itemLabel="False" itemValue="false" />

The "foo" entity domain object.

@Entity
@Table(name="FOO")
public class Foo {

     @Type(type="org.hibernate.type.NumericBooleanType")
     @Column(name="answer", nullable=false)
     private boolean answer;
     ...
}


问:
Can prometheus read consul node meta?
According to https://www.consul.io/docs/agent/options.html#_node_meta
I can associate with a consul node any metadata key/value pair.

Can prometheus read this metadata ?
I understand that only the following meta labels are available for prometheus:

__meta_consul_address: the address of the target

__meta_consul_node: the node name defined for the target

__meta_consul_tags: the list of tags of the target joined by the tag separator

__meta_consul_service: the name of the service the target belongs to

__meta_consul_service_address: the service address of the target

__meta_consul_service_port: the service port of the target

__meta_consul_service_id: the service ID of the target

__meta_consul_dc: the datacenter name for the target

But I would like to be absolutely sure that I miss nothing or there is no a trick to do it.

Thank you

答:
Yes. This was introduced into Prometheus 1.8

You can now simply reference __meta_consul_metadata_$KEYNAME

The following shows a prometheus label rewrite which filters the nodes 'location' metadata to a ldn fact which we've added to Consul agents running in London.

- source_labels: [__meta_consul_metadata_location]
    separator: ;
    regex: ldn
    replacement: $1
    action: keep

Title: Can prometheus read consul node meta?


问:
Select non empty elements of list in Python
Given:

```<code>a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'

list = (a, b, c, d, e)
</code>```

How can I get a string using all the non empty elements of the list ?

Desired output:

```<code>'aaa,ccc,eee'
</code>```

答:
Using a generator expression:

```<code>",".join(string for string in lst if len(string) > 0)
</code>```

The ",".join() part is using the join() method of strings, which takes an iterable argument and outputs a new string that concatenates the items using "," as delimiter.

The generator expression between parenthesis is being used to filter empty strings out of the list.

The original list doesn't change.

Body:
Given:

a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'

list = (a, b, c, d, e)

How can I get a string using all the non empty elements of the list ?

Desired output:

'aaa,ccc,eee'

Body:
Using a generator expression:

",".join(string for string in lst if len(string) > 0)

The ",".join() part is using the join() method of strings, which takes an iterable argument and outputs a new string that concatenates the items using "," as delimiter.

The generator expression between parenthesis is being used to filter empty strings out of the list.

The original list doesn't change.

ContentLicense: CC BY-SA 4.0


问:
AVCaptureDevice focusPointOfInterest doesn't change
I have an IBAction with this code:

.h file:

```<code>AVCaptureDevice *device;
</code>```

.m file:

```<code>- (IBAction)focusInfo {
 if (device == nil) {
  device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
 }

 NSLog(@"Camera focus point of interest: %d, %d", device.focusPointOfInterest.x, device.focusPointOfInterest.y);
}
</code>```

This is conneted to button on CustomCameraOverlay. When I am pressing the button while moving the camera nothing changes. The console log is all the  time the same:

```<code>Camera focus point of interest: 0, 1071644672
</code>```

Why it is not changing while camera is changing focus? What I am doing wrong? I tried also to get property isAdjustingFocus, but it is not changing as well.

I wanted to addObserwer for those properties, but stucked in here, observer won't work if value won't change.

答: focusPointOfInterest is of type CGPoint, which consists ofCGFloats. Try %f instead of %d.

Body:
I have an IBAction with this code:

.h file:

AVCaptureDevice *device;

.m file:

- (IBAction)focusInfo {
 if (device == nil) {
  device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
 }

 NSLog(@"Camera focus point of interest: %d, %d", device.focusPointOfInterest.x, device.focusPointOfInterest.y);
}

This is conneted to button on CustomCameraOverlay. When I am pressing the button while moving the camera nothing changes. The console log is all the  time the same:

Camera focus point of interest: 0, 1071644672

Why it is not changing while camera is changing focus? What I am doing wrong? I tried also to get property isAdjustingFocus, but it is not changing as well.

I wanted to addObserwer for those properties, but stucked in here, observer won't work if value won't change.


问:
How can you loop over lists of tuples where you compare the tuple in one list to the other tuples in the same list?
```<code>    for x in check:
        this = sorted(x) #the first tuple
        for y in check:
            that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
            if this == that:
                check.remove(x)

    print(check)
</code>```

I basically want to check for every list (in the list 'check') if there are tuples that are the same, such as (1, 3) and (3, 1). Then I want to remove the the last one ((3,1)) out of the list 'check'. However, the function returns a "list.remove(x): x not in list" error when I use "check.remove(x)". When I used "check.remove(y)", the result was :

output of "check.remove(y)"

I noticed that the first tuple (of the tuple with the same value) got deleted and that in the second last list, that there is still a pair of tuples that have the same values.

How the list 'check' looks like

How can I compare the tuples with each other in the same list and remove the second one that contains the same values?

答:
Repeated removal from a list is never a good a idea since it is O(N).
You can do the cleaning in one non-nested run-through, however. It is better to build a clean list from scratch and possibly reassign it to the same variable:

```<code>seen, no_dupes = set(), []
for c in check:
    s = tuple(sorted(c))
    if s not in seen:
         seen.add(s)
         no_dupes.append(c)
# check[:] = no_dupes  # if you must
</code>```

Body:
    for x in check:
        this = sorted(x) #the first tuple
        for y in check:
            that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
            if this == that:
                check.remove(x)

    print(check)

I basically want to check for every list (in the list 'check') if there are tuples that are the same, such as (1, 3) and (3, 1). Then I want to remove the the last one ((3,1)) out of the list 'check'. However, the function returns a "list.remove(x): x not in list" error when I use "check.remove(x)". When I used "check.remove(y)", the result was :

output of "check.remove(y)"

I noticed that the first tuple (of the tuple with the same value) got deleted and that in the second last list, that there is still a pair of tuples that have the same values.

How the list 'check' looks like

How can I compare the tuples with each other in the same list and remove the second one that contains the same values?

Body:
Repeated removal from a list is never a good a idea since it is O(N).
You can do the cleaning in one non-nested run-through, however. It is better to build a clean list from scratch and possibly reassign it to the same variable:

seen, no_dupes = set(), []
for c in check:
    s = tuple(sorted(c))
    if s not in seen:
         seen.add(s)
         no_dupes.append(c)
# check[:] = no_dupes  # if you must


问:
How to convert strings with even or odd numbers to 0 or 1?
Starting with the data of this form:

```<code>    col_1   col_2
0   a1      a6
1   a3      a7
2   a4      a2
3   a5      a8
</code>```

Where values are letters with numbers at the end. And I would like to convert values to 0 or 1 depending on the parity or oddness of the number at the end string, to data frame:

```<code>    col_1   col_2
0   1       0
1   1       1
2   0       0
3   1       0
</code>```

How I can approach this?

答:
If you have the data in a list of lists(dataList), this works

```<code>newData = []
for lst in dataList:
    data = []
    for item in lst:
        num = int(item[1::])%2
        data.append(num)
    newData.append(data)
</code>```

Output

```<code>[1, 0]
[1, 1]
[0, 0]
[1, 0]
</code>```

Then you can output the data however you like

Body:
Starting with the data of this form:

    col_1   col_2
0   a1      a6
1   a3      a7
2   a4      a2
3   a5      a8

Where values are letters with numbers at the end. And I would like to convert values to 0 or 1 depending on the parity or oddness of the number at the end string, to data frame:

    col_1   col_2
0   1       0
1   1       1
2   0       0
3   1       0

How I can approach this?

Body:
If you have the data in a list of lists(dataList), this works

newData = []
for lst in dataList:
    data = []
    for item in lst:
        num = int(item[1::])%2
        data.append(num)
    newData.append(data)

Output

[1, 0]
[1, 1]
[0, 0]
[1, 0]

Then you can output the data however you like


问:
Show postgres group schema permissions
I've performed the following on a postgres instance:

```<code>create group dev;
grant select on all tables in schema public to dev;
</code>```

All I'm trying to do is query a view/table to find this grant. I've tried looking in views like information_schema.table_privileges but can't see it. Could someone please point me in the right direction?

P.S. this needs to be a view to query as I'm running it from a python script, not psql.

EDIT: PostgreSQL version 10.0

答:
```<code>-bash-4.2$ psql t -E
psql (9.3.14)
Type "help" for help.

t=# \dp+ schema_name.*
********* QUERY **********
SELECT n.nspname as "Schema",
  c.relname as "Name",
  CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'S' THEN 'sequence' WHEN 'f' THEN 'foreign table' END as "Type",
  pg_catalog.array_to_string(c.relacl, E'\n') AS "Access privileges",
  pg_catalog.array_to_string(ARRAY(
    SELECT attname || E':\n  ' || pg_catalog.array_to_string(attacl, E'\n  ')
    FROM pg_catalog.pg_attribute a
    WHERE attrelid = c.oid AND NOT attisdropped AND attacl IS NOT NULL
  ), E'\n') AS "Column access privileges"
FROM pg_catalog.pg_class c
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'v', 'm', 'S', 'f')
  AND n.nspname ~ '^(schema_name)$'
ORDER BY 1, 2;
**************************
</code>```

so you can use same logic for your query, eg to list privs for user f in schema schema_name:

```<code>with l as (select relname,unnest(relacl) from pg_class c join pg_catalog.pg_namespace n ON n.oid = c.relnamespace where nspname = 'schema_name')
select * from l where unnest::text like 'f=%';
                       relname                       |    unnest
-----------------------------------------------------+--------------
 a_b                                                 | f=r/postgres
 b_c                                                 | f=r/postgres
</code>```

Title: Show postgres group schema permissions

Body:
I've performed the following on a postgres instance:

create group dev;
grant select on all tables in schema public to dev;

All I'm trying to do is query a view/table to find this grant. I've tried looking in views like information_schema.table_privileges but can't see it. Could someone please point me in the right direction?

P.S. this needs to be a view to query as I'm running it from a python script, not psql.

EDIT: PostgreSQL version 10.0

Body:
-bash-4.2$ psql t -E
psql (9.3.14)
Type "help" for help.

t=# \dp+ schema_name.*
********* QUERY **********
SELECT n.nspname as "Schema",
  c.relname as "Name",
  CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'S' THEN 'sequence' WHEN 'f' THEN 'foreign table' END as "Type",
  pg_catalog.array_to_string(c.relacl, E'\n') AS "Access privileges",
  pg_catalog.array_to_string(ARRAY(
    SELECT attname || E':\n  ' || pg_catalog.array_to_string(attacl, E'\n  ')
    FROM pg_catalog.pg_attribute a
    WHERE attrelid = c.oid AND NOT attisdropped AND attacl IS NOT NULL
  ), E'\n') AS "Column access privileges"
FROM pg_catalog.pg_class c
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'v', 'm', 'S', 'f')
  AND n.nspname ~ '^(schema_name)$'
ORDER BY 1, 2;
**************************

so you can use same logic for your query, eg to list privs for user f in schema schema_name:

with l as (select relname,unnest(relacl) from pg_class c join pg_catalog.pg_namespace n ON n.oid = c.relnamespace where nspname = 'schema_name')
select * from l where unnest::text like 'f=%';
                       relname                       |    unnest
-----------------------------------------------------+--------------
 a_b                                                 | f=r/postgres
 b_c                                                 | f=r/postgres


问:
How to read a class then a child class?
I am trying to find all the value in a child class using javascript (jquery). I am unable to pinpoint the issue using developer tool. I uploaded the HTML, javascript, and CSS FIDDLE

Just wanted to see what am I missing from my code that it doesn't even trigger the sample alert I have right after the loop of the parent-child code. HTML is here and in the fiddle. the alert should show Cost (1)

```<code></tr><tr class="ms-gb" lgrp="1"><td style="padding-left: 0px;" colspan="7"><a href="javascript:"><img id="lt_expandCollapseImage" onclick="_lt_LTGridViewExpandCollapseA(this.parentNode);" alt="Cost" src="/_layouts/15/images/plus.gif" border="0"></a> <span style="cursor: pointer;" onclick="_lt_LTGridViewExpandCollapseA(this);">Cost (1)</span></td></tr>

$(document).ready(function(){
    $(".ms-listviewtable td[class^='ms-gb']").each(function(){
      var mydiv = document.getElementsByClassName("nav-report-category")[0];
      var liTag = document.createElement('li');
      var aTag = document.createElement('a');
      var str = $(this).find("span:last");
      alert(str);
</code>```

$(document).ready(function() {
  $(".ms-listviewtable .tr[class='ms-gb']").each(function() {
    alert('test');
    var mydiv = document.getElementsByClassName("nav-report-category")[0];
    var liTag = document.createElement('li');
    var aTag = document.createElement('a');

    var str = $(this).find("span:last");
    alert(str);
    //var str = $(this).text();
    str = str.substring(str.indexOf(":") + 1); //remove everything before :
    str = str.substring(0, str.indexOf("(")); //remove counts

    if (!str.trim() || str.trim() == null) {
      liTag = document.createElement('li');
      aTag = document.createElement('a');
      aTag.innerHTML = "Other";
      var link = window.location.href + "&RC=" + str.trim();
    } else {
      liTag = document.createElement('li');
      aTag = document.createElement('a');
      aTag.innerHTML = str.trim();
      var link = window.location.href + "&RC=" + str.trim();
    }

    aTag.setAttribute('target', '_blank');
    aTag.setAttribute("href", link);

    liTag.appendChild(aTag);
    mydiv.appendChild(liTag);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-report-category {
  border: none !important;
}

.nav-report-category li {
  font-size: 16px;
  padding: 10px 0px;
  width: 110px;
  display: inline-block;
  background-color: rgb(74, 137, 220);
  color: #fff!important;
  margin-right: 5px;
  text-align: center;
  -moz-border-radius: 9px 9px 0px 0px;
  -webkit-border-radius: 9px 9px 0px 0px;
  border-radius: 9px 9px 0px 0px;
  font-color: #fff!important;
}

.nav-report-category li.active {
  background-color: #CB6015!important;
  color: #fff!important;
}

.nav-report-category li a:visited {
  color: #fff!important;
}

.nav-report-category li a {
  color: #fff!important;
}

.nav-report-category li:Hover {
  background-color: #BE3A34;
  text-decoration: none;
}

.tab-desc {
  background-color: rgb(93, 156, 236);
  color: #fff !important;
  padding: 5px;
}

.tab-desc H2 {
  color: #fff !important;
}</code>```

      Type

      Business Function

      Report Category

      Name
      Title

         Finance (9)

      rdl
      Accounting
      Finance
      AR Invoice Billing and Receipt History.rdl

      rdl
      Accounting
      Finance
      Financial Project Report V1.rdl

      rdl
      Accounting
      Finance
      Financial Project Report.rdl

      rdl
      Accounting
      Finance
      PA Billing Event Exception Details.rdl

      rdl
      Accounting
      Finance
      PA Expenditure Report.rdl

      rdl
      Accounting
      Finance
      Sales Order Detail Report.rdl

      rdl
      Accounting
      Finance
      Sales Order Summary Report.rdl

      rdl
      Accounting
      Finance
      WIP Reconciliation Report.rdl

      rdl
      Accounting
      Finance
      WIP Summary Report.rdl

         Markview (2)

      rdl
      Accounting
      Markview
      Markview Hold Report.rdl

      rdl
      Accounting
      Markview
      Markview Queue Rpt.rdl

```

答:
Two minor things:

ms-gb is on tr not on the td

str is a jQuery object. Change it to var str = $(this).find("span:last").text() for the text

Here's the FIDDLE

Title: How to read a class then a child class?

Body:
I am trying to find all the value in a child class using javascript (jquery). I am unable to pinpoint the issue using developer tool. I uploaded the HTML, javascript, and CSS FIDDLE

Just wanted to see what am I missing from my code that it doesn't even trigger the sample alert I have right after the loop of the parent-child code. HTML is here and in the fiddle. the alert should show Cost (1)

 Cost (1)

$(document).ready(function(){
    $(".ms-listviewtable td[class^='ms-gb']").each(function(){
      var mydiv = document.getElementsByClassName("nav-report-category")[0];
      var liTag = document.createElement('li');
      var aTag = document.createElement('a');
      var str = $(this).find("span:last");
      alert(str);

$(document).ready(function() {
  $(".ms-listviewtable .tr[class='ms-gb']").each(function() {
    alert('test');
    var mydiv = document.getElementsByClassName("nav-report-category")[0];
    var liTag = document.createElement('li');
    var aTag = document.createElement('a');

    var str = $(this).find("span:last");
    alert(str);
    //var str = $(this).text();
    str = str.substring(str.indexOf(":") + 1); //remove everything before :
    str = str.substring(0, str.indexOf("(")); //remove counts

    if (!str.trim() || str.trim() == null) {
      liTag = document.createElement('li');
      aTag = document.createElement('a');
      aTag.innerHTML = "Other";
      var link = window.location.href + "&RC=" + str.trim();
    } else {
      liTag = document.createElement('li');
      aTag = document.createElement('a');
      aTag.innerHTML = str.trim();
      var link = window.location.href + "&RC=" + str.trim();
    }

    aTag.setAttribute('target', '_blank');
    aTag.setAttribute("href", link);

    liTag.appendChild(aTag);
    mydiv.appendChild(liTag);
  });
});

.nav-report-category {
  border: none !important;
}

.nav-report-category li {
  font-size: 16px;
  padding: 10px 0px;
  width: 110px;
  display: inline-block;
  background-color: rgb(74, 137, 220);
  color: #fff!important;
  margin-right: 5px;
  text-align: center;
  -moz-border-radius: 9px 9px 0px 0px;
  -webkit-border-radius: 9px 9px 0px 0px;
  border-radius: 9px 9px 0px 0px;
  font-color: #fff!important;
}

.nav-report-category li.active {
  background-color: #CB6015!important;
  color: #fff!important;
}

.nav-report-category li a:visited {
  color: #fff!important;
}

.nav-report-category li a {
  color: #fff!important;
}

.nav-report-category li:Hover {
  background-color: #BE3A34;
  text-decoration: none;
}

.tab-desc {
  background-color: rgb(93, 156, 236);
  color: #fff !important;
  padding: 5px;
}

.tab-desc H2 {
  color: #fff !important;
}

      Type

      Business Function

      Report Category

      Name
      Title

         Finance (9)

        <a title="Click to open "AR Invoice Billing and Receipt History.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/AR%20Invoice%20Billing%20and%20Receipt%20History.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/AR%20Invoice%20Billing%20and%20Receipt%20History.rdl");"
          href="https://myanalytix.beta.com/SSRSReports/AR%20Invoice%20Billing%20and%20Receipt%20History.rdl">

      rdl
      Accounting
      Finance
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/AR%20Invoice%20Billing%20and%20Receipt%20History.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/AR%20Invoice%20Billing%20and%20Receipt%20History.rdl");"
          href="https://myanalytix.beta.com/SSRSReports/AR%20Invoice%20Billing%20and%20Receipt%20History.rdl">AR Invoice Billing and Receipt History.rdl

        <a title="Click to open "Financial Project Report V1.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Financial%20Project%20Report%20V1.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Financial%20Project%20Report%20V1.rdl");" href="https://myanalytix.beta.com/SSRSReports/Financial%20Project%20Report%20V1.rdl">

      rdl
      Accounting
      Finance
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Financial%20Project%20Report%20V1.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Financial%20Project%20Report%20V1.rdl");" href="https://myanalytix.beta.com/SSRSReports/Financial%20Project%20Report%20V1.rdl">Financial Project Report V1.rdl

        <a title="Click to open "Financial Project Report.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Financial%20Project%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Financial%20Project%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/Financial%20Project%20Report.rdl">

      rdl
      Accounting
      Finance
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Financial%20Project%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Financial%20Project%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/Financial%20Project%20Report.rdl">Financial Project Report.rdl

        <a title="Click to open "PA Billing Event Exception Details.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/PA%20Billing%20Event%20Exception%20Details.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/PA%20Billing%20Event%20Exception%20Details.rdl");" href="https://myanalytix.beta.com/SSRSReports/PA%20Billing%20Event%20Exception%20Details.rdl">

      rdl
      Accounting
      Finance
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/PA%20Billing%20Event%20Exception%20Details.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/PA%20Billing%20Event%20Exception%20Details.rdl");" href="https://myanalytix.beta.com/SSRSReports/PA%20Billing%20Event%20Exception%20Details.rdl">PA Billing Event Exception Details.rdl

        <a title="Click to open "PA Expenditure Report.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/PA%20Expenditure%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/PA%20Expenditure%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/PA%20Expenditure%20Report.rdl">

      rdl
      Accounting
      Finance
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/PA%20Expenditure%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/PA%20Expenditure%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/PA%20Expenditure%20Report.rdl">PA Expenditure Report.rdl

        <a title="Click to open "Sales Order Detail Report.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Sales%20Order%20Detail%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Sales%20Order%20Detail%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/Sales%20Order%20Detail%20Report.rdl">

      rdl
      Accounting
      Finance
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Sales%20Order%20Detail%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Sales%20Order%20Detail%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/Sales%20Order%20Detail%20Report.rdl">Sales Order Detail Report.rdl

        <a title="Click to open "Sales Order Summary Report.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Sales%20Order%20Summary%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Sales%20Order%20Summary%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/Sales%20Order%20Summary%20Report.rdl">

      rdl
      Accounting
      Finance
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Sales%20Order%20Summary%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Sales%20Order%20Summary%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/Sales%20Order%20Summary%20Report.rdl">Sales Order Summary Report.rdl

        <a title="Click to open "WIP Reconciliation Report.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/WIP%20Reconciliation%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/WIP%20Reconciliation%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/WIP%20Reconciliation%20Report.rdl">

      rdl
      Accounting
      Finance
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/WIP%20Reconciliation%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/WIP%20Reconciliation%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/WIP%20Reconciliation%20Report.rdl">WIP Reconciliation Report.rdl

        <a title="Click to open "WIP Summary Report.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/WIP%20Summary%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/WIP%20Summary%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/WIP%20Summary%20Report.rdl">

      rdl
      Accounting
      Finance
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/WIP%20Summary%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/WIP%20Summary%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/WIP%20Summary%20Report.rdl">WIP Summary Report.rdl

         Markview (2)

        <a title="Click to open "Markview Hold Report.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Markview%20Hold%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Markview%20Hold%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/Markview%20Hold%20Report.rdl">

      rdl
      Accounting
      Markview
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Markview%20Hold%20Report.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Markview%20Hold%20Report.rdl");" href="https://myanalytix.beta.com/SSRSReports/Markview%20Hold%20Report.rdl">Markview Hold Report.rdl

        <a title="Click to open "Markview Queue Rpt.rdl"" onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Markview%20Queue%20Rpt.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Markview%20Queue%20Rpt.rdl");" href="https://myanalytix.beta.com/SSRSReports/Markview%20Queue%20Rpt.rdl">

      rdl
      Accounting
      Markview
      <a onclick="DispDocItemExWithServerRedirect(this, event, "FALSE", "FALSE", "FALSE", "", "1", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Markview%20Queue%20Rpt.rdl"); return false;"
          onmousedown="return VerifyHref(this, event, "1", "", "1https://myanalytix.beta.com/_layouts/15/ReportServer/RSViewerPage.aspx?rv:RelativeReportUrl=/SSRSReports/Markview%20Queue%20Rpt.rdl");" href="https://myanalytix.beta.com/SSRSReports/Markview%20Queue%20Rpt.rdl">Markview Queue Rpt.rdl


问:
Remove table rows based on condition in matlab
a=[1; 2 ; 3]; b=[ 4; 5; 6 ]; T=table(a,b).
I want to remove rows of table for which the value of b is less than or equal to 5 (b<=5).

答:
Fast, simple. elegant:</p>

```<code>T(T.b <= 5,:) = [];
</code>```

Body:
Fast, simple. elegant:

T(T.b <= 5,:) = [];


问:
.(dot) access to static method
Following is a popular code:

```<code>class A
{
public:
    static const string TYPE = "AEvent";
    const string& getType() { return TYPE; }
};
</code>```

Above code could be use like this:

```<code>if (aInstance.getType() == A::TYPE)
{
    ...
}
</code>```

It's fine. But it's not intuitiveness. Did not? Look at the next code:

```<code>class A
{
public:
    static const string& getType()
    {
        static const string TYPE = "AEvent";
        return TYPE;
    }
}
//Usage
if (aInstance.getType() == A::getType())
    ....
</code>```

Of course, getType is static method but it's possible to access dot operator and It's more intuitively see to me.

How do you think about?

答: If it's clearer to use obj.static_member (or method), then use it; this is often true when the type name is long, such as with templates.  Otherwise use Type::static_member.</p>

Title: .(dot) access to static method

Body:
Following is a popular code:

class A
{
public:
    static const string TYPE = "AEvent";
    const string& getType() { return TYPE; }
};

Above code could be use like this:

if (aInstance.getType() == A::TYPE)
{
    ...
}

It's fine. But it's not intuitiveness. Did not? Look at the next code:

class A
{
public:
    static const string& getType()
    {
        static const string TYPE = "AEvent";
        return TYPE;
    }
}
//Usage
if (aInstance.getType() == A::getType())
    ....

Of course, getType is static method but it's possible to access dot operator and It's more intuitively see to me.

How do you think about?


问:
Count Case with 2 columns with the same values (Clarified)
Basically I want COUNT a CASE when values are present in 2 columns.

For example:

```<code>SELECT
   COUNT
      (CASE WHEN 1.sample AND 2.sample IN ('a','b','c')
       THEN 1
       ELSE NULL
       END
      )   AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2
...
</code>```

Message:

Conversion failed when converting the varchar value '08:12.06' to data
  type int. Warning: Null value is eliminated by an aggregate or other
  SET operation.

I get what's triggering the error, I just don't know a solution to count the case when values are present in both columns.

答:
You need to list the columns separately for comparison. Usually I specify a column to count, and you do not need to put NULL for the else condition.</p>

```<code>SELECT
   COUNT
      (CASE WHEN 1.sample IS NULL OR 2.sample IS NULL THEN 0
            WHEN (    1.sample IN ('a','b','c')
                  AND 2.sample IN ('a','b','c')
                 )
       THEN 1.sample
       END
      )   AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2 ON....
</code>```

Body:
Basically I want COUNT a CASE when values are present in 2 columns.

For example:

SELECT
   COUNT
      (CASE WHEN 1.sample AND 2.sample IN ('a','b','c')
       THEN 1
       ELSE NULL
       END
      )   AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2
...

Message:

Conversion failed when converting the varchar value '08:12.06' to data
  type int. Warning: Null value is eliminated by an aggregate or other
  SET operation.

I get what's triggering the error, I just don't know a solution to count the case when values are present in both columns.

Body:
You need to list the columns separately for comparison. Usually I specify a column to count, and you do not need to put NULL for the else condition.

SELECT
   COUNT
      (CASE WHEN 1.sample IS NULL OR 2.sample IS NULL THEN 0
            WHEN (    1.sample IN ('a','b','c')
                  AND 2.sample IN ('a','b','c')
                 )
       THEN 1.sample
       END
      )   AS CASE
FROM table1 AS 1
INNER JOIN table2 AS 2 ON....


问:
R - Correlation Matrix - How to plot with this data?
I have the data like below:

```<code>A B 100
A C 100
B D 80
A D 50
B C 5
B D 60
</code>```

basically three columns column 1 and Column 2 are character columns and column 3 is an integer which represents percentage of match between Col1 and Col2. Now I would like to represent this data as a correlation matrix. How can I do the same?

答:
Here is an example on how to reconstruct the whole correlation matrix relatively simply using igraph:

```<code>library(igraph)
library(corrplot)

g <- graph.data.frame(df, directed = FALSE)
mat <- get.adjacency(g, attr = "V3", sparse = FALSE)
mat
#output
    A   B   C  D
A   0 100 100 50
B 100   0   5 60
C 100   5   0  0
D  50  60   0  0
 diag(mat) <- 100
 mat <- mat/100

 corrplot.mixed(mat, upper =  "shade", "number")
</code>```

Body:
I have the data like below:

A B 100
A C 100
B D 80
A D 50
B C 5
B D 60

basically three columns column 1 and Column 2 are character columns and column 3 is an integer which represents percentage of match between Col1 and Col2. Now I would like to represent this data as a correlation matrix. How can I do the same?

Body:
Here is an example on how to reconstruct the whole correlation matrix relatively simply using igraph:

library(igraph)
library(corrplot)

g <- graph.data.frame(df, directed = FALSE)
mat <- get.adjacency(g, attr = "V3", sparse = FALSE)
mat
#output
    A   B   C  D
A   0 100 100 50
B 100   0   5 60
C 100   5   0  0
D  50  60   0  0
 diag(mat) <- 100
 mat <- mat/100

 corrplot.mixed(mat, upper =  "shade", "number")


问:
How to make search Icon and back button icon disappear when clicking on different tab in TabLayout?
When you click on Search icon the searchView and keyboard appear, if the user decides to click on a different tab in TabLayout, I got the searchView and keyboard to disappear but I can't get the "Back" icon button and Search Icon button to disappear.

Here's what it looks when searchView was open and user clicks on a different Tab in TabLayout:

^ Also when user clicks on different tab in TabLayout for some reason Search Icon appears on left side instead of right side before the searchView open click.

Here's my code in menu_main.xml:

```<code> <item
    android:id="@+id/menuSearch"
    android:title="@string/search"
    android:hint="@string/search"
    android:icon="@drawable/ic_search_black_24dp"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"

     />
</code>```

Here's my MainActivity code inside public boolean onCreateOptionsMenu(final Menu menu):

```<code>    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            final InputMethodManager imm = (InputMethodManager)getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);

         //   searchView.setLayoutParams(new ActionBar.LayoutParams(Gravity.END));

          //  actionBar.setDisplayHomeAsUpEnabled(false);
          //  searchView.setIconifiedByDefault(false);

           /* if (mViewPager.callOnClick()){
                actionBar.setDisplayHomeAsUpEnabled(false);
                  searchView.setIconifiedByDefault(false);
            }*/

            searchView.onActionViewCollapsed(); //closes searchView
</code>```

EDIT

```<code>  if (mViewPager.getCurrentItem() == 0 || mViewPager.getCurrentItem() == 1 || mViewPager.getCurrentItem() == 2) {
  menu.findItem(R.id.menuSearch).collapseActionView();

  }

        }

        @Override
        public void onPageScrolled(int position, float offset, int offsetPixels) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

    });
</code>```

The commented out code is what I tried but none of it seems to do anything. How do I get the "Back" icon button and Search icon button to also hide/disappear/close when I click on a different tab in TabLayout?

答:
Try this:

```<code>searchView.setIconified(true);
</code>```

or

```<code>MenuItemCompat.collapseActionView(menuItem)
</code>```

or

```<code>searchView.onActionViewCollapsed();
searchView.setQuery("", false);
searchView.clearFocus();
</code>```

Body:
When you click on Search icon the searchView and keyboard appear, if the user decides to click on a different tab in TabLayout, I got the searchView and keyboard to disappear but I can't get the "Back" icon button and Search Icon button to disappear.

Here's what it looks when searchView was open and user clicks on a different Tab in TabLayout:

^ Also when user clicks on different tab in TabLayout for some reason Search Icon appears on left side instead of right side before the searchView open click.

Here's my code in menu_main.xml:

 <item
    android:id="@+id/menuSearch"
    android:title="@string/search"
    android:hint="@string/search"
    android:icon="@drawable/ic_search_black_24dp"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"

     />

Here's my MainActivity code inside public boolean onCreateOptionsMenu(final Menu menu):

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            final InputMethodManager imm = (InputMethodManager)getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);

         //   searchView.setLayoutParams(new ActionBar.LayoutParams(Gravity.END));

          //  actionBar.setDisplayHomeAsUpEnabled(false);
          //  searchView.setIconifiedByDefault(false);

           /* if (mViewPager.callOnClick()){
                actionBar.setDisplayHomeAsUpEnabled(false);
                  searchView.setIconifiedByDefault(false);
            }*/

            searchView.onActionViewCollapsed(); //closes searchView

EDIT

  if (mViewPager.getCurrentItem() == 0 || mViewPager.getCurrentItem() == 1 || mViewPager.getCurrentItem() == 2) {
  menu.findItem(R.id.menuSearch).collapseActionView();

  }

        }

        @Override
        public void onPageScrolled(int position, float offset, int offsetPixels) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

    });

The commented out code is what I tried but none of it seems to do anything. How do I get the "Back" icon button and Search icon button to also hide/disappear/close when I click on a different tab in TabLayout?

Body:
Try this:

searchView.setIconified(true);

or

MenuItemCompat.collapseActionView(menuItem)

or

searchView.onActionViewCollapsed();
searchView.setQuery("", false);
searchView.clearFocus();


答:
Your question is a little confusing but generally speaking if you want to access a child element using jquery all you have to do is:</p>

```<code><div class="primary">
        <div>1</div>
        <div>2</div>
        <div>3</div>
    </div>
    $(document).ready(function(){
        $(".primary").click(function(){
            $(this).children().each(function(){

            });

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

Title: How to read a class then a child class?

Body:
Your question is a little confusing but generally speaking if you want to access a child element using jquery all you have to do is:

<div class="primary">
        <div>1</div>
        <div>2</div>
        <div>3</div>
    </div>
    $(document).ready(function(){
        $(".primary").click(function(){
            $(this).children().each(function(){

            });

        });
    });


问:
How to Convert Each Character of String to ASCII and Pad to Given Length
Using Python 3.4, I am trying to convert a string to padded ASCII values (for each character).

Given a sting:

```<code>myString = "hello world"
</code>```

Convert each character to ASCII and join back into a single string:

```<code>asciiString = ''.join(str(ord(c)) for c in myString)
</code>```

This works great, returning:

```<code>'10410110810811132119111114108100'
</code>```

I would like to pad EACH CHARACTER to 7 digits and then join. I've been trying to do this with format and have tried so many combinations of join, format, str, and ord that I can't even list them all. Can someone please help me figure out how to add format to the "asciiString =" line?  Maybe this can't be done in a single line of code?

答:
```<code>asciiString = ''.join(str('{num:07d}'.format(num=ord(c))) for c in myString)
</code>```

Body:
Using Python 3.4, I am trying to convert a string to padded ASCII values (for each character).

Given a sting:

myString = "hello world"

Convert each character to ASCII and join back into a single string:

asciiString = ''.join(str(ord(c)) for c in myString)

This works great, returning:

'10410110810811132119111114108100'

I would like to pad EACH CHARACTER to 7 digits and then join. I've been trying to do this with format and have tried so many combinations of join, format, str, and ord that I can't even list them all. Can someone please help me figure out how to add format to the "asciiString =" line?  Maybe this can't be done in a single line of code?


问:
IONIC2/Angular2 ngOnChange doesn't work
I'm new to Angular2 and I've been struggling for a while with this problem and have found no solution to it online.

[on ionic2!]

I want to use ngOnChanges() so i can detect changes to zonaid:

estados.html:

```<code><ion-item>
       <ion-label color="branco">Zonas</ion-label>

              <ion-select *ngIf="isTrue2" [(ngModel)]=zonaid>
                 <ion-option value={{bicho.zonas}} *ngFor="let bicho of idespecie">
                    {{bicho.zonas}}
                 </ion-option>
             </ion-select>

              <ion-select *ngIf="!isTrue2" [(ngModel)]="zonaid">
                 <ion-option value={{item.id}} *ngFor="let item of itemsZon" >
                    {{item.codigo}}
                 </ion-option>

              </ion-select>
     </ion-item>
</code>```

idespecie and itemsZon are parts of .json files

estados.ts

```<code>import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';
import { NavController } from 'ionic-angular';
import { IpmaBivService} from '../../app/services/ipmabiv.service'
import { Http } from '@angular/http';

@Component({
  selector: 'page-estados',
  templateUrl: 'estados.html'
})
export class EstadosPage {
   itemsZon: any;
   itemsEsp: any;
   zonaEscolhida: any;

   @Input()
   zonaid: string;

   idzona: '';
   idespecie: any[];

   isTrue1:boolean = false;
   isTrue2:boolean = false;
   constructor(public navCtrl: NavController, private ipmaBivService:IpmaBivService) {
  }
  ngOnChanges(changes: SimpleChanges){
     console.log('ngOnChanges ran');
     if(this.zonaid != ''){
        this.isTrue1 = true;
        this.getJsonZonas(this.zonaid);
     }
     if(this.especie != ''){
        this.isTrue2 = true;
        this.getJsonEspecies(this.especie);
     }
 }

}
  ngOnInit(){
     this.getDataZonas('zonas')
     this.getDataEspecies('especies')
   //   this.getData('especies')
 }
 }
</code>```

app.module.ts

```<code>    import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { HttpModule, JsonpModule } from '@angular/http';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { EstadosPage } from '../pages/estados/estados';
import { OutrosPage } from '../pages/estados/outros';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    EstadosPage,
    OutrosPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    JsonpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    OutrosPage,
    EstadosPage

  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
</code>```

Everything is happening in the same component (ionic page).

My goal is just to be able to run a method whenever zonaid changes. If you think there is a better way than goin through ngOnChanges, pls let me know

Thanks!

答:
try export class EstadosPage implements OnChanges {

https://angular.io/api/core/OnChanges

Title: IONIC2/Angular2 ngOnChange doesn't work

Body:
I'm new to Angular2 and I've been struggling for a while with this problem and have found no solution to it online.

[on ionic2!]

I want to use ngOnChanges() so i can detect changes to zonaid:

estados.html:

<ion-item>
       <ion-label color="branco">Zonas</ion-label>

              <ion-select *ngIf="isTrue2" [(ngModel)]=zonaid>
                 <ion-option value={{bicho.zonas}} *ngFor="let bicho of idespecie">
                    {{bicho.zonas}}
                 </ion-option>
             </ion-select>

              <ion-select *ngIf="!isTrue2" [(ngModel)]="zonaid">
                 <ion-option value={{item.id}} *ngFor="let item of itemsZon" >
                    {{item.codigo}}
                 </ion-option>

              </ion-select>
     </ion-item>

idespecie and itemsZon are parts of .json files

estados.ts

import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';
import { NavController } from 'ionic-angular';
import { IpmaBivService} from '../../app/services/ipmabiv.service'
import { Http } from '@angular/http';

@Component({
  selector: 'page-estados',
  templateUrl: 'estados.html'
})
export class EstadosPage {
   itemsZon: any;
   itemsEsp: any;
   zonaEscolhida: any;

   @Input()
   zonaid: string;

   idzona: '';
   idespecie: any[];

   isTrue1:boolean = false;
   isTrue2:boolean = false;
   constructor(public navCtrl: NavController, private ipmaBivService:IpmaBivService) {
  }
  ngOnChanges(changes: SimpleChanges){
     console.log('ngOnChanges ran');
     if(this.zonaid != ''){
        this.isTrue1 = true;
        this.getJsonZonas(this.zonaid);
     }
     if(this.especie != ''){
        this.isTrue2 = true;
        this.getJsonEspecies(this.especie);
     }
 }

}
  ngOnInit(){
     this.getDataZonas('zonas')
     this.getDataEspecies('especies')
   //   this.getData('especies')
 }
 }

app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { HttpModule, JsonpModule } from '@angular/http';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { EstadosPage } from '../pages/estados/estados';
import { OutrosPage } from '../pages/estados/outros';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    EstadosPage,
    OutrosPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    JsonpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    OutrosPage,
    EstadosPage

  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

Everything is happening in the same component (ionic page).

My goal is just to be able to run a method whenever zonaid changes. If you think there is a better way than goin through ngOnChanges, pls let me know

Thanks!


问:
Django OAuth Toolkit with Multiple Grants
I'm using Django OAuth Toolkit and I would like to register applications with multiple grants. Some applications may have just one type of grant, others may have more.

The official documentation:

http://django-oauth-toolkit.readthedocs.io/en/latest/advanced_topics.html#multiple-grants

recommends:

```<code>class MyApplication(AbstractApplication):
def allows_grant_type(self, *grant_types):
    # Assume, for this example, that self.authorization_grant_type is set to self.GRANT_AUTHORIZATION_CODE
    return bool( set(self.authorization_grant_type, self.GRANT_CLIENT_CREDENTIALS) & grant_types )
</code>```

but I get an error saying that "TypeError: set expected at most 1 arguments, got 2"

Also as I understand this doesn't modify the model in the db. This would return if the intersection of the sets is empty or not. So won't this make (if it works) the GRANT_CLIENT_CREDENTIALS available to all applications?

答:
like the error says
the set function expect one parameters you gave it 2
so you need to modify your code a little bit like that </p>

```<code>    return bool( set([self.authorization_grant_type, self.GRANT_CLIENT_CREDENTIALS]) & set(grant_types) )
</code>```

Body:
I'm using Django OAuth Toolkit and I would like to register applications with multiple grants. Some applications may have just one type of grant, others may have more.

The official documentation:

http://django-oauth-toolkit.readthedocs.io/en/latest/advanced_topics.html#multiple-grants

recommends:

class MyApplication(AbstractApplication):
def allows_grant_type(self, *grant_types):
    # Assume, for this example, that self.authorization_grant_type is set to self.GRANT_AUTHORIZATION_CODE
    return bool( set(self.authorization_grant_type, self.GRANT_CLIENT_CREDENTIALS) & grant_types )

but I get an error saying that "TypeError: set expected at most 1 arguments, got 2"

Also as I understand this doesn't modify the model in the db. This would return if the intersection of the sets is empty or not. So won't this make (if it works) the GRANT_CLIENT_CREDENTIALS available to all applications?

Body:
like the error says
the set function expect one parameters you gave it 2
so you need to modify your code a little bit like that

    return bool( set([self.authorization_grant_type, self.GRANT_CLIENT_CREDENTIALS]) & set(grant_types) )


问:
CSS Flexbox 3 columns Grid (4X4 + 1 large)
I'm trying to figure out how to get this in Flexbox, but the only thing I can get is in the code snippet:

Do you have an idea to manage this CSS only (I can't really touch the structure of the HTML as it is a PHP foreach loop)?

Could using CSS grid help here?

.grid {
  display: flex;
  justify-content: start;
  flex-wrap: wrap;
}

.photo {
  position: relative;
  flex: 0 0 calc(25% - 20px);
  margin: 10px;
  align-self: flex-start;
  overflow: hidden;
  background: black;
}

.photo:after {
  content: "";
  display: block;
  padding-top: 100%;
}

.large {
  flex: 0 0 calc(50% - 20px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="photo large"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
</div></code>```

答:
Based on then fact that this is squares, you can simply position the large absolute, to the right, and the smaller, with their padding-top trick, will controls the large's height.

Then, by setting a padding on the grid, we keep the smaller on the left side and make space on the right for the large.

Additionally, we also need to change the small to be 50% of the space, not 25%.

Stack snippet

.grid {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  padding-right: 50%;
}

.photo {
  position: relative;
  flex: 0 0 calc(50% - 20px);
  margin: 10px;
  overflow: hidden;
  background: black;
}

.photo:not(.large):after {
  content: "";
  display: block;
  padding-top: 100%;
}

.large {
  position: absolute;
  right: 0;
  width: calc(50% - 20px);
  height: calc(100% - 20px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="photo large"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
</div></code>```

Body:
Based on then fact that this is squares, you can simply position the large absolute, to the right, and the smaller, with their padding-top trick, will controls the large's height.

Then, by setting a padding on the grid, we keep the smaller on the left side and make space on the right for the large.

Additionally, we also need to change the small to be 50% of the space, not 25%.

Stack snippet

.grid {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  padding-right: 50%;
}

.photo {
  position: relative;
  flex: 0 0 calc(50% - 20px);
  margin: 10px;
  overflow: hidden;
  background: black;
}

.photo:not(.large):after {
  content: "";
  display: block;
  padding-top: 100%;
}

.large {
  position: absolute;
  right: 0;
  width: calc(50% - 20px);
  height: calc(100% - 20px);
}

<div class="grid">
  <div class="photo large"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
  <div class="photo"></div>
</div>


问:
I need help in action forms
I am working in HTML and forget how to The action of the form should be null (#).I have been looking through my book and even looking on the web for it can someone point me in the right directions. I have to make a survey for my class and it all need to be null or the form does. thank you so much.</p>

答: I think the only way to stop a form from submitting is to use JavaScript. If you leave the action blank (action="") or leave it off entirely, then it defaults to the current page. That's probably as close to a null action as you're going to get.

Title: I need help in action forms


问:
Has anybody recently made Google Maps work on localhost in development mode?
I have wasted several hours in vain. Some Stack Overflow answers elsewhere say that Google documentation is incorrect. However, their suggestions did not work for me. I still get this error:

Google Maps API error: RefererNotAllowedMapError
  https://developers.google.com/maps/documentation/javascript/error-messages#referer-not-allowed-map-error
  Your site URL to be authorized: http://localhost:3000/addresses/1

How am I supposed to do it on a Rails application in development mode?

I have tried various combinations of Application restrictions and I can not make it work. How do I correctly set up my API_KEY and it's restrictions? The UI has changed and the old answers do not help at all.

答:
If you haven't already, make sure you add localhost:3000/* to the "Accept requests from these HTTP referrers (web sites)" field. It's a little awkward to get this to save if I remember correctly.

Here's a screen shot of my settings that are working:


问:
Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"
I'm looking for more information on the message below. Xcode 9 seems to be hanging for a couple minutes already...

How can I tell Xcode 9 to quickly recognize my previously used device updated to iOS 11?

.Alex’s iPhone is busy: Preparing debugger support for .Alex’s iPhone

Xcode will continue when .Alex’s iPhone is finished.

答:
I had the same problem many times, these things worked for me:

restarting my phone + xCode.

checking that both your Mac and your iPhone are connected to the same Network.( has a high potential ).

repairing my phone.


问:
How can I remove the last character of a String in Swift 4?
How do I remove the last character of a string in Swift 4? I used to use substring in earlier versions of Swift, but the substring method is deprecated.

Here's the code I have.

```<code>temp = temp.substring(to: temp.index(before: temp.endIndex))
</code>```

答:
dropLast() is your safest bet, because it handles nils and empty strings without crashing (answer by OverD), but if you want to return the character you removed, use removeLast():

```<code>var str = "String"
let removedCharacter = str.removeLast() //str becomes "Strin"
                                        //and removedCharacter will be "g"
</code>```

A different function, removeLast(_:) changes the count of the characters that should be removed:

```<code>var str = "String"
str.removeLast(3) //Str
</code>```

The difference between the two is that removeLast() returns the character that was removed, while removeLast(_:) does not have a return value:

```<code>var str = "String"
print(str.removeLast()) //prints out "g"
</code>```

Body:
How do I remove the last character of a string in Swift 4? I used to use substring in earlier versions of Swift, but the substring method is deprecated.

Here's the code I have.

temp = temp.substring(to: temp.index(before: temp.endIndex))

Body:
dropLast() is your safest bet, because it handles nils and empty strings without crashing (answer by OverD), but if you want to return the character you removed, use removeLast():

var str = "String"
let removedCharacter = str.removeLast() //str becomes "Strin"
                                        //and removedCharacter will be "g"

A different function, removeLast(_:) changes the count of the characters that should be removed:

var str = "String"
str.removeLast(3) //Str

The difference between the two is that removeLast() returns the character that was removed, while removeLast(_:) does not have a return value:

var str = "String"
print(str.removeLast()) //prints out "g"