问:
image not correctly resized in chrome, compared to Firefox
I have an html page displaying an image.
When the image is larger than the window of the browser, the image is resized (keeping the same ratio) to fit in the window with Firefox.
But with Chrome, the image is compressed

Here is the html code:

```<code><div class="container">
  <div class="auto">
    <img class="full-width" src="http://laurent.delrocq.free.fr/test/img-1.jpg" />
    <div class="absolute">
        <img src="http://laurent.delrocq.free.fr/test/left.png" alt="#" class="left">
        <img src="http://laurent.delrocq.free.fr/test/right.png" alt="#" class="right">
    </div>
  </div>
</div>
</code>```

and the css:

```<code>html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.container {
  text-align: center;
}
.auto {
        width:auto;
        height:auto;
        position:relative;
        display:inline-block;
    }

    .absolute {
        position:absolute;
        top:0;
        left:0;
        height:100%;
        width:100%;
        z-index:2;
    }

    .left {
        position:absolute;
        top:50%;
        left:15px;
        transform: translateY(-50%);
    }

    .right {
        position:absolute;
        top:50%;
        right:15px;
        transform: translateY(-50%);
    }

  .full-width {
    width:auto;
    max-width:100%;
    max-height: 100vh;
    height:100%;
  }
</code>```

How can I change the code so that it works (resize) both on Firefox and Chrome ?

答:
I finally used js to set the correct size of the div according to the size of the image.

html:

```<code><div class='fill-screen'>
<img id="photo" class='make-it-fit' src='https://upload.wikimedia.org/wikipedia/commons/f/f2/Leaning_Tower_of_Pisa.jpg'>
<div id="over_image">
  <div class="left">
    <a href="https://en.wikipedia.org/wiki/Arrow_(symbol)#/media/File:U%2B2190.svg" style="outline:0">
      <img src="http://laurent.delrocq.free.fr/test/left.png" alt="#">
    </a>
  </div>
  <div class="right">
    <a href="https://en.wikipedia.org/wiki/Arrow_(symbol)#/media/File:U%2B2192.svg">
      <img src="http://laurent.delrocq.free.fr/test/right.png" alt="#">
    </a>
  </div></div>
</div>
</code>```

css:

```<code>div.fill-screen {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    text-align: center;
}
img.make-it-fit {
    max-width: 100%;
    max-height: 100%;
}

#over_image {
    margin:0px;
    padding:0px;
    display: inline-block;
    text-align: center;
    color: #fff;
    position: absolute;

    height:100%;
    background: rgba(0,0,0,.5);
}

.left{
    opacity:0;
    position:absolute;
    width:20%;
    height:100%;
}

.left a, .right a{
  position: absolute;
  top: 50%;
  left:50%;
  transform: translate(-50%, -50%);
}

.right{
    opacity:0;
    position:absolute;
    margin-left: 80%;
    width:20%;
    height:100%;
}

.left:hover{
  opacity:1;
}

.right:hover{
  opacity:1;
}
</code>```

js:

```<code>function resizeDiv()
{
  var img = document.getElementById('photo');

  var width  = img.clientWidth;
  var height = img.clientHeight;
  var left   = img.offsetLeft;
  var top    = img.offsetTop;

  document.getElementById('over_image').style.width= width + 'px';
  document.getElementById('over_image').style.height= height + 'px';
  document.getElementById('over_image').style.top= top + 'px';
  document.getElementById('over_image').style.left= left + 'px';
}

$(document).ready(function() {
  resizeDiv();
})

$(window).resize(function() {
    resizeDiv();
})
</code>```

The corresponding jsfiddle is here: https://jsfiddle.net/4kxjt813/

Body:
I have an html page displaying an image.
When the image is larger than the window of the browser, the image is resized (keeping the same ratio) to fit in the window with Firefox.
But with Chrome, the image is compressed

Here is the html code:

and the css:

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.container {
  text-align: center;
}
.auto {
        width:auto;
        height:auto;
        position:relative;
        display:inline-block;
    }

    .absolute {
        position:absolute;
        top:0;
        left:0;
        height:100%;
        width:100%;
        z-index:2;
    }

    .left {
        position:absolute;
        top:50%;
        left:15px;
        transform: translateY(-50%);
    }

    .right {
        position:absolute;
        top:50%;
        right:15px;
        transform: translateY(-50%);
    }

  .full-width {
    width:auto;
    max-width:100%;
    max-height: 100vh;
    height:100%;
  }

How can I change the code so that it works (resize) both on Firefox and Chrome ?

Body:
I finally used js to set the correct size of the div according to the size of the image.

html:

<div class='fill-screen'>
<img id="photo" class='make-it-fit' src='https://upload.wikimedia.org/wikipedia/commons/f/f2/Leaning_Tower_of_Pisa.jpg'>
<div id="over_image">
  <div class="left">
    <a href="https://en.wikipedia.org/wiki/Arrow_(symbol)#/media/File:U%2B2190.svg" style="outline:0">
      <img src="http://laurent.delrocq.free.fr/test/left.png" alt="#">
    </a>
  </div>
  <div class="right">
    <a href="https://en.wikipedia.org/wiki/Arrow_(symbol)#/media/File:U%2B2192.svg">
      <img src="http://laurent.delrocq.free.fr/test/right.png" alt="#">
    </a>
  </div></div>
</div>

css:

div.fill-screen {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    text-align: center;
}
img.make-it-fit {
    max-width: 100%;
    max-height: 100%;
}

#over_image {
    margin:0px;
    padding:0px;
    display: inline-block;
    text-align: center;
    color: #fff;
    position: absolute;

    height:100%;
    background: rgba(0,0,0,.5);
}

.left{
    opacity:0;
    position:absolute;
    width:20%;
    height:100%;
}

.left a, .right a{
  position: absolute;
  top: 50%;
  left:50%;
  transform: translate(-50%, -50%);
}

.right{
    opacity:0;
    position:absolute;
    margin-left: 80%;
    width:20%;
    height:100%;
}

.left:hover{
  opacity:1;
}

.right:hover{
  opacity:1;
}

js:

function resizeDiv()
{
  var img = document.getElementById('photo');

  var width  = img.clientWidth;
  var height = img.clientHeight;
  var left   = img.offsetLeft;
  var top    = img.offsetTop;

  document.getElementById('over_image').style.width= width + 'px';
  document.getElementById('over_image').style.height= height + 'px';
  document.getElementById('over_image').style.top= top + 'px';
  document.getElementById('over_image').style.left= left + 'px';
}

$(document).ready(function() {
  resizeDiv();
})

$(window).resize(function() {
    resizeDiv();
})

The corresponding jsfiddle is here: https://jsfiddle.net/4kxjt813/


来源: stackexchange

问:
PivotTable Do not show subtotals
I am converting a table into Pivot and then to a CSV file. I want to remove the subtotals of the pivot table. So far: this is my progress.

MACRO CreatePivot:

```<code>Sub CreatePivot()
' Creates a PivotTable report from the table on Sheet1
' by using the PivotTableWizard method with the PivotFields
' method to specify the fields in the PivotTable.
Dim objTable As PivotTable, objField As PivotField

' Select the sheet and first cell of the table that contains the data.
ActiveWorkbook.Sheets("Employees").Select
Range("A1").Select

' Create the PivotTable object based on the Employee data on Sheet1.
Set objTable = Sheet1.PivotTableWizard

' Specify row and column fields.
Set objField = objTable.PivotFields("Supplier")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("Part #")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("Tracking #")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("Packing/Inv#")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("PO#")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("Ship Date")
objField.Orientation = xlRowField

' Specify a data field with its summary
' function and format.
Set objField = objTable.PivotFields("Qty")
objField.Orientation = xlDataField
objField.Function = xlSum

' Specify a page field.
Set objField = objTable.PivotFields("Carrier")
objField.Orientation = xlPageField

' Prompt the user whether to delete the PivotTable.
Application.DisplayAlerts = False
If MsgBox("Delete the PivotTable?", vbYesNo) = vbYes Then
    ActiveSheet.Delete
End If
Application.DisplayAlerts = True

End Sub
</code>```

Also I just added MACRO DesigningPivotTable:

```<code>Sub DesigningPivotTable()
Dim PT As PivotTable
Set PT = ActiveSheet.PivotTables(1)
PT.TableRange1.Select
With PT
 .NullString = 0
 .RepeatAllLabels Repeat:=xlRepeatLabels
 .ColumnGrand = False
 .RowGrand = 0
 .PivotFields("Order #").Subtotals(1) = True
 .PivotFields("Order #").Subtotals(1) = False
End With
End Sub
</code>```

According to Excel 2013 Pivot Table Data Crunching; you can turn on the first subtotal, and this method automatically disables all the other subtotals, hence: it is not working for me:

```<code> .PivotFields("Order #").Subtotals(1) = True
 .PivotFields("Order #").Subtotals(1) = False
</code>```

答:
```<code>.PivotFields("Pivot Field Name").Subtotals = Array(False, False, False, False, False, False, False, False, False, False, False, False)
</code>```

it is not better is it just to make it clear

ContentLicense: CC BY-SA 3.0

Title: PivotTable Do not show subtotals

Body:
I am converting a table into Pivot and then to a CSV file. I want to remove the subtotals of the pivot table. So far: this is my progress.

MACRO CreatePivot:

Sub CreatePivot()
' Creates a PivotTable report from the table on Sheet1
' by using the PivotTableWizard method with the PivotFields
' method to specify the fields in the PivotTable.
Dim objTable As PivotTable, objField As PivotField

' Select the sheet and first cell of the table that contains the data.
ActiveWorkbook.Sheets("Employees").Select
Range("A1").Select

' Create the PivotTable object based on the Employee data on Sheet1.
Set objTable = Sheet1.PivotTableWizard

' Specify row and column fields.
Set objField = objTable.PivotFields("Supplier")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("Part #")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("Tracking #")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("Packing/Inv#")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("PO#")
objField.Orientation = xlRowField
Set objField = objTable.PivotFields("Ship Date")
objField.Orientation = xlRowField

' Specify a data field with its summary
' function and format.
Set objField = objTable.PivotFields("Qty")
objField.Orientation = xlDataField
objField.Function = xlSum

' Specify a page field.
Set objField = objTable.PivotFields("Carrier")
objField.Orientation = xlPageField

' Prompt the user whether to delete the PivotTable.
Application.DisplayAlerts = False
If MsgBox("Delete the PivotTable?", vbYesNo) = vbYes Then
    ActiveSheet.Delete
