问:
I'm getting disconnected from ble connection status = 22 using bluetooth-nativescript plugin from Eddy Verbruggen
I have a button with 3 stages cycle, where I can start a fan, boost it, or turn it off, while I'm subscribed to notifications to check its current speed. The issue is when I try to turn on/off the fan, I get this status message:
    MyGattCallback.onConnectionStateChange, status: 22, new state: 0
I lose my ble connection with the device, and can't seem to find a proper solution to reconnect it.
Can you help understanding why is it happening and how can I fix this?
Thanks </p>

```<code>function startBtn(args) {
    const button = args.object;
    const page = button.page;
    const frame = page.frame;

    if (index === undefined) {
        if(!isNotifyOn){
            isLoaded = true;
            readFan();
            isNotifyOn = true;
        }

        ble.write({
            peripheralUUID: global.peripheral.UUID,
            serviceUUID: 'd8b5a80c-17c5-11e8-b642-0ed5f89f718b',
            characteristicUUID: 'd8b5aa1e-17c5-11e8-b642-0ed5f89f718b',
            value: '0x01'

        }).then((result) => {
            index = "BOOST";
            console.log("LIGA TE!" + result);

        }, function (err) {
            console.log("write error: " + err);
        });
    } else if (index === "BOOST") {

        ble.write({
            peripheralUUID: global.peripheral.UUID,
            serviceUUID: 'd8b5a80c-17c5-11e8-b642-0ed5f89f718b',
            characteristicUUID: 'd8b5aa1e-17c5-11e8-b642-0ed5f89f718b',
            value: '0x01'

        }).then((result) => {
            index = "OFF";
            console.log("BOOST!" + result);

        }, function (err) {
            console.log("write error: " + err);
        });
    } else {
        stopNotify();
        isLoaded = false;
        isNotifyOn = false;
        index = undefined;
        ble.write({
            peripheralUUID: global.peripheral.UUID,
            serviceUUID: 'd8b5a80c-17c5-11e8-b642-0ed5f89f718b',
            characteristicUUID: 'd8b5aa1e-17c5-11e8-b642-0ed5f89f718b',
            value: '0x00'

        }).then((result) => {

            console.log("DESLIGA TE!" + result);

        }, function (err) {
            console.log("write error: " + err);
        });
    }

}

function stopNotify() {

    ble.stopNotifying({
        peripheralUUID: global.peripheral.UUID,
        serviceUUID: 'd8b5ac12-17c5-11e8-b642-0ed5f89f718b',
        characteristicUUID: 'd8b5ae06-17c5-11e8-b642-0ed5f89f718b'
    }).then(function () {
        console.log("STOP@!@@@@@@@@@@@@@@@@");
    }, function (err) {
        console.log("unsubscribe error: " + err);
    });

}

function readFan() {

            ble.startNotifying({
            peripheralUUID: global.peripheral.UUID,
            serviceUUID: 'd8b5ac12-17c5-11e8-b642-0ed5f89f718b',
            characteristicUUID: 'd8b5ae06-17c5-11e8-b642-0ed5f89f718b',
            onNotify: function (result) {
                var data = new Uint8Array(result.value);
                var valuePerMinute = convert(data);
                var valuePerSecond = convertToLS(valuePerMinute);

                source.set("currentValue", valuePerSecond);
                console.log("readFan");
            }
        }).then(function () {

            console.log("subscribed for notifications");

        }, function (err) {
            console.log("notification error: " + err);

        });

}

 bluetooth.connect({
                UUID: peri.UUID,
                onConnected: function (_peripheral) {

                    var navigationEntry2 = {
                        moduleName: "tab-view/tab-view",
                        context: {
                            peripheral: peri
                        },
                        animated: true,
                        transition: {
                            name: "slide",
                            duration: 300,
                            curve: "ease"
                        }
                    };
                    var topmost = frameModule.topmost();
                    topmost.navigate(navigationEntry2);
                },
                onDisconnected: function (_peripheral) {

                    reconnectBle();

                    console.log("Periperhal disconnected with UUID: " + _peripheral.UUID);
                }
            });

        }

    };

function reconnectBle(){
        bluetooth.connect({
            UUID: _peripheral.UUID,
            onConnected: function (_peripheral) {

              console.log("reconnected to "+ _peripheral.UUID);
            },
            onDisconnected: function (_peripheral) {

                reconnectBle();

                console.log("Periperhal disconnected with UUID: " + _peripheral.UUID);
            }
        });

    }

</code>```

答: Try putting a setTimeout(reconnectBle, 0). Many (all?) BLE callbacks require the ability to complete before another BLE request is made. Here, you are attempting to fire a BLE request in the callback handler for onDisconnected. By using a setTimeout, the callback thread will be allowed to complete, then the reconnect can start in the appropriate context.

Body:
I have a button with 3 stages cycle, where I can start a fan, boost it, or turn it off, while I'm subscribed to notifications to check its current speed. The issue is when I try to turn on/off the fan, I get this status message:
    MyGattCallback.onConnectionStateChange, status: 22, new state: 0
I lose my ble connection with the device, and can't seem to find a proper solution to reconnect it.
Can you help understanding why is it happening and how can I fix this?
Thanks

function startBtn(args) {
    const button = args.object;
    const page = button.page;
    const frame = page.frame;

    if (index === undefined) {
        if(!isNotifyOn){
            isLoaded = true;
            readFan();
            isNotifyOn = true;
        }

        ble.write({
            peripheralUUID: global.peripheral.UUID,
            serviceUUID: 'd8b5a80c-17c5-11e8-b642-0ed5f89f718b',
            characteristicUUID: 'd8b5aa1e-17c5-11e8-b642-0ed5f89f718b',
            value: '0x01'

        }).then((result) => {
            index = "BOOST";
            console.log("LIGA TE!" + result);

        }, function (err) {
            console.log("write error: " + err);
        });
    } else if (index === "BOOST") {

        ble.write({
            peripheralUUID: global.peripheral.UUID,
            serviceUUID: 'd8b5a80c-17c5-11e8-b642-0ed5f89f718b',
            characteristicUUID: 'd8b5aa1e-17c5-11e8-b642-0ed5f89f718b',
            value: '0x01'

        }).then((result) => {
            index = "OFF";
            console.log("BOOST!" + result);

        }, function (err) {
            console.log("write error: " + err);
        });
    } else {
        stopNotify();
        isLoaded = false;
        isNotifyOn = false;
        index = undefined;
        ble.write({
            peripheralUUID: global.peripheral.UUID,
            serviceUUID: 'd8b5a80c-17c5-11e8-b642-0ed5f89f718b',
            characteristicUUID: 'd8b5aa1e-17c5-11e8-b642-0ed5f89f718b',
            value: '0x00'

        }).then((result) => {

            console.log("DESLIGA TE!" + result);

        }, function (err) {
            console.log("write error: " + err);
        });
    }

}

function stopNotify() {

    ble.stopNotifying({
        peripheralUUID: global.peripheral.UUID,
        serviceUUID: 'd8b5ac12-17c5-11e8-b642-0ed5f89f718b',
        characteristicUUID: 'd8b5ae06-17c5-11e8-b642-0ed5f89f718b'
    }).then(function () {
        console.log("STOP@!@@@@@@@@@@@@@@@@");
    }, function (err) {
        console.log("unsubscribe error: " + err);
    });

}

function readFan() {

            ble.startNotifying({
            peripheralUUID: global.peripheral.UUID,
            serviceUUID: 'd8b5ac12-17c5-11e8-b642-0ed5f89f718b',
            characteristicUUID: 'd8b5ae06-17c5-11e8-b642-0ed5f89f718b',
            onNotify: function (result) {
                var data = new Uint8Array(result.value);
                var valuePerMinute = convert(data);
                var valuePerSecond = convertToLS(valuePerMinute);

                source.set("currentValue", valuePerSecond);
                console.log("readFan");
            }
        }).then(function () {

            console.log("subscribed for notifications");

        }, function (err) {
            console.log("notification error: " + err);

        });

}

 bluetooth.connect({
                UUID: peri.UUID,
                onConnected: function (_peripheral) {

                    var navigationEntry2 = {
                        moduleName: "tab-view/tab-view",
                        context: {
                            peripheral: peri
                        },
                        animated: true,
                        transition: {
                            name: "slide",
                            duration: 300,
                            curve: "ease"
                        }
                    };
                    var topmost = frameModule.topmost();
                    topmost.navigate(navigationEntry2);
                },
                onDisconnected: function (_peripheral) {

                    reconnectBle();

                    console.log("Periperhal disconnected with UUID: " + _peripheral.UUID);
                }
            });

        }

    };

function reconnectBle(){
        bluetooth.connect({
            UUID: _peripheral.UUID,
            onConnected: function (_peripheral) {

              console.log("reconnected to "+ _peripheral.UUID);
            },
            onDisconnected: function (_peripheral) {

                reconnectBle();

                console.log("Periperhal disconnected with UUID: " + _peripheral.UUID);
            }
        });

    }


来源: stackexchange

问:
When I click on the button the hidden content doesn't show, why is this?
I am trying create a read more read less button. My content that is hidden is in a span tag. I used some javascript to make this work. Currently, when I click on the button nothing happens. My goal is to create a news section that shows more news when you click on the button.

