问:
What are impact when Reorganize MariaDB table partition?
I have master and slave replication database.
I have a table with 10m rows. I set partition by rang monthly such as p_201701, p_201702, .. and include 'p_future'. In master, I plan to reorganize my partition 'p_future' into 'p_201711' and 'p_future'. I plan to reorganize with below query.

What are impact to my database when I run this query?

Will it prevent my table from insert, update or not?

What are impact to my replication slave?

..

```<code>ALTER TABLE tbl_history
    REORGANIZE PARTITION p_future INTO(
    PARTITION p_201711 VALUES LESS THAN (TO_DAYS('2017-12-01')),
    PARTITION p_future VALUES LESS THAN MAXVALUE
    );
</code>```

Appreciate your answer.

答:
(Sounds like you read my http://mysql.rjweb.org/doc.php/partitionmaint )

If you perform the REORGANIZE just before needing the LESS THAN '2017-12-01' partition, there should be virtually no impact.  This is because p_future should be empty, and nothing is yet storing into the new partition.

I say "virtually no impact" because there will be some brief meta locks on the table, etc., but no data to shovel around.

The technique is sort of "failsafe" because if you fail to run the query, everything continues to work.  New rows go (erroneously) into p_future, and SELECTs will find them.  Eventually, you need to run the script (and it will be slower) in order to create the new partition and move rows from p_future into it.

You tagged it with [replication], but there should be no impact on on/by replication.  For Galera, TOI should be the right way to do the ALTER.

Body:
I have master and slave replication database.
I have a table with 10m rows. I set partition by rang monthly such as p_201701, p_201702, .. and include 'p_future'. In master, I plan to reorganize my partition 'p_future' into 'p_201711' and 'p_future'. I plan to reorganize with below query.

What are impact to my database when I run this query?

Will it prevent my table from insert, update or not?

What are impact to my replication slave?

..

ALTER TABLE tbl_history
    REORGANIZE PARTITION p_future INTO(
    PARTITION p_201711 VALUES LESS THAN (TO_DAYS('2017-12-01')),
    PARTITION p_future VALUES LESS THAN MAXVALUE
    );

Appreciate your answer.


来源: stackexchange

问:
How to have a tooltip follow an element on a triggered event?
I have some problems with my code. Basically, I have a red ball and a div box for coordinates.

When I click on a document div.ball goes where I want to, but the box stays at its position. After 2nd click, ball goes where it should and the box moves to the previous position of the ball. The box goes where it should after double click on the same position.

I want the box be like a tooltip, appearing every time next to the ball.

Can you guys help me?

function menuRoll(){
    var hidden_collapse = document.getElementById("hidden_collapse");
    hidden_collapse.classList.toggle("myStyle");
}

function readPosition(ball){
    var rect = ball.getBoundingClientRect();
    var x = Math.round(rect.left) + "px";
    var y = Math.round(rect.top) + "px";
    coordinat.innerHTML = "Coordinates:"+ "
" + x + ", " + y;
    coordinat.style.top = Math.round(rect.top) - 30 + "px";
    coordinat.style.left = Math.round(rect.left) + 37 + "px";
}

window.onload = function(){
    var ball = document.getElementById('foo');
    var ball_space = document.getElementById('ball_space');
    var coordinat = document.getElementById("coordinat");
    document.addEventListener('click', function(e){

        ball.style.background = "#B40520";
        var ball_H = ball.offsetHeight;
        var ball_W = ball.offsetWidth;
        readPosition(ball);
        ball.style.transform = 'translateY('+(e.clientY-(0.5*ball_H))+'px)';
        ball.style.transform += 'translateX('+(e.clientX-(0.5*ball_W))+'px)';

    }, true);

};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#coordinat {
  transition: all 1s;
  border-radius: 5px;
  position: absolute;
  text-align: center;
  right: 5px;
  top: 5px;
  width: 150px;
  height: 30px;
  padding: 5px 5px;
  background-color: black;
  color: white;
  font-size: 0.8em;
}

#foo{
  margin: 2px;
  border-radius: 50px;
  width: 30px;
  height: 30px;
  /*background: #B40520;*/
  background: white;
  position: absolute;
  top: 0px;
  left: 0px;
  -moz-transition: transform 1s, background 1s;
  -webkit-transition: transform 1s, background 1s;
  -ms-transition: transform 1s, background 1s;
  -o-transition: transform 1s, background 1s;
  transition: transform 1s, background 1s;

}</code>```

Coordinates you will see!

```

答:
You should pass new position of ball to your redPosition() function, because this function doesn't know a position after animation. As you can find in JSFiddle I pass a new ball position to function, so now it can be calculated properly.

JS to solve your problems:

```<code>function menuRoll(){
      var hidden_collapse = document.getElementById("hidden_collapse");
      hidden_collapse.classList.toggle("myStyle");
      }

      function readPosition(ball, yPos, xPos){
        var rect = ball.getBoundingClientRect();
        var x = Math.round(xPos) + "px";
        var y = Math.round(yPos) + "px";
        coordinat.innerHTML = "Coordinates:"+ "<br>" + x + ", " + y;
        coordinat.style.top = Math.round(yPos) - 30 + "px";
        coordinat.style.left = Math.round(xPos) + 37 + "px";
      }

window.onload = function(){
  var ball = document.getElementById('foo');
  var ball_space = document.getElementById('ball_space');
  var coordinat = document.getElementById("coordinat");
  document.addEventListener('click', function(e){

    ball.style.background = "#B40520";
    var ball_H = ball.offsetHeight;
    var ball_W = ball.offsetWidth;

    var ball_new_h = e.clientY-(0.5*ball_H);
    var ball_new_w = e.clientX-(0.5*ball_W);
    readPosition(ball, ball_new_h, ball_new_w);
    ball.style.transform = 'translateY('+ ball_new_h +'px)';
    ball.style.transform += 'translateX('+ball_new_w+'px)';

  }, true);

};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some problems with my code. Basically, I have a red ball and a div box for coordinates.

When I click on a document div.ball goes where I want to, but the box stays at its position. After 2nd click, ball goes where it should and the box moves to the previous position of the ball. The box goes where it should after double click on the same position.

I want the box be like a tooltip, appearing every time next to the ball.

Can you guys help me?

function menuRoll(){
    var hidden_collapse = document.getElementById("hidden_collapse");
    hidden_collapse.classList.toggle("myStyle");
}

function readPosition(ball){
    var rect = ball.getBoundingClientRect();
    var x = Math.round(rect.left) + "px";
    var y = Math.round(rect.top) + "px";
    coordinat.innerHTML = "Coordinates:"+ "
" + x + ", " + y;
    coordinat.style.top = Math.round(rect.top) - 30 + "px";
    coordinat.style.left = Math.round(rect.left) + 37 + "px";
}

window.onload = function(){
    var ball = document.getElementById('foo');
    var ball_space = document.getElementById('ball_space');
    var coordinat = document.getElementById("coordinat");
    document.addEventListener('click', function(e){

        ball.style.background = "#B40520";
        var ball_H = ball.offsetHeight;
        var ball_W = ball.offsetWidth;
        readPosition(ball);
        ball.style.transform = 'translateY('+(e.clientY-(0.5*ball_H))+'px)';
        ball.style.transform += 'translateX('+(e.clientX-(0.5*ball_W))+'px)';

    }, true);

};

#coordinat {
  transition: all 1s;
  border-radius: 5px;
  position: absolute;
  text-align: center;
  right: 5px;
  top: 5px;
  width: 150px;
  height: 30px;
  padding: 5px 5px;
  background-color: black;
  color: white;
  font-size: 0.8em;
}

#foo{
  margin: 2px;
  border-radius: 50px;
  width: 30px;
  height: 30px;
  /*background: #B40520;*/
  background: white;
  position: absolute;
  top: 0px;
  left: 0px;
  -moz-transition: transform 1s, background 1s;
  -webkit-transition: transform 1s, background 1s;
  -ms-transition: transform 1s, background 1s;
  -o-transition: transform 1s, background 1s;
  transition: transform 1s, background 1s;

}

Coordinates you will see!

Body:
You should pass new position of ball to your redPosition() function, because this function doesn't know a position after animation. As you can find in JSFiddle I pass a new ball position to function, so now it can be calculated properly.

JS to solve your problems:

function menuRoll(){
      var hidden_collapse = document.getElementById("hidden_collapse");
      hidden_collapse.classList.toggle("myStyle");
      }

      function readPosition(ball, yPos, xPos){
        var rect = ball.getBoundingClientRect();
        var x = Math.round(xPos) + "px";
        var y = Math.round(yPos) + "px";
        coordinat.innerHTML = "Coordinates:"+ "<br>" + x + ", " + y;
        coordinat.style.top = Math.round(yPos) - 30 + "px";
        coordinat.style.left = Math.round(xPos) + 37 + "px";
      }

window.onload = function(){
  var ball = document.getElementById('foo');
  var ball_space = document.getElementById('ball_space');
  var coordinat = document.getElementById("coordinat");
  document.addEventListener('click', function(e){

    ball.style.background = "#B40520";
    var ball_H = ball.offsetHeight;
    var ball_W = ball.offsetWidth;

    var ball_new_h = e.clientY-(0.5*ball_H);
    var ball_new_w = e.clientX-(0.5*ball_W);
    readPosition(ball, ball_new_h, ball_new_w);
    ball.style.transform = 'translateY('+ ball_new_h +'px)';
    ball.style.transform += 'translateX('+ball_new_w+'px)';

  }, true);

};


问:
Get custom data attribute value and return as text in jQuery
I am trying to fetch pictures from Flickr's publick fedd via $.getJson() and struggling a bit with adding tag names, as they are stored in a custom data-tag attribute:

HTML

```<code><div data-tag="sun" class="gallery component"></div>
<div data-tag="moon" class="gallery component"></div>
etc...
</code>```

As each gallery line should be composed of four random pictures with these tags, I wanted to set up a variable that would get these tag names from data-tag, but I'm unsure on how to get to them.

js/jQuery

```<code>$(document).ready(function() {
    var flickrAPI = "http://https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
    var tagprop = $().text();
    var flickrTags = {
        tags: tagprop,
        format: "json"
    };

    $.getJson(flickrAPI, flickrTags, flickrDisp)
});
</code>```

I've tried data.(value), but probably misplaced it, as it did not work. It's probably something really simple, it's just that I'm lacking orientation in this.

答:
To get data attribute value try

```<code>$(elem).data("propName");
</code>```

In your case it will be

```<code><div data-tag="sun" class="gallery component"></div>
var tagValue = $("div").data("tag");
</code>```

(jQuery >= 1.4.3)

Body:
I am trying to fetch pictures from Flickr's publick fedd via $.getJson() and struggling a bit with adding tag names, as they are stored in a custom data-tag attribute:

HTML

etc...

As each gallery line should be composed of four random pictures with these tags, I wanted to set up a variable that would get these tag names from data-tag, but I'm unsure on how to get to them.

js/jQuery

$(document).ready(function() {
    var flickrAPI = "http://https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
    var tagprop = $().text();
    var flickrTags = {
        tags: tagprop,
        format: "json"
    };

    $.getJson(flickrAPI, flickrTags, flickrDisp)
});

I've tried data.(value), but probably misplaced it, as it did not work. It's probably something really simple, it's just that I'm lacking orientation in this.

Body:
To get data attribute value try

$(elem).data("propName");

In your case it will be

<div data-tag="sun" class="gallery component"></div>
var tagValue = $("div").data("tag");

(jQuery >= 1.4.3)


问:
VBA- Extracting Text from DIV where no CLASS, ID, TAG
Here is the Script

```<code><div style="padding-left:0em; margin:10px 25px 24px 0px;">
  <div style='word-wrap:break-word; max-height:50px; overflow:hidden;'>
    <a style="display:unset; font-size:1.25em;" href="http://www.aptcenter.research.va.gov/staff/investigators/zhu/">Hui Zhu, MD, ScD - Advanced Platform Technology <b>Center</b></a>
  </div>

  <div class="url" style='word-spacing:normal; word-wrap:break-word; color:#008933; margin-bottom:2px; margin-top:2px'>
        www.aptcenter.research.va.gov/staff/investigators/zhu
  </div>
  <div style='color:#545454; line-height:1.3em; word-wrap:break-word; margin-bottom:2px;'>Jewish Hospital. Fellowship training took place in Urological Oncology at the <b>Memorial</b> <b>Sloan</b>-<b>Kettering</b> <b>Cancer</b> <b>Center</b> in New York <b>Center</b>. Dr. Zhu</div>
    <div class='no-print' style='margin-bottom:10px; margin-top:4px; color:#010101;'>
        View results from <a href="/search/va/va_search.jsp?QT=Memorial+Sloan+Kettering+Cancer+Center&SQ=www.aptcenter.research.va.gov&DB=3">APTCENTER RESEARCH</a>
        or related <a href="/search/va/va_search.jsp?QT=Memorial+Sloan+Kettering+Cancer+Center&DB=3">Health Research</a> sites
    </div>
  </div>
