答:
Here you go:

$(document).ready(function(){

  var uniqueKeys = [];
var resultsTable = $('#results');
$(resultsTable).find('tbody > tr').each(function() {

 var currentAuditIdentity = $(this).data().auditidentity;
  var currentActivityLogId = $(this).data().activitylogid;
  var tableName = $(this).find('td:eq(0)').text();
  var tableAction = $(this).find('td:eq(1)').text();
  var uniqueKey = {'Name': tableName, 'Action': tableAction, 'AuditIdentity':currentAuditIdentity, 'ActivityLogId':currentActivityLogId};

 var matchingElements = $.grep(uniqueKeys, function(item){
    return (item != null && item.Name == uniqueKey.Name && item.Action == uniqueKey.Action);
  });
  if (matchingElements.length == 0) {
    uniqueKeys.push(uniqueKey);
  }
  else {
  matchingElements[0].AuditIdentity += ',' + currentAuditIdentity;
    // After we have what we need, remove the combined row as we are combining the keys into one row
    $(this).remove();
  }
});
//Finally, put the latest data back into the remaining unique rows
$.each(uniqueKeys, function(index, value){
  var item = $(resultsTable).find('tr').find('td:eq(0):contains("' + value.Name + '")').parent();
     item.data().auditidentity = value.AuditIdentity;
});
//Just to show the data result.
$('span#showArrayData').text(JSON.stringify(uniqueKeys));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="results">
<tbody role="alert" aria-live="polite" aria-relevant="all" data-auditidentity="18487179,18487183">
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487186" data-auditid="f831583e-d1a9-4e35-ac92-82a5cb48c62e">
    <td class="  sorting_1">Selection</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487179" data-auditid="88506880-632f-4e17-bceb-ebd4e20e435a">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487181" data-auditid="a2768380-8c4a-4070-9834-900f95db77a2">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487182" data-auditid="cb54deca-2bc4-4b71-ba5a-0e6d075b7b26">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487183" data-auditid="05803858-aaba-4f9b-9128-fc0c265cfaf6">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
</tbody></table>
<span id="showArrayData"></span></code>```

This will solve your problem.

Title: Updating a data attribute of a TR with jQuery

Body:
Here you go:

$(document).ready(function(){

  var uniqueKeys = [];
var resultsTable = $('#results');
$(resultsTable).find('tbody > tr').each(function() {

 var currentAuditIdentity = $(this).data().auditidentity;
  var currentActivityLogId = $(this).data().activitylogid;
  var tableName = $(this).find('td:eq(0)').text();
  var tableAction = $(this).find('td:eq(1)').text();
  var uniqueKey = {'Name': tableName, 'Action': tableAction, 'AuditIdentity':currentAuditIdentity, 'ActivityLogId':currentActivityLogId};

 var matchingElements = $.grep(uniqueKeys, function(item){
    return (item != null && item.Name == uniqueKey.Name && item.Action == uniqueKey.Action);
  });
  if (matchingElements.length == 0) {
    uniqueKeys.push(uniqueKey);
  }
  else {
  matchingElements[0].AuditIdentity += ',' + currentAuditIdentity;
    // After we have what we need, remove the combined row as we are combining the keys into one row
    $(this).remove();
  }
});
//Finally, put the latest data back into the remaining unique rows
$.each(uniqueKeys, function(index, value){
  var item = $(resultsTable).find('tr').find('td:eq(0):contains("' + value.Name + '")').parent();
     item.data().auditidentity = value.AuditIdentity;
});
//Just to show the data result.
$('span#showArrayData').text(JSON.stringify(uniqueKeys));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="results">
<tbody role="alert" aria-live="polite" aria-relevant="all" data-auditidentity="18487179,18487183">
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487186" data-auditid="f831583e-d1a9-4e35-ac92-82a5cb48c62e">
    <td class="  sorting_1">Selection</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487179" data-auditid="88506880-632f-4e17-bceb-ebd4e20e435a">
    <td class="  sorting_1">Procedure</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487181" data-auditid="a2768380-8c4a-4070-9834-900f95db77a2">
    <td class="  sorting_1">Procedure</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487182" data-auditid="cb54deca-2bc4-4b71-ba5a-0e6d075b7b26">
    <td class="  sorting_1">Procedure</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487183" data-auditid="05803858-aaba-4f9b-9128-fc0c265cfaf6">
    <td class="  sorting_1">Procedure</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
</tbody></table>
<span id="showArrayData"></span>

This will solve your problem.


来源: stackexchange

问:
Why aren't my animation keyframes triggering on hover?
Description:

I can't figure out why the items with the class .specialItem's animation wont trigger. If you can figure out why, that would be great. The background / border changes no hover but it won't fade in like it should.

$(window).on("resize", function() {
    var itemPercent = $("#percent");
    var itemCE = $("#ce");
    var itemC = $("#c");
    var itemDEL = $("#del");
    var itemDivide = $("#divide");
    var itemRoot = $("#squareRoot");
    var itemSeven = $("#seven");
    var itemEight = $("#eight");
    var itemNine = $("#nine");
    var itemMultiply = $("#multiply");
    var itemSupTwo = $("#supTwo");
    var itemFour = $("#four");
    var itemFive = $("#five");
    var itemSix = $("#six");
    var itemMinus = $("#minus");
    var itemSupThree = $("#supThree");
    var itemOne = $("#one");
    var itemTwo = $("#two");
    var itemThree = $("#three");
    var itemPlus = $("#plus");
    var itemUnSymbol = $("#unknownSymbol");
    var itemPosNeg = $("#posNeg");
    var itemZero = $("#zero");
    var itemDecimal = $("#decimal");
    var itemEquals = $("#equals");

    var defaultHeightCalc = $(window).height() - $(".output").height() - $(".special").height();
    $(".default").css("height", defaultHeightCalc);

    var itemHeightCalc = ($(".default").height() / 5 - 13);
    var itemWidthCalc = ($(".default").width() / 5 - 10);
    $(".item").css({
        "height": itemHeightCalc,
        "width": itemWidthCalc
    });
    $(".itemIconAlign").css("top", ($(".item").height() / 2) - ($(".itemIconAlign").height() / 2));
}).resize();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://fonts.googleapis.com/css?family=Droid+Sans+Mono|Pacifico|Oxygen);
body {
    background: #EEEEEE;
    overflow: hidden;
}
.wrapper {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
}
.storage {
    height: 100%;
    width: 19%;
    position: absolute;
    top: 0px;
    right: 0px;
}
.main {
    height: 100%;
    width: 81%;
    position: absolute;
    top: 0px;
    left: 0px;
}
.output {
    height: 25%;
    width: 100%;
    position: relative;
    top: 0px;
    left: 0px;
    font-family: 'Roboto', sans-serif;
    font-weight: 900;
    font-size: 104px;
    text-align: right;
}
.numLineAlign {
    position: relative;
    top: 30%;
    right: 0px;
    width: 100%;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.input {
    width: 100%;
    position: relative;
    top: 0%;
    left: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.special {
    height: 50px;
    width: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
}
.default {
    width: 100%;
    position: absolute;
    top: 50px;
    left: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.storageNav {
    height: 70px;
    width: 100%;
    position: relative;
    top: 0px;
    right: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.storageTab {
    height: 25%;
    position: relative;
    top: 25%;
    left: 0px;
    color: black;
    text-align: center;
    padding: 20px;
    display: inline-block;
    font-family: 'Raleway', sans-serif;
    font-weight: 600;
    cursor: default;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.item {
    text-align: center;
    background: white;
    display: inline-block;
    margin: 2px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    cursor: pointer;
    min-height: 50px;
}
.item:hover {
    -webkit-filter: brightness(80%);
    filter: brightness(80%);
}
#percent, #ce, #c, #del, #divide, #decimal, #minus, #plus, #equals,
#squareRoot, #supTwo, #supThree, #unknownSymbol, #posNeg, #multiply {
    background: #E0E0E0;
    font-family: 'Raleway', sans-serif;
    font-weight: 400;
    font-size: 20px;
}
#one, #two, #three, #four, #five,
#six, #seven, #eight, #nine, #zero {
    font-family: 'Raleway', sans-serif;
    font-weight: 800;
    font-size: 20px;
}
.itemIconAlign {
    position: relative;
    left: 0px;
}
.specialItem {
    display: inline-block;
    font-family: 'Raleway', sans-serif;
    font-weight: 800;
    font-size: 12px;
    text-align: center;
    padding: 25px;
    margin-top: -23px;
    cursor: pointer;
    border: 2px solid transparent;
}
.specialItem:hover {
    background: #E0E0E0;
    border: 2px solid white;
    animation: fade 1s;
}
@keyframes fade {
    0% {
        background: #E0E0E0;
        border: 2px solid white;
    }
    100% {
        background: #E0E0E0;
        border: 2px solid white;
    }
}</code>```

History

Memory

                0

MC

MR

M+

M-

MS

%

CE

C

DEL

÷

√

7

8

9

*

x2

4

5

6

-

x3

1

2

3

+

1/x

±

0

●

=

```

答:
You need to have different values on 0% and 100% of your animation.

```<code>@keyframes fade {
    0% {background: #EEE; border: 2px solid #EEE;}
    100% {}
}
</code>```

Also you can remove animation and use transition, in general when you would use only 0% and 100% you can use simple transition instead.

```<code>.specialItem {
    transition: all 1s;
}

.specialItem:hover {
    background: #E0E0E0;
    border: 2px solid white;
}
</code>```

See snippet below.

$(window).on("resize", function() {
    var itemPercent = $("#percent");
    var itemCE = $("#ce");
    var itemC = $("#c");
    var itemDEL = $("#del");
    var itemDivide = $("#divide");
    var itemRoot = $("#squareRoot");
    var itemSeven = $("#seven");
    var itemEight = $("#eight");
    var itemNine = $("#nine");
    var itemMultiply = $("#multiply");
    var itemSupTwo = $("#supTwo");
    var itemFour = $("#four");
    var itemFive = $("#five");
    var itemSix = $("#six");
    var itemMinus = $("#minus");
    var itemSupThree = $("#supThree");
    var itemOne = $("#one");
    var itemTwo = $("#two");
    var itemThree = $("#three");
    var itemPlus = $("#plus");
    var itemUnSymbol = $("#unknownSymbol");
    var itemPosNeg = $("#posNeg");
    var itemZero = $("#zero");
    var itemDecimal = $("#decimal");
    var itemEquals = $("#equals");

    var defaultHeightCalc = $(window).height() - $(".output").height() - $(".special").height();
    $(".default").css("height", defaultHeightCalc);

    var itemHeightCalc = ($(".default").height() / 5 - 13);
    var itemWidthCalc = ($(".default").width() / 5 - 10);
    $(".item").css({ "height" : itemHeightCalc, "width" : itemWidthCalc });
    $(".itemIconAlign").css("top", ($(".item").height() / 2) - ($(".itemIconAlign").height() / 2));
   }).resize();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://fonts.googleapis.com/css?family=Droid+Sans+Mono|Pacifico|Oxygen);

body {
background: #EEEEEE;
overflow: hidden;
}

.wrapper {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
}

.storage {
height: 100%;
width: 19%;
position: absolute;
top: 0px;
right: 0px;
}

.main {
height: 100%;
width: 81%;
position: absolute;
top: 0px;
left: 0px;
}

.output {
height: 25%;
width: 100%;
position: relative;
top: 0px;
left: 0px;
font-family: 'Roboto', sans-serif;
font-weight: 900;
font-size: 104px;
text-align: right;
}

.numLineAlign {
position: relative;
top: 30%;
right: 0px;
width: 100%;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.input {
width: 100%;
position: relative;
top: 0%;
left: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.special {
height: 50px;
width: 100%;
position: absolute;
top: 0px;
left: 0px;
}

.default {
width: 100%;
position: absolute;
top: 50px;
left: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.storageNav {
height: 70px;
width: 100%;
position: relative;
top: 0px;
right: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.storageTab {
height: 25%;
position: relative;
top: 25%;
left: 0px;
color: black;
text-align: center;
padding: 20px;
display: inline-block;
font-family: 'Raleway', sans-serif;
font-weight: 600;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.item {
text-align: center;
background: white;
display: inline-block;
margin: 2px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: pointer;
min-height: 50px;
}

.item:hover {
-webkit-filter: brightness(80%);
filter: brightness(80%);
}

#percent, #ce, #c, #del, #divide, #decimal, #minus, #plus, #equals, #squareRoot, #supTwo, #supThree, #unknownSymbol, #posNeg, #multiply {
background: #E0E0E0;
font-family: 'Raleway', sans-serif;
font-weight: 400;
font-size: 20px;
}

#one, #two, #three, #four, #five, #six, #seven, #eight, #nine, #zero {
font-family: 'Raleway', sans-serif;
font-weight: 800;
font-size: 20px;
}

.itemIconAlign {
position: relative;
left: 0px;
}

.specialItem {
display: inline-block;
font-family: 'Raleway', sans-serif;
font-weight: 800;
font-size: 12px;
text-align: center;
padding: 25px;
margin-top: -23px;
cursor: pointer;
border: 2px solid transparent;
}

.specialItem {
    transition: all 1s;
}

.specialItem:hover {
    background: #E0E0E0;
    border: 2px solid white;
}</code>```

History

Memory

        0

MC

MR

M+

M-

MS

%

CE

C

DEL

÷

√

7

8

9

*

x2

4

5

6

-

x3

1

2

3

+

1/x

±

0

●

=

```

ContentLicense: CC BY-SA 3.0

Body:
Description:

I can't figure out why the items with the class .specialItem's animation wont trigger. If you can figure out why, that would be great. The background / border changes no hover but it won't fade in like it should.

$(window).on("resize", function() {
    var itemPercent = $("#percent");
    var itemCE = $("#ce");
    var itemC = $("#c");
    var itemDEL = $("#del");
    var itemDivide = $("#divide");
    var itemRoot = $("#squareRoot");
    var itemSeven = $("#seven");
    var itemEight = $("#eight");
    var itemNine = $("#nine");
    var itemMultiply = $("#multiply");
    var itemSupTwo = $("#supTwo");
    var itemFour = $("#four");
    var itemFive = $("#five");
    var itemSix = $("#six");
    var itemMinus = $("#minus");
    var itemSupThree = $("#supThree");
    var itemOne = $("#one");
    var itemTwo = $("#two");
    var itemThree = $("#three");
    var itemPlus = $("#plus");
    var itemUnSymbol = $("#unknownSymbol");
    var itemPosNeg = $("#posNeg");
    var itemZero = $("#zero");
    var itemDecimal = $("#decimal");
    var itemEquals = $("#equals");

    var defaultHeightCalc = $(window).height() - $(".output").height() - $(".special").height();
    $(".default").css("height", defaultHeightCalc);

    var itemHeightCalc = ($(".default").height() / 5 - 13);
    var itemWidthCalc = ($(".default").width() / 5 - 10);
    $(".item").css({
        "height": itemHeightCalc,
        "width": itemWidthCalc
    });
    $(".itemIconAlign").css("top", ($(".item").height() / 2) - ($(".itemIconAlign").height() / 2));
}).resize();

@import url(https://fonts.googleapis.com/css?family=Droid+Sans+Mono|Pacifico|Oxygen);
body {
    background: #EEEEEE;
    overflow: hidden;
}
.wrapper {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
}
.storage {
    height: 100%;
    width: 19%;
    position: absolute;
    top: 0px;
    right: 0px;
}
.main {
    height: 100%;
    width: 81%;
    position: absolute;
    top: 0px;
    left: 0px;
}
.output {
    height: 25%;
    width: 100%;
    position: relative;
    top: 0px;
    left: 0px;
    font-family: 'Roboto', sans-serif;
    font-weight: 900;
    font-size: 104px;
    text-align: right;
}
.numLineAlign {
    position: relative;
    top: 30%;
    right: 0px;
    width: 100%;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.input {
    width: 100%;
    position: relative;
    top: 0%;
    left: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.special {
    height: 50px;
    width: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
}
.default {
    width: 100%;
    position: absolute;
    top: 50px;
    left: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.storageNav {
    height: 70px;
    width: 100%;
    position: relative;
    top: 0px;
    right: 0px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.storageTab {
    height: 25%;
    position: relative;
    top: 25%;
    left: 0px;
    color: black;
    text-align: center;
    padding: 20px;
    display: inline-block;
    font-family: 'Raleway', sans-serif;
    font-weight: 600;
    cursor: default;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.item {
    text-align: center;
    background: white;
    display: inline-block;
    margin: 2px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    cursor: pointer;
    min-height: 50px;
}
.item:hover {
    -webkit-filter: brightness(80%);
    filter: brightness(80%);
}
#percent, #ce, #c, #del, #divide, #decimal, #minus, #plus, #equals,
#squareRoot, #supTwo, #supThree, #unknownSymbol, #posNeg, #multiply {
    background: #E0E0E0;
    font-family: 'Raleway', sans-serif;
    font-weight: 400;
    font-size: 20px;
}
#one, #two, #three, #four, #five,
#six, #seven, #eight, #nine, #zero {
    font-family: 'Raleway', sans-serif;
    font-weight: 800;
    font-size: 20px;
}
.itemIconAlign {
    position: relative;
    left: 0px;
}
.specialItem {
    display: inline-block;
    font-family: 'Raleway', sans-serif;
    font-weight: 800;
    font-size: 12px;
    text-align: center;
    padding: 25px;
    margin-top: -23px;
    cursor: pointer;
    border: 2px solid transparent;
}
.specialItem:hover {
    background: #E0E0E0;
    border: 2px solid white;
    animation: fade 1s;
}
@keyframes fade {
    0% {
        background: #E0E0E0;
        border: 2px solid white;
    }
    100% {
        background: #E0E0E0;
        border: 2px solid white;
    }
}

History

Memory

                0

MC

MR

M+

M-

MS

%

CE

C

DEL

÷

√

7

8

9

*

x2

4

5

6

-

x3

1

2

3

+

1/x

±

0

●

=

Body:
You need to have different values on 0% and 100% of your animation.

@keyframes fade {
    0% {background: #EEE; border: 2px solid #EEE;}
    100% {}
}

Also you can remove animation and use transition, in general when you would use only 0% and 100% you can use simple transition instead.

.specialItem {
    transition: all 1s;
}

.specialItem:hover {
    background: #E0E0E0;
    border: 2px solid white;
}

See snippet below.

$(window).on("resize", function() {
    var itemPercent = $("#percent");
    var itemCE = $("#ce");
    var itemC = $("#c");
    var itemDEL = $("#del");
    var itemDivide = $("#divide");
    var itemRoot = $("#squareRoot");
    var itemSeven = $("#seven");
    var itemEight = $("#eight");
    var itemNine = $("#nine");
    var itemMultiply = $("#multiply");
    var itemSupTwo = $("#supTwo");
    var itemFour = $("#four");
    var itemFive = $("#five");
    var itemSix = $("#six");
    var itemMinus = $("#minus");
    var itemSupThree = $("#supThree");
    var itemOne = $("#one");
    var itemTwo = $("#two");
    var itemThree = $("#three");
    var itemPlus = $("#plus");
    var itemUnSymbol = $("#unknownSymbol");
    var itemPosNeg = $("#posNeg");
    var itemZero = $("#zero");
    var itemDecimal = $("#decimal");
    var itemEquals = $("#equals");

    var defaultHeightCalc = $(window).height() - $(".output").height() - $(".special").height();
    $(".default").css("height", defaultHeightCalc);

    var itemHeightCalc = ($(".default").height() / 5 - 13);
    var itemWidthCalc = ($(".default").width() / 5 - 10);
    $(".item").css({ "height" : itemHeightCalc, "width" : itemWidthCalc });
    $(".itemIconAlign").css("top", ($(".item").height() / 2) - ($(".itemIconAlign").height() / 2));
   }).resize();

@import url(https://fonts.googleapis.com/css?family=Droid+Sans+Mono|Pacifico|Oxygen);

body {
background: #EEEEEE;
overflow: hidden;
}

.wrapper {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
}

.storage {
height: 100%;
width: 19%;
position: absolute;
top: 0px;
right: 0px;
}

.main {
height: 100%;
width: 81%;
position: absolute;
top: 0px;
left: 0px;
}

.output {
height: 25%;
width: 100%;
position: relative;
top: 0px;
left: 0px;
font-family: 'Roboto', sans-serif;
font-weight: 900;
font-size: 104px;
text-align: right;
}

.numLineAlign {
position: relative;
top: 30%;
right: 0px;
width: 100%;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.input {
width: 100%;
position: relative;
top: 0%;
left: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.special {
height: 50px;
width: 100%;
position: absolute;
top: 0px;
left: 0px;
}

.default {
width: 100%;
position: absolute;
top: 50px;
left: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.storageNav {
height: 70px;
width: 100%;
position: relative;
top: 0px;
right: 0px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.storageTab {
height: 25%;
position: relative;
top: 25%;
left: 0px;
color: black;
text-align: center;
padding: 20px;
display: inline-block;
font-family: 'Raleway', sans-serif;
font-weight: 600;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.item {
text-align: center;
background: white;
display: inline-block;
margin: 2px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: pointer;
min-height: 50px;
}

.item:hover {
-webkit-filter: brightness(80%);
filter: brightness(80%);
}

#percent, #ce, #c, #del, #divide, #decimal, #minus, #plus, #equals, #squareRoot, #supTwo, #supThree, #unknownSymbol, #posNeg, #multiply {
background: #E0E0E0;
font-family: 'Raleway', sans-serif;
font-weight: 400;
font-size: 20px;
}

#one, #two, #three, #four, #five, #six, #seven, #eight, #nine, #zero {
font-family: 'Raleway', sans-serif;
font-weight: 800;
font-size: 20px;
}

.itemIconAlign {
position: relative;
left: 0px;
}

.specialItem {
display: inline-block;
font-family: 'Raleway', sans-serif;
font-weight: 800;
font-size: 12px;
text-align: center;
padding: 25px;
margin-top: -23px;
cursor: pointer;
border: 2px solid transparent;
}

.specialItem {
    transition: all 1s;
}

.specialItem:hover {
    background: #E0E0E0;
    border: 2px solid white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
     <div class="storage">
      <div class="storageNav">
       <div class="storageTab">History</div>
       <div class="storageTab">Memory</div>
      </div>
      <div class="storageBox">

      </div>
     </div>
     <div class="main">
      <div class="output">
       <div class="numLineAlign">
        0
       </div>
      </div>
      <div class="input">
        <div class="special">
         <div class="specialItem" id="memClean">MC</div>
         <div class="specialItem" id="memRead">MR</div>
         <div class="specialItem" id="memAdd">M+</div>
         <div class="specialItem" id="memRemove">M-</div>
         <div class="specialItem" id="memStore">MS</div>
        </div>
        <div class="default">
         <div class="row" id="r1">
          <div class="item" id="percent">
           <div class="itemIconAlign">%</div>
          </div>

          <div class="item" id="ce">
           <div class="itemIconAlign">CE</div>
          </div>

          <div class="item" id="c">
           <div class="itemIconAlign">C</div>
          </div>

          <div class="item" id="del">
           <div class="itemIconAlign">DEL</div>
          </div>

          <div class="item" id="divide">
           <div class="itemIconAlign">÷</div>
          </div>
         </div>
         <div class="row" id="r2">
          <div class="item" id="squareRoot">
           <div class="itemIconAlign">√</div>
          </div>

          <div class="item" id="seven">
           <div class="itemIconAlign">7</div>
          </div>

          <div class="item" id="eight">
           <div class="itemIconAlign">8</div>
          </div>

          <div class="item" id="nine">
           <div class="itemIconAlign">9</div>
          </div>

          <div class="item" id="multiply">
           <div class="itemIconAlign">*</div>
          </div>
         </div>
         <div class="row" id="r3">
          <div class="item" id="supTwo">
           <div class="itemIconAlign">x<sup>2</sup></div>
          </div>

          <div class="item" id="four">
           <div class="itemIconAlign">4</div>
          </div>

          <div class="item" id="five">
           <div class="itemIconAlign">5</div>
          </div>

          <div class="item" id="six">
           <div class="itemIconAlign">6</div>
          </div>

          <div class="item" id="minus">
           <div class="itemIconAlign">-</div>
          </div>
         </div>
         <div class="row" id="r4">
          <div class="item" id="supThree">
           <div class="itemIconAlign">x<sup>3</sup></div>
          </div>

          <div class="item" id="one">
           <div class="itemIconAlign">1</div>
          </div>

          <div class="item" id="two">
           <div class="itemIconAlign">2</div>
          </div>

          <div class="item" id="three">
           <div class="itemIconAlign">3</div>
          </div>

          <div class="item" id="plus">
           <div class="itemIconAlign">+</div>
          </div>
         </div>
         <div class="row" id="r5">
          <div class="item" id="unknownSymbol">
           <div class="itemIconAlign"><sup>1</sup>/x</div>
          </div>

          <div class="item" id="posNeg">
           <div class="itemIconAlign">±</div>
          </div>

          <div class="item" id="zero">
           <div class="itemIconAlign">0</div>
          </div>

          <div class="item" id="decimal">
           <div class="itemIconAlign">●</div>
          </div>

          <div class="item" id="equals">
           <div class="itemIconAlign">=</div>
          </div>
         </div>
        </div>
      </div>
     </div>
  </div>


问:
SQLCommand in C# Not Supplying Parameter
I have a function in c# that is to insert data. All it is supposed to do is call a stored procedure given from a Request Body that I supply through Fiddler. Right now I'm trying to test it but I keep getting this error.

"Procedure or function 'spCreatePerson' expects parameter '@first', which was not supplied."

Here is the object-

```<code>public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string Phone { get; set; }

    public string Email { get; set; }

    public int PersonTypeId { get; set; }
}
</code>```

Here is the request body -

```<code>{"FirstName":"Test","LastName":"MuhFuh","Phone":"5555555555","Email":"test@gmail.com","PersonTypeId":1}
</code>```

Here is the function for calling the proc-

```<code>public static int InsertData(string procName, Person p)
    {
        int rowsAffected = 0;

        con = CreateConnection();

        using (con)
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd = new SqlCommand("spCreatePerson", con);

            cmd.Parameters.AddWithValue("@first", p.FirstName);
            cmd.Parameters.AddWithValue("@last", p.LastName);
            cmd.Parameters.AddWithValue("@email", p.Email);
            cmd.Parameters.AddWithValue("@phone", p.Phone);
            cmd.Parameters.AddWithValue("@pTypeID", p.PersonTypeId);

            rowsAffected = cmd.ExecuteNonQuery();
        }

        return rowsAffected;
    }
</code>```

As you can see I passed in the parameter but am getting this error. Is there something I missed in the code? I stepped through it and the data seems to be passed just fine.

EDIT

Here is the stored procedure-

```<code>CREATE PROC [dbo].[spCreatePerson] @first nvarchar(100), @last
nvarchar(100), @email nvarchar(50), @phone nvarchar(100), @pTypeID int

AS

INSERT INTO Person(FirstName, LastName, Email, Phone, PersonTypeID)
VALUES(@first, @last, @email, @phone, @pTypeID)

GO
</code>```

答:
This might be the culprit, but at the very least this is a variable in the whole equation to eliminate.  These lines are very suspect:

```<code>cmd.CommandType = CommandType.StoredProcedure;
cmd = new SqlCommand("spCreatePerson", con);
</code>```

For one thing, the second line is completely negating the first.  They should be swapped:

```<code>cmd = new SqlCommand("spCreatePerson", con);
cmd.CommandType = CommandType.StoredProcedure;
</code>```

But more to the point, they illustrate a much bigger potential problem.  Namely...

Where are cmd and con even declared and created?

If you're using connection and command objects which exist in a larger scope, you're potentially sharing them with other operations.  This is a bad thing, and can lead to very difficult to diagnose bugs.

As a general rule of thumb, one should declare, create, use, and dispose of commands and connections in as small a scope as possible.

You're not gaining anything by keeping them around, the underlying system is pretty well optimized.  But what you are doing is opening up the possibility of bugs and strange behavior in the code.

The structure should basically be (in somewhat-pseudo-code):

```<code>using (var con = new Connection())
using (var cmd = new Command(con))
    // set parameters, command type, etc.
    // execute the command, get any results you might need
}
// any follow-up logic, etc.
</code>```

Body:
I have a function in c# that is to insert data. All it is supposed to do is call a stored procedure given from a Request Body that I supply through Fiddler. Right now I'm trying to test it but I keep getting this error.

"Procedure or function 'spCreatePerson' expects parameter '@first', which was not supplied."

Here is the object-

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string Phone { get; set; }

    public string Email { get; set; }

    public int PersonTypeId { get; set; }
}

Here is the request body -

{"FirstName":"Test","LastName":"MuhFuh","Phone":"5555555555","Email":"test@gmail.com","PersonTypeId":1}

Here is the function for calling the proc-

public static int InsertData(string procName, Person p)
    {
        int rowsAffected = 0;

        con = CreateConnection();

        using (con)
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd = new SqlCommand("spCreatePerson", con);

            cmd.Parameters.AddWithValue("@first", p.FirstName);
            cmd.Parameters.AddWithValue("@last", p.LastName);
            cmd.Parameters.AddWithValue("@email", p.Email);
            cmd.Parameters.AddWithValue("@phone", p.Phone);
            cmd.Parameters.AddWithValue("@pTypeID", p.PersonTypeId);

            rowsAffected = cmd.ExecuteNonQuery();
        }

        return rowsAffected;
    }

As you can see I passed in the parameter but am getting this error. Is there something I missed in the code? I stepped through it and the data seems to be passed just fine.

EDIT

Here is the stored procedure-

CREATE PROC [dbo].[spCreatePerson] @first nvarchar(100), @last
nvarchar(100), @email nvarchar(50), @phone nvarchar(100), @pTypeID int

AS

INSERT INTO Person(FirstName, LastName, Email, Phone, PersonTypeID)
VALUES(@first, @last, @email, @phone, @pTypeID)

GO

Body:
This might be the culprit, but at the very least this is a variable in the whole equation to eliminate.  These lines are very suspect:

cmd.CommandType = CommandType.StoredProcedure;
cmd = new SqlCommand("spCreatePerson", con);

For one thing, the second line is completely negating the first.  They should be swapped:

cmd = new SqlCommand("spCreatePerson", con);
cmd.CommandType = CommandType.StoredProcedure;

But more to the point, they illustrate a much bigger potential problem.  Namely...

Where are cmd and con even declared and created?

If you're using connection and command objects which exist in a larger scope, you're potentially sharing them with other operations.  This is a bad thing, and can lead to very difficult to diagnose bugs.

As a general rule of thumb, one should declare, create, use, and dispose of commands and connections in as small a scope as possible.

You're not gaining anything by keeping them around, the underlying system is pretty well optimized.  But what you are doing is opening up the possibility of bugs and strange behavior in the code.

The structure should basically be (in somewhat-pseudo-code):

using (var con = new Connection())
using (var cmd = new Command(con))
    // set parameters, command type, etc.
    // execute the command, get any results you might need
}
// any follow-up logic, etc.


问:
How to create new windows for subsequent matplotlib plots?
Currently using Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 23 2016, 11:57:41) on Windows (64 bits).

I want a procedure that I am writing to generate two different plots. One plot will have three separate graphs and then I want a separate window that shows a histogram.

```<code>plt.subplot(311)
plt.plot(z)
plt.xlabel('Time(s)', fontsize=14)
plt.ylabel('Amplitude(v)', fontsize=8)
fig.subplots_adjust(hspace=.5)
plt.figure
plt.subplot(312)
plt.plot(timey[0:(len(freq))//2],y)
plt.xlabel('Frequency(Hz)', fontsize=14)
plt.ylabel('Amplitude(V)', fontsize=8)
plt.subplot(313)
plt.plot(fre, psd)
plt.xlabel('Frequency(Hz)', fontsize=14)
plt.ylabel('Power Spectrum Density(Watts/Hz)', fontsize =8)
plt.show()
np.savetxt( file ,y, delimiter='  ',newline='  ')
plt.savefig('FFT'+i+'.png', bbox_inches='tight')
wait = input("PRESS ENTER TO CONTINUE.")   #an attempt at breakpoints
plt.figure
plt.subplot(111)
plt.plot(bin[0:bnn],his)
plt.show()
plt.savefig('Histogram'+i+'.png', bbox_inches='tight')
</code>```

Even using plt.figure(), I still plot overtop of existing plots unless I use plt.subplot(111), which erases the original plot and places the new one in the same window. I am hoping to generate two separate windows. I have read several previous questions to no avail. I tried using %matplotlib qt or what I have imported mpl as, but also no use. Perhaps I do not understand the syntax for this?

答:
First note that plt.figure does nothing. You would need to call plt.figure(). However, this is not solving the actual problem.

Since the old figure with 3 subplots is still the current figure at the point you want to start a new one, plt.figure() will simply get you the old figure.

To get a new figure, use a new figure number.

```<code>plt.figure(2)
</code>```

Body:
Currently using Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 23 2016, 11:57:41) on Windows (64 bits).

I want a procedure that I am writing to generate two different plots. One plot will have three separate graphs and then I want a separate window that shows a histogram.

plt.subplot(311)
plt.plot(z)
plt.xlabel('Time(s)', fontsize=14)
plt.ylabel('Amplitude(v)', fontsize=8)
fig.subplots_adjust(hspace=.5)
plt.figure
plt.subplot(312)
plt.plot(timey[0:(len(freq))//2],y)
plt.xlabel('Frequency(Hz)', fontsize=14)
plt.ylabel('Amplitude(V)', fontsize=8)
plt.subplot(313)
plt.plot(fre, psd)
plt.xlabel('Frequency(Hz)', fontsize=14)
plt.ylabel('Power Spectrum Density(Watts/Hz)', fontsize =8)
plt.show()
np.savetxt( file ,y, delimiter='  ',newline='  ')
plt.savefig('FFT'+i+'.png', bbox_inches='tight')
wait = input("PRESS ENTER TO CONTINUE.")   #an attempt at breakpoints
plt.figure
plt.subplot(111)
plt.plot(bin[0:bnn],his)
plt.show()
plt.savefig('Histogram'+i+'.png', bbox_inches='tight')

Even using plt.figure(), I still plot overtop of existing plots unless I use plt.subplot(111), which erases the original plot and places the new one in the same window. I am hoping to generate two separate windows. I have read several previous questions to no avail. I tried using %matplotlib qt or what I have imported mpl as, but also no use. Perhaps I do not understand the syntax for this?

Body:
First note that plt.figure does nothing. You would need to call plt.figure(). However, this is not solving the actual problem.

Since the old figure with 3 subplots is still the current figure at the point you want to start a new one, plt.figure() will simply get you the old figure.

To get a new figure, use a new figure number.

plt.figure(2)


问:
IE7 problems with displaying text in TD
I can not figure out why the text inside the TD is not displayed in IE7. I am frustrated to the core cuz it works in FF! All I am trying to do is dynamically build a table onload... Any help will be greatly appreciated.
The complete script is at pastebin </p>

答: IE needs a TBODY. Just add it as the first child of your table and then append your rows and cells to that.</p>

ContentLicense: CC BY-SA 2.5

Title: IE7 problems with displaying text in TD


问:
embed my two latest youtube uploads on my site using javascript
I know that there have been older answers to this question but I cant seem to find one that currently works. I want to be able to have my two latest uploads displayed on my website so users can watch them right there and not have to go to youtube. I have no code currently since I have no clue as to how this would be done.</p>

答:
without API, show playlist (latest video)

```<code><iframe src="https://www.youtube.com/embed/?listType=user_uploads&list={username}"></iframe>
</code>```

with API, javascript

```<code><div id="myvideo"></div>
</code>```

maxResults=2 limit 2 result video

```<code>$.ajax({
  url: 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={your_channelId}&maxResults=2&order=date&type=video&key={API_KEY}',
  success: function(response, status) {
    for(var i = 0; i < response.items.length; i++) {
      var video = '<iframe src="https://www.youtube.com/embed/' + response.items[i].id.videoId + '"></iframe>';
      $("#myvideo").append(video);
    }
  }
})
</code>```

Body:
without API, show playlist (latest video)

<iframe src="https://www.youtube.com/embed/?listType=user_uploads&list={username}"></iframe>

with API, javascript

<div id="myvideo"></div>

maxResults=2 limit 2 result video

$.ajax({
  url: 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={your_channelId}&maxResults=2&order=date&type=video&key={API_KEY}',
  success: function(response, status) {
    for(var i = 0; i < response.items.length; i++) {
      var video = '<iframe src="https://www.youtube.com/embed/' + response.items[i].id.videoId + '"></iframe>';
      $("#myvideo").append(video);
    }
  }
})


问:
How do I separate these image picker function?
I want to upload a third and maybe more images onto the image view but I don't know how to separate the third image. The first two works fine, how do I add the third function, i mostly need help on the func image picker controller i think.</p>

```<code>var selected = 1

@IBAction func pickImage1(_ sender: Any) {

    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image.allowsEditing = false
    selected = 1

    self.present(image, animated: true)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        if selected == 1 {
            myImageView1.image = image
        } else {
            myImageView2.image = image
            return
        }
       //i tried putting myImageView3 here but it just replaced the 2nd

    }
    else {
        //error
    }
    self.dismiss(animated: true, completion: nil)
}

@IBAction func pickImage2(_ sender: Any) {

       let image2 = UIImagePickerController()
    image2.delegate = self
    image2.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image2.allowsEditing = false
    selected = 2

    self.present(image2, animated: true)
}

@IBAction func pickImage3(_ sender: Any) {
    let image3 = UIImagePickerController()
    image3.delegate = self
    image3.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image3.allowsEditing = false
    selected = 3

    self.present(image3, animated: true)
}
</code>```

答:
First, add an unique tag for each image view. Avoid using 0 because the default tag is 0. So you will have image views with tags say 1 to 3. Set each image view like this

On your viewDidLoad, add a tap listener to all your image views. Call this method on all three image views one by one

```<code>let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.tag = 1
imageView.addGestureRecognizer(tapGestureRecognizer)
</code>```

Then in image tap handler, record which image view is tapped by recording it's tag number. Since tag numbers are unique, we can use that to figure out which image view is tapped later

```<code>func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image.allowsEditing = false
    let tappedImage = tapGestureRecognizer.view as! UIImageView
    selected = tappedImage.tag
    self.present(image, animated: true)
}
</code>```

Finally in image pick delegate, find your image view from it's parent view. Say you are adding your image views to self.view, simply get your view in this way and set image

```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        if let imageView = self.view.viewWithTag(selected) as? UIImageView {
            imageView.image = image
        }
    }
    else {
        //error
    }
    self.dismiss(animated: true, completion: nil)
}
</code>```

Body:
I want to upload a third and maybe more images onto the image view but I don't know how to separate the third image. The first two works fine, how do I add the third function, i mostly need help on the func image picker controller i think.

var selected = 1

@IBAction func pickImage1(_ sender: Any) {

    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image.allowsEditing = false
    selected = 1

    self.present(image, animated: true)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        if selected == 1 {
            myImageView1.image = image
        } else {
            myImageView2.image = image
            return
        }
       //i tried putting myImageView3 here but it just replaced the 2nd

    }
    else {
        //error
    }
    self.dismiss(animated: true, completion: nil)
}

@IBAction func pickImage2(_ sender: Any) {

       let image2 = UIImagePickerController()
    image2.delegate = self
    image2.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image2.allowsEditing = false
    selected = 2

    self.present(image2, animated: true)
}

@IBAction func pickImage3(_ sender: Any) {
    let image3 = UIImagePickerController()
    image3.delegate = self
    image3.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image3.allowsEditing = false
    selected = 3

    self.present(image3, animated: true)
}

Body:
First, add an unique tag for each image view. Avoid using 0 because the default tag is 0. So you will have image views with tags say 1 to 3. Set each image view like this

On your viewDidLoad, add a tap listener to all your image views. Call this method on all three image views one by one

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.tag = 1
imageView.addGestureRecognizer(tapGestureRecognizer)

Then in image tap handler, record which image view is tapped by recording it's tag number. Since tag numbers are unique, we can use that to figure out which image view is tapped later

func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image.allowsEditing = false
    let tappedImage = tapGestureRecognizer.view as! UIImageView
    selected = tappedImage.tag
    self.present(image, animated: true)
}

Finally in image pick delegate, find your image view from it's parent view. Say you are adding your image views to self.view, simply get your view in this way and set image

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        if let imageView = self.view.viewWithTag(selected) as? UIImageView {
            imageView.image = image
        }
    }
    else {
        //error
    }
    self.dismiss(animated: true, completion: nil)
}


问:
Chart.JS To Not Start At 0
I am attempting to have my chart to NOT start at 0.  I have this syntax, which works perfectly ->

```<code>var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
        responsive: true,
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: 'Title'
        }
    }
})
</code>```

However, when I try to add in the below - the beginAtZero the page will no longer display my chart.

```<code>var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
        responsive: true,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: false
                }
            }]
        },
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: 'Title'
        }
    }
});
</code>```

What is the proper way to add in the false for start at 0 with Chart.JS

EDIT

Per comment below, I added in the missing comma, however the chart still begins at 0?

EDIT 2

Added image below of my data.  I am after the xAxes to not start at 0 and I want the yAxes to be formatted as currency with $ sign and , commas (if possible)

This is a screenshot of my chart

EDIT 3

This is the console.log() of my JSON data
(13) ["Hornsby", 0, 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 99]
0:"Hornsby"
1:0
2:0
3:100
4:200
5:300
6:400
7:500
8:600
9:700
10:800
11:900
12:99
length:13

Edit 4

I am querying MSSQL and storing the results in an array - then passing the array to JSON for JQuery to parse.  Below is full syntax (excluding DB conenction & query info)

```<code><?php
$db->setQuery($sql);
$rows = $db->loadRowList();
$output = array();
foreach( $rows as $row ) {
array_push($output, $row);
}
$data = json_encode($output[0]);?>