This was working for me before, I used the exact same code and just merged it with some other code and it stopped working.

     $(document).ready(function () {

 var windowHeight = window.innerHeight;

 var navOpen = false;
 var onCloseBtn = false;
 var onAccordian = false;

 $("#hamburger").mouseover(function(){
  if(!navOpen){
   openMenu();
  }
  onCloseBtn = true;
 });

 $("#hamburger").mouseout(function(){
  onCloseBtn = false;
 });

 $("#hamburger").click(function(){
  toggleNav();
  console.log("clickedHam");
 });

 $("#navMenu").mouseover(function(){
  if(!navOpen && !onCloseBtn){
   keepOpen();
  }
 });

 $("#activeSpace").mouseleave(function(){
   console.log("navMenu Mouseout");
   closeMenu();
 });

 function toggleNav(){
  if(navOpen){
   closeMenu();

  } else {
   openMenu();
  }
 }
 function keepOpen(){
  console.log("keepOpen");
  navOpen = true;
  $('#hamburger').html('×');
  $('#hamburger').css("color","black");
  $("#navMenu").css("visibility","visible");
  $("#navMenu").css("height","auto");
  $("#navMenu").css("max-height", windowHeight);
 }

 function openMenu(){
  console.log("open");
  navOpen = true;
  $('#hamburger').html('×');
  $('#hamburger').css("color","black");
  $("#navMenu").css("visibility","visible");
  $("#navMenu").css("max-height", "250px"); ///change this depending on the max
 }

 function closeMenu(){
  closePanels();
  navOpen = false;
  console.log("close")
  $('#hamburger').html('☰');
  $('#hamburger').css("color","white");
  $("#navMenu").css("max-height", "0");
  $("#navMenu").css("visibility","hidden");
 }

 $(document).on('scroll', function() {
  if($(this).scrollTop()>=$('#changeNavColor').position().top - 40 && !navOpen){
   $(hamburger).css("color","black");
  }
  if($(this).scrollTop()<$('#changeNavColor').position().top - 40 && !navOpen){
   $(hamburger).css("color","white");
  }
 });

 var acc = document.getElementsByClassName("mobile-accordian");
 var i;

 for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
   //this.classList.toggle("active");
   $("#navMenu").css("height","auto");
   $("#navMenu").css("max-height", windowHeight);

   var panel = this.nextElementSibling;
   if (panel.style.maxHeight) {
    panel.style.maxHeight = null;
   } else {
     panel.style.maxHeight = panel.scrollHeight + "px";
   }
  });
 }

 function closePanels() {
  var panels = document.getElementsByClassName("mobile-accordian-panel");
  var j;

  for (j = 0; j < panels.length; j++){
   panels[j].style.maxHeight = null;
  }
 }

function toggleNewsButton() {
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (!moreText.style.display || moreText.style.display === "none") {
    btnText.innerHTML = "Read less";
    moreText.style.display = "block";
  } else {
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  }
}

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>     html, body{
  width: 100%;
  height: 100%;
  font-family: 'Roboto', sans-serif;
 }

 h1{
  font-size: 3em;
 }
 h2{
  font-size: 1.5em;
 }

 h3{
  font-size: 0.75em;
  font-weight:400;
  text-transform: uppercase;
 }

 .FullsizeImg{
  background-repeat: no-repeat;
  background-size: 30%;
  background-position: right;

 }
 #more {
   display: none;
 }

 #myBtn {
   color: black;
   background: #fff;
   border: 1px solid black;
   font-size: 17px;
   padding: 7px 12px;
   font-weight: normal;
   margin: 6px 0;
   margin-right: 12px;
 }

 .centerButton {
   text-align: center;
 }

 #myBtn:hover,
 #myBtn:active {
   background: black;
   color: white;
 }

 .allStories{
  margin-left:20px;
  margin-right:20px;
 }

 #hamburger{
  z-index: 11;
  display: block;
  visibility: visible;
  position: fixed;
  top: 10px;
  left: 10px;
  color: white;
  transition: all 0.25 ease;
 }

 #closeBtn{
  display:block;
  position:fixed;
  top:10px;
  left:10px;
 }

 #navMenu{
  z-index: 10;
  display: block;
  overflow:hidden;
  position: fixed;
  top: 0;
  left: 0;
  color: black;
  background-color: white;
  box-shadow: 0 0 8px rgba(33,33,33,.6);
  max-height: 0;
  width: 100%;
  -webkit-transition: 1s ease;
  -moz-transition: 1s ease;
  -o-transition: 1s ease;
  -ms-transition: 1s ease;
  transition: 1s ease;
  visibility: hidden;
 }

 .nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
 }

 .nav ul li {
  color: grey;
  font-size: 14px;
  font-weight: regular;
  font-family: inherit;
  padding: 5px 0px 5px 0px;
  cursor: pointer;
  transition: .5s ease;
  -webkit-transition: .5s ease;
  -moz-transition: .5s ease;
 }

 .nav li:hover {
  color: lightgrey;
  font-weight: bold;
  transition: .5s ease;
  -webkit-transition: .5s ease;
  -moz-transition: .5s ease;
 }

 .mainMargins{
  margin-left: 10%;
  margin-right: 10%;
 }

 .smallSpacer{
  height: 25px;
 }

 .bigSpacer{
  height: 100px;
 }

 .txtAlignRight{

 }

 .AlwaysFullScreen{
  width: 100%;
  height: 100%;
 }

 .fullScreen{
  width: 100%;
  height: 100%;
 }

 .withBGImg{
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
 }

 .jumbo-title{
  font-weight: bold;
  letter-spacing: 0.02em;
 }

 .jumbo-caption{
  font-weight: 300;
  font-size:
 }

 .jumbo-container{
  color: white;
 }

 .verticalCentreParent{
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
 }

 .verticalCentreChild{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }

 .content-verticalCentreParent{
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
 }

 .content-verticalCentreChild{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }

 .iconContainer{
  text-align: center;
 }
 .mediumIcons{
  height: 100px;
 }

 .scrollCard{
  box-shadow: 0 0 8px rgba(33,33,33,.2);
  width: 200px;
  height: 250px;
  border-radius: 10px;
  -webkit-transition: .3s ease;
  -moz-transition: .3s ease;
  -o-transition: .3s ease;
  -ms-transition: .3s ease;
  transition: .3s ease;
 }

 .scrollCard:hover{
  box-shadow: 0 0 11px rgba(33,33,33,.5);
 }

 .scrollCardBar {
  display: flex;
  min-width: 100%;
  min-height: 200px;
  overflow-x: auto;
  margin: 0;
 }

 .scrollCard {
  min-width: 300px;
  margin: 8px;
 }
 .scrollCardContainer{
  display: flex;
  margin-left: 10%;
  margin-right: 10%;
 }

 .scrollCardBar::-webkit-scrollbar {
  display: none;
 }

 .endOfScroll{
  width: 100px;
 }

 .line{
  margin-top: 10px;
  margin-bottom: 35px;
  background-color: white;
  height: 1px;
 }

 footer{
  height: auto;
  background-color: #5388EF;
  color: white;
   width: 100%;
   position: relative;
 }

 footer ul{
  font-weight: 300;
  list-style-type: none;

  margin-top: 20px;
  padding: 0;
 }

 footer li{
  padding: 10px 0px 5px 0px;
 }

 footer .row{
  margin: auto;
 }

 footer .footer-column{
  width: calc(100% / 6);
    height: auto;
    float: left;
    box-sizing: border-box;
   -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  padding: 0px 20px 20px 20px;
  margin-top: 20px;
 }

 @media only screen and (min-width: 2000px){
  .mainMargins{
   margin-left: 25%;
   margin-right: 25%;
  }
  .scrollCardContainer{
   margin-left: 25%;
   margin-right: 25%;
  }
 }

 @media only screen and (max-height: 1000px){
  .fullScreen{
   height: auto;
   width: auto;
  }

  .content-verticalCentreChild{
   position: relative;
   top: 100%;
   transform: none;
  }
 }

 @media only screen and (max-width: 1400px) {
  footer .footer-column{
   width: calc(100% / 3);
  }
 }

 @media only screen and (max-width: 600px) {
  h1{
   font-size: 2em;
  }

  h2{
   font-size: 1em;
  }

  #hamburger{
   top: 5px;
  left: px;
  }

  .mobile-accordian-panel{
  max-height: 0;
  overflow: hidden;
  -webkit-transition: .3s ease;
  -moz-transition: .3s ease;
  -o-transition: .3s ease;
  -ms-transition: .3s ease;
  transition: .3s ease;

  }

  .mainMargins{
   margin-left: 8%;
   margin-right: 8%;
  }

  .content-verticalCentreChild{
   position: relative;
   top: 100%;
   transform: none;
  }
  .scrollCardContainer{
   margin-left: 8%;
   margin-right: 8%;
  }
  .endOfScroll{
   width: 16px;
  }
  footer .footer-column{
   width: 100%
  }

 }</code>```

<!DOCTYPE html>

   <title></title>

<meta charset="utf-8" />

 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link rel="stylesheet" href="/css/style.css">

<meta name="viewport" content="width=device-width, initial-scale=1" />

  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700&display=swap" rel="stylesheet">

   ☰

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Title

About

Mission

Services

Social

Title

About

Mission

Services

Catchy Headline That Spans Multiple Lines

Headline Caption (Optional)

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

 Meet Our Reseachers

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

        A groundbreaking blueprint for store-program computers. Though a complete version of the ACE was never built, its concept has been used as a model by tech corporations worldwide for several years

        He first addressed the issue of artificial intelligence in his 1950 paper, "Computing machinery and intelligence". If an AI can convice a human that is it human, it should be considered intelligent.

        The highest acheivable award in the field of computer science. Named after Alan Turing for his grand contributions and is equivalent to the Noble Prize.

 News

 Read the Storie’s of sTTARR’s reseachers and users.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

 All Stories

Jan, 01, 2019

          Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

      Title of the news article will be diplayed under the photo.

Jan, 01, 2019

      Title of the news article will be diplayed under the photo.

Jan, 01, 2019

    Title of the news article will be diplayed under the photo.

Jan, 01, 2019

  Title of the news article will be diplayed under the photo.

 <button onclick="toggleNewsButton()" id="myBtn">Read more</button>

 Updates

 Here is a live twitter update.Here is a live twitter update.Here is a live twitter update.Here is a live twitter update.

        Tweets from UHN

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

```