</code>```

I want to get Title i.e. "Hui Zhu, MD, ScD - Advanced Platform Technology Center" and then Text below link i.e. "Jewish Hospital. Fellowship training took place in Urological Oncology at the Memorial Sloan-Kettering Cancer Center in New York Center. Dr. Zhu"

Here is my current code

```<code>Dim objIE As Object, Slink As String
Dim hUls As MSHTML.IHTMLElementCollection
Dim httpRequest As XMLHTTP
Dim divElem As HTMLDivElement

Set httpRequest = New XMLHTTP

Slink = "https://www.index.va.gov/search/va/va_search.jsp?QT=Memorial+Sloan+Kettering+Cancer+Center&RS=1"

With httpRequest
    .Open "GET", Slink, False
    .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    .send
End With
With httpRequest
    While Not .readyState = 4
        Application.Wait Now + TimeValue("0:00:01")
    Wend
    If .Status = 200 Then
        While InStr(1, .responseText, "Updating", 0) > 0
            Application.Wait Now + TimeValue("0:00:01")
        Wend
        Set oHtml = New HTMLDocument
        oHtml.body.innerHTML = .responseText
    End If
End With

Set divElem = oHtml.getElementById("innerContent")
MsgBox divElem.getAttribute("padding-left:0em; margin:10px 25px 24px 0px;").cssText
</code>```

答:
It took a little tweaking, and assuming the HTML doesn't really change, but this should help you out.

It will return an array at the end that has the "link" text and the "body" text that describes the link.

Remove Set divElem and after...and replace with this:

```<code>Dim i As Long
Dim title() As Variant
ReDim title(0)

Dim ele As Object

Set aElem = oHtml.getElementsByTagName("a")
For Each ele In aElem
    If ele.Style = "FONT-SIZE" Then ' Will return each of the search findings main info
        title(UBound(title)) = ele.innerText
        ReDim Preserve title(LBound(title) To UBound(title) + 1)
    End If
Next ele

Dim text() As Variant
ReDim text(0)

Set divElem = oHtml.getElementsByTagName("div")
For Each ele In divElem
    If ele.getAttribute("style").cssText = "WORD-WRAP: break-word; MARGIN-BOTTOM: 2px; COLOR: #545454; LINE-HEIGHT: 1.3em" Then
        text(UBound(text)) = ele.innerText
        ReDim Preserve text(LBound(text) To UBound(text) + 1)
    End If
Next ele

Dim combinedInfo() As Variant
ReDim combinedInfo(UBound(title), 1)
For i = LBound(title) To UBound(title)
    combinedInfo(i, 0) = title(i)
    combinedInfo(i, 1) = text(i)
Next i

For i = LBound(title) To UBound(title) - 1
    Debug.Print combinedInfo(i, 0) & " ::: " & combinedInfo(i, 1)
Next i

End Sub
</code>```

The combinedInfo array has the Link Text as the (i,0)  index, and the Link description is the (i,1) index.

It's a little clunky, but if it works, you can just refactor into separate functions (one for the a tags and one for the div tags perhaps), but it worked for me with what you gave.

Body:
Here is the Script

    Hui Zhu, MD, ScD - Advanced Platform Technology Center

        www.aptcenter.research.va.gov/staff/investigators/zhu

Jewish Hospital. Fellowship training took place in Urological Oncology at the Memorial Sloan-Kettering Cancer Center in New York Center. Dr. Zhu

        View results from APTCENTER RESEARCH
        or related Health Research sites

I want to get Title i.e. "Hui Zhu, MD, ScD - Advanced Platform Technology Center" and then Text below link i.e. "Jewish Hospital. Fellowship training took place in Urological Oncology at the Memorial Sloan-Kettering Cancer Center in New York Center. Dr. Zhu"

Here is my current code

Dim objIE As Object, Slink As String
Dim hUls As MSHTML.IHTMLElementCollection
Dim httpRequest As XMLHTTP
Dim divElem As HTMLDivElement

Set httpRequest = New XMLHTTP

Slink = "https://www.index.va.gov/search/va/va_search.jsp?QT=Memorial+Sloan+Kettering+Cancer+Center&RS=1"

With httpRequest
    .Open "GET", Slink, False
    .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    .send
End With
With httpRequest
    While Not .readyState = 4
        Application.Wait Now + TimeValue("0:00:01")
    Wend
    If .Status = 200 Then
        While InStr(1, .responseText, "Updating", 0) > 0
            Application.Wait Now + TimeValue("0:00:01")
        Wend
        Set oHtml = New HTMLDocument
        oHtml.body.innerHTML = .responseText
    End If
End With

Set divElem = oHtml.getElementById("innerContent")
MsgBox divElem.getAttribute("padding-left:0em; margin:10px 25px 24px 0px;").cssText

Body:
It took a little tweaking, and assuming the HTML doesn't really change, but this should help you out.

It will return an array at the end that has the "link" text and the "body" text that describes the link.

Remove Set divElem and after...and replace with this:

Dim i As Long
Dim title() As Variant
ReDim title(0)

Dim ele As Object

Set aElem = oHtml.getElementsByTagName("a")
For Each ele In aElem
    If ele.Style = "FONT-SIZE" Then ' Will return each of the search findings main info
        title(UBound(title)) = ele.innerText
        ReDim Preserve title(LBound(title) To UBound(title) + 1)
    End If
Next ele

Dim text() As Variant
ReDim text(0)

Set divElem = oHtml.getElementsByTagName("div")
For Each ele In divElem
    If ele.getAttribute("style").cssText = "WORD-WRAP: break-word; MARGIN-BOTTOM: 2px; COLOR: #545454; LINE-HEIGHT: 1.3em" Then
        text(UBound(text)) = ele.innerText
        ReDim Preserve text(LBound(text) To UBound(text) + 1)
    End If
Next ele

Dim combinedInfo() As Variant
ReDim combinedInfo(UBound(title), 1)
For i = LBound(title) To UBound(title)
    combinedInfo(i, 0) = title(i)
    combinedInfo(i, 1) = text(i)
Next i

For i = LBound(title) To UBound(title) - 1
    Debug.Print combinedInfo(i, 0) & " ::: " & combinedInfo(i, 1)
Next i

End Sub

The combinedInfo array has the Link Text as the (i,0)  index, and the Link description is the (i,1) index.

It's a little clunky, but if it works, you can just refactor into separate functions (one for the a tags and one for the div tags perhaps), but it worked for me with what you gave.


问:
Using split method to split a string

The user is able to specify where the .txt file they want to import is located, via typing the location in via an onscreen prompt (this is stored within String 'importFile', which is being populated using a keyboard scanner).

Content of the file is then scanned using the scanner 'fileReader'.

```<code>String importFile = "";
File Fileobject = new File(importFile);
Scanner fileReader = new Scanner(Fileobject);

