问:
Chart.js bubble chart pointStyle not working
I am working with chart.js bubble chart. I am trying to change the pointStyle from circle to something else. I have tried everything based on the documentation and still can't get it to work. Can someone help understand what I did wrong?

```<code>Chart.defaults.global.elements.point.pointStyle = 'star';
Chart.defaults.global.elements.point.backgroundColor = 'rgba(255,255,255,1)';

Chart.defaults.global.elements.point.radius = 20;

var data = {
datasets:[{
        pointStyle:      'triangle',
        //pointRadius:     8,
//          data:[ 27, 33, 49 ],
        data:[{ x:0, y: 0}]
    }]
};
var options = {
                responsive: true,
                title:{
                    display:true,
                    text:'Chart.js Bubble Chart'
                },
                tooltips: {
                    mode: 'point'
                }
            };
var canvas = document.getElementById('myChart');

var myBubbleChart = new Chart(canvas,{
type: 'bubble',
data: data,
options: options
});0
</code>```

I can make the change for line chart but it seems impossible to get bubble chart to change pointStyle.

https://jsfiddle.net/charleschiu/h31vfgnq/

Thanks

答:
Obviously, this is not going to work, as pointStyle is only applicable for line chart (which has points to hover over). Unfortunate enough, there isn't any native options to achieve this either.

However, this cloud be achieved in some kind of a hackish way, which is, overriding the actual draw function of the bubble chart.

ᴏᴠᴇʀʀɪᴅᴇ ᴛʜᴇ ᴅʀᴀᴡ ꜰᴜɴᴄᴛɪᴏɴ ᴏꜰ ʙᴜʙʙʟᴇ ᴄʜᴀʀᴛ

```<code>Chart.controllers.bubble.prototype.draw = function() {
   let c = this.chart; // chart instance
   let datasets = c.data.datasets; // datasets array
   datasets.forEach(function(e, i) { // loop through the datasets array
      let isHidden = e._meta[0].hidden; // dataset's hidden property
      if (!isHidden) { // if dataset is not hidden
         let data = c.getDatasetMeta(i).data; // coords array of bubble
         data.forEach(function(e) { // loop through the coords array
            let ctx = c.chart.ctx; // canvas context
            let x = e._model.x; // x coord of bubble
            let y = e._model.y; // y coord of bubble
            let r = e._model.radius; // radius of bubble
            let bgColor = e._model.backgroundColor; // background color of bubble

            /** draw anything using general canvas methods **/
            // draw a triangle
            ctx.save();
            ctx.moveTo(x, y - r);
            ctx.lineTo(x + r, y + r);
            ctx.lineTo(x - r, y + r);
            ctx.closePath();
            ctx.fillStyle = bgColor;
            ctx.fill();
            ctx.restore();
         });
      }
   });
}
</code>```

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

Chart.controllers.bubble.prototype.draw = function() {
   let c = this.chart; // chart instance
   let datasets = c.data.datasets; // datasets array
   datasets.forEach(function(e, i) { // loop through the datasets array
      let isHidden = e._meta[0].hidden; // dataset's hidden property
      if (!isHidden) { // if dataset is not hidden
         let data = c.getDatasetMeta(i).data; // coords array of bubble
         data.forEach(function(e) { // loop through the coords array
            let ctx = c.chart.ctx; // canvas context
            let x = e._model.x; // x coord of bubble
            let y = e._model.y; // y coord of bubble
            let r = e._model.radius; // radius of bubble
            let bgColor = e._model.backgroundColor; // background color of bubble

            /** draw anything using general canvas methods **/
            // draw a triangle
            ctx.save();
            ctx.moveTo(x, y - r);
            ctx.lineTo(x + r, y + r);
            ctx.lineTo(x - r, y + r);
            ctx.closePath();
            ctx.fillStyle = bgColor;
            ctx.fill();
            ctx.restore();
         });
      }
   });
}

var data = {
   datasets: [{
      label: 'Dataset 1',
      data: [
        { x: 6, y: 6, r: 10 },
        { x: 12, y: 12, r: 15 }
      ],
      backgroundColor: '#07C'
   }]
};
var options = {
 responsive: false,
   scales: {
      xAxes: [{ ticks: { min: 0, max: 20 } }],
      yAxes: [{ ticks: {  min: 0, max: 20 } }]
   },
   title: {
      display: true,
      text: 'Chart.js Bubble Chart'
   }
};

var canvas = document.getElementById('myChart');
var myBubbleChart = new Chart(canvas, {
   type: 'bubble',
   data: data,
   options: options
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
<canvas id="myChart" width="350" height="200"></canvas></code>```

Body:
I am working with chart.js bubble chart. I am trying to change the pointStyle from circle to something else. I have tried everything based on the documentation and still can't get it to work. Can someone help understand what I did wrong?

Chart.defaults.global.elements.point.pointStyle = 'star';
Chart.defaults.global.elements.point.backgroundColor = 'rgba(255,255,255,1)';

Chart.defaults.global.elements.point.radius = 20;

var data = {
datasets:[{
        pointStyle:      'triangle',
        //pointRadius:     8,
//          data:[ 27, 33, 49 ],
        data:[{ x:0, y: 0}]
    }]
};
var options = {
                responsive: true,
                title:{
                    display:true,
                    text:'Chart.js Bubble Chart'
                },
                tooltips: {
                    mode: 'point'
                }
            };
var canvas = document.getElementById('myChart');

var myBubbleChart = new Chart(canvas,{
type: 'bubble',
data: data,
options: options
});0

I can make the change for line chart but it seems impossible to get bubble chart to change pointStyle.

https://jsfiddle.net/charleschiu/h31vfgnq/

Thanks

Body:
Obviously, this is not going to work, as pointStyle is only applicable for line chart (which has points to hover over). Unfortunate enough, there isn't any native options to achieve this either.

However, this cloud be achieved in some kind of a hackish way, which is, overriding the actual draw function of the bubble chart.

ᴏᴠᴇʀʀɪᴅᴇ ᴛʜᴇ ᴅʀᴀᴡ ꜰᴜɴᴄᴛɪᴏɴ ᴏꜰ ʙᴜʙʙʟᴇ ᴄʜᴀʀᴛ

Chart.controllers.bubble.prototype.draw = function() {
   let c = this.chart; // chart instance
   let datasets = c.data.datasets; // datasets array
   datasets.forEach(function(e, i) { // loop through the datasets array
      let isHidden = e._meta[0].hidden; // dataset's hidden property
      if (!isHidden) { // if dataset is not hidden
         let data = c.getDatasetMeta(i).data; // coords array of bubble
         data.forEach(function(e) { // loop through the coords array
            let ctx = c.chart.ctx; // canvas context
            let x = e._model.x; // x coord of bubble
            let y = e._model.y; // y coord of bubble
            let r = e._model.radius; // radius of bubble
            let bgColor = e._model.backgroundColor; // background color of bubble

            /** draw anything using general canvas methods **/
            // draw a triangle
            ctx.save();
            ctx.moveTo(x, y - r);
            ctx.lineTo(x + r, y + r);
            ctx.lineTo(x - r, y + r);
            ctx.closePath();
            ctx.fillStyle = bgColor;
            ctx.fill();
            ctx.restore();
         });
      }
   });
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

Chart.controllers.bubble.prototype.draw = function() {
   let c = this.chart; // chart instance
   let datasets = c.data.datasets; // datasets array
   datasets.forEach(function(e, i) { // loop through the datasets array
      let isHidden = e._meta[0].hidden; // dataset's hidden property
      if (!isHidden) { // if dataset is not hidden
         let data = c.getDatasetMeta(i).data; // coords array of bubble
         data.forEach(function(e) { // loop through the coords array
            let ctx = c.chart.ctx; // canvas context
            let x = e._model.x; // x coord of bubble
            let y = e._model.y; // y coord of bubble
            let r = e._model.radius; // radius of bubble
            let bgColor = e._model.backgroundColor; // background color of bubble

            /** draw anything using general canvas methods **/
            // draw a triangle
            ctx.save();
            ctx.moveTo(x, y - r);
            ctx.lineTo(x + r, y + r);
            ctx.lineTo(x - r, y + r);
            ctx.closePath();
            ctx.fillStyle = bgColor;
            ctx.fill();
            ctx.restore();
         });
      }
   });
}

var data = {
   datasets: [{
      label: 'Dataset 1',
      data: [
        { x: 6, y: 6, r: 10 },
        { x: 12, y: 12, r: 15 }
      ],
      backgroundColor: '#07C'
   }]
};
var options = {
 responsive: false,
   scales: {
      xAxes: [{ ticks: { min: 0, max: 20 } }],
      yAxes: [{ ticks: {  min: 0, max: 20 } }]
   },
   title: {
      display: true,
      text: 'Chart.js Bubble Chart'
   }
};

var canvas = document.getElementById('myChart');
var myBubbleChart = new Chart(canvas, {
   type: 'bubble',
   data: data,
   options: options
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
<canvas id="myChart" width="350" height="200"></canvas>


来源: stackexchange

问:
iterm vs. zsh features
I'm confused on why I would need both iterm and zsh because from my understanding both just gives you coloring themes and shortcuts like gco instead of git checkout or is iterm more known for the former and zsh for the latter?

答:
Iterm does not give you shortcuts like gco. It is a terminal emulator. It is the shell ( like zsh or bash ) that enables you to define aliases. All popular shells nowadays provide support for such aliases. But zsh along with oh-my-zsh do provide a lot of nifty features for git out of the box with just a few lines of extra configuration.

Adding to @Klas's answer:

If your terminal application doesn't support coloring, any colors supported by your shell( zsh or bash or csh ) wouldn't show up. That being said, all basic terminal applications nowadays support basic coloring. So if it is just color support you are looking for, you don't need Iterm ( assuming you are using the default Terminal.app ).

But there are a lot of really good features of Iterm which you might use later down the line. My favourite feature provided by Iterm is Shell integration and tmux support.

ContentLicense: CC BY-SA 3.0

Title: iterm vs. zsh features


问:
Jquery Fade in menu on click
I'm trying to achieve a fade in effect when I click on an icon which toggles a 100% height and width menu and a fade out when I click the X. However I'm not sure how to achieve this effect. The only way I've managed to make it work is by adding a top, bottom, left and right value but I do not want it to slide from a side but rather appear as an opacity change from 0 to 1 with a transition. I've set the top value to work so you can see the menu but it is not what I'm looking for.

HTML:

```<code><div class="o1">
    <div class="o2"></div>
</div>

<div class="nav">

<div class="out">
<div class="x"></div>
<div class="x2"></div>
</div>

<ul>
    <li class="lione">About Me</li>
    <li class="litwo">My Portfolio</li>
    <li class="lithree">My Skills</li>
    <li class="lifour">Contact Me</li>
</ul>
</div>
</code>```

CSS:

```<code>.nav {
height: 100vh;
width: 100vw;
position: absolute;
top: -100%;
/left: -100%;
/right: -100%;
/bottom: -100%;
z-index: 1;
background-color: #3a3a3a;
transition: 1s all ease;
opacity: 0;
}

.nav ul {
list-style: none;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

.nav li {
text-align: center;
color: #81CFE0;
padding: 10px;
font-family: 'Quicksand';
font-weight: 100;
}

.lione {
border: 1px solid;
border-right: none;
border-bottom: none;
}

.litwo {
border: 1px solid;
border-top: none;
border-right: none;
border-bottom: none;
}

.lithree {
border: 1px solid;
border-top: none;
border-left: none;
border-bottom: none;
}

.lifour {
border: 1px solid;
border-top: none;
border-left: none;
}

.out {
height: 4vh;
margin-left: 98%;
margin-right: 0.5%;
transition: 1s all ease;
}

.x {
height: 1px;
background-color: #81cfe0;
width: 20px;
transform: rotate(45deg);
position: absolute;
top: 15px;
right: 10px;
}

.x2 {
height: 1px;
background-color: #81cfe0;
width: 20px;
transform: rotate(-45deg);
position: absolute;
right: 10px;
top: 15px;
}

.o1 {
height: 20px;
width: 20px;
border-radius: 100%;
border: 1px solid #81cfe0;
position: absolute;
top: 1%;
right: 1%;
}

.open {
opacity: 1;
top: 0;
}

.o2 {
height: 13px;
width: 13px;
border-radius: 100%;
border: 1px solid #3a3a3a;
position: absolute;
left: 51%;
top: 51%;
transform: translate(-50%, -50%);
transition: 1s all ease;
}
</code>```

JS:

```<code>$(function () {
$('.o1').click(function() {
   $('.nav').toggleClass('open');
});

$('.out').click(function() {
   $('.open').toggleClass('open');
});
});
</code>```

https://jsfiddle.net/u03ofj16/

答:
Check if you are looking for this.
Add z-index to the .o1 class.So it will be on the top of the nav.Then set the opacity:.5 to the .nav

$(function () {
    $('.o1').click(function() {
       $(this).addClass('hide');
       $('.nav').toggleClass('open');
    });

    $('.out').click(function() {
       $('.nav').toggleClass('open');
       $('.o1').removeClass('hide');
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav {
    height: 100vh;
    width: 100vw;
    position: absolute;
   /* top: -100%;
    left: -100%;
    right: -100%;
    bottom: -100%;*/
    top: 0px;
    z-index: 1;
    background-color: #3a3a3a;
    transition: 1s all ease;
    opacity: 0;
}

.nav ul {
    list-style: none;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.nav li {
    text-align: center;
    color: #81CFE0;
    padding: 10px;
    font-family: 'Quicksand';
    font-weight: 100;
}

.lione {
    border: 1px solid;
    border-right: none;
    border-bottom: none;
}

.litwo {
   border: 1px solid;
    border-top: none;
    border-right: none;
    border-bottom: none;
}

.lithree {
    border: 1px solid;
    border-top: none;
    border-left: none;
    border-bottom: none;
}

.lifour {
    border: 1px solid;
    border-top: none;
    border-left: none;
}

.out {
  /*  height: 4vh;*/
  height:20px;
    margin-left: 98%;
    margin-right: 0.5%;
    transition: 1s all ease;
}

.x {
    height: 1px;
    background-color: #81cfe0;
    width: 20px;
    transform: rotate(45deg);
    position: absolute;
    top: 15px;
    right: 10px;
}

.x2 {
    height: 1px;
    background-color: #81cfe0;
    width: 20px;
    transform: rotate(-45deg);
    position: absolute;
    right: 10px;
    top: 15px;
}

.o1 {
    height: 20px;
    width: 20px;
    border-radius: 100%;
    border: 1px solid #81cfe0;
    position: absolute;
    top: 1%;
    right: 1%;
    z-index:999;
}

.open {
    opacity: 1;
    top: 0;
}

.o2 {
    height: 13px;
    width: 13px;
    border-radius: 100%;
    border: 1px solid #3a3a3a;
    position: absolute;
    left: 51%;
    top: 51%;
    transform: translate(-50%, -50%);
    transition: 1s all ease;
}
.hide{
     display:none;
}</code>```

About Me

My Portfolio

My Skills

Contact Me

```

Title: Jquery Fade in menu on click

Body:
I'm trying to achieve a fade in effect when I click on an icon which toggles a 100% height and width menu and a fade out when I click the X. However I'm not sure how to achieve this effect. The only way I've managed to make it work is by adding a top, bottom, left and right value but I do not want it to slide from a side but rather appear as an opacity change from 0 to 1 with a transition. I've set the top value to work so you can see the menu but it is not what I'm looking for.

HTML:

About Me

My Portfolio

My Skills

Contact Me

CSS:

.nav {
height: 100vh;
width: 100vw;
position: absolute;
top: -100%;
/left: -100%;
/right: -100%;
/bottom: -100%;
z-index: 1;
background-color: #3a3a3a;
transition: 1s all ease;
opacity: 0;
}

.nav ul {
list-style: none;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

.nav li {
text-align: center;
color: #81CFE0;
padding: 10px;
font-family: 'Quicksand';
font-weight: 100;
}

.lione {
border: 1px solid;
border-right: none;
border-bottom: none;
}

.litwo {
border: 1px solid;
border-top: none;
border-right: none;
border-bottom: none;
}

.lithree {
border: 1px solid;
border-top: none;
border-left: none;
border-bottom: none;
}

.lifour {
border: 1px solid;
border-top: none;
border-left: none;
}

.out {
height: 4vh;
margin-left: 98%;
margin-right: 0.5%;
transition: 1s all ease;
}

.x {
height: 1px;
background-color: #81cfe0;
width: 20px;
transform: rotate(45deg);
position: absolute;
top: 15px;
right: 10px;
}

.x2 {
height: 1px;
background-color: #81cfe0;
width: 20px;
transform: rotate(-45deg);
position: absolute;
right: 10px;
top: 15px;
}

.o1 {
height: 20px;
width: 20px;
border-radius: 100%;
border: 1px solid #81cfe0;
position: absolute;
top: 1%;
right: 1%;
}

.open {
opacity: 1;
top: 0;
}

.o2 {
height: 13px;
width: 13px;
border-radius: 100%;
border: 1px solid #3a3a3a;
position: absolute;
left: 51%;
top: 51%;
transform: translate(-50%, -50%);
transition: 1s all ease;
}

JS:

$(function () {
$('.o1').click(function() {
   $('.nav').toggleClass('open');
});

$('.out').click(function() {
   $('.open').toggleClass('open');
});
});

https://jsfiddle.net/u03ofj16/

Body:
Check if you are looking for this.
Add z-index to the .o1 class.So it will be on the top of the nav.Then set the opacity:.5 to the .nav

$(function () {
    $('.o1').click(function() {
       $(this).addClass('hide');
       $('.nav').toggleClass('open');
    });

    $('.out').click(function() {
       $('.nav').toggleClass('open');
       $('.o1').removeClass('hide');
    });
});

.nav {
    height: 100vh;
    width: 100vw;
    position: absolute;
   /* top: -100%;
    left: -100%;
    right: -100%;
    bottom: -100%;*/
    top: 0px;
    z-index: 1;
    background-color: #3a3a3a;
    transition: 1s all ease;
    opacity: 0;
}

.nav ul {
    list-style: none;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

.nav li {
    text-align: center;
    color: #81CFE0;
    padding: 10px;
    font-family: 'Quicksand';
    font-weight: 100;
}

.lione {
    border: 1px solid;
    border-right: none;
    border-bottom: none;
}

.litwo {
   border: 1px solid;
    border-top: none;
    border-right: none;
    border-bottom: none;
}

.lithree {
    border: 1px solid;
    border-top: none;
    border-left: none;
    border-bottom: none;
}

.lifour {
    border: 1px solid;
    border-top: none;
    border-left: none;
}

.out {
  /*  height: 4vh;*/
  height:20px;
    margin-left: 98%;
    margin-right: 0.5%;
    transition: 1s all ease;
}

.x {
    height: 1px;
    background-color: #81cfe0;
    width: 20px;
    transform: rotate(45deg);
    position: absolute;
    top: 15px;
    right: 10px;
}

.x2 {
    height: 1px;
    background-color: #81cfe0;
    width: 20px;
    transform: rotate(-45deg);
    position: absolute;
    right: 10px;
    top: 15px;
}

.o1 {
    height: 20px;
    width: 20px;
    border-radius: 100%;
    border: 1px solid #81cfe0;
    position: absolute;
    top: 1%;
    right: 1%;
    z-index:999;
}

.open {
    opacity: 1;
    top: 0;
}

.o2 {
    height: 13px;
    width: 13px;
    border-radius: 100%;
    border: 1px solid #3a3a3a;
    position: absolute;
    left: 51%;
    top: 51%;
    transform: translate(-50%, -50%);
    transition: 1s all ease;
}
.hide{
     display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div class="o1">
        <div class="o2"></div>
  </div>

<div class="nav">

    <div class="out">
        <div class="x"></div>
        <div class="x2"></div>
    </div>

    <ul>
        <li class="lione">About Me</li>
        <li class="litwo">My Portfolio</li>
        <li class="lithree">My Skills</li>
        <li class="lifour">Contact Me</li>
    </ul>
</div>


问:
How to use setState in external function?
```<code>import Request from 'superagent';

const getApi = () => {
    let url = '/* URL */';
    return Request.get(url).then((res) => {
        this.setState({
             content: res.body
        });
    });
}

export default getApi;
</code>```

I've created function in external file for api call. How do I get access to function/setState in external file?

```<code>componentWillMount(){
   getApi();
}
</code>```

I receive this error:

'TypeError: Cannot read property 'setState' of undefined'

答:
My Solution: </p>

```<code>function getApi(component) {
        let url = '/* url */';
        return Request.get(url).then((res) => {
            component.setState({
                content: res.body,
            });
        });
    }
</code>```

<hr>

```<code>componentWillMount(){
   getApi(this);
}
</code>```

Body:
import Request from 'superagent';

const getApi = () => {
    let url = '/* URL */';
    return Request.get(url).then((res) => {
        this.setState({
             content: res.body
        });
    });
}

export default getApi;

I've created function in external file for api call. How do I get access to function/setState in external file?

componentWillMount(){
   getApi();
}

I receive this error:

'TypeError: Cannot read property 'setState' of undefined'

Body:
My Solution:

function getApi(component) {
        let url = '/* url */';
        return Request.get(url).then((res) => {
            component.setState({
                content: res.body,
            });
        });
    }

componentWillMount(){
   getApi(this);
}


问:
Adding models to collection throws error "Uncaught TypeError: Cannot read property 'idAttribute' of undefined"
I'm having an error trying to add multiple models from the server to a collection. It throws the error:

Uncaught TypeError: Cannot read property 'idAttribute' of undefined
```

<p>Here is a test example which gives same error:</p>

```

```

答:
The model property of the collection class should be a model constructor, not an instance.

```<code>Backbone.Collection.extend({ model: Mymodel });
</code>```

The model class has a idAttribute property, singular, which is already 'id' by default.

Putting the id attribute in the defaults isn't necessary and could lead to problems down the road.

Other than the previous points, doing rendering within a model is bad practice. Use a view for this.

```<code>render: function(){
    collection.add([{ id:1, name: "name" }, { id:2, name: "name" }])
}
</code>```

I understand this is a test example, but if it wasn't, a model class shouldn't change a global collection instance. The whole point of classes is to scope the responsibilities to the class itself and nothing outside of it.

Using a global like that just goes against the whole point of using Backbone.

Minimal code needed

```<code>var MyModel = Backbone.Model.extend({}),
    MyCollection = Backbone.Collection.extend({ model: MyModel }),
    collection = new MyCollection();

collection.add([
    { id: 1, name: "name" },
    { id: 2, name: "name" }
]);
</code>```

Body:
I'm having an error trying to add multiple models from the server to a collection. It throws the error:

Uncaught TypeError: Cannot read property 'idAttribute' of undefined

Here is a test example which gives same error:

Body:
The model property of the collection class should be a model constructor, not an instance.

Backbone.Collection.extend({ model: Mymodel });

The model class has a idAttribute property, singular, which is already 'id' by default.

Putting the id attribute in the defaults isn't necessary and could lead to problems down the road.

Other than the previous points, doing rendering within a model is bad practice. Use a view for this.

render: function(){
    collection.add([{ id:1, name: "name" }, { id:2, name: "name" }])
}

I understand this is a test example, but if it wasn't, a model class shouldn't change a global collection instance. The whole point of classes is to scope the responsibilities to the class itself and nothing outside of it.

Using a global like that just goes against the whole point of using Backbone.

Minimal code needed

var MyModel = Backbone.Model.extend({}),
    MyCollection = Backbone.Collection.extend({ model: MyModel }),
    collection = new MyCollection();

collection.add([
    { id: 1, name: "name" },
    { id: 2, name: "name" }
]);


问:
Where does the Spring Model that is passed to a JSP goes to?
I've been reading docs and tutorials about spring (3.0), so I've learnt how to return a ModelAndView with the JSP name and a Map as the model. I've learnt also that in a JSP, if you want to access one key of that map you do ${attributename} and so on. That's JSP EL. Now my questions:

What object of the page is the EL accessing? Is that PageContext? I tried to find those keys in PageContext.getAttribute but they are not there.

Whatever the object is, is it automatic that the things in the model go there?

Feel free to add resources to clarify my ideas

答:
They are usually stored in the request. So request.getAttributeNames() should give you all your model (but use that only for educational purposes - otherwise use EL to access the model). That said, it should also be accessible from the pageContext (in request scope).

And yes, it is automatically added.

ContentLicense: CC BY-SA 2.5


问:
Inefficient JavaScript Algorithm, How do I make the following code more efficient?
Problem Statement: Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order.

My Solution:

```<code>function comp(array1, array2){

  var test;

  if( array1.length <= 0 || array2.length <= 0 || array1 == null || array2 == null || array2.length != array1.length || array1==undefined || array2==undefined){
    return false;
  }else{
    for(i=0; i<array2.length; i++){
      for(j=0; j<array1.length; j++){
        if(array2[i] === Math.pow(array1[j],2)){
          test = true;
          break;
        }else{
          test = false;
        }
      }
      if(test==false)
        return false;
    }

    if(test === true)
      return true;
    else
      return false;
  }
}
</code>```

Also any constructive criticism about the code is appreciated as I'm still just a wookie so always looking to improve.

Test Example:

```<code>var a1 = [80, 2, 65, 68];
var a2 = [6401, 4, 4225, 4624];
</code>```

For the end result all I want is for true to be returned if true and likewise for false. The program solves all the test cases however it times out.

答:
In words:

Square the first array

Sort the first array

Sort the second array.

Now if any element does not match the corresponding element in the other array, there is no match.

otherwise they match

In code:

```<code>function comp(array1, array2){

    var test;

    if( !array1 || !array2 ){
        return false;
    }

    if ( array1.length != array2.length ){
        return false;
    }

    // first squre the array
    array1_squared = array1.map( function( val ){ return Math.pow( val, 2 ); } );

    // then sort both arrays
    array1_squared.sort()
    array2.sort()

    // then compare
    for ( var i=0 ; i < array1_squared.length ; i+= 1 ){
        if ( array1_squared[i] != array2[i] ) {
            return false;
        }
    }

    return true;
}
</code>```

More details, because:

Conceptually, I think this is easier to follow.  One difference is I do the squaring outside of the loop.  You are doing your square inside your loop, which means you are squaring length^2 times, instead of length times.  That makes for some wasted CPU cycles.  Also, you end up looping over your array while looping over your array, which gives length**2 loop executions.  Comparatively, sorting is fairly fast and then it lets us get the actual answer with just one loop.

Body:
Problem Statement: Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order.

My Solution:

function comp(array1, array2){

  var test;

  if( array1.length <= 0 || array2.length <= 0 || array1 == null || array2 == null || array2.length != array1.length || array1==undefined || array2==undefined){
    return false;
  }else{
    for(i=0; i<array2.length; i++){
      for(j=0; j<array1.length; j++){
        if(array2[i] === Math.pow(array1[j],2)){
          test = true;
          break;
        }else{
          test = false;
        }
      }
      if(test==false)
        return false;
    }

    if(test === true)
      return true;
    else
      return false;
  }
}

Also any constructive criticism about the code is appreciated as I'm still just a wookie so always looking to improve.

Test Example:

var a1 = [80, 2, 65, 68];
var a2 = [6401, 4, 4225, 4624];

For the end result all I want is for true to be returned if true and likewise for false. The program solves all the test cases however it times out.

Body:
In words:

Square the first array

Sort the first array

Sort the second array.

Now if any element does not match the corresponding element in the other array, there is no match.

otherwise they match

In code:

function comp(array1, array2){

    var test;

    if( !array1 || !array2 ){
        return false;
    }

    if ( array1.length != array2.length ){
        return false;
    }

    // first squre the array
    array1_squared = array1.map( function( val ){ return Math.pow( val, 2 ); } );

    // then sort both arrays
    array1_squared.sort()
    array2.sort()

    // then compare
    for ( var i=0 ; i < array1_squared.length ; i+= 1 ){
        if ( array1_squared[i] != array2[i] ) {
            return false;
        }
    }

    return true;
}

More details, because:

Conceptually, I think this is easier to follow.  One difference is I do the squaring outside of the loop.  You are doing your square inside your loop, which means you are squaring length^2 times, instead of length times.  That makes for some wasted CPU cycles.  Also, you end up looping over your array while looping over your array, which gives length**2 loop executions.  Comparatively, sorting is fairly fast and then it lets us get the actual answer with just one loop.


问:
Oracle: How to use Group by and Max(datetime) each record no duplication
I want to Group by Max(Datetime) in each record,
but my query has duplicate records. I don't want duplicate records.

SQL:

```<code>with temp as
(
SELECT a.ref_period, b.status, a.updated_dtm
 FROM ir_net_cndn_detail a,ir_net_cndn b
      WHERE a.bill_no=b.bill_no
      AND b.company_code = a.company_code
      AND TO_DATE(a.ref_period,'MM/yyyy') >= TO_DATE(&p_ref_period_start,'MM/yyyy')
      AND TO_DATE(a.ref_period,'MM/yyyy') <= TO_DATE(&p_ref_period_end,'MM/yyyy')
)

   select a.ref_period, a.status, max(updated_dtm) as updated_dtm
   from temp a
   where TO_DATE(a.ref_period,'MM/yyyy') >= TO_DATE(&p_ref_period_start,'MM/yyyy')
   AND TO_DATE(a.ref_period,'MM/yyyy') <= TO_DATE(&p_ref_period_end,'MM/yyyy')
   group by a.ref_period, a.status
</code>```

Resut SQL:

```<code>ref_period |    status  | update_dtm
01/2015  |  I   | 01/09/2016 13:29:56
01/2015  |  I   | 18/05/2017 17:01:52
01/2015  |  I   | 18/05/2017 16:16:23
07/2015  |  I   | 01/09/2016 13:29:56
07/2015  |  I   | 07/01/2016 10:17:39
08/2015  |  I   | 01/09/2016 13:29:56
09/2015  |  N   | 05/06/2017 15:59:55
09/2015  |  I   | 01/09/2016 13:29:56
10/2015  |  I   | 01/09/2016 13:29:56
</code>```

But I want Result:

```<code>ref_period |    status  | update_dtm  >> I want max(update)/1 record with no duplication
01/2015  |  I   | 18/05/2017 17:01:52
07/2015  |  I   | 01/09/2016 13:29:56
08/2015  |  I   | 01/09/2016 13:29:56
09/2015  |  N   | 05/06/2017 15:59:55
10/2015  |  I   | 01/09/2016 13:29:56
</code>```

答:
You should only group by ref_period, why are you also grouping by status? Rather, group by ref_period, select max(update_dtm), and - to get the status as well - use the LAST function (see the documentation if you are not familiar with it). https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions056.htm

```<code>...
select   ref_period,
         min(status) keep (dense_rank last order by update_dtm) as status,
         max(update_dtm) as update_dtm
from     temp
group by ref_period
</code>```

Body:
I want to Group by Max(Datetime) in each record,
but my query has duplicate records. I don't want duplicate records.

SQL:

with temp as
(
SELECT a.ref_period, b.status, a.updated_dtm
 FROM ir_net_cndn_detail a,ir_net_cndn b
      WHERE a.bill_no=b.bill_no
      AND b.company_code = a.company_code
      AND TO_DATE(a.ref_period,'MM/yyyy') >= TO_DATE(&p_ref_period_start,'MM/yyyy')
      AND TO_DATE(a.ref_period,'MM/yyyy') <= TO_DATE(&p_ref_period_end,'MM/yyyy')
)

   select a.ref_period, a.status, max(updated_dtm) as updated_dtm
   from temp a
   where TO_DATE(a.ref_period,'MM/yyyy') >= TO_DATE(&p_ref_period_start,'MM/yyyy')
   AND TO_DATE(a.ref_period,'MM/yyyy') <= TO_DATE(&p_ref_period_end,'MM/yyyy')
   group by a.ref_period, a.status

Resut SQL:

ref_period |    status  | update_dtm
01/2015  |  I   | 01/09/2016 13:29:56
01/2015  |  I   | 18/05/2017 17:01:52
01/2015  |  I   | 18/05/2017 16:16:23
07/2015  |  I   | 01/09/2016 13:29:56
07/2015  |  I   | 07/01/2016 10:17:39
08/2015  |  I   | 01/09/2016 13:29:56
09/2015  |  N   | 05/06/2017 15:59:55
09/2015  |  I   | 01/09/2016 13:29:56
10/2015  |  I   | 01/09/2016 13:29:56

But I want Result:

ref_period |    status  | update_dtm  >> I want max(update)/1 record with no duplication
01/2015  |  I   | 18/05/2017 17:01:52
07/2015  |  I   | 01/09/2016 13:29:56
08/2015  |  I   | 01/09/2016 13:29:56
09/2015  |  N   | 05/06/2017 15:59:55
10/2015  |  I   | 01/09/2016 13:29:56

Body:
You should only group by ref_period, why are you also grouping by status? Rather, group by ref_period, select max(update_dtm), and - to get the status as well - use the LAST function (see the documentation if you are not familiar with it). https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions056.htm

...
select   ref_period,
         min(status) keep (dense_rank last order by update_dtm) as status,
         max(update_dtm) as update_dtm
from     temp
group by ref_period


问:
IntentService is buggy on Android 4.2 (Jelly Bean)?
I am programming an application that needs to sync up with a remote server every minute. There is no way to use push notifications since an app is intended for internal use and it is not going to be published on Google Play.
I found out that I can use AlarmManager and IntentService to reach my objective. So I schedule pending intent to be delivered every minute and handle it in IntentService to perform network I/O. It sounds pretty simple but I faced following problem: app fails with the following error after some period of time (I suppose about 100 minutes).

```<code>05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: WARNING: The Looper class instance count has over a limit(100). There should be some leakage of Looper or HandlerThread.
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: Looper class instance count = 101
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: Current Thread Name: IntentService[BackgroundService]
</code>```

I created very simple example to inspect the problem closer. So it looks like:

Activity:

```<code>public class MainActivity extends AppCompatActivity {
    private AlarmManager alarmManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getService(getBaseContext(), 0, BackgroundService.getIntent(getBaseContext()), PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, 500, pi);
    }
}
</code>```

Service:

```<code>public class BackgroundService extends IntentService {
    private final static String TAG = BackgroundService.class.getSimpleName();
    private final static String ACTION_START = "ru.infotecs.intentservice.action.START";
    private static volatile int counter = 0;

    public BackgroundService() {
        super(TAG);
        counter = 0;
    }

    public static Intent getIntent(Context context) {
        Intent intent = new Intent(context, BackgroundService.class);
        intent.setAction(ACTION_START);
        return intent;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_START.equals(action)) {
                counter++;
                Log.d(TAG, ACTION_START + " - "+ counter);
            }
        }
    }
}
</code>```

As you can see I decreased time interval to 500ms from 1 minute to reproduce problem faster. So now it takes about minute but anyway result is the same:

```<code>05-27 06:52:04.348 32176-32717/ru.infotecs.intentservice D/BackgroundService: ru.infotecs.intentservice.action.START - 1
05-27 06:52:04.846 32176-32720/ru.infotecs.intentservice D/BackgroundService: ru.infotecs.intentservice.action.START - 1
05-27 06:52:05.349 32176-32726/ru.infotecs.intentservice D/BackgroundService: ru.infotecs.intentservice.action.START - 1
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: WARNING: The Looper class instance count has over a limit(100). There should be some leakage of Looper or HandlerThread.
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: Looper class instance count = 101
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: Current Thread Name: IntentService[BackgroundService]
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice I/System.out: java.lang.ThreadGroup[name=main,maxPriority=10]
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice I/System.out:     Thread[main,5,main]
05-27 06:52:05.846 32176-32732/ru.infotecs.intentservice I/System.out:     Thread[Thread-5,5,main]
05-27 06:52:05.847 32176-32732/ru.infotecs.intentservice I/System.out:     Thread[Binder_1,5,main]
05-27 06:52:05.847 32176-32732/ru.infotecs.intentservice I/System.out:     Thread[Binder_2,5,main]
05-27 06:52:05.847 32176-32732/ru.infotecs.intentservice I/System.out:     Thread[IntentService[BackgroundService],5,main]
05-27 06:52:05.848 32176-32732/ru.infotecs.intentservice W/System.err: java.lang.Throwable: stack dump
05-27 06:52:05.848 32176-32732/ru.infotecs.intentservice W/System.err:     at java.lang.Thread.dumpStack(Thread.java:489)
05-27 06:52:05.848 32176-32732/ru.infotecs.intentservice W/System.err:     at android.os.Looper.prepare(Looper.java:105)
05-27 06:52:05.849 32176-32732/ru.infotecs.intentservice W/System.err:     at android.os.Looper.prepare(Looper.java:86)
05-27 06:52:05.849 32176-32732/ru.infotecs.intentservice W/System.err:     at android.os.HandlerThread.run(HandlerThread.java:53)
05-27 06:52:05.850 32176-32732/ru.infotecs.intentservice D/BackgroundService: ru.infotecs.intentservice.action.START - 1
</code>```

I wonder how such trivial app may lead to the error. I inspected the IntentService implementation a little bit and found that service is voluntarily stopped after intent handling.

```<code>private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        onHandleIntent((Intent)msg.obj);
        stopSelf(msg.arg1);
    }
}
</code>```

Also looper is stopped each time service is destroyed:

```<code>@Override
public void onDestroy() {
    mServiceLooper.quit();
}
</code>```

So I completely have no idea what is wrong. Any ideas?

I use speific device to run my app. It is RugGear RG500. Problem does not reproduce on emulator so it may be a problem of device run-time.

P.S. Currently I got around the problem by coping IntentService implementation to my project with some modifications. I commented out stopSelf method call to keep Looper/Thread alive as much as possible. It does not fix problem completely since Android may stop service in case of memory shortage and start it again lately.

答:
It takes some time to find out what it is going on since I have not inspected memory leaks previously. It looks like device manufacturer did some instrumentation of the Looper code to track allocations. It just prints the error message and dumps call stack but the application is pretty stable at the same time. I think it is vendor specific code since I didn't find this message in a source code of Android SDK.

If you open memory allocation monitor you will see that memory is steadily allocated during some period of time and finally released. It means that garbage collection was initiated by the JVM. The peak value of allocated memory stays the same during the continuous period of time. It does not grow dramatically over the time as it may be expected.

Also, the error message disappears after GC. I assume that allocation counter is just reset in finalize method of instrumented class.

Body:
I am programming an application that needs to sync up with a remote server every minute. There is no way to use push notifications since an app is intended for internal use and it is not going to be published on Google Play.
I found out that I can use AlarmManager and IntentService to reach my objective. So I schedule pending intent to be delivered every minute and handle it in IntentService to perform network I/O. It sounds pretty simple but I faced following problem: app fails with the following error after some period of time (I suppose about 100 minutes).

05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: WARNING: The Looper class instance count has over a limit(100). There should be some leakage of Looper or HandlerThread.
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: Looper class instance count = 101
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: Current Thread Name: IntentService[BackgroundService]

I created very simple example to inspect the problem closer. So it looks like:

Activity:

public class MainActivity extends AppCompatActivity {
    private AlarmManager alarmManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getService(getBaseContext(), 0, BackgroundService.getIntent(getBaseContext()), PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, 500, pi);
    }
}

Service:

public class BackgroundService extends IntentService {
    private final static String TAG = BackgroundService.class.getSimpleName();
    private final static String ACTION_START = "ru.infotecs.intentservice.action.START";
    private static volatile int counter = 0;

    public BackgroundService() {
        super(TAG);
        counter = 0;
    }

    public static Intent getIntent(Context context) {
        Intent intent = new Intent(context, BackgroundService.class);
        intent.setAction(ACTION_START);
        return intent;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_START.equals(action)) {
                counter++;
                Log.d(TAG, ACTION_START + " - "+ counter);
            }
        }
    }
}

As you can see I decreased time interval to 500ms from 1 minute to reproduce problem faster. So now it takes about minute but anyway result is the same:

05-27 06:52:04.348 32176-32717/ru.infotecs.intentservice D/BackgroundService: ru.infotecs.intentservice.action.START - 1
05-27 06:52:04.846 32176-32720/ru.infotecs.intentservice D/BackgroundService: ru.infotecs.intentservice.action.START - 1
05-27 06:52:05.349 32176-32726/ru.infotecs.intentservice D/BackgroundService: ru.infotecs.intentservice.action.START - 1
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: WARNING: The Looper class instance count has over a limit(100). There should be some leakage of Looper or HandlerThread.
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: Looper class instance count = 101
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice E/Looper: Current Thread Name: IntentService[BackgroundService]
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice I/System.out: java.lang.ThreadGroup[name=main,maxPriority=10]
05-27 06:52:05.845 32176-32732/ru.infotecs.intentservice I/System.out:     Thread[main,5,main]
05-27 06:52:05.846 32176-32732/ru.infotecs.intentservice I/System.out:     Thread[Thread-5,5,main]
05-27 06:52:05.847 32176-32732/ru.infotecs.intentservice I/System.out:     Thread[Binder_1,5,main]
05-27 06:52:05.847 32176-32732/ru.infotecs.intentservice I/System.out:     Thread[Binder_2,5,main]
05-27 06:52:05.847 32176-32732/ru.infotecs.intentservice I/System.out:     Thread[IntentService[BackgroundService],5,main]
05-27 06:52:05.848 32176-32732/ru.infotecs.intentservice W/System.err: java.lang.Throwable: stack dump
05-27 06:52:05.848 32176-32732/ru.infotecs.intentservice W/System.err:     at java.lang.Thread.dumpStack(Thread.java:489)
05-27 06:52:05.848 32176-32732/ru.infotecs.intentservice W/System.err:     at android.os.Looper.prepare(Looper.java:105)
05-27 06:52:05.849 32176-32732/ru.infotecs.intentservice W/System.err:     at android.os.Looper.prepare(Looper.java:86)
05-27 06:52:05.849 32176-32732/ru.infotecs.intentservice W/System.err:     at android.os.HandlerThread.run(HandlerThread.java:53)
05-27 06:52:05.850 32176-32732/ru.infotecs.intentservice D/BackgroundService: ru.infotecs.intentservice.action.START - 1

I wonder how such trivial app may lead to the error. I inspected the IntentService implementation a little bit and found that service is voluntarily stopped after intent handling.

private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        onHandleIntent((Intent)msg.obj);
        stopSelf(msg.arg1);
    }
}

Also looper is stopped each time service is destroyed:

@Override
public void onDestroy() {
    mServiceLooper.quit();
}

So I completely have no idea what is wrong. Any ideas?

I use speific device to run my app. It is RugGear RG500. Problem does not reproduce on emulator so it may be a problem of device run-time.

P.S. Currently I got around the problem by coping IntentService implementation to my project with some modifications. I commented out stopSelf method call to keep Looper/Thread alive as much as possible. It does not fix problem completely since Android may stop service in case of memory shortage and start it again lately.


问:
Visual Studio referencing namespaces that don't exist anymore
While I've been making an MVC project with ASP.NET, I've renamed folders etc over time, and for some reason visual studio will still think the files are still stored there with the old name.

For example if I declare a class object that i've made, it will find it, but it will ask me to add like "using.FolderName.Class" when I've since renamed "FolderName" to "Folder" or even made a new folder and moved the class into it. The solution still builds, and everything works. But It's kind of worrying to see it's trying to reference something that's not there anymore. What's going on here? should I be worried?

答:
Check your source code files for the lines that look like

```<code>using System;

namespace MyProject.MyFolder {
}
</code>```

renaming folders won't automatically change the namespace. You could do it automatically with visual studio by right clicking on the folder and choosing  Adjust all namespaces in folder, or by right clicking on the namespace and choose to rename the namespace

Body:
Check your source code files for the lines that look like

using System;

namespace MyProject.MyFolder {
}

renaming folders won't automatically change the namespace. You could do it automatically with visual studio by right clicking on the folder and choosing  Adjust all namespaces in folder, or by right clicking on the namespace and choose to rename the namespace


问:
BLE background scanning
I'm running background service that scan for BLE devices 24/7 using Android BLE API.My service run using START_STICKY. When i find a specific device i do my work.

My question is : Do i still get ScanCallback when my device go to deep sleep or do i need to acquire PARTIAL_WAKE_LOCK to prevent CPU from going to deep sleep to get ScanCallback ?

Thanks.

```<code>public class MYService extends IntentService {

public void onCreate() {
        super.onCreate();
        Log.e("TAG","onCreate");
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        BluetoothLeScanner lEScanner = bluetoothAdapter.getBluetoothLeScanner();
        ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
        List<ScanFilter> filters = new ArrayList<>();
        ScanFilter.Builder sfBuilder = new ScanFilter.Builder();
        sfBuilder.setDeviceName(DEVICE_NAME);
        sfBuilder.setServiceUuid(ParcelUuid.fromString(ServiceUUID_D1));
        filters.add(sfBuilder.build());
        lEScanner.startScan(filters,settings,mScanCallback);
}
</code>```

答: You should use a Foreground Service in the process where you have the BLE scanner to avoid your app from being killed in the background.</p>

Title: BLE background scanning

Body:
I'm running background service that scan for BLE devices 24/7 using Android BLE API.My service run using START_STICKY. When i find a specific device i do my work.

My question is : Do i still get ScanCallback when my device go to deep sleep or do i need to acquire PARTIAL_WAKE_LOCK to prevent CPU from going to deep sleep to get ScanCallback ?

Thanks.

public class MYService extends IntentService {

public void onCreate() {
        super.onCreate();
        Log.e("TAG","onCreate");
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        BluetoothLeScanner lEScanner = bluetoothAdapter.getBluetoothLeScanner();
        ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
        List<ScanFilter> filters = new ArrayList<>();
        ScanFilter.Builder sfBuilder = new ScanFilter.Builder();
        sfBuilder.setDeviceName(DEVICE_NAME);
        sfBuilder.setServiceUuid(ParcelUuid.fromString(ServiceUUID_D1));
        filters.add(sfBuilder.build());
        lEScanner.startScan(filters,settings,mScanCallback);
}


问:
Problem serving images from IIS
I have 2 url's, seemingly they are identical except for case.

i.e

/admin/freetextbox/images/separator.vertical.gif   -   works

/Admin/freetextbox/images/separator.vertical.gif   -   fails with capital A for admin, instead redirects after a 302 Found to the log in page,  logging in simply redirects back to login.  IIS refuses to serve this file if using capital A for Admin.

/adMin/frEetextbox/images/separator.vertical.gif   -   All other mixes of case work

the folder is a Virtual Directory setup unter the root of the site in IIS and it's alias is 'Admin'

答: A further note, if I delete the file completely and copy it back in from source control IIS serves the files again. Must be permissions somewhere or possibly caching but I cannot find the source and one day this problem will rear its ugly head again but for now i have cheated. </p>

Title: Problem serving images from IIS


问:
Java CSV Formatting Issues
I am reading a HashMap and creating a CSV file.
The below code accepts a HashMap and produce a CSV file. However the formatting is a problem. For a HashMap,

```<code>HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);
</code>```

It produces

```<code>Feature2,Feature2,
2,1,Feature1,Feature1,
2,1,
</code>```

Expected Output (without comma at the end of each line):

```<code>Feature2,Feature1
2,1
</code>```

Which is  a wrong formatting

This is the code I use. How to fix it ?

```<code>public String appendCSV(Map featureset) throws IOException{
    StringBuilder csvReport = new StringBuilder();

    Map<String, Integer> map =featureset;
    Set<String> keys = map.keySet();

    String[] lsitofkeys = {};

    for(String elements:keys){
        for(int i =0 ; i< keys.size(); i++){
             csvReport.append(elements+",");
        }
        csvReport.append("\n");
        for(String key: keys){
            csvReport.append(map.get(key).toString()+",");
        }
    }

  return csvReport.toString();
}
</code>```

答:
You should to create a new stringbuilder into the cycle:

```<code>import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class NewClass {

    public NewClass() throws IOException {
        HashMap<String, Integer> hmap = new HashMap<String, Integer>();
        hmap.put("Feature1", 1);
        hmap.put("Feature2", 2);
        System.out.print(appendCSV(hmap));
    }

    public String appendCSV(Map featureset) throws IOException {
        StringBuilder csvReport = new StringBuilder();
        StringBuilder csvReportVal = new StringBuilder();

        Set<String> keys = featureset.keySet();

        for (String elements : keys) {
            csvReport.append(elements + ",");
            csvReportVal.append(featureset.get(elements).toString() + ",");
        }

        // Excluding the latest ","
        csvReport.setLength(csvReport.length() - 1);
        csvReportVal.setLength(csvReportVal.length() - 1);

        csvReport.append("\n" + csvReportVal.toString());
        return csvReport.toString();
    }

    public static void main(String[] args) throws IOException {
        new NewClass();
    }
}
</code>```

OUTPUT:

```<code>Feature2,Feature1
2,1
</code>```

Title: Java CSV Formatting Issues

Body:
I am reading a HashMap and creating a CSV file.
The below code accepts a HashMap and produce a CSV file. However the formatting is a problem. For a HashMap,

HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);

It produces

Feature2,Feature2,
2,1,Feature1,Feature1,
2,1,

Expected Output (without comma at the end of each line):

Feature2,Feature1
2,1

Which is  a wrong formatting

This is the code I use. How to fix it ?

public String appendCSV(Map featureset) throws IOException{
    StringBuilder csvReport = new StringBuilder();

    Map<String, Integer> map =featureset;
    Set<String> keys = map.keySet();

    String[] lsitofkeys = {};

    for(String elements:keys){
        for(int i =0 ; i< keys.size(); i++){
             csvReport.append(elements+",");
        }
        csvReport.append("\n");
        for(String key: keys){
            csvReport.append(map.get(key).toString()+",");
        }
    }

  return csvReport.toString();
}

Body:
You should to create a new stringbuilder into the cycle:

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class NewClass {

    public NewClass() throws IOException {
        HashMap<String, Integer> hmap = new HashMap<String, Integer>();
        hmap.put("Feature1", 1);
        hmap.put("Feature2", 2);
        System.out.print(appendCSV(hmap));
    }

    public String appendCSV(Map featureset) throws IOException {
        StringBuilder csvReport = new StringBuilder();
        StringBuilder csvReportVal = new StringBuilder();

        Set<String> keys = featureset.keySet();

        for (String elements : keys) {
            csvReport.append(elements + ",");
            csvReportVal.append(featureset.get(elements).toString() + ",");
        }

        // Excluding the latest ","
        csvReport.setLength(csvReport.length() - 1);
        csvReportVal.setLength(csvReportVal.length() - 1);

        csvReport.append("\n" + csvReportVal.toString());
        return csvReport.toString();
    }

    public static void main(String[] args) throws IOException {
        new NewClass();
    }
}

OUTPUT:

Feature2,Feature1
2,1


问:
Ionic 2 - Input ‘Go’ field on Keyboard is doing two things
I am building an Ionic App for iOS & Android and so far I have a form where users can upload or take a photo and then fill in some other information and submit the form.

My issue:

Currently when the user goes to an Input to enter some extra text there is a go button at the bottom of the keyboard. If the user clicks this 'Go' button it tries to submit the form along with opening the choosePicture() function I have.

What happen when I click the
Go button - it opens the Library

The HTML

```<code><ion-item class="file-upload">
    <button  class="btn btn-block" ion-button (click)="choosePhoto()">Choose a Photo</button>
    <span class="sep"></span>
    <button class="btn btn-block" ion-button (click)="takePicture()">Take a Picture</button>
    <div class="uploaded-img">
        <input type="file" value="" formControlName="hazardImage" hidden />
        <span class="img-desc">Please Take or Upload an Image.</span>
        <div class="img-picked" *ngIf="base64Img">
            <img [src]="base64Img" alt="Hazard Picture" />
            <!-- <img src="http://placehold.it/300x300" alt="Test Image" /> -->
        </div>
    </div>
</ion-item>

<small class="small-title">Where is the Hazard Location? (required)</small>
<ion-item class="input-box">
    <ion-input type="text" formControlName="hazardLocation" [class.invalid]="!hazardForm.controls.hazardLocation.valid && (hazardForm.controls.hazardLocation.dirty || submitAttempt)"></ion-input>
</ion-item>
</code>```

The TypeScript:

```<code>choosePhoto()
{
    this.Camera.getPicture({
        quality: 50,
        destinationType: this.Camera.DestinationType.DATA_URL,
        encodingType: this.Camera.EncodingType.JPEG,
        sourceType: this.Camera.PictureSourceType.PHOTOLIBRARY,
        allowEdit: true
    }).then((ImageData) => {
        // console.log(ImageData);
        this.base64Img = ImageData;
        this.hazardForm.patchValue({
            hazardImage: this.base64Img
        });
    }, (err) => {
        console.log(err);
    })
}
</code>```

I don't understand why the Go Button is opening the function for choosing a photo :/

答:
You have defined the <input> for "Hazard Location" as a Form since there is a  formControlName="hazardLocation" attribute. This makes the Go or form submit button appear in the mobile keyboard.

Instead, you should have it as a normal input field like this

```<code><input [(ngModel)]="hazardLocation">
</code>```

Body:
I am building an Ionic App for iOS & Android and so far I have a form where users can upload or take a photo and then fill in some other information and submit the form.

My issue:

Currently when the user goes to an Input to enter some extra text there is a go button at the bottom of the keyboard. If the user clicks this 'Go' button it tries to submit the form along with opening the choosePicture() function I have.

What happen when I click the
Go button - it opens the Library

The HTML

<ion-item class="file-upload">
    <button  class="btn btn-block" ion-button (click)="choosePhoto()">Choose a Photo</button>

    <button class="btn btn-block" ion-button (click)="takePicture()">Take a Picture</button>

        <input type="file" value="" formControlName="hazardImage" hidden />
        Please Take or Upload an Image.

</ion-item>

Where is the Hazard Location? (required)
<ion-item class="input-box">
    <ion-input type="text" formControlName="hazardLocation" [class.invalid]="!hazardForm.controls.hazardLocation.valid && (hazardForm.controls.hazardLocation.dirty || submitAttempt)"></ion-input>
</ion-item>

The TypeScript:

choosePhoto()
{
    this.Camera.getPicture({
        quality: 50,
        destinationType: this.Camera.DestinationType.DATA_URL,
        encodingType: this.Camera.EncodingType.JPEG,
        sourceType: this.Camera.PictureSourceType.PHOTOLIBRARY,
        allowEdit: true
    }).then((ImageData) => {
        // console.log(ImageData);
        this.base64Img = ImageData;
        this.hazardForm.patchValue({
            hazardImage: this.base64Img
        });
    }, (err) => {
        console.log(err);
    })
}

I don't understand why the Go Button is opening the function for choosing a photo :/

Body:
You have defined the <input> for "Hazard Location" as a Form since there is a  formControlName="hazardLocation" attribute. This makes the Go or form submit button appear in the mobile keyboard.

Instead, you should have it as a normal input field like this

<input [(ngModel)]="hazardLocation">


问:
Suppress Invoke-SQLCMD Warnings
I have the following code:

```<code>invoke-sqlcmd -ServerInstance $server\$instance -InputFile "$Path\checkDBEncryption.sql" -ErrorAction Ignore -ErrorVariable var | Format-Table;
</code>```

I need any error from invoke-sqlcmd to be hidden from the powershell output since I'm already logging the errors in a separate file. The problem is,        -ErrorAction Ignore (or SilentlyContinue) isn't working, and setting $ErrorActionPreference isn't an option.

答:
I recommend assigning it to a variable :

```<code>$response = invoke-sqlcmd -ServerInstance $server\$instance -InputFile "$Path\checkDBEncryption.sql" -ErrorAction Ignore -ErrorVariable var | Format-Table;
</code>```

If you do not assign the action to a variable anything returned by that cmdlet will basically be dumped into the console.

In some cases it can also cause issues with variable assignment (depending on how the code was written).

As an example if you have a function that returns a value but no variable is associated with it that will be returned to the instance in which you are calling the function.

In addition I recommend you make sure that your attempts to silence that issue have not interfered with your logging details.  I believe your fix is simple as this variable assignment.

Hope this helped with the issue!

Title: Suppress Invoke-SQLCMD Warnings

Body:
I have the following code:

invoke-sqlcmd -ServerInstance $server\$instance -InputFile "$Path\checkDBEncryption.sql" -ErrorAction Ignore -ErrorVariable var | Format-Table;

I need any error from invoke-sqlcmd to be hidden from the powershell output since I'm already logging the errors in a separate file. The problem is,        -ErrorAction Ignore (or SilentlyContinue) isn't working, and setting $ErrorActionPreference isn't an option.

Body:
I recommend assigning it to a variable :

$response = invoke-sqlcmd -ServerInstance $server\$instance -InputFile "$Path\checkDBEncryption.sql" -ErrorAction Ignore -ErrorVariable var | Format-Table;

If you do not assign the action to a variable anything returned by that cmdlet will basically be dumped into the console.

In some cases it can also cause issues with variable assignment (depending on how the code was written).

As an example if you have a function that returns a value but no variable is associated with it that will be returned to the instance in which you are calling the function.

In addition I recommend you make sure that your attempts to silence that issue have not interfered with your logging details.  I believe your fix is simple as this variable assignment.

Hope this helped with the issue!


问:
How to use Angular Decorator to reduce repetitive code?
I have a I18nService that needs to be initialized in 90% of my components. The procedure to do this is importing the service, importing the translation file, implementing ngOnInit() and calling the services init() function.

Now I am trying to reduce the repetitive code with the help of Class Decorators.
The problem I'm currently facing is using my I18nService inside the decorator since Decorators seem to run at compile time. I was trying to solve the problem with injectors and following this article: https://netbasal.com/inspiration-for-custom-decorators-in-angular-95aeb87f072c
but got AppModule undefined.

How can I solve the problem? Are Decorators the right choice to achieve this to begin with?

答:
You can store Injector in constructor AppModule and then use it inside patched ngOnInit method to get some Service registered in your app

app.module.ts

```<code>@NgModule({
  ...
  providers: [AnalyticsService],
})
export class AppModule {
  constructor(private injector: Injector) {
    AppModule.injector = injector;
  }

  static injector: Injector;
}
</code>```

page-track.decorator.ts

```<code>import { AnalyticsService, AppModule } from './app.module';

export function PageTrack(): ClassDecorator {
  return function ( constructor : any ) {
    const ngOnInit = constructor.prototype.ngOnInit;
    constructor.prototype.ngOnInit = function ( ...args ) {
      let service = AppModule.injector.get(AnalyticsService);
      service.visit();
      ngOnInit && ngOnInit.apply(this, args);
    };
  }
}
</code>```

app.component.ts

```<code>@Component({
  selector: 'my-app',
  templateUrl: `./app.component.html`
})
@PageTrack()
export class AppComponent {}
</code>```

Plunker Example

Body:
You can store Injector in constructor AppModule and then use it inside patched ngOnInit method to get some Service registered in your app

app.module.ts

@NgModule({
  ...
  providers: [AnalyticsService],
})
export class AppModule {
  constructor(private injector: Injector) {
    AppModule.injector = injector;
  }

  static injector: Injector;
}

page-track.decorator.ts

import { AnalyticsService, AppModule } from './app.module';

export function PageTrack(): ClassDecorator {
  return function ( constructor : any ) {
    const ngOnInit = constructor.prototype.ngOnInit;
    constructor.prototype.ngOnInit = function ( ...args ) {
      let service = AppModule.injector.get(AnalyticsService);
      service.visit();
      ngOnInit && ngOnInit.apply(this, args);
    };
  }
}

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: `./app.component.html`
})
@PageTrack()
export class AppComponent {}

Plunker Example


问:
Tkinter - Listbox with scrollbar
In my code I want to add some widgets in a Listbox widget, so I can later use a Scrollbar on it. The problem here is that the listbox will keep expanding no matter how many widgets I put in it, and the scrollbar is unusable since it does not update. How can I solve this issue?</p>

```<code>from tkinter import *

def pr_deleteChart():
    global _plotDictionary

    #_F_delChart.iconbitmap('ContaParole_icona.ico')

    _F_mainUpper = Frame(_root)
    _F_mainUpper.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = "nsew")

    _F_mainLower = Frame(_root)
    _F_mainLower.grid(row = 1, column = 0, padx = 5, sticky = "sew")

    #listbox scrollbar
    _S_ListBoxScrollBar = Scrollbar(_F_mainUpper,orient = "vertical")
    _S_ListBoxScrollBar.grid(row = 1, column = 1, sticky = "nse")

    #Main listbox
    _L_mainListBox = Listbox(_F_mainUpper)
    _L_mainListBox.grid(row = 1, column = 0, sticky = "nsew")

    _S_ListBoxScrollBar.config(command = _L_mainListBox.yview)

    #Carico lista di chiavi
    keysList = list(_graphReferences.keys())

    #Per ogni grafico salvo variabile, checkButton e salvo tutto dentro _plotDictionary
    for index in range(0,len(keysList)):

        button = Checkbutton(_L_mainListBox, text = keysList[index])
        button.grid(row = index, column = 0, sticky = "nw")

if __name__== "__main__":

    _root = Tk()
    _root.title("Main window")
    _root.resizable(width = FALSE, height = FALSE)

    _graphReferences = {"1":"2","3":"4","5":"6","7":"8","9":"10","11":"12"}

    pr_deleteChart()
</code>```

答: You cannot scroll items added to a listbox with grid, pack, or place. The scrollbar associated with a listbox will only scroll items added to the listbox with the insert method of the listbox.

Title: Tkinter - Listbox with scrollbar

Body:
In my code I want to add some widgets in a Listbox widget, so I can later use a Scrollbar on it. The problem here is that the listbox will keep expanding no matter how many widgets I put in it, and the scrollbar is unusable since it does not update. How can I solve this issue?

from tkinter import *

def pr_deleteChart():
    global _plotDictionary

    #_F_delChart.iconbitmap('ContaParole_icona.ico')

    _F_mainUpper = Frame(_root)
    _F_mainUpper.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = "nsew")

    _F_mainLower = Frame(_root)
    _F_mainLower.grid(row = 1, column = 0, padx = 5, sticky = "sew")

    #listbox scrollbar
    _S_ListBoxScrollBar = Scrollbar(_F_mainUpper,orient = "vertical")
    _S_ListBoxScrollBar.grid(row = 1, column = 1, sticky = "nse")

    #Main listbox
    _L_mainListBox = Listbox(_F_mainUpper)
    _L_mainListBox.grid(row = 1, column = 0, sticky = "nsew")

    _S_ListBoxScrollBar.config(command = _L_mainListBox.yview)

    #Carico lista di chiavi
    keysList = list(_graphReferences.keys())

    #Per ogni grafico salvo variabile, checkButton e salvo tutto dentro _plotDictionary
    for index in range(0,len(keysList)):

        button = Checkbutton(_L_mainListBox, text = keysList[index])
        button.grid(row = index, column = 0, sticky = "nw")

if __name__== "__main__":

    _root = Tk()
    _root.title("Main window")
    _root.resizable(width = FALSE, height = FALSE)

    _graphReferences = {"1":"2","3":"4","5":"6","7":"8","9":"10","11":"12"}

    pr_deleteChart()


问:
Passing array query parameters with API Gateway to lambda
Can we create a Rest URL like below in API Gateway?

[GET] /employees?id=1&id=2&id=3&id=4

I do not find a way to send id array and get that array into a lambda (python) function

答:
this is very late but I had the same issue and found the problem:

From AWS API Gateway Reference:

When a query parameter is a list type, its value must be a string of comma-separated items. For example, GET /restapis/restapi_id/deployments/deployment_id?embed=apisummary,sdksummary.

Amazon API Gateway does not support nested query parameters of the form: GET /team?user[id]=usrid on a method request. You could work around this limitation by passing an encoded map as a single parameter and serializing it as part of a mapping template or in your back-end integration.

So a fix you could use is restructuring your request such that:

[GET] /employees?id=1,2,3,4

Hope this helps!


问:
Android Emulator won't boot or start. Nothing is popping up
This question is already many times asked but nothing its like my problem.
I don't get it why its not booting up or starting my apk.

Its stuck right there. Nothing is happening just the waiting for target device respond is coming up.

Everything worked perfectly until now.

I even reinstalled it. Didn't help much

PC SPECS:
i7 Core 2.2 GHZ
16GB RAM
Intel Iris Pro 1500MB

Android Studio 2.3

```<code>Error while waiting for device: Timed out after 300seconds waiting for emulator to come online.
</code>```

Still the same error.....

答:
I ran the commands that Jamal Eason recommended in the comments:

```<code>$ cd Android/Sdk/emulator
$ ./emulator -list-avds
$ ./emulator -avd [AVD_NAME]
</code>```

I got some libGL error: unable to load driver: i965_dri.so errors when trying to run the AVD.

I was able to find this thread, where a user was able to fix a very similar issue by renaming the libstdc++.so.6 inside the emulator directory and linking the libstdc++.so.6 from the /usr/ directory.

```<code>$ cd Android/Sdk/emulator/lib64/libstdc++
$ mv libstdc++.so.6 libstdc++.so.6.bak
$ ln -s /usr/lib64/libstdc++.so.6 /home/user/Android/Sdk/emulator/lib64/libstdc++
</code>```

Body:
This question is already many times asked but nothing its like my problem.
I don't get it why its not booting up or starting my apk.

Its stuck right there. Nothing is happening just the waiting for target device respond is coming up.

Everything worked perfectly until now.

I even reinstalled it. Didn't help much

PC SPECS:
i7 Core 2.2 GHZ
16GB RAM
Intel Iris Pro 1500MB

Android Studio 2.3

Error while waiting for device: Timed out after 300seconds waiting for emulator to come online.

Still the same error.....

Body:
I ran the commands that Jamal Eason recommended in the comments:

$ cd Android/Sdk/emulator
$ ./emulator -list-avds
$ ./emulator -avd [AVD_NAME]

I got some libGL error: unable to load driver: i965_dri.so errors when trying to run the AVD.

I was able to find this thread, where a user was able to fix a very similar issue by renaming the libstdc++.so.6 inside the emulator directory and linking the libstdc++.so.6 from the /usr/ directory.

$ cd Android/Sdk/emulator/lib64/libstdc++
$ mv libstdc++.so.6 libstdc++.so.6.bak
$ ln -s /usr/lib64/libstdc++.so.6 /home/user/Android/Sdk/emulator/lib64/libstdc++


问:
Where is my response header coming from?
For an unknown ASP.NET application running under IIS, where can I find where a given response header is set?

Having a comprehensive list would be quite useful to all of us, so please contribute what you know.

Specifics

In my case, I have an ASP.NET MVC application running on IIS 7.0, in integrated pipeline mode. This is a dev environment, with no load-balancers or CDNs to get in the way. I have access to the source code, but haven't been able to find the culprit. I'm looking for the origin of the X-Frame-Options header, of which I have two, with conflicting values of DENY and SAMEORIGIN.

Where should I look for these two, conflicting values?

Similar questions

There's a similar question, specific to Max-Age which has an open bounty at the time of this writing. The reason this question is different is that Max-Age is more likely to be set by a third-party, such as a CDN or reverse-proxy, adding even more complication to the mixture.

Django/NGinx-specific, unanswered

Same problem on IIS6, no resolution

答:
Here are the places I checked. This didn't help me, but it might help someone else.

Web.config. (The following entries are in XPath notation)

/system.webServer/httpProtocol/customHeaders

Look for lines like <add name="header-name" value="header-value" />

/system.webServer/modules (Middleware modules)

Remove any suspect middleware modules temporarily, or step through their OnResponse code, looking at the sender.Response.Headers to see when (or if) the unwanted header is added.

Machine config (source): I looked for the same options as for Web.config, as well as searching for the header name and for any relevant modules. I checked both the 32-bit and 64-bit versions:

32-bit: %windir%\Microsoft.NET\Framework\[version]\config\machine.config

64-bit: %windir%\Microsoft.NET\Framework64\[version]\config\machine.config

Code

Controller annotations

While poking around the code, I found an annotation like this:

```<code>[AddHttpResponseHeaderCustomFilter("X-Frame-Options", "DENY")]
</code>```

Global.asax.cs: Look for anything which adds a header.

Solution-wide search: I tried searching for any occurrence of the following: X-Frame-Options, Frame-Options (case insensitive), frame (case insensitive, whole word only

IIS Manager

Checked the HTTP Response Headers for each of the following levels of hierarchy:

Machine (top-level)

Site (Default Web Site)

Application

Each folder under the application, drilling down to my controller's containing folder. (For most MVC apps, that would be a top-level folder named Controllers, but it could also be Area\AreaName\Controllers.)

Body:
Here are the places I checked. This didn't help me, but it might help someone else.

Web.config. (The following entries are in XPath notation)

/system.webServer/httpProtocol/customHeaders

Look for lines like <add name="header-name" value="header-value" />

/system.webServer/modules (Middleware modules)

Remove any suspect middleware modules temporarily, or step through their OnResponse code, looking at the sender.Response.Headers to see when (or if) the unwanted header is added.

Machine config (source): I looked for the same options as for Web.config, as well as searching for the header name and for any relevant modules. I checked both the 32-bit and 64-bit versions:

32-bit: %windir%\Microsoft.NET\Framework\[version]\config\machine.config

64-bit: %windir%\Microsoft.NET\Framework64\[version]\config\machine.config

Code

Controller annotations

While poking around the code, I found an annotation like this:

[AddHttpResponseHeaderCustomFilter("X-Frame-Options", "DENY")]

Global.asax.cs: Look for anything which adds a header.

Solution-wide search: I tried searching for any occurrence of the following: X-Frame-Options, Frame-Options (case insensitive), frame (case insensitive, whole word only

IIS Manager

Checked the HTTP Response Headers for each of the following levels of hierarchy:

Machine (top-level)

Site (Default Web Site)

Application

Each folder under the application, drilling down to my controller's containing folder. (For most MVC apps, that would be a top-level folder named Controllers, but it could also be Area\AreaName\Controllers.)


问:
How to add strata information to a genind
I have created a genind object from a table containing SNPs information.

I need to insert population information into this genind.

I know which individuals (which are identified by numbers) should go into each population.

How do I pick the correct individuals and place them into separate populations?

答:
It's always helpful to make a reproducible example when asking a question.

First, loading the necessary library (pretty sure its adegenet)

library(adegenet)

Making some fake data by first getting a vector of alleles

alleles <- paste0("0",1:4)

Setting number of loci, individuals per population, and the number of populations

```<code>nloci <- 10
nind <- 10
npops <- 2
</code>```

Using a for loop to make the fake dataset

```<code>i <- NULL
out <- NULL
for(i in 1:npops){
  #there are nind*nloci genotypes in each population
  #make a
  gts <- replicate(n = nind*nloci,
                   expr = paste0(sample(x = alleles,size = 1,replace = T),
                                 sample(x = alleles,size = 1,replace = T)))
  gts <- as.data.frame(matrix(data = gts,
                              nrow = nind, ncol = nloci, byrow = T))
  #making generic locus colnames()
  colnames(gts) <- paste("locus_",1:nloci)
  out <- rbind(out,gts)
} #end of for loop
head(out)
</code>```

Now converting that data.frame into a genind

```<code>obj <- df2genind(out, ploidy=2, ncode=2)
obj
</code>```

Note that the row.names() are considered individual IDs

Now for setting the populations, note its empty right now

```<code>obj@pop
</code>```

You just need a vector that represents the populations corresponding to each individual.

Option 1

If your individual IDs are clustered by population (e.g. 1-10 are from pop1 and 11-20 are from pop2), then something like this should work

```<code>pops<- paste0("pop",1:npops)
</code>```

Set the populations using that vector, make sure it's a factor

```<code>obj@pop <- as.factor(rep(pops,each=nind))
obj@pop
</code>```

Option 2

If the original data.frame (table) that contained your SNP information also contained population information, you could use that as your vector

e.g. If out looked like this

```<code>out$pops <- sample(x = pops,size = nrow(out),replace = T)
head(out)
</code>```

Then do could use that column as your vector

```<code>obj@pop <- as.factor(out$pops)
obj@pop
</code>```

Option 3

Alternatively, if you had another table that enabled you to identify which individuals corresponded to which population, then you use that information. It assumes that the second table (data.frame) is the same number of rows as out

Here is an example second table

```<code>df <- data.frame(pops = rep(pops,each=nind),
                 id = sample(x = 1:nrow(out),size = nrow(out),replace = F))
head(df)
</code>```

Note that the IDs are not in order, but they were in out and therefore are in the obj, so df needs to be ordered by df$id

```<code>df <- df[order(df$id),]
head(df)
</code>```

After they are in the correct order

```<code>obj@pop <- as.factor(df$pops)
obj@pop
</code>```

Body:
It's always helpful to make a reproducible example when asking a question.

First, loading the necessary library (pretty sure its adegenet)

library(adegenet)

Making some fake data by first getting a vector of alleles

alleles <- paste0("0",1:4)

Setting number of loci, individuals per population, and the number of populations

nloci <- 10
nind <- 10
npops <- 2

Using a for loop to make the fake dataset

i <- NULL
out <- NULL
for(i in 1:npops){
  #there are nind*nloci genotypes in each population
  #make a
  gts <- replicate(n = nind*nloci,
                   expr = paste0(sample(x = alleles,size = 1,replace = T),
                                 sample(x = alleles,size = 1,replace = T)))
  gts <- as.data.frame(matrix(data = gts,
                              nrow = nind, ncol = nloci, byrow = T))
  #making generic locus colnames()
  colnames(gts) <- paste("locus_",1:nloci)
  out <- rbind(out,gts)
} #end of for loop
head(out)

Now converting that data.frame into a genind

obj <- df2genind(out, ploidy=2, ncode=2)
obj

Note that the row.names() are considered individual IDs

Now for setting the populations, note its empty right now

obj@pop

You just need a vector that represents the populations corresponding to each individual.

Option 1

If your individual IDs are clustered by population (e.g. 1-10 are from pop1 and 11-20 are from pop2), then something like this should work

pops<- paste0("pop",1:npops)

Set the populations using that vector, make sure it's a factor

obj@pop <- as.factor(rep(pops,each=nind))
obj@pop

Option 2

If the original data.frame (table) that contained your SNP information also contained population information, you could use that as your vector

e.g. If out looked like this

out$pops <- sample(x = pops,size = nrow(out),replace = T)
head(out)

Then do could use that column as your vector

obj@pop <- as.factor(out$pops)
obj@pop

Option 3

Alternatively, if you had another table that enabled you to identify which individuals corresponded to which population, then you use that information. It assumes that the second table (data.frame) is the same number of rows as out

Here is an example second table

df <- data.frame(pops = rep(pops,each=nind),
                 id = sample(x = 1:nrow(out),size = nrow(out),replace = F))
head(df)

Note that the IDs are not in order, but they were in out and therefore are in the obj, so df needs to be ordered by df$id

df <- df[order(df$id),]
head(df)

After they are in the correct order

obj@pop <- as.factor(df$pops)
obj@pop


问:
How can I disable a table in a SQL Server database from SSMS
I inherited a SQL Server database used with a C# client application. I know enough to be dangerous but I'm not a programmer. I know the previous programmer liked to play around in the live database and as a result I have a number of what I think are orphaned tables.

The application itself isn't super high-usage and can withstand the exceptions of tables not being there for a small time frame. I'd like to start turning off or disabling these tables to see they're being used anymore through trial and error.

Is there a way to turn them off without completely removing the data so that I can re-enable them quickly if needed? Or is there a more transparent way to discover whether those tables are needed?

答:
You can change the permissions so that no one except you and the dbos have select permission on the table. You cannot prevent a dbo or sa from having all permissions on a table.

You can also encrypt the table see- Encrypting database tables in SQL Server 2008 in which case it is really locked down.

You can also used SQL Server Audit to see if anyone reads the data. Audit is a very low impact product (comes with SQL Server 2008) and is very easy to set up and can audit selects unlike a trigger.


问:
join strings in JS
I have an array A and array B:

```<code>A = ["1234","5678","4444"]
B = 7868,9090
</code>```

I want array C to be:

```<code>C = ["1234","5678","4444","7868","9090"]
</code>```

The length of array A and B can vary and array B should join the end of array A.

What is the best way to do this?

I tried using push() but I'm still having problems.

Thank you.

答:
Assuming B is also an array, you can make use of the ES6 spread function:

```<code>A = ["1234","5678","4444"];
B = ["7868","9090"];
C = [...A, ...B]
</code>```

which gives C = ["1234","5678","4444", "7868","9090"]

See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Spread_operator for more information and https://davidwalsh.name/spread-operator for more examples of the spread operator

Title: join strings in JS

Body:
I have an array A and array B:

A = ["1234","5678","4444"]
B = 7868,9090

I want array C to be:

C = ["1234","5678","4444","7868","9090"]

The length of array A and B can vary and array B should join the end of array A.

What is the best way to do this?

I tried using push() but I'm still having problems.

Thank you.

Body:
Assuming B is also an array, you can make use of the ES6 spread function:

A = ["1234","5678","4444"];
B = ["7868","9090"];
C = [...A, ...B]

which gives C = ["1234","5678","4444", "7868","9090"]

See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Spread_operator for more information and https://davidwalsh.name/spread-operator for more examples of the spread operator


问:
I need a way to see which of my db tables are not empty, but I am strugling with the syntax a bit
I use a reference table that references schemas (table names) by schemaid.
I need to run a SELECT count() from T(table) where count() > 0
But only for those tables with CORE:Table in the name. The substitution for the (table) I thought I could do by DECLARING @schemaset and then use the while loop to process it. I am more used to FOR loop, but MSSQL does not seem to have that.

```<code>DECLARE @schemaset VARCHAR

WHILE @schemaset in (select schemaId from arschema where name like 'CORE:Table%')

BEGIN
  select COUNT(*) from T(@schemaset)where FIELD1 IS NOT NULL
END
</code>```

Query runs, but it says it completed successfully. I tried PRINT to see the results, but that complained with an error.

So, how do I get a full/empty check on a set of specific tables?

答:
You don't need looping or dynamic sql for this. This will return all tables that have zero rows with a single select statement.</p>

```<code>SELECT TableName = t.name
    , TableRowCount = SUM(p.rows)
    , SchemaName = s.name
FROM sys.partitions AS p
INNER JOIN sys.tables AS t ON p.object_id = t.object_id
INNER JOIN sys.schemas AS s ON t.schema_id = s.schema_id
WHERE p.index_id IN (0, 1) -- heap or clustered index
group by t.name
    , s.name
having SUM(p.rows) = 0
order by t.name
</code>```

Body:
I use a reference table that references schemas (table names) by schemaid.
I need to run a SELECT count() from T(table) where count() > 0
But only for those tables with CORE:Table in the name. The substitution for the (table) I thought I could do by DECLARING @schemaset and then use the while loop to process it. I am more used to FOR loop, but MSSQL does not seem to have that.

DECLARE @schemaset VARCHAR

WHILE @schemaset in (select schemaId from arschema where name like 'CORE:Table%')

BEGIN
  select COUNT(*) from T(@schemaset)where FIELD1 IS NOT NULL
END

Query runs, but it says it completed successfully. I tried PRINT to see the results, but that complained with an error.

So, how do I get a full/empty check on a set of specific tables?

Body:
You don't need looping or dynamic sql for this. This will return all tables that have zero rows with a single select statement.

SELECT TableName = t.name
    , TableRowCount = SUM(p.rows)
    , SchemaName = s.name
FROM sys.partitions AS p
INNER JOIN sys.tables AS t ON p.object_id = t.object_id
INNER JOIN sys.schemas AS s ON t.schema_id = s.schema_id
WHERE p.index_id IN (0, 1) -- heap or clustered index
group by t.name
    , s.name
having SUM(p.rows) = 0
order by t.name


问:
Read Battery Percentage of iPhone via WLAN
I found an app that shows the battery percentage of my iPhone in the menu bar (iBetterCharge). The iPhone is not connected via USB or Bluetooth (it is only connected to the same network as my Macbook).

My question is: How can I get this information? The device shows up in IOReg, but only because I connected my phone via Bluetooth once.

答:
This can be done by using the unix application "libimobiledevice". I'm not sure that it works with all versions of iOS.

```<code>//install it:
brew install libimobiledevice

//list all device
idevice_id --list // list available device UDIDs. Normally, we have to plug the device at least once to get its UUID.

//get the current syslog of device that we want to check
idevicesyslog -u <device udid>

//do some text search to get the battery info

//or running ideviceinfo (I don't know if it works wirelessly)
//run 'ideviceinfo --help' to see how it works
ideviceinfo -u <device udid> --domain com.apple.mobile.battery
</code>```

More read at:
https://www.theiphonewiki.com/wiki/MobileDevice_Library

Body:
This can be done by using the unix application "libimobiledevice". I'm not sure that it works with all versions of iOS.

//install it:
brew install libimobiledevice

//list all device
idevice_id --list // list available device UDIDs. Normally, we have to plug the device at least once to get its UUID.

//get the current syslog of device that we want to check
idevicesyslog -u <device udid>

//do some text search to get the battery info

//or running ideviceinfo (I don't know if it works wirelessly)
//run 'ideviceinfo --help' to see how it works
ideviceinfo -u <device udid> --domain com.apple.mobile.battery

More read at:
https://www.theiphonewiki.com/wiki/MobileDevice_Library


问:
How to get Nth parent for an element in xml using Java
I am using w3c dom library to parse XML. Here I need 3rd parent of element .For example in below XML I am using element.getParentNode()

Input XML

```<code><abc cd="1">
    <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
        <current_conditions>
            <condition data="Clear">
                <item abc ="1" />
            </condition>
            <temp_f data="49"/>
            <temp_c data="9"/>
        </current_conditions>
    </weather>
</abc>
</code>```

I have Element eleItem= /item  and have to get to parent /weather I am doing it as :

```<code>(Element) eleItem.getParentNode().getParentNode().getParentNode();
</code>```

Is there any other method or using xpath as this doesn't seem to be the right way ?
something likegetXPathParent(eleItem, "../../..")

答:
You are almost there. You could use XPathFactory of java like below :

```<code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc = db.parse( new File( "input.xml" ) );

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();

XPathExpression expr = xpath.compile ( "//item/../../..");

Object exprValue = expr.evaluate( doc, XPathConstants.NODE );

if ( exprValue != null && exprValue instanceof Node )
{
    Node weatherNode = (Node)exprValue;

    System.out.println( weatherNode.getNodeName() );
}
</code>```

How it works?
The xpath //item/../../.. recursively searches for element item and gets its 3rd level parent.

The XPathConstants.NODE in the evaluate tells Java XPath engine to retrieve it as a Node.

Output will be :

weather

EDIT:
 - If you have an element as input :

The following code should give the 3rd parent, where element is item.

```<code>public Node getParentNodeUsingXPath( Element element )
{
    Node parentNode = null;
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();

    String nodeName = element.getNodeName();

    String expression = "//" + nodeName + "/../../..";

    Object obj =    xpath.evaluate(expression, element, XPathConstants.NODE );
    if ( obj != null )
    {
        parentNode = (Node)obj;
    }

    return parentNode;
}
</code>```

Body:
I am using w3c dom library to parse XML. Here I need 3rd parent of element .For example in below XML I am using element.getParentNode()

Input XML

<abc cd="1">
    <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
        <current_conditions>
            <condition data="Clear">
                <item abc ="1" />
            </condition>
            <temp_f data="49"/>
            <temp_c data="9"/>
        </current_conditions>
    </weather>
</abc>

I have Element eleItem= /item  and have to get to parent /weather I am doing it as :

(Element) eleItem.getParentNode().getParentNode().getParentNode();

Is there any other method or using xpath as this doesn't seem to be the right way ?
something likegetXPathParent(eleItem, "../../..")

Body:
You are almost there. You could use XPathFactory of java like below :

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc = db.parse( new File( "input.xml" ) );

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();

XPathExpression expr = xpath.compile ( "//item/../../..");

Object exprValue = expr.evaluate( doc, XPathConstants.NODE );

if ( exprValue != null && exprValue instanceof Node )
{
    Node weatherNode = (Node)exprValue;

    System.out.println( weatherNode.getNodeName() );
}

How it works?
The xpath //item/../../.. recursively searches for element item and gets its 3rd level parent.

The XPathConstants.NODE in the evaluate tells Java XPath engine to retrieve it as a Node.

Output will be :

weather

EDIT:
 - If you have an element as input :

The following code should give the 3rd parent, where element is item.

public Node getParentNodeUsingXPath( Element element )
{
    Node parentNode = null;
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();

    String nodeName = element.getNodeName();

    String expression = "//" + nodeName + "/../../..";

    Object obj =    xpath.evaluate(expression, element, XPathConstants.NODE );
    if ( obj != null )
    {
        parentNode = (Node)obj;
    }

    return parentNode;
}


问:
Double check my IF AND OR statement
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

```<code>$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }
</code>```

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

答:
"Is this logical?"

I believe the answer is no.

```<code>let p = is_file($dirchk1)
let q = is_file($dirchk2)

  |p |p'|
--+--+--+
q |1 |0 |
--+--+--+
q'|1 |0 |
</code>```

You want to do the code when only p is true, and then else if only q is true, so the simplification is as follows:

```<code>if (is_file($dirchk1))
{
  //do code
}
else if (is_file($dirchk2))
{
  //only $dirchk2 exists
}
</code>```

EDIT: After the OP specified the false/false condition needing to be part of the else block:

the final answer should be:

```<code>if (is_file($dirchk1))
{
  //do code
}
else
{
  //dirchk2 may or may not exist
}
</code>```

Title: Double check my IF AND OR statement

Body:
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

Body:
"Is this logical?"

I believe the answer is no.

let p = is_file($dirchk1)
let q = is_file($dirchk2)

  |p |p'|
--+--+--+
q |1 |0 |
--+--+--+
q'|1 |0 |

You want to do the code when only p is true, and then else if only q is true, so the simplification is as follows:

if (is_file($dirchk1))
{
  //do code
}
else if (is_file($dirchk2))
{
  //only $dirchk2 exists
}

EDIT: After the OP specified the false/false condition needing to be part of the else block:

the final answer should be:

if (is_file($dirchk1))
{
  //do code
}
else
{
  //dirchk2 may or may not exist
}