End If
Application.DisplayAlerts = True

End Sub

Also I just added MACRO DesigningPivotTable:

Sub DesigningPivotTable()
Dim PT As PivotTable
Set PT = ActiveSheet.PivotTables(1)
PT.TableRange1.Select
With PT
 .NullString = 0
 .RepeatAllLabels Repeat:=xlRepeatLabels
 .ColumnGrand = False
 .RowGrand = 0
 .PivotFields("Order #").Subtotals(1) = True
 .PivotFields("Order #").Subtotals(1) = False
End With
End Sub

According to Excel 2013 Pivot Table Data Crunching; you can turn on the first subtotal, and this method automatically disables all the other subtotals, hence: it is not working for me:

 .PivotFields("Order #").Subtotals(1) = True
 .PivotFields("Order #").Subtotals(1) = False

Body:
.PivotFields("Pivot Field Name").Subtotals = Array(False, False, False, False, False, False, False, False, False, False, False, False)

it is not better is it just to make it clear


问:
Calling Button from different view in Android
In my app I have 3 radiobuttons on top of the view. When i choose one the 'body' underneath that changes to the XML-view i defined.

(If you want more information + pics, I asked a question about this earlier: Dynamically change view inside view in Android)

Now i want to call and change the text of the buttons and edittext's from the different views.

When I do btnAutopech = (Button) findViewById(R.id.btnAutopech); it's gives an NullPointerException.

How can I do this?

答:
Depends on how you solved the last question you linked to. If your inflating new views into the area you want to change then you won't be able to retreive a reference to them using finViewById. I.e. they don't actually exist.

When you re-display your view, within which you want to display text based, on your other views outcome, you would have to re-assign the text when you re-attach/display your view. You could then assign text from a member variable of the class, or perhaps from sharedPreferences or a contentProvider.

EIther way, this sort of all depends on how you've solved the issue of your original question and when you attach/remove your views.

To summerise:

It looks like your removing your other views when you visit other views, so store your data in a member variable that persists.

attach view A

got to view B

Click button or something in view B and update member variable used by view A

Go to view A (Removing view B and attaching view A)

set text on view A from member variable (updated as a result of clicking button in view B for example)

ContentLicense: CC BY-SA 2.5


问:
HTMLAgilityPack QuerySelectorAll throwing exception, potentially Fizzler dll version mismatch?
We recently updated a bunch of dlls in our project, including HtmlAgilityPack to their latest versions. This has made the following code which had been working start throwing errors on the first line.

```<code>List<HtmlNode> foundNodes = document.QuerySelectorAll(".divider").ToList();

foreach(HtmlNode node in foundNodes){
    doWhatever(node);
}
</code>```

Method not found: 'System.Collections.Generic.IEnumerable`1 HtmlAgilityPack.HtmlNode.Descendants()'.

The last line of the stack trace is:

"at Fizzler.Systems.HtmlAgilityPack.HtmlNodeOps.b__71(HtmlNode n)"

The QuerySelectorAll is returning an IEnumerable of HtmlNode, however I can't seem to be able to cast it to a list anymore. I would hazard a guess there is some related dll with an incompatible version now (fizzler?) missing the Descendants method? However the NuGet page for HtmlAgilityPack shows no dependencies, and the fizzler version I'm using is 1.0.0 which I think is correct.

答:
Disclaimer: I'm the owner of the project Html Agility Pack

The version 1.5.0 has been released, and this issue has been fixed in the v1.5.0-beta5.

It was caused because a default parameter was added to a method in the v1.4.9.5

Since the library is strongly named, Fizzler could not find anymore this method.

Body:
We recently updated a bunch of dlls in our project, including HtmlAgilityPack to their latest versions. This has made the following code which had been working start throwing errors on the first line.

List<HtmlNode> foundNodes = document.QuerySelectorAll(".divider").ToList();

foreach(HtmlNode node in foundNodes){
    doWhatever(node);
}

Method not found: 'System.Collections.Generic.IEnumerable`1 HtmlAgilityPack.HtmlNode.Descendants()'.

The last line of the stack trace is:

"at Fizzler.Systems.HtmlAgilityPack.HtmlNodeOps.b__71(HtmlNode n)"

The QuerySelectorAll is returning an IEnumerable of HtmlNode, however I can't seem to be able to cast it to a list anymore. I would hazard a guess there is some related dll with an incompatible version now (fizzler?) missing the Descendants method? However the NuGet page for HtmlAgilityPack shows no dependencies, and the fizzler version I'm using is 1.0.0 which I think is correct.


问:
How to match a string against an array of pattern in Javascript?
I've two variables:

```<code>var input = "user1@gmail.com";
var preferredPatterns = ["*@gmail.com", "*@yahoo.com", "*@live.com"];
</code>```

Want to match the input with preferred pattern array. If any of the patterns matches I've to do certain task (in this example, input is a definite match). How can I match against an array of pattern in javascript?

答:
No regexp you may do as follows;

function matchPattern(xs, [y,...ys]){

  function helper([x,...xs]){
    return "*" + xs.join('') === y ? true
                                   : xs.length ? helper(xs)
                                               : false;
  }

  return helper(xs) ? y
                    : ys.length ? matchPattern(xs,ys)
                                : "No Match..!";
}

var input             = "user1@gmail.com",
    preferredPatterns = ["*@yahoo.com", "*@live.com", "*@gmail.com"];
    result            = matchPattern(input, preferredPatterns);

console.log(result);```

ContentLicense: CC BY-SA 4.0

Body:
I've two variables:

var input = "user1@gmail.com";
var preferredPatterns = ["*@gmail.com", "*@yahoo.com", "*@live.com"];

Want to match the input with preferred pattern array. If any of the patterns matches I've to do certain task (in this example, input is a definite match). How can I match against an array of pattern in javascript?


问:
Trying to return a JSON result from an API using async await pattern
I am trying to call this API using the async await style but having some issues.

```<code>public async Task<User> GetUser(int userId)
{
    User user = null;
    HttpResponseMessage response = await client.GetAsync("/user/...");
    if(response.IsSuccessStatusCode)
    {
        var result = await response.Content.ReadAsStringAsync();
        user = JsonConvert.DeserializeObject<User>(result);
    }

    return user;
}
</code>```

I am calling the above method in my console app:

```<code>var user = apiClient.GetUser(123);

Console.WriteLine($"user result is {user.Result.UserId}");
</code>```

I get the error:

An unhandled exception of type 'System.NullReferenceException
  Object reference not set to an instance..

Is my code snippet following the best practise is there something wrong?

My endpoint works fine when I test using Postman.

Update

The interface for my GetUser method is:

```<code>Task<User> GetUser(int userId);
</code>```

答:
I did the following, I was getting also an error and when I get the value I also get the result response.Content.ReadAsStringAsync().Result;, but also you should debug and check that you are really getting a json value.

```<code>    string responseString = "";
    ...
        if (response.IsSuccessStatusCode)
        {
         responseString = response.Content.ReadAsStringAsync().Result;
         Message jsonObject = JsonConvert.DeserializeObject<Message>(responseString.ToString(),
    new JsonSerializerSettings
    {
    NullValueHandling = NullValueHandling.Ignore
    });

        ...
}
</code>```

Body:
I am trying to call this API using the async await style but having some issues.

public async Task<User> GetUser(int userId)
{
    User user = null;
    HttpResponseMessage response = await client.GetAsync("/user/...");
    if(response.IsSuccessStatusCode)
    {
        var result = await response.Content.ReadAsStringAsync();
        user = JsonConvert.DeserializeObject<User>(result);
    }

    return user;
}

I am calling the above method in my console app:

var user = apiClient.GetUser(123);

Console.WriteLine($"user result is {user.Result.UserId}");

I get the error:

An unhandled exception of type 'System.NullReferenceException
  Object reference not set to an instance..

Is my code snippet following the best practise is there something wrong?

My endpoint works fine when I test using Postman.

Update

The interface for my GetUser method is:

Task<User> GetUser(int userId);

Body:
I did the following, I was getting also an error and when I get the value I also get the result response.Content.ReadAsStringAsync().Result;, but also you should debug and check that you are really getting a json value.

    string responseString = "";
    ...
        if (response.IsSuccessStatusCode)
        {
         responseString = response.Content.ReadAsStringAsync().Result;
         Message jsonObject = JsonConvert.DeserializeObject<Message>(responseString.ToString(),
    new JsonSerializerSettings
    {
    NullValueHandling = NullValueHandling.Ignore
    });

        ...
}


问:
Creating multiple objects using a loop
I'm a beginner and I have a question about building objects.

I don't understand how it is possible to create two objects with the same variable name "oneCar" in this situation :

```<code> for (int i = 0; i<2 ; ++i)
    {
        Car oneCar = new Car();
    }
</code>```

It will create two objects "oneCar" with two different references.

But if I do this :

```<code>Car oneCar = new Car();
Car oneCar = new Car();
</code>```

This will tell me that there is a duplicate variable.

答:
With a couple of exceptions, local variables in Java are scoped to the nearest surrounding set of braces. That means, as far as the compiler is concerned, the variable no longer  exists once you exit the braces. The variable oneCar declared on the first iteration doesn't exist by the time you reach the second iteration. It is equivalent to writing:

```<code>{
    Car oneCar = new Car();
}
{
    Car oneCar = new Car();
}
</code>```

which is perfectly legal.

Title: Creating multiple objects using a loop

Body:
I'm a beginner and I have a question about building objects.

I don't understand how it is possible to create two objects with the same variable name "oneCar" in this situation :

 for (int i = 0; i<2 ; ++i)
    {
        Car oneCar = new Car();
    }

It will create two objects "oneCar" with two different references.

But if I do this :

Car oneCar = new Car();
Car oneCar = new Car();

This will tell me that there is a duplicate variable.

Body:
With a couple of exceptions, local variables in Java are scoped to the nearest surrounding set of braces. That means, as far as the compiler is concerned, the variable no longer  exists once you exit the braces. The variable oneCar declared on the first iteration doesn't exist by the time you reach the second iteration. It is equivalent to writing:

{
    Car oneCar = new Car();
}
{
    Car oneCar = new Car();
}

which is perfectly legal.


问:
Remove white space at the top and the bottom in h3
h3 with white space at the top and the bottom

I have some white space around my h3. To align it the same as some pictures I want to delete the white space at the top and the bottom of the h3. The margin is 0, but there is still space between the top and the bottom of the text. How do I solve this?

this is my code:

```<code><html>
 <head>
 </head>
 <body>
  <h3>title</h3>
 </body>