while(fileReader.hasNext())
{
  importFile = fileReader.next();
  String [] splitText = importFile.split("[-\\s]");
  System.out.println(splitText[0]);
}
</code>```

However, i am having some trouble then splitting the data within the text file properly...

Each line of text within the text file is formatted as follows:

```<code>abcd - efgh - 12.34 - ijkl - mnop
</code>```

the text should be formatted as such after being split:

```<code>abcd
efgh
12.34
ijkl
mnop
</code>```

i want the text to be stored within the array 'splitText' once it is split, so for example "abcd" will be located within splitText[0] etc. etc. though the whole string is being put into splitText[0] even after being split - screenshot follows (here

答:
Instead of [-\s], you can split with \s*-\s* like this :

```<code>String [] splitText = importFile.split("\\s*-\\s*");
String result = String.join("\n", splitText);//Join the results
System.out.println(result);
</code>```

Or to just print the results you can use (It work if you are using Java 8):

```<code>Stream.of(importFile.split("\\s*-\\s*")).forEach(System.out::println);
</code>```

Outputs

```<code>abcd
efgh
12.34
ijkl
mnop
</code>```

ideone demo

Title: Using split method to split a string

Body:
The user is able to specify where the .txt file they want to import is located, via typing the location in via an onscreen prompt (this is stored within String 'importFile', which is being populated using a keyboard scanner).

Content of the file is then scanned using the scanner 'fileReader'.

String importFile = "";
File Fileobject = new File(importFile);
Scanner fileReader = new Scanner(Fileobject);

while(fileReader.hasNext())
{
  importFile = fileReader.next();
  String [] splitText = importFile.split("[-\\s]");
  System.out.println(splitText[0]);
}

However, i am having some trouble then splitting the data within the text file properly...

Each line of text within the text file is formatted as follows:

abcd - efgh - 12.34 - ijkl - mnop

the text should be formatted as such after being split:

abcd
efgh
12.34
ijkl
mnop

i want the text to be stored within the array 'splitText' once it is split, so for example "abcd" will be located within splitText[0] etc. etc. though the whole string is being put into splitText[0] even after being split - screenshot follows (here

Body:
Instead of [-\s], you can split with \s*-\s* like this :

String [] splitText = importFile.split("\\s*-\\s*");
String result = String.join("\n", splitText);//Join the results
System.out.println(result);

Or to just print the results you can use (It work if you are using Java 8):

Stream.of(importFile.split("\\s*-\\s*")).forEach(System.out::println);

Outputs

abcd
efgh
12.34
ijkl
mnop

ideone demo


问:
Javascript Conditional Statement Fails
I'm trying to toggle the display on an element, and whilst I have used the conditional statement using below of '===' on say an ID of an element, which worked, I cannot get this code to work.

Does anyone know why the condition 'if (smallnavbar[0].style.display === 'none')' doesn't work? Is there a way to make the code work (toggle the display between none and flex)?

Thanks in advance!

```<code>function displayMenu(){
  var smallnavbar = document.getElementsByClassName("small-navbar-tabs");
  if (smallnavbar[0].style.display === 'none') {
    smallnavbar[0].style.display = 'flex';
  }
  else if (smallnavbar[0].style.display === 'flex') {
    smallnavbar[0].style.display = 'none';
  }
}
</code>```

答:
style.display is referring to the inline style (

). If the display is set by a class in a stylesheet, the display value will be an empty string.

In such case, neither conditions will be true, and therefore it will seems to you that are "failing".

You can simply double check my hypothesis with a console.log before the if statement (of course assuming the displayMenu is called).

There are several workaround for fixing this.
You can:

Check the computed style of the element instead of the inline one:

```<code>function displayMenu(){
  var smallnavbar = document.getElementsByClassName("small-navbar-tabs");
  var display = window.getComputedStyle(smallnavbar[0], "").display;

  smallnavbar[0].style.display = display === 'none' ? 'flex' : 'none';
}
</code>```

}

Having a separate class name for "flex" and "none" and check that instead of the value (if the browser support or you provide a shim for classList that would be easy:

```<code>smallnavbar[0].classList.toggle("flexible");
</code>```

Assuming the default value – e.g. you know that all small-navbar-tabs by default have display:none for example, therefore you could have:

```<code>if (smallnavbar[0].style.display === "flex") {
  smallnavbar[0].style.display = ""; // remove the inline style
} else {
  // since we're adding the inline style here,
  // it would pass the first check in the future.
  smallnavbar[0].style.display = "flex";
}
</code>```

Title: Javascript Conditional Statement Fails

Body:
I'm trying to toggle the display on an element, and whilst I have used the conditional statement using below of '===' on say an ID of an element, which worked, I cannot get this code to work.

Does anyone know why the condition 'if (smallnavbar[0].style.display === 'none')' doesn't work? Is there a way to make the code work (toggle the display between none and flex)?

Thanks in advance!

function displayMenu(){
  var smallnavbar = document.getElementsByClassName("small-navbar-tabs");
  if (smallnavbar[0].style.display === 'none') {
    smallnavbar[0].style.display = 'flex';
  }
  else if (smallnavbar[0].style.display === 'flex') {
    smallnavbar[0].style.display = 'none';
  }
}

Body:
style.display is referring to the inline style (<div style='display:block'></div>). If the display is set by a class in a stylesheet, the display value will be an empty string.

In such case, neither conditions will be true, and therefore it will seems to you that are "failing".

You can simply double check my hypothesis with a console.log before the if statement (of course assuming the displayMenu is called).

There are several workaround for fixing this.
You can:

Check the computed style of the element instead of the inline one:

function displayMenu(){
  var smallnavbar = document.getElementsByClassName("small-navbar-tabs");
  var display = window.getComputedStyle(smallnavbar[0], "").display;

  smallnavbar[0].style.display = display === 'none' ? 'flex' : 'none';
}

}

Having a separate class name for "flex" and "none" and check that instead of the value (if the browser support or you provide a shim for classList that would be easy:

smallnavbar[0].classList.toggle("flexible");

Assuming the default value – e.g. you know that all small-navbar-tabs by default have display:none for example, therefore you could have:

if (smallnavbar[0].style.display === "flex") {
  smallnavbar[0].style.display = ""; // remove the inline style
} else {
  // since we're adding the inline style here,
  // it would pass the first check in the future.
  smallnavbar[0].style.display = "flex";
}


问:
Polymer - dom-repeat when end binding event?
I have a simple question, because I didn't found this after long search.

Scenario:

When a component is loading, I make AJAX call to get data from an API. After call ends i put data in a property that is used for dom-repeat. After dom-repeat ends rendering I want to do some operation on elements in it. Read() is called even before AJAX call ends. Are there others ways to handle that?

答:
dom-repeat will fire dom-change event after it update DOM tree.

So you can do something like

```<code><template is='dom-repeat' items='[[items]]' on-dom-change='doSomething'>
   ...
</template>
</code>```

See in document.

Body:
dom-repeat will fire dom-change event after it update DOM tree.

So you can do something like

<template is='dom-repeat' items='[[items]]' on-dom-change='doSomething'>
   ...
</template>

See in document.


问:
How to use sum for lists of custom types?
Refer to below snippet:

```<code>class Foo(val b:BigDecimal) {
  def +(f:Foo) = new Foo(b+f.b)
}
val l = List(new Foo(1), new Foo(2))

l.sum // gives error: could not find implicit value for parameter num: Numeric[Foo]
</code>```

What is the easiest way to get this to work? I know I have to define some implicit conversions.

Note: the class Foo is inside a library so I cannot edit that code. I need to do it outside Foo.

I could not find answer to this particular case despite there being several examples of using Numeric types

答:
You can define necessary implicit:

```<code>  class Foo(val b:BigDecimal) {
    def +(f:Foo) = new Foo(b+f.b)
  }
  object Foo {
    implicit val numericFoo: Numeric[Foo] = new Numeric[Foo] {
      override def plus(x: Foo, y: Foo): Foo = new Foo(x.b + y.b)
      override def minus(x: Foo, y: Foo): Foo = new Foo(x.b - y.b)
      override def times(x: Foo, y: Foo): Foo = new Foo(x.b * y.b)
      override def negate(x: Foo): Foo = new Foo(-x.b)
      override def fromInt(x: Int): Foo = new Foo(x)
      override def toInt(x: Foo): Int = x.b.toInt
      override def toLong(x: Foo): Long = x.b.toLong
      override def toFloat(x: Foo): Float = x.b.toFloat
      override def toDouble(x: Foo): Double = x.b.toDouble
      override def compare(x: Foo, y: Foo): Int = x.b.compare(y.b)
    }
  }
</code>```

or just

```<code>implicit val numericFoo: Numeric[Foo] = new Numeric[Foo] {
  override def plus(x: Foo, y: Foo): Foo = x + y
  override def minus(x: Foo, y: Foo): Foo = ???
  override def times(x: Foo, y: Foo): Foo = ???
  override def negate(x: Foo): Foo = ???
  override def fromInt(x: Int): Foo = new Foo(x)
  override def toInt(x: Foo): Int = ???
  override def toLong(x: Foo): Long = ???
  override def toFloat(x: Foo): Float = ???
  override def toDouble(x: Foo): Double = ???
  override def compare(x: Foo, y: Foo): Int = ???
}
</code>```

Or you can define your own extension method

```<code>  implicit class FooList(foos: List[Foo]) {
    def sum1: Foo = foos.foldLeft(new Foo(0))(_ + _)
  }

  l.sum1
</code>```

Body:
Refer to below snippet:

class Foo(val b:BigDecimal) {
  def +(f:Foo) = new Foo(b+f.b)
}
val l = List(new Foo(1), new Foo(2))

l.sum // gives error: could not find implicit value for parameter num: Numeric[Foo]

What is the easiest way to get this to work? I know I have to define some implicit conversions.

Note: the class Foo is inside a library so I cannot edit that code. I need to do it outside Foo.

I could not find answer to this particular case despite there being several examples of using Numeric types

Body:
You can define necessary implicit:

  class Foo(val b:BigDecimal) {
    def +(f:Foo) = new Foo(b+f.b)
  }
  object Foo {
    implicit val numericFoo: Numeric[Foo] = new Numeric[Foo] {
      override def plus(x: Foo, y: Foo): Foo = new Foo(x.b + y.b)
      override def minus(x: Foo, y: Foo): Foo = new Foo(x.b - y.b)
      override def times(x: Foo, y: Foo): Foo = new Foo(x.b * y.b)
      override def negate(x: Foo): Foo = new Foo(-x.b)
      override def fromInt(x: Int): Foo = new Foo(x)
      override def toInt(x: Foo): Int = x.b.toInt
      override def toLong(x: Foo): Long = x.b.toLong
      override def toFloat(x: Foo): Float = x.b.toFloat
      override def toDouble(x: Foo): Double = x.b.toDouble
      override def compare(x: Foo, y: Foo): Int = x.b.compare(y.b)
    }
  }

or just

implicit val numericFoo: Numeric[Foo] = new Numeric[Foo] {
  override def plus(x: Foo, y: Foo): Foo = x + y
  override def minus(x: Foo, y: Foo): Foo = ???
  override def times(x: Foo, y: Foo): Foo = ???
  override def negate(x: Foo): Foo = ???
  override def fromInt(x: Int): Foo = new Foo(x)
  override def toInt(x: Foo): Int = ???
  override def toLong(x: Foo): Long = ???
  override def toFloat(x: Foo): Float = ???
  override def toDouble(x: Foo): Double = ???
  override def compare(x: Foo, y: Foo): Int = ???
}

Or you can define your own extension method

  implicit class FooList(foos: List[Foo]) {
    def sum1: Foo = foos.foldLeft(new Foo(0))(_ + _)
  }

  l.sum1


问:
tensorflow tensorboard error : you must feed a value for placeholder tensor
Beginner and trying to use tensorboard in my tensorflow prgm. I added tensorboard refs as I saw in the tutorials, but I get the error message below :

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'x' with dtype float
       [[Node: x = Placeholderdtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]]

Error seems related to this line I added in my training loop. Without this line the program throws no errors:

```<code>summary = sess.run(merged_summary_op, {x: x_train, y_prim: y_train})
</code>```

Thanks if somebody can check my code below and help:

```<code># -*- coding: utf-8 -*-

import tensorflow as tf
sess = tf.Session()

# parms
a = tf.Variable([2.0], dtype=tf.float32, name="a")
x = tf.placeholder(tf.float32, name="x")
b = tf.Variable([1.0], dtype=tf.float32, name="b")

# model : y=ax+b
with tf.name_scope('Model'):
    y = tf.add ((tf.multiply(a, x)), b)

# info for TensorBoard
writer = tf.summary.FileWriter("D:\\tmp\\tensorflow\\logs", sess.graph)

# loss fct - mean square error
with tf.name_scope('cost'):
    y_prim = tf.placeholder(tf.float32)
    cost = tf.reduce_sum(tf.square(y - y_prim))

# optimizer = gradientdescent
with tf.name_scope('GradDes'):
    optimizer = tf.train.GradientDescentOptimizer(0.01)
    train = optimizer.minimize(cost)

# train datas
x_train = [1, 2, 3, 4]
y_train = [5.2, 8.4, 11.1, 14.7]

# summary for Tensorboard
tf.summary.scalar("cost", cost)
merged_summary_op = tf.summary.merge_all()

# init vars
init = tf.global_variables_initializer()

# train loop
sess.run(init)
for i in range (500):
    sess.run([train, cost], feed_dict={x: x_train, y_prim: y_train})
    summary = sess.run(merged_summary_op, {x: x_train, y_prim: y_train})
    a_found, b_found, curr_cost = sess.run([a, b, cost], feed_dict={x:x_train, y_prim: y_train})
    print("iteration :", i, "a: ", a_found, "b: ", b_found, "cost: ",curr_cost)
</code>```

答:
Don't execute the merged summary operation in a separate sess.run. Try this instead:

```<code>a_found, b_found, curr_cost, summary = sess.run([a, b, cost, merged_summary_op], feed_dict={x:x_train, y_prim: y_train})
</code>```

After the session runs, you need to call the add_summary method of your FileWriter:

```<code>writer.add_summary(summary)
writer.flush()
</code>```

Body:
Beginner and trying to use tensorboard in my tensorflow prgm. I added tensorboard refs as I saw in the tutorials, but I get the error message below :

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'x' with dtype float
       [[Node: x = Placeholderdtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]]

Error seems related to this line I added in my training loop. Without this line the program throws no errors:

summary = sess.run(merged_summary_op, {x: x_train, y_prim: y_train})

Thanks if somebody can check my code below and help:

# -*- coding: utf-8 -*-

import tensorflow as tf
sess = tf.Session()

# parms
a = tf.Variable([2.0], dtype=tf.float32, name="a")
x = tf.placeholder(tf.float32, name="x")
b = tf.Variable([1.0], dtype=tf.float32, name="b")

# model : y=ax+b
with tf.name_scope('Model'):
    y = tf.add ((tf.multiply(a, x)), b)

# info for TensorBoard
writer = tf.summary.FileWriter("D:\\tmp\\tensorflow\\logs", sess.graph)

# loss fct - mean square error
with tf.name_scope('cost'):
    y_prim = tf.placeholder(tf.float32)
    cost = tf.reduce_sum(tf.square(y - y_prim))

# optimizer = gradientdescent
with tf.name_scope('GradDes'):
    optimizer = tf.train.GradientDescentOptimizer(0.01)
    train = optimizer.minimize(cost)

# train datas
x_train = [1, 2, 3, 4]
y_train = [5.2, 8.4, 11.1, 14.7]

# summary for Tensorboard
tf.summary.scalar("cost", cost)
merged_summary_op = tf.summary.merge_all()

# init vars
init = tf.global_variables_initializer()

# train loop
sess.run(init)
for i in range (500):
    sess.run([train, cost], feed_dict={x: x_train, y_prim: y_train})
    summary = sess.run(merged_summary_op, {x: x_train, y_prim: y_train})
    a_found, b_found, curr_cost = sess.run([a, b, cost], feed_dict={x:x_train, y_prim: y_train})
    print("iteration :", i, "a: ", a_found, "b: ", b_found, "cost: ",curr_cost)

Body:
Don't execute the merged summary operation in a separate sess.run. Try this instead:

a_found, b_found, curr_cost, summary = sess.run([a, b, cost, merged_summary_op], feed_dict={x:x_train, y_prim: y_train})

After the session runs, you need to call the add_summary method of your FileWriter:

writer.add_summary(summary)
writer.flush()


问:
How to initialize a local variable in ActionListener? - Java
If I want to initialize a local variable in an ActionListener I get this error:

Local variable word defined in an enclosing scope must be final or effectively final.

The code looks something like this:

```<code>int number = 0;

anyButton.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {

        //And here I get the error:
        number++;

    }
});
</code>```

Do you know how to do it?

答:
You need a mutable thread-safe variable, not a primitive.

Consider replacing that primitive by either a wrapper class (could be your own, or a standard one [e.g. AtomicInteger]) or a single-element array:

```<code>final AtomicInteger number = new AtomicInteger();
...
number.getAndIncrement();
</code>```

Body:
If I want to initialize a local variable in an ActionListener I get this error:

Local variable word defined in an enclosing scope must be final or effectively final.

The code looks something like this:

int number = 0;

anyButton.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {

        //And here I get the error:
        number++;

    }
});

Do you know how to do it?

Body:
You need a mutable thread-safe variable, not a primitive.

Consider replacing that primitive by either a wrapper class (could be your own, or a standard one [e.g. AtomicInteger]) or a single-element array:

final AtomicInteger number = new AtomicInteger();
...
number.getAndIncrement();


问:
How to make Generic Enum as OrmLite Column
I'm trying to minimize some of the work I'm going to have to do by "generifying" my lookup tables. They are all going to have int id as primary key but I'd also like them to have the ability to be searched by their "type" (whatever the Enum value is). Here's the abstract LookupRecord class

```<code>public abstract class LookupRecord<T extends Enum<T>> extends DatabaseRecord {
    public static final String TYPE_FIELD_NAME = "type";

    @DatabaseField(unique = true, columnName = TYPE_FIELD_NAME)
    private T type;

    public LookupRecord(T type) {
        this.type = type;
    }

    public T getType() {
        return type;
    }
}
</code>```

So whenever I try to initialize the Dao for any of the lookup tables I get the following error:

java.sql.SQLException: Field FieldType:name=type,class=LookupRecord improperly configured as type com.j256.ormlite.field.types.EnumStringType@5e80d5

答:
They are all going to have int id as primary key but I'd also like them to have the ability to be searched by their "type" (whatever the Enum value is).

```<code>@DatabaseField(unique = true, columnName = TYPE_FIELD_NAME)
private T type;
</code>```

Yeah this isn't going to work because of type erasure.  When ORMLite goes to investigate the class in question using reflection, it tries to lookup the enum constants for this field.  All it gets is the type Enum and not the specific concrete Enum class from the sub-class.  Unfortunately that error message is less than helpful pointing that out.

When the class is configured, all it knows is that it's an enum.  It doesn't know which enum it is so it can't configure the field correctly or create instances of the object with an appropriate enum field there.

Body:
I'm trying to minimize some of the work I'm going to have to do by "generifying" my lookup tables. They are all going to have int id as primary key but I'd also like them to have the ability to be searched by their "type" (whatever the Enum value is). Here's the abstract LookupRecord class

public abstract class LookupRecord<T extends Enum<T>> extends DatabaseRecord {
    public static final String TYPE_FIELD_NAME = "type";

    @DatabaseField(unique = true, columnName = TYPE_FIELD_NAME)
    private T type;

    public LookupRecord(T type) {
        this.type = type;
    }

    public T getType() {
        return type;
    }
}

So whenever I try to initialize the Dao for any of the lookup tables I get the following error:

java.sql.SQLException: Field FieldType:name=type,class=LookupRecord improperly configured as type com.j256.ormlite.field.types.EnumStringType@5e80d5

Body:
They are all going to have int id as primary key but I'd also like them to have the ability to be searched by their "type" (whatever the Enum value is).

@DatabaseField(unique = true, columnName = TYPE_FIELD_NAME)
private T type;

Yeah this isn't going to work because of type erasure.  When ORMLite goes to investigate the class in question using reflection, it tries to lookup the enum constants for this field.  All it gets is the type Enum and not the specific concrete Enum class from the sub-class.  Unfortunately that error message is less than helpful pointing that out.

When the class is configured, all it knows is that it's an enum.  It doesn't know which enum it is so it can't configure the field correctly or create instances of the object with an appropriate enum field there.


问:
Python: Making Different Parameters Global
I am having problems making some variables global in this code. I would like the outputted numbers to be 4, 8, 6, and 10. The output is always just 1, 2, 3, and 4 like the function does not process the numbers at all. I tried making each variable global before, after, and inside the function, but this did not work. If anyone has a solution to this, it would be greatly appreciated. My actual code for my project has several more pairs of variables, I just included these to simplify it. </p>

```<code>Xone = 1
Yone = 2
Xtwo = 3
Ytwo = 4
def function(parameterOne, parameterTwo):
    parameterOne = parameterOne + 3
    parameterTwo = parameterTwo + 6
function(Xone, Yone)
function(Xtwo, Ytwo)
print str(Xone)
print str(Yone)
print str(Xtwo)
print str(Ytwo)
</code>```

答:
Assign values to variables on return from function:</p>

```<code>def function(parameterOne, parameterTwo):
    parameterOne = parameterOne + 3
    parameterTwo = parameterTwo + 6
    return parameterOne, parameterTwo

Xone, Yone = function(Xone, Yone)
</code>```

Body:
I am having problems making some variables global in this code. I would like the outputted numbers to be 4, 8, 6, and 10. The output is always just 1, 2, 3, and 4 like the function does not process the numbers at all. I tried making each variable global before, after, and inside the function, but this did not work. If anyone has a solution to this, it would be greatly appreciated. My actual code for my project has several more pairs of variables, I just included these to simplify it.

Xone = 1
Yone = 2
Xtwo = 3
Ytwo = 4
def function(parameterOne, parameterTwo):
    parameterOne = parameterOne + 3
    parameterTwo = parameterTwo + 6
function(Xone, Yone)
function(Xtwo, Ytwo)
print str(Xone)
print str(Yone)
print str(Xtwo)
print str(Ytwo)

Body:
Assign values to variables on return from function:

def function(parameterOne, parameterTwo):
    parameterOne = parameterOne + 3
    parameterTwo = parameterTwo + 6
    return parameterOne, parameterTwo

Xone, Yone = function(Xone, Yone)


问:
How can i use Docker to deploy a Vagrant image?
I am using a Vagrant image (https://app.vagrantup.com/scratchpads/boxes/aegir-scratchpads2/versions/1.0.1) to deploy a virtual box machine with everything working but i have a problem... i want to use Docker instead of Vagrant for this (since i want it in the cloud).

Is there any way to use Docker to deploy this Vagrant image instead of it creating a Virtual Box machine with Vagrant (or get the vagrant complete config with everything it installs for it to run)?

答:
Docker and vagrant both serve for different purposes

It is not possible to boot docker containers with vagrant image

You need to create a docker image

The process to create a docker image is pretty easy

Check out Docker docs to know how to build images


问:
Can I simplify this iOS renderer now that I no longer need to explicitly subscribe to property-changed-event
I am using this custom renderer:

```<code>public class ExtViewCellRenderer : ViewCellRenderer
{
    UITableViewCell _nativeCell;

    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        _nativeCell = base.GetCell(item, reusableCell, tv);
        var formsCell = item as ExtViewCell;

        if (formsCell != null)
        {
            formsCell.PropertyChanged -= OnPropertyChanged;
            formsCell.PropertyChanged += OnPropertyChanged;
        }
        SetTap(formsCell);

        return _nativeCell;
    }

    void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        var formsCell = sender as ExtViewCell;
        if (formsCell == null)
            return;

        if (e.PropertyName == ExtViewCell.NoTapProperty.PropertyName)
        {
            SetTap(formsCell);
        }
    }

    private void SetTap(ExtViewCell formsCell)
    {
        if (formsCell.NoTap)
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.None;
        else
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.Default;
    }

}
</code>```

I read that with a TextCellRenderer it's no longer necessary to explicitly subscribe to property-changed-event as there is a base overridable method HandlePropertyChanged that can be re-used in this context.

Can someone tell me if this is the case also for the ViewCellRenderer and if so then how could I modify this code to make use of this?

I also saw code like this in another renderer:

```<code>public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
    var textCell = (TextCell)item;
    var fullName = item.GetType().FullName;
    cell = tv.DequeueReusableCell(fullName) as CellTableViewCell;

    //...
</code>```

But not here.  Is it necessary to do this Cell = tv.DequeueReusableCell ?

答:
I read that with a TextCellRenderer it's no longer necessary to explicitly subscribe to property-changed-event as there is a base overridable method HandlePropertyChanged that can be re-used in this context.

Yes that is correct according to its source code

```<code>protected virtual void HandlePropertyChanged(object sender, PropertyChangedEventArgs args) {
    //...
}
</code>```

TextCellRenderer Source

Can someone tell me if this is the case also for the ViewCellRenderer and if so then how could I modify this code to make use of this?

No it is not the case also for the ViewCellRenderer as according to source code ViewCellRenderer  is not exposing its ViewCellPropertyChanged as it is private

```<code>void ViewCellPropertyChanged(object sender, PropertyChangedEventArgs e) {
    //...
}
</code>```

ViewCellRenderer Source

You could always modify it yourself and create a pull request to add that feature.

Body:
I am using this custom renderer:

public class ExtViewCellRenderer : ViewCellRenderer
{
    UITableViewCell _nativeCell;

    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        _nativeCell = base.GetCell(item, reusableCell, tv);
        var formsCell = item as ExtViewCell;

        if (formsCell != null)
        {
            formsCell.PropertyChanged -= OnPropertyChanged;
            formsCell.PropertyChanged += OnPropertyChanged;
        }
        SetTap(formsCell);

        return _nativeCell;
    }

    void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        var formsCell = sender as ExtViewCell;
        if (formsCell == null)
            return;

        if (e.PropertyName == ExtViewCell.NoTapProperty.PropertyName)
        {
            SetTap(formsCell);
        }
    }

    private void SetTap(ExtViewCell formsCell)
    {
        if (formsCell.NoTap)
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.None;
        else
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.Default;
    }

}

I read that with a TextCellRenderer it's no longer necessary to explicitly subscribe to property-changed-event as there is a base overridable method HandlePropertyChanged that can be re-used in this context.

Can someone tell me if this is the case also for the ViewCellRenderer and if so then how could I modify this code to make use of this?

I also saw code like this in another renderer:

public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
    var textCell = (TextCell)item;
    var fullName = item.GetType().FullName;
    cell = tv.DequeueReusableCell(fullName) as CellTableViewCell;

    //...

But not here.  Is it necessary to do this Cell = tv.DequeueReusableCell ?

Body:
I read that with a TextCellRenderer it's no longer necessary to explicitly subscribe to property-changed-event as there is a base overridable method HandlePropertyChanged that can be re-used in this context.

Yes that is correct according to its source code

protected virtual void HandlePropertyChanged(object sender, PropertyChangedEventArgs args) {
    //...
}

TextCellRenderer Source

Can someone tell me if this is the case also for the ViewCellRenderer and if so then how could I modify this code to make use of this?

No it is not the case also for the ViewCellRenderer as according to source code ViewCellRenderer  is not exposing its ViewCellPropertyChanged as it is private

void ViewCellPropertyChanged(object sender, PropertyChangedEventArgs e) {
    //...
}

ViewCellRenderer Source

You could always modify it yourself and create a pull request to add that feature.


问:
Atm machine logic error at array input
I have created an application about ATM machine that have an array account size of 10 but for some weird reason, the input only accept 0(first id), but not the other 9 ids for the other ids, it always show the Invalid id error message. I've stuck for hours searching for the error.

the ones that related to checking the ids would be these two;

```<code>public static boolean hasID(Account acc[], int id){ //this is to check whether the id exist or not.
    for(int i=0; i<acc.length; i++){
        if(id == acc[i].getID()){
            return true;
        }
    }
    return false;
}

public static int gID(Account[] acc){  //this is the login method to initiate the hasID method.
    Scanner sc = new Scanner(System.in);
    int id=0;
    boolean valid = false;
    while(!valid){
        System.out.println("Enter ID: ");
        id = sc.nextInt();

        if(!hasID(acc, id)){
            System.out.println("YOUR ID IS INVALID.");
        } else{
            valid = true;
        }
    }
    return id;
}

public Account(int mID, double mBalance/*, double mInterestRate*/){
    this.id = getID();
    this.balance = getBalance();
    //this.interestRate = getInterestRate();
}

public static Account getAccount(Account acc[], int id){
    for(int i = 0; i<acc.length; i++){
        if(id == acc[i].getID()){
            return acc[i];
        }
    }
    return null;
}
</code>```

and here is my main:

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

    Scanner sc = new Scanner(System.in);
    Account acc[] = new Account[10];
    for(int i = 0; i<acc.length; i++){
        acc[i] = new Account(i, 100.0);
    }

    int a = 0;
    int id = gID(acc);

    while(a != 4){
        Account ac = getAccount(acc,id);
        System.out.println("1: Check Balance");
        System.out.println("2: Withdraw");
        System.out.println("3: Deposit");
        System.out.println("4: Exit");

        System.out.println("Enter your choice: ");
        a = sc.nextInt();
        switch(a){
        case 1:
            System.out.println("Your Balance is: RM " + ac.getBalance());
            break;

        case 2:
            System.out.println("Amount to withdraw: RM ");
            ac.withdraw(sc.nextDouble());
            break;

        case 3:
            System.out.println("Amount to deposit: RM ");
            ac.deposit(sc.nextDouble());
            break;

        case 4:
            id = gID(acc);
            a = 0;
            break;

        default:
            System.out.println("Invalid input!");
        }
    }

}
</code>```

Edit: Account constructor, the insterestrate is not used.
The setter and getter for id and balance:

```<code>public int getID(){
    return id;
}

public void setID(int mID){
    id = mID;
}

public double getBalance(){
    return balance;
}

public void setBalance(double mBalance){
    balance = mBalance;
}
</code>```

Thanks for your time.

答:
```<code>public Account(int mID, double mBalance/*, double mInterestRate*/){
    this.id = getID();
    this.balance = getBalance();
    //this.interestRate = getInterestRate();
}
</code>```

Shouldn't you be using

```<code> public Account(int mID, double mBalance/*, double mInterestRate*/){
    this.id = mID;
    this.balance = mBalance;
    //this.interestRate = getInterestRate();
 }
</code>```

getters and  setter are part of the FIELDS ENCAPSULATION, but for better user experiance I could suggest you the following code

```<code>public Account(/*you dont need a parameter*/){
   this.id = setIdByScannedValue();
   this.balance = setBalanceByScannedValue();
   //this.interestRate = setInterestRateByScannedValue();
}

private void setIdByScannedValue(){
    Scanner sc = new Scanner(System.in);
    boolean provided = false;
    while(!provided)
    try{
        System.out.print("provide id: ");
        this.id = sc.nextInt();
    }catch(NumberFormatException e){
        System.out.println("you must provide an integer id format !!!");
    }finally{
        provided = true;
    }
}
</code>```

I ll let you do the other methods so you can learn using this idea by your self this way I'll be sure that you understand my code.

Title: Atm machine logic error at array input

Body:
I have created an application about ATM machine that have an array account size of 10 but for some weird reason, the input only accept 0(first id), but not the other 9 ids for the other ids, it always show the Invalid id error message. I've stuck for hours searching for the error.

the ones that related to checking the ids would be these two;

public static boolean hasID(Account acc[], int id){ //this is to check whether the id exist or not.
    for(int i=0; i<acc.length; i++){
        if(id == acc[i].getID()){
            return true;
        }
    }
    return false;
}

public static int gID(Account[] acc){  //this is the login method to initiate the hasID method.
    Scanner sc = new Scanner(System.in);
    int id=0;
    boolean valid = false;
    while(!valid){
        System.out.println("Enter ID: ");
        id = sc.nextInt();

        if(!hasID(acc, id)){
            System.out.println("YOUR ID IS INVALID.");
        } else{
            valid = true;
        }
    }
    return id;
}

public Account(int mID, double mBalance/*, double mInterestRate*/){
    this.id = getID();
    this.balance = getBalance();
    //this.interestRate = getInterestRate();
}

public static Account getAccount(Account acc[], int id){
    for(int i = 0; i<acc.length; i++){
        if(id == acc[i].getID()){
            return acc[i];
        }
    }
    return null;
}

and here is my main:

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    Account acc[] = new Account[10];
    for(int i = 0; i<acc.length; i++){
        acc[i] = new Account(i, 100.0);
    }

    int a = 0;
    int id = gID(acc);

    while(a != 4){
        Account ac = getAccount(acc,id);
        System.out.println("1: Check Balance");
        System.out.println("2: Withdraw");
        System.out.println("3: Deposit");
        System.out.println("4: Exit");

        System.out.println("Enter your choice: ");
        a = sc.nextInt();
        switch(a){
        case 1:
            System.out.println("Your Balance is: RM " + ac.getBalance());
            break;

        case 2:
            System.out.println("Amount to withdraw: RM ");
            ac.withdraw(sc.nextDouble());
            break;

        case 3:
            System.out.println("Amount to deposit: RM ");
            ac.deposit(sc.nextDouble());
            break;

        case 4:
            id = gID(acc);
            a = 0;
            break;

        default:
            System.out.println("Invalid input!");
        }
    }

}

Edit: Account constructor, the insterestrate is not used.
The setter and getter for id and balance:

public int getID(){
    return id;
}

public void setID(int mID){
    id = mID;
}

public double getBalance(){
    return balance;
}

public void setBalance(double mBalance){
    balance = mBalance;
}

Thanks for your time.

Body:
public Account(int mID, double mBalance/*, double mInterestRate*/){
    this.id = getID();
    this.balance = getBalance();
    //this.interestRate = getInterestRate();
}

Shouldn't you be using

 public Account(int mID, double mBalance/*, double mInterestRate*/){
    this.id = mID;
    this.balance = mBalance;
    //this.interestRate = getInterestRate();
 }

getters and  setter are part of the FIELDS ENCAPSULATION, but for better user experiance I could suggest you the following code

public Account(/*you dont need a parameter*/){
   this.id = setIdByScannedValue();
   this.balance = setBalanceByScannedValue();
   //this.interestRate = setInterestRateByScannedValue();
}

private void setIdByScannedValue(){
    Scanner sc = new Scanner(System.in);
    boolean provided = false;
    while(!provided)
    try{
        System.out.print("provide id: ");
        this.id = sc.nextInt();
    }catch(NumberFormatException e){
        System.out.println("you must provide an integer id format !!!");
    }finally{
        provided = true;
    }
}

I ll let you do the other methods so you can learn using this idea by your self this way I'll be sure that you understand my code.


答:
You can return the computed values:

```<code>def function(parameterOne, parameterTwo):
    return (parameterOne + 3, parameterTwo + 6)

Xone = 1
Yone = 2
Xtwo = 3
Ytwo = 4

Xone, Yone = function(Xone, Yone)
Xtwo, Ytwo = function(Xtwo, Ytwo)

print str(Xone)
print str(Yone)
print str(Xtwo)
print str(Ytwo)
</code>```

This returns:

```<code>4
8
6
10
</code>```

Title: Python: Making Different Parameters Global

Body:
You can return the computed values:

def function(parameterOne, parameterTwo):
    return (parameterOne + 3, parameterTwo + 6)

Xone = 1
Yone = 2
Xtwo = 3
Ytwo = 4

Xone, Yone = function(Xone, Yone)
Xtwo, Ytwo = function(Xtwo, Ytwo)

print str(Xone)
print str(Yone)
print str(Xtwo)
print str(Ytwo)

This returns:

4
8
6
10


答:
The full signature for List's sum method is:

```<code>def sum[B >: A](implicit num: Numeric[B]): B
</code>```

So you must provide an implicit Numeric for your class, or some superclass of your class:

```<code>implicit val fooNumeric = new Numeric[Foo] {
  def compare(x: Foo, y: Foo): Int = ???
  def plus(x: Foo, y: Foo): Foo = ???
  ... other methods ...
}
</code>```

My guess is sum only needs plus to work correctly, but you'll at least have to give a dummy implementation of the other abstract Numeric methods to get it to compile.

Title: How to use sum for lists of custom types?

Body:
The full signature for List's sum method is:

def sum[B >: A](implicit num: Numeric[B]): B

So you must provide an implicit Numeric for your class, or some superclass of your class:

implicit val fooNumeric = new Numeric[Foo] {
  def compare(x: Foo, y: Foo): Int = ???
  def plus(x: Foo, y: Foo): Foo = ???
  ... other methods ...
}

My guess is sum only needs plus to work correctly, but you'll at least have to give a dummy implementation of the other abstract Numeric methods to get it to compile.


问:
PMA Database ... not OK in phpMyAdmin upgrade
I have just been wrangling with phpMyAdmin and MySQL server on my Win8 PC IIS localhost (there was no connection between these, which I think was due to MySQL service not starting so I reinstalled MySQL and reran the config setup and reestablished a connection between them, which fixed that).

However phpMyAdmin advised an update which I did by overwriting the files with the new version and including the previous config file.

I now have:

The phpMyAdmin configuration storage is not completely configured, some extended features have been deactivated. To find out why click here.

and on clicking I get

PMA Database ... not OK [ Documentation ]

General relation features Disabled

When I click the link I get a http 404 page which gives this:

```<code>Physical path C:\inetpub\wwwroot\phpMyAdmin\pmadb
</code>```

So what is the pmadb in phpMyAdmin and should I be bothered by this? As it stands I'm a bit fed up at having to have had to spend time tweaking all of this (ie it has not been a smooth trouble free event/install). Is it some DB for the old version or what? I do not think I created it!

I do not feel very bothered by this as hopefully I can setup my databases for my localhost IIS websites and press on with my webdeverry(!) but I don't really like having this unknown error and wouldn't mind fixing it/getting rid of it.

答:
For me the db phpmyadmin was missing, you can find the file create_tables.sql inside the phpmyadmin installation in the sql/ directory.  You can use this file to rebuild your table.

From the command line, you can import that sql file.
# mysql -u root < create_tables.sql

Be careful this will probably overrwrite your data, dont run it until you move your old phpmyadmin table, if you have one intact already.

Body:
I have just been wrangling with phpMyAdmin and MySQL server on my Win8 PC IIS localhost (there was no connection between these, which I think was due to MySQL service not starting so I reinstalled MySQL and reran the config setup and reestablished a connection between them, which fixed that).

However phpMyAdmin advised an update which I did by overwriting the files with the new version and including the previous config file.

I now have:

The phpMyAdmin configuration storage is not completely configured, some extended features have been deactivated. To find out why click here.

and on clicking I get

PMA Database ... not OK [ Documentation ]

General relation features Disabled

When I click the link I get a http 404 page which gives this:

Physical path C:\inetpub\wwwroot\phpMyAdmin\pmadb

So what is the pmadb in phpMyAdmin and should I be bothered by this? As it stands I'm a bit fed up at having to have had to spend time tweaking all of this (ie it has not been a smooth trouble free event/install). Is it some DB for the old version or what? I do not think I created it!

I do not feel very bothered by this as hopefully I can setup my databases for my localhost IIS websites and press on with my webdeverry(!) but I don't really like having this unknown error and wouldn't mind fixing it/getting rid of it.


问:
Find largest sum of 3 numbers which is also divisable by 3
How to find largest sum of 3 numbers which is also divisable by 3?

Examples:

Input: [1, 15, 4, 7, 2]

Output: [15, 7, 2] (In that order)

Input: [1, 2, 4, 7]

Output: [1, 4, 7] (In that order)

I came up only with this:

```<code>function largestSum(arr) {
    let max = -1;
    let nums;

    for (let i = 0; i < arr.length; i++)
        for (let j = i + 1; j < arr.length; j++)
            for (let k = j + 1; k < arr.length; k++)
                if ((arr[i] + arr[j] + arr[k]) % 3 === 0 && arr[i] + arr[j] + arr[k] > max)
                    nums = [arr[i], arr[j], arr[k]], max = arr[i] + arr[j] + arr[k];

    return nums;
}
</code>```

But, isn't it better option here (with better efficiency)?

答:
Another simple solution with a simple combination algorithm and check for the wanted parameters.

function getCombinations(array) {
    function add(a, b) { return a + b; }

    function fork(i, t) {
        var sum = t.reduce(add, 0);
        if (i === array.length) {
            if (t.length === 3 && sum % 3 === 0 && sum > result.reduce(add, 0)) {
                result = t;
            }
            return;
        }
        fork(i + 1, t.concat([array[i]]));
        fork(i + 1, t);
    }

    var result = [];
    fork(0, []);
    return result;
}

console.log(getCombinations([1, 15, 4, 7, 2]));
console.log(getCombinations([1, 2, 4, 7]));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
How to find largest sum of 3 numbers which is also divisable by 3?

Examples:

Input: [1, 15, 4, 7, 2]

Output: [15, 7, 2] (In that order)

Input: [1, 2, 4, 7]

Output: [1, 4, 7] (In that order)

I came up only with this:

function largestSum(arr) {
    let max = -1;
    let nums;

    for (let i = 0; i < arr.length; i++)
        for (let j = i + 1; j < arr.length; j++)
            for (let k = j + 1; k < arr.length; k++)
                if ((arr[i] + arr[j] + arr[k]) % 3 === 0 && arr[i] + arr[j] + arr[k] > max)
                    nums = [arr[i], arr[j], arr[k]], max = arr[i] + arr[j] + arr[k];

    return nums;
}

But, isn't it better option here (with better efficiency)?

Body:
Another simple solution with a simple combination algorithm and check for the wanted parameters.

function getCombinations(array) {
    function add(a, b) { return a + b; }

    function fork(i, t) {
        var sum = t.reduce(add, 0);
        if (i === array.length) {
            if (t.length === 3 && sum % 3 === 0 && sum > result.reduce(add, 0)) {
                result = t;
            }
            return;
        }
        fork(i + 1, t.concat([array[i]]));
        fork(i + 1, t);
    }

    var result = [];
    fork(0, []);
    return result;
}

console.log(getCombinations([1, 15, 4, 7, 2]));
console.log(getCombinations([1, 2, 4, 7]));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Yobit c#, jsonconvert.deserialize
From https://yobit.net/api/3/depth/btc_usd?limit=5 i have

```<code>    string response = { "btc_usd":{ "asks":[[6657,0.06689384],[6680.47685546,0.001],[6680.47690546,0.00526334],[6697,0.05],[6698,0.05]],"bids":[[6656,0.02371773],[6640.00000001,0.0297727],[6640,0.34752146],[6637.46352566,0.0011574],[6634,0.00424518]]}}
</code>```

I want to deserialize this.
I created some classes

```<code>public class Orderbook
{
    [JsonProperty("asks")]
    public List<BidAsk> asks { get; set; }

    [JsonProperty("bids")]
    public List<BidAsk> bids { get; set; }
}

public class BidAsk
{
    public decimal price { get; set; }
    public decimal volume { get; set; }
}

var jsonResponse = JsonConvert.DeserializeObject<Orderbook>(response);
</code>```

After this operation i got:
jsonResponse.asks = null
jsonResponse.bids = null

What I've done wrong in deserialization?

答:
How deserialize these responses if I don't know, which pair i got?
For example, two different requests:

1)https://yobit.net/api/3/depth/btc_usd?limit=5

2)https://yobit.net/api/3/depth/eth_usd?limit=5

Should I create a new JsonProperty for another pair "eth_usd"?

```<code>[JsonProperty("eth_usd")]
public Currency ETHToUSD{ get; set; }
</code>```

In this case in each request all other attributes of class will be null.
I want to get something like this:

```<code>   var Asks = jsonresponse.pair_name.asks
</code>```

Title: Yobit c#, jsonconvert.deserialize

Body:
From https://yobit.net/api/3/depth/btc_usd?limit=5 i have

    string response = { "btc_usd":{ "asks":[[6657,0.06689384],[6680.47685546,0.001],[6680.47690546,0.00526334],[6697,0.05],[6698,0.05]],"bids":[[6656,0.02371773],[6640.00000001,0.0297727],[6640,0.34752146],[6637.46352566,0.0011574],[6634,0.00424518]]}}

I want to deserialize this.
I created some classes

public class Orderbook
{
    [JsonProperty("asks")]
    public List<BidAsk> asks { get; set; }

    [JsonProperty("bids")]
    public List<BidAsk> bids { get; set; }
}

public class BidAsk
{
    public decimal price { get; set; }
    public decimal volume { get; set; }
}

var jsonResponse = JsonConvert.DeserializeObject<Orderbook>(response);

After this operation i got:
jsonResponse.asks = null
jsonResponse.bids = null

What I've done wrong in deserialization?

Body:
How deserialize these responses if I don't know, which pair i got?
For example, two different requests:

1)https://yobit.net/api/3/depth/btc_usd?limit=5

2)https://yobit.net/api/3/depth/eth_usd?limit=5

Should I create a new JsonProperty for another pair "eth_usd"?

[JsonProperty("eth_usd")]
public Currency ETHToUSD{ get; set; }

In this case in each request all other attributes of class will be null.
I want to get something like this:

   var Asks = jsonresponse.pair_name.asks


问:
Set tooltip on a plottablejs linegraph from Angular directive
I got a angular directive that displays a plottable line graph. But I need to set tooltips whit the value when the cursor hovers the line im plotting.

I got something like this:

```<code>var plot = new Plottable.Plots.Line()
   .addDataset(ds)
   .x(project_x, xScale)
   .y(project_y, yScale)
   .attr('stroke', function(d) { return label; }, colorScale);
</code>```

and renders with

```<code>var svgElem = elem.find('svg')[0];
plot.renderTo(svgElem);
</code>```

That works greate :) and then I tries to add some tooltips from this example:
http://jsfiddle.net/gv1xsnkr/

```<code>// Initializing tooltip anchor
var tooltipAnchorSelection = plot.foreground().append("circle").attr({
  r: 3,
  opacity: 0
});
</code>```

In the example they are using jquery, I dont want to import jquery just for this

```<code>var tooltipAnchor = $(tooltipAnchorSelection.node());
tooltipAnchor.tooltip({
  animation: false,
  container: "body",
  placement: "auto",
  title: "text",
  trigger: "manual"
});
</code>```

So I tries to do it like this

```<code>var tooltipAnchor = document.querySelectorAll(tooltipAnchorSelection.node().nodeName);
</code>```

But I get an error on

```<code>tooltipAnchor.tooltip({ ... });
</code>```

angular.js:14516 TypeError: tooltipAnchor.tooltip is not a function

Anyone got a clue hot to do this?

答:
I had this problem using Vue.js, not Angular, but the problem sounds very similar. It was a problem of importing the libraries in the correct order:

First jquery (required by bootstrap)

Then bootstrap

How are you packaging your app?

I used gulp, so the sequence that worked for me was to put the jquery script tag in index.html and bootstrap = require('bootstrap') in the vue component (you'd put it in the directive). Requiring in bootstrap should be all that's necessary - that will give you access to the tooltip function.

Body:
I got a angular directive that displays a plottable line graph. But I need to set tooltips whit the value when the cursor hovers the line im plotting.

I got something like this:

var plot = new Plottable.Plots.Line()
   .addDataset(ds)
   .x(project_x, xScale)
   .y(project_y, yScale)
   .attr('stroke', function(d) { return label; }, colorScale);

and renders with

var svgElem = elem.find('svg')[0];
plot.renderTo(svgElem);

That works greate :) and then I tries to add some tooltips from this example:
http://jsfiddle.net/gv1xsnkr/

// Initializing tooltip anchor
var tooltipAnchorSelection = plot.foreground().append("circle").attr({
  r: 3,
  opacity: 0
});

In the example they are using jquery, I dont want to import jquery just for this

var tooltipAnchor = $(tooltipAnchorSelection.node());
tooltipAnchor.tooltip({
  animation: false,
  container: "body",
  placement: "auto",
  title: "text",
  trigger: "manual"
});

So I tries to do it like this

var tooltipAnchor = document.querySelectorAll(tooltipAnchorSelection.node().nodeName);

But I get an error on

tooltipAnchor.tooltip({ ... });

angular.js:14516 TypeError: tooltipAnchor.tooltip is not a function

Anyone got a clue hot to do this?


问:
How to prevent my process from being killed on logout in Windows?
How can I allow my process to persist after logout and not be killed, preferably without requiring the process to have administrator privileges? I am unable to use a service/scheduled task due to some peculiarities in the program.</p>

答:
The correct way to achieve this is through a Windows service. They are designed to run while the machine is on, independent of any interactive user logins.

You state in an edit that you aren't able to use a service. If that really is true then your task is not viable. My guess is that if you design your service correctly, perhaps interacting with a companion desktop app, then a service is perfectly feasible.

ContentLicense: CC BY-SA 4.0


问:
How to take screenshot a webpage using PHP for different browsers?
I want to know is it possible to take the the screen shot of webpage/url entered and get the response as .jpg/.png etc.

Here what I am specifically looking for is getting screen shots for different browsers i.e. the web page look on IE,FF,Safari etc.

Browser can be given as input at the time of giving the url.

Regards

Deepak

答: SeleniumRC has facilities to take screen shots and can be run against pretty much any browser and any of the supported languages which include PHP.</p>

ContentLicense: CC BY-SA 2.5


问:
Angular 1.4 View Encapsulation and Shadow DOM - is it possible?
I am in the process of changing my app from using Polymer to Angular 1.4 for stability reasons. Because of my familiarity with Polymer and web components (and future use of Angular 2) I am choosing to architect my app using the Component Pattern.

I have searched and thus far only come across this question and the solution was a no longer maintained github repo. I want to know if it is possible to have view encapsulation with Angular 1.4. In case I am misstating, specifically, can my directives with templates have their own encapsulated styles like is done in Polymer and Angular 2 without relying on Grunt?

答:
Seems like it is. I am using Angular 1.6 in my test, but I was able to get shadow DOM working inside an angular directive including bindings.

Here is my sample code:

```<code><!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8">
    <title>Angular 1.x ShadowDOM example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script>
    var app = angular.module('app', []);

    app.controller('myElController', ($scope) => {

    });

    var template = `
    <style>
    :host {
      left: 50%;
      position: fixed;
      top: 50%;
      transform: translate(-50%,-50%);
      border: 1px solid black;
      box-shadow: 4px 4px 4px rgba(0,0,0,.4);
      display: inline-block;
      padding: 6px 12px;
    }

    h3 {
      border-bottom: 1px solid #999;
      margin: 0 -12px 8px;
      padding: 0 12px 8px;
    }

    p {
      margin: 0;
    }
    </style>
        <h3>{{title}}</h3>
      <p>{{info}}</p>
    `;

    app.directive('myEl', ($compile) => {
        return {
          "restrict": "E",
          "controller": "myElController",
          "template": '',
          "scope": {
            "title": "@",
            "info": "@"
          },
          "link": function($scope, $element) {
            console.log('here');
            $scope.shadowRoot = $element[0].attachShadow({mode:'open'});
            $scope.shadowRoot.innerHTML = template;
            $compile($scope.shadowRoot)($scope);
          }
        };
    });
    </script>
  </head>
  <body>
    <div>
      <my-el title="This is a title" info="This is the info of the element"></my-el>
    </div>
    <div class="shell">
      <h3>Outside title (H3)</h3>
      <p>Outside content (P)</p>
    </div>
  </body>
</html>
</code>```

The trick is to not have a default template for the directive. Just us an empty string. Then, in the link function you would create the shadow root and set it's innerHTML to your real template. Then you need to run $compile on the shadow root to bind it back to the directive's $scope.

Be aware that this will only work on a browser that natively supports shadow DOM. Any Polyfill will not support real CSS encapsulation. For that it is better to use a form of BEM CSS: http://getbem.com/introduction/

Body:
Seems like it is. I am using Angular 1.6 in my test, but I was able to get shadow DOM working inside an angular directive including bindings.

Here is my sample code:

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8">
    <title>Angular 1.x ShadowDOM example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script>
    var app = angular.module('app', []);

    app.controller('myElController', ($scope) => {

    });

    var template = `
    <style>
    :host {
      left: 50%;
      position: fixed;
      top: 50%;
      transform: translate(-50%,-50%);
      border: 1px solid black;
      box-shadow: 4px 4px 4px rgba(0,0,0,.4);
      display: inline-block;
      padding: 6px 12px;
    }

    h3 {
      border-bottom: 1px solid #999;
      margin: 0 -12px 8px;
      padding: 0 12px 8px;
    }

    p {
      margin: 0;
    }
    </style>
        <h3>{{title}}</h3>
      <p>{{info}}</p>
    `;

    app.directive('myEl', ($compile) => {
        return {
          "restrict": "E",
          "controller": "myElController",
          "template": '',
          "scope": {
            "title": "@",
            "info": "@"
          },
          "link": function($scope, $element) {
            console.log('here');
            $scope.shadowRoot = $element[0].attachShadow({mode:'open'});
            $scope.shadowRoot.innerHTML = template;
            $compile($scope.shadowRoot)($scope);
          }
        };
    });
    </script>
  </head>
  <body>
    <div>
      <my-el title="This is a title" info="This is the info of the element"></my-el>
    </div>
    <div class="shell">
      <h3>Outside title (H3)</h3>
      <p>Outside content (P)</p>
    </div>
  </body>
</html>

The trick is to not have a default template for the directive. Just us an empty string. Then, in the link function you would create the shadow root and set it's innerHTML to your real template. Then you need to run $compile on the shadow root to bind it back to the directive's $scope.

Be aware that this will only work on a browser that natively supports shadow DOM. Any Polyfill will not support real CSS encapsulation. For that it is better to use a form of BEM CSS: http://getbem.com/introduction/


问:
Git dummy needs help on Windows
Admittedly, I'm new to Git.  I know... welcome to the century right!  But here's my issue...

I have a repo containing an Angular app.  The app happens to contain an MP4 video file that exceeds the 100mb GitHub limit.  (Before you recommend that the video shouldn't be local to the app... trust me, it needs to be in this particular case.)  My initial attempt to push the repo to GitHub failed due to the size of that one file.

So then I did something stupid...
I reverted the commit, thinking that it would simply revert back to the state that it was in prior to me attempting to push to GitHub.  But what it ACTUALLY did was restore my repo (entire app) to the original state that it was in when it was created by the Angular CLI... so it was just a new, blank app.

So I deleted the repo, restored my code from a backup, and started over.  This time, I added an exclusion for .mp4 to my .gitignore file.  I was confident that that exclusion would prevent git from trying to push the video up with the commit.  It did not.  So I'm basically in the same boat as yesterday.  I'm in the middle of an unsuccessful push.  The offending video file is in my History and I don't understand why it wasn't excluded, or what I should do to recover.

I am using GitHub Desktop for Windows.  And I have Git version 2.15.0 installed.

I understand that GitHub Desktop may not provide the solution that I need, as it seems to only provide a limited subset of git functionality.  I'm very comfortable working from a command line to do whatever needs to be done.  I'm just not sure what that is.  When attempting to search for solutions to similar scenarios, the responses didn't seem highly relevant, or didn't indicate that they would definitely resolve the issue.

Here is my .gitignore file

```<code># compiled output
/dist
/tmp
/out-tsc

# dependencies
/node_modules

# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
testem.log
/typings

# e2e
/e2e/*.js
/e2e/*.map

# System Files
.DS_Store
Thumbs.db

# Video file exclusion
.mp4
</code>```

答: Change the .mp4 to *.mp4, otherwise it will only match files named .mp4. You can use git rm --cached $(file) to remove files that are already committed without deleting them from the work tree.

Title: Git dummy needs help on Windows

Body:
Admittedly, I'm new to Git.  I know... welcome to the century right!  But here's my issue...

I have a repo containing an Angular app.  The app happens to contain an MP4 video file that exceeds the 100mb GitHub limit.  (Before you recommend that the video shouldn't be local to the app... trust me, it needs to be in this particular case.)  My initial attempt to push the repo to GitHub failed due to the size of that one file.

So then I did something stupid...
I reverted the commit, thinking that it would simply revert back to the state that it was in prior to me attempting to push to GitHub.  But what it ACTUALLY did was restore my repo (entire app) to the original state that it was in when it was created by the Angular CLI... so it was just a new, blank app.

So I deleted the repo, restored my code from a backup, and started over.  This time, I added an exclusion for .mp4 to my .gitignore file.  I was confident that that exclusion would prevent git from trying to push the video up with the commit.  It did not.  So I'm basically in the same boat as yesterday.  I'm in the middle of an unsuccessful push.  The offending video file is in my History and I don't understand why it wasn't excluded, or what I should do to recover.

I am using GitHub Desktop for Windows.  And I have Git version 2.15.0 installed.

I understand that GitHub Desktop may not provide the solution that I need, as it seems to only provide a limited subset of git functionality.  I'm very comfortable working from a command line to do whatever needs to be done.  I'm just not sure what that is.  When attempting to search for solutions to similar scenarios, the responses didn't seem highly relevant, or didn't indicate that they would definitely resolve the issue.

Here is my .gitignore file

# compiled output
/dist
/tmp
/out-tsc

# dependencies
/node_modules

# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
testem.log
/typings

# e2e
/e2e/*.js
/e2e/*.map

# System Files
.DS_Store
Thumbs.db

# Video file exclusion
.mp4


问:
Can't Start MySQL Service Ubuntu
After editing /etc/mysql/mysql.conf.d/mysqld.cnf to change my bind address to allow external connections to my MySQL database, I tried restarting the MySQL service to get the following error:

```<code>ubuntu@resonance:/var/www/html$ sudo service mysql start
Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details.
</code>```

upon typing both of those commands, I get the following:

```<code>Nov 15 17:45:06 resonance systemd[1]: Stopped MySQL Community Server.
-- Subject: Unit mysql.service has finished shutting down
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit mysql.service has finished shutting down.
Nov 15 17:45:06 resonance systemd[1]: Starting MySQL Community Server...
-- Subject: Unit mysql.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit mysql.service has begun starting up.
Nov 15 17:45:06 resonance audit[24219]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/24219/status" pid=24219 com
Nov 15 17:45:06 resonance audit[24219]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=24
Nov 15 17:45:06 resonance audit[24219]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/24219/status" pid=24219 com
Nov 15 17:45:06 resonance kernel: audit: type=1400 audit(1510767906.536:98): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="
Nov 15 17:45:06 resonance kernel: audit: type=1400 audit(1510767906.536:99): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="
Nov 15 17:45:06 resonance kernel: audit: type=1400 audit(1510767906.536:100): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name=
Nov 15 17:45:08 resonance systemd[1]: mysql.service: Main process exited, code=exited, status=1/FAILURE
Nov 15 17:45:26 resonance dhclient[1326]: DHCPREQUEST of 10.2.6.251 on ens3 to 10.2.11.18 port 67 (xid=0x7d5eaaff)
Nov 15 17:45:26 resonance dhclient[1326]: DHCPACK of 10.2.6.251 from 10.2.11.18
Nov 15 17:45:26 resonance root[24322]: /etc/dhcp/dhclient-enter-hooks.d/avahi-autoipd returned non-zero exit status 1
Nov 15 17:45:26 resonance dhclient[1326]: bound to 10.2.6.251 -- renewal in 53 seconds.
</code>```

and

```<code>● mysql.service - MySQL Community Server
   Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
   Active: activating (start-post) since Wed 2017-11-15 17:46:38 UTC; 84ms ago
  Process: 24586 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
 Main PID: 24595 (mysqld);         : 24596 (mysql-systemd-s)
    Tasks: 3
   Memory: 1.4M
      CPU: 86ms
   CGroup: /system.slice/mysql.service
           ├─24595 /usr/sbin/mysqld
           └─control
             ├─24596 /bin/bash /usr/share/mysql/mysql-systemd-start post
             └─24601 sleep 1

Nov 15 17:46:38 resonance systemd[1]: Starting MySQL Community Server...
</code>```

any idea what I'm doing wrong? This is the file I changed:

https://pastebin.com/pevhYMNK

EDIT
So I tried changing the bind IP back to 127.0.0.1 and it started working again. What do I have to do to allow external connections? I really need it working.

答: You should comment out bind-address and skip-netwroking lines in your config and then restart.

Title: Can't Start MySQL Service Ubuntu

Body:
After editing /etc/mysql/mysql.conf.d/mysqld.cnf to change my bind address to allow external connections to my MySQL database, I tried restarting the MySQL service to get the following error:

ubuntu@resonance:/var/www/html$ sudo service mysql start
Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details.

upon typing both of those commands, I get the following:

Nov 15 17:45:06 resonance systemd[1]: Stopped MySQL Community Server.
-- Subject: Unit mysql.service has finished shutting down
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit mysql.service has finished shutting down.
Nov 15 17:45:06 resonance systemd[1]: Starting MySQL Community Server...
-- Subject: Unit mysql.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit mysql.service has begun starting up.
Nov 15 17:45:06 resonance audit[24219]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/24219/status" pid=24219 com
Nov 15 17:45:06 resonance audit[24219]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=24
Nov 15 17:45:06 resonance audit[24219]: AVC apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/24219/status" pid=24219 com
Nov 15 17:45:06 resonance kernel: audit: type=1400 audit(1510767906.536:98): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="
Nov 15 17:45:06 resonance kernel: audit: type=1400 audit(1510767906.536:99): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="
Nov 15 17:45:06 resonance kernel: audit: type=1400 audit(1510767906.536:100): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name=
Nov 15 17:45:08 resonance systemd[1]: mysql.service: Main process exited, code=exited, status=1/FAILURE
Nov 15 17:45:26 resonance dhclient[1326]: DHCPREQUEST of 10.2.6.251 on ens3 to 10.2.11.18 port 67 (xid=0x7d5eaaff)
Nov 15 17:45:26 resonance dhclient[1326]: DHCPACK of 10.2.6.251 from 10.2.11.18
Nov 15 17:45:26 resonance root[24322]: /etc/dhcp/dhclient-enter-hooks.d/avahi-autoipd returned non-zero exit status 1
Nov 15 17:45:26 resonance dhclient[1326]: bound to 10.2.6.251 -- renewal in 53 seconds.

and

● mysql.service - MySQL Community Server
   Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
   Active: activating (start-post) since Wed 2017-11-15 17:46:38 UTC; 84ms ago
  Process: 24586 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
 Main PID: 24595 (mysqld);         : 24596 (mysql-systemd-s)
    Tasks: 3
   Memory: 1.4M
      CPU: 86ms
   CGroup: /system.slice/mysql.service
           ├─24595 /usr/sbin/mysqld
           └─control
             ├─24596 /bin/bash /usr/share/mysql/mysql-systemd-start post
             └─24601 sleep 1

Nov 15 17:46:38 resonance systemd[1]: Starting MySQL Community Server...

any idea what I'm doing wrong? This is the file I changed:

https://pastebin.com/pevhYMNK

EDIT
So I tried changing the bind IP back to 127.0.0.1 and it started working again. What do I have to do to allow external connections? I really need it working.