问:
Animating a div with CSS animations with a slight delay between two
What I am trying to do is basically a notification bar which I want to show and hide with CSS animation. The problem is I am not being able to make a good amount of delay between the occurring of two animations.

HTML

```<code><div id="notification" class="alert" role="alert"></div>
</code>```

JS

```<code>$('#notification').html('This place is already occupied!').addClass('alert-warning animated bounceInDown').show().delay(5000).addClass('bounceOutUp');
</code>```

CSS

```<code>#notification {
    position: fixed;
    top: 5px;
    border-radius: 0;
    width: 100%;
    display: none;
    z-index: 1200 !important;
}
.animated {
    -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
}
@-webkit-keyframes bounceInDown {
    from, 60%, 75%, 90%, to {
        -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
        animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    }
    0% {
        opacity: 0;
        -webkit-transform: translate3d(0, -3000px, 0);
        transform: translate3d(0, -3000px, 0);
    }
    60% {
        opacity: 1;
        -webkit-transform: translate3d(0, 25px, 0);
        transform: translate3d(0, 25px, 0);
    }
    75% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    90% {
        -webkit-transform: translate3d(0, 5px, 0);
        transform: translate3d(0, 5px, 0);
    }
    to {
        -webkit-transform: none;
        transform: none;
    }
}
@keyframes bounceInDown {
    from, 60%, 75%, 90%, to {
        -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
        animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    }
    0% {
        opacity: 0;
        -webkit-transform: translate3d(0, -3000px, 0);
        transform: translate3d(0, -3000px, 0);
    }
    60% {
        opacity: 1;
        -webkit-transform: translate3d(0, 25px, 0);
        transform: translate3d(0, 25px, 0);
    }
    75% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    90% {
        -webkit-transform: translate3d(0, 5px, 0);
        transform: translate3d(0, 5px, 0);
    }
    to {
        -webkit-transform: none;
        transform: none;
    }
}
.bounceInDown {
    -webkit-animation-name: bounceInDown;
    animation-name: bounceInDown;
}
@-webkit-keyframes bounceOutUp {
    20% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    40%, 45% {
        opacity: 1;
        -webkit-transform: translate3d(0, 20px, 0);
        transform: translate3d(0, 20px, 0);
    }
    to {
        opacity: 0;
        -webkit-transform: translate3d(0, -2000px, 0);
        transform: translate3d(0, -2000px, 0);
    }
}
@keyframes bounceOutUp {
    20% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    40%, 45% {
        opacity: 1;
        -webkit-transform: translate3d(0, 20px, 0);
        transform: translate3d(0, 20px, 0);
    }
    to {
        opacity: 0;
        -webkit-transform: translate3d(0, -2000px, 0);
        transform: translate3d(0, -2000px, 0);
    }
}
.bounceOutUp {
    -webkit-animation-name: bounceOutUp;
    animation-name: bounceOutUp;
}
</code>```

答:
You can add an animationend event listener with a setTimeout() that adds the next animation after the animation has run.

var $notification = $('#notification'),
    delay = 5000;
$notification.html('This place is already occupied!').addClass('alert-warning animated bounceInDown').show().one('animationend',function() {
  var timeout = setTimeout(function() {
    $notification.addClass('bounceOutUp');
  },delay)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#notification {
  position: fixed;
  top: 5px;
  border-radius: 0;
  width: 100%;
  display: none;
  z-index: 1200 !important;
}

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

@-webkit-keyframes bounceInDown {
  from,
  60%,
  75%,
  90%,
  to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }
  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }
  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }
  to {
    -webkit-transform: none;
    transform: none;
  }
}

@keyframes bounceInDown {
  from,
  60%,
  75%,
  90%,
  to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }
  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }
  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }
  to {
    -webkit-transform: none;
    transform: none;
  }
}

.bounceInDown {
  -webkit-animation-name: bounceInDown;
  animation-name: bounceInDown;
}

@-webkit-keyframes bounceOutUp {
  20% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  40%,
  45% {
    opacity: 1;
    -webkit-transform: translate3d(0, 20px, 0);
    transform: translate3d(0, 20px, 0);
  }
  to {
    opacity: 0;
    -webkit-transform: translate3d(0, -2000px, 0);
    transform: translate3d(0, -2000px, 0);
  }
}

@keyframes bounceOutUp {
  20% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  40%,
  45% {
    opacity: 1;
    -webkit-transform: translate3d(0, 20px, 0);
    transform: translate3d(0, 20px, 0);
  }
  to {
    opacity: 0;
    -webkit-transform: translate3d(0, -2000px, 0);
    transform: translate3d(0, -2000px, 0);
  }
}

.bounceOutUp {
  -webkit-animation-name: bounceOutUp;
  animation-name: bounceOutUp;
}</code>```

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

<p>You could also use the same technique and just alter the <code>animation-delay</code> of the <code>.bounceOutUp</code> class to be 5s instead of using a timer.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var $notification = $('#notification');

$notification.html('This place is already occupied!').addClass('alert-warning animated bounceInDown').show().one('animationend',function() {
  $(this).addClass('bounceOutUp');
});</code>```

#notification {
  position: fixed;
  top: 5px;
  border-radius: 0;
  width: 100%;
  display: none;
  z-index: 1200 !important;
}

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

@-webkit-keyframes bounceInDown {
  from,
  60%,
  75%,
  90%,
  to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }
  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }
  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }
  to {
    -webkit-transform: none;
    transform: none;
  }
}

@keyframes bounceInDown {
  from,
  60%,
  75%,
  90%,
  to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }
  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }
  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }
  to {
    -webkit-transform: none;
    transform: none;
  }
}

.bounceInDown {
  -webkit-animation-name: bounceInDown;
  animation-name: bounceInDown;
}

@-webkit-keyframes bounceOutUp {
  20% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  40%,
  45% {
    opacity: 1;
    -webkit-transform: translate3d(0, 20px, 0);
    transform: translate3d(0, 20px, 0);
  }
  to {
    opacity: 0;
    -webkit-transform: translate3d(0, -2000px, 0);
    transform: translate3d(0, -2000px, 0);
  }
}

@keyframes bounceOutUp {
  20% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  40%,
  45% {
    opacity: 1;
    -webkit-transform: translate3d(0, 20px, 0);
    transform: translate3d(0, 20px, 0);
  }
  to {
    opacity: 0;
    -webkit-transform: translate3d(0, -2000px, 0);
    transform: translate3d(0, -2000px, 0);
  }
}

.bounceOutUp {
  -webkit-animation-name: bounceOutUp;
  animation-name: bounceOutUp;
  animation-delay: 5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notification" class="alert" role="alert"></div></code>```

Body:
What I am trying to do is basically a notification bar which I want to show and hide with CSS animation. The problem is I am not being able to make a good amount of delay between the occurring of two animations.

HTML

JS

$('#notification').html('This place is already occupied!').addClass('alert-warning animated bounceInDown').show().delay(5000).addClass('bounceOutUp');

CSS

#notification {
    position: fixed;
    top: 5px;
    border-radius: 0;
    width: 100%;
    display: none;
    z-index: 1200 !important;
}
.animated {
    -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
}
@-webkit-keyframes bounceInDown {
    from, 60%, 75%, 90%, to {
        -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
        animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    }
    0% {
        opacity: 0;
        -webkit-transform: translate3d(0, -3000px, 0);
        transform: translate3d(0, -3000px, 0);
    }
    60% {
        opacity: 1;
        -webkit-transform: translate3d(0, 25px, 0);
        transform: translate3d(0, 25px, 0);
    }
    75% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    90% {
        -webkit-transform: translate3d(0, 5px, 0);
        transform: translate3d(0, 5px, 0);
    }
    to {
        -webkit-transform: none;
        transform: none;
    }
}
@keyframes bounceInDown {
    from, 60%, 75%, 90%, to {
        -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
        animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    }
    0% {
        opacity: 0;
        -webkit-transform: translate3d(0, -3000px, 0);
        transform: translate3d(0, -3000px, 0);
    }
    60% {
        opacity: 1;
        -webkit-transform: translate3d(0, 25px, 0);
        transform: translate3d(0, 25px, 0);
    }
    75% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    90% {
        -webkit-transform: translate3d(0, 5px, 0);
        transform: translate3d(0, 5px, 0);
    }
    to {
        -webkit-transform: none;
        transform: none;
    }
}
.bounceInDown {
    -webkit-animation-name: bounceInDown;
    animation-name: bounceInDown;
}
@-webkit-keyframes bounceOutUp {
    20% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    40%, 45% {
        opacity: 1;
        -webkit-transform: translate3d(0, 20px, 0);
        transform: translate3d(0, 20px, 0);
    }
    to {
        opacity: 0;
        -webkit-transform: translate3d(0, -2000px, 0);
        transform: translate3d(0, -2000px, 0);
    }
}
@keyframes bounceOutUp {
    20% {
        -webkit-transform: translate3d(0, -10px, 0);
        transform: translate3d(0, -10px, 0);
    }
    40%, 45% {
        opacity: 1;
        -webkit-transform: translate3d(0, 20px, 0);
        transform: translate3d(0, 20px, 0);
    }
    to {
        opacity: 0;
        -webkit-transform: translate3d(0, -2000px, 0);
        transform: translate3d(0, -2000px, 0);
    }
}
.bounceOutUp {
    -webkit-animation-name: bounceOutUp;
    animation-name: bounceOutUp;
}

Body:
You can add an animationend event listener with a setTimeout() that adds the next animation after the animation has run.

var $notification = $('#notification'),
    delay = 5000;
$notification.html('This place is already occupied!').addClass('alert-warning animated bounceInDown').show().one('animationend',function() {
  var timeout = setTimeout(function() {
    $notification.addClass('bounceOutUp');
  },delay)
});

#notification {
  position: fixed;
  top: 5px;
  border-radius: 0;
  width: 100%;
  display: none;
  z-index: 1200 !important;
}

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

@-webkit-keyframes bounceInDown {
  from,
  60%,
  75%,
  90%,
  to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }
  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }
  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }
  to {
    -webkit-transform: none;
    transform: none;
  }
}

@keyframes bounceInDown {
  from,
  60%,
  75%,
  90%,
  to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }
  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }
  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }
  to {
    -webkit-transform: none;
    transform: none;
  }
}

.bounceInDown {
  -webkit-animation-name: bounceInDown;
  animation-name: bounceInDown;
}

@-webkit-keyframes bounceOutUp {
  20% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  40%,
  45% {
    opacity: 1;
    -webkit-transform: translate3d(0, 20px, 0);
    transform: translate3d(0, 20px, 0);
  }
  to {
    opacity: 0;
    -webkit-transform: translate3d(0, -2000px, 0);
    transform: translate3d(0, -2000px, 0);
  }
}

@keyframes bounceOutUp {
  20% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  40%,
  45% {
    opacity: 1;
    -webkit-transform: translate3d(0, 20px, 0);
    transform: translate3d(0, 20px, 0);
  }
  to {
    opacity: 0;
    -webkit-transform: translate3d(0, -2000px, 0);
    transform: translate3d(0, -2000px, 0);
  }
}

.bounceOutUp {
  -webkit-animation-name: bounceOutUp;
  animation-name: bounceOutUp;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notification" class="alert" role="alert"></div>

You could also use the same technique and just alter the animation-delay of the .bounceOutUp class to be 5s instead of using a timer.

var $notification = $('#notification');

$notification.html('This place is already occupied!').addClass('alert-warning animated bounceInDown').show().one('animationend',function() {
  $(this).addClass('bounceOutUp');
});

#notification {
  position: fixed;
  top: 5px;
  border-radius: 0;
  width: 100%;
  display: none;
  z-index: 1200 !important;
}

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

@-webkit-keyframes bounceInDown {
  from,
  60%,
  75%,
  90%,
  to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }
  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }
  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }
  to {
    -webkit-transform: none;
    transform: none;
  }
}

@keyframes bounceInDown {
  from,
  60%,
  75%,
  90%,
  to {
    -webkit-animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
  }
  0% {
    opacity: 0;
    -webkit-transform: translate3d(0, -3000px, 0);
    transform: translate3d(0, -3000px, 0);
  }
  60% {
    opacity: 1;
    -webkit-transform: translate3d(0, 25px, 0);
    transform: translate3d(0, 25px, 0);
  }
  75% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  90% {
    -webkit-transform: translate3d(0, 5px, 0);
    transform: translate3d(0, 5px, 0);
  }
  to {
    -webkit-transform: none;
    transform: none;
  }
}

.bounceInDown {
  -webkit-animation-name: bounceInDown;
  animation-name: bounceInDown;
}

@-webkit-keyframes bounceOutUp {
  20% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  40%,
  45% {
    opacity: 1;
    -webkit-transform: translate3d(0, 20px, 0);
    transform: translate3d(0, 20px, 0);
  }
  to {
    opacity: 0;
    -webkit-transform: translate3d(0, -2000px, 0);
    transform: translate3d(0, -2000px, 0);
  }
}

@keyframes bounceOutUp {
  20% {
    -webkit-transform: translate3d(0, -10px, 0);
    transform: translate3d(0, -10px, 0);
  }
  40%,
  45% {
    opacity: 1;
    -webkit-transform: translate3d(0, 20px, 0);
    transform: translate3d(0, 20px, 0);
  }
  to {
    opacity: 0;
    -webkit-transform: translate3d(0, -2000px, 0);
    transform: translate3d(0, -2000px, 0);
  }
}

.bounceOutUp {
  -webkit-animation-name: bounceOutUp;
  animation-name: bounceOutUp;
  animation-delay: 5s;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notification" class="alert" role="alert"></div>


来源: stackexchange

答:
Pure numpy

```<code>numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1)
</code>```

Check out the loadtxt documentation.

You can also use python's csv module:

```<code>import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")
</code>```

You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:

```
result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")
```

Added Hint:

You could also use pandas.io.parsers.read_csv and get the associated numpy array which can be faster.

ContentLicense: CC BY-SA 3.0

Title: load csv into 2D matrix with numpy for plotting

Body:
Given this CSV file:

"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12

I simply want to load it as a matrix/ndarray with 3 rows and 7 columns.  However, for some reason, all I can get out of numpy is an ndarray with 3 rows (one per line) and no columns.

r = np.genfromtxt(fname,delimiter=',',dtype=None, names=True)
print r
print r.shape

[ (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291111964948.0)
 (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291113113366.0)
 (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291120650486.0)]
(3,)

I can manually iterate and hack it into the shape I want, but this seems silly.  I just want to load it as a proper matrix so I can slice it across different dimensions and plot it, just like in matlab.

Body:
Pure numpy

numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1)

Check out the loadtxt documentation.

You can also use python's csv module:

import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")

You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:

result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")

Added Hint:

You could also use pandas.io.parsers.read_csv and get the associated numpy array which can be faster.


问:
AFrame: how to add a touch event listener to an entity
In mobile browser, I want to do something when user touches an image, but I don't know how to use touch listeners. Is there some components that I can use? Or give me some idea how to do it on my own.</p>

答:
A-Frame supports DOM events very similarly to web normal pages. Example:

```<code><a-scene>
  <!-- Target -->
  <a-box id="target" material="color: green"></a-box>

  <!-- Camera + Cursor -->
  <a-entity camera>
    <a-entity cursor="fuse: true; fuseTimeout: 500"
            position="0 0 -1"
            geometry="primitive: ring; radiusInner: 0.02; radiusOuter: 0.03"
            material="color: black; shader: flat">
    </a-entity>
  </a-entity>
</a-scene>
</code>```

And then in JavaScript:

```<code>var targetEl = document.querySelector('#target');
targetEl.addEventListener('click', function() {
  targetEl.setAttribute('material', {color: 'red'});
});
</code>```

See A-Frame's cursor component documentation for more details.

Body:
A-Frame supports DOM events very similarly to web normal pages. Example:

<a-scene>
  <!-- Target -->
  <a-box id="target" material="color: green"></a-box>

  <!-- Camera + Cursor -->
  <a-entity camera>
    <a-entity cursor="fuse: true; fuseTimeout: 500"
            position="0 0 -1"
            geometry="primitive: ring; radiusInner: 0.02; radiusOuter: 0.03"
            material="color: black; shader: flat">
    </a-entity>
  </a-entity>
</a-scene>

And then in JavaScript:

var targetEl = document.querySelector('#target');
targetEl.addEventListener('click', function() {
  targetEl.setAttribute('material', {color: 'red'});
});

See A-Frame's cursor component documentation for more details.


问:
How is the binary data of each character in a unicode string separated from the binary data of the next character?
in JavaScript I can get the Unicode from a single character using the charCodeAt-method.

When I use this to convert a string to the unicode number I will get following results:

"A".charCodeAt(0) === 65

"४".charCodeAt(0) === 2410

Converting these decimal numbers to binary numbers would be following:

"A".charCodeAt(0).toString(2) === "1000001" // 1 byte, with padleft: "01000001"

"४".charCodeAt(0).toString(2) === "100101101010" // 2 bytes, with padleft: "0000100101101010"

This means, that the ४-symbol uses 2 bytes to get represented. But how does the reading process know that?

It could be also two different characters " " and "j":

String.fromCharCode(parseInt("00001001", 2)) === " " // horizontal tabulator

String.fromCharCode(parseInt("01101010", 2)) === "j".

So how does the binary reading process know how many bytes are used for one single character? Is there something like a separator?

答:
Unicode maps each character* to an integer “code point”.  Valid code points are U+0000 through U+10FFFF, allowing for more than a million characters (although most of these aren't assigned yet).

(* It's a bit more complicated than that because there are “combining characters” where one user-perceived character can be represented by more than one code point.  And some characters have both pre-composed and decomposed representations.  For example, the Spanish letter ñ can be represented either as the single  code point U+00F1, or as the sequence U+006E U+0303 (n + combining tilde).)

There are three different encoding forms (not counting offbeat ones like UTF-9 and UTF-18) that can be used to represent Unicode characters in a string.

UTF-32 is the most straightforward one: Each code point is represented by a 32-bit integer.  So, for example:

A (U+0041) = 0x00000041

ñ (U+00F1) = 0x000000F1

४ (U+096A) = 0x0000096A

 (U+1F4AA) = 0x0001F4AA

While simple, UTF-32 uses a lot of memory (4 bytes for every character), and is rarely used.

UTF-16 uses 16-bit code units.  Characters U+0000 through U+FFFF (the “Basic Multilingual Plane”) are represented straightforwardly as a single code unit, while characters U+10000 through U+10FFFF are represented as a “surrogate pair”.  Specifically, you subtract 0x10000 from the code point (resulting in a 20-bit number), and use these bits to fill out the binary sequence 110110xxxxxxxxxx 110111xxxxxxxxxx.  For example,

A (U+0041) = 0x0041

ñ (U+00F1) = 0x00F1

४ (U+096A) = 0x096A

 (U+1F4AA) = 0xD83D 0xDCAA

In order for this system to work, the code points U+D800 through U+DFFF are permanently reserved for this UTF-16 surrogate mechanism and will never be assigned to “real” characters.

It's a backwards-compatibility “hack” to allow the full 17-“plane” Unicode code space to be represented on 1990's-era platforms that were designed with the expectation that Unicode characters would always be 16-bits.  This includes Windows NT, Java, and JavaScript.

UTF-8 represents Unicode code points with sequences of 1-4 bytes.  Specifically, each character is represented with the shortest of:

0xxxxxxx

110xxxxx 10xxxxxx

1110xxxx 10xxxxxx 10xxxxxx

11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

So, with the example from earlier:

A (U+0041) = 0x41

ñ (U+00F1) = 0xC3 0xB1

४ (U+096A) = 0xE0 0xA5 0xAA

 (U+1F4AA) = 0xF0 0x9F 0x92 0xAA

This encoding has the property that the number of bytes in the sequence can be determined from the value of the first byte.  Furthermore, leading bytes can be easily distinguished from continuation bytes:

0xxxxxxx = single-byte character (ASCII-compatible)

10xxxxxx = continuation byte of 2-, 3-, or 4-byte character

110xxxxx = lead byte of 2-byte character

1110xxxx = lead byte of 3-byte character

11110xxx = lead byte of 4 byte character

11111xxx = not used


问:
JsonDataSource for table fields get empty Jasper report
I am new to jasper reports.
I am trying to generate a pdf from a son file, which contains some info like name, class etc and an array marks. I am trying to render the marks array as a table. my JSON is

```<code>{"data": {"name" : "Johny",
    "class" : "A2",
    "sub" : "cs",
    "interest" : "films",
    "marks" : [{
               "subject" : "Maths",
               "mark" : "24",
               "grade" : "A",
               "remarks" : "",
               "slNo" : "1"
               },
               {
               "subject" : "English",
               "mark" : "24",
               "grade" : "A",
               "remarks" : "",
               "slNo" : "2"
               },

               ]
}}
</code>```

I have given subdatasource expression as

```<code><dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource()]]></dataSourceExpression>
</code>```

Full jrxml - Here

Now I call these from java like,

```<code>File jsonFile = new File("/Volumes/Johny/Work/EclipseWorkspace/SecondReport/res/Marks.Json");
JasperDesign jasperDesign = JRXmlLoader.load(new File("/Volumes/Johny/Work/EclipseWorkspace/SecondReport/res/First.jrxml"));
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

parameters.put(JsonQueryExecuterFactory.JSON_INPUT_STREAM, new FileInputStream(jsonFile));
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters);
JasperExportManager.exportReportToPdfFile(jasperPrint, "/Users/johnykutty/Desktop/Sample2.pdf");
</code>```

Other fields are getting populated, but table values are getting as null.

答:
Found answer from  here
The issue was I have to pass the key for the array in dataSourceExpression. So, the dataSourceExpression should be like

```<code><dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("marks")]]></dataSourceExpression>
</code>```

Note the "marks" parameter to subDataSource() method

Body:
I am new to jasper reports.
I am trying to generate a pdf from a son file, which contains some info like name, class etc and an array marks. I am trying to render the marks array as a table. my JSON is

{"data": {"name" : "Johny",
    "class" : "A2",
    "sub" : "cs",
    "interest" : "films",
    "marks" : [{
               "subject" : "Maths",
               "mark" : "24",
               "grade" : "A",
               "remarks" : "",
               "slNo" : "1"
               },
               {
               "subject" : "English",
               "mark" : "24",
               "grade" : "A",
               "remarks" : "",
               "slNo" : "2"
               },

               ]
}}

I have given subdatasource expression as

<dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource()]]></dataSourceExpression>

Full jrxml - Here

Now I call these from java like,

File jsonFile = new File("/Volumes/Johny/Work/EclipseWorkspace/SecondReport/res/Marks.Json");
JasperDesign jasperDesign = JRXmlLoader.load(new File("/Volumes/Johny/Work/EclipseWorkspace/SecondReport/res/First.jrxml"));
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

parameters.put(JsonQueryExecuterFactory.JSON_INPUT_STREAM, new FileInputStream(jsonFile));
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters);
JasperExportManager.exportReportToPdfFile(jasperPrint, "/Users/johnykutty/Desktop/Sample2.pdf");

Other fields are getting populated, but table values are getting as null.

Body:
Found answer from  here
The issue was I have to pass the key for the array in dataSourceExpression. So, the dataSourceExpression should be like

<dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("marks")]]></dataSourceExpression>

Note the "marks" parameter to subDataSource() method


问:
Program consuming too much RAM
I am trying to run a simple code that will create a 2D array. At first I declared the array normally, but it got an abnormal termination.

In the task manager the program typically grew to a size of 0.4 MB and was terminated. So, after some research, I discovered the heap and consequently tried to store there. This time it took almost 3 GB and my OS restarted due to low memory.

```<code>int main()
{
    for(int i=0;i<1000;i++)            // outer loop to create 1000 instances
    {
        int** c = new int*[3000];         // creating 2D array of size 3000*3000
        int** b = new int*[3000];

        for(int z=0;z<3000;z++)
        {
            c[z] = new int[3000];
            b[z] = new int[3000];
        }

    }
    return 0;
}
</code>```

So, as far as I can tell, the maximum size of c is [3000][3000] = 36*10^6 B = 36 MB

Now I have 4GB of RAM, so this seems quite unfair.

Anyway I understand that C++ does not have auto garbage collection; that's why the remains are left out. However, I need this array structure for computation. How can I get it to use more of the available memory?

答:
Looks like you've got the wrong idea of how new works (and how to use it). Basically, your code is allocating way more than 3000 x 3000 integers.

That aside, I'd suggest collapsing the 2D array into a 1D array. I'd also suggest using std::vector<int> instead).

If you're set on allocating the memory yourself though you can use:

```<code>int* array = new int[3000 * 3000];
</code>```

And then eventually call delete to free the memory as in:

```<code>delete[] array;
</code>```

Here's an example:

```<code>int main()
{
    int* array = new int[3000 * 3000];
    // assume that array now points to un-initialized memory
    // i.e. don't assume any array element has any particular value
    //    until you set the value of the element.

    for (int i = 0; i < 3000; ++i)
    {
        for (int j = 0; j < 3000; ++j)
        {
             // To store a value...
             int yourvalue = i * 3000 + j; // or whatever value it is you want to store
             array[i * 3000 + j] = yourvalue;

             // Or to read a value...
             yourvalue = array[i * 3000 + j];
        }
    }
    delete [] array;
}
</code>```

Hope this answers your question of how to create and use a 3000 x 3000 sized buffer of memory without consuming too much memory. Of course this assumes your system has at least 3000 * 3000 * sizeof(int) of memory to space. Which, if sizeof(int) == 4 (and it often does), is roughly 36MB.

Title: Program consuming too much RAM

Body:
I am trying to run a simple code that will create a 2D array. At first I declared the array normally, but it got an abnormal termination.

In the task manager the program typically grew to a size of 0.4 MB and was terminated. So, after some research, I discovered the heap and consequently tried to store there. This time it took almost 3 GB and my OS restarted due to low memory.

int main()
{
    for(int i=0;i<1000;i++)            // outer loop to create 1000 instances
    {
        int** c = new int*[3000];         // creating 2D array of size 3000*3000
        int** b = new int*[3000];

        for(int z=0;z<3000;z++)
        {
            c[z] = new int[3000];
            b[z] = new int[3000];
        }

    }
    return 0;
}

So, as far as I can tell, the maximum size of c is [3000][3000] = 36*10^6 B = 36 MB

Now I have 4GB of RAM, so this seems quite unfair.

Anyway I understand that C++ does not have auto garbage collection; that's why the remains are left out. However, I need this array structure for computation. How can I get it to use more of the available memory?

Body:
Looks like you've got the wrong idea of how new works (and how to use it). Basically, your code is allocating way more than 3000 x 3000 integers.

That aside, I'd suggest collapsing the 2D array into a 1D array. I'd also suggest using std::vector<int> instead).

If you're set on allocating the memory yourself though you can use:

int* array = new int[3000 * 3000];

And then eventually call delete to free the memory as in:

delete[] array;

Here's an example:

int main()
{
    int* array = new int[3000 * 3000];
    // assume that array now points to un-initialized memory
    // i.e. don't assume any array element has any particular value
    //    until you set the value of the element.

    for (int i = 0; i < 3000; ++i)
    {
        for (int j = 0; j < 3000; ++j)
        {
             // To store a value...
             int yourvalue = i * 3000 + j; // or whatever value it is you want to store
             array[i * 3000 + j] = yourvalue;

             // Or to read a value...
             yourvalue = array[i * 3000 + j];
        }
    }
    delete [] array;
}

Hope this answers your question of how to create and use a 3000 x 3000 sized buffer of memory without consuming too much memory. Of course this assumes your system has at least 3000 * 3000 * sizeof(int) of memory to space. Which, if sizeof(int) == 4 (and it often does), is roughly 36MB.


问:
How to set qlabel text's opacity in PyQt?
I have a label and I want to set it html\css formatted text from text variable.

```<code>label = QtGui.QLabel()
text = '''<font face="tahoma" color="#45688E">THIS TEXT</font>'''
label.setText(text)
</code>```

I need the word THIS to be colored with my color(#45688E) and word TEXT to be transparent.

The idea is that I want label to show only one word on screen, meanwhile I could programatically get two words.

How to do it?

Thank you.

Update1: photo
Code:

```<code>from PyQt4 import QtGui, QtCore
import sys

app = QtGui.QApplication(sys.argv)

window = QtGui.QWidget()
window.resize(300, 400)
window.setWindowTitle('TITLE1')

window_layout = QtGui.QVBoxLayout()
window.setLayout(window_layout)

label = QtGui.QLabel()
text = '''<font face="tahoma"><span style="color:#45688E">THIS</span><span style="opacity:0"> TEXTANOTHER_WORD</span></font>'''
label.setText(text)

window_layout.addWidget(label)

window.show()
sys.exit(app.exec_())
</code>```

答:
Wrap your first word in a span tag and style with a color. Add all other words in another span tag and set the opacity of the span tag to 0

```<code>'''<font face="tahoma"><span style="color:#45688E">THIS</span><span style="opacity:0">TEXTANOTHER_WORD</span></font>'''
</code>```

Browser Snippet below

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

<p>EDIT: </p>

<p><strong>Solution 2</strong></p>

``` '''THISTEXTANOTHER_WORD'''
```

<p><strong>A somewhat odd solution with PyQT</strong></p>

<p>Somewhat setting the color to transparent hides that text</p>

```style="color:transparent"
```

<p>Example</p>

```text = '''THISTEXT'''
```

Picture below

Body:
I have a label and I want to set it html\css formatted text from text variable.

label = QtGui.QLabel()
text = '''THIS TEXT'''
label.setText(text)

I need the word THIS to be colored with my color(#45688E) and word TEXT to be transparent.

The idea is that I want label to show only one word on screen, meanwhile I could programatically get two words.

How to do it?

Thank you.

Update1: photo
Code:

from PyQt4 import QtGui, QtCore
import sys

app = QtGui.QApplication(sys.argv)

window = QtGui.QWidget()
window.resize(300, 400)
window.setWindowTitle('TITLE1')

window_layout = QtGui.QVBoxLayout()
window.setLayout(window_layout)

label = QtGui.QLabel()
text = '''THIS TEXTANOTHER_WORD'''
label.setText(text)

window_layout.addWidget(label)

window.show()
sys.exit(app.exec_())

Body:
Wrap your first word in a span tag and style with a color. Add all other words in another span tag and set the opacity of the span tag to 0

'''<font face="tahoma"><span style="color:#45688E">THIS</span><span style="opacity:0">TEXTANOTHER_WORD</span></font>'''

Browser Snippet below

<font face="tahoma"><span style="color:#45688E">THIS</span><span style="opacity:0">TEXTANOTHER_WORD</span></font>

EDIT:

Solution 2

 '''<font face="tahoma"><span style="color:#45688E">THIS</span><span style="display:none">TEXTANOTHER_WORD</span></font>'''

A somewhat odd solution with PyQT

Somewhat setting the color to transparent hides that text

style="color:transparent"

Example

text = '''<font face="tahoma" color="red" style="color:green;"><span>THIS</span><span  style="color:transparent">TEXT</span></font>'''

Picture below


问:
JQuery - why does live work but click doesn't?
We have a page with this structure:

```<code><script type="text/javascript" src="/js/lots.of.javascript.js"></script>
<jsp:include page="html.jsp"/>
</code>```

The JavaScript has lots of $(function(){...} blocks.  In one block we tried a $("#mylink").click(...) but this did NOT work.  However the corresponding .live('click' DID work.  Why is this?

Update: More specifically I am assuming the click and live statements ARE running after the link has been added to the DOM as the link is included in the html.jsp file and the statements are executed in $(function(){...} blocks...  So given this I'm not sure why click wouldn't work...

答: Without seeing more code, there's no way to know for sure, but the only way I know of that this happens is if your control (in this case - the item with id="mylink") is created AFTER the page has loaded.</p>

ContentLicense: CC BY-SA 2.5

Body:
We have a page with this structure:

<jsp:include page="html.jsp"/>

The JavaScript has lots of $(function(){...} blocks.  In one block we tried a $("#mylink").click(...) but this did NOT work.  However the corresponding .live('click' DID work.  Why is this?

Update: More specifically I am assuming the click and live statements ARE running after the link has been added to the DOM as the link is included in the html.jsp file and the statements are executed in $(function(){...} blocks...  So given this I'm not sure why click wouldn't work...


问:
Something's wrong with mouseOver() and multiples elements
I am currently working on a some sort of small html game.
Below is my code :

```<code><div id="BS">
        <img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" onmouseover="mouseOver()" src="Pictures/BS1.png"/>
    </div>
    <script type="text/javascript">
            function mouseOver() {
                document.getElementById("BS").innerHTML = '<img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" src="Pictures/BS2.png" onmouseout="mouseOut()"/>';
                }
            function mouseOut() {
                document.getElementById("BS").innerHTML = '<img style="position:absolute; top:375px; left:500px; width:176px; height:286px;" src="Pictures/BS1.png" onmouseover="mouseOver()"/>';
            }
    </script>

  <div id="Radio">
        <img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" onmouseover="mouseOver()" src="Pictures/radio1.png"/>
    </div>
    <script type="text/javascript">
            function mouseOver() {
                document.getElementById("Radio").innerHTML = '<img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" src="Pictures/radio2.png" onmouseout="mouseOut()"/>';
                }
            function mouseOut() {
                document.getElementById("Radio").innerHTML = '<img style="position:absolute; top:478px; left:768px; width:101px; height:71px;" src="Pictures/radio1.png" onmouseover="mouseOver()"/>';
            }
    </script>
</code>```

The issue is, only the last item coded ( here, the Radio ) is working when I'm putting my cursor onto it. So i was wondering, is there a way to fix this ? Cause I did plan to put at least 2 more elements ...
Thanks,
Paul

答:
The way it works

function bigImg(x) {
    x.style.height = "64px";
    x.style.width = "64px";
}

function normalImg(x) {
    x.style.height = "32px";
    x.style.width = "32px";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img onmouseover="bigImg(this)" src="smiley.gif" alt="Smiley"></code>```

Or You can do it another way

Mouse over this text
```

Body:
I am currently working on a some sort of small html game.
Below is my code :

The issue is, only the last item coded ( here, the Radio ) is working when I'm putting my cursor onto it. So i was wondering, is there a way to fix this ? Cause I did plan to put at least 2 more elements ...
Thanks,
Paul

Body:
The way it works

function bigImg(x) {
    x.style.height = "64px";
    x.style.width = "64px";
}

function normalImg(x) {
    x.style.height = "32px";
    x.style.width = "32px";
}

<img onmouseover="bigImg(this)" src="smiley.gif" alt="Smiley">

Or You can do it another way

<h1 onmouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this text</h1>


答: I would guess that the element was added to the DOM after the page was loaded. The .live method insures that elements added after will get the correct event handler.

Title: JQuery - why does live work but click doesn't?


问:
How can change handle drag in dialog widget jquery ui?
I want to change handle drag in this widget but I don't know how can do this

look at the above picture, I won't handle with the first section but I want to change it that element inside it.

答:
I decided to make an example on how to style the default area.  Adding the minimize and etc. is possible but not really recommended.  They're are better extensions for mini-winows than jQuery UI.

  $( function() {
    $( "#dialog" )
      .dialog()
      .parents(".ui-dialog")
      .find(".ui-dialog-titlebar")
      .css("background", "orange");
  } );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="dialog" title="汉语/漢語">
 <p style="text-align:right;font-weight:bold;">some text here</p>
</div></code>```

Body:
I decided to make an example on how to style the default area.  Adding the minimize and etc. is possible but not really recommended.  They're are better extensions for mini-winows than jQuery UI.

  $( function() {
    $( "#dialog" )
      .dialog()
      .parents(".ui-dialog")
      .find(".ui-dialog-titlebar")
      .css("background", "orange");
  } );

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="dialog" title="汉语/漢語">
 <p style="text-align:right;font-weight:bold;">some text here</p>
</div>


问:
Can't vertically center text in a table cell
I'm creating a website for a school project using HTML and CSS. In the header there is a table and I need a text (which is inside a cell) to be aligned on the vertical center and on the horizontal right.

This is the HTML code

```<code><table id="intestazione">
........
    <tr>
        <td class="centerV"><h1>Text</h1></td>
        <td><img src="Logo.jpg"></td>
    </tr>
</table>
</code>```

and this is the CSS code

```<code>h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;
    text-align:right;
}
.centerV
{
    display:table-cell;
    vertical-align:middle;
}
</code>```

but it doesn't work as I want, so I changed the CSS code into

```<code>h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;

    display:table-cell;
    vertical-align:middle;
    text-align:right;
}
</code>```

and the text is vertically centered, but not on the right (it is on the left). I've read that I can use line-height or a padding on the top, but in my opinion it is more clean and elegant to use vertical-align (tell me if I am wrong).

I tried also other code from suggestions on the web but I don't write it otherwise the question will be too long.

答:
You can use align="right" in td by default content is vertically aligned in td.

Text

```

Body:
I'm creating a website for a school project using HTML and CSS. In the header there is a table and I need a text (which is inside a cell) to be aligned on the vertical center and on the horizontal right.

This is the HTML code

........

Text

and this is the CSS code

h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;
    text-align:right;
}
.centerV
{
    display:table-cell;
    vertical-align:middle;
}

but it doesn't work as I want, so I changed the CSS code into

h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;

    display:table-cell;
    vertical-align:middle;
    text-align:right;
}

and the text is vertically centered, but not on the right (it is on the left). I've read that I can use line-height or a padding on the top, but in my opinion it is more clean and elegant to use vertical-align (tell me if I am wrong).

I tried also other code from suggestions on the web but I don't write it otherwise the question will be too long.

Body:
You can use align="right" in td by default content is vertically aligned in td.

<table id="intestazione" width="100%" bgcolor="green">
    <tr>
        <td align="right" valign="middle" ><h1>Text</h1></td>
        <td><img src="Logo.jpg"></td>
    </tr>
</table>


问:
C++ std::plus as template parameter
I wanna write a class for a binary indexed array,

which use two non-type default template parameter, op and identity.

And need to check the constraint that op(identity,identity) == identity.

My problem is,

I don't to how to specify op, my current solution does not compile.
‘class std::function<T(T, T)>’ is not a valid type for a template non-type parameter

how to to check op(identity,identity) == identity, currently I cannot verify, since failed on step 1, maybe static_assert?

So currently I use below workaround, but then I cannot specify op, eg, std::multiplies<int>.
Can anyone tell me how to achieve the goal?

```<code>#include <vector>
#include <functional>

// template <typename T = int, std::function<T(T,T)> op = std::plus<T>(), const T identity = T()>
template <typename T = int, const T identity = T()>     // currently workaround
class BIT { // binary indexed array
    const std::function<T(T,T)> op = std::plus<T>();    // currently workaround
public:
    BIT(std::vector<T> value) : value(value), prefixSum(value.size() + 1, identity) {
        for (size_t i = 1; i < prefixSum.size(); ++i) {
            incrementNodeByValue(i, value[i-1]);
        }
        // print(prefixSum,"prefixSum");
    }
    T getSum(size_t i) {
        auto sum = identity;
        while (i) {
            sum = op(sum, prefixSum(i));
            i = firstSmallerAncestor(i);
        }
        return sum;
    }
    void incrementNodeByValue(size_t i, T x) {
        while (i < prefixSum.size()) {
            prefixSum[i] = op(prefixSum[i], x);
            i = firstLargerAncestor(i);
        }
    }
private:
    inline size_t firstLargerAncestor(size_t node) { return node + (node & -node); }
    inline size_t firstSmallerAncestor(size_t node) { return node & (node - 1); }
    std::vector<T> value;
    std::vector<T> prefixSum;
};

int main() {
    auto vec = std::vector<int> {5,1,15,11,52,28,0};
    auto bit = BIT<>(vec);
}
</code>```

答:
The use of std::function here is a waste and seems to be the source of your confusion.

Note that templates may only be parameterized on typenames and values of integral types (char, int, long, etc). Here you're attempting to parameterize on a value of a std::function instantiation, which isn't an integral type. That said, you don't actually need to parameterize on a value in this case.

Because your constructor doesn't accept an argument to initialize the op member variable nor is it accessible via the interface, I gather it's safe to assume the operator is known at compile-time, is guaranteed immutable, and default constructible.

As such, I declared the op member to be of a parameter type called operation.

```<code>#include <functional>
#include <vector>

template< typename T = int,
          typename operation = std::plus<T>,
          const T identity = T() >
class BIT {
    const operation op = operation();

    static_assert( operation()(identity, identity) == identity );

    std::vector<T> value;
    std::vector<T> prefixSum;

    inline size_t firstLargerAncestor(size_t node) { return node + (node & -node); }
    inline size_t firstSmallerAncestor(size_t node) { return node & (node - 1); }

 public:
    BIT(std::vector<T> value) :
        value(value),
        prefixSum(value.size() + 1, identity) {
        for (size_t i = 1; i < prefixSum.size(); ++i) {
            incrementNodeByValue(i, value[i-1]);
        }
    }

    T getSum(size_t i) {
        auto sum = identity;
        while (i) {
            sum = op(sum, prefixSum(i));
            i = firstSmallerAncestor(i);
        }
        return sum;
    }
    void incrementNodeByValue(size_t i, T x) {
        while (i < prefixSum.size()) {
            prefixSum[i] = op(prefixSum[i], x);
            i = firstLargerAncestor(i);
        }
    }
};
</code>```

live example

As a note, you'll likely want to define an identity template elsewhere to parameterized on an operation and value types to default the third parameter here. As is, it seems you'll almost always be defining all three parameters during instantiation.

Title: C++ std::plus as template parameter

Body:
I wanna write a class for a binary indexed array,

which use two non-type default template parameter, op and identity.

And need to check the constraint that op(identity,identity) == identity.

My problem is,

I don't to how to specify op, my current solution does not compile.
‘class std::function<T(T, T)>’ is not a valid type for a template non-type parameter

how to to check op(identity,identity) == identity, currently I cannot verify, since failed on step 1, maybe static_assert?

So currently I use below workaround, but then I cannot specify op, eg, std::multiplies<int>.
Can anyone tell me how to achieve the goal?

#include <vector>
#include <functional>

// template <typename T = int, std::function<T(T,T)> op = std::plus<T>(), const T identity = T()>
template <typename T = int, const T identity = T()>     // currently workaround
class BIT { // binary indexed array
    const std::function<T(T,T)> op = std::plus<T>();    // currently workaround
public:
    BIT(std::vector<T> value) : value(value), prefixSum(value.size() + 1, identity) {
        for (size_t i = 1; i < prefixSum.size(); ++i) {
            incrementNodeByValue(i, value[i-1]);
        }
        // print(prefixSum,"prefixSum");
    }
    T getSum(size_t i) {
        auto sum = identity;
        while (i) {
            sum = op(sum, prefixSum(i));
            i = firstSmallerAncestor(i);
        }
        return sum;
    }
    void incrementNodeByValue(size_t i, T x) {
        while (i < prefixSum.size()) {
            prefixSum[i] = op(prefixSum[i], x);
            i = firstLargerAncestor(i);
        }
    }
private:
    inline size_t firstLargerAncestor(size_t node) { return node + (node & -node); }
    inline size_t firstSmallerAncestor(size_t node) { return node & (node - 1); }
    std::vector<T> value;
    std::vector<T> prefixSum;
};

int main() {
    auto vec = std::vector<int> {5,1,15,11,52,28,0};
    auto bit = BIT<>(vec);
}

Body:
The use of std::function here is a waste and seems to be the source of your confusion.

Note that templates may only be parameterized on typenames and values of integral types (char, int, long, etc). Here you're attempting to parameterize on a value of a std::function instantiation, which isn't an integral type. That said, you don't actually need to parameterize on a value in this case.

Because your constructor doesn't accept an argument to initialize the op member variable nor is it accessible via the interface, I gather it's safe to assume the operator is known at compile-time, is guaranteed immutable, and default constructible.

As such, I declared the op member to be of a parameter type called operation.

#include <functional>
#include <vector>

template< typename T = int,
          typename operation = std::plus<T>,
          const T identity = T() >
class BIT {
    const operation op = operation();

    static_assert( operation()(identity, identity) == identity );

    std::vector<T> value;
    std::vector<T> prefixSum;

    inline size_t firstLargerAncestor(size_t node) { return node + (node & -node); }
    inline size_t firstSmallerAncestor(size_t node) { return node & (node - 1); }

 public:
    BIT(std::vector<T> value) :
        value(value),
        prefixSum(value.size() + 1, identity) {
        for (size_t i = 1; i < prefixSum.size(); ++i) {
            incrementNodeByValue(i, value[i-1]);
        }
    }

    T getSum(size_t i) {
        auto sum = identity;
        while (i) {
            sum = op(sum, prefixSum(i));
            i = firstSmallerAncestor(i);
        }
        return sum;
    }
    void incrementNodeByValue(size_t i, T x) {
        while (i < prefixSum.size()) {
            prefixSum[i] = op(prefixSum[i], x);
            i = firstLargerAncestor(i);
        }
    }
};

live example

As a note, you'll likely want to define an identity template elsewhere to parameterized on an operation and value types to default the third parameter here. As is, it seems you'll almost always be defining all three parameters during instantiation.


问:
R lme4 Error in '/usr/lib/rstudio/bin/rsession' : malloc(): memory corruption:
Whenever I run lmer or glmer from lme4 package, I get the following error:

Error in '/usr/lib/rstudio/bin/rsession' : malloc(): memory
  corruption:

I update all R packages but still getting the same error.

sessionInfo()

```<code>R version 3.3.2 (2016-10-31)
Platform: i686-pc-linux-gnu (32-bit)
Running under: Ubuntu 16.04.2 LTS

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8
 [4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C
[10] LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] lme4_1.1-13  Matrix_1.2-8

loaded via a namespace (and not attached):
[1] minqa_1.2.4     MASS_7.3-45     tools_3.3.2     Rcpp_0.12.9     splines_3.3.2
[6] nlme_3.1-131    grid_3.3.2      nloptr_1.0.4    lattice_0.20-34
</code>```

Edited

```<code>library(lme4)
fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
</code>```

Throws the following error:

Error in '/usr/lib/rstudio/bin/rsession' : malloc(): memory
  corruption:

答:
In the time the problem has been diagnosed and solved by me (the maintainer of Matrix):

Matrix 1.2-8 had updated its API, but RcppEigen had copied part of Matrix's C API (headers etc)... and now was no longer compatible...  on 32-bit only.

In the mean time, RcppEigen has been updated (and Matrix too).
Please install the latest versions of these two and all such lme4 problems should be gone.

Body:
Whenever I run lmer or glmer from lme4 package, I get the following error:

Error in '/usr/lib/rstudio/bin/rsession' : malloc(): memory
  corruption:

I update all R packages but still getting the same error.

sessionInfo()

R version 3.3.2 (2016-10-31)
Platform: i686-pc-linux-gnu (32-bit)
Running under: Ubuntu 16.04.2 LTS

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8
 [4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C
[10] LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] lme4_1.1-13  Matrix_1.2-8

loaded via a namespace (and not attached):
[1] minqa_1.2.4     MASS_7.3-45     tools_3.3.2     Rcpp_0.12.9     splines_3.3.2
[6] nlme_3.1-131    grid_3.3.2      nloptr_1.0.4    lattice_0.20-34

Edited

library(lme4)
fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)

Throws the following error:

Error in '/usr/lib/rstudio/bin/rsession' : malloc(): memory
  corruption:


问:
Doctrine QueryBuilder sort results by field priority
I have Service entity with title, tags and description fields. When searching service with QueryBuilder how can I get results sorted by field priority. For example, when I search term php I want get services with php in their title at the top of the list, then services with php in their tags and services with search term in their description as last.

This is part of my Querybuilder:

```<code>    $qb = $this->createQueryBuilder('service');
    $qb->leftJoin('service.tags', 'tag');

    $conditions = array($conditions[] = $qb->expr()->eq('service.enabled', true));
    $conditions[] = $qb->expr()->eq('service.category', $categoryId);
    $term = '%' . $term . '%';
    $conditions[] = $qb->expr()->orX(
            $qb->expr()->like('service.title', "'$term'"),
            $qb->expr()->like('service.description',  "'$term'"),
            $qb->expr()->like('tag.name', "'$term'")
        );

    $conditions = call_user_func_array(array($qb->expr(), 'andX'), $conditions);

    $qb->where($conditions);
</code>```

答:
I would not try get the desired results in only one query. It will be too complicated and you'll spent to much time trying get what you want.

First, I assume you'd like to get a sorted Array of Service entities like this:

```<code>/** @var Service[] $results **/
$results = $this->getDoctrine()->getManager()->getRepository('YourBundle:YourServiceRepo')->findSerivesByGivenSerchCriteria($yourConditions);
</code>```

so you can simply iterate (foreach) through it

If it's the case, concider following:

create three separate methods whitin your service-repository to get

services with search-criteria in their title - first priority

services with search-criteria in their tags - second priority

services with serach-criteria in their desc - third priority

and in your findSerivesByGivenSearchCriteria()method you call all three of them and could combine the found results in any order i'd like

for Example:

```<code>public function findSerivesByGivenSerchCriteria( $searchTirm ) {
    $foundServicesByTitle = $this->findServicesBySearchCriteriaInTitle( $searachTirm );
    $foundServicesByTag = $this->findServicesBySearchCriteriaInTags( $searchTirm );
    $foundServicesByDesc = $this->findServicesBySearchCriteriaInDesc( $searchTirm );

    // Hier you can combine found results in any order
    $results = [];
    if( false === empty($foundServicesByTitle ) )
    {
    // for example with array_merge ...
    // NOTE: If you choose array_merge() you have to make sure your $foundServicesByTitle, $foundServicesByTag, $foundServicesByDesc have unique array-indexes
    //       And you get Results like
    //       array( 'unique_id_1' => ServiceEntity, 'unique_id_2' => ServiceEntity ... )
     $results = array_merge($results, $foundServicesByTitle);
    }
    // .. do the same with other two
    return $results;
}
</code>```

To get the "uniqness" try to combine Doctrine's INDEX BY and HIDDEN

INDEX BY -> http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#using-index-by

INDEX BY in QueryBuilder -> https://stackoverflow.com/a/15120793/348193

HIDDEN -> https://michelsalib.com/2012/03/04/doctrine2-ninja-with-the-hidden-keyword/

Why I wouldn't choose the UNION way?

Since you work with symfony and doctrine UNION isn't the best way. See How to write UNION in Doctrine 2.0

As you can see, UNION isn't supported by Doctrine and you have to use NativeQuery (which could be frustrating with ResultSetMappingBuilder and corect mapping and turning raw-results in to desired entities)

Body:
I have Service entity with title, tags and description fields. When searching service with QueryBuilder how can I get results sorted by field priority. For example, when I search term php I want get services with php in their title at the top of the list, then services with php in their tags and services with search term in their description as last.

This is part of my Querybuilder:

    $qb = $this->createQueryBuilder('service');
    $qb->leftJoin('service.tags', 'tag');

    $conditions = array($conditions[] = $qb->expr()->eq('service.enabled', true));
    $conditions[] = $qb->expr()->eq('service.category', $categoryId);
    $term = '%' . $term . '%';
    $conditions[] = $qb->expr()->orX(
            $qb->expr()->like('service.title', "'$term'"),
            $qb->expr()->like('service.description',  "'$term'"),
            $qb->expr()->like('tag.name', "'$term'")
        );

    $conditions = call_user_func_array(array($qb->expr(), 'andX'), $conditions);

    $qb->where($conditions);

Body:
I would not try get the desired results in only one query. It will be too complicated and you'll spent to much time trying get what you want.

First, I assume you'd like to get a sorted Array of Service entities like this:

/** @var Service[] $results **/
$results = $this->getDoctrine()->getManager()->getRepository('YourBundle:YourServiceRepo')->findSerivesByGivenSerchCriteria($yourConditions);

so you can simply iterate (foreach) through it

If it's the case, concider following:

create three separate methods whitin your service-repository to get

services with search-criteria in their title - first priority

services with search-criteria in their tags - second priority

services with serach-criteria in their desc - third priority

and in your findSerivesByGivenSearchCriteria()method you call all three of them and could combine the found results in any order i'd like

for Example:

public function findSerivesByGivenSerchCriteria( $searchTirm ) {
    $foundServicesByTitle = $this->findServicesBySearchCriteriaInTitle( $searachTirm );
    $foundServicesByTag = $this->findServicesBySearchCriteriaInTags( $searchTirm );
    $foundServicesByDesc = $this->findServicesBySearchCriteriaInDesc( $searchTirm );

    // Hier you can combine found results in any order
    $results = [];
    if( false === empty($foundServicesByTitle ) )
    {
    // for example with array_merge ...
    // NOTE: If you choose array_merge() you have to make sure your $foundServicesByTitle, $foundServicesByTag, $foundServicesByDesc have unique array-indexes
    //       And you get Results like
    //       array( 'unique_id_1' => ServiceEntity, 'unique_id_2' => ServiceEntity ... )
     $results = array_merge($results, $foundServicesByTitle);
    }
    // .. do the same with other two
    return $results;
}

To get the "uniqness" try to combine Doctrine's INDEX BY and HIDDEN

INDEX BY -> http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#using-index-by

INDEX BY in QueryBuilder -> https://stackoverflow.com/a/15120793/348193

HIDDEN -> https://michelsalib.com/2012/03/04/doctrine2-ninja-with-the-hidden-keyword/

Why I wouldn't choose the UNION way?

Since you work with symfony and doctrine UNION isn't the best way. See How to write UNION in Doctrine 2.0

As you can see, UNION isn't supported by Doctrine and you have to use NativeQuery (which could be frustrating with ResultSetMappingBuilder and corect mapping and turning raw-results in to desired entities)


问:
Graceful handing over resources from initramfs to userspace
There are hardware devices which need userspace suppport, like daemon running and handling parts of interaction not suitable (too complex or policy-related) for kernel space.

Running such daemons is easy once you reach userspace -- you can run'em as a result of hotplug event and don't worry much.

Once initramfs comes to the picture, everything suddenly breaks apart: if the daemon is run from initramfs then it needs to either keep running when execution is switched to regular rootfs, which is particularily hard, given initramfs is freed during switch_root or hand out resources and state to another copy of itself, run from rootfs. Both solutions seem inelegant and hacky.

Is there obvious way to manage such devices and their supporting daemons I overlooked?

答:
Do you need this daemon to mount your real root device ? I guess the answer is yes, otherwise the solution would be to wait for your real root.

I your device is so complicated it needs a daemon to just work, may be you could do part of the job in the kernel, and handle the policy through sysfs attribute ?
I fail to see an example of hardware invlved in mounting the real root deice that would need a daemon to work. Device discovery apply, but you don't need a daemon for the device to actually work. An example would be welcome.

Also, do you really need to switch root ? You could keep your initramfs, and mount whatever you need to have a fully functionnal system under /usr/ That is what I do with some of my embedded system.

Update :
mdev is an embedded alternative to udev, which runsin two mode: on scans sysfs to add device, the other is running for hotplug event. So I guess you don't need to "store" hotplug event, because all the info is still available in sysfs. So the solution is something like :

run udev from initramfs

mount real root and switch root

scan sysfs (does udev do that on startup ?)

normal operation (ie wait for hotplug event)


问:
Pure javascript slider bar limit
Im working with 3 slider bars with max=100 min=0, the first one its the principal, the other two bars value can't be higher or equal than the first one, and the third one value can't be higher or equal than the second one.
I dont know if it's there an operator or function to do that, to limit the value between a min max range.

<!DOCTYPE html>

 <title></title>

Foundations
<input type="range" name="s1" min="0" max="100"  id="bar1" value="0" oninput="mover1();">

Walls
<input type="range" name="s2" min="0" max="100"  id="bar2" value="0" style="margin-left: 1.9em;" >

Roof
<input type="range" name="s3" min="0" max="100" id="bar3" value="0" style="margin-left: 2.7em;" >

```

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

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

    <div>
    Foundations
    <input type="range" name="s1" min="0" max="100"  id="bar1" value="0" oninput="mover1();" onchange="changeOne();">

    </div>
    <div>
    Walls
    <input type="range" name="s2" min="0" max="100"  id="bar2" value="0" style="margin-left: 1.9em;" onchange="changeTwo();">

    </div>
    <div>
    Roof
    <input type="range" name="s3" min="0" max="100" id="bar3" value="0" style="margin-left: 2.7em;" >
    </div>

       <script>
        var bar1 = document.getElementById("bar1");
        var bar2 = document.getElementById("bar2");
        var bar3 = document.getElementById("bar3");
            function changeOne()
            {

                bar2.setAttribute("max", bar1.value);
                bar3.setAttribute("max", bar2.value);
            }

             function changeTwo()
            {

                bar3.setAttribute("max", bar2.value);
            }

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

Title: Pure javascript slider bar limit

Body:
You can do something like this:

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

    <div>
    Foundations
    <input type="range" name="s1" min="0" max="100"  id="bar1" value="0" oninput="mover1();" onchange="changeOne();">

    </div>
    <div>
    Walls
    <input type="range" name="s2" min="0" max="100"  id="bar2" value="0" style="margin-left: 1.9em;" onchange="changeTwo();">

    </div>
    <div>
    Roof
    <input type="range" name="s3" min="0" max="100" id="bar3" value="0" style="margin-left: 2.7em;" >
    </div>

       <script>
        var bar1 = document.getElementById("bar1");
        var bar2 = document.getElementById("bar2");
        var bar3 = document.getElementById("bar3");
            function changeOne()
            {

                bar2.setAttribute("max", bar1.value);
                bar3.setAttribute("max", bar2.value);
            }

             function changeTwo()
            {

                bar3.setAttribute("max", bar2.value);
            }

            </script>
    </body>
    </html>


问:
Closing a running program from a process
How can I close a program from a child process?
For exanple:

```<code>import easygui
import multiprocessing

def func():
    reply=easygui.buttonbox("start?",image="F:\project\phonber.png",choices=['yes','no'])
    if reply=="yes":
        exit_option()

if __name__=='__main__':
    p=multiprocessing.Process(target=func,args=())
    t=p.start()
    while True:
        None
</code>```

Is there a way to execute the exit_option() ?

答:
Your forgot to actually call the function:

```<code>import easygui
import multiprocessing

def func():
    reply=easygui.buttonbox("start?",image="F:\project\phonber.png",choices=['yes','no'])
    if reply=="yes":
        exit_option()

func()

if __name__=='__main__':
    p=multiprocessing.Process(target=func,args=())
    t=p.start()
    while True:
        None
</code>```

Then, to actually kill a running process there are, of course, many options. The most obvious ones being psutil its kill or terminate method, or os its kill method. Both as shown here.

Body:
How can I close a program from a child process?
For exanple:

import easygui
import multiprocessing

def func():
    reply=easygui.buttonbox("start?",image="F:\project\phonber.png",choices=['yes','no'])
    if reply=="yes":
        exit_option()

if __name__=='__main__':
    p=multiprocessing.Process(target=func,args=())
    t=p.start()
    while True:
        None

Is there a way to execute the exit_option() ?

Body:
Your forgot to actually call the function:

import easygui
import multiprocessing

def func():
    reply=easygui.buttonbox("start?",image="F:\project\phonber.png",choices=['yes','no'])
    if reply=="yes":
        exit_option()

func()

if __name__=='__main__':
    p=multiprocessing.Process(target=func,args=())
    t=p.start()
    while True:
        None

Then, to actually kill a running process there are, of course, many options. The most obvious ones being psutil its kill or terminate method, or os its kill method. Both as shown here.


问:
How the $scope.$watch works
I wrote an application to understand the Angular $scope.$watch(). But while doing so faced an issue I couldn't understand.

With the following code, I am expecting that when the value in the input box is changing the statement "Data is changing!!" will be logged to the console.

```<code>   <!DOCTYPE html>
     <html lang='en' ng-app="app">
       <head>
         <meta charset="utf-8">
         <title>My $Scope.$watch demo</title>
       </head>
       <body>
         <div ng-controller="MainController">
           <input ng-model='myData.val'>
           <h1>{{myData.val}}</h1>
         </div>
         <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
         <script type="text/javascript">
           angular.module('app', [])
           .controller('MainController', ['$scope', function($scope){
             $scope.myData = {};
             console.log($scope.myData);
             $scope.myData = { val:"Bablo"};
             console.log($scope.myData.val);
             $scope.$watch('$scope.myData.val', function(){
               console.log("Data is changing!!");
             });
           }]);
         </script>
       </body>
     </html>
</code>```

But I didn't observe what I was expecting, but when I changed the $scope.$watch() parameter to myData.val (earlier it was $scope.myData.val), it started working fine. Why so?

What's the issue here if I pass the whole $scope.myData.val instead of just mydata.val?

答:
When you say $scope.$watch(.. then it means angular is watching for properties inside $scope, and since view is bind with ng-controller so it is not required in view to append $scope before property.

If you append $scope to your property the angular looks for new property $scope.$scope, which of course doesn't exist., and as soon as your create this (for example by appending $scope in view, then property created and it start watching it. See this fiddle and try to connect.

Title: How the $scope.$watch works

Body:
I wrote an application to understand the Angular $scope.$watch(). But while doing so faced an issue I couldn't understand.

With the following code, I am expecting that when the value in the input box is changing the statement "Data is changing!!" will be logged to the console.

   <!DOCTYPE html>

         <meta charset="utf-8">
         <title>My $Scope.$watch demo</title>

           <input ng-model='myData.val'>

{{myData.val}}

But I didn't observe what I was expecting, but when I changed the $scope.$watch() parameter to myData.val (earlier it was $scope.myData.val), it started working fine. Why so?

What's the issue here if I pass the whole $scope.myData.val instead of just mydata.val?


答:
You can do that by setting the max property of a slider to the value property of the previous slider. If you do this for all (except the first) sliders at any change of any of them, you'll have the desired effect:

var sliders = Array.from(document.querySelectorAll('input[type=range]'));
sliders.forEach( slider => slider.addEventListener('change', updateSliders));

function updateSliders() {
    sliders.reduce( (prev, curr) => {
        curr.max = prev.value - 1;
        return curr;
    });
}

// Optionally show the value next to the slider:
var values = Array.from(document.querySelectorAll('.value'));
sliders.forEach( slider => slider.addEventListener('change', displayValue));

function displayValue() {
    sliders.forEach( (curr, i) => values[i].textContent = curr.value );
}
displayValue();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table><tr>
    <td>Foundations</td>
    <td><input type="range" name="s1" min="0" max="100" id="bar1" value="0"></td>
    <td class="value"></td>
</tr><tr>
    <td>Walls</td>
    <td><input type="range" name="s2" min="0" max="100" id="bar2" value="0"></td>
    <td class="value"></td>
</tr><tr>
    <td>Roof</td>
    <td><input type="range" name="s3" min="0" max="100" id="bar3" value="0"></td>
    <td class="value"></td>
</tr></table></code>```

Title: Pure javascript slider bar limit

Body:
Im working with 3 slider bars with max=100 min=0, the first one its the principal, the other two bars value can't be higher or equal than the first one, and the third one value can't be higher or equal than the second one.
I dont know if it's there an operator or function to do that, to limit the value between a min max range.

<!DOCTYPE html>

 <title></title>

Foundations
<input type="range" name="s1" min="0" max="100"  id="bar1" value="0" oninput="mover1();">

Walls
<input type="range" name="s2" min="0" max="100"  id="bar2" value="0" style="margin-left: 1.9em;" >

Roof
<input type="range" name="s3" min="0" max="100" id="bar3" value="0" style="margin-left: 2.7em;" >

Body:
You can do that by setting the max property of a slider to the value property of the previous slider. If you do this for all (except the first) sliders at any change of any of them, you'll have the desired effect:

var sliders = Array.from(document.querySelectorAll('input[type=range]'));
sliders.forEach( slider => slider.addEventListener('change', updateSliders));

function updateSliders() {
    sliders.reduce( (prev, curr) => {
        curr.max = prev.value - 1;
        return curr;
    });
}

// Optionally show the value next to the slider:
var values = Array.from(document.querySelectorAll('.value'));
sliders.forEach( slider => slider.addEventListener('change', displayValue));

function displayValue() {
    sliders.forEach( (curr, i) => values[i].textContent = curr.value );
}
displayValue();

<table><tr>
    <td>Foundations</td>
    <td><input type="range" name="s1" min="0" max="100" id="bar1" value="0"></td>
    <td class="value"></td>
</tr><tr>
    <td>Walls</td>
    <td><input type="range" name="s2" min="0" max="100" id="bar2" value="0"></td>
    <td class="value"></td>
</tr><tr>
    <td>Roof</td>
    <td><input type="range" name="s3" min="0" max="100" id="bar3" value="0"></td>
    <td class="value"></td>
</tr></table>


问:
Display orders placed before April 1, 2009. Write the query in two different ways
I did it the usual way. I don't get how to write the query in another way.

```<code>SELECT Order#, Shipdate
FROM Orders
WHERE Shipdate < '01-APR-2009';
</code>```

What can be the another way to write the same query?

答:
Assuming shipdate is date not string,

```<code>SELECT Order#, Shipdate FROM Orders
 WHERE Shipdate < to_date('01-APR-2009','DD-MON-YYYY');
</code>```

Body:
I did it the usual way. I don't get how to write the query in another way.

SELECT Order#, Shipdate
FROM Orders
WHERE Shipdate < '01-APR-2009';

What can be the another way to write the same query?

Body:
Assuming shipdate is date not string,

SELECT Order#, Shipdate FROM Orders
 WHERE Shipdate < to_date('01-APR-2009','DD-MON-YYYY');


问:
Unable to Commit Git Changes. Error Message: fatal: cannot lock ref 'HEAD': unable to resolve reference 'refs/heads/master': reference broken
I am getting the above error when tryping to commit changes in my repo.
git gc returns the following:

```<code>error: bad ref for .git/logs/HEAD
error: bad ref for .git/logs/refs/heads/master
error: bad ref for .git/logs/HEAD
error: bad ref for .git/logs/refs/heads/master
error: inflate: data stream error (unknown compression method)
fatal: loose object 3ee0ce38a1503fa8a00412a81ea64965c85d8943 (stored in .git/objects/3e/e0ce38a1503fa8a00412a81ea64965c85d8943) is corrupt
error: failed to run repack
</code>```

I don't really know how to resolve this sort of thing and other answers I have found to similar questions haven't done the trick.

答: OK, so the only quick way I could find to fix this was to clone the repo into a different location and then re-make any changes from the other location of the repo. Not really a fix but a work around and took 10 minutes all-in-all.</p>

Body:
I am getting the above error when tryping to commit changes in my repo.
git gc returns the following:

error: bad ref for .git/logs/HEAD
error: bad ref for .git/logs/refs/heads/master
error: bad ref for .git/logs/HEAD
error: bad ref for .git/logs/refs/heads/master
error: inflate: data stream error (unknown compression method)
fatal: loose object 3ee0ce38a1503fa8a00412a81ea64965c85d8943 (stored in .git/objects/3e/e0ce38a1503fa8a00412a81ea64965c85d8943) is corrupt
error: failed to run repack

I don't really know how to resolve this sort of thing and other answers I have found to similar questions haven't done the trick.


问:
Compiler error C3493: 'func' cannot be implicitly captured because no default capture mode has been specified
Can you help me resolve this compiler error?

```<code>template<class T>
static void ComputeGenericDropCount(function<void(Npc *, int)> func)
{
    T::ForEach([](T *what) {
        Npc *npc = Npc::Find(what->sourceId);

        if(npc)
            func(npc, what->itemCount); // <<<<<<< ERROR HERE
            // Error    1   error C3493: 'func' cannot be implicitly captured because no default capture mode has been specified

    });
}

static void PreComputeNStar()
{
     // ...
    ComputeGenericDropCount<DropSkinningNpcCount>([](Npc *npc, int i) { npc->nSkinned += i; });
    ComputeGenericDropCount<DropHerbGatheringNpcCount>([](Npc *npc, int i) { npc->nGathered += i; });
    ComputeGenericDropCount<DropMiningNpcCount>([](Npc *npc, int i) { npc->nMined += i; });
}
</code>```

I can't understand why it's giving me the error and I don't know how to fix it. ComputeGenericDropCount(auto func) doesn't work either.

答:
You need to specify how to capture func into the lambda.

[] don't capture anything

[&] capture-by-reference

[=] capture-by-value (copy)

```<code>T::ForEach([&](T *what) {
</code>```

I'd also recommend that you should send func by const reference.

```<code>static void ComputeGenericDropCount(const function<void(Npc *, int)>& func)
</code>```

Body:
Can you help me resolve this compiler error?

template<class T>
static void ComputeGenericDropCount(function<void(Npc *, int)> func)
{
    T::ForEach([](T *what) {
        Npc *npc = Npc::Find(what->sourceId);

        if(npc)
            func(npc, what->itemCount); // <<<<<<< ERROR HERE
            // Error    1   error C3493: 'func' cannot be implicitly captured because no default capture mode has been specified

    });
}

static void PreComputeNStar()
{
     // ...
    ComputeGenericDropCount<DropSkinningNpcCount>([](Npc *npc, int i) { npc->nSkinned += i; });
    ComputeGenericDropCount<DropHerbGatheringNpcCount>([](Npc *npc, int i) { npc->nGathered += i; });
    ComputeGenericDropCount<DropMiningNpcCount>([](Npc *npc, int i) { npc->nMined += i; });
}

I can't understand why it's giving me the error and I don't know how to fix it. ComputeGenericDropCount(auto func) doesn't work either.

Body:
You need to specify how to capture func into the lambda.

[] don't capture anything

[&] capture-by-reference

[=] capture-by-value (copy)

T::ForEach([&](T *what) {

I'd also recommend that you should send func by const reference.

static void ComputeGenericDropCount(const function<void(Npc *, int)>& func)


问:
How do I find the Pareto-optimal points in O(nh) and O(nlog(h)) complexity?
Can anybody suggest an algorithm to find Pareto-optimal points (to form a staircase) just as given in diagram in O(n*h) and O(n*log(h)) time complexity, where h is the number of Pareto-optimal points?

I used gift wrapping algorithm to solve this (in O(n*h)), but it only finds convex hulls type of staircase and misses those points who form concave angles.

答:
To put suggestion in one place.

Idea is to use divide and conquer strategy. If we can find pareto point P which splits rest of pareto points in half's in O(n) than it can be done in O(n log(h)). That can be checked by splitting points in three parts right of P, left and up of P, left and down of P. Third set doesn't have pareto points. And recursively do same procedure on other two set of points. Set that three parts split points in ratio: a, b, 1 - a - b. With that complexity is:

```<code>T(n, h) = T(a*n, h/2) + T(b*n, h/2) + O(n)
       <= T(n, h/2) + O(n)
       <= T(n, h/4) + 2 * O(n)
       <= T(n, h/8) + 3 * O(n)
       <= ...
       <= O(n log(h))
</code>```

Problem is finding pareto point with that characteristic in <= O(n). Some simple heuristic like P where x >= (min(x) + max(x)) / 2, probably makes very good average.

I am not sure, but I think it is possible to use k-th order statistic to find point with that characteristic. Similar to finding median as pivot in quicksort.

Body:
To put suggestion in one place.

Idea is to use divide and conquer strategy. If we can find pareto point P which splits rest of pareto points in half's in O(n) than it can be done in O(n log(h)). That can be checked by splitting points in three parts right of P, left and up of P, left and down of P. Third set doesn't have pareto points. And recursively do same procedure on other two set of points. Set that three parts split points in ratio: a, b, 1 - a - b. With that complexity is:

T(n, h) = T(a*n, h/2) + T(b*n, h/2) + O(n)
       <= T(n, h/2) + O(n)
       <= T(n, h/4) + 2 * O(n)
       <= T(n, h/8) + 3 * O(n)
       <= ...
       <= O(n log(h))

Problem is finding pareto point with that characteristic in <= O(n). Some simple heuristic like P where x >= (min(x) + max(x)) / 2, probably makes very good average.

I am not sure, but I think it is possible to use k-th order statistic to find point with that characteristic. Similar to finding median as pivot in quicksort.


问:
Unzip vs explicit loop
what's the difference between the two ways to unzip two zipped lists?

```<code>assert isinstance(X, list)
assert isinstance(X[0], tuple)
assert isinstance(X[0][0], list)
assert isinstance(X[0][0][0], dict)

X_model = []
X_synth = []
for row in X:
    X_model.append(row[0])
    X_synth.append(row[1])
</code>```

X_model is now a list of list of dict

```<code>X_model, X_synth, = zip(*X)
</code>```

X_model is a tuple of list of dicts
shouldn't the results be the same?

答:
Let's use an example. For simplicity sake, instead of using a list of dicts let's use numbers. Notice the first element of every tuple is odd and the second element of every tuple is even.

```<code>>>> X = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
>>> X_model = []
>>> X_synth = []
>>> for row in X:
...     X_model.append(row[0])
...     X_synth.append(row[1])
...
>>> X_model
[1, 3, 5, 7, 9]
>>> X_synth
[2, 4, 6, 8, 10]
>>> X_model, X_synth = zip(*X)
>>> X_model
(1, 3, 5, 7, 9)
>>> X_synth
(2, 4, 6, 8, 10)
</code>```

Let's consider zip(*X). zip(*X) is equivalent to

```<code>zip((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
</code>```

From the Python Docs

zip:
  This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

Hence zip will return a list of tuples where the 0th tuple contains the 0th element from each argument (all odd numbers) and the 1st tuple contains all the 1st element from each argument (all even numbers)

```<code>X_model, X_synth = [(1, 3, 5, 7, 9), (2, 4, 6, 8, 10)]
</code>```

Title: Unzip vs explicit loop

Body:
what's the difference between the two ways to unzip two zipped lists?

assert isinstance(X, list)
assert isinstance(X[0], tuple)
assert isinstance(X[0][0], list)
assert isinstance(X[0][0][0], dict)

X_model = []
X_synth = []
for row in X:
    X_model.append(row[0])
    X_synth.append(row[1])

X_model is now a list of list of dict

X_model, X_synth, = zip(*X)

X_model is a tuple of list of dicts
shouldn't the results be the same?

Body:
Let's use an example. For simplicity sake, instead of using a list of dicts let's use numbers. Notice the first element of every tuple is odd and the second element of every tuple is even.

>>> X = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
>>> X_model = []
>>> X_synth = []
>>> for row in X:
...     X_model.append(row[0])
...     X_synth.append(row[1])
...
>>> X_model
[1, 3, 5, 7, 9]
>>> X_synth
[2, 4, 6, 8, 10]
>>> X_model, X_synth = zip(*X)
>>> X_model
(1, 3, 5, 7, 9)
>>> X_synth
(2, 4, 6, 8, 10)

Let's consider zip(*X). zip(*X) is equivalent to

zip((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))

From the Python Docs

zip:
  This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

Hence zip will return a list of tuples where the 0th tuple contains the 0th element from each argument (all odd numbers) and the 1st tuple contains all the 1st element from each argument (all even numbers)

X_model, X_synth = [(1, 3, 5, 7, 9), (2, 4, 6, 8, 10)]


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
The beginnings of structured programming in BASIC with...</p>

```<code>GOSUB 1000
</code>```

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

Body:
The beginnings of structured programming in BASIC with...

GOSUB 1000

OwnerDisplayName: edg

LastEditorDisplayName: edg


问:
JAX-WS client for IIS Integrated Windows authentication (NTLM)
Recently, I am working on a project that requires to build a web service client in Java running on JAX-WS engine to talk to a .NET web service secured by Integrated Windows authentication (also known as NTLM protocol)

I searched on the Internet. It seems a well-known issue, but no one has good solution yet.

Anyone has done this before?

Any suggestion will be appreciated.

答:
We are using the JAX-WS that is built in to java 6, and running the client on Windows XP and Windows 2003 Server.  The server is IIS 7 on Windows 2003 Server.

I found to my surpise that integrated authentication works out of the box.  No configuration supplied.  I turned on trace logging at the HTTP layer, and found that NTLM authentication was being used.  Not sure if it would work if only Negotiate authentication was being used and NTLM was turned off.

So basically, the answer is: it just works.

To test:

```<code>package url.auth;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;

public class DownloadUrl {
    public static void main(String[] args) {

        try {
            URL url = new URL("http://myserver/url/that/requires/authentication");
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            Map<String, List<String>> headers = conn.getHeaderFields();
            for(String header : headers.keySet()) {
                System.out.println(header + ": " + headers.get(header));
            }
            System.out.println("");
            System.out.println(IOUtils.toString(is));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
We are using the JAX-WS that is built in to java 6, and running the client on Windows XP and Windows 2003 Server.  The server is IIS 7 on Windows 2003 Server.

I found to my surpise that integrated authentication works out of the box.  No configuration supplied.  I turned on trace logging at the HTTP layer, and found that NTLM authentication was being used.  Not sure if it would work if only Negotiate authentication was being used and NTLM was turned off.

So basically, the answer is: it just works.

To test:

package url.auth;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;

public class DownloadUrl {
    public static void main(String[] args) {

        try {
            URL url = new URL("http://myserver/url/that/requires/authentication");
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            Map<String, List<String>> headers = conn.getHeaderFields();
            for(String header : headers.keySet()) {
                System.out.println(header + ": " + headers.get(header));
            }
            System.out.println("");
            System.out.println(IOUtils.toString(is));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


问:
slf4j-log4j bridge with log4j 2.8.1
I am working on removing any dependencies on log4j 1.x versions as they have EOL'd. My code uses slf4j-log4j12 bridge. In maven central compile dependencies for slf4j-log4j shows log4j at version 1.2.17 with updates column showing 2.8.1.

So I tried following in build.gradle with the hope that log4j-api-2.8.1 would be used in place of log4j-1.2.17 which is pulled by default. But that doesn't seem to be working. I still see log4j-1.2.17 in the dependent jars.

So I wanted to ask, is this something that is not allowed at all? I.e. there is no slf4j-log4j bridge to log4j 2.8.1 version or for that matter 2.x version? Essentially I should migrate my code to use log4j-api-2.8.1. Or am I missing something here?

```<code>dependencies {
    compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.8.1'
    compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.7.25'
}
</code>```

答:
slf4j-log4j12 is a binding for log4j version 1.2. But you need log4j version 2 (log4j2) binding, which is named log4j-slf4j-impl.

To use slf4j along with log4j2, you will require:

log4j-api (2.8.1)

log4j-core (2.8.1)

log4j-slf4j-impl (2.8.1)

slf4j-api (1.7.25)

If you have any implementation and/or dependency over log4j version 1.2, you will also require:

log4j-1.2-api (2.8.1)

However, you should not include following dependencies in any case:

log4j-to-slf4j (2.x)

log4j (1.2.x)

Title: slf4j-log4j bridge with log4j 2.8.1

Body:
I am working on removing any dependencies on log4j 1.x versions as they have EOL'd. My code uses slf4j-log4j12 bridge. In maven central compile dependencies for slf4j-log4j shows log4j at version 1.2.17 with updates column showing 2.8.1.

So I tried following in build.gradle with the hope that log4j-api-2.8.1 would be used in place of log4j-1.2.17 which is pulled by default. But that doesn't seem to be working. I still see log4j-1.2.17 in the dependent jars.

So I wanted to ask, is this something that is not allowed at all? I.e. there is no slf4j-log4j bridge to log4j 2.8.1 version or for that matter 2.x version? Essentially I should migrate my code to use log4j-api-2.8.1. Or am I missing something here?

dependencies {
    compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.8.1'
    compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.7.25'
}

ContentLicense: CC BY-SA 4.0