</html>
</code>```

答:
As noted before, it is hard to reproduce your situation without the full CSS code that you have also.

However, a quick test of this gave me a h3 without any whitespace:

```<code><html>
 <head>
 </head>
 <body style="padding: 0;">
  <h3 style="margin: 0; padding: 0;">test</h3>
 </body>
</html>
</code>```

It is probably browser dependent what the default margins/paddings on both the  body and h3 elements are. I hope this helps you.

Body:
h3 with white space at the top and the bottom

I have some white space around my h3. To align it the same as some pictures I want to delete the white space at the top and the bottom of the h3. The margin is 0, but there is still space between the top and the bottom of the text. How do I solve this?

this is my code:

title

Body:
As noted before, it is hard to reproduce your situation without the full CSS code that you have also.

However, a quick test of this gave me a h3 without any whitespace:

<html>
 <head>
 </head>
 <body style="padding: 0;">
  <h3 style="margin: 0; padding: 0;">test</h3>
 </body>
</html>

It is probably browser dependent what the default margins/paddings on both the  body and h3 elements are. I hope this helps you.


问:
How to define a query parameter to be a list of specific values with Raml 1.0?
I've been looking around on how to define the following queryParameters in RAML 1.0

```<code>/api/route?attrs=attr1,attr2,attr3
</code>```

Where attr1,attr2 and attr3 are specific values and each one must be present only once

to make it more clear if I have a return object like

```<code>{
  name: 'myName',
  lastName: 'myLastName',
  age: 20
}
</code>```

The possible values in 'attrs' would be 'name','lastName' and 'age'.

i.e.

These are valid:

```<code>/api/route?attrs=name,lastName,age
/api/route?attrs=name,lastName
/api/route?attrs=name
</code>```

These are invalid:

```<code>/api/route?attrs=name,lastName,name
/api/route?attrs=name,age,age
</code>```

I appreciate your help and if anyone know how to accomplish this please let me know.
Thank you in advance.

答:
You can define a regular expression pattern to validate the field.

https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/raml-10.md#built-in-types

Body:
I've been looking around on how to define the following queryParameters in RAML 1.0

/api/route?attrs=attr1,attr2,attr3

Where attr1,attr2 and attr3 are specific values and each one must be present only once

to make it more clear if I have a return object like

{
  name: 'myName',
  lastName: 'myLastName',
  age: 20
}

The possible values in 'attrs' would be 'name','lastName' and 'age'.

i.e.

These are valid:

/api/route?attrs=name,lastName,age
/api/route?attrs=name,lastName
/api/route?attrs=name

These are invalid:

/api/route?attrs=name,lastName,name
/api/route?attrs=name,age,age

I appreciate your help and if anyone know how to accomplish this please let me know.
Thank you in advance.


问:
The reason to use masking
```<code>gcc 4.4.1 c89
</code>```

I am using a API that our previous programmer has produced. However, I am a bit confused as to why they do masking in this why.

What is the reason to OR the hex with a mask. And what would be the reason to have IPEV_ERROR_MASK OR'ed with IPEV_START. Why not have just the hex values?

```<code>#define IPEV_MASK               0x9000
#define IPEV_ERROR_MASK     (IPEV_MASK | 0x0800)
#define IPEV_OPEN               (IPEV_MASK | 0x01)
#define IPEV_START              (IPEV_MASK | 0x02)
#define IPEV_MEDIA_FAIL     (IPEV_ERROR_MASK | IPEV_START)
</code>```

Many thanks for any suggestions,

答:
Masks help you extract the bits you want from an integer, and discard the bits you are not interested in.

The value 0x9000 looks like this in binary:

```<code>1001 0000 0000 0000
</code>```

So the intention of this mask is to use bits 12 and 15, discarding the rest.

The IPEV_ERROR_MASK is a combination of the bits set in IPEV_MASK plus the bits set in 0000 1000 0000 0000. So it could be that bit 11 is reserved for indicating whether an error has occurred, and combining it with IPEV_START in IPEV_MEDIA_FAIL makes sense.

Title: The reason to use masking

Body:
gcc 4.4.1 c89

I am using a API that our previous programmer has produced. However, I am a bit confused as to why they do masking in this why.

What is the reason to OR the hex with a mask. And what would be the reason to have IPEV_ERROR_MASK OR'ed with IPEV_START. Why not have just the hex values?

#define IPEV_MASK               0x9000
#define IPEV_ERROR_MASK     (IPEV_MASK | 0x0800)
#define IPEV_OPEN               (IPEV_MASK | 0x01)
#define IPEV_START              (IPEV_MASK | 0x02)
#define IPEV_MEDIA_FAIL     (IPEV_ERROR_MASK | IPEV_START)

Many thanks for any suggestions,

Body:
Masks help you extract the bits you want from an integer, and discard the bits you are not interested in.

The value 0x9000 looks like this in binary:

1001 0000 0000 0000

So the intention of this mask is to use bits 12 and 15, discarding the rest.

The IPEV_ERROR_MASK is a combination of the bits set in IPEV_MASK plus the bits set in 0000 1000 0000 0000. So it could be that bit 11 is reserved for indicating whether an error has occurred, and combining it with IPEV_START in IPEV_MEDIA_FAIL makes sense.


问:
Javascript Promise.all - how to handle all errors
How can I handle errors from other than first promise rejection?

Example:

```<code>Promise.all[p1, p2, p3].then(...)
.catch((error) => { console.log(error) })
</code>```

Order of rejection:
p1
p2
p3

Is it possible to get errors from p2 and p3?

EDIT:
from comments below: is it possible to catch error from specific Promise before passing it to .all? E.g. I want to stay with Promise.all funcionality but log all error cases also

答: There will be only one rejected promise. No more. You'll receive error for the first one rejected and that's it.</p>

Body:
How can I handle errors from other than first promise rejection?

Example:

Promise.all[p1, p2, p3].then(...)
.catch((error) => { console.log(error) })

Order of rejection:
p1
p2
p3

Is it possible to get errors from p2 and p3?

EDIT:
from comments below: is it possible to catch error from specific Promise before passing it to .all? E.g. I want to stay with Promise.all funcionality but log all error cases also


问:
angularjs ngOptions having 2 object property as label and tracking by Id
Okay so i have an object that contains a few object named as professionals
the structure looks like that

lstProf=[{firstName:'tony',lastName:'bob',id:188},{...},{...}];

I want my select field to show firstName + lastName and track by ID

somehow this is not working :

```<code>    <select class="input-antoine section2-control"
    data-ng-options="prof.id as prof.firstName +'
     '+prof.lastName for prof in lstProfs track by prof.id"
    data-ng-model="patient.treatingProfessionnal"
    data-convert-to-number>
    </select>
</code>```

my ng-model is also an int.

what am i doing wrong.

答:
```<code>lstProf=[{firstName:'tony',lastName:'bob',id:188},{...},{...}];

<select data-ng-options="prof.id as prof.firstName +'
     '+prof.lastName for prof in lstProf track by prof.id"
    data-ng-model="personById"
    data-convert-to-number>
</select>
</code>```

First you have typo in the question.
Collection is named lstProf, then you are referencing to it in the ng-options in plural form lstProfs.
Second according to documentation as  Pankaj Parkar brought up there is the caution of using select as with track by.
Whatever property is in the track by, quoting documentation
track by expression is also applied to the ngModel.

Prepared simple plunker to expose difference of approach to your problem.
https://plnkr.co/edit/Rx8JfTee0JnyQa7UD1qE?p=preview

Body:
Okay so i have an object that contains a few object named as professionals
the structure looks like that

lstProf=[{firstName:'tony',lastName:'bob',id:188},{...},{...}];

I want my select field to show firstName + lastName and track by ID

somehow this is not working :

    <select class="input-antoine section2-control"
    data-ng-options="prof.id as prof.firstName +'
     '+prof.lastName for prof in lstProfs track by prof.id"
    data-ng-model="patient.treatingProfessionnal"
    data-convert-to-number>
    </select>

my ng-model is also an int.

what am i doing wrong.

Body:
lstProf=[{firstName:'tony',lastName:'bob',id:188},{...},{...}];

<select data-ng-options="prof.id as prof.firstName +'
     '+prof.lastName for prof in lstProf track by prof.id"
    data-ng-model="personById"
    data-convert-to-number>
</select>

First you have typo in the question.
Collection is named lstProf, then you are referencing to it in the ng-options in plural form lstProfs.
Second according to documentation as  Pankaj Parkar brought up there is the caution of using select as with track by.
Whatever property is in the track by, quoting documentation
track by expression is also applied to the ngModel.

Prepared simple plunker to expose difference of approach to your problem.
https://plnkr.co/edit/Rx8JfTee0JnyQa7UD1qE?p=preview


问:
Google Apps Script Security Considerations for Sensitive Data
I've been tasked with creating a system to store employee paperwork for the HR department. We are deeply entrenched in the Google Docs Platform (all our documents are made and served via Google Apps), and I already have a time clock program built on Google Apps Script running on our internal google site and pulling from google Sheets for data. This new task, however, will contain much more sensitive data that should be stored in an encrypted manner and served after two factor-authentication is used.

TL;DR: I need help to create a system to serve web pages in an encrypted manner and using two-factor authentication within the Google Docs Ecosystem.

Here is some psuedo code I thought might help describe what I am looking for:

CODE.GS

//CONSTANT VARIABLES
var adminList = ['Sarah@mycompany.com',
                 'Lewis@mycompany.com',
                 'Tim@mycompany.com'];

function doGet() {
  var htmlTemplate = HtmlService.createTemplateFromFile('Login_Prompt');
  var htmlOutput = htmlTemplate.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle('Login to HR Module');
  return htmlOutput;
}

function processLogin(username)
{
  if(adminList.indexOf(username) > -1)
  {
    var htmlTemplate = HtmlService.createTemplateFromFile('Admin_Page');
    var htmlOutput = htmlTemplate.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle('HR Management Module');
    return htmlOutput;
  }

  else
  {
    var htmlTemplate = HtmlService.createTemplateFromFile('User Page');
    var htmlOutput = htmlTemplate.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle('Employee Profile');
    return htmlOutput;

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

<p><strong>Login-Prompt.HTML</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h4>HR Management Console</h4>
    <p>Please log into this system using your Google Account Credentials</p>
    <form>
    Username: <input type="text" size = "6">
    Password: <input type="password" size = "4">
    <button>Submit</button>
    </form>
  </body>
</html></code>```