`<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>

<script>
var jsondata = <?php echo $data; ?>;
var values = [];
for (var i in jsondata) {
values.push(jsondata[i]);
}
var labelsarr = Object.keys(jsondata);
var barChartData = {
labels: labelsarr,
datasets: [{
label: 'Dollar Amount',
backgroundColor:'rgba(200, 200, 200, 0.75)',
borderColor: 'rgb(255, 99, 132)',
borderWidth: 1,
data: values
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Sample Data'
}
}
});
</script>
</body>
</html>`
</code>```

答:
I am unable to reproduce the issue.

It works as long as you have this setting beginAtZero: false - this works for the yAxis, however.

It seems that you are looking for handling the array returned.  I would simply modify the chart similar to demo below.

See demo below

window.onload = function() {
  var barChartData = {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    datasets: [{
      label: 'Hornsby',
      backgroundColor: '#ff0000',
      borderColor: '#ff9900',
      borderWidth: 1,
      data: [0, 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 99]
    }]
  };

  var ctx = document.getElementById("canvas").getContext("2d");

  window.myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
      responsive: true,
      scales: {
        xAxes: [{
          ticks: {
            beginAtZero: false,
            suggestedMin: 3
          }
        }]
      },
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: 'Title'
      }
    }
  });
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
  width: 500px;
  height: 300px;
  border: 1px solid lightgrey;
}</code>```

<canvas id="canvas"></canvas>```
</div>
</div>
</p>

<p><strong>UPDATE</strong></p>

<p>The code from your PHP/JS could change slightly as well.  Assuming your data looks like this: </p>

<blockquote>
  <p>["Stanley",0,0,10,20,30,50000,400000,70000,700,800,900,1111]</p>
</blockquote>

<p>Then you could make these changes (note: I have not tested them)</p>

```var jsondata = <?php echo $data; ?>;
var values = [];

// Iterate through loop starting at position 1
// (position zero has a name, not a value)
for (var i=1; i<jsondata.length; i++) {
    values.push(jsondata[i]);  // we end up with 12 values
}

// this could be hard-coded
var labelsarr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
 ...
// label could be coming from the data set
// the first element in the array has a label, let's use it
label: jsondata[0],
```

Title: Chart.JS To Not Start At 0

Body:
I am attempting to have my chart to NOT start at 0.  I have this syntax, which works perfectly ->

var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
        responsive: true,
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: 'Title'
        }
    }
})

However, when I try to add in the below - the beginAtZero the page will no longer display my chart.

var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
        responsive: true,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: false
                }
            }]
        },
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: 'Title'
        }
    }
});

What is the proper way to add in the false for start at 0 with Chart.JS

EDIT

Per comment below, I added in the missing comma, however the chart still begins at 0?

EDIT 2

Added image below of my data.  I am after the xAxes to not start at 0 and I want the yAxes to be formatted as currency with $ sign and , commas (if possible)

This is a screenshot of my chart

EDIT 3

This is the console.log() of my JSON data
(13) ["Hornsby", 0, 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 99]
0:"Hornsby"
1:0
2:0
3:100
4:200
5:300
6:400
7:500
8:600
9:700
10:800
11:900
12:99
length:13

Edit 4

I am querying MSSQL and storing the results in an array - then passing the array to JSON for JQuery to parse.  Below is full syntax (excluding DB conenction & query info)

<?php
$db->setQuery($sql);
$rows = $db->loadRowList();
$output = array();
foreach( $rows as $row ) {
array_push($output, $row);
}
$data = json_encode($output[0]);?>

`

<canvas id="canvas"></canvas>

`

Body:
I am unable to reproduce the issue.

It works as long as you have this setting beginAtZero: false - this works for the yAxis, however.

It seems that you are looking for handling the array returned.  I would simply modify the chart similar to demo below.

See demo below

window.onload = function() {
  var barChartData = {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    datasets: [{
      label: 'Hornsby',
      backgroundColor: '#ff0000',
      borderColor: '#ff9900',
      borderWidth: 1,
      data: [0, 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 99]
    }]
  };

  var ctx = document.getElementById("canvas").getContext("2d");

  window.myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
      responsive: true,
      scales: {
        xAxes: [{
          ticks: {
            beginAtZero: false,
            suggestedMin: 3
          }
        }]
      },
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: 'Title'
      }
    }
  });
};

#canvas {
  width: 500px;
  height: 300px;
  border: 1px solid lightgrey;
}

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

<canvas id="canvas"></canvas>

UPDATE

The code from your PHP/JS could change slightly as well.  Assuming your data looks like this:

["Stanley",0,0,10,20,30,50000,400000,70000,700,800,900,1111]

Then you could make these changes (note: I have not tested them)

var jsondata = <?php echo $data; ?>;
var values = [];

// Iterate through loop starting at position 1
// (position zero has a name, not a value)
for (var i=1; i<jsondata.length; i++) {
    values.push(jsondata[i]);  // we end up with 12 values
}

// this could be hard-coded
var labelsarr = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
 ...
// label could be coming from the data set
// the first element in the array has a label, let's use it
label: jsondata[0],


答:
You have a lot of repeated code. Create a single function for selecting a picture. Simply have each button action save off the appropriate image view that will be set once the picture is selected.

Here's the updated code:

```<code>var selectedImageView: UIImageView? = nil

@IBAction func pickImage1(_ sender: Any) {
    selectedImageView = myImageView1

    selectPicture()
}

@IBAction func pickImage2(_ sender: Any) {
    selectedImageView = myImageView2

    selectPicture()
}

@IBAction func pickImage3(_ sender: Any) {
    selectedImageView = myImageView3

    selectPicture()
}

func selectImage() {
    let picker = UIImagePickerController()
    picker.delegate = self
    picker.sourceType = .photoLibrary
    picker.allowsEditing = false

    present(image, animated: true)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        if let imageView = selectedImageView {
            imageView.image = image
        }
    }

    selectedImageView = nil

    self.dismiss(animated: true, completion: nil)
}
</code>```

You can also use a single button action if you give each button a unique tag. Let's say you give the 3 buttons the tags 1, 2, and 3. Replace the 3 pickImageX methods with one:

```<code>@IBAction func pickImage(_ sender: UIButton) {
    switch sender.tag {
    case 1:
        selectedImageView = myImageView1
    case 2:
        selectedImageView = myImageView2
    case 3:
        selectedImageView = myImageView3
    default:
        break
    }

    if selectedImageView != nil {
        selectPicture()
    }
}
</code>```

This assumes you are using a UIButton for this. Adjust as needed otherwise.

Title: How do I separate these image picker function?

Body:
You have a lot of repeated code. Create a single function for selecting a picture. Simply have each button action save off the appropriate image view that will be set once the picture is selected.

Here's the updated code:

var selectedImageView: UIImageView? = nil

@IBAction func pickImage1(_ sender: Any) {
    selectedImageView = myImageView1

    selectPicture()
}

@IBAction func pickImage2(_ sender: Any) {
    selectedImageView = myImageView2

    selectPicture()
}

@IBAction func pickImage3(_ sender: Any) {
    selectedImageView = myImageView3

    selectPicture()
}

func selectImage() {
    let picker = UIImagePickerController()
    picker.delegate = self
    picker.sourceType = .photoLibrary
    picker.allowsEditing = false

    present(image, animated: true)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        if let imageView = selectedImageView {
            imageView.image = image
        }
    }

    selectedImageView = nil

    self.dismiss(animated: true, completion: nil)
}

You can also use a single button action if you give each button a unique tag. Let's say you give the 3 buttons the tags 1, 2, and 3. Replace the 3 pickImageX methods with one:

@IBAction func pickImage(_ sender: UIButton) {
    switch sender.tag {
    case 1:
        selectedImageView = myImageView1
    case 2:
        selectedImageView = myImageView2
    case 3:
        selectedImageView = myImageView3
    default:
        break
    }

    if selectedImageView != nil {
        selectPicture()
    }
}

This assumes you are using a UIButton for this. Adjust as needed otherwise.


问:
Android Opencv Submat null object reference
I am trying to detect a color of a static image using the algorithm from color blob detection from android opencv.

I have a problem around the submat() area but I have installed the opencv correctly. Getting this error:
PS: mRgba is declared as Mat

```<code> java.lang.NullPointerException: Attempt to invoke virtual method 'org.opencv.core.Mat org.opencv.core.Mat.submat(org.opencv.core.Rect)' on a null object reference
                                                                                at com.example.backup.contour_image.MainActivity.onTouch(MainActivity.java:103)
                                                                                at android.view.View.dispatchTouchEvent(View.java:9406)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2668)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2257)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2668)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2257)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2668)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2257)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2668)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2257)
</code>```

My code

```<code> public boolean onTouch(View v, MotionEvent event)
{
    //mDetector = new ColorBlobDetector();
    Bitmap bm =((BitmapDrawable)iv.getDrawable()).getBitmap();
    Mat touchedRegionHsv = new Mat();
    Log.e(TAG,"Touched!");
    Utils.bitmapToMat(bm,touchedRegionHsv,true);

    Scalar lower = new Scalar(22,255,255);
    Scalar upper = new Scalar(38,100,100);

    Rect roi = new Rect();

    int x = (int)event.getX();
    int y = (int)event.getY();

    roi.x = (x>4) ? x-4 : 0;
    roi.y = (y>4) ? y-4 : 0;

    roi.width = 8;
    roi.height = 8;

    Mat touchedRegionRgba = mRgba.submat(roi);    //<--------------- line of error
    Mat touchedRegionRgba_clone = touchedRegionRgba.clone();

    Imgproc.cvtColor(touchedRegionRgba,touchedRegionHsv,Imgproc.COLOR_RGB2HSV);
    Core.inRange(touchedRegionHsv,lower,upper,touchedRegionRgba_clone);

    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Mat heirarchy = new Mat();
    Imgproc.findContours(touchedRegionRgba_clone,contours,heirarchy,Imgproc.RETR_EXTERNAL,Imgproc.CHAIN_APPROX_NONE);

    return false;
}
</code>```

答: You need to check if mRgba is null before mRgba.submit().

Body:
I am trying to detect a color of a static image using the algorithm from color blob detection from android opencv.

I have a problem around the submat() area but I have installed the opencv correctly. Getting this error:
PS: mRgba is declared as Mat

 java.lang.NullPointerException: Attempt to invoke virtual method 'org.opencv.core.Mat org.opencv.core.Mat.submat(org.opencv.core.Rect)' on a null object reference
                                                                                at com.example.backup.contour_image.MainActivity.onTouch(MainActivity.java:103)
                                                                                at android.view.View.dispatchTouchEvent(View.java:9406)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2668)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2257)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2668)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2257)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2668)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2257)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2668)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2257)

My code

 public boolean onTouch(View v, MotionEvent event)
{
    //mDetector = new ColorBlobDetector();
    Bitmap bm =((BitmapDrawable)iv.getDrawable()).getBitmap();
    Mat touchedRegionHsv = new Mat();
    Log.e(TAG,"Touched!");
    Utils.bitmapToMat(bm,touchedRegionHsv,true);

    Scalar lower = new Scalar(22,255,255);
    Scalar upper = new Scalar(38,100,100);

    Rect roi = new Rect();

    int x = (int)event.getX();
    int y = (int)event.getY();

    roi.x = (x>4) ? x-4 : 0;
    roi.y = (y>4) ? y-4 : 0;

    roi.width = 8;
    roi.height = 8;

    Mat touchedRegionRgba = mRgba.submat(roi);    //<--------------- line of error
    Mat touchedRegionRgba_clone = touchedRegionRgba.clone();

    Imgproc.cvtColor(touchedRegionRgba,touchedRegionHsv,Imgproc.COLOR_RGB2HSV);
    Core.inRange(touchedRegionHsv,lower,upper,touchedRegionRgba_clone);

    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Mat heirarchy = new Mat();
    Imgproc.findContours(touchedRegionRgba_clone,contours,heirarchy,Imgproc.RETR_EXTERNAL,Imgproc.CHAIN_APPROX_NONE);

    return false;
}


问:
Can I detect XHTML parsing errors using Javascript?
When I have a markup error in my XHTML page, Mozilla Firefox displays the "Yellow Screen of Death", showing only a large red error message on a yellow background.

While these errors are rare, they are extremely user-unfriendly.

Is there a way I can detect these using Javascript, and thereby send a message back to the server?

What I've discovered so far:
 - Scripts placed before the parsing error still run. (Of course.)
 - Timeouts and intervals that were set in these scripts will still execute after the parsing error.
 - In Firefox, the DOM is a <parsererror> with a <sourcetext> inside it. I can detect this if I query document.firstChild.tagName.

Remaining questions:
 - What events are available that I could listen for to detect this happening? (Polling sucks.)
 - How can I detect this in other browsers?

答:
My first question would be: Since Internet Explorer does not easily allow you to actually specify application/xhtml+xml as the mime type, nor support it all that well, why do you need to detect XHTML parse errors?

As for detecting the errors - have a look at http://www.quirksmode.org

OwnerDisplayName: phyzome

OwnerDisplayName: cofie


问:
Best way to access package.json version and build variables in react native app?
I'm building a react native iOS app, and would like to:

1) Display the app's current version from the package.json file in the app itself.

Specifically: Now that I've implemented codepush, I want to display the current app version on the Settings page, so that app users can tell if their app has been upgraded. I currently set the version number in the package.json file and use this shell script to propagate that to the xcode project. If there's a better way to manage/update a projects version number, please let me know!

2) Execute certain .js code based on build variables from xcode.

I have three build configurations (Debug, Staging, Release) setup in xcode, and I would like to specify the updateDialog: true flag to codepush only for Staging builds. I would also like to display on the settings page whether this is a Debug, Staging or Release build.

What is the best way to accomplish these things?

Are there best practices for setting/syncing a project's version number and accessing it within the app, or is this stuff usually just coded by hand?

Fwiw, this answer is relevant, but doesn't say what specific environment variables xcode defines that would help me here, and doesn't speak to the versioning question.

答:
```<code>async function getAppVersion() {
  const {appVersion} = await codePush.getConfiguration();

  const meta = await codePush.getUpdateMetadata();
  if (!meta) return {appVersion};

  const {label} = meta;
  return {appVersion, label};
}
</code>```

label will contain codepush release label (by default v1, v2...)

For env variables react-native-config maybe can help you. I am using fastlane with increment_build_number (iOS) and handmade fastlane code (Android) to autoincrement build number. To be honest I'm on my own in best practice search.

Body:
async function getAppVersion() {
  const {appVersion} = await codePush.getConfiguration();

  const meta = await codePush.getUpdateMetadata();
  if (!meta) return {appVersion};

  const {label} = meta;
  return {appVersion, label};
}

label will contain codepush release label (by default v1, v2...)

For env variables react-native-config maybe can help you. I am using fastlane with increment_build_number (iOS) and handmade fastlane code (Android) to autoincrement build number. To be honest I'm on my own in best practice search.


问:
"Commit failed for offsets" while committing offset asynchronously
I have a kafka consumer from which I am consuming data from a particular topic and I am seeing below exception. I am using 0.10.0.0 kafka version.

```<code>LoggingCommitCallback.onComplete: Commit failed for offsets= {....}, eventType= some_type, time taken= 19ms, error= org.apache.kafka.clients.consumer.CommitFailedException: Commit cannot be completed since the group has already rebalanced and assigned the partitions to another member. This means that the time between subsequent calls to poll() was longer than the configured session.timeout.ms, which typically implies that the poll loop is spending too much time message processing. You can address this either by increasing the session timeout or by reducing the maximum size of batches returned in poll() with max.poll.records.
</code>```

I added these two extra consumer properties but still it didn't helped:

```<code>session.timeout.ms=20000
max.poll.records=500
</code>```

I am committing offsets in a different background thread as shown below:

```<code>kafkaConsumer.commitAsync(new LoggingCommitCallback(consumerType.name()));
</code>```

What does that error mean and how can I resolve it? Do I need to add some other consumer properties?

答: Yes, lower max.poll.records. You'll get smaller batches of data but there more frequent calls to poll that will result will help keep the session alive.</p>

Body:
I have a kafka consumer from which I am consuming data from a particular topic and I am seeing below exception. I am using 0.10.0.0 kafka version.

LoggingCommitCallback.onComplete: Commit failed for offsets= {....}, eventType= some_type, time taken= 19ms, error= org.apache.kafka.clients.consumer.CommitFailedException: Commit cannot be completed since the group has already rebalanced and assigned the partitions to another member. This means that the time between subsequent calls to poll() was longer than the configured session.timeout.ms, which typically implies that the poll loop is spending too much time message processing. You can address this either by increasing the session timeout or by reducing the maximum size of batches returned in poll() with max.poll.records.

I added these two extra consumer properties but still it didn't helped:

session.timeout.ms=20000
max.poll.records=500

I am committing offsets in a different background thread as shown below:

kafkaConsumer.commitAsync(new LoggingCommitCallback(consumerType.name()));

What does that error mean and how can I resolve it? Do I need to add some other consumer properties?


问:
function in C returns always the same arbitrary number
So i´m trying to get the power of any two numbers,

```<code>int expo(int base, int expon){
    int z = 1;
    printf("%i",&z);  // Here i get 635678
    if (expon == 0){
        printf("A");  // this gets printed if expon== 0
        return 1;
    }
    else{
        for (int x=0; x < expon; x++){
            z *= base;
            printf("%i",&z); // here i get 6356780
        }
        return z;
    }

}
</code>```

The thing that amazes me the most is the first 635678, i just told the computer that z = 1 !, the second one is that when it prints A, it doesnt even return 1. It always return 6356776. ( i just declare an int value as being the result of the function and print the int, maybe i even do that bad). I dont care about this particular function, i just want to know what i am telling to the computer, because it is obviously not what i think.
Thanks and sorry because there is a good chance that this question should not be here.

答:
Well, you're doing it wrong like this:

```<code>printf("%i",&z);
</code>```

%i is for printing an integer, but what you pass is a pointer to an integer -- you apply the & (address of) operator.

This is undefined behavior. Simple solution: remove the &.

I have a theory how you got to this code: you were probably taught to use scanf() for reading input (another thing I would question, but let's put this aside for now).

With scanf(), you need to pass a pointer to an int with the %i conversion specifier. But that's because scanf() has to set the value of a variable, and as in C, variables are passed by value, this is only possible through a pointer.

printf() on the other hand only needs a value to print, it doesn't have to modify anything. So it directly expects this value, not a pointer to it.

Body:
So i´m trying to get the power of any two numbers,

int expo(int base, int expon){
    int z = 1;
    printf("%i",&z);  // Here i get 635678
    if (expon == 0){
        printf("A");  // this gets printed if expon== 0
        return 1;
    }
    else{
        for (int x=0; x < expon; x++){
            z *= base;
            printf("%i",&z); // here i get 6356780
        }
        return z;
    }

}

The thing that amazes me the most is the first 635678, i just told the computer that z = 1 !, the second one is that when it prints A, it doesnt even return 1. It always return 6356776. ( i just declare an int value as being the result of the function and print the int, maybe i even do that bad). I dont care about this particular function, i just want to know what i am telling to the computer, because it is obviously not what i think.
Thanks and sorry because there is a good chance that this question should not be here.

Body:
Well, you're doing it wrong like this:

printf("%i",&z);

%i is for printing an integer, but what you pass is a pointer to an integer -- you apply the & (address of) operator.

This is undefined behavior. Simple solution: remove the &.

I have a theory how you got to this code: you were probably taught to use scanf() for reading input (another thing I would question, but let's put this aside for now).

With scanf(), you need to pass a pointer to an int with the %i conversion specifier. But that's because scanf() has to set the value of a variable, and as in C, variables are passed by value, this is only possible through a pointer.

printf() on the other hand only needs a value to print, it doesn't have to modify anything. So it directly expects this value, not a pointer to it.


问:
Create Ubuntu Server resource on Azure with Terraform.io
I really like Terraform.io and I'd like to adopt it for my new project.

I am trying to deploy a Ubuntu Server on my Azure subscription using Terraform.

I have created an example.tf file with this content:

```<code># Configure Azure provider
provider "azure" {
  publish_settings = "${file("credentials.publishsettings")}"
}

# Create web server
resource "azure_instance" "web" {
  image = "Ubuntu Server 16.04 LTS"
  location = "ukwest"
  name = "some_name"
  size = "A0"
  username = "some_user"
}
</code>```

When I run

```<code>terraform apply
</code>```

I get this error:

```<code>* azure_instance.web: When using a platform image, the 'storage' parameter is required
</code>```

So I tried to add an storage parameter in the resource element, like this:

```<code># Create web server
resource "azure_instance" "web" {
  image = "Ubuntu Server 16.04 LTS"
  storage = "abc"
  location = "ukwest"
  name = "cloudlabs"
  size = "A0"
  username = "cloudlabs"
}
</code>```

But then I get this other error message:

```<code>* azure_instance.web: : invalid or unknown key: storage
</code>```

... And I'm stuck in here. I'm probably doing something wrong that is very obvious since this is my first tf file. Any ideas welcome!

答:
I'm not an Azure user, but as long as I see the document, it looks like storage_service_name instead of storage.

See: https://www.terraform.io/docs/providers/azure/r/instance.html#storage_service_name

Body:
I really like Terraform.io and I'd like to adopt it for my new project.

I am trying to deploy a Ubuntu Server on my Azure subscription using Terraform.

I have created an example.tf file with this content:

# Configure Azure provider
provider "azure" {
  publish_settings = "${file("credentials.publishsettings")}"
}

# Create web server
resource "azure_instance" "web" {
  image = "Ubuntu Server 16.04 LTS"
  location = "ukwest"
  name = "some_name"
  size = "A0"
  username = "some_user"
}

When I run

terraform apply

I get this error:

* azure_instance.web: When using a platform image, the 'storage' parameter is required

So I tried to add an storage parameter in the resource element, like this:

# Create web server
resource "azure_instance" "web" {
  image = "Ubuntu Server 16.04 LTS"
  storage = "abc"
  location = "ukwest"
  name = "cloudlabs"
  size = "A0"
  username = "cloudlabs"
}

But then I get this other error message:

* azure_instance.web: : invalid or unknown key: storage

... And I'm stuck in here. I'm probably doing something wrong that is very obvious since this is my first tf file. Any ideas welcome!


问:
Excel-Add-in-ASPNET-QuickBooks sample from github not loading in Excel
I have just downloaded and unzipped and followed the "change your IDs" part of the add-in steps here https://github.com/OfficeDev/Excel-Add-in-ASPNET-QuickBooks

When I try to load it by pressing F5 (Start Debug), Excel does start, and it looks like it's trying to load in a pane on the right (not a button on the ribbon like I'm expecting?), but it says Loading... for a while and then a red-X pops for a second too fast that I can see/click, but then it goes back to  Loading... and my HDD is thrashing..
There are no errors that I can see, but I would like to know what that red-X is, and ultimately have the button show on the ribbon.

I don't have to do an "install" per-se, do I? I think that side pane is doing the install, but failing, and I can't find a log anywhere..

答:
Turns out I needed an Excel update..
I had ProcMon running and tried to analyze minidumps and tried everything else that I could think of..

Still a touch of wonkiness (like having to copy my 32-bit .exe as the 64) but it at least loads in Excel now.


问:
System.out.print is overlapping the questions why?
My problem is when i run the program it runs all the System.out.print right but when i run
it for the second student some of it overlaps like so:

```<code>"Enter the second student's name: Enter the student's score: "
</code>```

instead of

```<code>"Enter the second students's name: "

"Enter the student's score: "
</code>```

I also can not input data into the System.out.print method of the second student

My main code where the error is:

```<code>System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: ");
    score = reader.nextInt();
    student1.setScore(i, score);
}

System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: "); //program skips to here to input
//data
    score = reader.nextInt();
    student2.setScore(i, score);
}
</code>```

the part that deals with the error from the class is as follows

```<code>public void setName(String nm){
    name = nm;
}
</code>```

答: Could you more clearly describe this 'overlapping'? In your original question your 'one versus the other' were identical.  Make it a code sample if need be to preserve spacing and such,</p>

Body:
My problem is when i run the program it runs all the System.out.print right but when i run
it for the second student some of it overlaps like so:

"Enter the second student's name: Enter the student's score: "

instead of

"Enter the second students's name: "

"Enter the student's score: "

I also can not input data into the System.out.print method of the second student

My main code where the error is:

System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: ");
    score = reader.nextInt();
    student1.setScore(i, score);
}

System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: "); //program skips to here to input
//data
    score = reader.nextInt();
    student2.setScore(i, score);
}

the part that deals with the error from the class is as follows

public void setName(String nm){
    name = nm;
}


答: You are printing the location in memory of your variable z not the value z contains. if you put & in front of the variable you get the address in memory, just put printf("%i", z), to get his value.</p>

Title: function in C returns always the same arbitrary number


问:
Python: Matplotlib imshow shift xlabel numbers
Is it possible to shift the x and y axis label numbers for example +2 ? For example i have this image created, but i want that the label numbers begin with 2:

My code for this was :

```<code>jacaardMatrix = 1.662887377173091485e-01    3.432835820895522305e-01    3.568320278503046006e-01
5.065963060686015651e-02    3.160270880361173984e-01    3.374888691006233121e-01
3.093987157034442520e-02    1.802120141342756221e-01    1.748178980228928259e-01

fig2=plt.figure()
plt.title("Radius and FRC Jacaard Values for Scoring System: "+str(i))
plt.xlabel('Radius')
plt.ylabel('FRC Size')
plt.imshow(jacaardMatrix)
</code>```

答:
You can use the extent argument of imshow to set the scale of the plot. To have it scale from 2 to 5 use

```<code>plt.imshow(jacaardMatrix, extent=[2,5,2,5])
</code>```

where the first two numbers denote the x range and the second two numbers the y range.

Body:
Is it possible to shift the x and y axis label numbers for example +2 ? For example i have this image created, but i want that the label numbers begin with 2:

My code for this was :

jacaardMatrix = 1.662887377173091485e-01    3.432835820895522305e-01    3.568320278503046006e-01
5.065963060686015651e-02    3.160270880361173984e-01    3.374888691006233121e-01
3.093987157034442520e-02    1.802120141342756221e-01    1.748178980228928259e-01

fig2=plt.figure()
plt.title("Radius and FRC Jacaard Values for Scoring System: "+str(i))
plt.xlabel('Radius')
plt.ylabel('FRC Size')
plt.imshow(jacaardMatrix)

Body:
You can use the extent argument of imshow to set the scale of the plot. To have it scale from 2 to 5 use

plt.imshow(jacaardMatrix, extent=[2,5,2,5])

where the first two numbers denote the x range and the second two numbers the y range.


问:
Setting AWS S3 Region
I am trying to create an aws s3 bucket using the following java code.

```<code>AmazonS3 s3client = AmazonS3ClientBuilder.defaultClient();
    s3client.setRegion(Region.getRegion(Regions.AP_SOUTH_1));
</code>```

But I am getting the following error:

"exception": "com.amazonaws.SdkClientException",
    "message": "Unable to find a region via the region provider chain. Must provide an explicit region in the builder or setup environment to supply a region."

Am I trying to set region in an incorrect way? Please advice.

答:
If you are not using any proxies and you already setup your credentials, you can use below code:

```<code>AmazonS3 s3client = AmazonS3ClientBuilder.standard()
.withRegion(Region.getRegion(Regions.AP_SOUTH_1));
</code>```

But if you need to setup a proxy and manually set the credentials, you can use below code:

```<code>AWSCredentials cred = new BasicAWSCredentials(<accessKey>,<secretKey>);
AmazonS3 s3client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(cred))
.withClientConfiguration(<your configuration>)
.withRegion(Region.getRegion(Regions.AP_SOUTH_1));
</code>```

Title: Setting AWS S3 Region

Body:
I am trying to create an aws s3 bucket using the following java code.

AmazonS3 s3client = AmazonS3ClientBuilder.defaultClient();
    s3client.setRegion(Region.getRegion(Regions.AP_SOUTH_1));

But I am getting the following error:

"exception": "com.amazonaws.SdkClientException",
    "message": "Unable to find a region via the region provider chain. Must provide an explicit region in the builder or setup environment to supply a region."

Am I trying to set region in an incorrect way? Please advice.

Body:
If you are not using any proxies and you already setup your credentials, you can use below code:

AmazonS3 s3client = AmazonS3ClientBuilder.standard()
.withRegion(Region.getRegion(Regions.AP_SOUTH_1));

But if you need to setup a proxy and manually set the credentials, you can use below code:

AWSCredentials cred = new BasicAWSCredentials(<accessKey>,<secretKey>);
AmazonS3 s3client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(cred))
.withClientConfiguration(<your configuration>)
.withRegion(Region.getRegion(Regions.AP_SOUTH_1));


问:
AppDynamics Reuse nodename in Machine Agent Registration
We have implemented AppDynamics in Jboss application. We have load balancer and autoscalling which means we will have node registration when new server comes up.

The problem here is Java and Machine Agent. Java Agent can reuse name with prefix (Appd Controlled Node Names) , but machine agent node name need to be provided at configuration level.

We are getting two separate agents listed. One is 100% with Machine Agent and another with Java agent. We need Machine Agent will ping at same line.

https://i.stack.imgur.com/MhpeU.png

答:
The Issue is resolved.
The controller-info of Machine Agent need not to have any Application,Node and Tier name. It should include unique host id which should be same as controller-info of JavaAgent. </p>


问:
Javascript function is not accessing the global scope?
I wanted to create a simple input field that takes the value of what was inputed to calculate the area of a triangle and I noticed something with my function.
I noticed that for some reason my function could not access the variables that was created in the global scope. like this:

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

input 1: <input type="input" placeholder="Side a" id="sideA"> <br>
input 2: <input type="input" placeholder="Side b"  id="sideB"><br>
input 3: <input type="input" placeholder="Side c" id="sideC"><br>
<button onclick=" AreaResults()"> Calculate</button>

<p id="P_result">

    The area of the triangle is:
</p>
<script >

var side_a = document.getElementById("sideA").value;
     var side_b = document.getElementById("sideB").value;
     var side_c = document.getElementById("sideC").value;

var Allsides = side_c + side_b + side_a;
var perimeter = Allsides/2;
var area = Math.sqrt(( perimeter*(perimeter-side_a)*(perimeter-side_b)*(perimeter-side_c)));

function AreaResults(){

    var resultsInput = document.getElementById("P_result");
    resultsInput.append(area);

}

</script>
</body>
</html>
</code>```

After moving them into the function like this:

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

input 1: <input type="input" placeholder="Side a" id="sideA"> <br>
input 2: <input type="input" placeholder="Side b"  id="sideB"><br>
input 3: <input type="input" placeholder="Side c" id="sideC"><br>
<button onclick=" AreaResults()"> Calculate</button>

<p id="P_result">

    The area of the triangle is:
</p>
<script >

function AreaResults(){

var side_a = document.getElementById("sideA").value;
     var side_b = document.getElementById("sideB").value;
     var side_c = document.getElementById("sideC").value;

var Allsides = side_c + side_b + side_a;
var perimeter = Allsides/2;
var area = Math.sqrt(( perimeter*(perimeter-side_a)*(perimeter-side_b)*(perimeter-side_c)));

    var resultsInput = document.getElementById("P_result");
    resultsInput.append(area);

}

</script>
</body>
</html>
</code>```

Everything works just fine.
I do not understand because I thought functions can access all the variable in the global scope

答:
You're accessing the variables just fine.

However, you set them before the user typed anything (when the page loaded), so they're empty.

Body:
I wanted to create a simple input field that takes the value of what was inputed to calculate the area of a triangle and I noticed something with my function.
I noticed that for some reason my function could not access the variables that was created in the global scope. like this:

<!DOCTYPE html>

    <title></title>

input 1: <input type="input" placeholder="Side a" id="sideA">

input 2: <input type="input" placeholder="Side b"  id="sideB">

input 3: <input type="input" placeholder="Side c" id="sideC">

<button onclick=" AreaResults()"> Calculate</button>

    The area of the triangle is:

After moving them into the function like this:

<!DOCTYPE html>

    <title></title>

input 1: <input type="input" placeholder="Side a" id="sideA">

input 2: <input type="input" placeholder="Side b"  id="sideB">

input 3: <input type="input" placeholder="Side c" id="sideC">

<button onclick=" AreaResults()"> Calculate</button>

    The area of the triangle is:

Everything works just fine.
I do not understand because I thought functions can access all the variable in the global scope


问:
readr::read_csv issue: numbers become double/character
I'm trying to import a large dataset (more 150 columns, csv-file) to RStudio, however I am stuck with manually choosing "numeric" for all the columns, as they seem they import in "double" or "character" default mode. This takes a lot of time for large files.
Here is the code:

```<code>> Test_example <- read_csv("~/Desktop/Test_example.csv",
+     col_types = cols(c_perc = col_number(),
+         n_perc = col_number(), treatment = col_integer()),
+     na = "0")
</code>```

I've tried using "stringsAsFactors" command but it does not work.
Also if I do not sign the columns a format when importing, I get error:

```<code>"Parsed with column specification:
cols(
  .default = col_integer()
)
See spec(...) for full column specifications."
</code>```

答:
Check the help on the function.
If you specify col_types you need a specification for all 150 columns or use cols_only()
You could also use a compact string like "cid" for character, integer, double
You could try letting the function guess as well.

Body:
I'm trying to import a large dataset (more 150 columns, csv-file) to RStudio, however I am stuck with manually choosing "numeric" for all the columns, as they seem they import in "double" or "character" default mode. This takes a lot of time for large files.
Here is the code:

> Test_example <- read_csv("~/Desktop/Test_example.csv",
+     col_types = cols(c_perc = col_number(),
+         n_perc = col_number(), treatment = col_integer()),
+     na = "0")

I've tried using "stringsAsFactors" command but it does not work.
Also if I do not sign the columns a format when importing, I get error:

"Parsed with column specification:
cols(
  .default = col_integer()
)
See spec(...) for full column specifications."


问:
UWP maps, add 3D object
I would like to add 3D object in Windows 10 UWP map control.

This object would be "polygon with height", e.g. simple representation of a house - cuboid or cube.

Illustration image:

I know that I can add Xaml control (and inside it 3D object e.g. Cube) but then this Cube is not 'map object', only pinned to a certain Lat/Lon.

Any idea how to implement this?

答:
Microsoft has added MapElement3D in Windows 10 Insider Preview v10.0.16257.0. - that's the falls creators update. It allows you to add objects, turn them, control their size, and direction. You can make them move too!

Example

How-To

Represents a 3D element displayed on a MapControl.

It's usage appears to be very similar to other MapElements, such as MapIcons and MapBillboards.

```<code>map3dSphereStreamReference = RandomAccessStreamReference.CreateFromUri
   (new Uri("ms-appx:///Assets/trainengine.3mf"));

 var myModel = await MapModel3D.CreateFrom3MFAsync(map3dSphereStreamReference,
     MapModel3DShadingOption.Smooth);

 var my3DElement = new MapElement3D();
 my3DElement.Location = myMap.Center;
 my3DElement.Model = myModel;

 myMap.MapElements.Add(my3DElement);
</code>```

Beware of two undocumented issues:

Attempting to add the same 3DMapElement to two different MapControls will result in System.AccessViolationException. This can happen if you cached the 3D model but not the page with the map control.

HResult=-2147467261 Message=Attempted to read or write protected
  memory. This is often an indication that other memory is corrupt.

Attempting to call MapModel3D.CreateFrom3MFAsync() from a non-Ui thread will cause a crash. This must be called from a UI thread.

Title: UWP maps, add 3D object

Body:
Microsoft has added MapElement3D in Windows 10 Insider Preview v10.0.16257.0. - that's the falls creators update. It allows you to add objects, turn them, control their size, and direction. You can make them move too!

Example

How-To

Represents a 3D element displayed on a MapControl.

It's usage appears to be very similar to other MapElements, such as MapIcons and MapBillboards.

map3dSphereStreamReference = RandomAccessStreamReference.CreateFromUri
   (new Uri("ms-appx:///Assets/trainengine.3mf"));

 var myModel = await MapModel3D.CreateFrom3MFAsync(map3dSphereStreamReference,
     MapModel3DShadingOption.Smooth);

 var my3DElement = new MapElement3D();
 my3DElement.Location = myMap.Center;
 my3DElement.Model = myModel;

 myMap.MapElements.Add(my3DElement);

Beware of two undocumented issues:

Attempting to add the same 3DMapElement to two different MapControls will result in System.AccessViolationException. This can happen if you cached the 3D model but not the page with the map control.

HResult=-2147467261 Message=Attempted to read or write protected
  memory. This is often an indication that other memory is corrupt.

Attempting to call MapModel3D.CreateFrom3MFAsync() from a non-Ui thread will cause a crash. This must be called from a UI thread.


问:
High-level level language for image processing
My final year project group is planning to build a real time application with neural network support and need to handle image processing efficiently, Any language suggestions would be very much helpful. Thanks.</p>

答: My suggestion is OpenCV and C++. OpenCV is also usable with Python, but I don't recommend it if you need to write fast code, Python can be really slow.</p>


问:
PHP Get Site's Google Ranking WITHOUT Crawling Google
I want to programmatically retrieve Google Search Results for the purpose of finding where a specific domain ranks in the search results pages.

HOWEVER, I do NOT want to simply crawl search result pages because I'm expecting high volume and needing to do this frequently, and this is judged as abuse by Google if I understand correctly?

Most scripts/classes I've been able to find try to parse the HTML pages, there's gotta be a better way.

Is there an API to get google results?
Any ideas?

Thanks!

答:
I don't like the selected answer.

First of all it is too generalizing, there IS a SERP rank and it mostly depends on language and country.

The other factors are rarely a real factor and very minor (for example in Google you can favorite your websites, they will be ranked on top).

I've personally made a lot of testing and when I scrape keywords from foreign countries and ask people from there I get the exactly same ones.

Now the central problem
The Google custom search API is not an option for rank tracking, it's useful for a small amount of data research only.

Same counts for Bing and both are really expensive for larger amounts.

If you want to get that ranking data you only can either scrape (crawl) the search engines, that's definitely possible (I do it) or you use a scraping service which does it for you and delivers raw data to your software (also using that one myself).

As you said you don't want to crawl yourself, take a look at scraping.services.

That's a scraping service mostly designed for developers if I am not mistaken, you can make a full featured rank tracking engine that way for high volumes of keywords.

They also have some API module for generating charts and reports (different from sistrix but same same sort of sauce) if you don't want to do it yourself.

Personally I have not used their keyword tracker yet, I used Google and Bing their scraping API directly and it works without issues so far.

If you get interested in scraping search engines on your own I can help you out, it's not difficult (also possible for large volumes).