问:
Status bar and navigation bar appear over my view's bounds in iOS 7
I recently downloaded Xcode 5 DP to test my apps in iOS 7. The first thing I noticed and confirmed is that my view's bounds is not always resized to account for the status bar and navigation bar.

In viewDidLayoutSubviews, I print the view's bounds:

{{0, 0}, {320, 568}}

This results in my content appearing below the navigation bar and status bar.

I know I could account for the height myself by getting the main screen's height, subtracting the status bar's height and navigation bar's height, but that seems like unnecessary extra work.

How can I fix this issue?

Update:

I've found a solution for this specific problem. Set the navigation bar's translucent property to NO:

```<code>self.navigationController.navigationBar.translucent = NO;
</code>```

This will fix the view from being framed underneath the navigation bar and status bar.

However, I have not found a fix for the case when you want the navigation bar to be translucent. For instance, viewing a photo full screen, I wish to have the navigation bar translucent, and the view to be framed underneath it. That works, but when I toggle showing/hiding the navigation bar, I've experienced even stranger results. The first subview (a UIScrollView) gets its bounds y origin changed every time.

答:
Swift 3

```<code>override func viewWillAppear(_ animated: Bool) {
    self.edgesForExtendedLayout = []
}
</code>```

Body:
I recently downloaded Xcode 5 DP to test my apps in iOS 7. The first thing I noticed and confirmed is that my view's bounds is not always resized to account for the status bar and navigation bar.

In viewDidLayoutSubviews, I print the view's bounds:

{{0, 0}, {320, 568}}

This results in my content appearing below the navigation bar and status bar.

I know I could account for the height myself by getting the main screen's height, subtracting the status bar's height and navigation bar's height, but that seems like unnecessary extra work.

How can I fix this issue?

Update:

I've found a solution for this specific problem. Set the navigation bar's translucent property to NO:

self.navigationController.navigationBar.translucent = NO;

This will fix the view from being framed underneath the navigation bar and status bar.

However, I have not found a fix for the case when you want the navigation bar to be translucent. For instance, viewing a photo full screen, I wish to have the navigation bar translucent, and the view to be framed underneath it. That works, but when I toggle showing/hiding the navigation bar, I've experienced even stranger results. The first subview (a UIScrollView) gets its bounds y origin changed every time.

Body:
Swift 3

override func viewWillAppear(_ animated: Bool) {
    self.edgesForExtendedLayout = []
}


来源: stackexchange

问:
Count unique values based on criteria given in another column
I have a list of machines with respective batches and part number being manufactured.

I need a unique count of a batches running in a machine. This long list is updated daily. I have attached an example here.

I have this rough code.

```<code>last_row = ws.Cells(Rows.Count,1).End(xlUp).Row
For Each M_cCell in M_cRange
    Counter = 0
    For i = 2 to last_row
        If Cells(1, 1).Value = M_cCell Then
            Counter = Counter + (1/(WorksheetFunction.CountIF _
            (Range(Cells(2,2),Cells(Last_row,2),M_ccell.Value)))
        End If
    Next i
Next M_cCell
</code>```

This gives an undesired result in decimal figures.

答:
Assumptions:
a. data in columns A:C
b. the only used ranges in data sheet are columns A:C
c. results will be printed in range("E1")

the use of dictionaries would likely be one of the most efficient ways for you to remove duplicates given that you are expecting large quantities of data. Do let me know if this helps.

```<code>Sub test()
    Dim dictMachine As Object: Set dictMachine = CreateObject("scripting.dictionary")
    Dim dictBatch As Object
    Dim vTemp As Variant: vTemp = ActiveSheet.UsedRange
    Dim vTemp2 As Variant
    Dim i As Long

    For i = LBound(vTemp, 1) + 1 To UBound(vTemp, 1)
        Set dictBatch = CreateObject("scripting.dictionary")
        If dictMachine.exists(vTemp(i, 1)) Then
            dictMachine(vTemp(i, 1))(vTemp(i, 2)) = dictMachine(vTemp(i, 1))(vTemp(i, 2)) + 1
        Else
            dictBatch(vTemp(i, 2)) = dictBatch(vTemp(i, 2)) + 1
            Set dictMachine(vTemp(i, 1)) = dictBatch
        End If
    Next i

    vTemp = dictMachine.Keys
    ReDim vTemp2(0 To UBound(vTemp, 1) + 1, 0 To 1)
    vTemp2(0, 0) = "Machine"
    vTemp2(0, 1) = "Number of Batches"
    For i = LBound(vTemp, 1) To UBound(vTemp, 1)
        vTemp2(i + 1, 0) = vTemp(i)
        vTemp2(i + 1, 1) = dictMachine(vTemp(i)).Count
    Next i

    ActiveSheet.Range("E1").Resize(UBound(vTemp2, 1) - LBound(vTemp2, 1) + 1, UBound(vTemp2, 2) - LBound(vTemp2, 2) + 1) = vTemp2

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of machines with respective batches and part number being manufactured.

I need a unique count of a batches running in a machine. This long list is updated daily. I have attached an example here.

I have this rough code.

last_row = ws.Cells(Rows.Count,1).End(xlUp).Row
For Each M_cCell in M_cRange
    Counter = 0
    For i = 2 to last_row
        If Cells(1, 1).Value = M_cCell Then
            Counter = Counter + (1/(WorksheetFunction.CountIF _
            (Range(Cells(2,2),Cells(Last_row,2),M_ccell.Value)))
        End If
    Next i
Next M_cCell

This gives an undesired result in decimal figures.

Body:
Assumptions:
a. data in columns A:C
b. the only used ranges in data sheet are columns A:C
c. results will be printed in range("E1")

the use of dictionaries would likely be one of the most efficient ways for you to remove duplicates given that you are expecting large quantities of data. Do let me know if this helps.

Sub test()
    Dim dictMachine As Object: Set dictMachine = CreateObject("scripting.dictionary")
    Dim dictBatch As Object
    Dim vTemp As Variant: vTemp = ActiveSheet.UsedRange
    Dim vTemp2 As Variant
    Dim i As Long

    For i = LBound(vTemp, 1) + 1 To UBound(vTemp, 1)
        Set dictBatch = CreateObject("scripting.dictionary")
        If dictMachine.exists(vTemp(i, 1)) Then
            dictMachine(vTemp(i, 1))(vTemp(i, 2)) = dictMachine(vTemp(i, 1))(vTemp(i, 2)) + 1
        Else
            dictBatch(vTemp(i, 2)) = dictBatch(vTemp(i, 2)) + 1
            Set dictMachine(vTemp(i, 1)) = dictBatch
        End If
    Next i

    vTemp = dictMachine.Keys
    ReDim vTemp2(0 To UBound(vTemp, 1) + 1, 0 To 1)
    vTemp2(0, 0) = "Machine"
    vTemp2(0, 1) = "Number of Batches"
    For i = LBound(vTemp, 1) To UBound(vTemp, 1)
        vTemp2(i + 1, 0) = vTemp(i)
        vTemp2(i + 1, 1) = dictMachine(vTemp(i)).Count
    Next i

    ActiveSheet.Range("E1").Resize(UBound(vTemp2, 1) - LBound(vTemp2, 1) + 1, UBound(vTemp2, 2) - LBound(vTemp2, 2) + 1) = vTemp2

End Sub

ContentLicense: CC BY-SA 3.0


问:
How to differentiate between multiple inputs with the same class inside loop using jQuery or Javascript
I am using the following jQuery to add and take away increments of 1 into an input box.

```<code>$(function(){
    $('button.quantity-increment').on('click', function(){
        var form = $(this).closest('form');
        if($(this).hasClass('quantity-left-minus')){
            form.find('input.quantity').val(parseInt(form.find('input.quantity').val()) - 1);
        } else {
            form.find('input.quantity').val(parseInt(form.find('input.quantity').val()) + 1);
        }
        $('a.add_to_cart_variable').attr('data-quantity', form.find('input.quantity').val());
        logDataQuantityAttribute();
    });

    form.find('input.quantity').on('keyup', function(){
        $('a.add_to_cart_variable').attr('data-quantity', this.value);
        logDataQuantityAttribute();
    });
});
</code>```

The form below is inside of a Wordpress loop. So when I click the plus and minus increment buttons currently it changes all of the input values.

Is there anyway to just increment the input inside the same form as the plus and minus glyphs are in?

```<code><form class="cart-num" action="index.html" method="post">
    <input type="text" name="quantity" class="form-control input-number quantity" value="1" min="1" max="100">
    <span class="input-group-btn">
        <button type="button" class="quantity-left-minus quantity-increment btn btn-number"  data-type="minus" data-field="">
          <span class="glyphicon glyphicon-minus"></span>
        </button>
    </span>
    <span class="input-group-btn">
        <button type="button" class="quantity-right-plus quantity-increment btn btn-number" data-type="plus" data-field="">
            <span class="glyphicon glyphicon-plus"></span>
        </button>
    </span>
</form>
</code>```

答:
Yes there is a way use jquery selectors, first of all

Select form of clicked glyphicon with:

```<code>$('span.glyphicon').on('click', function(){
   var form = $(this).parents('form.cart-num');
});
</code>```

Then you can do finding within form, and increment only input within this form.

```<code>$(function(){
    $('span.glyphicon').on('click', function(){
        var form = $(this).parents('form.cart-num');
        if($(this).hasClass('glyphicon-minus')){
            form.find('input#quantity').val(parseInt(form.find('input#quantity').val()) - 1);
        } else {
            form.find('input#quantity').val(parseInt(form.find('input#quantity').val()) + 1);
        }
        $('a.add_to_cart_variable').attr('data-quantity', form.find('input#quantity').val());
        logDataQuantityAttribute();
    });

    $('input#quantity').on('keyup', function(){
        $('a.add_to_cart_variable').attr('data-quantity', this.value);
        logDataQuantityAttribute();
    });
});
</code>```

Working example:

$(function(){
    $('span.glyphicon').on('click', function(){
        var form = $(this).parents('form.cart-num');
        if($(this).hasClass('glyphicon-minus')){
            form.find('input').val(parseInt(form.find('input').val()) - 1);
        } else {
            form.find('input').val(parseInt(form.find('input').val()) + 1);
        }
        //$('a.add_to_cart_variable').attr('data-quantity', form.find('input').val());
        //logDataQuantityAttribute();
    });

    $('input#quantity').on('keyup', function(){
        //$('a.add_to_cart_variable').attr('data-quantity', this.value);
        logDataQuantityAttribute();
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button { padding: 0px; border: none; background: transparent; }</code>```