User_Page.html

<!DOCTYPE html>

    <base target="_top">

 Welcome, User!

Profile

Sensitive information 1

Sensitive information 2

Sensitive information 3

Sensitive information 4

    <button>Update your profile</button>
    <!-Open Form to access and edit personal data->

 Documents

Document 1

Document 2

Document 3

Document 4

    <button>upload a document</button>
    <!-Open Form to upload HR Documents->

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

<p><strong>Admin_Page.html</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <p>Welcome, Manager!</p>
    <p>Users:</p>
    <ul>
      <li>LastName, FirstName 1 <button>Edit</button></li>
      <li>LastName, FirstName 2 <button>Edit</button></li>
      <li>LastName, FirstName 3 <button>Edit</button></li>
    </ul>
  </body>
</html></code>```

How can I implement encryption and two factor authentication to this process. Is this possible to do in the Google Docs ecosystem using Google Apps Script?

答: I think we are going to go with a MySQL Database hosted in Cloud SQL with an SSL certificate. As long as the the SSL line is intact, I think Google Appscript's embedded security measures should be enough for us. Thanks all for helping us to think through this one!</p>

Body:
I've been tasked with creating a system to store employee paperwork for the HR department. We are deeply entrenched in the Google Docs Platform (all our documents are made and served via Google Apps), and I already have a time clock program built on Google Apps Script running on our internal google site and pulling from google Sheets for data. This new task, however, will contain much more sensitive data that should be stored in an encrypted manner and served after two factor-authentication is used.

TL;DR: I need help to create a system to serve web pages in an encrypted manner and using two-factor authentication within the Google Docs Ecosystem.

Here is some psuedo code I thought might help describe what I am looking for:

CODE.GS

//CONSTANT VARIABLES
var adminList = ['Sarah@mycompany.com',
                 'Lewis@mycompany.com',
                 'Tim@mycompany.com'];

function doGet() {
  var htmlTemplate = HtmlService.createTemplateFromFile('Login_Prompt');
  var htmlOutput = htmlTemplate.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle('Login to HR Module');
  return htmlOutput;
}

function processLogin(username)
{
  if(adminList.indexOf(username) > -1)
  {
    var htmlTemplate = HtmlService.createTemplateFromFile('Admin_Page');
    var htmlOutput = htmlTemplate.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle('HR Management Module');
    return htmlOutput;
  }

  else
  {
    var htmlTemplate = HtmlService.createTemplateFromFile('User Page');
    var htmlOutput = htmlTemplate.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle('Employee Profile');
    return htmlOutput;

  }
}

Login-Prompt.HTML

<!DOCTYPE html>

    <base target="_top">

HR Management Console

Please log into this system using your Google Account Credentials

    <form>
    Username: <input type="text" size = "6">
    Password: <input type="password" size = "4">
    <button>Submit</button>
    </form>

User_Page.html

<!DOCTYPE html>

    <base target="_top">

 Welcome, User!

Profile

Sensitive information 1

Sensitive information 2

Sensitive information 3

Sensitive information 4

    <button>Update your profile</button>
    <!-Open Form to access and edit personal data->

 Documents

Document 1

Document 2

Document 3

Document 4

    <button>upload a document</button>
    <!-Open Form to upload HR Documents->

Admin_Page.html

<!DOCTYPE html>

    <base target="_top">

Welcome, Manager!

Users:

LastName, FirstName 1 <button>Edit</button>

LastName, FirstName 2 <button>Edit</button>

LastName, FirstName 3 <button>Edit</button>

How can I implement encryption and two factor authentication to this process. Is this possible to do in the Google Docs ecosystem using Google Apps Script?


问:
Android Notification Not Showing On API 26
I recently updated my app to API 26, and notifications are no longer working, without even changing the code.

```<code>val notification = NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("Title")
                .setContentText("Text")
                .build()
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(1, notification)
</code>```

Why isn't it working? Was there some change to the API that I'm not aware of?

答:
From the documentation:

Android O introduces notification channels to provide a unified system to help users manage notifications. When you target Android O, you must implement one or more notification channels to display notifications to your users. If you don't target Android O, your apps behave the same as they do on Android 7.0 when running on Android O devices.

(emphasis added)

You do not seem to be associating this Notification with a channel.

Body:
I recently updated my app to API 26, and notifications are no longer working, without even changing the code.

val notification = NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("Title")
                .setContentText("Text")
                .build()
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(1, notification)

Why isn't it working? Was there some change to the API that I'm not aware of?


答:
Yes because you are declaring 2 time the same variable with the same name. I think you can solve your problem creating an array of Carand then use the constructor for each array field inside a for statement.</p>

```<code>Car cars[10];
for(int i=0;i<9;i++){
    cars[i]= new Car();
}
</code>```

Title: Creating multiple objects using a loop

Body:
Yes because you are declaring 2 time the same variable with the same name. I think you can solve your problem creating an array of Carand then use the constructor for each array field inside a for statement.

Car cars[10];
for(int i=0;i<9;i++){
    cars[i]= new Car();
}


问:
Convert HTML to PDF using npm html-pdf
I'm trying to convert a HTML file to PDF, using npm html-pdf, but the converted PDF is not as the HTML(the style is wrong). Can someone tell me what am I doing wrong?</p>

```<code>var pdf = require('html-pdf');
var html = fs.readFileSync('./example.html', 'utf8');

    pdf.create(html, options).toFile(folderName + '/' + fileName, function (err, res) { // if the file doesnt exist it will be created
    if (err) return console.log(err);

    console.log(res);
  });
</code>```

答:
I have implemented this but its a slightly different way to approach converting html to pdf. In the code below, I use jade (now called pug) to allow this pdf to be dynamic if it structurally wont change, just the values. In other words, it's a reusable template. Also, I did this asynchronously, which is a potential reason you are running into issues. Is there a specific reason you are writing synchronous code?

Within your code, there are a couple variables that you are not showing the definition to, so I cannot see if that's where the issue resides. If you include your code, I will be able to assist you a little more. I hope my code assists you in the meantime.

```<code>let fs = require('fs');
let path = require('path');
let jade = require('jade');
let pdf = require('html-pdf');
let filepath = path.resolve(__dirname, '../views/example.jade');
let templateVariables = {}; // If you have any to pass in
fs.readFile(filepath, 'utf8', function(err, data) {
    if (err) throw err;
    let fn = jade.compile(data);
    let html = fn(templateVariables);
    let options = {
        pageSize: 'Letter',
        marginTop: '0.5in',
        marginLeft: '0.25in',
        marginRight: '1.0in',
        marginBottom: '0.5in'
    };
    if (html) {
        pdf.create(html, options).toFile('./example.pdf', function(err, res){
            if (err) {
                console.log(err);
                cb(err);
            }
            if (res) {
                console.log('pdf res ', res);
            }
        });
    }
});
</code>```

Title: Convert HTML to PDF using npm html-pdf

Body:
I'm trying to convert a HTML file to PDF, using npm html-pdf, but the converted PDF is not as the HTML(the style is wrong). Can someone tell me what am I doing wrong?

var pdf = require('html-pdf');
var html = fs.readFileSync('./example.html', 'utf8');

    pdf.create(html, options).toFile(folderName + '/' + fileName, function (err, res) { // if the file doesnt exist it will be created
    if (err) return console.log(err);

    console.log(res);
  });

Body:
I have implemented this but its a slightly different way to approach converting html to pdf. In the code below, I use jade (now called pug) to allow this pdf to be dynamic if it structurally wont change, just the values. In other words, it's a reusable template. Also, I did this asynchronously, which is a potential reason you are running into issues. Is there a specific reason you are writing synchronous code?

Within your code, there are a couple variables that you are not showing the definition to, so I cannot see if that's where the issue resides. If you include your code, I will be able to assist you a little more. I hope my code assists you in the meantime.

let fs = require('fs');
let path = require('path');
let jade = require('jade');
let pdf = require('html-pdf');
let filepath = path.resolve(__dirname, '../views/example.jade');
let templateVariables = {}; // If you have any to pass in
fs.readFile(filepath, 'utf8', function(err, data) {
    if (err) throw err;
    let fn = jade.compile(data);
    let html = fn(templateVariables);
    let options = {
        pageSize: 'Letter',
        marginTop: '0.5in',
        marginLeft: '0.25in',
        marginRight: '1.0in',
        marginBottom: '0.5in'
    };
    if (html) {
        pdf.create(html, options).toFile('./example.pdf', function(err, res){
            if (err) {
                console.log(err);
                cb(err);
            }
            if (res) {
                console.log('pdf res ', res);
            }
        });
    }
});


问:
Problems understanding error building Java Shim Client JAR
When building the Java shim client JAR I have come across following error message. However, I am new at this and don't quite understand the message. Anyone could help to explain, and guide to further reading to resolve this? Appreciate any suggestions. Thanks!

What went wrong:

A problem occurred configuring project ':core:chaincode:shim:java'.

  No signature of method: org.gradle.api.internal.tasks.DefaultTaskInputs.source
  () is applicable for argument types: (com.google.protobuf.gradle.ProtobufSourceD
  irectorySet_Decorated) values: [main Proto source]

Possible solutions: collect(), use([Ljava.lang.Object;)`

答: Downgrading gradle to 2.14 solved my problem.</p>


问:
Kivy button text alignment issue
I am trying to develop an email application in Kivy, basically just as an exercise to learn the in's and out's of the framework... I am trying to create the initial window and have reached a bit of a stumbling block! The idea is that it will simply display a list of emails in the inbox, much like any basic email app on a mobile device.

The problem I'm having is that I can't figure out how to get the text of each list item (which is a just a button) to align properly. Using "halign='left'" in my button will make the text align left, but only relative to each button; it's still centered within each button.