EXPECTED: button should show the information in the read more tag.

ACTUAL: button doesn't do anything when you click it.

答:
This should do it. This also needed changing:

```<code>if (readmore.style.display === "none") {
</code>```

to

```<code>if (moreText.style.display === "none") {
</code>```

function toggleNewsButton() {
  var readmore = document.getElementById("readmore");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (moreText.style.display === "none") {
    readmore.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    readmore.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#more {
  display: none;
}

#myBtn {
  color: black;
  background: #fff;
  border: 1px solid black;
  font-size: 17px;
  padding: 7px 12px;
  font-weight: normal;
  margin: 6px 0;
  margin-right: 12px;
}

.centerButton {
  text-align: center;
}

#myBtn:hover,
#myBtn:active {
  background: black;
  color: white;
}</code>```

 All Stories

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

          Title of the news article will be diplayed under the photo.

Jan, 01, 2019

          Title of the news article will be diplayed under the photo.

Jan, 01, 2019

          Title of the news article will be diplayed under the photo.

    <button onclick="toggleNewsButton()" id="myBtn">Read more</button>

```

ContentLicense: CC BY-SA 4.0

Body:
I am trying create a read more read less button. My content that is hidden is in a span tag. I used some javascript to make this work. Currently, when I click on the button nothing happens. My goal is to create a news section that shows more news when you click on the button.

This was working for me before, I used the exact same code and just merged it with some other code and it stopped working.

     $(document).ready(function () {

 var windowHeight = window.innerHeight;

 var navOpen = false;
 var onCloseBtn = false;
 var onAccordian = false;

 $("#hamburger").mouseover(function(){
  if(!navOpen){
   openMenu();
  }
  onCloseBtn = true;
 });

 $("#hamburger").mouseout(function(){
  onCloseBtn = false;
 });

 $("#hamburger").click(function(){
  toggleNav();
  console.log("clickedHam");
 });

 $("#navMenu").mouseover(function(){
  if(!navOpen && !onCloseBtn){
   keepOpen();
  }
 });

 $("#activeSpace").mouseleave(function(){
   console.log("navMenu Mouseout");
   closeMenu();
 });

 function toggleNav(){
  if(navOpen){
   closeMenu();

  } else {
   openMenu();
  }
 }
 function keepOpen(){
  console.log("keepOpen");
  navOpen = true;
  $('#hamburger').html('×');
  $('#hamburger').css("color","black");
  $("#navMenu").css("visibility","visible");
  $("#navMenu").css("height","auto");
  $("#navMenu").css("max-height", windowHeight);
 }

 function openMenu(){
  console.log("open");
  navOpen = true;
  $('#hamburger').html('×');
  $('#hamburger').css("color","black");
  $("#navMenu").css("visibility","visible");
  $("#navMenu").css("max-height", "250px"); ///change this depending on the max
 }

 function closeMenu(){
  closePanels();
  navOpen = false;
  console.log("close")
  $('#hamburger').html('☰');
  $('#hamburger').css("color","white");
  $("#navMenu").css("max-height", "0");
  $("#navMenu").css("visibility","hidden");
 }

 $(document).on('scroll', function() {
  if($(this).scrollTop()>=$('#changeNavColor').position().top - 40 && !navOpen){
   $(hamburger).css("color","black");
  }
  if($(this).scrollTop()<$('#changeNavColor').position().top - 40 && !navOpen){
   $(hamburger).css("color","white");
  }
 });

 var acc = document.getElementsByClassName("mobile-accordian");
 var i;

 for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
   //this.classList.toggle("active");
   $("#navMenu").css("height","auto");
   $("#navMenu").css("max-height", windowHeight);

   var panel = this.nextElementSibling;
   if (panel.style.maxHeight) {
    panel.style.maxHeight = null;
   } else {
     panel.style.maxHeight = panel.scrollHeight + "px";
   }
  });
 }

 function closePanels() {
  var panels = document.getElementsByClassName("mobile-accordian-panel");
  var j;

  for (j = 0; j < panels.length; j++){
   panels[j].style.maxHeight = null;
  }
 }

function toggleNewsButton() {
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (!moreText.style.display || moreText.style.display === "none") {
    btnText.innerHTML = "Read less";
    moreText.style.display = "block";
  } else {
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  }
}

});

     html, body{
  width: 100%;
  height: 100%;
  font-family: 'Roboto', sans-serif;
 }

 h1{
  font-size: 3em;
 }
 h2{
  font-size: 1.5em;
 }

 h3{
  font-size: 0.75em;
  font-weight:400;
  text-transform: uppercase;
 }

 .FullsizeImg{
  background-repeat: no-repeat;
  background-size: 30%;
  background-position: right;

 }
 #more {
   display: none;
 }

 #myBtn {
   color: black;
   background: #fff;
   border: 1px solid black;
   font-size: 17px;
   padding: 7px 12px;
   font-weight: normal;
   margin: 6px 0;
   margin-right: 12px;
 }

 .centerButton {
   text-align: center;
 }

 #myBtn:hover,
 #myBtn:active {
   background: black;
   color: white;
 }

 .allStories{
  margin-left:20px;
  margin-right:20px;
 }

 #hamburger{
  z-index: 11;
  display: block;
  visibility: visible;
  position: fixed;
  top: 10px;
  left: 10px;
  color: white;
  transition: all 0.25 ease;
 }

 #closeBtn{
  display:block;
  position:fixed;
  top:10px;
  left:10px;
 }

 #navMenu{
  z-index: 10;
  display: block;
  overflow:hidden;
  position: fixed;
  top: 0;
  left: 0;
  color: black;
  background-color: white;
  box-shadow: 0 0 8px rgba(33,33,33,.6);
  max-height: 0;
  width: 100%;
  -webkit-transition: 1s ease;
  -moz-transition: 1s ease;
  -o-transition: 1s ease;
  -ms-transition: 1s ease;
  transition: 1s ease;
  visibility: hidden;
 }

 .nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
 }

 .nav ul li {
  color: grey;
  font-size: 14px;
  font-weight: regular;
  font-family: inherit;
  padding: 5px 0px 5px 0px;
  cursor: pointer;
  transition: .5s ease;
  -webkit-transition: .5s ease;
  -moz-transition: .5s ease;
 }

 .nav li:hover {
  color: lightgrey;
  font-weight: bold;
  transition: .5s ease;
  -webkit-transition: .5s ease;
  -moz-transition: .5s ease;
 }

 .mainMargins{
  margin-left: 10%;
  margin-right: 10%;
 }

 .smallSpacer{
  height: 25px;
 }

 .bigSpacer{
  height: 100px;
 }

 .txtAlignRight{

 }

 .AlwaysFullScreen{
  width: 100%;
  height: 100%;
 }

 .fullScreen{
  width: 100%;
  height: 100%;
 }

 .withBGImg{
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
 }

 .jumbo-title{
  font-weight: bold;
  letter-spacing: 0.02em;
 }

 .jumbo-caption{
  font-weight: 300;
  font-size:
 }

 .jumbo-container{
  color: white;
 }

 .verticalCentreParent{
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
 }

 .verticalCentreChild{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }

 .content-verticalCentreParent{
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
 }

 .content-verticalCentreChild{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }

 .iconContainer{
  text-align: center;
 }
 .mediumIcons{
  height: 100px;
 }

 .scrollCard{
  box-shadow: 0 0 8px rgba(33,33,33,.2);
  width: 200px;
  height: 250px;
  border-radius: 10px;
  -webkit-transition: .3s ease;
  -moz-transition: .3s ease;
  -o-transition: .3s ease;
  -ms-transition: .3s ease;
  transition: .3s ease;
 }

 .scrollCard:hover{
  box-shadow: 0 0 11px rgba(33,33,33,.5);
 }

 .scrollCardBar {
  display: flex;
  min-width: 100%;
  min-height: 200px;
  overflow-x: auto;
  margin: 0;
 }

 .scrollCard {
  min-width: 300px;
  margin: 8px;
 }
 .scrollCardContainer{
  display: flex;
  margin-left: 10%;
  margin-right: 10%;
 }

 .scrollCardBar::-webkit-scrollbar {
  display: none;
 }

 .endOfScroll{
  width: 100px;
 }

 .line{
  margin-top: 10px;
  margin-bottom: 35px;
  background-color: white;
  height: 1px;
 }

 footer{
  height: auto;
  background-color: #5388EF;
  color: white;
   width: 100%;
   position: relative;
 }

 footer ul{
  font-weight: 300;
  list-style-type: none;

  margin-top: 20px;
  padding: 0;
 }

 footer li{
  padding: 10px 0px 5px 0px;
 }

 footer .row{
  margin: auto;
 }

 footer .footer-column{
  width: calc(100% / 6);
    height: auto;
    float: left;
    box-sizing: border-box;
   -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  padding: 0px 20px 20px 20px;
  margin-top: 20px;
 }

 @media only screen and (min-width: 2000px){
  .mainMargins{
   margin-left: 25%;
   margin-right: 25%;
  }
  .scrollCardContainer{
   margin-left: 25%;
   margin-right: 25%;
  }
 }

 @media only screen and (max-height: 1000px){
  .fullScreen{
   height: auto;
   width: auto;
  }

  .content-verticalCentreChild{
   position: relative;
   top: 100%;
   transform: none;
  }
 }

 @media only screen and (max-width: 1400px) {
  footer .footer-column{
   width: calc(100% / 3);
  }
 }

 @media only screen and (max-width: 600px) {
  h1{
   font-size: 2em;
  }

  h2{
   font-size: 1em;
  }

  #hamburger{
   top: 5px;
  left: px;
  }

  .mobile-accordian-panel{
  max-height: 0;
  overflow: hidden;
  -webkit-transition: .3s ease;
  -moz-transition: .3s ease;
  -o-transition: .3s ease;
  -ms-transition: .3s ease;
  transition: .3s ease;

  }

  .mainMargins{
   margin-left: 8%;
   margin-right: 8%;
  }

  .content-verticalCentreChild{
   position: relative;
   top: 100%;
   transform: none;
  }
  .scrollCardContainer{
   margin-left: 8%;
   margin-right: 8%;
  }
  .endOfScroll{
   width: 16px;
  }
  footer .footer-column{
   width: 100%
  }

 }

<!DOCTYPE html>

   <title></title>

<meta charset="utf-8" />

 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link rel="stylesheet" href="/css/style.css">

<meta name="viewport" content="width=device-width, initial-scale=1" />

  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700&display=swap" rel="stylesheet">

   ☰

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Title

About

Mission

Services

Social

Title

About

Mission

Services

Catchy Headline That Spans Multiple Lines

Headline Caption (Optional)

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

Title

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking). This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

 Meet Our Reseachers

This is paragraph text. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content (also called greeking).

        A groundbreaking blueprint for store-program computers. Though a complete version of the ACE was never built, its concept has been used as a model by tech corporations worldwide for several years

        He first addressed the issue of artificial intelligence in his 1950 paper, "Computing machinery and intelligence". If an AI can convice a human that is it human, it should be considered intelligent.

        The highest acheivable award in the field of computer science. Named after Alan Turing for his grand contributions and is equivalent to the Noble Prize.

 News

 Read the Storie’s of sTTARR’s reseachers and users.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

 All Stories

Jan, 01, 2019

          Title of the news article will be diplayed under the photo.

Jan, 01, 2019

        Title of the news article will be diplayed under the photo.

Jan, 01, 2019

      Title of the news article will be diplayed under the photo.

Jan, 01, 2019

      Title of the news article will be diplayed under the photo.

Jan, 01, 2019

    Title of the news article will be diplayed under the photo.

Jan, 01, 2019

  Title of the news article will be diplayed under the photo.

 <button onclick="toggleNewsButton()" id="myBtn">Read more</button>

 Updates

 Here is a live twitter update.Here is a live twitter update.Here is a live twitter update.Here is a live twitter update.

        Tweets from UHN

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

Title

About

Mission

Services

Social

Get in touch

EXPECTED: button should show the information in the read more tag.

ACTUAL: button doesn't do anything when you click it.

Body:
This should do it. This also needed changing:

if (readmore.style.display === "none") {

to

if (moreText.style.display === "none") {

function toggleNewsButton() {
  var readmore = document.getElementById("readmore");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (moreText.style.display === "none") {
    readmore.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    readmore.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}

#more {
  display: none;
}

#myBtn {
  color: black;
  background: #fff;
  border: 1px solid black;
  font-size: 17px;
  padding: 7px 12px;
  font-weight: normal;
  margin: 6px 0;
  margin-right: 12px;
}

.centerButton {
  text-align: center;
}

#myBtn:hover,
#myBtn:active {
  background: black;
  color: white;
}

<section id="#" class="">

  <div class="allStories">
    <hr>
    <h2 style="text-align:center;"> All Stories</h2>
    <hr>
    <div class="smallSpacer"></div>

    <div class="row">
      <div class="col-sm-6" style="text-align:left;">
        <p class="#" style="color:lightgray;">Jan, 01, 2019 </p>
        <small>Title of the news article will be diplayed under the photo. </small>
      </div>
      <div class="col-sm-6" style="text-align: right;">
        <img src="/images/news1.jpg" style="height:200px; width:300px;">
      </div>
    </div>
    <hr>
    <div class="row">
      <div class="col-sm-6" style="text-align:left;">
        <p class="#" style="color:lightgray;  ">Jan, 01, 2019 </p>
        <small>Title of the news article will be diplayed under the photo. </small>
      </div>
      <div class="col-sm-6" style="text-align: right;">
        <img src="/images/news2.jpg" style="height:200px; width:300px; ">
      </div>
    </div>
    <hr>
    <div class="row">
      <div class="col-sm-6" style="text-align:left;">
        <p class="#" style="color:lightgray;  ">Jan, 01, 2019 </p>
        <small>Title of the news article will be diplayed under the photo. </small>
      </div>
      <div class="col-sm-6" style="text-align: right;">
        <img src="/images/news3.jpg" style="height:200px; width:300px; ">
      </div>
    </div>
    <hr>
    <span id="readmore"></span>

    <div id="more">

      <div class="row">
        <div class="col-sm-6" style="text-align:left;">
          <p class="#" style="color:lightgray;">Jan, 01, 2019 </p>
          <small>Title of the news article will be diplayed under the photo. </small>
        </div>
        <div class="col-sm-6" style="text-align: right;">
          <img src="/images/news1.jpg" style="height:200px; width:300px;">
        </div>
      </div>
      <hr>
      <div class="row">
        <div class="col-sm-6" style="text-align:left;">
          <p class="#" style="color:lightgray;  ">Jan, 01, 2019 </p>
          <small>Title of the news article will be diplayed under the photo. </small>
        </div>
        <div class="col-sm-6" style="text-align: right;">
          <img src="/images/news2.jpg" style="height:200px; width:300px; ">
        </div>
      </div>
      <hr>
      <div class="row">
        <div class="col-sm-6" style="text-align:left;">
          <p class="#" style="color:lightgray;  ">Jan, 01, 2019 </p>
          <small>Title of the news article will be diplayed under the photo. </small>
        </div>
        <div class="col-sm-6" style="text-align: right;">
          <img src="/images/news3.jpg" style="height:200px; width:300px; ">
        </div>
      </div>
    </div>
  </div>
  </div>

  <div class="centerButton">
    <button onclick="toggleNewsButton()" id="myBtn">Read more</button>
  </div>

</section>


问:
Calculating working days between 2 dates in SSRS 2016
I am using the below code, found on this website. It somehow works but not properly when the FromDate falls on a Friday as it adds another day on top.

See the screenshot for the demonstration.

What is it wrong in the code itself?

```<code>= (DateDiff(DateInterval.day,Fields!FromDate.Value,Fields!UntilDate.Value)+1)
- (DateDiff(DateInterval.WeekOfYear,Fields!FromDate.Value,Fields!UntilDate.Value)*2)
- IIF(Weekday(Fields!FromDate.Value,1) = 1,1,0)
- IIF(Weekday(Fields!FromDate.Value,1) = 7,1,0)
- IIF(Weekday(Fields!UntilDate.Value,1) = 1,1,0)
- IIF(Weekday(Fields!UntilDate.Value,1) = 7,1,0)
</code>```

答:
The code is OK. The problem is that your computer may be using a different First Day of Week in the Region and Language settings than the computer that the code was made on (or mine).

To test, set a text box to =WEEKDAY(TODAY). The computer this code works on has 1 as Sunday, which would make today (Wednesday) a 4. My guess is that you get 3.

If your first day of the week is Monday, you'd need to change the weekdays to 6 and 7 rather than 1 and 7 that it currently uses.

```<code>= (DateDiff(DateInterval.day,Parameters!START.Value,Parameters!END.Value)+1)
- (DateDiff(DateInterval.WeekOfYear,Parameters!START.Value,Parameters!END.Value)*2)
- IIF(Weekday(Parameters!START.Value,1) = 6,1,0)
- IIF(Weekday(Parameters!START.Value,1) = 7,1,0)
- IIF(Weekday(Parameters!END.Value,1) = 6,1,0)
- IIF(Weekday(Parameters!END.Value,1) = 7,1,0)
</code>```

If it's a Saturday, you'd need to use 1 and 2 as the weekend days.

Body:
I am using the below code, found on this website. It somehow works but not properly when the FromDate falls on a Friday as it adds another day on top.

See the screenshot for the demonstration.

What is it wrong in the code itself?

= (DateDiff(DateInterval.day,Fields!FromDate.Value,Fields!UntilDate.Value)+1)
- (DateDiff(DateInterval.WeekOfYear,Fields!FromDate.Value,Fields!UntilDate.Value)*2)
- IIF(Weekday(Fields!FromDate.Value,1) = 1,1,0)
- IIF(Weekday(Fields!FromDate.Value,1) = 7,1,0)
- IIF(Weekday(Fields!UntilDate.Value,1) = 1,1,0)
- IIF(Weekday(Fields!UntilDate.Value,1) = 7,1,0)

Body:
The code is OK. The problem is that your computer may be using a different First Day of Week in the Region and Language settings than the computer that the code was made on (or mine).

To test, set a text box to =WEEKDAY(TODAY). The computer this code works on has 1 as Sunday, which would make today (Wednesday) a 4. My guess is that you get 3.

If your first day of the week is Monday, you'd need to change the weekdays to 6 and 7 rather than 1 and 7 that it currently uses.

= (DateDiff(DateInterval.day,Parameters!START.Value,Parameters!END.Value)+1)
- (DateDiff(DateInterval.WeekOfYear,Parameters!START.Value,Parameters!END.Value)*2)
- IIF(Weekday(Parameters!START.Value,1) = 6,1,0)
- IIF(Weekday(Parameters!START.Value,1) = 7,1,0)
- IIF(Weekday(Parameters!END.Value,1) = 6,1,0)
- IIF(Weekday(Parameters!END.Value,1) = 7,1,0)

If it's a Saturday, you'd need to use 1 and 2 as the weekend days.


问:
Average line on a bar chart
I have a problem with a bar chart and its line average.

The average line doesn't cover all the bars. The last bar is without average line.

I used d3js code.

var data = [{
    "session": "1",
    "score": 70
  },
  {
    "session": "2",
    "score": 30
  },
  {
    "session": "3",
    "score": 50
  },
  {
    "session": "4",
    "score": 60
  },
  {
    "session": "5",
    "score": 40
  }
];

var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = 480 - margin.left - margin.right,
  height = 250 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
  .rangeRoundBands([0, width], .1);

var x2 = d3.scale.ordinal()
  .rangeBands([0, width], 0);

var y = d3.scale.linear()
  .range([height, 0]);

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom");

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left");

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
  d.score = +d.score;
});

x.domain(data.map(function(d) {
  return d.session;
}));
x2.domain(data.map(function(d) {
  return d.session;
}));
y.domain([0, d3.max(data, function(d) {
  return d.score;
})]);

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("score");

svg.selectAll(".bar")
  .data(data)
  .enter().append("rect")
  .attr("class", "bar")
  .attr("x", function(d) {
    return x(d.session);
  })
  .attr("width", x.rangeBand())
  .attr("y", function(d) {
    return y(d.score);
  })
  .attr("height", function(d) {
    return height - y(d.score);
  });

var dataSum = d3.sum(data, function(d) {
  return d.score;
});

var line = d3.svg.line()
  .x(function(d, i) {
    return x2(d.session) + i;
  })
  .y(function(d, i) {
    return y(dataSum / data.length);
  });

svg.append("path")
  .datum(data)
  .attr("class", "line")
  .attr("stroke-width", "2")
  .attr("d", line);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<meta name="robots" content="noindex">
<html>

<head>
  <meta charset=utf-8 />
  <title>JS Bin</title>
  <style>
    rect.bar {
      fill: cyan;
    }
    path.line {
      stroke: black;
    }
  </style>
</head>

<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
</body>

</html></code>```

答:
The existing code was appending a multi-segment path that stopped short because it was going from the start point of each entry in data to the next start point. This example replaces it with a single line that goes from the left most element's start position to the far right side of the graph.

var data = [{
    "session": "1",
    "score": 70
  },
  {
    "session": "2",
    "score": 30
  },
  {
    "session": "3",
    "score": 50
  },
  {
    "session": "4",
    "score": 60
  },
  {
    "session": "5",
    "score": 40
  }
];

var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = 480 - margin.left - margin.right,
  height = 250 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
  .rangeRoundBands([0, width], .1);

var x2 = d3.scale.ordinal()
  .rangeBands([0, width], 0);

var y = d3.scale.linear()
  .range([height, 0]);

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom");

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left");

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
  d.score = +d.score;
});

x.domain(data.map(function(d) {
  return d.session;
}));
x2.domain(data.map(function(d) {
  return d.session;
}));
y.domain([0, d3.max(data, function(d) {
  return d.score;
})]);

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("score");

svg.selectAll(".bar")
  .data(data)
  .enter().append("rect")
  .attr("class", "bar")
  .attr("x", function(d) {
    return x(d.session);
  })
  .attr("width", x.rangeBand())
  .attr("y", function(d) {
    return y(d.score);
  })
  .attr("height", function(d) {
    return height - y(d.score);
  });

var dataSum = d3.sum(data, function(d) {
  return d.score;
});

svg.append("line")
    .attr("x1", x2(1))
    .attr("x2", width)
    .attr("y1", y(dataSum / data.length))
    .attr("y2", y(dataSum / data.length));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<meta name="robots" content="noindex">
<html>

<head>
  <meta charset=utf-8 />
  <title>JS Bin</title>
  <style>
    rect.bar {
      fill: cyan;
    }
    line {
      stroke: black;
    }
  </style>
</head>

<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
</body>

</html></code>```

Title: Average line on a bar chart

Body:
I have a problem with a bar chart and its line average.

The average line doesn't cover all the bars. The last bar is without average line.

I used d3js code.

var data = [{
    "session": "1",
    "score": 70
  },
  {
    "session": "2",
    "score": 30
  },
  {
    "session": "3",
    "score": 50
  },
  {
    "session": "4",
    "score": 60
  },
  {
    "session": "5",
    "score": 40
  }
];

var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = 480 - margin.left - margin.right,
  height = 250 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
  .rangeRoundBands([0, width], .1);

var x2 = d3.scale.ordinal()
  .rangeBands([0, width], 0);

var y = d3.scale.linear()
  .range([height, 0]);

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom");

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left");

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
  d.score = +d.score;
});

x.domain(data.map(function(d) {
  return d.session;
}));
x2.domain(data.map(function(d) {
  return d.session;
}));
y.domain([0, d3.max(data, function(d) {
  return d.score;
})]);

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("score");

svg.selectAll(".bar")
  .data(data)
  .enter().append("rect")
  .attr("class", "bar")
  .attr("x", function(d) {
    return x(d.session);
  })
  .attr("width", x.rangeBand())
  .attr("y", function(d) {
    return y(d.score);
  })
  .attr("height", function(d) {
    return height - y(d.score);
  });

var dataSum = d3.sum(data, function(d) {
  return d.score;
});

var line = d3.svg.line()
  .x(function(d, i) {
    return x2(d.session) + i;
  })
  .y(function(d, i) {
    return y(dataSum / data.length);
  });

svg.append("path")
  .datum(data)
  .attr("class", "line")
  .attr("stroke-width", "2")
  .attr("d", line);

<!DOCTYPE html>
<meta name="robots" content="noindex">

  <meta charset=utf-8 />
  <title>JS Bin</title>

Body:
The existing code was appending a multi-segment path that stopped short because it was going from the start point of each entry in data to the next start point. This example replaces it with a single line that goes from the left most element's start position to the far right side of the graph.

var data = [{
    "session": "1",
    "score": 70
  },
  {
    "session": "2",
    "score": 30
  },
  {
    "session": "3",
    "score": 50
  },
  {
    "session": "4",
    "score": 60
  },
  {
    "session": "5",
    "score": 40
  }
];

var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = 480 - margin.left - margin.right,
  height = 250 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
  .rangeRoundBands([0, width], .1);

var x2 = d3.scale.ordinal()
  .rangeBands([0, width], 0);

var y = d3.scale.linear()
  .range([height, 0]);

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom");

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left");

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
  d.score = +d.score;
});

x.domain(data.map(function(d) {
  return d.session;
}));
x2.domain(data.map(function(d) {
  return d.session;
}));
y.domain([0, d3.max(data, function(d) {
  return d.score;
})]);

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("score");

svg.selectAll(".bar")
  .data(data)
  .enter().append("rect")
  .attr("class", "bar")
  .attr("x", function(d) {
    return x(d.session);
  })
  .attr("width", x.rangeBand())
  .attr("y", function(d) {
    return y(d.score);
  })
  .attr("height", function(d) {
    return height - y(d.score);
  });

var dataSum = d3.sum(data, function(d) {
  return d.score;
});

svg.append("line")
    .attr("x1", x2(1))
    .attr("x2", width)
    .attr("y1", y(dataSum / data.length))
    .attr("y2", y(dataSum / data.length));

<!DOCTYPE html>
<meta name="robots" content="noindex">
<html>

<head>
  <meta charset=utf-8 />
  <title>JS Bin</title>
  <style>
    rect.bar {
      fill: cyan;
    }
    line {
      stroke: black;
    }
  </style>
</head>

<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
</body>

</html>


问:
Is there a way to skip error "filename is not found" and move to the next file
Is there a way to skip error "filename is not found" and move to the next file?

```<code>Sub CopyDataAndMoveDown()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        Call MoveBelow
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(4, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

Sub MoveBelow ()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        ' At this point when the macro meet again a empty cell
        ' it should keep moving from the same counted X
        ' but start the paste operation from 24 rows below.
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(28, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub
</code>```

So when the macro is copying / pasting data from Sheet 1 to Sheet 2 and meets an empty cell it should keep going, copying next available data, but paste it 24 rows below.

--------Below the old question.

I have a VBA which is opening and closing file for that INDEX function get data. My problem is that. VBA is getting the filename from reference cell which contain the full path. But some of the reference cells are blanks/zeros and then the running VBA stops and give me error "filename is not found". Is there a way to skip that and move to next step?

```<code>Sub HaeReseptiTiedot()

Dim myfile As String
Dim myfile1 As String
Dim myfile2 As String
Dim myfile3 As String
Dim myfile4 As String
Dim myfile5 As String
Dim myfile6 As String
Dim myfile7 As String
Dim myfile8 As String
Dim myfile9 As String

myfile = Cells(19, 4).Value
myfile1 = Cells(19, 9).Value
myfile2 = Cells(19, 14).Value
myfile3 = Cells(19, 19).Value
myfile4 = Cells(19, 24).Value
myfile5 = Cells(19, 29).Value
myfile6 = Cells(19, 34).Value
myfile7 = Cells(19, 39).Value
myfile8 = Cells(19, 44).Value
myfile9 = Cells(19, 49).Value

Application.ScreenUpdating = False

Workbooks.Open Filename:=myfile, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("D16:G30").Select
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Workbooks.Open Filename:=myfile1, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("I16:L30").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("G4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
</code>```

答:
The best way I have found to handle this is to use the "On Error" statement. You can keep it really simple and use On Error Resume Next, which tells the code to skip the error entirely and move to the next statement (that does not have an error). The main issue with this is that it covers ALL errors, not just the specific one you are having issues with currently. It can make it hard to know if errors are occurring/if your code is functioning as you expect.

The other option, which can help avoid the issues mentioned above, is to use something like this:

```<code>On Error GoTo ErrH
    'Main Body of Your Code
    Exit Sub 'Use to avoid continuing on to the ErrH section.
ErrH:
    'Some method for handling the error, such as a message box or other notification.
</code>```

This usually isn't necessary with small chunks of code, but when you start combining your subs and functions it can be a life saver!

Good Luck!

Edit: You could/should also consider removing those blanks if they are not necessary for the sheet to work.

Body:
Is there a way to skip error "filename is not found" and move to the next file?

Sub CopyDataAndMoveDown()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        Call MoveBelow
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(4, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

Sub MoveBelow ()

Application.ScreenUpdating = False

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet

For x = 4 To 504 Step 6

    With wb.Sheets("Sheet1")
        breakdown1 = breakdown.Cells(9, x - 2)
    End With

    If IsEmpty(breakdown1) Then
        ' At this point when the macro meet again a empty cell
        ' it should keep moving from the same counted X
        ' but start the paste operation from 24 rows below.
    Else

        With wb.Sheets("Sheet1")
            Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
            Debug.Print rngToCopy.Address
        End With

        With wb.Sheets("Sheet2")
            Set rngToPaste = .Range(.Cells(28, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
            Debug.Print rngToPaste.Address
        End With

        rngToPaste = rngToCopy.Value
    End If

Next x

Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub

So when the macro is copying / pasting data from Sheet 1 to Sheet 2 and meets an empty cell it should keep going, copying next available data, but paste it 24 rows below.

--------Below the old question.

I have a VBA which is opening and closing file for that INDEX function get data. My problem is that. VBA is getting the filename from reference cell which contain the full path. But some of the reference cells are blanks/zeros and then the running VBA stops and give me error "filename is not found". Is there a way to skip that and move to next step?

Sub HaeReseptiTiedot()

Dim myfile As String
Dim myfile1 As String
Dim myfile2 As String
Dim myfile3 As String
Dim myfile4 As String
Dim myfile5 As String
Dim myfile6 As String
Dim myfile7 As String
Dim myfile8 As String
Dim myfile9 As String

myfile = Cells(19, 4).Value
myfile1 = Cells(19, 9).Value
myfile2 = Cells(19, 14).Value
myfile3 = Cells(19, 19).Value
myfile4 = Cells(19, 24).Value
myfile5 = Cells(19, 29).Value
myfile6 = Cells(19, 34).Value
myfile7 = Cells(19, 39).Value
myfile8 = Cells(19, 44).Value
myfile9 = Cells(19, 49).Value

Application.ScreenUpdating = False

Workbooks.Open Filename:=myfile, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("D16:G30").Select
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Workbooks.Open Filename:=myfile1, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("I16:L30").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("G4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Body:
The best way I have found to handle this is to use the "On Error" statement. You can keep it really simple and use On Error Resume Next, which tells the code to skip the error entirely and move to the next statement (that does not have an error). The main issue with this is that it covers ALL errors, not just the specific one you are having issues with currently. It can make it hard to know if errors are occurring/if your code is functioning as you expect.

The other option, which can help avoid the issues mentioned above, is to use something like this:

On Error GoTo ErrH
    'Main Body of Your Code
    Exit Sub 'Use to avoid continuing on to the ErrH section.
ErrH:
    'Some method for handling the error, such as a message box or other notification.

This usually isn't necessary with small chunks of code, but when you start combining your subs and functions it can be a life saver!

Good Luck!

Edit: You could/should also consider removing those blanks if they are not necessary for the sheet to work.


问:
Error: Could not find or load main class in intelliJ IDE
I'm a beginner in Java and am trying to run my code using IntelliJ that I just installed as my IDE with JDK 1.7.  The following piece of code keeps does not even compile and keeps giving me the error:

```<code>Error: Could not find or load main class libTest
</code>```

Code

```<code>import java.lang.Integer;
import java.lang.String;
import java.lang.System;
import java.util.*;

class book {

    private String name = "trial";
    private int bookCode=1;
    private int issued=0;

     public void Issue(){
         if(issued==0) {
             issued=1;
             System.out.println("You have succesfully issued the book");
         }
         else {
             System.out.println("The book is already issued. Please contact the librarian for further details");
         }
    }

    public int checkCode() {
        return bookCode;
    }

    String readName() {
        return name;
    }

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

    public void setBookCode(int newCode){
        bookCode=newCode;
    }
}

class library {
    private ArrayList books=new ArrayList();

    public void getList(){
        for(int bk:books){
            String bName=books(bk).readName();
            System.out.println((bk+1)+")  "+bName);
        }
    }
}

public class libTest{
    public static void main(String[] args){
        library newLib= new library();
        System.out.println("code working");
   }
}
</code>```

Is there any change that i have to make in the compiler settings?? Or is it the code.

答: I inherited a bunch of .JAVA files from elsewhere and couldn't figure out how to get them to work in any IDE. Ultimately I had to go to the command line where the Main.JAVA file was and run javac Main.java.  This created a bunch of .CLASS files.  The IDE's were then able to figure out what to do.

ContentLicense: CC BY-SA 3.0

Body:
I'm a beginner in Java and am trying to run my code using IntelliJ that I just installed as my IDE with JDK 1.7.  The following piece of code keeps does not even compile and keeps giving me the error:

Error: Could not find or load main class libTest

Code

import java.lang.Integer;
import java.lang.String;
import java.lang.System;
import java.util.*;

class book {

    private String name = "trial";
    private int bookCode=1;
    private int issued=0;

     public void Issue(){
         if(issued==0) {
             issued=1;
             System.out.println("You have succesfully issued the book");
         }
         else {
             System.out.println("The book is already issued. Please contact the librarian for further details");
         }
    }

    public int checkCode() {
        return bookCode;
    }

    String readName() {
        return name;
    }

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

    public void setBookCode(int newCode){
        bookCode=newCode;
    }
}

class library {
    private ArrayList books=new ArrayList();

    public void getList(){
        for(int bk:books){
            String bName=books(bk).readName();
            System.out.println((bk+1)+")  "+bName);
        }
    }
}

public class libTest{
    public static void main(String[] args){
        library newLib= new library();
        System.out.println("code working");
   }
}

Is there any change that i have to make in the compiler settings?? Or is it the code.


问:
How to check if string2 has characters not in string1?
```<code>char String1 = "1234567890+-";
char String2 = "1+a";
</code>```

String2 is an input and I want to check if it contains any character that is not in String1.

I have tried using strpbrk(String2,String1) but this returns true as long as any character in String1 exists in String2.

Is there a better way to do it?

答:
strspn will return the index of the first character in String2 that is not in String1. If all the characters match, the index will be to the terminating zero.

```<code>#include <stdio.h>
#include <string.h>

int main ( void) {
    char *String1 = "1234567890+-";
    char *String2 = "1+a";
    int index = strspn ( String2, String1);
    if ( String2[index]) {
        printf ( "character \'%c\' not found in %s\n", String2[index], String1);
    }
    return 0;
}
</code>```

Body:
char String1 = "1234567890+-";
char String2 = "1+a";

String2 is an input and I want to check if it contains any character that is not in String1.

I have tried using strpbrk(String2,String1) but this returns true as long as any character in String1 exists in String2.

Is there a better way to do it?

Body:
strspn will return the index of the first character in String2 that is not in String1. If all the characters match, the index will be to the terminating zero.

#include <stdio.h>
#include <string.h>

int main ( void) {
    char *String1 = "1234567890+-";
    char *String2 = "1+a";
    int index = strspn ( String2, String1);
    if ( String2[index]) {
        printf ( "character \'%c\' not found in %s\n", String2[index], String1);
    }
    return 0;
}


问:
Sqflite in flutter, working with two databases (attach)
I have a litte problem with the handling of two databases. I am using flutter with dart and the sqlite package sqflite.

Description of the problem:
I have two databases in my asset (assets/masterdata.db and assets/usr.db).
The masterdata.db has new data from time to time and in the usr.db I am storing the user data.
I want to copy usr.db once and masterdata.db everytime at least with an update of the application.

Question:
Is there a way to use "attach database" for the two databases and how can I do that?

Question 2:
Or is there another way to save the data of the tables inside the usr.db while updating the masterdata?
I want to avoid writing 100 of insert statements for new masterdata in the onUpdate event.
And also using csv files for new data sounds not really smart.

Thank you in advance for any hint.

答:
In your masterdata database helper you can do something like this to attach the database

```<code>    Future<Database> attachDb({Database db, String databaseName, String databaseAlias}) async {
      Directory documentDirectory = await getApplicationDocumentsDirectory();
      String absoluteEndPath = join(documentDirectory.path, databaseName);
      await db.rawQuery("ATTACH DATABASE '$absoluteEndPath' as '$databaseAlias'");
      return db;
    }
</code>```

So when you initialize your database you can run

```<code>    attachDb(
        db:db,
        databaseName:"usr.db",
        databaseAlias:"USER_DATABASE",
    );
</code>```

Then you can reference the database in your queries like this

```<code>    db.rawQuery("SELECT * FROM USER_DATABASE.table_name");
</code>```

Body:
In your masterdata database helper you can do something like this to attach the database

    Future<Database> attachDb({Database db, String databaseName, String databaseAlias}) async {
      Directory documentDirectory = await getApplicationDocumentsDirectory();
      String absoluteEndPath = join(documentDirectory.path, databaseName);
      await db.rawQuery("ATTACH DATABASE '$absoluteEndPath' as '$databaseAlias'");
      return db;
    }

So when you initialize your database you can run

    attachDb(
        db:db,
        databaseName:"usr.db",
        databaseAlias:"USER_DATABASE",
    );

Then you can reference the database in your queries like this

    db.rawQuery("SELECT * FROM USER_DATABASE.table_name");


问:
how to make a multiline textbox not accept Enter and Backspace
I have a multiline textbox which shouldn't accept alphabets, numbers, newline(enter key) and backspace. In short, the textbox.Text shouldn't be editable. But I do want the textbox to accept two shortcut keys - control and control+R. One way I can make the textbox un-editable is by making it read-only. But then the textbox wont accept any keystroke at all. In short, my shortcuts ( control and control+R) wont work( Control + R) with read-only method.

Can anyone help in this regard. That's all I have to do.

One thing I could do here is not to make the textbox read-only and then restrict the characters(alphabets and digits) that could be inputted in the textbox. With this code:

```<code>    private void txtResult_KeyPress(object sender, KeyPressEventArgs e)
    {
        // only modifier keys, escape, enter, backspace etc is accepted now
        e.Handled = !char.IsControl(e.KeyChar);
    }

    private void txtResult_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control == true)
        {
            if (e.KeyCode == Keys.R)
            {
                // do something
            }
            else
            {
                //do something
            }
        }

        if (e.KeyCode == Keys.Escape)
        {
            //do something
        }
    }
</code>```

With this technique I can get the shortcuts(control and control+R) working. But the trouble with this method is that Enter and Backspace keys work as well making it possible to edit the text of textbox. How can I specifically restrict Enter and Backspace key being registered from the textbox, but let Control and Escape??

答:
did you try SuppressKeyPress = true ?

```<code>private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control == true)
            {
                if (e.KeyCode == Keys.R)
                {
                    // do something
                }
                else
                {
                    //do something
                }
            }
            else
                e.SuppressKeyPress = true;

        }
</code>```

Body:
I have a multiline textbox which shouldn't accept alphabets, numbers, newline(enter key) and backspace. In short, the textbox.Text shouldn't be editable. But I do want the textbox to accept two shortcut keys - control and control+R. One way I can make the textbox un-editable is by making it read-only. But then the textbox wont accept any keystroke at all. In short, my shortcuts ( control and control+R) wont work( Control + R) with read-only method.

Can anyone help in this regard. That's all I have to do.

One thing I could do here is not to make the textbox read-only and then restrict the characters(alphabets and digits) that could be inputted in the textbox. With this code:

    private void txtResult_KeyPress(object sender, KeyPressEventArgs e)
    {
        // only modifier keys, escape, enter, backspace etc is accepted now
        e.Handled = !char.IsControl(e.KeyChar);
    }

    private void txtResult_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control == true)
        {
            if (e.KeyCode == Keys.R)
            {
                // do something
            }
            else
            {
                //do something
            }
        }

        if (e.KeyCode == Keys.Escape)
        {
            //do something
        }
    }

With this technique I can get the shortcuts(control and control+R) working. But the trouble with this method is that Enter and Backspace keys work as well making it possible to edit the text of textbox. How can I specifically restrict Enter and Backspace key being registered from the textbox, but let Control and Escape??

Body:
did you try SuppressKeyPress = true ?

private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control == true)
            {
                if (e.KeyCode == Keys.R)
                {
                    // do something
                }
                else
                {
                    //do something
                }
            }
            else
                e.SuppressKeyPress = true;

        }


问:
Using Promise.all() with rxjs epics in React.js
I need a solution to return one single promise from 3 different API calls. Currently running 3 different API calls via rxjs epics and looking to return one single promise object after all 3 calls are complete. Having trouble understanding how to use Promise.all() and where to call it. I think something similar to Promise.all() is forkJoin(). I have some dummy data for the example of my epic that I'm using below. This is all happening in React. Could someone please provide an in-depth example of how to use Promise.all() or forkJoin with epics in React please?

Thanks

```<code>  action$.ofType(GET_PROMISE).mergeMap(
    action =>
      action.payload.search_location === undefined ||
      action.payload.search_location.length === 0 ||
      action.payload.search_location === "" ||
      stateRegex.test(action.payload.search_location.toLowerCase()) === true
      ? api
         .fetchPromise(action.payload)
         .map(
           payload =>
           payload.value === undefined || payload.value.length === 0
                 ? getPromiseFail()
                 : getPromiseSuccess(payload)
           )
</code>```

At the moment, when I get the promise object back, I'm updating state and concatting that data with two other promises from 2 different API calls. Since they are async they are coming back at different times. So I would like to combine all 3 calls before displaying any data in the web application.

答:
You're right to look into forkJoin.

Heres a rough rewrite of your example:

action$.ofType(GET_PROMISE).mergeMap(
  action =>
    // wait for all three fetches to complete
    forkJoin(
      api.fetchOne(action.payload),
      api.fetchTwo(action.payload),
      api.fetchThree(action.payload)
    )
    // now we have all three results as an array here:
    .map(([one, two, three]) => {
      // turn those results into an action
      return getPromiseSuccess(one, two, three)
    })
)
```

Please note that the code you've shared seem to use an outdated version of RxJS, so an upgrade or at least writing code in pipeable form is advised.

Hope this helps

Body:
I need a solution to return one single promise from 3 different API calls. Currently running 3 different API calls via rxjs epics and looking to return one single promise object after all 3 calls are complete. Having trouble understanding how to use Promise.all() and where to call it. I think something similar to Promise.all() is forkJoin(). I have some dummy data for the example of my epic that I'm using below. This is all happening in React. Could someone please provide an in-depth example of how to use Promise.all() or forkJoin with epics in React please?

Thanks

  action$.ofType(GET_PROMISE).mergeMap(
    action =>
      action.payload.search_location === undefined ||
      action.payload.search_location.length === 0 ||
      action.payload.search_location === "" ||
      stateRegex.test(action.payload.search_location.toLowerCase()) === true
      ? api
         .fetchPromise(action.payload)
         .map(
           payload =>
           payload.value === undefined || payload.value.length === 0
                 ? getPromiseFail()
                 : getPromiseSuccess(payload)
           )

At the moment, when I get the promise object back, I'm updating state and concatting that data with two other promises from 2 different API calls. Since they are async they are coming back at different times. So I would like to combine all 3 calls before displaying any data in the web application.

Body:
You're right to look into forkJoin.

Heres a rough rewrite of your example:

action$.ofType(GET_PROMISE).mergeMap(
  action =>
    // wait for all three fetches to complete
    forkJoin(
      api.fetchOne(action.payload),
      api.fetchTwo(action.payload),
      api.fetchThree(action.payload)
    )
    // now we have all three results as an array here:
    .map(([one, two, three]) => {
      // turn those results into an action
      return getPromiseSuccess(one, two, three)
    })
)

Please note that the code you've shared seem to use an outdated version of RxJS, so an upgrade or at least writing code in pipeable form is advised.

Hope this helps


问:
How to fix pygame installation
I am making an online tetris game that requires a pygame installation on my laptop. For some reason, it won't let me run even though I successfully imported it.

I ran the following command:

```<code>py -3.7 -m pip install pygame
</code>```

which gave me the following line:

Installing collected packages: pygame Successfully installed
pygame-1.9.6

I then wrote import pygame in the first line of my code:

import pygame

and the error I got was:

Unable to import 'pygame'pylint(import-error)

What would be the fix for this?

答:
Try upgrading the library:

pip install --upgrade pygame

Title: How to fix pygame installation

Body:
I am making an online tetris game that requires a pygame installation on my laptop. For some reason, it won't let me run even though I successfully imported it.

I ran the following command:

py -3.7 -m pip install pygame

which gave me the following line:

Installing collected packages: pygame Successfully installed
pygame-1.9.6

I then wrote import pygame in the first line of my code:

import pygame

and the error I got was:

Unable to import 'pygame'pylint(import-error)

What would be the fix for this?


问:
How to get parent folder name of current directory?
I know there are functions for finding parent directory or path such as.

```<code>os.path.dirname(os.path.realpath(__file__))
</code>```

'C:\Users\jahon\Desktop\Projects\CAA\Result\caa\project_folder'

Is there a function that just returns the parent folder name? In this case it should be project_folder.

答:
You can use split and os.path.sep to get the list of path elements and then call the last element of the list:</p>

```<code>import os

path = 'C:\\Users\\jahon\\Desktop\\Projects\\CAA\\Result\\caa\\project_folder'

    if path.split(os.path.sep)[-1]:
                parent_folder = path.split(os.path.sep)[-1] # if no backslashes at the end
            else:
                parent_folder = path.split(os.path.sep)[-2] # with backslashes at the end
</code>```

Body:
I know there are functions for finding parent directory or path such as.

os.path.dirname(os.path.realpath(__file__))

'C:\Users\jahon\Desktop\Projects\CAA\Result\caa\project_folder'

Is there a function that just returns the parent folder name? In this case it should be project_folder.

Body:
You can use split and os.path.sep to get the list of path elements and then call the last element of the list:

import os

path = 'C:\\Users\\jahon\\Desktop\\Projects\\CAA\\Result\\caa\\project_folder'

    if path.split(os.path.sep)[-1]:
                parent_folder = path.split(os.path.sep)[-1] # if no backslashes at the end
            else:
                parent_folder = path.split(os.path.sep)[-2] # with backslashes at the end


问:
Contains function in pandas dataframe column (AttributeError: 'str' object has no attribute 'str'
I'm trying to search in string in dataframe column by using contains

1.

```<code>for idx, row in df.iterrows():
  if(row['name'].str.contains('abc')):
</code>```

the above code throw this error

```<code>AttributeError: 'str' object has no attribute 'str'
</code>```

2.

```<code>for idx, row in df.iterrows():
      if(row['name'].contains('abc')):
</code>```

and the second code throw this error

```<code>AttributeError: 'str' object has no attribute 'contains'
</code>```

答:
row['name'] is a dictionary with the value being the string you are searching. To search in a vectorized way, you don't need to use iterrows():

df['name'].str.contains('abc') will return a boolean index because it uses the pandas Series string contains method.

At the row level (if this is what you want) just use in:

```<code>for idx, row in df.iterrows():
      if 'abc' in row['name']:
</code>```

Body:
I'm trying to search in string in dataframe column by using contains

1.

for idx, row in df.iterrows():
  if(row['name'].str.contains('abc')):

the above code throw this error

AttributeError: 'str' object has no attribute 'str'

2.

for idx, row in df.iterrows():
      if(row['name'].contains('abc')):

and the second code throw this error

AttributeError: 'str' object has no attribute 'contains'

Body:
row['name'] is a dictionary with the value being the string you are searching. To search in a vectorized way, you don't need to use iterrows():

df['name'].str.contains('abc') will return a boolean index because it uses the pandas Series string contains method.

At the row level (if this is what you want) just use in:

for idx, row in df.iterrows():
      if 'abc' in row['name']:


问:
How memory works if vectors inside class array are dynamically push_backed?
Assume that we have following class:

```<code>class Test {
public:
   Test() {}
   std::vector<int>& getIntList() {
      return intList;
   }
private:
   std::vector<int> intList;
};
</code>```

Also, we have following codes inside main function to declare class array:

```<code>int main(void) {
   Test* test[20];

   for (int i = 0; i < 20; ++i) {
      test[i] = new Test();
   }
}
</code>```

In these cases, test objects are instantiated.

Now if I append multiple items in the vector inside each class randomly,

there might exist chances to collide memory address range of each vector inside each class while resizing their memory size.

In this case, is the entire 'test' object copied into other memory area and vector is resized?
Or, is vector STL only copied into other memory area and resized while the class references the vector?

Entirely, is not a good idea to code like this?

答:
Consider this example:

```<code>struct foo {
    std::vector<int> x;
    std::vector<int> y;
};
</code>```

Now sizeof(foo) is a compile time constant. It does not change when you add elements to the vectors. Also sizeof(std::vector<int>) is constant.

The size of a foo instance is not increasing when the size() of the vector grows. It is similar to having a dynamic array (only for the sake of the example):

```<code>struct bar {
   int* c_array;
};
</code>```

Here, sizeof(bar) is likely to be just sizeof(int*), because it is just a pointer, even though it could point to the first element of a c-style array, or to a single int.

Body:
Assume that we have following class:

class Test {
public:
   Test() {}
   std::vector<int>& getIntList() {
      return intList;
   }
private:
   std::vector<int> intList;
};

Also, we have following codes inside main function to declare class array:

int main(void) {
   Test* test[20];

   for (int i = 0; i < 20; ++i) {
      test[i] = new Test();
   }
}

In these cases, test objects are instantiated.

Now if I append multiple items in the vector inside each class randomly,

there might exist chances to collide memory address range of each vector inside each class while resizing their memory size.

In this case, is the entire 'test' object copied into other memory area and vector is resized?
Or, is vector STL only copied into other memory area and resized while the class references the vector?

Entirely, is not a good idea to code like this?

Body:
Consider this example:

struct foo {
    std::vector<int> x;
    std::vector<int> y;
};

Now sizeof(foo) is a compile time constant. It does not change when you add elements to the vectors. Also sizeof(std::vector<int>) is constant.

The size of a foo instance is not increasing when the size() of the vector grows. It is similar to having a dynamic array (only for the sake of the example):

struct bar {
   int* c_array;
};

Here, sizeof(bar) is likely to be just sizeof(int*), because it is just a pointer, even though it could point to the first element of a c-style array, or to a single int.


问:
is it posible to create a transparent tk window and on it a non-transperent pic, only with tk and PIL
Is it posible to crate a transparent tk window and on it a non-transparent image, only with tk and PIL, or if it's not possible which libary should I use ?
image link</p>

答:
You can use wm_attributes('-transparentcolor', '#abcdef') to set a specific color to be the transparent color of the window, and then set the window background color to that color.

Below is a sample code:

```<code>from tkinter import *

root = Tk()
root.wm_attributes('-transparentcolor', '#abcdef')
root.config(bg='#abcdef')
root.geometry('400x200')

photo = PhotoImage(file='python.png')
Label(root, image=photo).place(x=50, y=50)

root.mainloop()
</code>```

and the result in Windows 10:

Updated:

In order to use transparent image, Canvas.create_image(..) can be used:

from tkinter import *

```<code>root = Tk()
root.geometry('400x200')

transparent_color = '#abcdef'
root.wm_attributes('-transparentcolor', transparent_color)

canvas = Canvas(root, bg=transparent_color)
canvas.pack(fill=BOTH, expand=1)
photo = PhotoImage(file='python-logo.png')
canvas.create_image(50, 50, image=photo, anchor=N+W)

root.mainloop()
</code>```

The result:

Body:
You can use wm_attributes('-transparentcolor', '#abcdef') to set a specific color to be the transparent color of the window, and then set the window background color to that color.

Below is a sample code:

from tkinter import *

root = Tk()
root.wm_attributes('-transparentcolor', '#abcdef')
root.config(bg='#abcdef')
root.geometry('400x200')

photo = PhotoImage(file='python.png')
Label(root, image=photo).place(x=50, y=50)

root.mainloop()

and the result in Windows 10:

Updated:

In order to use transparent image, Canvas.create_image(..) can be used:

from tkinter import *

root = Tk()
root.geometry('400x200')

transparent_color = '#abcdef'
root.wm_attributes('-transparentcolor', transparent_color)

canvas = Canvas(root, bg=transparent_color)
canvas.pack(fill=BOTH, expand=1)
photo = PhotoImage(file='python-logo.png')
canvas.create_image(50, 50, image=photo, anchor=N+W)

root.mainloop()

The result:


问:
ReSharper - force curly braces around single line
Can I configure ReSharper to fix C# code when curly braces are not used to surround a single-line code block, like this:

```<code>if (blnSomeCondition)
   DoSomething();  // complain

if (blnSomeOtherCondition)
{
   DoSomethingElse(); // don't complain
}
</code>```

Thanks

答:
Just if it can help somebody else to save time, on one machine of my company, following Sergey advices was not enough despite the great quality of his post.

On concerned setup (VS2017, R# 2019, both up to date) these settings on R# side were already good, but I also had to modify it in Visual Studio options :

In Options window, go to Text editor -> C# -> Code style ->
Formatting -> General,

Check "Perform Additional code cleanup
during formatting" and "Add/remove braces for single-line control
statement"

ContentLicense: CC BY-SA 2.5

Body:
Can I configure ReSharper to fix C# code when curly braces are not used to surround a single-line code block, like this:

if (blnSomeCondition)
   DoSomething();  // complain

if (blnSomeOtherCondition)
{
   DoSomethingElse(); // don't complain
}

Thanks


问:
Is there any way to get EmployeeID in .NET Core without third party libraries?
I used to use the UserPrincipal class to retrieve active directory information on a user, specifically the EmployeeId (not the username, we don't usually use that to tie employees to specific data points in sql). However, in .net core that class doesn't exist and I'm still fairly new to .net core so I'm not sure how a lot of it's features work in an Intranet setting. I know many probably won't work with asp.net core being cross platform and other server types not having any idea of active directory.

Below is code I use in regular asp.net environments to grab an employee id.

```<code>var userContext = System.Web.HttpContext.Current;
PrincipalContext pcxt = new PrincipalContext(ContextType.Domain, "mydomain.com");
UserPrincipal uPrincipal = UserPrincipal.FindByIdentity(pcxt, IdentityType.SamAccountName, userContext.User.Identity.Name);
return uPrincipal.EmployeeId;
</code>```

What kind of code if any can I use to grab the same information? Is it possible without third party libraries? It seems the IIS server may transport some kind of information I need through claims? I've attempted to do research but every thing just leads me down more research avenues and I'm not sure where to start.

答:
Okay, looks like for .net core 2> Microsoft has implemented the Principal Context library again, even though the documentation says there is no page when clicking .NET Core 2.2. At the very least, I am able to install the package and it works. It's authored by Microsoft, so I don't consider it Third Party.

https://dotnet.myget.org/feed/dotnet-core/package/nuget/System.DirectoryServices.AccountManagement

Luckily was able to find the package thanks to this answer: https://stackoverflow.com/a/49773749/5245385

The code is the exact same as it is in my question. All functionality seems intact.

Body:
I used to use the UserPrincipal class to retrieve active directory information on a user, specifically the EmployeeId (not the username, we don't usually use that to tie employees to specific data points in sql). However, in .net core that class doesn't exist and I'm still fairly new to .net core so I'm not sure how a lot of it's features work in an Intranet setting. I know many probably won't work with asp.net core being cross platform and other server types not having any idea of active directory.

Below is code I use in regular asp.net environments to grab an employee id.

var userContext = System.Web.HttpContext.Current;
PrincipalContext pcxt = new PrincipalContext(ContextType.Domain, "mydomain.com");
UserPrincipal uPrincipal = UserPrincipal.FindByIdentity(pcxt, IdentityType.SamAccountName, userContext.User.Identity.Name);
return uPrincipal.EmployeeId;

What kind of code if any can I use to grab the same information? Is it possible without third party libraries? It seems the IIS server may transport some kind of information I need through claims? I've attempted to do research but every thing just leads me down more research avenues and I'm not sure where to start.


问:
XMLReader() in PHP - parsing attributes in multiple elements with the same name
Im using XMLReader to parse XML but i've come across a situation where two elements have the same name and not sure how to deal with it

the elements in question are

```<code><field name="latitude" value="51.4070767"/>
<field name="longitude" value="-0.6366062"/>
</code>```

I want to pull in the two value fields into seperate strings.

I can pull in the first one using this method

```<code>$bp = $product->fields->field["value"]; ###gives 51.4070767
</code>```

but how do i access the second? (-0.6366062)

Cheers

答:
It's just one idea...
You can find the node by attribute (getAttribute) and after you can select the node using moveToElement.

But the best option is use the simpleXML, where you can use XPath to find what you want.

Body:
Im using XMLReader to parse XML but i've come across a situation where two elements have the same name and not sure how to deal with it

the elements in question are

<field name="latitude" value="51.4070767"/>
<field name="longitude" value="-0.6366062"/>

I want to pull in the two value fields into seperate strings.

I can pull in the first one using this method

$bp = $product->fields->field["value"]; ###gives 51.4070767

but how do i access the second? (-0.6366062)

Cheers