<form class="cart-num" action="index.html" method="post">
            <input type="text" id="quantity" name="quantity" class="form-control input-number" value="1" min="1" max="100">

        <button type="button" class="quantity-left-minus btn btn-number"  data-type="minus" data-field="">
          -
        </button>

        <button type="button" class="quantity-right-plus btn btn-number" data-type="plus" data-field="">
            +
        </button>

</form>
<form class="cart-num" action="index.html" method="post">
            <input type="text" id="quantity" name="quantity" class="form-control input-number" value="1" min="1" max="100">

        <button type="button" class="quantity-left-minus btn btn-number"  data-type="minus" data-field="">
          -
        </button>

        <button type="button" class="quantity-right-plus btn btn-number" data-type="plus" data-field="">
            +
        </button>

</form>```

Body:
I am using the following jQuery to add and take away increments of 1 into an input box.

$(function(){
    $('button.quantity-increment').on('click', function(){
        var form = $(this).closest('form');
        if($(this).hasClass('quantity-left-minus')){
            form.find('input.quantity').val(parseInt(form.find('input.quantity').val()) - 1);
        } else {
            form.find('input.quantity').val(parseInt(form.find('input.quantity').val()) + 1);
        }
        $('a.add_to_cart_variable').attr('data-quantity', form.find('input.quantity').val());
        logDataQuantityAttribute();
    });

    form.find('input.quantity').on('keyup', function(){
        $('a.add_to_cart_variable').attr('data-quantity', this.value);
        logDataQuantityAttribute();
    });
});

The form below is inside of a Wordpress loop. So when I click the plus and minus increment buttons currently it changes all of the input values.

Is there anyway to just increment the input inside the same form as the plus and minus glyphs are in?

<form class="cart-num" action="index.html" method="post">
    <input type="text" name="quantity" class="form-control input-number quantity" value="1" min="1" max="100">

        <button type="button" class="quantity-left-minus quantity-increment btn btn-number"  data-type="minus" data-field="">

        </button>

        <button type="button" class="quantity-right-plus quantity-increment btn btn-number" data-type="plus" data-field="">

        </button>

</form>

Body:
Yes there is a way use jquery selectors, first of all

Select form of clicked glyphicon with:

$('span.glyphicon').on('click', function(){
   var form = $(this).parents('form.cart-num');
});

Then you can do finding within form, and increment only input within this form.

$(function(){
    $('span.glyphicon').on('click', function(){
        var form = $(this).parents('form.cart-num');
        if($(this).hasClass('glyphicon-minus')){
            form.find('input#quantity').val(parseInt(form.find('input#quantity').val()) - 1);
        } else {
            form.find('input#quantity').val(parseInt(form.find('input#quantity').val()) + 1);
        }
        $('a.add_to_cart_variable').attr('data-quantity', form.find('input#quantity').val());
        logDataQuantityAttribute();
    });

    $('input#quantity').on('keyup', function(){
        $('a.add_to_cart_variable').attr('data-quantity', this.value);
        logDataQuantityAttribute();
    });
});

Working example:

$(function(){
    $('span.glyphicon').on('click', function(){
        var form = $(this).parents('form.cart-num');
        if($(this).hasClass('glyphicon-minus')){
            form.find('input').val(parseInt(form.find('input').val()) - 1);
        } else {
            form.find('input').val(parseInt(form.find('input').val()) + 1);
        }
        //$('a.add_to_cart_variable').attr('data-quantity', form.find('input').val());
        //logDataQuantityAttribute();
    });

    $('input#quantity').on('keyup', function(){
        //$('a.add_to_cart_variable').attr('data-quantity', this.value);
        logDataQuantityAttribute();
    });
});

button { padding: 0px; border: none; background: transparent; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="cart-num" action="index.html" method="post">
            <input type="text" id="quantity" name="quantity" class="form-control input-number" value="1" min="1" max="100">
    <span class="input-group-btn">
        <button type="button" class="quantity-left-minus btn btn-number"  data-type="minus" data-field="">
          <span class="glyphicon glyphicon-minus">-</span>
        </button>
    </span>
    <span class="input-group-btn">
        <button type="button" class="quantity-right-plus btn btn-number" data-type="plus" data-field="">
            <span class="glyphicon glyphicon-plus">+</span>
        </button>
    </span>
</form>
<form class="cart-num" action="index.html" method="post">
            <input type="text" id="quantity" name="quantity" class="form-control input-number" value="1" min="1" max="100">
    <span class="input-group-btn">
        <button type="button" class="quantity-left-minus btn btn-number"  data-type="minus" data-field="">
          <span class="glyphicon glyphicon-minus">-</span>
        </button>
    </span>
    <span class="input-group-btn">
        <button type="button" class="quantity-right-plus btn btn-number" data-type="plus" data-field="">
            <span class="glyphicon glyphicon-plus">+</span>
        </button>
    </span>
</form>


问:
How to fix textContent as undefined inside of for loop?
When i run the code below, it says "Cannot read property 'textContent' of undefined". Even onclick, addEventListener, length and much more says undefined! How can i fix this?

Here's the code:

```<code><div id = "dropdown-content" class = "d-con">
    <a href = "#">America</a>
    <a href = "#">Canada</a>
    <a href = "#">Rio</a>
</div>
</code>```

And The javaScript:

```<code>(function(){
    var i;
    var dropdown = document.getElementsByClassName('d-con');
    for(i = 0; i <= dropdown.length; i = i + 1){
        alert(dropdown[i].textContent);
    }
}());
</code>```

答: If div with id dropdown-content is the only element that contains class d-con, then grab the element by using getElementById or you can simply alert the content without using any loop by writing alert(dropdown[0].textContent);

Body:
When i run the code below, it says "Cannot read property 'textContent' of undefined". Even onclick, addEventListener, length and much more says undefined! How can i fix this?

Here's the code:

    America
    Canada
    Rio

And The javaScript:

(function(){
    var i;
    var dropdown = document.getElementsByClassName('d-con');
    for(i = 0; i <= dropdown.length; i = i + 1){
        alert(dropdown[i].textContent);
    }
}());


问:
jq split array into two arrays
I am new to jq and still trying to learn the basics of JSON, so please, excuse my lack of knowledge.
I find the tool amazingly fast, but I am struggling to get the results I need. I am sure it's possible as I've made it once by accident :(
I have input data, such as

```<code>[
  {"time":1499150456,"data":{"power":{"bus":3.88,"shunt":6.98,"load":3.89,"current":76.00},"light":{"light":21}}},
  {"time":1499150516,"data":{"power":{"bus":3.93,"shunt":1.67,"load":3.93,"current":16.20},"light":{"light":21}}},
  {"time":1499150576,"data":{"power":{"bus":3.92,"shunt":5.58,"load":3.93,"current":25.30},"light":{"light":21}}},
  {}
]
</code>```

I want to extract it into something like

```<code>  [
   1499150456,
   1499150516,
   1499150576
  ]
  [
   76.00,
   16.20,
   25.30
  ]
</code>```

What I used so far was:

```<code>cat inputFile.json | jq -C '.[] | select (length > 0)'
</code>```

which outputs nice initial array without the last empty record.
Next, I am able to do

```<code>cat inputFile.json | jq -C '.[] | select (length > 0) | .time, .data.power.current'
</code>```

The result is very close, but not exactly what I need.
I wanted to use map(.time) that I found in some example, but that resulted in an error - not sure how to use it and the examples did not work for me so far.

答:
first of all you can create a new json object. Before creting operation you should collect data in new array like this;</p>

```<code>var timeData=[];
var currentData=[];
var mergedJsonData={};

var yourJsonDataLenght= JSON.yourJsonData.length;

for (infoIndex = 0; infoIndex < yourJsonDataLenght; infoIndex++) {

    timeData.push(JSON.yourJsonData.time[infoIndex]);
    currentData.push(JSON.yourJsonData.time[infoIndex].power.current);
}

mergedJsonData.push(timeData);
mergedJsonData.push(currentData);
</code>```

Title: jq split array into two arrays

Body:
I am new to jq and still trying to learn the basics of JSON, so please, excuse my lack of knowledge.
I find the tool amazingly fast, but I am struggling to get the results I need. I am sure it's possible as I've made it once by accident :(
I have input data, such as

[
  {"time":1499150456,"data":{"power":{"bus":3.88,"shunt":6.98,"load":3.89,"current":76.00},"light":{"light":21}}},
  {"time":1499150516,"data":{"power":{"bus":3.93,"shunt":1.67,"load":3.93,"current":16.20},"light":{"light":21}}},
  {"time":1499150576,"data":{"power":{"bus":3.92,"shunt":5.58,"load":3.93,"current":25.30},"light":{"light":21}}},
  {}
]

I want to extract it into something like

  [
   1499150456,
   1499150516,
   1499150576
  ]
  [
   76.00,
   16.20,
   25.30
  ]

What I used so far was:

cat inputFile.json | jq -C '.[] | select (length > 0)'

which outputs nice initial array without the last empty record.
Next, I am able to do

cat inputFile.json | jq -C '.[] | select (length > 0) | .time, .data.power.current'

The result is very close, but not exactly what I need.
I wanted to use map(.time) that I found in some example, but that resulted in an error - not sure how to use it and the examples did not work for me so far.

Body:
first of all you can create a new json object. Before creting operation you should collect data in new array like this;

var timeData=[];
var currentData=[];
var mergedJsonData={};

var yourJsonDataLenght= JSON.yourJsonData.length;

for (infoIndex = 0; infoIndex < yourJsonDataLenght; infoIndex++) {

    timeData.push(JSON.yourJsonData.time[infoIndex]);
    currentData.push(JSON.yourJsonData.time[infoIndex].power.current);
}

mergedJsonData.push(timeData);
mergedJsonData.push(currentData);


问:
Interop issue in .NET
I have a 32 bit managed assembly that access a 32 bit COM component. When i compile the assembly using the 64 bit flag, i get an error when i try to access the 32 bit COM component from it.

Is there a way around this problem?

答:
When you use the 64 bit flag and run on a 64bit OS, the assembly will load into a 64 bit process.  The vast majority of COM objects are created as "In Proc Servers."

The first step in creating an "in proc server" is to load the DLL containing the COM object into the process doing the creation.  The DLL is 32 bit and cannot be loaded into the process.

You're unfortunately stuck with 2 options

Explicitly compile the .Net EXE for 32 bit

Write the component so that it can be hosted in it's own process.  Even then I'm not sure how easy it will be to get the 32bit and 64bit process to talk with each other.

OwnerDisplayName: Nick

ContentLicense: CC BY-SA 2.5

Title: Interop issue in .NET

OwnerDisplayName: JaredPar


问:
Manually telling my ListBox's scrollbar where to be
```<code>private void button2_Click(object sender, EventArgs e)
{
    listBox1.AutoScrollOffset.Y = 10;
}
</code>```

I'm trying to manually set the location of my vertical scrollbar using code during runtime. This is what I've tried.

The .Y property says: "Gets or sets the Y coordinate of this point". Why doesn't this compile and give me an exception:

Error 1   Cannot modify the return value
  of
  'System.Windows.Forms.Control.AutoScrollOffset'
  because it is not a variable

答:
It is a struct, so you need to set a new Point into the property instead of accessing struct members.

Because struct types are immutable, accessing them via a property introduces an oft-unknown quirk of its design.  You call the get of the property by doing listBox1.AutoScrollOffset, this gives you a copy.  You then set into the copy the new value of Y, not the property itself.  Thus when you go and review the value of the struct you thought you were editing, you find it hasn't changed.

As for controlling the scroll, I just found this:

http://moiashvin-tech.blogspot.com/2008/04/scroll-listbox-programmatically.html

Doesn't control it via coordinates, but via the items in the list.

OwnerDisplayName: delete

Body:
private void button2_Click(object sender, EventArgs e)
{
    listBox1.AutoScrollOffset.Y = 10;
}

I'm trying to manually set the location of my vertical scrollbar using code during runtime. This is what I've tried.

The .Y property says: "Gets or sets the Y coordinate of this point". Why doesn't this compile and give me an exception:

Error 1   Cannot modify the return value
  of
  'System.Windows.Forms.Control.AutoScrollOffset'
  because it is not a variable


问:
getting the url as WebDriver instead of www.google.com
While performing the code the Test is getting failed as it is taking the actualtitle as webdriver

it has been made by using iedriver
a comparision is made to the base url and current url .

```<code>package newproject;
import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;

public class Test1 {

    `public static void main(String[] args`) {

     // declaration and instantiation of objects/variables

     String exePath = "D:\\IEDriverServer_x64_3.4.0\\IEDriverServer.exe";
     InternetExplorerDriverService.Builder serviceBuilder = new
     InternetExplorerDriverService.Builder();

     serviceBuilder.usingAnyFreePort(); // This specifies that sever can pick any available free port to start

     serviceBuilder.usingDriverExecutable(new File(exePath));
     //Tell it where you server exe is

   serviceBuilder.withLogLevel(InternetExplorerDriverLogLevel.TRACE);//Specifies the log level of the server
     serviceBuilder.withLogFile(new File("D:\\abc\\Documents\\logFile.txt")); //Specify the log file. Change it based on your system

     InternetExplorerDriverService service = serviceBuilder.build();

     //Create a driver service and pass it to Internet explorer driver instance

    InternetExplorerDriver driver = new InternetExplorerDriver(service);

    String baseUrl = "http://www.google.com";
    StringBuffer expectedTitle = new StringBuffer("web driver");
    String actualTitle = "";
    driver.get("http://www.google.com");// get the actual value of the title
    actualTitle = driver.getTitle();
    System.out.println(actualTitle);

    /*compare the actual title of the page with the expected one and prin the result as "Passed" or "Failed"*/

     if (actualTitle.equalsIgnoreCase(baseUrl) )
                    {
                        System.out.println("Test Passed!");
           } else {
                        System.out.println("Test Failed");
           }

     // exit the program explicitly
                System.exit(0);
   }
</code>```

How to get the page url instead of WebDriver??

答:
I have just verified your code. It is taking the actual title as "Google" not webdriver.

This line is incorrect:

```<code>if (actualTitle.equalsIgnoreCase(baseUrl) ) {
    System.out.println("Test Passed!");
} else {
    System.out.println("Test Failed");
}
</code>```

You shouldn't compare title with the base URL. A comparison should be between expected title and actual title.

Body:
While performing the code the Test is getting failed as it is taking the actualtitle as webdriver

it has been made by using iedriver
a comparision is made to the base url and current url .

package newproject;
import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;

public class Test1 {

    `public static void main(String[] args`) {

     // declaration and instantiation of objects/variables

     String exePath = "D:\\IEDriverServer_x64_3.4.0\\IEDriverServer.exe";
     InternetExplorerDriverService.Builder serviceBuilder = new
     InternetExplorerDriverService.Builder();

     serviceBuilder.usingAnyFreePort(); // This specifies that sever can pick any available free port to start

     serviceBuilder.usingDriverExecutable(new File(exePath));
     //Tell it where you server exe is

   serviceBuilder.withLogLevel(InternetExplorerDriverLogLevel.TRACE);//Specifies the log level of the server
     serviceBuilder.withLogFile(new File("D:\\abc\\Documents\\logFile.txt")); //Specify the log file. Change it based on your system

     InternetExplorerDriverService service = serviceBuilder.build();

     //Create a driver service and pass it to Internet explorer driver instance

    InternetExplorerDriver driver = new InternetExplorerDriver(service);

    String baseUrl = "http://www.google.com";
    StringBuffer expectedTitle = new StringBuffer("web driver");
    String actualTitle = "";
    driver.get("http://www.google.com");// get the actual value of the title
    actualTitle = driver.getTitle();
    System.out.println(actualTitle);

    /*compare the actual title of the page with the expected one and prin the result as "Passed" or "Failed"*/

     if (actualTitle.equalsIgnoreCase(baseUrl) )
                    {
                        System.out.println("Test Passed!");
           } else {
                        System.out.println("Test Failed");
           }

     // exit the program explicitly
                System.exit(0);
   }

How to get the page url instead of WebDriver??

Body:
I have just verified your code. It is taking the actual title as "Google" not webdriver.

This line is incorrect:

if (actualTitle.equalsIgnoreCase(baseUrl) ) {
    System.out.println("Test Passed!");
} else {
    System.out.println("Test Failed");
}

You shouldn't compare title with the base URL. A comparison should be between expected title and actual title.


问:
Backbone, multi-language and root
I'm using backbone to manage my routing. I need to implement multi-language on my website as following :

in french : www.example.com

in english : www.example.com/en

Moreover I have an additional root on my url on production, so it gives www.example.com/dev or www.example.com/dev/en

The root is provided through my web server (node). It's retrieved through the <%- prefix %> variable in the example below.

It works well on localhost, but as soon as I pass on my server with a url with the additional root, the pages are not found. I'm looking for a generic solution to manage both situations (with or without root).

```<code><!DOCTYPE html>
<html>
<head>
...
</head>
<body>

<script type="text/javascript">

window.onload = function()
{
    let prefix = '<%- prefix %>'.substr(1);

    var BaseRouter = Backbone.Router.extend({
        routes: {

            [prefix + 'imgfocus/:imgid'] : 'imgfocus',
            [prefix + 'skymap/:obsids'] : 'skymap',
            // ...
            },

        imgfocus : function(imgid)
        {
            navservice.loadScreen({page : 'imgfocus', imgid : imgid});
        },
        skymap : function(obsids, stateid, tourid)
        {
            navservice.loadScreen({page : 'skymap', obsids : parseInt(obsids) === 0 ? undefined : obsids, stateid : stateid, tourid : tourid});
        },
        /// ...
    });

    let br = new BaseRouter();

    for (let i = 0; i < navservice.languages.length; i++)
        {
            if (navservice.languages[i] !== '')
            {
                for (let key in br.routes)
                {
                    br.routes[navservice.formatUrl(key, navservice.languages[i]).substr(1)] = br.routes[key];
                }
            }
        }
        // language retrieval
        var language = navservice.getUserLanguage();

        Backbone.history.start({pushState : true, root: '/' + (language ? language : '')});
    }

    $(document).on("click", "a:not([data-bypass])", function (evt) {
        var href = { prop: $(this).prop("href"), attr: $(this).attr("href") };
        var root = location.protocol + "//" + location.host + Backbone.history.options.root;
        if (href.prop && href.prop.slice(0, root.length) === root) {
            evt.preventDefault();
            var route = href.attr;

            // language retrieval
            var lang = navservice.getUserLanguage(route);

            if(lang && route.slice(0,lang.length+1) === "/" + lang) {
                route = route.slice(lang.length+1);
            }

            Backbone.history.navigate(route, {trigger : true});
        }
    });
}

</script>
</code>```

答:
Actually I managed to fix it by adding log inside backbone.js and checking what was going on.

The real issue was in the usage of 'prefix' variable in the routes definition. I removed it and most of the fix was done.

Title: Backbone, multi-language and root

Body:
I'm using backbone to manage my routing. I need to implement multi-language on my website as following :

in french : www.example.com

in english : www.example.com/en

Moreover I have an additional root on my url on production, so it gives www.example.com/dev or www.example.com/dev/en

The root is provided through my web server (node). It's retrieved through the <%- prefix %> variable in the example below.

It works well on localhost, but as soon as I pass on my server with a url with the additional root, the pages are not found. I'm looking for a generic solution to manage both situations (with or without root).

<!DOCTYPE html>

...


问:
Triangle Mesh, unable to add object to scene in JavaFX
I'm working on importing a 3D model (obj file) and using JavaFX triangle mesh to add it to the scene.

first, I read the obj file, parse it and save its content to (float array "Vertices", and integer array for "Faces". My mesh points :[0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0], and mesh faces : [1, 0, 7, 0, 5, 0, 1, 0, 3, 0, 7, 0, 1, 0, 4, 0, 3, 0,........]

and then I add it to my scene

```<code>    MeshView cubeMesh = new MeshView(mesh);
    cubeMesh.setDrawMode(DrawMode.FILL);
    cubeMesh.setTranslateX(20);
    cubeMesh.setTranslateY(10);
    cubeMesh.setTranslateZ(20);

    displayPane.getChildren().add(cubeMesh);
</code>```

Unfortunately, nothing is added to the scene. Would anybody be able to suggest a solution, tutorial or a book?

答: Here is an initial tutorial directly from Oracle: https://docs.oracle.com/javase/8/javafx/graphics-tutorial/javafx-3d-graphics.htm</p>

Body:
I'm working on importing a 3D model (obj file) and using JavaFX triangle mesh to add it to the scene.

first, I read the obj file, parse it and save its content to (float array "Vertices", and integer array for "Faces". My mesh points :[0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0], and mesh faces : [1, 0, 7, 0, 5, 0, 1, 0, 3, 0, 7, 0, 1, 0, 4, 0, 3, 0,........]

and then I add it to my scene

    MeshView cubeMesh = new MeshView(mesh);
    cubeMesh.setDrawMode(DrawMode.FILL);
    cubeMesh.setTranslateX(20);
    cubeMesh.setTranslateY(10);
    cubeMesh.setTranslateZ(20);

    displayPane.getChildren().add(cubeMesh);

Unfortunately, nothing is added to the scene. Would anybody be able to suggest a solution, tutorial or a book?


问:
Different parameters value in .ini file for different runs
How can I have different parameters value defined in .ini file for each repeat in omnet using cmdenv? I have repeat value as 4 and trying to have different value of accidentStart and accidentDuration.

答:
You can't. And shouldn't. The whole point of repetition is that all parameters have the same value, just the RNGs are seeded differently. So you get a different sample of the same distribution for every result value.

What you're looking for are iteration variables.
Something like this:

```<code>**.accidentStart = ${100, 200, 350}s
</code>```

This will generate 3 runs without repetition, and 12 runs with repeat=4.

and if you add

```<code>**.accidentDuration = ${duration=300, 450, 600..1800 step 600}s
</code>```

this will multiply the number of runs by another factor of 5.

By default, iteration variables produce a Cartesian product of their respective assigned sets of values. But there are ways to change this, consult the manual for how.

Body:
You can't. And shouldn't. The whole point of repetition is that all parameters have the same value, just the RNGs are seeded differently. So you get a different sample of the same distribution for every result value.

What you're looking for are iteration variables.
Something like this:

**.accidentStart = ${100, 200, 350}s

This will generate 3 runs without repetition, and 12 runs with repeat=4.

and if you add

**.accidentDuration = ${duration=300, 450, 600..1800 step 600}s

this will multiply the number of runs by another factor of 5.

By default, iteration variables produce a Cartesian product of their respective assigned sets of values. But there are ways to change this, consult the manual for how.


问:
how data can be parsing in xml parsing and data show in listview in android
I have a doubt in xml parsing. How to do XML parsing in this type of example:

```<code><companies>
  <company name="ramki" symbol="ram"/>
  <company name="addidas" symbol="ads"/>
  <company name="samsang" symbol="sam"/>
  .................
</code>```

and also tell me how to show the in ListView (name and symbol also)

答:
Two parts :

for XML parsing, it's the same thing as in Java. You can see this question about XML parsing. As said in the link MGS provided, StaX is not implemented in Android, but can be easily replaced by the XMLPullParser.

As for displaying your data in a ListView, you'll juste have to use an ArrayAdapter. For more help about lists, see the associated resource in Android Help.

Body:
I have a doubt in xml parsing. How to do XML parsing in this type of example:

<companies>
  <company name="ramki" symbol="ram"/>
  <company name="addidas" symbol="ads"/>
  <company name="samsang" symbol="sam"/>
  .................

and also tell me how to show the in ListView (name and symbol also)


问:
Unable to get the
 tag with a specific text using xpath() in Selenium
I have a script which I am trying to run on Selenium environment using Mocha:

```<code>var assert = require('assert');
var test = require('selenium-webdriver/testing');
var webdriver = require('selenium-webdriver');
var By = webdriver.By;
var until = webdriver.until;
var equals = webdriver.equals;

test.describe('TrackRevenue Test', function()
{
  test.it('should work', function()
  {
        var driver = new webdriver.Builder()
                    .withCapabilities(webdriver.Capabilities.phantomjs())
                    .build();
        var loginFlag = 0;
        var baseUrl = 'http://saswatr3.ouh.co/login';
        var expectedTitle = "Track Revenue";
        var successMessage = "Welcome to the admin page!";
        driver.get(baseUrl);
        driver.getTitle().then(function(title)
        {
            if(expectedTitle === title)
            {
                console.log("Verification Successful - The correct title is displayed on the web page.");
            }
            else
            {
                console.log("Verification Failed - An incorrect title is displayed on the web page.");
            }
        });
        driver.findElement(By.id('username')).sendKeys('saswat@matrixnmedia.com');
        driver.findElement(By.id('password')).sendKeys('DarkPrince2012');
        driver.findElement(By.id('_submit')).click();
        driver.wait(until.titleIs('Track Revenue'), 1000);
        if(driver.findElements(By.xpath("//p[text()[contains(.,'Welcome to the admin page!')]]")).size() != 0)
        {

            loginFlag = 1;
        }

        if(loginFlag ==1)
                console.log("Login Successful");
            else
                console.log("Login Unsuccessful");
    driver.quit();
  });
});
</code>```

Using the following code, I am trying to check if a
 tag is present having the text "Welcome to the admin page!"

```<code>if(driver.findElements(By.xpath("//p[text()[contains(.,'Welcome to the admin page!')]]")).size() != 0)
</code>```

But I am getting the following error:

```<code>C:\xampp\htdocs\testPhantomJS\node_modules\selenium-webdriver>mocha -t 50000 testMocha\login-as-administrator-mocha.js

  TrackRevenue Test
Verification Successful - The correct title is displayed on the web page.
    1) should work

  0 passing (21s)
  1 failing

  1) TrackRevenue Test should work:
     TypeError: undefined is not a function
  From: Task: TrackRevenue Test should work
</code>```

What wrong am I doing?

Here is the HTML for the
 which I am trying to find:

```<code><div class="wrapper wrapper-content animated fadeIn">
   <div class="row">
     <div class="col-centered col-xs-12">
     <div class="ibox float-e-margins">
     <div class="ibox-title">
       <h5>Links</h5>
       <div class="ibox-tools"> </div>
     </div>
     <div class="ibox-content">
        <p>Welcome to the admin page!</p>
        <p>Please use the menu on the left</p>
     </div>
     </div>
     </div>
   </div>
</div>
</code>```

答:
Please, try this XPath:

```<code>"//*[text()[contains(., 'Welcome to the admin page!')]]"
</code>```

Ivo.

Title: Unable to get the <p> tag with a specific text using xpath() in Selenium

Body:
I have a script which I am trying to run on Selenium environment using Mocha:

var assert = require('assert');
var test = require('selenium-webdriver/testing');
var webdriver = require('selenium-webdriver');
var By = webdriver.By;
var until = webdriver.until;
var equals = webdriver.equals;

test.describe('TrackRevenue Test', function()
{
  test.it('should work', function()
  {
        var driver = new webdriver.Builder()
                    .withCapabilities(webdriver.Capabilities.phantomjs())
                    .build();
        var loginFlag = 0;
        var baseUrl = 'http://saswatr3.ouh.co/login';
        var expectedTitle = "Track Revenue";
        var successMessage = "Welcome to the admin page!";
        driver.get(baseUrl);
        driver.getTitle().then(function(title)
        {
            if(expectedTitle === title)
            {
                console.log("Verification Successful - The correct title is displayed on the web page.");
            }
            else
            {
                console.log("Verification Failed - An incorrect title is displayed on the web page.");
            }
        });
        driver.findElement(By.id('username')).sendKeys('saswat@matrixnmedia.com');
        driver.findElement(By.id('password')).sendKeys('DarkPrince2012');
        driver.findElement(By.id('_submit')).click();
        driver.wait(until.titleIs('Track Revenue'), 1000);
        if(driver.findElements(By.xpath("//p[text()[contains(.,'Welcome to the admin page!')]]")).size() != 0)
        {

            loginFlag = 1;
        }

        if(loginFlag ==1)
                console.log("Login Successful");
            else
                console.log("Login Unsuccessful");
    driver.quit();
  });
});

Using the following code, I am trying to check if a
 tag is present having the text "Welcome to the admin page!"

if(driver.findElements(By.xpath("//p[text()[contains(.,'Welcome to the admin page!')]]")).size() != 0)

But I am getting the following error:

C:\xampp\htdocs\testPhantomJS\node_modules\selenium-webdriver>mocha -t 50000 testMocha\login-as-administrator-mocha.js

  TrackRevenue Test
Verification Successful - The correct title is displayed on the web page.
    1) should work

  0 passing (21s)
  1 failing

  1) TrackRevenue Test should work:
     TypeError: undefined is not a function
  From: Task: TrackRevenue Test should work

What wrong am I doing?

Here is the HTML for the
 which I am trying to find:

Links

Welcome to the admin page!

Please use the menu on the left

Body:
Please, try this XPath:

"//*[text()[contains(., 'Welcome to the admin page!')]]"

Ivo.


问:
How to return a viewEntryCollection in random order
I have the following code

```<code>var vec:ViewEntryCollection = database.getView("view").getAllEntriesByKey("Mykey",true)
</code>```

how can I make "vec" in random order using SSJS (or java) so that I get a new order every time?

答:
Considered the average collection size I would loop through the collection and add each item to a Java list or a JavaScript array.

If you go Java you can use Collections.shuffle.

If you go JavaScript you can use well established functions/algorithms

Body:
I have the following code

var vec:ViewEntryCollection = database.getView("view").getAllEntriesByKey("Mykey",true)

how can I make "vec" in random order using SSJS (or java) so that I get a new order every time?


问:
Template match nodes that have a particular child node - streaming XSLT
I want to select the Worker nodes, that have a Plan child node coming up in Addl_Information section

```<code><xsl:mode streamable="yes"/>
<xsl:template match="Worker[Addl_Information/Plan]">
</code>```

When I use the above code, I get error from Saxon-EE 9.6.0.5 processor saying

```<code>XTSE3430: Template rule is declared streamable but it does not satisfy the streamability rules. * The match pattern is not motionless
</code>```

What am I doing wrong?

I see examples of (similar) motionless patterns in w3c site but it is not working for me, kindly advise.

Update: Here is my stylesheet. I am trying to include only the people who have a record of a certain plan in their worker data. Note, the below patth variable was another angle I was trying to evaluate - basically having an IF condition right after, around the remaining code. That also does not work.

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:mode streamable="yes"/>
        <xsl:template match="Worker_Sync">
            <File>
                <xsl:apply-templates select="Worker"/>
            </File>
        </xsl:template>

        <xsl:template match="Worker">
            <xsl:variable name="ThisPerson" select="copy-of()"/>
            <xsl:variable name="patth" select="Additional_Information/ws:plan"/>
            <xsl:if test="$ThisPerson/$patth">
                <Row>
                    <A1_Account_Number><xsl:value-of select="$ThisPerson/Additional_Information/Account_Number"/></A1_Account_Number>
                    <A2_Employee_Number>...</A2_Employee_Number>
                </Row>
            </xsl:if>
        </xsl:template>
    </xsl:stylesheet>
</code>```

答:
A template rule in a streamable mode has to have a motionless match pattern. "Motionless" in this context essentially means that you can evaluate the pattern while the parser is positioned at the element start tag. You can't do that in this case because the predicate tests for the existence of an Addl_Information child with a Plan grandchild, and you can't tell whether those exist without reading forwards beyond the start tag.

I'm happy to take a look at the stylesheet as a whole to see if I can come up with any suggestions for making it streamable, provided it's reasonably compact.

==LATER==

You can use the approach of making a copy of each Worker element when you encounter it, in this case you just need to do all subsequent access within the copied element:

```<code><xsl:variable name="ThisPerson" select="copy-of()"/>
<xsl:if test="$ThisPerson/Additional_Information/ws:plan">
    <Row>
        <A1_Account_Number><xsl:value-of select="$ThisPerson/Additional_Information/Account_Number"/>   </A1_Account_Number>
        <A2_Employee_Number>...</A2_Employee_Number>
    </Row>
</xsl:if>
</code>```

And that is probably the easiest solution. There might be ways of avoiding the copy operation (depending on the exact source document structure), but it will be more complicated, and unless the individual Worker elements are very large, it isn't worth the effort.

Body:
I want to select the Worker nodes, that have a Plan child node coming up in Addl_Information section

<xsl:mode streamable="yes"/>
<xsl:template match="Worker[Addl_Information/Plan]">

When I use the above code, I get error from Saxon-EE 9.6.0.5 processor saying

XTSE3430: Template rule is declared streamable but it does not satisfy the streamability rules. * The match pattern is not motionless

What am I doing wrong?

I see examples of (similar) motionless patterns in w3c site but it is not working for me, kindly advise.

Update: Here is my stylesheet. I am trying to include only the people who have a record of a certain plan in their worker data. Note, the below patth variable was another angle I was trying to evaluate - basically having an IF condition right after, around the remaining code. That also does not work.

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:mode streamable="yes"/>
        <xsl:template match="Worker_Sync">
            <File>
                <xsl:apply-templates select="Worker"/>
            </File>
        </xsl:template>

        <xsl:template match="Worker">
            <xsl:variable name="ThisPerson" select="copy-of()"/>
            <xsl:variable name="patth" select="Additional_Information/ws:plan"/>
            <xsl:if test="$ThisPerson/$patth">
                <Row>
                    <A1_Account_Number><xsl:value-of select="$ThisPerson/Additional_Information/Account_Number"/></A1_Account_Number>
                    <A2_Employee_Number>...</A2_Employee_Number>
                </Row>
            </xsl:if>
        </xsl:template>
    </xsl:stylesheet>

Body:
A template rule in a streamable mode has to have a motionless match pattern. "Motionless" in this context essentially means that you can evaluate the pattern while the parser is positioned at the element start tag. You can't do that in this case because the predicate tests for the existence of an Addl_Information child with a Plan grandchild, and you can't tell whether those exist without reading forwards beyond the start tag.

I'm happy to take a look at the stylesheet as a whole to see if I can come up with any suggestions for making it streamable, provided it's reasonably compact.

==LATER==

You can use the approach of making a copy of each Worker element when you encounter it, in this case you just need to do all subsequent access within the copied element:

<xsl:variable name="ThisPerson" select="copy-of()"/>
<xsl:if test="$ThisPerson/Additional_Information/ws:plan">
    <Row>
        <A1_Account_Number><xsl:value-of select="$ThisPerson/Additional_Information/Account_Number"/>   </A1_Account_Number>
        <A2_Employee_Number>...</A2_Employee_Number>
    </Row>
</xsl:if>

And that is probably the easiest solution. There might be ways of avoiding the copy operation (depending on the exact source document structure), but it will be more complicated, and unless the individual Worker elements are very large, it isn't worth the effort.


问:
Automatic decimal places in textbox
It looks very strange, but I can't find an online solution for my problem! At least in VB.NET.

Here's the deal:
I have a TextBox in a form (limited to numbers by a KeyPress event) and want to keep two decimal places as long as the user inputs his data.

For example, if the TextBox is blank, then, when the user presses, let's say, "2", the TextBox shows "0,02". Then, if the user presses "7", the TextBox shows "0,27". Then again, by pressing "6", it shows "2,76" and so on...

I managed to do this for one decimal place with the code:

```<code>    Select Case Me.TextBox.Text
        Case ""
        Case ","
            Me.TextBox.Text = ""
        Case Else
            Me.TextBox.Text = Strings.Left(Replace(Me.TextBox.Text, ",", ""), Strings.Len(Replace(Me.TextBox.Text, ",", "")) - 1) & "," & Strings.Right(Replace(Me.TextBox.Text, ",", ""), 1)
            Me.TextBox.SelectionStart = Len(Me.TextBox.Text)
    End Select
</code>```

Please note that: 1. This code's running on a TextChanged event; 2. I'm from Portugal and here we use a comma (",") instead of a dot (".") for the decimal separator.

Could you help me to adjust my piece of code to work properly with two decimal places?

Any help will be very appreciated. And, as always, thank you all in advance.

答:
Thank you @Visual Vincent. Your method works fine. However I managed to find a simpler way of doing what I asked by the following code:

```<code>Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox.KeyPress
    If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
        e.Handled = True
    End If
End Sub
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox.TextChanged
    Select Case Val(Replace(Me.TextBox.Text, ",", "."))
        Case 0 : Me.TextBox.Text = ""
        Case Else
            Me.TextBox.Text = Format(Val(Replace(Me.TextBox.Text, ",", "")) / 100, "0.00")
            Me.TextBox.SelectionStart = Len(Me.TextBox.Text)
    End Select
End Sub
</code>```

This piece of code look suspicious simple to me. For now it works fine and does the trick exactly how I wanted. Maybe there's something missing to me, or maybe I wasn't clear enough on the description of my goal.
If you find any flaw on my method, please feel free to point it! I'll appreciate it very much.

Title: Automatic decimal places in textbox

Body:
It looks very strange, but I can't find an online solution for my problem! At least in VB.NET.

Here's the deal:
I have a TextBox in a form (limited to numbers by a KeyPress event) and want to keep two decimal places as long as the user inputs his data.

For example, if the TextBox is blank, then, when the user presses, let's say, "2", the TextBox shows "0,02". Then, if the user presses "7", the TextBox shows "0,27". Then again, by pressing "6", it shows "2,76" and so on...

I managed to do this for one decimal place with the code:

    Select Case Me.TextBox.Text
        Case ""
        Case ","
            Me.TextBox.Text = ""
        Case Else
            Me.TextBox.Text = Strings.Left(Replace(Me.TextBox.Text, ",", ""), Strings.Len(Replace(Me.TextBox.Text, ",", "")) - 1) & "," & Strings.Right(Replace(Me.TextBox.Text, ",", ""), 1)
            Me.TextBox.SelectionStart = Len(Me.TextBox.Text)
    End Select

Please note that: 1. This code's running on a TextChanged event; 2. I'm from Portugal and here we use a comma (",") instead of a dot (".") for the decimal separator.

Could you help me to adjust my piece of code to work properly with two decimal places?

Any help will be very appreciated. And, as always, thank you all in advance.

Body:
Thank you @Visual Vincent. Your method works fine. However I managed to find a simpler way of doing what I asked by the following code:

Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox.KeyPress
    If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
        e.Handled = True
    End If
End Sub
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox.TextChanged
    Select Case Val(Replace(Me.TextBox.Text, ",", "."))
        Case 0 : Me.TextBox.Text = ""
        Case Else
            Me.TextBox.Text = Format(Val(Replace(Me.TextBox.Text, ",", "")) / 100, "0.00")
            Me.TextBox.SelectionStart = Len(Me.TextBox.Text)
    End Select
End Sub

This piece of code look suspicious simple to me. For now it works fine and does the trick exactly how I wanted. Maybe there's something missing to me, or maybe I wasn't clear enough on the description of my goal.
If you find any flaw on my method, please feel free to point it! I'll appreciate it very much.


问:
UI update without using Broadcast Receiver or Handler from Service in android
I know service is running on main thread so why are we using Broadcast Receiver or Handler to update UI in android. can we directly update UI without using handler or Broadcast Receiver from service in android. I am confused so please clarify on this discussion.</p>

答:
to update the UI, you need to have a reference to the view. You can't get references to the views in the service. But you can do it the Activity. That's why you have to enforce the Activity to update UI prior to doing it in the service (since service has no UI itself).

You can pass the reference to the UI into the service, but it will likely lead to memory leaks because of Activity and the Service lifecycles can be different, and you may end up with a deadlock where your Service locks the Activity from being GCed, and Activity locks the service.


问:
Angular2 authentication Services
I am trying to load local JSON data to angular console,with AuthHttp.

getData(){

```<code>   let trail = this.authHttp.get('app/_services/admin.json')
  .map(res => res.json())

  console.log('hello',trail);
  return trail;
}
</code>```

Instead of the actual JSON data, im getting below observable

Observable {_isScalar: false, source: DeferObservable, operator: MapOperator}

Please help me in solving this issue.

Thanks in advance!

答:
It is because angular2 get() method returns an observable, to get the value you must subscribe() the returned value..
So in your code it should be like:

```<code>trail.subscribe(response => {
    console.log(response);
    // the response should be json now
});
</code>```

Title: Angular2 authentication Services

Body:
I am trying to load local JSON data to angular console,with AuthHttp.

getData(){

   let trail = this.authHttp.get('app/_services/admin.json')
  .map(res => res.json())

  console.log('hello',trail);
  return trail;
}

Instead of the actual JSON data, im getting below observable

Observable {_isScalar: false, source: DeferObservable, operator: MapOperator}

Please help me in solving this issue.

Thanks in advance!

Body:
It is because angular2 get() method returns an observable, to get the value you must subscribe() the returned value..
So in your code it should be like:

trail.subscribe(response => {
    console.log(response);
    // the response should be json now
});


问:
How to edit azure storage table from azure function?
I am able to add new row in table using code below

```<code>context.bindings.sampleTable = {
"partitionKey": "11111111",
"rowKey": "222",
"deviceId": 1111,
"messageId": 2222,
"temperature": 3333,
"humidity": 4444
 };

 context.done();
</code>```

now I want to edit this new added row so I tried same code with same partitionkey and rowkey but it gives error as below

```<code>Exception while executing function: Functions.CCCJSFunc. Microsoft.Azure.WebJobs.Host: Error while handling parameter _binder after function returned:. Microsoft.WindowsAzure.Storage: The specified entity already exists.
</code>```

so please correct me.

答:
The thread How to update a Azure table row in Azure function using Bindings? addresses the same issue. Currently, if you need arbitrary updates/deletes etc, you would have to do that manually with Azure Storage SDK for Node.js.

You can check out this blog post: Updating and Deleting Table Storage Entities with Azure Functions (C# and JavaScript) for a workaround.

Body:
I am able to add new row in table using code below

context.bindings.sampleTable = {
"partitionKey": "11111111",
"rowKey": "222",
"deviceId": 1111,
"messageId": 2222,
"temperature": 3333,
"humidity": 4444
 };

 context.done();

now I want to edit this new added row so I tried same code with same partitionkey and rowkey but it gives error as below

Exception while executing function: Functions.CCCJSFunc. Microsoft.Azure.WebJobs.Host: Error while handling parameter _binder after function returned:. Microsoft.WindowsAzure.Storage: The specified entity already exists.

so please correct me.


问:
Using TypeScript 2.3 and TypeScript 2.4 on the same machine with Visual Studio 2015.3
Is it possible to use TS 2.3 and TS 2.4 on the same machine?

I.e. I have on VS 2015.3 project compiling in TS 2.3 but other compiling in latest TypeScript (TS 2.4).

I installed TypeScript 2.4 and that uninstalled TypeScript 2.3. So I'm not able to compile the TS 2.3 project without upgrading it to TS 2.4. The TS 2.3 project is currently only open for critical bugfixes and can not be upgraded to TS 2.4.

答:
You can have installer more than one TS compiler. Install 2.3 then back 2.4 as primary. Do not do uninstall any. In C:\Program Files (x86)\Microsoft SDKs\TypeScript you will have (at least) two folders (2.3 and 2.4). Make copy of both (_2.3 and _2.4). Then you can switch between them by changing folder names. Visual Studio is using the last installed version (e.g. 2.4). But when folder with name 2.4 contains 2.3 compiler it often works too. Problems are between switching soo much versions (e.g 1.8 and 2.4) because Visual Studio is often using arguments which these prehistoric versions don't know.

This is main concept of changing TypeScript compiler. You can do it handly or you can write .bat files which will make this changes and you can set up this scripts as post-build script of Visual Studio Project. Then Visual Studio will automaticaly "change" TypeScript compiler versions.

Let's write C:\set-ts-24.bat file

```<code>rmdir /S /Q "C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.4"
xcopy /E /Y "C:\Program Files (x86)\Microsoft SDKs\TypeScript\_2.4" "C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.4\"
</code>```

and C:\set-ts-23.bat

```<code>rmdir /S /Q "C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.4"
xcopy /E /Y "C:\Program Files (x86)\Microsoft SDKs\TypeScript\_2.3" "C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.4\"
</code>```

Now set post-build command in Visual Studio Project file. In Solution Explorer right click on Project File (not a Solution) then Unload Project.

When project is unloaded you edit jsproj file. Right click project file again. Then press Edit yourporjectname.jsproj

Xml File will be opened. Add PrropertyGroup element at end of XML document before last closign  tag. In PostBuildEvent set path to set-ts-24.bat or set-ts-23.bat script.

```<code>...
  <PropertyGroup>
    <PostBuildEvent>"C:\set-ts-24.bat"</PostBuildEvent>
  </PropertyGroup>
</Project>
</code>```

Then save project file, close project file, right click on project and Reload project

Body:
You can have installer more than one TS compiler. Install 2.3 then back 2.4 as primary. Do not do uninstall any. In C:\Program Files (x86)\Microsoft SDKs\TypeScript you will have (at least) two folders (2.3 and 2.4). Make copy of both (_2.3 and _2.4). Then you can switch between them by changing folder names. Visual Studio is using the last installed version (e.g. 2.4). But when folder with name 2.4 contains 2.3 compiler it often works too. Problems are between switching soo much versions (e.g 1.8 and 2.4) because Visual Studio is often using arguments which these prehistoric versions don't know.

This is main concept of changing TypeScript compiler. You can do it handly or you can write .bat files which will make this changes and you can set up this scripts as post-build script of Visual Studio Project. Then Visual Studio will automaticaly "change" TypeScript compiler versions.

Let's write C:\set-ts-24.bat file

rmdir /S /Q "C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.4"
xcopy /E /Y "C:\Program Files (x86)\Microsoft SDKs\TypeScript\_2.4" "C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.4\"

and C:\set-ts-23.bat

rmdir /S /Q "C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.4"
xcopy /E /Y "C:\Program Files (x86)\Microsoft SDKs\TypeScript\_2.3" "C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.4\"

Now set post-build command in Visual Studio Project file. In Solution Explorer right click on Project File (not a Solution) then Unload Project.

When project is unloaded you edit jsproj file. Right click project file again. Then press Edit yourporjectname.jsproj

Xml File will be opened. Add PrropertyGroup element at end of XML document before last closign  tag. In PostBuildEvent set path to set-ts-24.bat or set-ts-23.bat script.

...
  <PropertyGroup>
    <PostBuildEvent>"C:\set-ts-24.bat"</PostBuildEvent>
  </PropertyGroup>
</Project>

Then save project file, close project file, right click on project and Reload project


问:
Access Application using same ip within office network
I've deployed one application developed using Java-Struts on one of my client's office. Application is web-based - So we hosted it on one the machine available in client's office - using static ip. The application runs fine(well I had couple of issues to deal with honestly). But when we were testing the application within client's environment - we came across odd issue.

If client needs to access the application inside their network - they need to use local ip address, something like this -
http://192.168.1.12:8080/CTS

Outside the network - they need to use following url -
http://99.99.999.999:8080/CTS

How I can make sure client does not have to use 2 different urls to access this application?
I went through few forums and got to know about host mapping and NAT forwarding, etc. I'm not a networking expert, So I really need some guidance of how to achieve this with right method.
Thank you very much in advance.

答: For security reason the intranet IP(http://192.168.1.12:8080/CTS) is not exposed publicly.Have to check with the network team of Client whether the IP is publicly exposed if not then map local IP with domain/Static IP and that should be exposed publicly.If it is publicly exposed then within the network too the client can access intranet IP/domain.</p>


问:
Populate a column in SQL Server by weekday or weekend depending on the datetime
I am working on SQL Server, wherein I cannot update any existing column nor can I add any more data/ column to the data.

I have a column of dttime (yyyy-mm-dd hh:mm:ss) which consists of the date time value against each entry.
I want to select the existing columns , and a new column as wd which will be populated as 'weekend' when the day of the week is either Saturday or Sunday and 'weekday' in case of other days

I am using the below query:

```<code>SELECT id, total,
case when dayofweek(dttime) in (1,7) then 'Weekend' else 'Weekday' end as wd
from table_name
</code>```

Please suggest where is the mistake here, or is there any alternative to this, in case I have more than two different things to populate in a similar way, based on another column.

答:
You can use DATENAME of dw or weekday to achieve your expectation:

```<code>SELECT id, total,
       CASE WHEN DATENAME (dw, dttime) IN ('Saturday', 'Sunday') THEN 'Weekend'
       ELSE 'Weekday' END AS wd
FROM table_name
</code>```

Also your first day of the week can be set by the SET DATEFIRST, so based on the DATEFIRST set value the integer value for Sunday and Saturday can change. So getting DATENAME for the dttime will not cause any confusion.

You can execute the below query to understand more in detail, DATENAME will always return the current day name, but DATEPART will return based on the DATEFIRST.

```<code>SELECT @@DATEFIRST AS 'First Day',
       DATEPART(dw, GETDATE()) AS 'Today',
       DATENAME(dw, GETDATE()) AS 'TodayName';
</code>```

If SELECT @@DATEFIRST returns 7, then you can use

```<code>CASE WHEN DATEPART(dw, dttime) IN (1, 7) THEN 'Weekend' ELSE 'Weekday' END AS wd
</code>```

Here 1 for Sunday and 7 for Saturday.

Body:
I am working on SQL Server, wherein I cannot update any existing column nor can I add any more data/ column to the data.

I have a column of dttime (yyyy-mm-dd hh:mm:ss) which consists of the date time value against each entry.
I want to select the existing columns , and a new column as wd which will be populated as 'weekend' when the day of the week is either Saturday or Sunday and 'weekday' in case of other days

I am using the below query:

SELECT id, total,
case when dayofweek(dttime) in (1,7) then 'Weekend' else 'Weekday' end as wd
from table_name

Please suggest where is the mistake here, or is there any alternative to this, in case I have more than two different things to populate in a similar way, based on another column.

Body:
You can use DATENAME of dw or weekday to achieve your expectation:

SELECT id, total,
       CASE WHEN DATENAME (dw, dttime) IN ('Saturday', 'Sunday') THEN 'Weekend'
       ELSE 'Weekday' END AS wd
FROM table_name

Also your first day of the week can be set by the SET DATEFIRST, so based on the DATEFIRST set value the integer value for Sunday and Saturday can change. So getting DATENAME for the dttime will not cause any confusion.

You can execute the below query to understand more in detail, DATENAME will always return the current day name, but DATEPART will return based on the DATEFIRST.

SELECT @@DATEFIRST AS 'First Day',
       DATEPART(dw, GETDATE()) AS 'Today',
       DATENAME(dw, GETDATE()) AS 'TodayName';

If SELECT @@DATEFIRST returns 7, then you can use

CASE WHEN DATEPART(dw, dttime) IN (1, 7) THEN 'Weekend' ELSE 'Weekday' END AS wd

Here 1 for Sunday and 7 for Saturday.


问:
How can I write sequential execution in foreach loop of nodejs?
I am new to nodejs. please help me how to save the data in foreach loop and send response back to controller.it returns false not return object. Thanks in advance

Here is my code like

```<code>var rideStatus = require('../models/ridestatus');
module.exports = {
  invite_ride: function* (body) {
    var saved = false;
    var receivers = body.uids;
    receivers = receivers.split(',').filter(function(n) { return n != 'null'; });
    receivers.forEach(function* (n) {
      yield rideStatus.findOne(
        {$and: [{ride_id: body.rideid}, {receiver_id: receivers}]},
        function(err, doc) {
          if (doc === null) {
            new rideStatus({
              ride_id: body.rideid,
              invited_id: body.userId,
              receiver_id: receivers,
            }).save(function(err1, ridestatus) {
              if (!err1) {
                rideStatus.findOne({_id: ridestatus._id}).
                  populate('ride_id').
                  populate('invited_id').
                  populate('receiver_id').
                  exec(function(err2, user) {
                    // console.log(user);
                    if (user != null) {
                      saved = user;

                    }
                  });
              }
            });
          }
        });
    });
    return saved;
  },
};
</code>```

答:
because of the asynchronous nature of node.js your "return save" statement won't wait for your i/o to complete his work. and also note that if you have multiple values to be saved, you should return an array of saved Users objects.</p>

```<code>var rideStatus = require('../models/ridestatus');
module.exports = {
    invite_ride: function* (body) {
        var savedUsers = [];
        var receivers = body.uids;
        receivers = receivers.split(',').filter(function(n) { return n != 'null'; });
        var len = receivers.length
        var i=0
        receivers.forEach(function* (n) {
            yield rideStatus.findOne(
                {$and: [{ride_id: body.rideid}, {receiver_id: receivers}]},
                function(err, doc) {
                    if (doc === null) {
                        new rideStatus({
                            ride_id: body.rideid,
                            invited_id: body.userId,
                            receiver_id: receivers,
                        }).save(function(err1, ridestatus) {
                            if (!err1) {
                                rideStatus.findOne({_id: ridestatus._id}).
                                    populate('ride_id').
                                    populate('invited_id').
                                    populate('receiver_id').
                                    exec(function(err2, user) {
                                        // console.log(user);
                                        if (user != null) {
                                            savedUsers.push(user);
                                        }
                                        if(i==len-1)
                                            return savedUsers;
                                        else
                                            i++
                                    });
                            }else{
                                i++
                            }
                        });
                    }else{
                        i++
                    }
            });
        });
    },
};
</code>```

Body:
I am new to nodejs. please help me how to save the data in foreach loop and send response back to controller.it returns false not return object. Thanks in advance

Here is my code like

var rideStatus = require('../models/ridestatus');
module.exports = {
  invite_ride: function* (body) {
    var saved = false;
    var receivers = body.uids;
    receivers = receivers.split(',').filter(function(n) { return n != 'null'; });
    receivers.forEach(function* (n) {
      yield rideStatus.findOne(
        {$and: [{ride_id: body.rideid}, {receiver_id: receivers}]},
        function(err, doc) {
          if (doc === null) {
            new rideStatus({
              ride_id: body.rideid,
              invited_id: body.userId,
              receiver_id: receivers,
            }).save(function(err1, ridestatus) {
              if (!err1) {
                rideStatus.findOne({_id: ridestatus._id}).
                  populate('ride_id').
                  populate('invited_id').
                  populate('receiver_id').
                  exec(function(err2, user) {
                    // console.log(user);
                    if (user != null) {
                      saved = user;

                    }
                  });
              }
            });
          }
        });
    });
    return saved;
  },
};

Body:
because of the asynchronous nature of node.js your "return save" statement won't wait for your i/o to complete his work. and also note that if you have multiple values to be saved, you should return an array of saved Users objects.

var rideStatus = require('../models/ridestatus');
module.exports = {
    invite_ride: function* (body) {
        var savedUsers = [];
        var receivers = body.uids;
        receivers = receivers.split(',').filter(function(n) { return n != 'null'; });
        var len = receivers.length
        var i=0
        receivers.forEach(function* (n) {
            yield rideStatus.findOne(
                {$and: [{ride_id: body.rideid}, {receiver_id: receivers}]},
                function(err, doc) {
                    if (doc === null) {
                        new rideStatus({
                            ride_id: body.rideid,
                            invited_id: body.userId,
                            receiver_id: receivers,
                        }).save(function(err1, ridestatus) {
                            if (!err1) {
                                rideStatus.findOne({_id: ridestatus._id}).
                                    populate('ride_id').
                                    populate('invited_id').
                                    populate('receiver_id').
                                    exec(function(err2, user) {
                                        // console.log(user);
                                        if (user != null) {
                                            savedUsers.push(user);
                                        }
                                        if(i==len-1)
                                            return savedUsers;
                                        else
                                            i++
                                    });
                            }else{
                                i++
                            }
                        });
                    }else{
                        i++
                    }
            });
        });
    },
};


问:
xml:lang attribute for  tag effects SEO?
I have a concern regarding xml:lang attribute for  tag.

Is really needed to boost SEO?

I am changing my  tag to

Google looks for this declaration when interpreting organic search results?

答:
Specifying your content language always helps, but there's no point specifying xml:lang when you already have lang, since you're not writing XHTML.

So no, xml:lang is not needed.

Title: xml:lang attribute for <html> tag effects SEO?


问:
onclick not working with selectpicker multiselect dropdown
I have a selectpicker multiselect dropdown. I'm not able to invoke 'onclick' when I select any option. But this works with the normal html multiple dropdown. How to make it work with selectpicker?

Here's the code:

```<code> <!DOCTYPE html>
   <html>
     <head>
       <meta charset="utf-8">
       <meta name="viewport" content="width=device-width, initial-scale=1">

       <link rel="stylesheet"
       href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-
       select/1.6.3/css/bootstrap-select.min.css" />
       <link rel="stylesheet" href="https:
       //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
       <script
         src=
         "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
       </script>
       <script
         src=
       "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
 >
       </script>
       <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-
         select/1.6.3/js/bootstrap-select.min.js"></script>
     </head>
     <body>

       <form action="/action_page.php">
         <select class="selectpicker" name="cars"  multiple>
         <option value="volvo" onclick="myFunction(this)">Volvo</option>
         <option value="bmw" onclick="myFunction(this)">Bmw</option>
         <option value="opel" onclick="myFunction(this)">Opel</option>
         <option value="audi" onclick="myFunction(this)">Audi</option>
         </select>
         <input type="submit">
       </form>

       <p>Hold down the Ctrl (windows) / Command (Mac) button to select
        multiple options.</p>

       <script type="text/javascript">
         function myFunction(option) {

           if (option.selected) {
             alert(option.text);
           }
         }

       </script>
   </body>

 </html>
</code>```

答:
I have changed the dropdownlist a bit below:

```<code><select class="selectpicker" onchange="myFunction()" id="cars" name="cars"  multiple>
    <option value="volvo">Volvo</option>
    <option value="bmw">Bmw</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
</select>
</code>```

Then modified your myFunction below:

```<code>var oldarr = [];
var newarr = [];
function myFunction() {
    if ($("#cars option:selected").length == 1) {
        oldarr = [];
        oldarr.push($("#cars option:selected").val());
        alert($("#cars option:selected").val());
    }
    else {
        newarr = [];
        $("#cars option:selected").each(function(i){
            newarr.push($(this).val());
        });
        newitem = $(newarr).not(oldarr).get();
        if (newitem.length > 0) {
            alert(newitem[0]);
            oldarr.push(newitem[0]);
        }
        else {
            oldarr = newarr;
        }
    }
}
</code>```

Basically, the oldarr will store the previous list of selected items. Then we insert the latest list of selected items into newarr. Then we compare what is in the newarr but not in the oldarr. This way we can filter out only the latest clicked item. If the user deselects an item instead, we just assign the newarr to oldarr.

Body:
I have a selectpicker multiselect dropdown. I'm not able to invoke 'onclick' when I select any option. But this works with the normal html multiple dropdown. How to make it work with selectpicker?

Here's the code:

 <!DOCTYPE html>

       <meta charset="utf-8">
       <meta name="viewport" content="width=device-width, initial-scale=1">

       <link rel="stylesheet"
       href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-
       select/1.6.3/css/bootstrap-select.min.css" />
       <link rel="stylesheet" href="https:
       //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

       <form action="/action_page.php">
         <select class="selectpicker" name="cars"  multiple>
         <option value="volvo" onclick="myFunction(this)">Volvo</option>
         <option value="bmw" onclick="myFunction(this)">Bmw</option>
         <option value="opel" onclick="myFunction(this)">Opel</option>
         <option value="audi" onclick="myFunction(this)">Audi</option>
         </select>
         <input type="submit">
       </form>

Hold down the Ctrl (windows) / Command (Mac) button to select
        multiple options.

Body:
I have changed the dropdownlist a bit below:

<select class="selectpicker" onchange="myFunction()" id="cars" name="cars"  multiple>
    <option value="volvo">Volvo</option>
    <option value="bmw">Bmw</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
</select>

Then modified your myFunction below:

var oldarr = [];
var newarr = [];
function myFunction() {
    if ($("#cars option:selected").length == 1) {
        oldarr = [];
        oldarr.push($("#cars option:selected").val());
        alert($("#cars option:selected").val());
    }
    else {
        newarr = [];
        $("#cars option:selected").each(function(i){
            newarr.push($(this).val());
        });
        newitem = $(newarr).not(oldarr).get();
        if (newitem.length > 0) {
            alert(newitem[0]);
            oldarr.push(newitem[0]);
        }
        else {
            oldarr = newarr;
        }
    }
}

Basically, the oldarr will store the previous list of selected items. Then we insert the latest list of selected items into newarr. Then we compare what is in the newarr but not in the oldarr. This way we can filter out only the latest clicked item. If the user deselects an item instead, we just assign the newarr to oldarr.


问:
How should I package my Language Server with my client?
I'm trying to create a language server for VSCode. It's made up of a client and a server, communicating over RPC.

The official docs have a working example, with the language-server split into in two directories, the client and the server.

What I want to do is to package both into a VSIX file, so I can install them together.

In their example, they say cd to the client directory and run vsce package. However, If I do that and install the resultant package, VSCode says

"Error: Cannot find module '/home/blah/vscode.language-client-example-0.0.1/server/server.js"

I can't run vsce package in the server directory, as it complains

"Error: Missing publisher name"

How do I package it?

答:
You can publish extension and try. Official doc for publishing extensions

In short for publishing, follow below steps

npm install -g vsce

vsce publish


问:
Basemap / PySide QWidget: Drawing text onto map
I'm having difficulty writing text onto a Basemap that is inside a PySide QWidget. From what I've found online, people do the following:

```<code>import matplotlib.pyplot as plt
...
plt.text(x, y, 'some text')
</code>```

But when I try something like that with my code, it pops up another window with the text, not on the map within the widget.

Basemap doesn't have a method like text() so I've been stumped with what to do. Anybody have ideas on how to draw text to a basemap in this scenario?

Full Code:

```<code>'''
This program should draw a dot on a random point on Earth and label it 'Point'
You'll probably attempt to do this on line 43 in changeMap()
'''

from PySide import QtCore, QtGui

import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from mpl_toolkits.basemap import Basemap

from random import randint

class MapWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.layout = QtGui.QVBoxLayout(self)
        self.mplToolbar = NavigationToolbar(self.canvas, self, coordinates=False)
        self.layout.addWidget(self.canvas)
        self.layout.addWidget(self.mplToolbar)
        self.axes = self.figure.add_subplot(111)
        self.setLayout(self.layout)
        # Create our Basemap
        self.map = Basemap(projection='robin', lon_0=0, ax=self.axes, resolution='c')
        self.map.drawcoastlines()
        self.map.drawcountries()
        # Create empty plot to store random coordinates in for later
        self.points, = self.map.plot([], [], 'o')
        # Draw to screen
        self.canvas.draw()
        self.show()

    def changeMap(self, lat, lon, text):
        x, y = self.map(lon, lat)
        self.points.set_data(x, y)
        # Draw text here

        self.canvas.draw()

class Ui_MainWindow(object):
    def plot(self):
        # Plot on some random coordinate and label it 'Point'
        self.Map.changeMap(randint(-90, 90), randint(-180, 180), 'Point')

    def myChanges(self):
        # Initialize our Basemap
        self.Map = MapWidget()
        self.layoutMap = QtGui.QVBoxLayout(self.widget)
        self.layoutMap.addWidget(self.Map)
        # Plot a new point when the button is clicked
        self.pushButton.clicked.connect(self.plot)

    # The following is all PySide code, not very relevant to the question
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout_2 = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setMaximumSize(QtCore.QSize(100, 16777215))
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.widget = QtGui.QWidget(self.centralwidget)
        self.widget.setObjectName("widget")
        self.horizontalLayout.addWidget(self.widget)
        self.horizontalLayout_2.addLayout(self.horizontalLayout)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.myChanges()

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "Plot", None, QtGui.QApplication.UnicodeUTF8))

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

答:
To get text on a basemap plot you would add that text to the axes. You have stored those in self.axes.
Here you would create an empty text

```<code># Create empty plot to store random coordinates in for later
self.points, = self.map.plot([], [], 'o')
self.pointsannotate = self.axes.text(0,0,"", color="crimson")
</code>```

and later update the text's position and string:

```<code>def changeMap(self, lat, lon, text):
    x, y = self.map(lon, lat)
    self.points.set_data(x, y)
    # Draw text here
    self.pointsannotate.set_position([x,y])
    self.pointsannotate.set_text("{},{}".format(lon, lat))

    self.canvas.draw()
</code>```

Body:
I'm having difficulty writing text onto a Basemap that is inside a PySide QWidget. From what I've found online, people do the following:

import matplotlib.pyplot as plt
...
plt.text(x, y, 'some text')

But when I try something like that with my code, it pops up another window with the text, not on the map within the widget.

Basemap doesn't have a method like text() so I've been stumped with what to do. Anybody have ideas on how to draw text to a basemap in this scenario?

Full Code:

'''
This program should draw a dot on a random point on Earth and label it 'Point'
You'll probably attempt to do this on line 43 in changeMap()
'''

from PySide import QtCore, QtGui

import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from mpl_toolkits.basemap import Basemap

from random import randint

class MapWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.layout = QtGui.QVBoxLayout(self)
        self.mplToolbar = NavigationToolbar(self.canvas, self, coordinates=False)
        self.layout.addWidget(self.canvas)
        self.layout.addWidget(self.mplToolbar)
        self.axes = self.figure.add_subplot(111)
        self.setLayout(self.layout)
        # Create our Basemap
        self.map = Basemap(projection='robin', lon_0=0, ax=self.axes, resolution='c')
        self.map.drawcoastlines()
        self.map.drawcountries()
        # Create empty plot to store random coordinates in for later
        self.points, = self.map.plot([], [], 'o')
        # Draw to screen
        self.canvas.draw()
        self.show()

    def changeMap(self, lat, lon, text):
        x, y = self.map(lon, lat)
        self.points.set_data(x, y)
        # Draw text here

        self.canvas.draw()

class Ui_MainWindow(object):
    def plot(self):
        # Plot on some random coordinate and label it 'Point'
        self.Map.changeMap(randint(-90, 90), randint(-180, 180), 'Point')

    def myChanges(self):
        # Initialize our Basemap
        self.Map = MapWidget()
        self.layoutMap = QtGui.QVBoxLayout(self.widget)
        self.layoutMap.addWidget(self.Map)
        # Plot a new point when the button is clicked
        self.pushButton.clicked.connect(self.plot)

    # The following is all PySide code, not very relevant to the question
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout_2 = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setMaximumSize(QtCore.QSize(100, 16777215))
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.widget = QtGui.QWidget(self.centralwidget)
        self.widget.setObjectName("widget")
        self.horizontalLayout.addWidget(self.widget)
        self.horizontalLayout_2.addLayout(self.horizontalLayout)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.myChanges()

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "Plot", None, QtGui.QApplication.UnicodeUTF8))

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Body:
To get text on a basemap plot you would add that text to the axes. You have stored those in self.axes.
Here you would create an empty text

# Create empty plot to store random coordinates in for later
self.points, = self.map.plot([], [], 'o')
self.pointsannotate = self.axes.text(0,0,"", color="crimson")

and later update the text's position and string:

def changeMap(self, lat, lon, text):
    x, y = self.map(lon, lat)
    self.points.set_data(x, y)
    # Draw text here
    self.pointsannotate.set_position([x,y])
    self.pointsannotate.set_text("{},{}".format(lon, lat))

    self.canvas.draw()


问:
jQuery ancestors
Is there an easier way to say

```<code>$('element').parent('parentElement').parent('grandParentElement');
</code>```

Answer: Try parents() or closest()

Title: jQuery ancestors

Body:
Is there an easier way to say

$('element').parent('parentElement').parent('grandParentElement');

Answer: Try parents() or closest()

Body: $('element').closest('grandParentElement');


问:
Ember-leaflet-draw onClick event
onClick event inside ember-leaflet-draw is not working, i called an action onClick and console logged something but it doesn't seem to be working.</p>

```<code> {{draw-control position="topright" showDrawingLayer=true
 enableEditing=true drawingFinishedAction='handleDrawingFinishedAction'
  addHooks=true onClick=(action 'clicked')}}
</code>```

答:
I have not used this addon. but by looking at the code I can say these are the supported events,

```<code>leafletEvents: [
    'draw:editstart',
    'draw:editmove',
    'draw:editvertex',
    'draw:editstop',
    'draw:edited'
  ],
</code>```

By defualt draw-control component will trigger drawEditstart, drawEditmove, drawEditvertex, drawEditstop, drawEdited these events alone. so if you send action name while including the component then your action will be called. for eg., if you want to call action on editstart then,

```<code>{{draw-control position="topright" showDrawingLayer=true
 enableEditing=true drawingFinishedAction='handleDrawingFinishedAction'
  addHooks=true drawEditstart='drawEditstart'}}
</code>```

Title: Ember-leaflet-draw onClick event

Body:
onClick event inside ember-leaflet-draw is not working, i called an action onClick and console logged something but it doesn't seem to be working.

 {{draw-control position="topright" showDrawingLayer=true
 enableEditing=true drawingFinishedAction='handleDrawingFinishedAction'
  addHooks=true onClick=(action 'clicked')}}

Body:
I have not used this addon. but by looking at the code I can say these are the supported events,

leafletEvents: [
    'draw:editstart',
    'draw:editmove',
    'draw:editvertex',
    'draw:editstop',
    'draw:edited'
  ],

By defualt draw-control component will trigger drawEditstart, drawEditmove, drawEditvertex, drawEditstop, drawEdited these events alone. so if you send action name while including the component then your action will be called. for eg., if you want to call action on editstart then,

{{draw-control position="topright" showDrawingLayer=true
 enableEditing=true drawingFinishedAction='handleDrawingFinishedAction'
  addHooks=true drawEditstart='drawEditstart'}}


问:
Merging 2 dataframes on Pandas
Sorry I have a very simple question. So I have two dataframes that look like
Dataframe 1:
columns: a b c d e f g h

Dataframe 2:
columns: e ef

I'm trying to join Dataframe 2 on Dataframe 1 at column e, which should yield
columns: a b c d e ef g h
or
columns: a b c d e f g h ef

However:
df1.merge(df2, how = 'inner', on = 'e') yields a blank dataframe when I print it out.

'outer' merge only extends the dataframe vertically (like using an append function).

Would appreciate some help thank you!

答:
You can do it like this:</p>

```<code>def mergeDfs(df1,df2):
    newDf = dict()
    dfList = []
    for i in df1:
        l = len(i)
        row = []
        for j in range(l):
            row.append(df1[i][j])
        newDf[i] = row
        dfList.append(i)
    for i in df2:
        l = len(i)
        row = []
        if i not in dfList:
            for j in range(l):
                row.append(df2[i][j])
            newDf[i] = row
    df = pd.DataFrame(newDf)
    return df
</code>```

Title: Merging 2 dataframes on Pandas

Body:
You can do it like this:

def mergeDfs(df1,df2):
    newDf = dict()
    dfList = []
    for i in df1:
        l = len(i)
        row = []
        for j in range(l):
            row.append(df1[i][j])
        newDf[i] = row
        dfList.append(i)
    for i in df2:
        l = len(i)
        row = []
        if i not in dfList:
            for j in range(l):
                row.append(df2[i][j])
            newDf[i] = row
    df = pd.DataFrame(newDf)
    return df