My actual app is a bit large to post, so this is a quick and dirty example I made from a stock Kivy example. (I realize this code isn't perfect... like I said quick and dirty for examples sake... it does work though!) So as you can see, the two rows of text on each button align with each other, but they don't all align overall. Can anyone suggest what I would do to make all the text align at, say, 10px from the left of each button? I did find one relative sounding item on StackOverflow, but it didn't really answer the question for example, it seemed to deal more with using images on buttons. I am new to Kivy, but I've read through the tutorials and documentation, as well as searched Google extensively - so any help would be greatly appreciated!

```<code>import kivy
kivy.require('1.0.8')

from kivy.app import App
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout

import random

class ScrollViewApp(App):

    def build(self):
        # create a default grid layout with custom width/height
        layout = GridLayout(cols=1, spacing=10, size_hint=(None, None),
                            width=Window.width)

        # when we add children to the grid layout, its size doesn't change at
        # all. we need to ensure that the height will be the minimum required to
        # contain all the childs. (otherwise, we'll child outside the bounding
        # box of the childs)
        layout.bind(minimum_height=layout.setter('height'))

        # add button into that grid
        for i in range(30):
            btn = Button(text=str(i * random.random()) + '\n' + str(i * random.random()),
                         size=(300, 40),
                         size_hint=(None, None),
                         halign='left')
            layout.add_widget(btn)

        # create a scroll view, with a size < size of the grid
        root = ScrollView(size_hint=(None, None))
        root.size = (Window.width, Window.height)
        root.center = Window.center
        root.add_widget(layout)

        return root

if __name__ == '__main__':

    ScrollViewApp().run()
</code>```

答:
If you want to avoid numbers in text.size, then try this:

text_size: self.size

Title: Kivy button text alignment issue

Body:
I am trying to develop an email application in Kivy, basically just as an exercise to learn the in's and out's of the framework... I am trying to create the initial window and have reached a bit of a stumbling block! The idea is that it will simply display a list of emails in the inbox, much like any basic email app on a mobile device.

The problem I'm having is that I can't figure out how to get the text of each list item (which is a just a button) to align properly. Using "halign='left'" in my button will make the text align left, but only relative to each button; it's still centered within each button.

My actual app is a bit large to post, so this is a quick and dirty example I made from a stock Kivy example. (I realize this code isn't perfect... like I said quick and dirty for examples sake... it does work though!) So as you can see, the two rows of text on each button align with each other, but they don't all align overall. Can anyone suggest what I would do to make all the text align at, say, 10px from the left of each button? I did find one relative sounding item on StackOverflow, but it didn't really answer the question for example, it seemed to deal more with using images on buttons. I am new to Kivy, but I've read through the tutorials and documentation, as well as searched Google extensively - so any help would be greatly appreciated!

import kivy
kivy.require('1.0.8')

from kivy.app import App
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout

import random

class ScrollViewApp(App):

    def build(self):
        # create a default grid layout with custom width/height
        layout = GridLayout(cols=1, spacing=10, size_hint=(None, None),
                            width=Window.width)

        # when we add children to the grid layout, its size doesn't change at
        # all. we need to ensure that the height will be the minimum required to
        # contain all the childs. (otherwise, we'll child outside the bounding
        # box of the childs)
        layout.bind(minimum_height=layout.setter('height'))

        # add button into that grid
        for i in range(30):
            btn = Button(text=str(i * random.random()) + '\n' + str(i * random.random()),
                         size=(300, 40),
                         size_hint=(None, None),
                         halign='left')
            layout.add_widget(btn)

        # create a scroll view, with a size < size of the grid
        root = ScrollView(size_hint=(None, None))
        root.size = (Window.width, Window.height)
        root.center = Window.center
        root.add_widget(layout)

        return root

if __name__ == '__main__':

    ScrollViewApp().run()


问:
Java: how to initialize String[]?
Error

```<code>% javac  StringTest.java
StringTest.java:4: variable errorSoon might not have been initialized
        errorSoon[0] = "Error, why?";
</code>```

Code

```<code>public class StringTest {
        public static void main(String[] args) {
                String[] errorSoon;
                errorSoon[0] = "Error, why?";
        }
}
</code>```

答:
```<code>String[] string=new String[60];
System.out.println(string.length);
</code>```

it is initialization and getting the STRING LENGTH code in very simple way for beginners

Title: Java: how to initialize String[]?

Body:
Error

% javac  StringTest.java
StringTest.java:4: variable errorSoon might not have been initialized
        errorSoon[0] = "Error, why?";

Code

public class StringTest {
        public static void main(String[] args) {
                String[] errorSoon;
                errorSoon[0] = "Error, why?";
        }
}

Body:
String[] string=new String[60];
System.out.println(string.length);

it is initialization and getting the STRING LENGTH code in very simple way for beginners


问:
How to scroll the terminal emulator in neovim?
With :vsplit | te <command> I run a command in the terminal emulator of neovim  in a vertical split. But how can I scroll its output? When I press a key, the split window is closed again.

For illustrational purpose, lets take the command :vsplit | te ls -lah /usr/lib/ which produces a long output in the split window. How can I now scroll up in this split window in order to see a bit more of the output? I found out that it is possible with the mouse-wheel when you use set mouse=a, but I don't like to use the mouse.

答:
According to the Neovim documentation:

Terminal-mode has its own |:tnoremap| namespace for mappings, this can be used to automate any terminal interaction.

Therefore, you can map whatever keys or combinations you want.

Additionally, you can scroll the terminal window by using PgUp and PgDown. On a full keyboard those keys should be available, on a laptop one it's often available through fn↑ and fn↓.

Update:

Some additional configuration options regarding Terminal-mode.

```<code>if has("nvim")
  " Make escape work in the Neovim terminal.
  tnoremap <Esc> <C-\><C-n>

  " Make navigation into and out of Neovim terminal splits nicer.
  tnoremap <C-h> <C-\><C-N><C-w>h
  tnoremap <C-j> <C-\><C-N><C-w>j
  tnoremap <C-k> <C-\><C-N><C-w>k
  tnoremap <C-l> <C-\><C-N><C-w>l

  " I like relative numbering when in normal mode.
  autocmd TermOpen * setlocal conceallevel=0 colorcolumn=0 relativenumber

  " Prefer Neovim terminal insert mode to normal mode.
  autocmd BufEnter term://* startinsert
endif
</code>```

Body:
According to the Neovim documentation:

Terminal-mode has its own |:tnoremap| namespace for mappings, this can be used to automate any terminal interaction.

Therefore, you can map whatever keys or combinations you want.

Additionally, you can scroll the terminal window by using PgUp and PgDown. On a full keyboard those keys should be available, on a laptop one it's often available through fn↑ and fn↓.

Update:

Some additional configuration options regarding Terminal-mode.

if has("nvim")
  " Make escape work in the Neovim terminal.
  tnoremap <Esc> <C-\><C-n>

  " Make navigation into and out of Neovim terminal splits nicer.
  tnoremap <C-h> <C-\><C-N><C-w>h
  tnoremap <C-j> <C-\><C-N><C-w>j
  tnoremap <C-k> <C-\><C-N><C-w>k
  tnoremap <C-l> <C-\><C-N><C-w>l

  " I like relative numbering when in normal mode.
  autocmd TermOpen * setlocal conceallevel=0 colorcolumn=0 relativenumber

  " Prefer Neovim terminal insert mode to normal mode.
  autocmd BufEnter term://* startinsert
endif


问:
Need Help Creating runnable Jar file for a Java FX Application
I am having an issue with trying to create a runnable Jar file for a Java FX Application I built using Eclipse Neon and Java 1.8.  When I attempt to generate the Runnable Jar from Eclipse via the Runnable Jar File Specification dialog box, I get the error message: "Could not find main method from given launch configuration."

I am specifying the main class in the "Launch Configuration" pull down menu.

Appreciate any help with this!

Thanks!

答:
You can fix this by adding a public void main() defined within your application, thusly:</p>

```<code>public class myApplication extends Application
{
  public static void main(String[] args)
  {
    launch(args);
  }

  public void start( Stage stage ) throws Exception
  {
    ...
  }
}
</code>```

Body:
You can fix this by adding a public void main() defined within your application, thusly:

public class myApplication extends Application
{
  public static void main(String[] args)
  {
    launch(args);
  }

  public void start( Stage stage ) throws Exception
  {
    ...
  }
}


问:
How can i use 'parallel' option in jenkins pipeline in the 'post' section?
I looked at many pipeline examples and how to write the post build section in a pipeline script. But never got my answer i was looking for.
I have 4 jobs - say Job A,B,C and D. I want job A to run first, and if successful it should trigger Job B,C,D in parallel. If Job A fails, it should trigger only Job B. Something like below:

```<code>pipeline {
    agent any

stages {
    stage('Build_1') {
        steps {
            sh '''
               Build Job A
            '''
        }
    }

post {
    failure {
        sh '''
            Build Job B
        '''
    }
    success {
         sh '''
             Build Job B,C,D in parallel
         '''
    }
}
}
</code>```

I tried using 'parallel' option in post section but it gave me errors. Is there a way to build Job B,C,D in parallel, in the post 'success' section?

Thanks in advance!

答:
The error message is quiet clear about this:

Invalid step "parallel" used - not allowed in this context - The
  parallel step can only be used as the only top-level step in a stages
  step

The more restrictive declarative syntax does not allow the usage of parallel in thw post section at the moment.

If you don't want to switch to the scripted syntax, another option that should work: Build the jobs B,C,D in parallel in a second stage and move the  the failure condition in the post section of your first stage. As a result job B,C,D will run if A is successful. If A is not successful only job B will run.

```<code>pipeline {
    agent any

    stages {
        stage('one') {
            steps {
                // run job A
            }
            post {
                failure {
                    // run job B
                }
            }
        }
        stage('two') {
            steps {
                parallel(
                     // run job B, C, D
                )

            }
        }
    }
}
</code>```

Body:
I looked at many pipeline examples and how to write the post build section in a pipeline script. But never got my answer i was looking for.
I have 4 jobs - say Job A,B,C and D. I want job A to run first, and if successful it should trigger Job B,C,D in parallel. If Job A fails, it should trigger only Job B. Something like below:

pipeline {
    agent any

stages {
    stage('Build_1') {
        steps {
            sh '''
               Build Job A
            '''
        }
    }

post {
    failure {
        sh '''
            Build Job B
        '''
    }
    success {
         sh '''
             Build Job B,C,D in parallel
         '''
    }
}
}

I tried using 'parallel' option in post section but it gave me errors. Is there a way to build Job B,C,D in parallel, in the post 'success' section?

Thanks in advance!

Body:
The error message is quiet clear about this:

Invalid step "parallel" used - not allowed in this context - The
  parallel step can only be used as the only top-level step in a stages
  step

The more restrictive declarative syntax does not allow the usage of parallel in thw post section at the moment.

If you don't want to switch to the scripted syntax, another option that should work: Build the jobs B,C,D in parallel in a second stage and move the  the failure condition in the post section of your first stage. As a result job B,C,D will run if A is successful. If A is not successful only job B will run.

pipeline {
    agent any

    stages {
        stage('one') {
            steps {
                // run job A
            }
            post {
                failure {
                    // run job B
                }
            }
        }
        stage('two') {
            steps {
                parallel(
                     // run job B, C, D
                )

            }
        }
    }
}


问:
Adding a custom domain name with surge.sh
I'm a newbie in domain names, DNS etc.

I'm using surge.sh for deploying my app. Now I want to add a custom domain, that I registered using transIP, and I can't get it working. I set the IP address to 45.55.110.124, as they explain here. All together, I entered the following settings:

Name: *

TTL: 1 min

Type: A

Address: 45.55.110.124

And another one, exactly the same but then using name @:

Name: @

TTL: 1 min

Type: A

Address: 45.55.110.124

I created a test page that contains hello domain, inside a simple html file. Now, I deployed the page by moving to the folder that contains the html file and doing: surge ./ mydomain.io.

I waited over 5 minutes and nothing is changing.
Now, my questions are:

What am I doing wrong?

My domain provider suggests that I also use an IPv6 address, but which one should I use for Surge?

Why is there an option of setting TTL longer than 1 minute, who wants to wait longer before their deploy comes online?

答:
For starters, you want to use the CNAME instead of A record if possible. The reason for this is that their IP address can possibly change out from under you when infrastructure changes / updates / re-deploys. If possible, remove the A records and create CNAME records pointing to na-west1.surge.sh. instead.

Next, assuming that they want you to point to the same IP as na-west1.surge.sh resolves to, that IP is different from the documentation (possible even due to my previous explanation). You can ping the domain or use the host utility to get the current IP address:

```<code>$ host na-west1.surge.sh
na-west1.surge.sh has address 138.197.235.123
</code>```

Armed with this information, try changing to CNAME records first. If this isn't possible, then use the updated IP address that you get from resolving the their CNAME.

Body:
For starters, you want to use the CNAME instead of A record if possible. The reason for this is that their IP address can possibly change out from under you when infrastructure changes / updates / re-deploys. If possible, remove the A records and create CNAME records pointing to na-west1.surge.sh. instead.

Next, assuming that they want you to point to the same IP as na-west1.surge.sh resolves to, that IP is different from the documentation (possible even due to my previous explanation). You can ping the domain or use the host utility to get the current IP address:

$ host na-west1.surge.sh
na-west1.surge.sh has address 138.197.235.123

Armed with this information, try changing to CNAME records first. If this isn't possible, then use the updated IP address that you get from resolving the their CNAME.


问:
very simple delegate musing
Sometimes the simplest questions make me love C/C++ and C# more and more.

Today sitting on the bus musing aout delegates I remembered
reading somwhere you don't need to use the new keyword when instaniating
a new delegate.

For example:

```<code>    public static void SomeMethod(string message)
    {
      ...
    }

    ...

   public delegate void TestDelgate(string message); //Define a delegate

    ...........

   //create a new instance ..METHOD 1
   TestDelgate t = new TestDelgate(SomeMethod);

   //OR another way to create a new instance ..METHOD 2
   TestDelgate t = SomeMethod;   //create a new instance ..METHOD 2
</code>```

So todays questions are

What happens under the hood in method 2. Does the compiler expand method 2 into method 1, hence writing TestDelgate t = SomeMethod; is just a shortcut for
TestDelgate t = new TestDelgate(SomeMethod);, or is there another reason for the exsitence of method 2

Do you guys think method 1 or method 2 is better for readability (this is a subjective question, but I'd just like to get a unscientific feel of general opinion of stackoverflow :-))

答: One advantage of the 'new' syntax is that it informed the programmer that a new object was being allocated; if it would be desirable to avoid repeatedly creating new identical delegates, one could pull the delegate out to a field.  I know that in fact one is allowed to use one delegate to subscribe and another to unsubscribe, but to me that feels wrong.  Storing to a field the delegate used to subscribe, and then unsubscribing using that same delegate feels cleaner.  Cleaner still, IMHO, would have been if the act of subscribing would have returned a MethodInvoker which, when called, would unsubscribe (in which case an "event" would simply be a function that accepted an EventHandler and returned a MethodInvoker), but that's not how .net events work.</p>

Title: very simple delegate musing

Body:
Sometimes the simplest questions make me love C/C++ and C# more and more.

Today sitting on the bus musing aout delegates I remembered
reading somwhere you don't need to use the new keyword when instaniating
a new delegate.

For example:

    public static void SomeMethod(string message)
    {
      ...
    }

    ...

   public delegate void TestDelgate(string message); //Define a delegate

    ...........

   //create a new instance ..METHOD 1
   TestDelgate t = new TestDelgate(SomeMethod);

   //OR another way to create a new instance ..METHOD 2
   TestDelgate t = SomeMethod;   //create a new instance ..METHOD 2

So todays questions are

What happens under the hood in method 2. Does the compiler expand method 2 into method 1, hence writing TestDelgate t = SomeMethod; is just a shortcut for
TestDelgate t = new TestDelgate(SomeMethod);, or is there another reason for the exsitence of method 2

Do you guys think method 1 or method 2 is better for readability (this is a subjective question, but I'd just like to get a unscientific feel of general opinion of stackoverflow :-))


问:
C program working and stop running at the same time?

How can I run this program without any crash #C #CoFactors

This program is about finding cofactors of a number it is working but at the same time this program crashes after showing the output. Please take a look.

Here is the program.

```<code>int coFactors(int number,int divisor)
{
if(number%divisor==0)
{
    printf("%d ",divisor);
    number /= divisor;
    coFactors(number,divisor);
}
else if(number==divisor-1)
{
    return;
}
else
{
    coFactors(number,++divisor);
}
             }

int main()
{
int num;
printf("Enter number:");
scanf("%d",&num);
coFactors(num,2);

return 0;
}
</code>```

答:
seems below condition is wrong:

```<code>else if(number==divisor-1)
</code>```

it should be:

```<code>else if(number < (divisor))
</code>```

My earlier post would have avoided crashed but to get correct Co factor condition should have been like edited.

BLUEPIXY has suggested correctly.

Body:
How can I run this program without any crash #C #CoFactors

This program is about finding cofactors of a number it is working but at the same time this program crashes after showing the output. Please take a look.

Here is the program.

int coFactors(int number,int divisor)
{
if(number%divisor==0)
{
    printf("%d ",divisor);
    number /= divisor;
    coFactors(number,divisor);
}
else if(number==divisor-1)
{
    return;
}
else
{
    coFactors(number,++divisor);
}
             }

int main()
{
int num;
printf("Enter number:");
scanf("%d",&num);
coFactors(num,2);

return 0;
}

Body:
seems below condition is wrong:

else if(number==divisor-1)

it should be:

else if(number < (divisor))

My earlier post would have avoided crashed but to get correct Co factor condition should have been like edited.

BLUEPIXY has suggested correctly.


问:
How to assert that a method can only be called if the calling object is a const value?
for optimization purposes I am writing a class in which the copy operator passes the internals of the class by reference.

However I want to be able to write two copy operators, one that accepts const values and can only be called by a const object and a non-const variant that then can call non-const methods.

IE I would like something similar to...

```<code>myClass& operator= (const myClass& copy_to, const myClass& copy_from);
myClass& operator= (myClass& copy_to, myClass& copy_from);
</code>```

However in C++ the copy operator must be non-static and can only accept 1 parameter. How can I ensure that the copy operator accepting a const parameter only be called from a const calling object?

If there are any issues with my question please comment so I may improve*

答:
It's important to respect the concept. The user doesn't expect a modified source object after a copy operation. This is a postcondition to the concept CopyAssignable.

```<code>t = v //postcondition: The value of v is unchanged.
</code>```

The const modifier, for the source parameter, explicits this requirement to the user: a read-only object.

Maybe a move ctor ou move assignment operator(MoveAssignable) can serve you.
If not, I think so it's a good idea to leave out the copy concept here.

Body:
for optimization purposes I am writing a class in which the copy operator passes the internals of the class by reference.

However I want to be able to write two copy operators, one that accepts const values and can only be called by a const object and a non-const variant that then can call non-const methods.

IE I would like something similar to...

myClass& operator= (const myClass& copy_to, const myClass& copy_from);
myClass& operator= (myClass& copy_to, myClass& copy_from);

However in C++ the copy operator must be non-static and can only accept 1 parameter. How can I ensure that the copy operator accepting a const parameter only be called from a const calling object?

If there are any issues with my question please comment so I may improve*

Body:
It's important to respect the concept. The user doesn't expect a modified source object after a copy operation. This is a postcondition to the concept CopyAssignable.

t = v //postcondition: The value of v is unchanged.

The const modifier, for the source parameter, explicits this requirement to the user: a read-only object.

Maybe a move ctor ou move assignment operator(MoveAssignable) can serve you.
If not, I think so it's a good idea to leave out the copy concept here.


问:
Git switch master and project branch
I have a project branch and a master branch in my Git project. I would like to make the project branch become the master branch. However, I would like to keep the old master branch as a side branch. How can I do this?

Current:

```<code>----------- master
    \______ project
</code>```

What I want:

```<code>-------------------- project (new master branch)
    \______ master (old)
</code>```

答:
```<code>// If you want to still retain the old master branch, then create a tag or new branch on that particular commit so you don't loose it:

git checkout master

git checkout -b master-old

// now if you want to go back to the old master branch you can checkout the master-old branch.

// from here you can simply reset the master branch to the project branch

git checkout master

git reset --hard project

git checkout master

// now your master branch and the project branch should be pointing to the same commit. you can continue developing on your master branch. you may even want to delete the project branch. up to you.
</code>```

EDIT: Don't do this if it's a public repo!!

Title: Git switch master and project branch

Body:
I have a project branch and a master branch in my Git project. I would like to make the project branch become the master branch. However, I would like to keep the old master branch as a side branch. How can I do this?

Current:

----------- master
    \______ project

What I want:

-------------------- project (new master branch)
    \______ master (old)

Body:
// If you want to still retain the old master branch, then create a tag or new branch on that particular commit so you don't loose it:

git checkout master

git checkout -b master-old

// now if you want to go back to the old master branch you can checkout the master-old branch.

// from here you can simply reset the master branch to the project branch

git checkout master

git reset --hard project

git checkout master

// now your master branch and the project branch should be pointing to the same commit. you can continue developing on your master branch. you may even want to delete the project branch. up to you.

EDIT: Don't do this if it's a public repo!!


问:
Cancel WebClient DownloadTask Async
I have a WebClient which I use to download a file.

This is my code, in which I have a ProgressDialog and a WebClient to download:

```<code>dialog = new ProgressDialog(mContext);
                dialog.SetProgressStyle(Android.App.ProgressDialogStyle.Horizontal);
                dialog.SetCancelable(true);
                dialog.SetCanceledOnTouchOutside(true);

                dialog.Show();// showing a dialog

                string url = "myurl";

                WebClient webClient = new WebClient();
                webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
                dialog.CancelEvent += (s, e) =>
                {
                    webClient.CancelAsync();
       //----------------------- Crashes Here
                };

                try
                {
                    bytes = await webClient.DownloadDataTaskAsync(url);
                }
                catch (TaskCanceledException)
                {
                    return;
                }
                catch (Exception a)
                {
                    return;
                }
</code>```

How do I cancel the download in the middle?

```<code>webClient.CancelAsync();
</code>```

throws an exception:

```<code>Object reference not set to an instance of an object
</code>```

答:
The problem was in exception handling code when inner exception was null. To make it work just checking for inner exception using "?"</p>

```<code>dialog.CancelEvent += (s, e) =>
                    {
                        webClient.CancelAsync();
                    };

                    try
                    {
                        bytes = await webClient.DownloadDataTaskAsync(url);
                    }
                    catch (WebException wex)
                    {
                        if (wex.Status == WebExceptionStatus.RequestCanceled)
                            return;
                        Toast.MakeText(mContext, wex.Message + "," + wex?.InnerException?.Message, ToastLength.Long).Show();
                        dialog.Progress = 0;
                        return;
                    }
                    catch (TaskCanceledException)
                    {
                        return;
                    }
                    catch (Exception a)
                    {
                        Toast.MakeText(mContext, a.Message + "," + a?.InnerException?.Message, ToastLength.Long).Show();
                        dialog.Progress = 0;
                        return;
                    }
</code>```

Title: Cancel WebClient DownloadTask Async

Body:
I have a WebClient which I use to download a file.

This is my code, in which I have a ProgressDialog and a WebClient to download:

dialog = new ProgressDialog(mContext);
                dialog.SetProgressStyle(Android.App.ProgressDialogStyle.Horizontal);
                dialog.SetCancelable(true);
                dialog.SetCanceledOnTouchOutside(true);

                dialog.Show();// showing a dialog

                string url = "myurl";

                WebClient webClient = new WebClient();
                webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
                dialog.CancelEvent += (s, e) =>
                {
                    webClient.CancelAsync();
       //----------------------- Crashes Here
                };

                try
                {
                    bytes = await webClient.DownloadDataTaskAsync(url);
                }
                catch (TaskCanceledException)
                {
                    return;
                }
                catch (Exception a)
                {
                    return;
                }

How do I cancel the download in the middle?

webClient.CancelAsync();

throws an exception:

Object reference not set to an instance of an object

Body:
The problem was in exception handling code when inner exception was null. To make it work just checking for inner exception using "?"

dialog.CancelEvent += (s, e) =>
                    {
                        webClient.CancelAsync();
                    };

                    try
                    {
                        bytes = await webClient.DownloadDataTaskAsync(url);
                    }
                    catch (WebException wex)
                    {
                        if (wex.Status == WebExceptionStatus.RequestCanceled)
                            return;
                        Toast.MakeText(mContext, wex.Message + "," + wex?.InnerException?.Message, ToastLength.Long).Show();
                        dialog.Progress = 0;
                        return;
                    }
                    catch (TaskCanceledException)
                    {
                        return;
                    }
                    catch (Exception a)
                    {
                        Toast.MakeText(mContext, a.Message + "," + a?.InnerException?.Message, ToastLength.Long).Show();
                        dialog.Progress = 0;
                        return;
                    }


问:
Separately rotating 2 texture coordinates sets for the same object
I've given this a go for a while, but I haven't been able to get favorable results. Basically, I have a sphere with 2 textures. One is blended on top with other and the idea is to have it be a face environment mapping. I want one texture to rotate with the sphere and the other to stay fixed to the initial texture coordinates.

I have tried rotating the GL_TEXTURE matrix of one texture and resetting the other, but this doesn't really do the trick because the texture mapping isn't right when it's rotated certain ways.

Anyone know how i can rotate only one set of texture coordinates and keep the other fixed?

Here's my render code at the moment:

```<code>glColor4f(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();

glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);

glClientActiveTexture( GL_TEXTURE0);
glActiveTexture( GL_TEXTURE0);
glBindTexture( GL_TEXTURE_2D, tex[0]);
glEnableClientState( GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(TexturedVertexData3D), &SphereVertexData[0].texCoord);

glMatrixMode(GL_TEXTURE);
glPushMatrix();
glTranslatef(0, 0, -4.5f);
glRotatef(.00001, .00001, .0, .0);

glClientActiveTexture( GL_TEXTURE1);
glActiveTexture( GL_TEXTURE1);
glEnable( GL_TEXTURE_2D);
glBindTexture( GL_TEXTURE_2D, tex[1]);
glEnableClientState( GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(TexturedVertexData3D), &SphereVertexData[0].texCoord);

glPopMatrix();

glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(0, 0, -4.5f);

glVertexPointer(3, GL_FLOAT, sizeof(TexturedVertexData3D), &SphereVertexData[0].vertex);
glNormalPointer(GL_FLOAT, sizeof(TexturedVertexData3D), &SphereVertexData[0].normal);
glDrawArrays(GL_TRIANGLES, 0, kSphereNumberOfVertices);

glPopMatrix();

glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);

rotation += .0001;
</code>```

If anyone needs to see more of what is going on just let me know.

答: You could use two spheres and only issue the glRotatef() to the sphere with the texture that you want rotating. The other sphere would just receive the corresponding glTranslatef() commands. If you are using the alpha channel to blend the textures it should work the same.</p>

Body:
I've given this a go for a while, but I haven't been able to get favorable results. Basically, I have a sphere with 2 textures. One is blended on top with other and the idea is to have it be a face environment mapping. I want one texture to rotate with the sphere and the other to stay fixed to the initial texture coordinates.

I have tried rotating the GL_TEXTURE matrix of one texture and resetting the other, but this doesn't really do the trick because the texture mapping isn't right when it's rotated certain ways.

Anyone know how i can rotate only one set of texture coordinates and keep the other fixed?

Here's my render code at the moment:

glColor4f(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();

glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);

glClientActiveTexture( GL_TEXTURE0);
glActiveTexture( GL_TEXTURE0);
glBindTexture( GL_TEXTURE_2D, tex[0]);
glEnableClientState( GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(TexturedVertexData3D), &SphereVertexData[0].texCoord);

glMatrixMode(GL_TEXTURE);
glPushMatrix();
glTranslatef(0, 0, -4.5f);
glRotatef(.00001, .00001, .0, .0);

glClientActiveTexture( GL_TEXTURE1);
glActiveTexture( GL_TEXTURE1);
glEnable( GL_TEXTURE_2D);
glBindTexture( GL_TEXTURE_2D, tex[1]);
glEnableClientState( GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(TexturedVertexData3D), &SphereVertexData[0].texCoord);

glPopMatrix();

glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(0, 0, -4.5f);

glVertexPointer(3, GL_FLOAT, sizeof(TexturedVertexData3D), &SphereVertexData[0].vertex);
glNormalPointer(GL_FLOAT, sizeof(TexturedVertexData3D), &SphereVertexData[0].normal);
glDrawArrays(GL_TRIANGLES, 0, kSphereNumberOfVertices);

glPopMatrix();

glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);

rotation += .0001;

If anyone needs to see more of what is going on just let me know.


问:
How can I clone an entire Realm?
I've created an incorrect primary key in Realm and now I wish to remove it, however the platform forbids it claiming:

```<code>The following changes cannot be made in additive-only schema mode:
- Primary Key for class 'Entry' has been removed."
</code>```

This means I would need to reset the entire db. I wish to copy the records to the new database (or solve this otherwise) Any ideas?

答:
The reason that only additive changes are allowed is that allowing destructive changes would make changes un-mergeable to older devices not yet upgraded. We might allow this in future by disallowing sync to older clients, but for now you will have to work around it.

You have 2 options:

1) Create a new Realm, like my-realm-v2 and copy all data over, with the changes needed. This would have a similar effect to disallowing synchronization to older clients.

2) Create a new class MyClassV2 in the original Realm and just copy the class that changed.

Title: How can I clone an entire Realm?

Body:
I've created an incorrect primary key in Realm and now I wish to remove it, however the platform forbids it claiming:

The following changes cannot be made in additive-only schema mode:
- Primary Key for class 'Entry' has been removed."

This means I would need to reset the entire db. I wish to copy the records to the new database (or solve this otherwise) Any ideas?


问:
Reacting to user input
I'm currently busy with a bot that searches an area around the user. The user has the ability to increase the search radius. This is the code I'm using to handle the users input, so far the "Yes" bit of the code works, however I'm not sure how to re-trigger the search.

The search is initially triggered by a luis intent so I thought that would probably be the easiest way to navigate to the different tasks in the bot. However I'm not sure how to send a message to the bot programmatically / trigger a luis intent from code.

```<code>[LuisIntent("Stores")]
        public async Task Stores(IDialogContext context, LuisResult result)
        {
            var reply = context.MakeMessage();
            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            reply.Attachments = new List<Attachment>();
            List<CardImage> images = new List<CardImage>();

            InfoClass IC = new InfoClass();
            latitude = "-29.794618";
            longitude = "30.823497";
            LocationObject[] StoreLocations = IC.NearBy(latitude, longitude, Radius, context);
            int count = StoreLocations.Length;
            for (int z = 0; z < count; z++)
            {
                CardImage Ci = new CardImage("https://maps.googleapis.com/maps/api/staticmap?size=764x400&center=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude + "&zoom=15&markers=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude);
                images.Add(Ci);

                HeroCard hc = new HeroCard()
                {
                    Title = StoreLocations[z].StoreName,
                    Subtitle = StoreLocations[z].Subtitle,
                    Images = new List<CardImage> { images[z] },
                    Buttons = new List<CardAction>()
                };

                CardAction ca = new CardAction()
                {
                    Title = "Show Me",
                    Type = "openUrl",
                    Value = "https://www.google.co.za/maps/search/" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude
                };
                hc.Buttons.Add(ca);
                reply.Attachments.Add(hc.ToAttachment());
            }
            await context.PostAsync(reply);
            PromptDialog.Confirm(context, promtDecision, "Would You Like To Change The Search Radius ?", attempts: 100);
        }
    async Task promtDecision(IDialogContext context, IAwaitable<string> userInput)
    {
        string inputText = await userInput;
        if (inputText.Equals("yes") || inputText.Equals("y"))
        {
            RadiusPromt(context);
        }
        else
        {
            StartUp(context, null).Start();
        }
    }
    void RadiusPromt(IDialogContext context)
    {
        PromptDialog.Number(context, AfterPromptMethod, "Please Enter Search Radius (In Kilometers)", attempts: 100);
    }
    async Task AfterPromptMethod(IDialogContext context, IAwaitable<long> userInput)
    {
        int Radius = Convert.ToInt32(await userInput);
        await context.PostAsync("Store Locations");
    }
}
</code>```

答:
Based on what I understood from your problem, here is an implementation calling a method that I called SearchInArea, using an int parameter.

This method is called from 2 places:

when your LuisIntent Stores is recognized

when you come back avec changing the radius value

Code:

```<code>[LuisIntent("Stores")]
public async Task Stores(IDialogContext context, LuisResult result)
{
    var defaultRadius = 10;
    await SearchInArea(context, defaultRadius);
}

private async Task SearchInArea(IDialogContext context, int radius)
{
    var reply = context.MakeMessage();
    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
    reply.Attachments = new List<Attachment>();
    List<CardImage> images = new List<CardImage>();

    InfoClass IC = new InfoClass();
    latitude = "-29.794618";
    longitude = "30.823497";
    LocationObject[] StoreLocations = IC.NearBy(latitude, longitude, radius, context);
    int count = StoreLocations.Length;
    for (int z = 0; z < count; z++)
    {
        CardImage Ci = new CardImage("https://maps.googleapis.com/maps/api/staticmap?size=764x400&center=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude + "&zoom=15&markers=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude);
        images.Add(Ci);

        HeroCard hc = new HeroCard()
        {
            Title = StoreLocations[z].StoreName,
            Subtitle = StoreLocations[z].Subtitle,
            Images = new List<CardImage> { images[z] },
            Buttons = new List<CardAction>()
        };

        CardAction ca = new CardAction()
        {
            Title = "Show Me",
            Type = "openUrl",
            Value = "https://www.google.co.za/maps/search/" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude
        };
        hc.Buttons.Add(ca);
        reply.Attachments.Add(hc.ToAttachment());
    }

    await context.PostAsync(reply);
    PromptDialog.Confirm(context, PromptDecision, "Would You Like To Change The Search Radius ?", attempts: 100);
}

private async Task PromptDecision(IDialogContext context, IAwaitable<bool> userInput)
{
    var userBoolChoice = await userInput;
    if (userBoolChoice)
    {
        RadiusPromt(context);
    }
    else
    {
        StartUp(context, null).Start();
    }
}

private void RadiusPromt(IDialogContext context)
{
    PromptDialog.Number(context, AfterPromptMethod, "Please Enter Search Radius (In Kilometers)", attempts: 100);
}

private async Task AfterPromptMethod(IDialogContext context, IAwaitable<long> userInput)
{
    int radius = Convert.ToInt32(await userInput);
    await SearchInArea(context, radius);
}
</code>```

Title: Reacting to user input

Body:
I'm currently busy with a bot that searches an area around the user. The user has the ability to increase the search radius. This is the code I'm using to handle the users input, so far the "Yes" bit of the code works, however I'm not sure how to re-trigger the search.

The search is initially triggered by a luis intent so I thought that would probably be the easiest way to navigate to the different tasks in the bot. However I'm not sure how to send a message to the bot programmatically / trigger a luis intent from code.

[LuisIntent("Stores")]
        public async Task Stores(IDialogContext context, LuisResult result)
        {
            var reply = context.MakeMessage();
            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            reply.Attachments = new List<Attachment>();
            List<CardImage> images = new List<CardImage>();

            InfoClass IC = new InfoClass();
            latitude = "-29.794618";
            longitude = "30.823497";
            LocationObject[] StoreLocations = IC.NearBy(latitude, longitude, Radius, context);
            int count = StoreLocations.Length;
            for (int z = 0; z < count; z++)
            {
                CardImage Ci = new CardImage("https://maps.googleapis.com/maps/api/staticmap?size=764x400&center=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude + "&zoom=15&markers=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude);
                images.Add(Ci);

                HeroCard hc = new HeroCard()
                {
                    Title = StoreLocations[z].StoreName,
                    Subtitle = StoreLocations[z].Subtitle,
                    Images = new List<CardImage> { images[z] },
                    Buttons = new List<CardAction>()
                };

                CardAction ca = new CardAction()
                {
                    Title = "Show Me",
                    Type = "openUrl",
                    Value = "https://www.google.co.za/maps/search/" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude
                };
                hc.Buttons.Add(ca);
                reply.Attachments.Add(hc.ToAttachment());
            }
            await context.PostAsync(reply);
            PromptDialog.Confirm(context, promtDecision, "Would You Like To Change The Search Radius ?", attempts: 100);
        }
    async Task promtDecision(IDialogContext context, IAwaitable<string> userInput)
    {
        string inputText = await userInput;
        if (inputText.Equals("yes") || inputText.Equals("y"))
        {
            RadiusPromt(context);
        }
        else
        {
            StartUp(context, null).Start();
        }
    }
    void RadiusPromt(IDialogContext context)
    {
        PromptDialog.Number(context, AfterPromptMethod, "Please Enter Search Radius (In Kilometers)", attempts: 100);
    }
    async Task AfterPromptMethod(IDialogContext context, IAwaitable<long> userInput)
    {
        int Radius = Convert.ToInt32(await userInput);
        await context.PostAsync("Store Locations");
    }
}

Body:
Based on what I understood from your problem, here is an implementation calling a method that I called SearchInArea, using an int parameter.

This method is called from 2 places:

when your LuisIntent Stores is recognized

when you come back avec changing the radius value

Code:

[LuisIntent("Stores")]
public async Task Stores(IDialogContext context, LuisResult result)
{
    var defaultRadius = 10;
    await SearchInArea(context, defaultRadius);
}

private async Task SearchInArea(IDialogContext context, int radius)
{
    var reply = context.MakeMessage();
    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
    reply.Attachments = new List<Attachment>();
    List<CardImage> images = new List<CardImage>();

    InfoClass IC = new InfoClass();
    latitude = "-29.794618";
    longitude = "30.823497";
    LocationObject[] StoreLocations = IC.NearBy(latitude, longitude, radius, context);
    int count = StoreLocations.Length;
    for (int z = 0; z < count; z++)
    {
        CardImage Ci = new CardImage("https://maps.googleapis.com/maps/api/staticmap?size=764x400&center=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude + "&zoom=15&markers=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude);
        images.Add(Ci);

        HeroCard hc = new HeroCard()
        {
            Title = StoreLocations[z].StoreName,
            Subtitle = StoreLocations[z].Subtitle,
            Images = new List<CardImage> { images[z] },
            Buttons = new List<CardAction>()
        };

        CardAction ca = new CardAction()
        {
            Title = "Show Me",
            Type = "openUrl",
            Value = "https://www.google.co.za/maps/search/" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude
        };
        hc.Buttons.Add(ca);
        reply.Attachments.Add(hc.ToAttachment());
    }

    await context.PostAsync(reply);
    PromptDialog.Confirm(context, PromptDecision, "Would You Like To Change The Search Radius ?", attempts: 100);
}

private async Task PromptDecision(IDialogContext context, IAwaitable<bool> userInput)
{
    var userBoolChoice = await userInput;
    if (userBoolChoice)
    {
        RadiusPromt(context);
    }
    else
    {
        StartUp(context, null).Start();
    }
}

private void RadiusPromt(IDialogContext context)
{
    PromptDialog.Number(context, AfterPromptMethod, "Please Enter Search Radius (In Kilometers)", attempts: 100);
}

private async Task AfterPromptMethod(IDialogContext context, IAwaitable<long> userInput)
{
    int radius = Convert.ToInt32(await userInput);
    await SearchInArea(context, radius);
}


问:
How may I dynamically insert a string into a large javascript template string in python?
Suppose a template javascript string like this:

```<code>js_string = u'function hello() { alert({0}); } function goodbye() { alert({1}); }'
</code>```

I would like to get following result:

```<code>function hello() { alert('Hello!'); } function goodbye() { alert('Goodbye!'); }
</code>```

My initial idea was to use the .format() method, which resulted in a KeyError due to the arbitrary curly braces. I then had a look at this question and replaced said curly braces with double curly braces. Although this produces the desired result, I cannot use it, as I'm working with a rather large javascript template and am not up for changing each and every single curly brace.

I have also tried the .replace() function:

```<code>js_string.replace("{0}", repr("Hello!")).replace("{1}", repr("Goodbye!"))
</code>```

However, calling .replace() more than once seems inconvenient to me, which is why I am asking if there is any straightforward alternative for this problem.

答:
Use string interpolation with the % operator:

```<code>>>> u'function hello() { alert(%r); } function goodbye() { alert(%r); }' % ('Hello', 'Goodbye')
"function hello() { alert('Hello'); } function goodbye() { alert('Goodbye'); }"
</code>```

Here %r means use the repr, if you want to insert the string directly use %s. %% is a literal %.

More details: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

Body:
Suppose a template javascript string like this:

js_string = u'function hello() { alert({0}); } function goodbye() { alert({1}); }'

I would like to get following result:

function hello() { alert('Hello!'); } function goodbye() { alert('Goodbye!'); }

My initial idea was to use the .format() method, which resulted in a KeyError due to the arbitrary curly braces. I then had a look at this question and replaced said curly braces with double curly braces. Although this produces the desired result, I cannot use it, as I'm working with a rather large javascript template and am not up for changing each and every single curly brace.

I have also tried the .replace() function:

js_string.replace("{0}", repr("Hello!")).replace("{1}", repr("Goodbye!"))

However, calling .replace() more than once seems inconvenient to me, which is why I am asking if there is any straightforward alternative for this problem.

Body:
Use string interpolation with the % operator:

>>> u'function hello() { alert(%r); } function goodbye() { alert(%r); }' % ('Hello', 'Goodbye')
"function hello() { alert('Hello'); } function goodbye() { alert('Goodbye'); }"

Here %r means use the repr, if you want to insert the string directly use %s. %% is a literal %.

More details: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations