Why does an SVG with  lose gradients when converting to a ?

Question: I have a logo for the RXJS library which I want to display on my website.  When displayed as an <svg> element it works as expected.

.logo {
  width: 96px;
  height: 96px;
  display: inline-block;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 283.5 283.5" class="logo">
  <defs>
    <linearGradient id="rxjs-linear-gradient" x1="53.5" y1="36.29" x2="177.94" y2="168.67" gradientTransform="translate(0 284) scale(1 -1)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#e01d84" />
      <stop offset=".4" stop-color="#df1d85" />
      <stop offset=".77" stop-color="#932c87" />
      <stop offset="1" stop-color="#5d2f88" />
    </linearGradient>
    <radialGradient id="rxjs-radial-gradient" cx="190.17" cy="226.58" fx="190.17" fy="226.58" r="121.58" gradientTransform="translate(-.17 269.21) rotate(.14) scale(1 -.84)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#e01d84" />
      <stop offset=".14" stop-color="#de1e85" />
      <stop offset=".28" stop-color="#d62085" />
      <stop offset=".43" stop-color="#c92386" />
      <stop offset=".59" stop-color="#b72786" />
      <stop offset=".74" stop-color="#9d2b87" />
      <stop offset=".89" stop-color="#7c2e88" />
      <stop offset="1" stop-color="#5d2f88" />
    </radialGradient>
    <linearGradient id="rxjs-linear-gradient-2" x1="83.21" y1="221.66" x2="137.32" y2="221.66" gradientTransform="translate(0 284) scale(1 -1)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#e01d84" />
      <stop offset=".24" stop-color="#da1e85" />
      <stop offset=".66" stop-color="#c72085" />
      <stop offset="1" stop-color="#b52284" />
    </linearGradient>
  </defs>
  <path fill="#e32286" d="m29.6,175.3c-5.2-16.2-6.7-33.3-3.7-50.9,1.3-7.3,3.3-14.3,5.5-21.4,0,0,13.8-45.3,60.5-66,0,0,16.1-8.5,40.3-9.1,0,0-3.3-3.2-5.4-4.6-11.4-7.6-28.4-10.1-38.7.6-3.1,3.2-5.7,6.7-8.6,9.9-3.3,3.6-7.3,6.6-11.9,8.3-4,1.5-8,1.2-12.1,1.9-4.2.7-8.5,2.2-11.9,4.9-3.7,3-5.2,7-5.6,11.6-.4,3.6-.3,7.3-.5,10.9-.5,10.6-3.9,13.6-11.5,19.5-3.2,2.4-5.9,5.6-7.9,9-6,10.6,3.6,21.6,4.1,32.3.1,2.2-.1,4.4-.9,6.5-.8,2.3-2.4,3.8-3.7,5.7-1.8,2.5-3,5.5-2.5,8.6s2.1,6,3.6,8.7c2.9,4.8,6.5,9.1,10.3,13.2.2,0,.184.108.40.206"/>
  <path fill="url(#rxjs-linear-gradient)" d="m220.4,213.7c23-10,32.8-27.3,32.8-27.3,21.5-29.3,14.2-60.2,14.2-60.2-13.7,29.8-26.2,38-26.2,38,33.7-51.3.2-82.3.2-82.3,13.7,29.2-4.5,64.8-4.5,64.8-15.3,32.2-37,43.7-37,43.7,24.2,4.5,42-11.8,42-11.8-34.7,37.5-72.3,35.7-72.3,35.7,15.8,17.7,39.5,16.2,39.5,16.2-31,7.3-60.1-3-84-22.9-4.5-3.7-8.8-7.7-12.8-12,0,0-3.6-3.8-4.3-4.8l-.1-.1c-.5,18.5,18.8,35.7,18.8,35.7-24.2-10-35.3-31.7-35.3-31.7,0,0-16.3-27.8-4.5-59.5s47.5-38.5,47.5-38.5c29.5,14.3,54.5,18.8,54.5,18.8,52.7,8.8,49.7-17,49.7-17,.5-22.2-33-45.8-33-45.8-59.7-44.3-113.7-15.7-113.7-15.7C45.2,57.7,31.4,103,31.4,103c-2.2,7.1-4.2,14.1-5.5,21.4-5.1,29.7,2.6,57.8,19.3,82.8,26,38.8,68.2,52.2,68.2,52.2,62.5,21.2,105.2-10,105.2-10,39.3-27,47.2-58.2,47.2-58.2-31.7,24.8-45.4,22.5-45.4,22.5Zm-48.8-145.9c3,0,5.4,2.4,5.4,5.4s-2.4,5.4-5.4,5.4-5.4-2.4-5.4-5.4,2.4-5.4,5.4-5.4Z"/>
  <path fill="url(#rxjs-radial-gradient)" d="m238.5,98.4c.5-22.2-33-45.8-33-45.8-59.7-44.2-113.7-15.6-113.7-15.6C45.1,57.7,31.3,103,31.3,103c-2.7,7.7-5.1,19.5-5.1,19.5-2.9,14.8-1.6,28.5-1.6,28.5,1.2,13.1,4.1,21.9,4.1,21.9,3,9.4,4.4,12.3,4.4,12.3-.1-.3-.6-2.5-.6-2.5,0,0-4.2-20.2-.3-39.6,0,0,3.4-20.2,17.2-35.8,0,0,22.4-31.9,64.1-19.4,0,0,9,3.2,12.1,4.8,3.1,1.5,8.5,3.8,8.5,3.8,29.5,14.3,54.5,18.8,54.5,18.8,52.9,8.9,49.9-16.9,49.9-16.9Zm-66.9-19.7c-3,0-5.4-2.4-5.4-5.4s2.4-5.4,5.4-5.4,5.4,2.4,5.4,5.4-2.4,5.4-5.4,5.4Z"/>
  <path fill="url(#rxjs-linear-gradient-2)" d="m137.4,58.2l-34.1-10.6c-.2,0-1.2-.5-3,0,0,0-20.1,5.1-16.6,16.1,0,0,2.1,6.9,7.8,13.6l37.5-1.8,8.4-17.3Z"/>
</svg>

When I Convert it to a <symbol> and store it inside of an <svg> that contains many other logos I want to display, it no longer shows any of the gradients.  The gradients are defined in <defs> and I have moved them to the containing <svg> element so they are not inside the <symbol>.
This is how I display the image, which works fine for everything else that doesn't use gradients.
<svg class="logo" role="img">
  <use xlink:href="#rxjs"></use>
</svg>

.logo {
  width: 96px;
  height: 96px;
  display: inline-block;
}
<svg xmlns="http://www.w3.org/2000/svg" style="display: none">
  <defs>
    <linearGradient id="rxjs-linear-gradient" x1="53.5" y1="36.29" x2="177.94" y2="168.67" gradientTransform="translate(0 284) scale(1 -1)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#e01d84" />
      <stop offset=".4" stop-color="#df1d85" />
      <stop offset=".77" stop-color="#932c87" />
      <stop offset="1" stop-color="#5d2f88" />
    </linearGradient>
    <radialGradient id="rxjs-radial-gradient" cx="190.17" cy="226.58" fx="190.17" fy="226.58" r="121.58" gradientTransform="translate(-.17 269.21) rotate(.14) scale(1 -.84)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#e01d84" />
      <stop offset=".14" stop-color="#de1e85" />
      <stop offset=".28" stop-color="#d62085" />
      <stop offset=".43" stop-color="#c92386" />
      <stop offset=".59" stop-color="#b72786" />
      <stop offset=".74" stop-color="#9d2b87" />
      <stop offset=".89" stop-color="#7c2e88" />
      <stop offset="1" stop-color="#5d2f88" />
    </radialGradient>
    <linearGradient id="rxjs-linear-gradient-2" x1="83.21" y1="221.66" x2="137.32" y2="221.66" gradientTransform="translate(0 284) scale(1 -1)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#e01d84" />
      <stop offset=".24" stop-color="#da1e85" />
      <stop offset=".66" stop-color="#c72085" />
      <stop offset="1" stop-color="#b52284" />
    </linearGradient>
  </defs>

  <symbol id="rxjs" viewBox="0 0 283.5 283.5">
    <path fill="#e32286" d="m29.6,175.3c-5.2-16.2-6.7-33.3-3.7-50.9,1.3-7.3,3.3-14.3,5.5-21.4,0,0,13.8-45.3,60.5-66,0,0,16.1-8.5,40.3-9.1,0,0-3.3-3.2-5.4-4.6-11.4-7.6-28.4-10.1-38.7.6-3.1,3.2-5.7,6.7-8.6,9.9-3.3,3.6-7.3,6.6-11.9,8.3-4,1.5-8,1.2-12.1,1.9-4.2.7-8.5,2.2-11.9,4.9-3.7,3-5.2,7-5.6,11.6-.4,3.6-.3,7.3-.5,10.9-.5,10.6-3.9,13.6-11.5,19.5-3.2,2.4-5.9,5.6-7.9,9-6,10.6,3.6,21.6,4.1,32.3.1,2.2-.1,4.4-.9,6.5-.8,2.3-2.4,3.8-3.7,5.7-1.8,2.5-3,5.5-2.5,8.6s2.1,6,3.6,8.7c2.9,4.8,6.5,9.1,10.3,13.2.2,0,.18.104.22.168"/>
    <path fill="url(#rxjs-linear-gradient)" d="m220.4,213.7c23-10,32.8-27.3,32.8-27.3,21.5-29.3,14.2-60.2,14.2-60.2-13.7,29.8-26.2,38-26.2,38,33.7-51.3.2-82.3.2-82.3,13.7,29.2-4.5,64.8-4.5,64.8-15.3,32.2-37,43.7-37,43.7,24.2,4.5,42-11.8,42-11.8-34.7,37.5-72.3,35.7-72.3,35.7,15.8,17.7,39.5,16.2,39.5,16.2-31,7.3-60.1-3-84-22.9-4.5-3.7-8.8-7.7-12.8-12,0,0-3.6-3.8-4.3-4.8l-.1-.1c-.5,18.5,18.8,35.7,18.8,35.7-24.2-10-35.3-31.7-35.3-31.7,0,0-16.3-27.8-4.5-59.5s47.5-38.5,47.5-38.5c29.5,14.3,54.5,18.8,54.5,18.8,52.7,8.8,49.7-17,49.7-17,.5-22.2-33-45.8-33-45.8-59.7-44.3-113.7-15.7-113.7-15.7C45.2,57.7,31.4,103,31.4,103c-2.2,7.1-4.2,14.1-5.5,21.4-5.1,29.7,2.6,57.8,19.3,82.8,26,38.8,68.2,52.2,68.2,52.2,62.5,21.2,105.2-10,105.2-10,39.3-27,47.2-58.2,47.2-58.2-31.7,24.8-45.4,22.5-45.4,22.5Zm-48.8-145.9c3,0,5.4,2.4,5.4,5.4s-2.4,5.4-5.4,5.4-5.4-2.4-5.4-5.4,2.4-5.4,5.4-5.4Z"/>
    <path fill="url(#rxjs-radial-gradient)" d="m238.5,98.4c.5-22.2-33-45.8-33-45.8-59.7-44.2-113.7-15.6-113.7-15.6C45.1,57.7,31.3,103,31.3,103c-2.7,7.7-5.1,19.5-5.1,19.5-2.9,14.8-1.6,28.5-1.6,28.5,1.2,13.1,4.1,21.9,4.1,21.9,3,9.4,4.4,12.3,4.4,12.3-.1-.3-.6-2.5-.6-2.5,0,0-4.2-20.2-.3-39.6,0,0,3.4-20.2,17.2-35.8,0,0,22.4-31.9,64.1-19.4,0,0,9,3.2,12.1,4.8,3.1,1.5,8.5,3.8,8.5,3.8,29.5,14.3,54.5,18.8,54.5,18.8,52.9,8.9,49.9-16.9,49.9-16.9Zm-66.9-19.7c-3,0-5.4-2.4-5.4-5.4s2.4-5.4,5.4-5.4,5.4,2.4,5.4,5.4-2.4,5.4-5.4,5.4Z"/>
    <path fill="url(#rxjs-linear-gradient-2)" d="m137.4,58.2l-34.1-10.6c-.2,0-1.2-.5-3,0,0,0-20.1,5.1-16.6,16.1,0,0,2.1,6.9,7.8,13.6l37.5-1.8,8.4-17.3Z"/>
  </symbol>

  <symbol id="angular" viewBox="0 0 48 48">
    <path fill="#bdbdbd" d="M23.933 2L3 9.285 6.308 36.408 23.955 46 41.693 36.278 45 9.156z"></path>
    <path fill="#b71c1c" d="M42.818 10.527L24 4.135 24 43.695 39.832 35.017z"></path>
    <path fill="#dd2c00" d="M23.941 4.115L5.181 10.644 8.168 35.143 23.951 43.721 24 43.695 24 4.135z"></path>
    <path fill="#bdbdbd" d="M24 5.996L24 15.504 32.578 34 36.987 34z"></path>
    <path fill="#eee" d="M11.013 34L15.422 34 24 15.504 24 5.996z"></path>
    <path fill="#bdbdbd" d="M24 24H30V28H24z"></path>
    <path fill="#eee" d="M18 24H24V28H18z"></path>
  </symbol>
</svg>

<svg class="logo" role="img">
  <use xlink:href="#rxjs"></use>
</svg>

<svg class="logo" role="img">
  <use xlink:href="#angular"></use>
</svg>

I've added a 2nd logo here to prove that this syntax works just fine for other SVG images without gradients
What do I need to change to get the gradients to show when I use the <symbol>/<use> syntax?
Answer: I've discovered this issue was due to display:none.  This messes with gradients for some reason.  Here's my solution to hide the host <svg> element visually instead of setting the display property

.logo {
  width: 96px;
  height: 96px;
  display: inline-block;
}

.hidden-svg {
  /*hide this but keep is visible/available. Setting display:none screws up the mix-blend-mode and gradients*/
  height: 0px;
  width: 0px;
  overflow: hidden;
  opacity: 0;
  position: absolute;
  z-index: -999;
  left: 0;
  top: 0;
}
<svg xmlns="http://www.w3.org/2000/svg" class="hidden-svg">
  <defs>
    <linearGradient id="rxjs-linear-gradient" x1="53.5" y1="36.29" x2="177.94" y2="168.67" gradientTransform="translate(0 284) scale(1 -1)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#e01d84" />
      <stop offset=".4" stop-color="#df1d85" />
      <stop offset=".77" stop-color="#932c87" />
      <stop offset="1" stop-color="#5d2f88" />
    </linearGradient>
    <radialGradient id="rxjs-radial-gradient" cx="190.17" cy="226.58" fx="190.17" fy="226.58" r="121.58" gradientTransform="translate(-.17 269.21) rotate(.14) scale(1 -.84)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#e01d84" />
      <stop offset=".14" stop-color="#de1e85" />
      <stop offset=".28" stop-color="#d62085" />
      <stop offset=".43" stop-color="#c92386" />
      <stop offset=".59" stop-color="#b72786" />
      <stop offset=".74" stop-color="#9d2b87" />
      <stop offset=".89" stop-color="#7c2e88" />
      <stop offset="1" stop-color="#5d2f88" />
    </radialGradient>
    <linearGradient id="rxjs-linear-gradient-2" x1="83.21" y1="221.66" x2="137.32" y2="221.66" gradientTransform="translate(0 284) scale(1 -1)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#e01d84" />
      <stop offset=".24" stop-color="#da1e85" />
      <stop offset=".66" stop-color="#c72085" />
      <stop offset="1" stop-color="#b52284" />
    </linearGradient>
  </defs>

  <symbol id="rxjs" viewBox="0 0 283.5 283.5">
    <path fill="#e32286" d="m29.6,175.3c-5.2-16.2-6.7-33.3-3.7-50.9,1.3-7.3,3.3-14.3,5.5-21.4,0,0,13.8-45.3,60.5-66,0,0,16.1-8.5,40.3-9.1,0,0-3.3-3.2-5.4-4.6-11.4-7.6-28.4-10.1-38.7.6-3.1,3.2-5.7,6.7-8.6,9.9-3.3,3.6-7.3,6.6-11.9,8.3-4,1.5-8,1.2-12.1,1.9-4.2.7-8.5,2.2-11.9,4.9-3.7,3-5.2,7-5.6,11.6-.4,3.6-.3,7.3-.5,10.9-.5,10.6-3.9,13.6-11.5,19.5-3.2,2.4-5.9,5.6-7.9,9-6,10.6,3.6,21.6,4.1,32.3.1,2.2-.1,4.4-.9,6.5-.8,2.3-2.4,3.8-3.7,5.7-1.8,2.5-3,5.5-2.5,8.6s2.1,6,3.6,8.7c2.9,4.8,6.5,9.1,10.3,13.2.2,0,.18.104.22.168"/>
    <path fill="url(#rxjs-linear-gradient)" d="m220.4,213.7c23-10,32.8-27.3,32.8-27.3,21.5-29.3,14.2-60.2,14.2-60.2-13.7,29.8-26.2,38-26.2,38,33.7-51.3.2-82.3.2-82.3,13.7,29.2-4.5,64.8-4.5,64.8-15.3,32.2-37,43.7-37,43.7,24.2,4.5,42-11.8,42-11.8-34.7,37.5-72.3,35.7-72.3,35.7,15.8,17.7,39.5,16.2,39.5,16.2-31,7.3-60.1-3-84-22.9-4.5-3.7-8.8-7.7-12.8-12,0,0-3.6-3.8-4.3-4.8l-.1-.1c-.5,18.5,18.8,35.7,18.8,35.7-24.2-10-35.3-31.7-35.3-31.7,0,0-16.3-27.8-4.5-59.5s47.5-38.5,47.5-38.5c29.5,14.3,54.5,18.8,54.5,18.8,52.7,8.8,49.7-17,49.7-17,.5-22.2-33-45.8-33-45.8-59.7-44.3-113.7-15.7-113.7-15.7C45.2,57.7,31.4,103,31.4,103c-2.2,7.1-4.2,14.1-5.5,21.4-5.1,29.7,2.6,57.8,19.3,82.8,26,38.8,68.2,52.2,68.2,52.2,62.5,21.2,105.2-10,105.2-10,39.3-27,47.2-58.2,47.2-58.2-31.7,24.8-45.4,22.5-45.4,22.5Zm-48.8-145.9c3,0,5.4,2.4,5.4,5.4s-2.4,5.4-5.4,5.4-5.4-2.4-5.4-5.4,2.4-5.4,5.4-5.4Z"/>
    <path fill="url(#rxjs-radial-gradient)" d="m238.5,98.4c.5-22.2-33-45.8-33-45.8-59.7-44.2-113.7-15.6-113.7-15.6C45.1,57.7,31.3,103,31.3,103c-2.7,7.7-5.1,19.5-5.1,19.5-2.9,14.8-1.6,28.5-1.6,28.5,1.2,13.1,4.1,21.9,4.1,21.9,3,9.4,4.4,12.3,4.4,12.3-.1-.3-.6-2.5-.6-2.5,0,0-4.2-20.2-.3-39.6,0,0,3.4-20.2,17.2-35.8,0,0,22.4-31.9,64.1-19.4,0,0,9,3.2,12.1,4.8,3.1,1.5,8.5,3.8,8.5,3.8,29.5,14.3,54.5,18.8,54.5,18.8,52.9,8.9,49.9-16.9,49.9-16.9Zm-66.9-19.7c-3,0-5.4-2.4-5.4-5.4s2.4-5.4,5.4-5.4,5.4,2.4,5.4,5.4-2.4,5.4-5.4,5.4Z"/>
    <path fill="url(#rxjs-linear-gradient-2)" d="m137.4,58.2l-34.1-10.6c-.2,0-1.2-.5-3,0,0,0-20.1,5.1-16.6,16.1,0,0,2.1,6.9,7.8,13.6l37.5-1.8,8.4-17.3Z"/>
  </symbol>

  <symbol id="angular" viewBox="0 0 48 48">
    <path fill="#bdbdbd" d="M23.933 2L3 9.285 6.308 36.408 23.955 46 41.693 36.278 45 9.156z"></path>
    <path fill="#b71c1c" d="M42.818 10.527L24 4.135 24 43.695 39.832 35.017z"></path>
    <path fill="#dd2c00" d="M23.941 4.115L5.181 10.644 8.168 35.143 23.951 43.721 24 43.695 24 4.135z"></path>
    <path fill="#bdbdbd" d="M24 5.996L24 15.504 32.578 34 36.987 34z"></path>
    <path fill="#eee" d="M11.013 34L15.422 34 24 15.504 24 5.996z"></path>
    <path fill="#bdbdbd" d="M24 24H30V28H24z"></path>
    <path fill="#eee" d="M18 24H24V28H18z"></path>
  </symbol>
</svg>

<svg class="logo" role="img">
  <use xlink:href="#rxjs"></use>
</svg>

<svg class="logo" role="img">
  <use xlink:href="#angular"></use>
</svg>
Comment: display:none says there's no CSS below this point. Gradient properties are mapped CSS so gradients (and many other things) don't really work when they are display:none.


Can I use Html Agility Pack To Parse HTML Fragment?

Question: Can Html Agility Pack be used to parse an html string fragment?
Such As:
var fragment = "Some code ";

Then extract all  tags? All the examples I seen so far have been loading like html documents.
Comment: It could be done even simlier with HAP, in one line: `var text = HtmlNode.CreateNode("Some code ").InnerText;`
Answer: If it's html then yes.
string str = "Some code";
// not sure if needed
string html = string.Format("{0}", str);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);

// look xpath tutorials for how to select elements
// select 1st  element
HtmlNode bNode = doc.DocumentNode.SelectSingleNode("b[1]");
string boldText = bNode.InnerText;

Comment: Ok then what would I do with it how would I do some parsing?
Comment: Hmm thanks but I copied and pasted that code into a console app and imported html agility back but on HtmlNode line I get a null reference exception.
Comment: Maybe it's HtmlNode bNode = doc.DocumentNode.SelectSingleNode("/b[1]");
Comment: Try HtmlNode bNode = doc.DocumentNode.SelectSingleNode("//b[1]");
Answer: I dont think this is really the best use of HtmlAgilityPack.
Normally I see people trying to parse large amounts of html using regular expressions and I point them towards HtmlAgilityPack but in this case I think it would be better to use a regex.
Roy Osherove has a blog post describing how you can strip out all the html from a snippet:

http://weblogs.asp.net/rosherove/archive/2003/05/13/6963.aspx

Even if you did get the correct xpath with Mika Kolari's sample this would only work for a snippet with a  tag in it and would break if the code changed.
Answer: This answer came up when I searched for the same thing. I don't know if the features have changed since it was answered but this below should be better.
$string = 'Some code '
[HtmlAgilityPack.HtmlNode]::CreateNode($string)


Firebase: Checking whether a value already exists in any of the child nodes or not

Question: I want to find whether a email (entered by the user) already exists in the my Firebase child node or not.
How do i check it?
MY PROGRAM:
String email = "firstname.lastname@example.com";
Query check = FirebaseDatabase.getInstance().getReference("student").child(RANDOM_ID).orderByChild("email").equalTo(email);
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {

            if(snapshot.exists())
            {
                Toast.makeText(this, "Email already exists!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this, "Email doesn't exists!", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    };
    check.addListenerForSingleValueEvent(eventListener);

note: i'm using RANDOM_ID just for the reference, it'll be randomly generated id's
Comment: `if(snapshot.exists())` the else is only going to be the opposite of this so it is not ncessary to call `if (!snapshot.exists())`
Comment: Please **never** leave `onCancelled` empty. At its minimum it should be `public void onCancelled(@NonNull DatabaseError databaseError) { throw databaseError.toException(); }`.
Answer: When you run a query on that path, Firebase checks the condition for each child directly under that path. Since you run the query on /student/$RANDOM_ID, it then checks each child node under that (so email, id, etc) whether they have a property email with the given value. And since there is no /student/$RANDOM_ID/email/email, the query doesn't match any nodes.
The correct query to check whether any direct child node of student has a email property with the given value, is:
Query check = FirebaseDatabase.getInstance().getReference("student").orderByChild("email").equalTo(email);


Analisar se um número é par ou ímpar

Question: O programa deve fazer:

Digite um Número: 12345

1 e ímpar
2 e par
3 e ímpar
4 e pra
5 e ímpar

Até agora eu fiz o seguinte código:
void parImpar (int num) {
    int resto;
    while (num > 0) {
        resto = num%10;
        if(resto%2==0) {
            printf("\n%d eh Par", resto);
        } else {
            printf("\n%d eh Impar", resto);
        }
        num = num / 10;
    }

}

int main(int argc, char** argv) {
    int num;
    printf("Digite um numero inteiro: ");
    scanf("%d",&num);
    parImpar(num);
}

Esse código me retorna o inverso:

Digite um Número: 12345

5 e ímpar
4 e par
3 e ímpar
2 e pra
1 e ímpar

Comment: Não está claro. A ideia é verificar número por número de um número? Exemplo: `255 | 2, 5 e 5`?
Comment: @Renan exatamente isso, Renan!
Comment: @LeoCaracciolo Também não entendo de C++, Leo! Mas parece mais complicado do que aparenta ser.
Answer: Tem algumas formas de fazer isso, tem a mais confusa e a mais inteligente, que eu preferi:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void parImpar (int num) {
    int digitos = floor(log10(abs(num))) + 1;
    for (int i = digitos - 1; i >= 0; i--) {
        int div = num / (int)pow(10, i);
        num = num % (int)pow(10, i);
        printf(div % 2 == 0 ? "\n%d eh Par" : "\n%d eh Impar", div);
    }
}

int main() {
    int num;
    printf("Digite um numero inteiro: ");
    scanf("%d", &num);
    parImpar(num);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Primeiro ele descobre o número de dígitos através de uma fórmula conhecida. Tem outras formas de obter isto, mas não gosto de nenhuma.
Aí fazemos um laço já sabendo onde começa e onde termina. E nele fazemos a conta para obter o valor do dígito dividindo pela potência de 10 elevando à posição que está analisando. E depois pega-se o resto dessa divisão para continuar fazendo o mesmo com os demais dígitos.
Exemplificando: a primeira potência resultará em 10000 (10 ^ 4) então dividir 12345 por 10000 dá 1 e isso é pode ser analisado se é par ou impar. Aí pega-se o resto disto que dá 2345 e que será dividido por 1000, então dá 2, e depois sobre 345 dividido por 100 que dá 3, e sobra 45 dividido por 10 dá 4 e finalmente 5 dividido por 1 dá 5.
Comment: Fantástico! Era exatamente isso! Obrigado pela explicação!

Analisar se um número é par ou ímpar


PowerPoint VBA - SlideRange position on a screen

Question: I am creating a PPT Add-In and I am struggling to find the answer whether it is possible to determine the SlideRange position on a screen.
I would like to have a userform to be opened in a particular position (for example left = 10, top = 10 starting from left-top corner of the SlideRange). Unfortunatelly its position is based on a screen resolution. As the resolution can be changed and the PPT view type may be modified I am unable to establish the accurate position of SlideRange.
Is it possible to do with VBA?
Thanks in advance!
MJ
Answer: SlideRange has no particular position ... it's a collection of slides, and it's unclear what units you're using when you want to position the form at 10,10.  But in normal full screen view, you can get the slide show window coordinates in points like so:
With SlideShowWindows(1)
    Debug.Print .Left
    Debug.Print .Top
    Debug.Print .Height
    Debug.Print .Width
End With
To get the results in screen pixels you have to use a Win API call to get the screen DPI (dots per inch).
Inches = Points / 72
Pixels = Inches * DPI
Comment: Hi Steve,
Thank you for your answer. Good to know that there is no way to find a slide position.
I am trying to create a floating ruler (userform) that shows its current posiotion which will help me to align objects.
I realised that it can be replaced by a picture and a separate userform will show current picture position.
I faced another obstacle which is a lack of MouseUp/Down event in PPT.
WindowSelectionChange does not solve the problem... Do you know if it is possible to catch mouse events in PPT?
Thanks
MJ
Answer: << Do you know if it is possible to catch mouse events in PPT?
Only if the mouseclick changes the selection, and as you know, that's NOT all the time.
There's probably some way of doing it via the Win API but nothing like this is built into PPT itself.


Erro ao capturar informação de componente no Angular

Question: Meus amigos, estou começando a estudar angular, estou fazendo um CRUD de produtos me deparei com o seguinte erro ao criar o componente para editar o produto cadastrado.
Tentei de varias formas, mas nada resolveu.
Aparece as seguintes mensagens:
"error TS2564: Property 'product' has no initializer and is not definitely assigned in the constructor.
13   product: Product"
e
"error TS2663: Cannot find name 'product'. Did you mean the instance member 'this.product'?
20       this.product = product"
Esse é meu arquivo product-update.component.html ele é que deveria mostrar o produto que será editado.

    <mat-card>
    <mat-card-title>Alterar Produto</mat-card-title>
    <form>
        <mat-form-field>
            <input matInput placeholder="Nome"
                [(ngModel)]="product.name" name="name">
        </mat-form-field>
        <mat-form-field>
            <input matInput placeholder="Preço (R$)"
                [(ngModel)]="product.price" name="price">
        </mat-form-field>
    </form>
    <button mat-raised-button (click)="updateProduct()" color="primary">
        Atualizar
    </button>

    <button mat-raised-button (click)="cancel()">
        Cancelar
    </button>
</mat-card>

E este é o meu product-update.component.ts que deveria ser o responsável por trazer as informações do produto selecionado. Ainda não terminei todas as funções desse arquivo. As mensagens de erro aparecem nele.

    import { ActivatedRoute, Router } from '@angular/router';
import { ProductService } from './../product.service';
import { Component, OnInit } from '@angular/core';
import { Product } from '../product.model';

@Component({
  selector: 'app-product-update',
  templateUrl: './product-update.component.html',
  styleUrls: ['./product-update.component.css']
})
export class ProductUpdateComponent implements OnInit {

  product: Product

  constructor(private productService: ProductService, private router: Router, private route: ActivatedRoute) { }

  ngOnInit(): void {
    const id = this.route.snapshot.paramMap.get('id') || ''
    this.productService.readById(id).subscribe(prduct => {
      this.product = product

    });
  }

  updateProduct():void{

  }

  cancel(): void{
    this.router.navigate(['/products'])
  }

}

Eu preciso identificar como corrigir estas duas mensagens de erro, se algum puder ajudar, agradeço imensamente.
Comment: acho que inves de só declarar o product vc tem que inicializar ele como um produto vazio
Comment: Se eu fizer isso, vai trazer no HTML os campos vazios, mas eu preciso que traga as informações do produto relacionado ao ID para poder editar. ou não?
Comment: vc pode fazer um ngif="product" no html tbm ali na altura do form
Comment: Não está faltando instanciar o **Product** não??!
Comment: Você deveria inicializar o proudct = new Product(); E no momento que você faz o "readById" você escreveu 'prduct' ao invés de 'product'
Comment: Quando você criar o **Product**, tente fazer assim: `product!: Product` .  Acredito que isso deva resolver.
Answer: Tente isso
export class ProductUpdateComponent implements OnInit {

  product!: Product;

  constructor(
    private productService: ProductService,
    private router: Router,
    private route: ActivatedRoute
  ) { }

  ngOnInit(): void {
    const id = this.route.snapshot.paramMap.get('id')
    this.productService.readById(id).subscribe(product => {
      this.product = product;

    })

  }

No product.service
tente isso
readById(id: any): Observable<Product>{
    const url= `${this.baseUrl}/${id}`
    return this.http.get<Product>(url)
  }


Is the change of base scheme $\operatorname{Spec} K \to \operatorname{Spec} k$ relevant?

Question: Let $X$ be a $K$-scheme (affine if necessary), $K|k$ an extension of fields (separable, finite, ... as necessary).
Then $k \hookrightarrow K$ is unique as a homomorphism of $k$-algebras and so $\operatorname{Spec} K \to \operatorname{Spec} k$ is unique as a morphism of $k$-schemes.
In this way, $X$ has the unique associated structure morphism $X \to \operatorname{Spec} K \to \operatorname{Spec} k$, which makes $X$ into a $k$-scheme.
Is this construction helpful for anything or do you know of a place where it is used?
I have not seen it used so far, but am new to the language of schemes and may be missing something.
Answer: This isn't widely used and I also haven't seen it around. But it can lead to some weird things which play with intuition, atleast for me.
Suppose $ X $ is the hyperbola $ \operatorname{Spec} \mathbb{C} [u,v] / (uv -1) $ considered as a scheme over $ \operatorname{Spec} \mathbb{C} $. We can consider it as a scheme $ X|_{ \mathbb{R} } $ over $ \operatorname{Spec} \mathbb{R} $ via the inclusion of $ \mathbb{R} $ in $ \mathbb{C} $. Then $ X|_{ \mathbb{R} } $ has no real points (going against the intuition that the hyperbola has lots of real points) simply because there is no morphism $ \mathbb{C} [u,v] / (uv -1) \rightarrow \mathbb{R} $ over $ \mathbb{R} $.
Also, base changing $ X|_{ \mathbb{R} } $ back to $ \mathbb{C} $ does not give you $ X $, but two disjoint copies of $ X $.
A better concept of 'restriction of scalars' for schemes over fields is Weil restriction. You might want to look that up.


How do I get the window that currently has the cursor on top of it with X11?

Question: How can I retrieve the top window of which the cursor is on top of in the X11 server?
The window doesn't have to be "active" (selected, open, whatever), it just has to have the cursor floating on top of it.
Thanks in advance.
Answer: You can use XQueryPointer() to get the mouse position. Then get a window list using XQueryTree(). XQueryTree() returns the window list in proper z-order so you can just loop through all the windows until you find one whose bounding box is under the pointer, XGetWindowAttributes() will give you everything you need to figure out the bounding box. I'm not sure what you would do with shaped windows though.
I haven't work with X11 for a few years so this might be a rather clunky approach but it should work. I also don't have my O'Reilly X11 books anymore, you'll want to get your hands on book one of that series if you're going to work with low level X11 stuff; I think the whole series is available for free online these days.
Comment: for example here : http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V51B_ACRO_SUP/XWINSYS.PDF
Comment: I was thinking of the Adrian Nye books (XLib Programming Manual, XLib Reference Manual) published by O'Reilly, that series was my bible back in my X11/Motif days.
Answer: I haven't programmed X11 for over a decade, so forgive me if I get this wrong.
I believe you can register for mouse movement events on your windows. If you handle such event by storing the window handle in some variable or other, and then handling the event so it doesn't percolate down the tree, then at the time you want to identify the window you can just query the variable.
However this will only work when the mouse is over a window you have registered a suitable event handler for, so you won't know about windows belonging to other applications - unless there is a way to register for events on other people's windows which may be possible.
The advantage over the other answer is that you don't have to traverse the whole tree. The disadvantage is that you need to handle a great many mouse movement events, and it may not work to find other people's windows.
I believe there may also be mouse enter and mouse leave events too which would reduce the amount of processing required.


Does the data of Galois group, ramified places, and inertia groups, determine a Galois number field?

Question: Suppose I tell you that $K/\mathbb{Q}$ is a finite Galois extension, and I specify the Galois group $G$, and suppose further that I give you a finite list $S$ of places of $\mathbb{Q}$ and for each place $p$ a conjugacy class $C_p$ of subgroups of $G$, and I tell you that $K/\mathbb{Q}$ is ramified precisely at the places $p$ of $S$, with inertia groups $C_p$.
Is this enough information to recover $K$?
If not, can you provide a counterexample? If so, can you refer me to some sources (or, if the proof is not too hard, can you indicate lines of proof)?
ADDENDUM August 8: To clarify a point. The list $S$ is allowed to include the infinite place. If the infinite place is ramified, i.e. if $K$ is not a real field, then, fixing some embedding of $K$ in $\mathbb{C}$, $G$ contains complex conjugation and the relevant conjugacy class $C_\infty$ is that of the subgroup generated by complex conjugation. So, the data $S,\{C_p\}$ that we start with includes whether the infinite place is ramified.
Comment: We can probably use already-available global class field theory to answer this for abelian groups.
Comment: This seems unlikely; it's just not a whole lot of information. I would look for counterexamples among number fields with the same Dedekind zeta function (see for example http://mathoverflow.net/questions/23571/number-fields-with-same-discriminant-and-regulator for some references).
Comment: Something along these lines which is true is that a number field (I'm not sure if it has to be Galois or not) is determined by which primes split completely in it, although I don't know a reference for this.
Comment: Aren't the completely split primes exactly those with trivial inertia groups (outside of $S$?
Comment: @JyrkiLahtonen - no, the inertia group is trivial iff there is no ramification, but there can be some inertia.
Comment: @JyrkiLahtonen - the "inertia group" and "decomposition group" are so named because of their fixed fields.  In the decomposition field, a prime of the base field does all the splitting it will do, and the primes above it in the decomposition field then stay inert in the inertia field, whereupon, passing to the top field, they ramify. This is why trivial inertia group $\Leftrightarrow$ inertia field is the top field $\Leftrightarrow$ no ramification.
Comment: Oops. You're right. I had the wrong recollection that inertia group has order $f$, but it is of index $f$ in the decomposition group. Sorry.
Answer: I would say no. For example, take $K=\mathbb Q(i)$ and $L=\mathbb Q(\sqrt{2})$, which are non-isomorphic number field. Both are ramified precisely at $2$, and the inertia subgroup at $2$ is the whole Galois group. So if I tell you $G=C_2$, $S=\{2\}$ and $C_2=G$, you are not able to recover exactly one between $K$ and $L$.
Comment: I was satisfied when I read this, but actually it's occurring to me now that if we admit the infinite place (which I absolutely want to do), then $\mathbb{Q}(i)$ is ramified at the infinite place but $\mathbb{Q}(\sqrt{2})$ isn't.
Answer: Ferra's $K$ and $L$ are distinguished by the infinite place, but they inspired me to look for simple quadratic counterexamples:
Take $K=\mathbb{Q}(\sqrt{3})$ and $L=\mathbb{Q}(\sqrt{6})$. These are both ramified at 2 and 3 and because the Galois group of both is $\mathbb{Z}/2\mathbb{Z}$, whose only nontrivial subgroup is the whole group, the inertia groups at both 2 and 3 must be the whole group.  Then $K$ and $L$ cannot be distinguished by the information specified in the question.
Actually, for any squarefree $m$ that is $>0$ and $3$ mod $4$, $K=\mathbb{Q}(\sqrt{m})$ and $L=\mathbb{Q}(\sqrt{2m})$ would also always provide a counterexample, because the discriminants are $4m$ and $8m$ and these are divisible by the same primes, so they are ramified at the same places.


Using Java8 streams to filter list and get the first element

Question:  collectorConfiguration = Optional.ofNullable(recapPlacement.getPnetCode())
                    .map(pnetCode -> Optional.ofNullable(collectorConfigurations.stream()
                    .filter(c -> pnetCode.equals(c.getPnetCode()))
                    .collect(Collectors.toList())
                    .stream().filter(Objects::nonNull).findFirst())
                    .orElse(unknownExternalCollector))
                    .orElse(unknownExternalCollector);

Here in the above code
1) I want to return unknownExternalCollector if pnetCode is null
    OR
2) I want to iterate collectorConfigurations and find atleast one
    record by using pnetCode, if there are no elements in the list that
    matches pnetCode then I want return unknownExternalCollector.
I am getting compilation error saying
orElse
(java.util.Optional<com.capitalone.omega.collectorservice.domain.CollectorConfiguration>)
in Optional cannot be applied om.capitalone.omega.collectorservice.domain.CollectorConfiguration

Answer: You can simplify it as follows (there is no need to collect and then stream and call findFirst. You can use flatMap here)
collectorConfiguration = Optional.ofNullable(recapPlacement.getPnetCode())
            .flatMap(pnetCode -> collectorConfigurations.stream()
                    .filter(c -> pnetCode.equals(c.getPnetCode()))
                    .filter(Objects::nonNull)
                    .findFirst())
            .orElse(unknownExternalCollector);


Server taking too long to respond error

Question: This is my first post on serverFault and my first entry in to web server configuration.
The hardware and software.
CPU: GenuineIntel, Intel(R) Core(TM)2 Duo CPU E7500 @ 2.93GHz
OS: Linux 2.6.18-128.el5
Memory: 2Gb
Background.
I am running a small database (MySQL), around 1000 records with each record containing 44 fields. At the start of each day "00:01" the tables are cleared and populated with fresh data.
The are 10 remote PCs all running Winodws XP and Firefox internet browser. All remote PC's are connected to the internet using a min 4Gb broadband connection.
Each remote PC runs a URL which displays a dynamic page of data which is refreshed every 20 seconds. This is a continual process 24 hours a day.
I problem I am having is on odd occasions throughout the day the PC browser error with "Server taking too long to respond error". What I am trying to find our is if I have the correct setting in the httpd.conf file on the server. Any help or advice anyone can provide would be very helpful.
Best regards
Dereck
Server config file:
httpd.conf
<code>ServerRoot "/etc/httpd"

PidFile run/httpd.pid

Timeout 120

KeepAlive On

MaxKeepAliveRequests 200

KeepAliveTimeout 5

<IfModule prefork.c>
StartServers       8
MinSpareServers    5
MaxSpareServers   20
ServerLimit      256
MaxClients       254
MaxRequestsPerChild  4000
</IfModule>

<IfModule worker.c>
StartServers         2
MaxClients         150
MinSpareThreads     25
MaxSpareThreads     150
ThreadsPerChild     25
MaxRequestsPerChild  0
</IfModule>
</code>
Comment: Are you using the worker or the prefork MPM for apache?
Answer: A few things you can check:

Are you sure it is your site that is not available and not a local Intranet or Internet issue? Is it always the same computer that has the access problem or do all of them have it randomly? If it is the former I would suspect a local connection issue.
Check the logs (Apache, MySQL, system, etc...) around the time when you see the issue for any relevant error messages.
If possible check the load on the server when you encounter an issue (top, netstat, df, etc...). You can also setup some form of simple monitoring service that will notify you of any significant system issues.
The issue is not necessarily the Apache settings but anything in the stack that your app uses, so MySQL and whatever language (PHP/PERL/...) you're using.
You can try benchmarking/stress testing your site using ab/siege to see if you forcibly duplicate the issue rather than waiting for it to appear. The issue could simply be that at certain times in the day all 10 computers submit a request at the same time which your server can't handle. Benchmarking would help tell you if this is an issue or not.
Once you get closer to identifying the cause you can try writing short test cases to try and isolate/duplicate it. Once you fix the problem you can re-run the tests to confirm that the issue is indeed fixed (as opposed to the good ole 'well it didn't crash today' test).
Answer: Your config is far from optimal, however it should have absolutely no problem in serving the load you describe.
You've not given us much details on how the code works. There's nothing in your description of the code to suggest that it could cause a timeout - but it is conceivable that there could be deadlocks in the code. In this case, your logs should be full of errors. Indeed, that's the first place to look when your site doesn't behave as you expect. Your access log (apache is usually configured to use the combined log format) will show the times taken for each request. Are there any high values? Anything over 120 seconds should produce an error log entry as well.
You can't access a MySQL database from Apache- you need some application logic in between - but you've given no details. This should be logging errors if the requests really were taking that long.
However I'd place bets on the problem being at the client end or on the network - the request is never getting to the webserver. In order to prove this, I'd verify the duration of the last request from a client before it went client - it will be no longer than expected. As to how you isolate the root cause....that's more complicated. Maintaining detailled packet logs at all clients and the server is rather difficult. The most likely candidates are the network itself or "security" software.
It's probably a lot simpler to look at the mechanism by which the page is refreshed and construct something a lot more resillient with some basic diagnostics built in (i.e. written in javascript, displaying a sensible error message when stuff fails and checking site connectivity)
Answer: It sounds like your server is blocking for some reason. You might need to increase the apache settings or switch to fastcgi, but I suspect that there is a slowdown in PHP or MYSQL. Turn on the mysql slow query log to see if mysql might be the slowdown. See http://dev.mysql.com/doc/refman/5.5/en/slow-query-log.html
Comment: "around 1000 records" - this is extremely unlikely to be caused by poor performance - it's a deadlock or connectivity problem.

Server taking too long to respond error


Time Series: relating duration of one time series to events

Question: I have a stats question, and not enough experience to even begin to know how to find the answer.  It's a time series question relating two time series:
A = anomolous conditions (-,0,+) --- continuous variable
B = # of events --- discrete variable
If I wanted to find out, quantitatively, a threshold of duration under which + anomalous conditions must occur in order for there to be an event, how might one go about doing this? For example, I am more lucky than normal for X consecutive weeks duration before a great opportunity arises. How do I find out the distribution of durations (i.e., my distribution of X)?
I've tried thinking about it and autoregressive analysis won't answer the question because it would simply tell me when the peaks align and the temporal persistence of the anomalous conditions.
I'm looking for key words, methods, links, example problems - anything to point me in the right direction. Any advice is very welcome!
Answer: I needed an answer quickly, so I asked here AND among my PhD Statistician friends. I proposed that I conduct a smooth (e.g., moving average) of different time scales that X could be and then conduct lead-/lag- analysis to determine the highest correlation time and compare then across the different scales of X, but this seems clunky. Is there a better way?
Here is the answer they gave me:
Let's call your "A", A(t), indicating that it is a function of time, and "B", B(t).  Let's suppose B(t) = 0 unless there is an event, and there, B(t) = 1.  Maybe there can be two events at the same time, then B(t) = 2.
I pretty much like your third approach.  Take a window size W and smooth A(t) at that window size to produce A(t;W).  Then look at the joint behavior of A(t;W) and B(t).
In particular, look at A(t;W) where B(t) = 1.  And, look at the integral of A(t;W) over an interval I, versus the number of events in B(t) over the same interval I.
In general, event data like B(t) are often modeled as Poisson processes in time — like radioactive decay events in a lump of uranium, or lightning strikes in a large fixed area.  Take lightning strikes.  Maybe the rate of lightning strikes over time depends on some external forcing, like clouds.  Then the rate function of the Poisson events can be modeled as controlled by the forcing.  For your problem, maybe the forcing is A(t), and maybe the Poisson rate is A(t;W), or something like A(t;W). Note that the poisson model implies that the waiting times between events follow an exponential distribution.
How you might do this analysis depends on the number of events B(t)!!  If you have a lot of events in a plausible time-window-width W, you might prefer to smooth B (find the number of events in an interval I) and compare to A.
One quick example of this kind of approach is:
http://people.ee.duke.edu/~lcarin/PoissonProcess.pdf
I'm not suggesting you implement this, just that the authors are good and the references to older work might be useful.


How to make youtube video exit fullscreen when the video is done

Question: I'm using the Youtube iOS API helper in order to show videos. Most users will want to view the videos in fullscreen, but after watching the video, the app needs to exit the fullscreen video so that users can complete related tasks. Is there a way to exit the video on videoEnded.
Comment: Can you not just call - (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state {} and check when the player has stopped and then exit your player?
Comment: I don't see a way of exiting the player. I know I can track the state in that way, but then I'm stuck in fullscreen until the user hits Done
Comment: Can you not programmatically click the done button when finshed playing?
Comment: Do you have an action that is called when the button is pressed?
Comment: No. All of that is handled by the iframe created by youtube (I think).
Answer: In the playerVars dictionary you should set a property @"autohide" : @1
That Will make the video exit full screen after the video is done.
It will look something like this:
NSDictionary *playerVars = @{@"autohide" : @1};
[self.playerView loadWithVideoId:self.videoID playerVars:playerVars];

Answer: it's work for me,
source https://gist.github.com/akisute/a46c5ec54d27f73b62da
- (void)exitFullScreenVideo:(BOOL)animated completion:(void (^)(void))completion
    {
        if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 8.0) {
            BOOL isFullScreenVideoContent = NO;
            for (UIWindow *window in [UIApplication sharedApplication].windows) {
                if ([window.rootViewController.presentedViewController isKindOfClass:NSClassFromString(@"AVFullScreenViewController")]) {
                    [window.rootViewController dismissViewControllerAnimated:animated completion:^{
                        window.rootViewController = nil;
                        window.hidden = YES;
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                        [window performSelector:NSSelectorFromString(@"release")];
    #pragma clang diagnostic pop
                        completion();
                    }];
                    isFullScreenVideoContent = YES;
                    break;
                }
            }
            if (!isFullScreenVideoContent) {
                completion();
            }
        } else {
            completion();
        }
    }


How to predict factor scores in Lavaan

Question: In doing a CFA in Lavaan, I had to use the covariance matrix as an input because I was getting some errors with the original data e.g., negative variances.
I would normally have predicted factor scores using the predict() function, lavPredict functions the same, but now that I'm using the covariance matrix it's not possible to do this directly.
Is there a way to use the information from the CFA to calculate factor scores in the same way as Lavaan does it? I believe the predict() function uses the method of regression to calculate factor scores.
This is sample code to produce factor scores with raw data as input.
Using this method I get an error in one of my variances:
library(lavaan)

model1 = '
Latent1 =~ X1 + X2
Latent2 =~ X3 + X4 + X5
Latent3 =~ X6 + X7
'

model1.fit = cfa(model1, data=mydata) #fit Lavaan model

predict(model1.fit) #Predict factor scores (method of regression)

This is the code to produce factor scores with covariance matrix as input. There are no error messages here, but I can't produce factor scores as there is not data to link them to:
cov = cor2cov(cor,std) #(using cor2cov function to create covariance matrix out of correlation table (cor) and standard deviations (std))

model2 = '
Latent1 =~ X1+ X2
Latent2 =~ X3 + X4 + X5
Latent3 =~ X6 + X7
'

model2.fit = cfa(model=model2, sample.cov=cov,sample.nobs=102,std.lv=FALSE)

How to proceed from here to produce factor scores using the results from Lavaan's CFA analysis?
Comment: If you got errors with the data, you should get errors with the covariance matrix (unless you had missing data, or used something other than ML). perhaps some code would help?
Comment: Hi Jeremy, not necessarily. Some errors do go away if you just use the covariance matrix and standard deviations as input for Lavaan. The thing is that now I cannot use the predict() function, and calculating factor scores independently using the regression method is beyond my current skill set...
Comment: On the right of the screen, there I see some related questions, e.g. http://stats.stackexchange.com/q/142285/3277. Can that help?
Comment: Just for info, I've got the idea of using the covariance table instead of the raw data to get better models from Erin Buchanan CFA lectures, such as this one: https://www.youtube.com/watch?v=wT2z0zEK-yw&list=PLw93TUuxrFAZkJVc5dhgTZpOT7qmTjlT7&index=19 (min 6 to 9)
Comment: Hi ttnphns, not really. I saw that answer, but the matrix response is beyond my understanding. and the other one "Since the factor scores are a linear function of the observables, once you've calculated them once, you can simply use lm to fit a linear regression between the fitted scores and the observables. ", doesn't really apply since I was not able to calculate fitted scores.
Comment: Can you show us the code for both models?
Comment: Hi Jeremy, I included the code for both models.
Answer: This question has received a number of views since it was first posed, but no answers. Here is a solution, which may be useful to future readers of this question.
To demonstrate it works I will first run a cfa() model in using the HolzingerSwineford1939. The model is taken from the lavaan tutorial page.
library(lavaan)
dat<-data.frame(HolzingerSwineford1939[,7:15])

mod<-'
visual=~x1+x2+x3
textual=~x4+x5+x6
speed=~x7+x8+x9
'

fit<-cfa(mod, data = dat)

This returns the following solution:
> summary(fit)
lavaan (0.5-22) converged normally after  35 iterations

  Number of observations                           301

  Estimator                                         ML
  Minimum Function Test Statistic               85.306
  Degrees of freedom                                24
  P-value (Chi-square)                           0.000

Parameter Estimates:

  Information                                 Expected
  Standard Errors                             Standard

Latent Variables:
                   Estimate  Std.Err  z-value  P(>|z|)
  visual =~
    x1                1.000
    x2                0.554    0.100    5.554    0.000
    x3                0.729    0.109    6.685    0.000
  textual =~
    x4                1.000
    x5                1.113    0.065   17.014    0.000
    x6                0.926    0.055   16.703    0.000
  speed =~
    x7                1.000
    x8                1.180    0.165    7.152    0.000
    x9                1.082    0.151    7.155    0.000

Covariances:
                   Estimate  Std.Err  z-value  P(>|z|)
  visual ~~
    textual           0.408    0.074    5.552    0.000
    speed             0.262    0.056    4.660    0.000
  textual ~~
    speed             0.173    0.049    3.518    0.000

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .x1                0.549    0.114    4.833    0.000
   .x2                1.134    0.102   11.146    0.000
   .x3                0.844    0.091    9.317    0.000
   .x4                0.371    0.048    7.779    0.000
   .x5                0.446    0.058    7.642    0.000
   .x6                0.356    0.043    8.277    0.000
   .x7                0.799    0.081    9.823    0.000
   .x8                0.488    0.074    6.573    0.000
   .x9                0.566    0.071    8.003    0.000
    visual            0.809    0.145    5.564    0.000
    textual           0.979    0.112    8.737    0.000
    speed             0.384    0.086    4.451    0.000

When using raw data for input the lavPredict() and predict() return predicted values for the latent variables.
> head(lavPredict(fit))
          visual     textual       speed
[1,] -0.81767524 -0.13754501  0.06150726
[2,]  0.04951940 -1.01272402  0.62549360
[3,] -0.76139670 -1.87228634 -0.84057276
[4,]  0.41934153  0.01848569 -0.27133710
[5,] -0.41590481 -0.12225009  0.19432951
[6,]  0.02325632 -1.32981727  0.70885348

Running the same model with the covariance matrix as input returns the same results, but as the original poster notes yields an error when attempting to derive the factor scores.
> COV<-cov(dat)
> fit1<-cfa(mod, sample.cov = COV, sample.nobs = 301, sample.mean = colMeans(dat))
> lavPredict(fit1)
Error in lavPredict(fit1) :
  lavaan ERROR: sample statistics were used for fitting and newdata is empty

The solution is fairly straightforward as what the package needs is some raw data to "chew on" so to speak. Here you amend the code to identify the original dataset as raw data input for the prediction function (lavPredict(fit1, newdata = dat)). This returns the following (which remember is the same model fitted in lavaan but using the covariance matrix as input).
> head(lavPredict(fit1, newdata = dat))
          visual     textual       speed
[1,] -0.81767524 -0.13754501  0.06150726
[2,]  0.04951940 -1.01272402  0.62549360
[3,] -0.76139670 -1.87228634 -0.84057276
[4,]  0.41934153  0.01848569 -0.27133710
[5,] -0.41590481 -0.12225009  0.19432951
[6,]  0.02325632 -1.32981727  0.70885348

As you can see the results are identical.
Comment: Thank you, Matt.
But, what happens if you only have the cov matrix without the original raw data file.
Comment: Are you saying that you have the covariance matrix and an already fitted lavaan object (and/or model)? You just do not have the raw data that generate the covariance or the model?
Comment: this was common in the 70's as a way of avoiding printing massive tables to textbooks and reports -- sharing the cov matrix is common in psychometrics.

I think in this case you have to just sample from the model-implied matrices themselves.
Answer: A solution to this problem, can be to use the covariance matrix together with the mean and std devitation to create a simulation of the data. Then after testing that the simulated data follows your assumptions, you could run the analysis.
I have done this, to replicate papers that did not share their data.
I would do the following...
# Set your means and stddev
mu <- c(4.23, 3.01, 2.91)
stddev <- c(1.23, 0.92, 1.32)

Then get your correlation matrix and you will be able to get your covariance.
corMat <- matrix(c(1, 0.78, 0.23,
                   0.78, 1, 0.27,
                   0.23, 0.27, 1),
                 ncol = 3)
corMat

#Create the covariance matrix:
covMat <- stddev %*% t(stddev) * corMat
covMat

Now i will use MASS library to cast the mvrnorm function...
set.seed(1)
library(MASS)
dat1 <- mvrnorm(n = 1000, mu = mu, Sigma = covMat, empirical = FALSE)

Finally, you can use this to check if what you have done makes sense
colMeans(dat1)
cor(dat1)

If you are comfortable with this synthetic data, the next step will be to run your simulation.
I hope it helps someone!
Best,
J

How to predict factor scores in Lavaan


Adaboost Probabilities

Question: Adaboost prediction is the sign of the strong classifier. How can we obtain the probability of the prediction $P(y = 1 | x)$?
Can we use the logistic function or some other function as follows:
$$P(y = 1 | x) = \frac1{1+\exp(-F(x))}$$
where $F(x)$ is the strong classifier.
Comment: Why not use gradient boosting?  There is rarely a reason to use adaboost instead in 2018.
Comment: Do you mean gradient boosting with exponential loss function? In that case how to convert the score into probabilities?
Answer: You can do something similar, mathematically, but with a slightly different sigmoidal function to what you specified. To convert the output of AdaBoost
$$F(x) = \sum_{t=1}^T \alpha_t h_t (x)$$
to a conditional probability, you can pass it through the following sigmoidal:
$$\pi(x) = \frac{1}{1+e^{-2F(x)}}$$
(Source, including reasoning: Schapire-Freund Section 7.5.3.)
But beware: the probabilities will be inaccurate on small data sets because of the inherent assumptions of the AdaBoost model.

Adaboost Probabilities


How to intercept socket traffic on solaris?

Question: I'm not very familiar with Solaris, so maybe there are tools that I don't know about. I need to debug the communication between two components on the same machine, talking to each other using a normal TCP socket.
Now there seem to be two tools available, one known from linux called tcpdump, the other one being a solaris utility called snoop. Unfortunately, at the client's site, there are a lot of restrictions and whatnot, so using these tools is not allowed / possible.
So, what I figured is that I could change the listening port of the server process to something else and have a tool like netcat act as a proxy on the actual port while forwarding the traffic to the "real" server process, so I can dump the communication between those components.
Is there a tool that does this - preferably outputting a known format like tcpdump's? Or how else would you go about this?
Comment: Are you using Solaris 10 or later?
Comment: It's Solaris 10.
Answer: snoop is not an option anyway because it won't work for traffic between two processes on the same host.
DTrace is your best bet. For example, here is a script for capturing traffic between two processes on the same server in snoop format. However, this particular script relies on the internal workings of the kernel so it may or may not work with your version of Solaris 10.
Answer:
change the listening port of the server process to something else and have a tool like netcat

netcat will do the port forwarding - but not logging the info. However the suorce code is widely available - so if your C skills are up to it, it would be straightforward to add this in. If the prefer Perl - then there's several port forwarders written using that. There's a cpan module here.
If the data is travelling across a network and you have physical access to the network (at a point where the data is not encrypted) then you could use wireshark.
Comment: Unfortunately, this happens in a high-security environment, where (if even possible) it would not be allowed to have tools like wireshark around. +1 however on the CPAN link, maybe this could be used.
Comment: @Dave Vogt, I am still puzzling over why it's acceptable to write your own tool (potentially buggy, with unintended 0-day exploits, and no widespread code review) instead of using something open-source (like wireshark) to do presumably the exact same thing.


How to write custom action in install shield?

Question: I have a custom action that runs an executable file(which will be insatlled in the registry) only if that executable is not installed.
I want the executable to install every time when i run the MSI(over write the installed exe in the registry). Could any please provide the custom condition to do the same.
Currently i'm using the condition as: Not installed in the Install exe condition.
Answer: If you want for 'exe' file to be executed every time, just remove the condition.
If you want your 'exe' to be executed if that 'exe' is not been executed before, you can check the specific registry value and you can set a property accordingly and use that property in the condition.
Please elaborate the question to get the exact answer for your problem.


React and Zend Framework 3 layout

Question: I'm actually starting to use React and I want to integrate to my project that is made with ZF3.
I want to manage the layout of the project with React but i don't understand how manage the content of the templates since that content is on a variable of the layout named $content
Which is the best approach to solve this?
Answer: I was watching some videos of how to integrate react with php and I think that you would need to use zf3 as an api (It is supported using AbstractRestfulController)
React would run as an independent system and call zf3 api when it is needed via ajax

React and Zend Framework 3 layout


How does eigenvalues work with binary data in redundancy analysis?

Question: I am using the vegan package in R to do a redundancy analysis (RDA, a part of canonical correlation analysis). My response data is binary and my explanatory variables contains 0, 0.5 an 1. I get quite low eigenvalues (~0.05) and my question is how is the binary data affecting the eigenvalue? Will the variability always be 'badly' explained?
Comment: The economic value is not the same as the eigenvalue value. The eigenvalue is a semi major axis length from the hyperellipsoid. You can think of an economic value as a linear model coefficient multiplied by the central value of that term. The PCA tells you where your points are but doesn't necessarily deal well with variation in density. What that means is a low value for an eigenvalue isn't necessarily the whole story. It can be small and still strongly meaningful.
Answer: You don't explain if you do some normalization of the variables via scaling them, but it is completely normal to have the canonical variables around the 0.
The variability that they can explain depend on the data itself or the experiment. If the two datasets have low in common the CCA won't be able to explain it, or if it does it will be a false positive.


Given two related ratios within a population, derive a third ratio (eg. redheads, non-redheads, and skin cancer)

Question: If

People X are N times more likely to have attribute A than non-X
People X are P percent of the population

then

What percentage of A's are X?

Example (the numbers are just for illustration).
If

A redhead is 3 times more likely to get skin cancer than a non-redhead.
Redheads are 7% of the population.

Then
What percentage of skin cancer victims are redheads?
X = Is a Redhead, A = Suffer Skin cancer, N = 3, P = 7
Comment: This looks like self study - what have you attempted so far?
Comment: [Hint](https://en.wikipedia.org/wiki/Bayes%27_theorem). The answer is approx 22.5% off the top of my head.
Answer: I will go through the numerical example.
We are given: $\frac{P(C|R)}{P(C|\lnot R)}=3$ and $P(R)=0.07$. We need to find $P(R|C)$.
Bayes Theorem:
$P(C|R)= \frac{P(R|C)P(C)}{P(R)} \quad P(C|\lnot R)= \frac{P(\lnot R|C)P(C)}{P(\lnot R)} $
Dividing these terms will yield:
$ \frac{P(C|R)}{P(C|\lnot R)}= 3 =\frac{P(R|C)}{P(\lnot R|C)}\frac{P(\lnot R)}{P(R)}=\frac{P(R|C)}{1-P(R|C)}\frac{1-0.07}{0.07}$
Then, you can solve for $P(R|C)$.
Comment: Many thanks for a well worked answer, @Ozan! I've upvoted it, but will have to work through it to confirm before awarding the bounty. I'm broadly familiar with the mathematics you've presented here (which I trust is correct), but rusty. I'll try to finish this within 24 hours and award the bounty. It looks lovely!
Comment: @StephenHosking I hope it helps :)
Comment: Once again, thanks for the solution, for invoking Bayes Theorem (I had thought it was a purely algebraic problem), and for presenting it so elegantly. Bonus awarded!
Comment: Thank you. I am glad that it was useful for you.
Comment: My algebraic manipulation solving for P(R|C) comes up with P(R|C) = A / 1 - A, where A = 1-0.07 / 0.07. Which is 0.18. I'll have to check it a couple of times, and try on other examples fr.


How to get 2 digit year w/ Javascript?

Question: I am trying to find some javascript code that will write the current date in this format: mmddyy
Everything I have found uses 4 digit years and I need 2 digit.
Comment: here's one for your great grandchildren to fix someday `new Date().getFullYear() - 2000`
Comment: not a big fan of substring are ya
Comment: "I need 2 digit"... really? You would die without 2-digit years? On the contrary, 2 digit years are probably going to cause you a lot more pain.
Comment: May I suggest: http://stackoverflow.com/questions/13184067/get-date-using-javascript-in-this-format-mm-dd-yy
Comment: how did you research this?  see http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript?rq=1
Answer: The specific answer to this question is found in this one line below:

//pull the last two digits of the year
//logs to console
//creates a new date object (has the current date and time by default)
//gets the full year from the date object (currently 2017)
//converts the variable to a string
//gets the substring backwards by 2 characters (last two characters)
console.log(new Date().getFullYear().toString().substr(-2));

Formatting Full Date Time Example, Single Function (MMddyy):
JavaScript:

//A function for formatting a date to MMddyy
function formatDate(d)
{
    //get the month
    var month = d.getMonth();
    //get the day
    //convert day to string
    var day = d.getDate().toString().padStart(2, '0');
    //get the year
    var year = d.getFullYear();

    //pull the last two digits of the year
    year = year.toString().substr(-2);

    //increment month by 1 since it is 0 indexed
    //converts month to a string
    month = (month + 1).toString().padStart(2, '0');

    //return the string "MMddyy"
    return month + day + year;
}

var d = new Date();
console.log(formatDate(d));

Formatting Full Date Example, multiple functions (MMddyy):

// function getMonth with 1 parameter expecting date
// This function returns a string of type MM (example: 05 = May)
function getMonth(d) {
    //get the month
    var month = d.getMonth();

    //increment month by 1 since it is 0 indexed
    //converts month to a string
    //if month is 1-9 pad right with a 0 for two digits
    month = (month + 1).toString().padStart(2, '0');

    return month;
}

// function getDay with 1 parameter expecting date
// This function returns a string of type dd (example: 09 = The 9th day of the month)
function getDay(d) {
    //get the day
    //convert day to string
    //if day is between 1-9 pad right with a 0 for two digits
    var day = d.getDate().toString().padStart(2, '0');;

    return day;
}

// function getYear with 1 parameter expecting date
// This function returns the year in format yy (example: 21 = 2021)
function getYear(d) {
    //get the year
    var year = d.getFullYear();

    //pull the last two digits of the year
    year = year.toString().substr(-2);

    return year;
}

//A function for formatting a date to MMddyy
function formatDate(d)
{
    //return the string "MMddyy"
    return getMonth(d) + getDay(d) + getYear(d);
}

var d = new Date();
console.log(formatDate(d));

Answers for full browser support (Internet Explorer)
Formatting Full Date Time Example, Single Function (MMddyy): jsFiddle
JavaScript:

//A function for formatting a date to MMddyy
function formatDate(d)
{
    //get the month
    var month = d.getMonth();
    //get the day
    //convert day to string
    var day = d.getDate().toString();
    //get the year
    var year = d.getFullYear();

    //pull the last two digits of the year
    year = year.toString().substr(-2);

    //increment month by 1 since it is 0 indexed
    //converts month to a string
    month = (month + 1).toString();

    //if month is 1-9 pad right with a 0 for two digits
    if (month.length === 1)
    {
        month = "0" + month;
    }

    //if day is between 1-9 pad right with a 0 for two digits
    if (day.length === 1)
    {
        day = "0" + day;
    }

    //return the string "MMddyy"
    return month + day + year;
}

var d = new Date();
console.log(formatDate(d));

Formatting Full Date Example, multiple functions (MMddyy):

// function getMonth with 1 parameter expecting date
// This function returns a string of type MM (example: 05 = May)
function getMonth(d) {
    //get the month
    var month = d.getMonth();

    //increment month by 1 since it is 0 indexed
    //converts month to a string
    month = (month + 1).toString();

    //if month is 1-9 pad right with a 0 for two digits
    if (month.length === 1)
    {
        month = "0" + month;
    }

    return month;
}

// function getDay with 1 parameter expecting date
// This function returns a string of type dd (example: 09 = The 9th day of the month)
function getDay(d) {
    //get the day
    //convert day to string
    var day = d.getDate().toString();

      //if day is between 1-9 pad right with a 0 for two digits
    if (day.length === 1)
    {
        day = "0" + day;
    }

    return day;
}

// function getYear with 1 parameter expecting date
// This function returns the year in format yy (example: 21 = 2021)
function getYear(d) {
    //get the year
    var year = d.getFullYear();

    //pull the last two digits of the year
    year = year.toString().substr(-2);

    return year;
}

//A function for formatting a date to MMddyy
function formatDate(d)
{
    //return the string "MMddyy"
    return getMonth(d) + getDay(d) + getYear(d);
}

var d = new Date();
console.log(formatDate(d));
Comment: Downvote because won't work after year 10.000 (jk xD) Btw, easily fixed with `.slice(-2)`.
Comment: `slice(-2)` should be used even if you don't care about supporting >10000 dates as `.substr()` is deprecated
Comment: `var day = d.getDate().toString().padStart(2,"0");` no need for if statements...
Comment: If you are going for oneliners...

month = ("0" + (d.getMonth() + 1).toString()).substr(-2)
Comment: @Merovex or just `console.log(("0" + (new Date().getMonth() + 1).toString()).substr(-2) + ("0" + new Date().getDate().toString()).substr(-2) + new Date().getFullYear().toString().substr(-2))`
Comment: @Salketer that's really cool, IE doesn't support padStart so it isn't a global solution like the function above.  Also i'm sure padStart is doing a loop and probably something like an if statement so from a code complexity standpoint you aren't gaining much i'd wager.
Comment: Interesting... About complexity, padStart is 10 times less complex than a for loop. It is way easier to use and read. I'm sure you meant performance wise, then I'd assume it would be pretty much the same yes
Comment: @Salketer correct i was describing Cyclomatic complexity, it probably is easier to read.
Answer: Given a date object:
date.getFullYear().toString().substr(2,2);

It returns the number as string. If you want it as integer just wrap it inside the parseInt() function:
var twoDigitsYear = parseInt(date.getFullYear().toString().substr(2,2), 10);

Example with the current year in one line:
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(2,2));

Comment: For what purpose are you specifying the second parameter of the `substr()` method? Wouldn't it be simplier to use `date.getFullYear().toString().substr(2);`?
Comment: @Alexander Abakumov You are right, when you are working with years which don't exceed four digits ;) This comes from my defensive coding style.
Answer: var d = new Date();
var n = d.getFullYear();

Yes, n will give you the 4 digit year, but you can always use substring or something similar to split up the year, thus giving you only two digits:
var final = n.toString().substring(2);

This will give you the last two digits of the year (2013 will become 13, etc...)
If there's a better way, hopefully someone posts it! This is the only way I can think of. Let us know if it works!
Answer: var currentYear =  (new Date()).getFullYear();
var twoLastDigits = currentYear%100;

var formatedTwoLastDigits = "";

if (twoLastDigits <10 ) {
    formatedTwoLastDigits = "0" + twoLastDigits;
} else {
    formatedTwoLastDigits = "" + twoLastDigits;
}

Answer: another version:
var yy = (new Date().getFullYear()+'').slice(-2);

Comment: personal habit, different behavior with null/undefined and also performance
Comment: why not use toString() instead of adding an empty string?

`var yy = ((new Date().getFullYear().toString()).slice(-2);`

How to get 2 digit year w/ Javascript?


Can I use a separate pre-amp in my combo amp's effects loop?

Question: I'm curious, is it possible to use a preamp head in the effects loop of my combo amp?
The chain would be:
guitar -> combo amp in -> effects send to preamp -> preamp out to combo amp return -> power amp
Would it damage either the preamp or combo amp in such a combination?
Specifics: Can I use a Behringer Ultragain Pro Mic2200 preamp in the effects loop of a Fender Hot Rod Deluxe? (There are probably loads of tone related opinions about whether it should be done, but I'm just curious whether it can be done)
Comment: As long as the preamp in the loop has matching wattage and impendance you should be fine (I'm no pro, though). But why would you not just leave the combo's preamp out like this: guitar -> head preamp -> combo amp return -> cab. That way you'd only use the combo's cab, ignoring the comob's preamp.
Comment: Could you be more specific - what are the two units in question? Do you actually want to cascade the two preamps (internal and external)? What is a *"preamp head"* - is it a rack-mount preamp?
Comment: @jonrsharpe yes it is a rack-mount preamp and I do want to cascade them
Comment: What make/model of combo amp and preamp?
Comment: @jonrsharpe Fender combo, Behringer preamp, but does this really matter? Like I said, I'm just curious...
Comment: It's useful to know what kinds of inputs and outputs you're talking about; for example, FX loops sometimes have level selection (for e.g pedals vs. racks) and a rack-mount preamp will likely have several different levels of output (some specifically designed to run into a guitar amp, some not). You may find reading the user manuals will cover some of these connection options.
Comment: @jonrsharpe I see. It's a Fender Hot Rod Deluxe and a Behringer UltraGain Pro Mic2200
Answer: Yes, you can use that preamp in your combo's effects loop. The Fender Hot Rod Deluxe has a series (vs. parallel, so no blending for you), line-level FX loop over unbalanced connectors, which the Behringer UltraGain MIC2200 can certainly handle. You will have to set the UltraGain to LINE (vs. MIC) mode to use the jack input.
I would start with the UltraGain's OUTPUT control in the middle position (0dB, on a range of +/-20dB), and increase slowly at first. It can provide a significant boost, but note that this is in-line with other boost pedals (e.g. MXR Micro Amp provides +26dB). You will be driving the power amp tubes harder, which will provide a different tone to overdriving the preamp (as you would with a boost before the amp's input).


excluding phpmyadmin in htaccess

Question: Hi I have been searching and searching for how to get this to work and cannot figure out what is wrong.  I have tried many of the solutions that have been posted and still no luck.
I would appreciate any help.
My url is being redirected to a subdirectory.  However I can not prevent phpmyadmin from not getting redirected.  Below is what I have come up with my htaccess file.  What am I missing.
Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !^/redesign [NC]
RewriteRule ^ /redesign%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_URI} ^/phpmyadmin
RewriteRule ^.*$ - [NC,L]

Thanks.
Comment: yes this is the full htaccess rules i have
Answer: I didn't test this, but maybe you can try this:
UPDATE: changed RewriteCond
Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !^/redesign [NC]
RewriteCond %{REQUEST_URI} !^(/phpmyadmin)($|/)
RewriteRule ^ /redesign%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_URI} ^/phpmyadmin
RewriteRule ^.*$ - [NC,L]

You can have more than one RewriteConditions before the RewriteRule
Comment: Instead of `^.*$ -`, just put `^ -`
Comment: I tried both suggestions and I keep getting www.domain.com/redesign/phpmyadmin instead of www.domain.com/phpmyadmin
Comment: @hozdaman, nice to hear, what´s different? - the condition `($|/)` now also considers `phpmyadmin` without a trailing slash.

excluding phpmyadmin in htaccess


Como cria arquivo PDF do ZERO (sem frameworks)?

Question: Bem, estou analisando algumas possibilidades de gerar PDF's no Android (offline), e nenhuma é totalmente satisfatória, seja pela licença, funcionalidades, grande tamanho do framework, ou versão de suporte do Android (há o PdfDocument, que está disponível a partir da API 19 do Android, mas meu minTarget=14).
Então como estou necessitando até então é gerar um PDF simples, (quase que .txt, só texto, sem muita firula), só que uma exigência do cliente é que seja em PDF (clientes, sabem né). Então pensei em criar meu próprio PDF, a partir do source, só que pesquisei um bocado e não encontrei nada sobre templates do source de PDF's, por exemplo, como que tem que ser o header, como que se cria um paragrafo, etc. Só me aparece nas pesquisas frameworks, e mas frameworks.
Então gostaria de saber se alguém conhece algo e possa me mostrar um exemplo de criação do ZERO de um PDF, bem simples, com headers, um titulo e um paragrafo, e de bônus uma tabela (é a parte mais complexa do pdf que tenho que gerar), isso já estaria excelente.
E também como até onde conheço o PDF é da Adobe, então talvez possa ter algum problema ou licença em relação a isso.
Comment: Fernando, deu uma olhada no iText? http://www.vogella.com/tutorials/JavaPDF/article.html
Comment: @Guest, mas eu já até testei esse, só que ele além de ter um certo tamanho, [trabalha sobre licença AGPL](http://itextpdf.com/pricing), que não é o caminho que estou querendo seguir, já que, pretendia nem utilizar frameworks.
Comment: Andei procurando algumas aqui e, realmente, todas possuem algum tipo de licença. =( Não vi nenhuma de código aberto, para que você possa ver como funciona...
Comment: [pdfDocument](https://android.googlesource.com/platform/frameworks/base/+/cd92588/graphics/java/android/graphics/pdf/PdfDocument.java) Talvez você possa observar o próprio widget do Android e tentar desenvolver o seu, não?
Comment: @Guest, já tentei mas ele `extends` de outra `class` nativa é se eu estendo dela, não tenho acesso a alguns recursos, internal (não visíveis para fora do `package`). Dai não consigo implementar minha biblioteca baseado na PdfDocument.
Comment: @Guest, a algum tempo atrás até postei [essa questão aqui](http://pt.stackoverflow.com/questions/3029/api-de-suporte-a-pdfdocument-api-19-vers%C3%A3o-a-partir-da-api-14) mesmo no SOpt, mas não obtive sucesso e desisti da implementação.
Comment: isso é bem complicado. Até porquê seu cliente exige a API 14, mas a classe nativa do android só está disponível pra API19 (Patético) e ainda mais, todas as libs atuais são pagas! É... isso é bem chato. Eu vou estudar um pouco essas libs e, tentar, fazer alguma lib com uma licença totalmente open-source.
Comment: @Guest, sim, bem complicado, meus cliente já utilizam dispositivos com versão do Android 4.0 (API 14), atualmente desenvolvi para a primeira entrega os relatório em HTML, mais futuramente terei que migrar para PDF. Esperava que a própria Google fornecesse talvez uma API de suporte para versões anteriores, com uma copia do PdfDocument. O iText até já testei, e é bem bacana, funcionou bem nas minhas necessidades, só tem o problema da licença, que não é viável para o produto hoje.
Comment: Não tem como você tentar gerar os relatório para HTML e depois passar pra PDF?
Comment: Poderia ser uma boa até. Você gera o HTML no dispositivo, manda pra um servidor na WEB que vai receber, alterar para PDF, e mandar de volta já como PDF. O cliente não precisa saber disso... hahaha.
Comment: @Guest, até já vi, mas dai, é no servidor, e em meu caso tenho que gerar off-line, para mesmo off-line ele já ter acesso ao PDF, e poder enviar a uma impressora ou salvar em seus arquivos.
Comment: É. Realmente, complicou mesmo! Anyway, se eu achar alguma lib que seja útil pra você, eu mando aqui.
Comment: [PDFReader-Writer](https://github.com/bhavyahmehta/Pdf-Reader---Writer) Olha esse. Acho que *pode* ser o que você quer.
Comment: @Guest, vou dar uma olhada nessa lib e se der gol, posto um feed aqui. Valeu pela dica.
Comment: só um aviso, ela não é bem uma lib, está mais para um `app` que foi feito para isto. Acho que pode ser até melhor pra você, pois aí você pode fazer do seu jeito e com algumas alterações e etc. Boa sorte e abraços!
Answer: No que eu percebi em sua pergunta foi que você quer criar um pdf, mas sua api mínima é minTarget=14, uma ajuda é copia o source code de PdfDocument.java ou você pode fazer seu próprio código, mas pensando muito, percebo que você esta usando JAVA N-IDE, para que o projeto não fique muito pesado, recomendo que você copie apenas o necessário, alright!
vou te dar um exemplo:
<code>package android.graphics.pdf;

public class PdfDocument {
    // agora você pode adicionar algo aqui, exemplo: as variaveis:
    private final byte[] mChunk = new byte[4096];
    private final CloseGuard mCloseGuard = CloseGuard.get();
    private final List<PageInfo> mPages = new ArrayList<PageInfo>();
    private int mNativeDocument;
    private Page mCurrentPage;
}
</code>
e se caso haver uma variável que use uma classe que não exista, você pode fazer a mesma coisa, mas lembrando, copie apenas o necessário e também o que vai ser usado por outras funções.
Comment: Me desculpe pessoal, era porque minha conta estava sendo usada por meu amigo, porque ele havia perdido a conta dele.


I have got additional 30px to the position

Question: It is a copied code from an exercise, but I don't know why the header sets -30px beyond the right boarder of the viewport (doesn't happen on the video tutorial). I have tried applying 30px to the right, but it counts from 0 not from that additional pixels I got as a gift.
The Internet hasn't shown me any answers yet..
Please help.
As seen here it adds 30px on the right hand side, so the header (100% width) goes outside the viewport:
snapshot

@charset "UTF-8";
header {
  width: 100%;
  height: 88px;
  position: fixed;
  right: auto;
  padding: 15px;
  top: 0;
  left: 0;
  z-index: 5;
  background: #FF825C;
  box-shadow: 0px 2px 4px #EA6044;
  border-bottom-right-radius: 15px;
  border-bottom-left-radius: 15px;
}

header input {
  width: 100%;
  height: 50px;
  float: left;
  background: #FFA473;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  border-top-right-radius: 25px;
  border-bottom-right-radius: 25px;
  border: 0px;
  box-shadow: none;
  outline: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  -ms-appearance: none;
  -o-appearance: none;
  appearance: none;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>ToDoList app</title>
  <link rel="stylesheet" type="text/css" href="resources/css/reset.css">
  <link rel="stylesheet" type="text/css" href="resources/css/style.css">

    <input type="text" placeholder="Enter an activity...">
    <button type="button" name="button"></button>

Comment: Try to add the screenshots as edits in your original post instead of posting a separate answer with them (since it's not an answer it's adding to the question).
Comment: what is your expected output? can you add screenshots
Comment: I replied below.
Comment: Welcome to Stack Overflow!  You question goal is not clear. We don't know what you are trying to achieve, we just got a piece of code that works fine. Add a screenshot or something to help us to understand your problem. Please read about [How to Ask a Question](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) to learn how to write effective questions.
Comment: @teocci : It does not work in my browser, and in your website's part, 'run the code snippet', does not work neither. The header goes beyond the viewport (30px is added to the right position, so the width: 100% goes outside the viewport, as I said before.
Answer: That happens because you set the padding for all sides. Try to put right padding only and check:

@charset "UTF-8";
header {
    width: 98.5%;
    height: 88px;
    position: fixed;
    padding: 15px;
    top: 0;
    left: 0;
    z-index: 1;
    background: #FF825C;
    box-shadow: 0px 2px 4px #EA6044;
    border-bottom-right-radius: 15px;
    border-bottom-left-radius: 15px;
  }

  header input {
    width: 99.5%;
    height:50px;
    float: left;
    background: #FFA473;
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
    border-top-right-radius: 25px;
    border-bottom-right-radius: 25px;
    border: 0px;
    box-shadow: none;
    outline: none;
    -webkit-appearance: none;
    -moz-appearance: none;
    -ms-appearance: none;
    -o-appearance: none;
    appearance: none;
  }
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>ToDoList app</title>
    <link rel="stylesheet" type="text/css" href="resources/css/reset.css">
    <link rel="stylesheet" type="text/css" href="resources/css/style.css">

      <input type="text" placeholder="Enter an activity..."/>
      <button type="button" name="button"></button>

Comment: I actually need padding in all four directions. If I type them separately not in a general 'padding' it does the same.


kyverno pods stuck in crashloop

Question: Two of our three Kyverno pods keep getting stuck in crash loops.
State details in ArgoCD are:
back-off 5m0s restarting failed container=kyverno pod=kyverno-85b8ccfffd-7vb4t_kyverno(cf50fb6d-a1c2-4384-bdbf-bebe865daa73)

All I can find in the logs is:
panic: interface conversion: interface {} is nil, not string [recovered]
       panic: interface conversion: interface {} is nil, not string

goroutine 2254 [running]:
k8s.io/apimachinery/pkg/util/runtime.HandleCrash({0x0, 0x0, 0xc004736140?})
    firstname.lastname@example.com/pkg/util/runtime/runtime.go:56 +0xd7
panic({0x2f552e0, 0xc00158ee40})
    runtime/panic.go:884 +0x212

which does not clarify a whole lot. How do I resolve this?
Comment: It looks like kyerno is crashing. I would consider opening an issue in https://github.com/kyverno/kyverno/issues, because even if the ultimate cause turns out to be a configuration issue, you should be receiving a useful error message rather than a crash and a traceback.
Answer: As commented, please do open an issue in the Kyverno GitHub repo and provide reproduction steps including version, K8s platform, etc.

kyverno pods stuck in crashloop


photoshop CS4 javascript: Photoshop doesn't register "saved" after saveAs command

Question: I am making a wizard style script for people to quickly create formulaic slide images from text data files, I have two scripts one to create the images(as layers) from data and one to export the images as PNGs. to make this simple as possible for the user I'd like it to export all data and images into the same folder, so far I've manually saved the psd into the directory that I have the other data files and have the exporter check to see if the document is saved() and if it is to saveAs() all the images to the same directory, if not it throws a message alerting the user to save the document.
However this intermittent saving is not ideal, because the user must navigate twice to the same folder if they want to save the images in the same place, so I thought I'd make the slide creator script save the presave document before the user has the opportunity to make edits that way when they go to save their changes it will default to the same folder as the text data file.
the problem: when I run the script the saveAs works, saves a file, but then going to the export script it throws a message that the document hasn't been saved. Sure enough I look at the title tab and it doesn't have my filename and still has an * beside it
Comment: The `saveAs` method has an `asCopy` boolean parameter: `saveAs(saveIn [, options] [, asCopy] [, extensionType])` Is this set to false? If not, it could be saving the file as a copy without affecting the original (unsaved) document. It would help to show your code.
Comment: Thank you nullability, that was it exactly!
Answer: "Save As" normally saves a copy without affecting the original document. Try setting the asCopy parameter of the saveAs() method to false.
Answer: Thank you, nullability, it was the asCopy parameter that I was over looking in the documentation.
The asCopy parameter was set to true. My bad :(


How to find the Hilbert Adjoint operator of $T(f)(t)=\int_{0}^tf(s)\ ds$?

Question:
Possible Duplicate:
Finding the adjoint of an operator

Consider the vector space $C[0, 1]$ with inner product,
\begin{align*}
\langle f, g\rangle=\int_{0}^1f(t)g(t)\ dt.
\end{align*}
Let $T:C[0, 1]\rightarrow C[0, 1]$ the bounded linear operador given by,
\begin{align*}
T(f)(t)=\int_{0}^tf(s)\ ds.
\end{align*}
How can I find the Hilbert adjoint operator $T^*$ of $T$?
Answer: $\def\sp#1{\left\langle#1\right\rangle}$For $f,g \in C[0,1]$ we have
\begin{align*}
  \sp{Tf, g} &= \int_0^1 Tf(t)g(t)\,dt\\
             &= \int_0^1 \int_0^t f(s)\,ds \cdot g(t)\,dt\\
             &= \int_0^1 \int_s^1 f(s)g(t)\,dt\,ds\\
             &= \int_0^1 f(s)\int_s^1 g(t)\,dt\,ds\\
             &=: \sp{f, T^*g}
\end{align*}
with
$$ (T^*g)(s) = \int_s^1 g(t)\, dt, \qquad s \in [0,1] $$
Comment: It's Fubini. Both are the integral of $(s,t)\mapsto f(s)g(t)$ over $\{(s,t) \mid 0 \le s \le t \le 1\}$ (@Berci's triangle).
Comment: Ah, I see, integral over the triangle $(0,0)$, $(1,0)$, $(1,1)$.
Comment: Very interesting @martini, but I still have a doubt, how did you get the equality
\begin{align*}
\int_{0}^1\int_{0}^tf(s)ds\cdot g(t)\ dt=\int_{0}^1\int_{s}^1f(s)g(t)\ dt\ ds?
\end{align*}
Answer: We have
$$
(Tf)'=f \quad \forall\ f \in X:=C([0,1]).
$$
Using integration by parts we have, for every $f, g \in X$:
\begin{eqnarray}
\langle Tf,g\rangle &=&\int_0^1(Tf)(t)g(t)\,dt=\int_0^1(Tf)(t)(Tg)'(t)\,dt\\
&=&\left[(Tf)(t)(Tg)(t)\right]_0^1-\int_0^1(Tf)'(t)(Tg)(t)\,dt\\
&=&(Tf)(1)(Tg)(1)-\int_0^1(Tf)'(t)(Tg)(t)\,dt\\
&=&\int_0^1f(t)(Tg)(1)dt-\int_0^1f(t)(Tg)(t)\,dt\\
&=&\int_0^1f(t)[(Tg)(1)-(Tg)(t)]\,dt\\
&=&\langle f,T^*g\rangle,
\end{eqnarray}
where
$$
(T^*g)(t)=(Tg)(1)-(Tg)(t)=\int_0^1g(s)\,ds-\int_0^tg(s)\,ds=\int_t^1g(s)\,ds.
$$
Hence
$$
(T^*f)(t)=\int_t^1f(s)\, ds \quad \forall\ f \in X.
$$


Canonical way to convert Completable to Single?

Question: I have an RxJava Completable that I want to execute, then chain to a Single<Long>. I can write it like this:
return Completable.complete().toSingleDefault(0L).flatMap { Single.just(1L) }

but this seems unnecessarily complicated. I would have thought Completable#toSingle() would do the job, but if I write:
Completable.complete().toSingle { Single.just(1L) }

I get errors. Is there a missing function in Completable or am I overlooking something?
Comment: Please read the [Getting started](https://github.com/ReactiveX/RxJava#non-dependent).
Answer: You probably want to use the andThen opeator, which will subscribe to the source you send to it after the Completable completes.
return Completable.complete()
    .andThen(Single.just(1L))

As @akarnokd said, this is a case of non-dependent continuations.
In case of your source needing to be resolved at runtime, this would be a deferred-dependent continuation, and you'd need to defer it:
return Completable.complete()
    .andThen(Single.defer(() -> Single.just(1L)))

Comment: `andThen` will return whatever the combined function returns. In the example case, it's return `Single.just(1L)`, so you get a `Single` out of it.
Comment: @JohnyTex: unless you add an `onError` handler, the usual RxJava behavior will kick in. Depending on where it happens, your `andThen` won't be executed.
Comment: Actually that's not what I needed, but did point me in the right direction. What I need is the [deferred-dependent](https://github.com/ReactiveX/RxJava#deferred-dependent) continuation - I need the Single source to be evaluated at runtime, not assembly time, so `.andThen(Single.defer{lfmap.count()})`. I used `just(1)` as an example but in fact my Single source can't be evaluated until after the Completable has completed.
Comment: So what I want is something like this extension: `fun  Completable.thenSingle(singleSource: () -> Single): Single {
    return Single.defer(singleSource)
}` so I can write `.thenSingle{lfmap.count()}`
Comment: Cool, glad it helped. Edited my answer for the sake of completeness (pun intended)
Comment: Single.just(Unit) is fine if you use Kotlin
Comment: `andThen` returns a Completable, so I don't understand how you have changed a `Completable` into a `Single`
Comment: Thank you, that is true! I had an issue where `.andThen { Single.just(Result.success()) }` still returned a completable, for some reason it was using `public final Completable andThen(CompletableSource next)`
Comment: What happens onError?


How to check that jQuery methods (fadeOut, hide, etc) have been called with Jasmine

Question: I'm trying to clean up my Javascript by employing the same TDD methods that work for me in Ruby, but the jump to Jasmine has been throwing me for a curve.
For a simple example, I'd like to specify that a given element fades out on click:
$('.position-details').live 'click', ->
  $this = $(this)
  $this.fadeOut 'fast', ->
    $this.closest('.fields').find('.position-search').fadeIn('fast').focus()

My specs:
describe "Position picker", ->
  beforeEach ->
    loadFixtures("position_picker.html")
    @details = $('.position-details')
    @picker = $('.position-picker')
    jasmine.Clock.useMock()

  it "the position details are initially shown", ->
    expect(@details).toBeVisible()

  describe "when the position details are clicked", ->
    it "fades out the position details", ->
      @details.trigger('click')
      jasmine.Clock.tick(1000)
      expect(@details).not.toBeVisible()

My fixture:

  Position*

  <input class="position-search" type="text" />

    <input class="position_id" type="text" />

The first spec passes and I'm not sure why the second doesn't. Once I get a few of these under my belt I'm sure it'll feel second nature. Thanks for any help or advice!
Comment: Why you wanna test that the element is invisible. Your code is not liable for this, but jquery. So if there is a bug in jquery your test will fail, even if your code is correct. All you should test is that on click the function are called to your element.
Comment: Thanks for your help. I don't want to test that jquery works, but that I've written code that calls fadeOut, because the element is supposed to fade. I imagine that semantically I'm not testing this the correct way, but I can't find examples of the way I _should_ be testing this. My code is liable to call fadeOut if it's supposed to fade still. There's just a different way to do this I'm not getting and it isn't the code above.
Comment: Take look at this SO: http://stackoverflow.com/a/8526477/184883 and this blog post http://tinnedfruit.com/2011/04/26/testing-backbone-apps-with-jasmine-sinon-3.html
Comment: @AndreasKöberle this comment is so helpful. If you reword this as an answer I will accept it. It truly is the solution.
Answer: You can use spyOn
check this:

it("fades out the element", function() {
  spyOn($.fn, 'fadeOut');
  fadeOutElem();
  expect($.fn.fadeOut).toHaveBeenCalled();
});

Also you can use a timeout like this:

it("fades out the element", function(done) {
  fadeOutElem();
  setTimeout(300, function() {
    expect($(".position-details").css('display').toEqual('none');
    done();
  });
});
Answer: Take look at this SO and this blog post


android: handover sms to default application

Question: Please guide, in Android how can I pass my string (less then 160 char) to the default built-in SMS applicaion or queue, which will complete the process.
I mean, from my activity I want to call a built-in SMS application and pass my SMS string to that, then the built-in application will be responsible to rest of activity like SMS resending, etc.
Comment: Perhaps you could **accept** some answers ?
Answer: To call the default sms application, with sms body and phone number :
Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( "sms:" + phoneNumber ) );
intent.putExtra( "sms_body", smsBody );
context.startActivity( intent );

By default I mean the application chosen by the user. Actually it's better to start the default sms application than the built-in because you have to respect the user choice. If the device owner has chosen ChompSms as default SMS application, he will prefer your application launches ChompSms and not an other.
Comment: I do not see where that is documented in the SDK. Got a link? If it is not documented, it will not be reliable -- device manufacturers might replace the SMS application and not respond to this Intent, for example.
Comment: I found that in google groups (http://groups.google.com/group/android-developers/browse_thread/thread/2bc997d602d4bb4a).
It's working well on my samsung galaxy.
Answer: To call the default sms application, with sms body and phone number :
Uri uri = Uri.parse("smsto:123456789");
    Intent it = new Intent(Intent.ACTION_SENDTO, uri);
    it.putExtra("sms_body", "The Hello How R U...");
    startActivity(it);

Answer: Beyond Thomas' answer, you can use ACTION_SEND and createChooser() to allow the user to pick the application with which to send your message, whether that be the built-in SMS application or a third-party SMS application or email or GMail or Twidroid or whatever.
You can also use SmsManager to send the SMS yourself, but that will not pop up any built-in activity.
With luck, there is a spot in the documentation that covers Thomas's answer (elsewhere in this StackOverflow page), as that is the simplest solution to your request.
Comment: OK. Use SmsManager, as I wrote above.
Comment: Does ACTION_SEND launch the sms application and wait for user to click "send" or direct send the SMS ? (SMS or mail or tweet...)
Comment: If you do not specify a destination, it will definitely wait, because it needs a number. The question does not state that the code has an SMS phone number.
Comment: ??????????
I dont want to launch that default or buildin application, I want to pass message body, phonenumer else to that application who must sent my sms directly without need user to click send (should not open any other interface)

can i put my sms in system sms queue for sending?