问:
How to remove an element above the navbar without moving the content?

I built this so far with w3.css:

 $(function() {

  $(window).scroll(function() {
    var x = $(window).scrollTop();
    var h = $("#navi").height();
    var z = $("#topper").height();

    if (x >= z) {
      //$("#header").hide();
      $("#navi").addClass("w3-top");
      $("#content").css("margin-top", h);
    } else {
      //$("#header").show();
      $("#navi").removeClass("w3-top");
      $("#content").css("margin-top", 0);
    }

  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
 <title></title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
 <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<body>

 <header class="w3-container" id="topper">
  <span>HEADER HEADER HEADER</span>
 </header>

 <div class="" id="navi">
  <div class="w3-bar w3-pink">
   <span class="w3-bar-item" style="display: none; width:">SOLI</span>
   <div class="w3-dropdown-hover">
    <button class="w3-button w3-mobile">1</button>
    <div class="w3-dropdown-content w3-bar-block w3-card-4">
     1a
     1b
     1c
     1d
    </div>
   </div>
   <div class="w3-dropdown-hover" id="navi">
    <button class="w3-button">2</button>
    <div class="w3-dropdown-content w3-bar-block w3-card-4">
     2a
     2b
     2c
     2d
     2e
     2f
    </div>
   </div>
   3
   4
   5
   6
  </div>
 </div>

 <div class="" id="content">
  <img src="https://assets.pixolum.com/blog/wp-content/uploads/2016/10/focus-stacking-scharfe-bilder-1.jpg">
  <img src="https://assets.pixolum.com/blog/wp-content/uploads/2016/10/focus-stacking-scharfe-bilder-1.jpg">
  <img src="https://assets.pixolum.com/blog/wp-content/uploads/2016/10/focus-stacking-scharfe-bilder-1.jpg">
 </div>
</body></code>```

But the problem is whenever I scroll down the content (eagle pictures) scolls, too, and hides behind the navbar...
I want the site to behave similar like this page when I scoll down.

Does anyone know what to do here? :)

sorry: ddddddd dddddddddddddddddd dddddddddddddddd ddddddddddddddddddddddddddd dddddd

答:
It's hard to tell what you want, but I think this is it. You need to add background through CSS and use fixed property on it.

$(function() {

  $(window).scroll(function() {
    var x = $(window).scrollTop();
    var h = $("#navi").height();
    var z = $("#topper").height();

    if (x >= z) {
      //$("#header").hide();
      $("#navi").addClass("w3-top");
      $("#content").css("margin-top", h);
    } else {
      //$("#header").show();
      $("#navi").removeClass("w3-top");
      $("#content").css("margin-top", 0);
    }

  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
 <title></title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
 <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<body style='background: url(https://assets.pixolum.com/blog/wp-content/uploads/2016/10/focus-stacking-scharfe-bilder-1.jpg) no-repeat center center fixed; background-size: cover; height: 200em;'>

 <header class="w3-container" id="topper">
  <span>HEADER HEADER HEADER</span>
 </header>

 <div class="" id="navi">
  <div class="w3-bar w3-pink">
   <span class="w3-bar-item" style="display: none; width:">SOLI</span>
   <div class="w3-dropdown-hover">
    <button class="w3-button w3-mobile">1</button>
    <div class="w3-dropdown-content w3-bar-block w3-card-4">
     1a
     1b
     1c
     1d
    </div>
   </div>
   <div class="w3-dropdown-hover" id="navi">
    <button class="w3-button">2</button>
    <div class="w3-dropdown-content w3-bar-block w3-card-4">
     2a
     2b
     2c
     2d
     2e
     2f
    </div>
   </div>
   3
   4
   5
   6
  </div>
 </div>

</body></code>```

Body:
I built this so far with w3.css:

 $(function() {

  $(window).scroll(function() {
    var x = $(window).scrollTop();
    var h = $("#navi").height();
    var z = $("#topper").height();

    if (x >= z) {
      //$("#header").hide();
      $("#navi").addClass("w3-top");
      $("#content").css("margin-top", h);
    } else {
      //$("#header").show();
      $("#navi").removeClass("w3-top");
      $("#content").css("margin-top", 0);
    }

  });

});

 <title></title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
 <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

  HEADER HEADER HEADER

   SOLI

    <button class="w3-button w3-mobile">1</button>

     1a
     1b
     1c
     1d

    <button class="w3-button">2</button>

     2a
     2b
     2c
     2d
     2e
     2f

   3
   4
   5
   6

But the problem is whenever I scroll down the content (eagle pictures) scolls, too, and hides behind the navbar...
I want the site to behave similar like this page when I scoll down.

Does anyone know what to do here? :)

sorry: ddddddd dddddddddddddddddd dddddddddddddddd ddddddddddddddddddddddddddd dddddd

Body:
It's hard to tell what you want, but I think this is it. You need to add background through CSS and use fixed property on it.

$(function() {

  $(window).scroll(function() {
    var x = $(window).scrollTop();
    var h = $("#navi").height();
    var z = $("#topper").height();

    if (x >= z) {
      //$("#header").hide();
      $("#navi").addClass("w3-top");
      $("#content").css("margin-top", h);
    } else {
      //$("#header").show();
      $("#navi").removeClass("w3-top");
      $("#content").css("margin-top", 0);
    }

  });

});

<head>
 <title></title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
 <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<body style='background: url(https://assets.pixolum.com/blog/wp-content/uploads/2016/10/focus-stacking-scharfe-bilder-1.jpg) no-repeat center center fixed; background-size: cover; height: 200em;'>

 <header class="w3-container" id="topper">
  <span>HEADER HEADER HEADER</span>
 </header>

 <div class="" id="navi">
  <div class="w3-bar w3-pink">
   <span class="w3-bar-item" style="display: none; width:">SOLI</span>
   <div class="w3-dropdown-hover">
    <button class="w3-button w3-mobile">1</button>
    <div class="w3-dropdown-content w3-bar-block w3-card-4">
     <a href="#" class="w3-bar-item w3-button" style="width:">1a</a>
     <a href="#" class="w3-bar-item w3-button" style="width:">1b</a>
     <a href="#" class="w3-bar-item w3-button" style="width:">1c</a>
     <a href="#" class="w3-bar-item w3-button" style="width:">1d</a>
    </div>
   </div>
   <div class="w3-dropdown-hover" id="navi">
    <button class="w3-button">2</button>
    <div class="w3-dropdown-content w3-bar-block w3-card-4">
     <a href="#" class="w3-bar-item w3-button" style="width:">2a</a>
     <a href="#" class="w3-bar-item w3-button" style="width:">2b</a>
     <a href="#" class="w3-bar-item w3-button" style="width:">2c</a>
     <a href="#" class="w3-bar-item w3-button" style="width:">2d</a>
     <a href="#" class="w3-bar-item w3-button" style="width:">2e</a>
     <a href="#" class="w3-bar-item w3-button" style="width:">2f</a>
    </div>
   </div>
   <a href="#" class="w3-bar-item w3-button" style="width:">3</a>
   <a href="#" class="w3-bar-item w3-button" style="width:">4</a>
   <a href="#" class="w3-bar-item w3-button" style="width:">5</a>
   <a href="#" class="w3-bar-item w3-button w3-right" style="width:">6</a>
  </div>
 </div>

</body>


来源: stackexchange

问:
Can one make unaligned loads and stores in CUDA?
Does CUDA support unaligned loads and stores? Can one naively read a (single) value of size k bytes from an address addr such that addr % k != 0?

More concretely, will accesses such as:

```<code>unsigned* p = (unsigned*) ((char *) my_aligned_ptr + 1); *p = 0xAABBCCDD;
</code>```

or

```<code>unsigned* q = (unsigned*) ((char *) my_aligned_ptr + 11); unsigned x = *q;
</code>```

have the expected effect?

答:
Despite the Size and Alignment Requirement subsection of the CUDA Programming guide being somewhat ambiguous, the answer is No, unaligned access is not supported, period. The code will compile but the result will (likely) be as if some nearby aligned addresses were used. Or otherwise undefined.

@tera has work-around code in this answer.

ContentLicense: CC BY-SA 3.0

Body:
Does CUDA support unaligned loads and stores? Can one naively read a (single) value of size k bytes from an address addr such that addr % k != 0?

More concretely, will accesses such as:

unsigned* p = (unsigned*) ((char *) my_aligned_ptr + 1); *p = 0xAABBCCDD;

or

unsigned* q = (unsigned*) ((char *) my_aligned_ptr + 11); unsigned x = *q;

have the expected effect?


问:
Modify image href attribute inside an svg element
Inside a function I have an svg object, when I console log it looks like this:

```<code><svg height="100" version="1.1" width="1000" xmlns="http://www.w3.org/2000/svg"
     style="overflow: hidden; position: relative;">

  <desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with Raphaël 2.1.0</desc>
  <defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></defs>
  <path fill="#000000" stroke="#000000" d="M0,0L12,12L12,-12L0,0" transform="matrix(1,0,0,1,0,50)"
     opacity="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0;">
  </path>
  <rect x="0" y="10" width="30" height="80" r="0" rx="0" ry="0"
    fill="#000000" stroke="#000" opacity="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0;"></rect>
  <image x="134" y="10" width="30" height="80" preserveAspectRatio="none"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xlink:href="/static/img/pads/numberline/symbols/leftParen.png"
    style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
  </image>
</svg>
</code>```

Now I need to change the href of the image inside the svg element.
What i did it so far is set the width svgObject.setAttribute('width', 1000);

But how can I change and select the image element href attribute?

答:
Use setAttributeNS to set the xlink:href attribute as it's in the xlink namespace.

These days some browsers (but not Safari or IE) will let you set the href attribute in the null namespace (which you can do with setAttribute) and will use that in preference to xlink:href but till Safari catches up you're best sticking with xlink:href

<svg height="100" version="1.1" width="1000" xmlns="http://www.w3.org/2000/svg">

  <image x="134" y="10" width="100" height="100"     xmlns:xlink="http://www.w3.org/1999/xlink"
    xlink:href="https://bellard.org/bpg/2.png" onclick="this.setAttributeNS('http://www.w3.org/1999/xlink', 'href', 'http://pngimg.com/uploads/polar_bear/polar_bear_PNG23514.png')">
  </image>
</svg>```

Body:
Inside a function I have an svg object, when I console log it looks like this:

<svg height="100" version="1.1" width="1000" xmlns="http://www.w3.org/2000/svg"
     style="overflow: hidden; position: relative;">

  <desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with Raphaël 2.1.0</desc>
  <defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></defs>
  <path fill="#000000" stroke="#000000" d="M0,0L12,12L12,-12L0,0" transform="matrix(1,0,0,1,0,50)"
     opacity="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0;">
  </path>
  <rect x="0" y="10" width="30" height="80" r="0" rx="0" ry="0"
    fill="#000000" stroke="#000" opacity="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0;"></rect>
  <image x="134" y="10" width="30" height="80" preserveAspectRatio="none"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xlink:href="/static/img/pads/numberline/symbols/leftParen.png"
    style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
  </image>
</svg>

Now I need to change the href of the image inside the svg element.
What i did it so far is set the width svgObject.setAttribute('width', 1000);

But how can I change and select the image element href attribute?


问:
Send inputs from an Android App to Google Documents Spreadsheet
my friend and I are currently making a simple Weather chance calculator  android app for a summer project. The app currently works by asking the user for some inputs using some EditTexts (formatted in decimal numbers) that are then put into a simple formula and then a result is spit out.

What I want to do is take the user inputs and transfer them to a public Google Docs spreadsheet, so that EditText1 goes to cell A1, EditText2 goes to cell A2, ect.

Can someone point me in the right direction?

Thanks,

答:
you can achieve same with out google forms, use app scripts follow the below tutorials

How To Use Google Sheet As DataBase For Android App Part - 2 | Post data Sheet from Android App
https://www.youtube.com/watch?v=QZZrMlUiH2M


问:
Array/object parameter in octopus custom step template
Is there a way to add array/object parameter to octopus custom step template?
Built in step "Deploy to IIS" allows to add collection of bindings. Can such functionality be added to a custom step?

答:
I don't think it's possible to setup an array parameter for a custom step template. See Custom Step Templates documentation.

You could put an array into a variable and parse that with Powershell. Also, here is a custom step template example.

You could reach out to Octopus Support to see if they have any other recommendations or maybe add it to their UserVoice to see if others are interested in the feature.


问:
Check if exist and create
I try generate and save uncial slug for title in DB.

```<code>                $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);
</code>```

How check if such field in url exist? And if exist save:

```<code>'url' => str_slug($feed->name,"-1"),
</code>```

I think:

```<code>  if (FriendlyUrl::whereUrl(str_slug($feed->name))){
            $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);} else {
                $feed->friendlyUrl()->make([
                    'url' => str_slug($feed->name),
                    'action' => "feeds/{$feed->id}-1",
                    'complicated' => false,
                    'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            };
            break;
</code>```

But it not clean and what if such url - str_slug($feed->name,"-1") already exists?

答:
Unique slug for title  </p>

```<code>public static function boot()
           {
               parent::boot();

           static::creating(function($model) {
               $model->slug = str_slug($model->ToBeSluggified);// change the ToBeSluggiefied

               $latestSlug =
                   static::whereRaw("slug = '$model->slug' or slug LIKE '$model->slug-%'")
                       ->latest('id')
                       ->value('slug');
               if ($latestSlug) {
                   $pieces = explode('-', $latestSlug);

                   $number = intval(end($pieces));

                   $model->slug .= '-' . ($number + 1);
               }
           });
       }
</code>```

Title: Check if exist and create

Body:
I try generate and save uncial slug for title in DB.

                $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);

How check if such field in url exist? And if exist save:

'url' => str_slug($feed->name,"-1"),

I think:

  if (FriendlyUrl::whereUrl(str_slug($feed->name))){
            $feed->friendlyUrl()->make([
                'url' => str_slug($feed->name),
                'action' => "feeds/{$feed->id}",
                'complicated' => false,
                'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            ]);} else {
                $feed->friendlyUrl()->make([
                    'url' => str_slug($feed->name),
                    'action' => "feeds/{$feed->id}-1",
                    'complicated' => false,
                    'page_type_id' => PageType::TYPE_INDIVIDUAL_FEED_PAGE,
            };
            break;

But it not clean and what if such url - str_slug($feed->name,"-1") already exists?

Body:
Unique slug for title

public static function boot()
           {
               parent::boot();

           static::creating(function($model) {
               $model->slug = str_slug($model->ToBeSluggified);// change the ToBeSluggiefied

               $latestSlug =
                   static::whereRaw("slug = '$model->slug' or slug LIKE '$model->slug-%'")
                       ->latest('id')
                       ->value('slug');
               if ($latestSlug) {
                   $pieces = explode('-', $latestSlug);

                   $number = intval(end($pieces));

                   $model->slug .= '-' . ($number + 1);
               }
           });
       }


问:
how to display different data type values with same variable in javascript
Issue:

When I am using same variable to hold different data types in java script,
and trying to display all values, it is not showing up all values except the last value which it holds. is there any alternate way to show up all data type values with same variable?

Script:

```<code><script>
var x;
document.getElementById("demo").innerHTML = x;
x = 5;
document.getElementById("demo").innerHTML = x;
x = "John";
document.getElementById("demo").innerHTML = x;
</script>
</code>```

Expected result:

undefined
5
John

Actual result:

John

答:
    var x;
    document.getElementById("demo").innerHTML += x + ' ';
    x = 5;
    document.getElementById("demo").innerHTML += x + ' ';
    x = "John";
    document.getElementById("demo").innerHTML += x + ' ';```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="demo"> </div></code>```

Every time you set the innerHTML your overwriting what was there you need to add to it like below.

```<code>document.getElementById("demo").innerHTML += x + '<br/>';
</code>```

Body:
Issue:

When I am using same variable to hold different data types in java script,
and trying to display all values, it is not showing up all values except the last value which it holds. is there any alternate way to show up all data type values with same variable?

Script:

Expected result:

undefined
5
John

Actual result:

John

Body:
    var x;
    document.getElementById("demo").innerHTML += x + ' ';
    x = 5;
    document.getElementById("demo").innerHTML += x + ' ';
    x = "John";
    document.getElementById("demo").innerHTML += x + ' ';

<div id="demo"> </div>

Every time you set the innerHTML your overwriting what was there you need to add to it like below.

document.getElementById("demo").innerHTML += x + '<br/>';


问:
Accessing ASP.NET controls dynamically from JavaScript
here's what I mean:

I have a few controls, for example,

```<code><asp:DropDownList ID="ddlDate1" runat="server" />
<asp:DropDownList ID="ddlDate2" runat="server" />
<asp:DropDownList ID="ddlDate3" runat="server" />
</code>```

in my javascript, I want to do something like this:

```<code>for (i = 1; i <= count; i++) {
    something[i] = document.getElementById("<%= ddlDateRange" + i + ".ClientID %>");
}
</code>```

any way I can make this work, or any alternatives?

答:
Put your dropdown lists into an array. Then you can populate a javascript array like so</p>

```<code>var dropDownListIds = [];
<% foreach (DropDownList ddl in myListOfDropDowns) { %>
dropDownListIds.push('<%= ddl.ClientID %>');
<% } %>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
here's what I mean:

I have a few controls, for example,

<asp:DropDownList ID="ddlDate1" runat="server" />
<asp:DropDownList ID="ddlDate2" runat="server" />
<asp:DropDownList ID="ddlDate3" runat="server" />

in my javascript, I want to do something like this:

for (i = 1; i <= count; i++) {
    something[i] = document.getElementById("<%= ddlDateRange" + i + ".ClientID %>");
}

any way I can make this work, or any alternatives?

Body:
Put your dropdown lists into an array. Then you can populate a javascript array like so

var dropDownListIds = [];
<% foreach (DropDownList ddl in myListOfDropDowns) { %>
dropDownListIds.push('<%= ddl.ClientID %>');
<% } %>


答:
Simply by map you array into a function and then parse the values as you desire.

The following example uses:

Array.map to loop through the array

String.split to split the string using whitespace and get only the last part

Template literals `` to output the value

Relevant method:

```<code>const result = data.histdata.map(hist => {
  const datetime = hist['***datetime***'].split(' ')[1];
  const value = hist['***value***'];
  return `${datetime},${value}`;
});
</code>```

Check the snippet:

const data = {
    "prtg-version": "17.3.33.2830",
    "treesize": 4,
    "histdata": [{
        "***datetime***": "04.12.2017 16:35:08",
        "datetime_raw": 43073.5660648727,
        "value": "111.983 KByte",
        "value_raw": 114670936.0000,
        "***value***": "30.579 kbit/s",
        "value_raw": 3822364.5333,
        "value": "107.893 KByte",
        "value_raw": 110482503.0000,
        "value": "29.462 kbit/s",
        "value_raw": 3682750.1000,
        "value": "4.090 KByte",
        "value_raw": 4188433.0000,
        "value": "1.117 kbit/s",
        "value_raw": 139614.4333,
        "coverage": "100 %",
        "coverage_raw": 10000
    }, {
        "***datetime***": "04.12.2017 16:35:38",
        "datetime_raw": 43073.5664120718,
        "value": "85.464 KByte",
        "value_raw": 87514907.0000,
        "***value***": "23.345 kbit/s",
        "value_raw": 2918136.2788,
        "value": "81.993 KByte",
        "value_raw": 83960378.0000,
        "value": "22.397 kbit/s",
        "value_raw": 2799612.4708,
        "value": "3.471 KByte",
        "value_raw": 3554529.0000,
        "value": "948 kbit/s",
        "value_raw": 118523.8079,
        "coverage": "100 %",
        "coverage_raw": 10000
    }]
}

const result = data.histdata.map(hist => {
  const datetime = hist['***datetime***'].split(' ')[1];
  const value = hist['***value***'];
  return `${datetime},${value}`;
});

console.log(result)```

Title: How to parse Advanced Json Data

Body:
I have a JSON output like below. I am using getjson to get data. My aim is to take datetime and value field(italic and bold) like [16:35:08,30.579 kbit/s],[16:35:38,23.345 kbit/s]. Is there any way to succeed this? Thanks,

{
    "prtg-version": "17.3.33.2830",
    "treesize": 4,
    "histdata": [{
        "***datetime***": "04.12.2017 16:35:08",
        "datetime_raw": 43073.5660648727,
        "value": "111.983 KByte",
        "value_raw": 114670936.0000,
        "***value***": "30.579 kbit/s",
        "value_raw": 3822364.5333,
        "value": "107.893 KByte",
        "value_raw": 110482503.0000,
        "value": "29.462 kbit/s",
        "value_raw": 3682750.1000,
        "value": "4.090 KByte",
        "value_raw": 4188433.0000,
        "value": "1.117 kbit/s",
        "value_raw": 139614.4333,
        "coverage": "100 %",
        "coverage_raw": 10000
    }, {
        "***datetime***": "04.12.2017 16:35:38",
        "datetime_raw": 43073.5664120718,
        "value": "85.464 KByte",
        "value_raw": 87514907.0000,
        "***value***": "23.345 kbit/s",
        "value_raw": 2918136.2788,
        "value": "81.993 KByte",
        "value_raw": 83960378.0000,
        "value": "22.397 kbit/s",
        "value_raw": 2799612.4708,
        "value": "3.471 KByte",
        "value_raw": 3554529.0000,
        "value": "948 kbit/s",
        "value_raw": 118523.8079,
        "coverage": "100 %",
        "coverage_raw": 10000
    }]
}

Body:
Simply by map you array into a function and then parse the values as you desire.

The following example uses:

Array.map to loop through the array

String.split to split the string using whitespace and get only the last part

Template literals `` to output the value

Relevant method:

const result = data.histdata.map(hist => {
  const datetime = hist['***datetime***'].split(' ')[1];
  const value = hist['***value***'];
  return `${datetime},${value}`;
});

Check the snippet:

const data = {
    "prtg-version": "17.3.33.2830",
    "treesize": 4,
    "histdata": [{
        "***datetime***": "04.12.2017 16:35:08",
        "datetime_raw": 43073.5660648727,
        "value": "111.983 KByte",
        "value_raw": 114670936.0000,
        "***value***": "30.579 kbit/s",
        "value_raw": 3822364.5333,
        "value": "107.893 KByte",
        "value_raw": 110482503.0000,
        "value": "29.462 kbit/s",
        "value_raw": 3682750.1000,
        "value": "4.090 KByte",
        "value_raw": 4188433.0000,
        "value": "1.117 kbit/s",
        "value_raw": 139614.4333,
        "coverage": "100 %",
        "coverage_raw": 10000
    }, {
        "***datetime***": "04.12.2017 16:35:38",
        "datetime_raw": 43073.5664120718,
        "value": "85.464 KByte",
        "value_raw": 87514907.0000,
        "***value***": "23.345 kbit/s",
        "value_raw": 2918136.2788,
        "value": "81.993 KByte",
        "value_raw": 83960378.0000,
        "value": "22.397 kbit/s",
        "value_raw": 2799612.4708,
        "value": "3.471 KByte",
        "value_raw": 3554529.0000,
        "value": "948 kbit/s",
        "value_raw": 118523.8079,
        "coverage": "100 %",
        "coverage_raw": 10000
    }]
}

const result = data.histdata.map(hist => {
  const datetime = hist['***datetime***'].split(' ')[1];
  const value = hist['***value***'];
  return `${datetime},${value}`;
});

console.log(result)


问:
How to copy entire row based on Percentage comparison of 2 Cells
I'm trying to copy an entire row to another sheet if a cell is greater than 2% of another cell in the same row. This is what I'm stuck, getting an IF Greater based off a formula comparing 2 cells:

```<code>Sub Filtration()

For Each Cell In Sheets(1).Range("R:R")
    If Formula = "(R1 / P1)" > 0.021 Then
        matchRow = Cell.Row
        Rows(matchRow & ":" & matchRow).Select
        Selection.Copy

        Sheets("Sheet2").Select
        ActiveSheet.Rows(matchRow).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        Sheets("Sheet1").Select
    End If
Next
</code>```

EDIT: Thanks to @JNevil & @ShaiRado and the help they provide, I think I'm only stuck on the Macro returning an Overflow. I think that the percentage = Cell.Value / Cell.Offset(, -2).Value is being confused/conflicted some how and believes that percentage = 0 always. There is also the issue that my Sheet1 contains blank lines, a header, and possible negative numbers on future updates. The full code is as follows:

```<code>Sub Filtration()

Dim writeRow As Integer
Dim percentage As Double

For Each Cell In Sheets(1).Range("R:R")

    'because we don't want to do this for every cell in Column R (There are one million), then exit the loop when we need to
    If Cell.Value = "" Or Cell.Value <= 0 Then

    'Lets make sure we won't be dividing by zero. If we are then set the result to 0
    If Cell.Offset(, -2).Value < 0 Then
        percentage = 0
    Else

        percentage = Cell.Value / Cell.Offset(, -2).Value

    End If

    'divide the current cell's value by the the cell one column over's value and compare
    If percentage > 0.021 Then

        'Write this out to the writeRow variable in the other sheet and increment that number by 1 after writing
        Sheet1.Rows(Cell.Row).Copy Destination:=Sheet2.Cells(writeRow, 1).Paste
        writeRow = writeRow + 1
    End If
    End If
Next
    End Sub
</code>```

答:
Try the code below:</p>

```<code>Sub Filtration()

Dim Cell As Range
With Sheets(1)
    For Each Cell In .Range("R1:R" & .Cells(.Rows.Count, "R").End(xlUp).Row)
        If Cell.Value / Cell.Offset(, -2).Value > 0.021 Then
            .Rows(Cell.Row).Copy
             Sheets("Sheet2").Range("A" & Cell.Row).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
                                        SkipBlanks:=False, Transpose:=False
        End If
    Next
End With

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to copy an entire row to another sheet if a cell is greater than 2% of another cell in the same row. This is what I'm stuck, getting an IF Greater based off a formula comparing 2 cells:

Sub Filtration()

For Each Cell In Sheets(1).Range("R:R")
    If Formula = "(R1 / P1)" > 0.021 Then
        matchRow = Cell.Row
        Rows(matchRow & ":" & matchRow).Select
        Selection.Copy

        Sheets("Sheet2").Select
        ActiveSheet.Rows(matchRow).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        Sheets("Sheet1").Select
    End If
Next

EDIT: Thanks to @JNevil & @ShaiRado and the help they provide, I think I'm only stuck on the Macro returning an Overflow. I think that the percentage = Cell.Value / Cell.Offset(, -2).Value is being confused/conflicted some how and believes that percentage = 0 always. There is also the issue that my Sheet1 contains blank lines, a header, and possible negative numbers on future updates. The full code is as follows:

Sub Filtration()

Dim writeRow As Integer
Dim percentage As Double

For Each Cell In Sheets(1).Range("R:R")

    'because we don't want to do this for every cell in Column R (There are one million), then exit the loop when we need to
    If Cell.Value = "" Or Cell.Value <= 0 Then

    'Lets make sure we won't be dividing by zero. If we are then set the result to 0
    If Cell.Offset(, -2).Value < 0 Then
        percentage = 0
    Else

        percentage = Cell.Value / Cell.Offset(, -2).Value

    End If

    'divide the current cell's value by the the cell one column over's value and compare
    If percentage > 0.021 Then

        'Write this out to the writeRow variable in the other sheet and increment that number by 1 after writing
        Sheet1.Rows(Cell.Row).Copy Destination:=Sheet2.Cells(writeRow, 1).Paste
        writeRow = writeRow + 1
    End If
    End If
Next
    End Sub

Body:
Try the code below:

Sub Filtration()

Dim Cell As Range
With Sheets(1)
    For Each Cell In .Range("R1:R" & .Cells(.Rows.Count, "R").End(xlUp).Row)
        If Cell.Value / Cell.Offset(, -2).Value > 0.021 Then
            .Rows(Cell.Row).Copy
             Sheets("Sheet2").Range("A" & Cell.Row).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
                                        SkipBlanks:=False, Transpose:=False
        End If
    Next
End With

End Sub


问:
Can't connect to "Jenkins-On-Azure"
I created a Jenkins linux vm on Azure on a new resource group.

I followed the steps described here:
Create a Jenkins server on an Azure Linux VM from the Azure portal.

So I ran the command ssh -L 127.0.0.1:8080:localhost:8080 jenkinsadmin@jenkins2517454.eastus.cloudapp.azure.com
 (changed the username and dns name to my own) on my linux vm and it seems fine (no errors).

Now whenever I try to connect from my own computer (not on azure) on port 8080 I get on the linux vm the following message: channel 2: open failed: administratively prohibited: open failed and It doesn't let me log in into Jenkins.

How can it be solved?

Thank you

答:
In order to access from external network, you need to "add inbound port rule" as follows:

For more details, refer "Create Jenkins server on an Azure Linux VM from the Azure Portal".

Title: Can't connect to "Jenkins-On-Azure"


问:
Loss of precision when casting Math.pow()
I tried to calculate the maximum value of int, however I can not figure out why calculated value that is cast to int is lower than when cast to long. I raised (2^31) - 1 on the calculator and the value is

```<code>2_147_483_647
</code>```

and I would expect the same when I rise 2^31 and deduct 1 in Java, it should calculate maximum number for int 2147483647, but it doesn't.

```<code>System.out.println(((long) Math.pow(2, 31)) - 1);
System.out.println((int) Math.pow(2, 31) - 1);
</code>```

The first calculation gives: 2_147_483_647

Second calculation gives: 2_147_483_646

答:
Writing your code like this (int) Math.pow(2, 31) - 1 makes Java cast Math.pow(2, 31) to int. Since that is more than the max value of int, it results to be 2_147_483_647. Since you subtract 1 afterwards, you get a value lower than the actual solution.
You should rather cast the whole calculation to int than just Math.pow(2, 31) so it looks like this:
(int) (Math.pow(2, 31) - 1)

Body:
I tried to calculate the maximum value of int, however I can not figure out why calculated value that is cast to int is lower than when cast to long. I raised (2^31) - 1 on the calculator and the value is

2_147_483_647

and I would expect the same when I rise 2^31 and deduct 1 in Java, it should calculate maximum number for int 2147483647, but it doesn't.

System.out.println(((long) Math.pow(2, 31)) - 1);
System.out.println((int) Math.pow(2, 31) - 1);

The first calculation gives: 2_147_483_647

Second calculation gives: 2_147_483_646


问:
Change color of divider/text in dropdown menu/collapsed, How do i change them independently of each other in CSS
MY picture

in my picture on the left side with the collapsed dropdown menu, i have a white divider line, but now i also have a white divider line in my dropdown menu, and i want the divider in the dropdown menu to be a black divider line, and still keep my white divider line in the collapsed dropdown menu. How do i change them  independently of each other in CSS?

.navbar-header {
 padding-bottom: 45px;
}

.navbar-inverse .navbar-nav>.active>a, .navbar-inverse .navbar-nav>.active>a:hover, .navbar-inverse .navbar-nav>.active>a:focus {
  color: #fff;
  background-color:transparent;
}

.nav>li {
  position: relative;
  display: block;
  box-sizing: border-box;
  color: rgb(51, 51, 51);
  font-family: oswald, 'open sans', sans-serif;
  font-size: 14px;
  list-style-image: none;
  list-style-position: outside;
  list-style-type: none;
  text-align: left;
  text-transform: uppercase;
}

.dropdown-header  {
  list-style: none;
  font-size: 14px;
}

.navbar-inverse .navbar-collapse  {
  max-height: none;
}

.navbar-inverse .navbar-nav>li>a   {
  color: #fff;
  font-weight: 500;
  text-transform: uppercase;
  font-family: oswald, "MS Serif", "New York", serif;
  font-size: 14px;
}

.navbar-nav>li>a {
  padding-top: 2px;
  padding-bottom: 2px;
  line-height: 20px;
}

.nav>li>a {
  position: relative;
  display: block;
  padding: 10px 10px;
}

.navbar-inverse .navbar-nav>.active>a, .navbar-inverse {
  color: #82C332;
  font-weight: 500;
}

.navbar-inverse .navbar-nav .dropdown-menu .divider {
  background-color: #000;
}

.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
  background-color: #fff;
}

.open .dropdown-menu>li>a {
  color: #000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
     <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
     </button>
     <img src="img/logo/servicepc-logo1.png">
   </div>

   <div class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
     <li class="active">FORSIDE</li>
          <li class="dropdown">
          SERVICE <b class="caret"></b>
         <ul class="dropdown-menu">
      <li class="dropdown-header">Alle reparationer</li>
               <li class="divider"></li>
               <li>Computer Reparationer</li>
               <li>Backup</li>
               <li>Virus fjernelse</li>
               <li>Backup</li>
               <li>Data Recovery</li>
               <li>Rensning PC (Støv)</li>
               <li>Geninstallering af system</li>
               <li class="divider"></li>
               <li class="dropdown-header">Info</li>
               <li>Portfolio 1</li>
               <li>Portfolio 2</li>
  </ul>
    </li>
            <li>Priser</li>
             <li>OM OS</li>
   <li>KONTAKT</li>
  </ul>
 </div>
  </div>
</div></code>```

I hope you understand what i mean.

Kind Regards

Thomas

答:
In Bootstrap 4.0.0-beta.2 you can use:</p>

```<code><div class="dropdown-divider" style="border-color:black;"></div>
</code>```

Body:
MY picture

in my picture on the left side with the collapsed dropdown menu, i have a white divider line, but now i also have a white divider line in my dropdown menu, and i want the divider in the dropdown menu to be a black divider line, and still keep my white divider line in the collapsed dropdown menu. How do i change them  independently of each other in CSS?

.navbar-header {
 padding-bottom: 45px;
}

.navbar-inverse .navbar-nav>.active>a, .navbar-inverse .navbar-nav>.active>a:hover, .navbar-inverse .navbar-nav>.active>a:focus {
  color: #fff;
  background-color:transparent;
}

.nav>li {
  position: relative;
  display: block;
  box-sizing: border-box;
  color: rgb(51, 51, 51);
  font-family: oswald, 'open sans', sans-serif;
  font-size: 14px;
  list-style-image: none;
  list-style-position: outside;
  list-style-type: none;
  text-align: left;
  text-transform: uppercase;
}

.dropdown-header  {
  list-style: none;
  font-size: 14px;
}

.navbar-inverse .navbar-collapse  {
  max-height: none;
}

.navbar-inverse .navbar-nav>li>a   {
  color: #fff;
  font-weight: 500;
  text-transform: uppercase;
  font-family: oswald, "MS Serif", "New York", serif;
  font-size: 14px;
}

.navbar-nav>li>a {
  padding-top: 2px;
  padding-bottom: 2px;
  line-height: 20px;
}

.nav>li>a {
  position: relative;
  display: block;
  padding: 10px 10px;
}

.navbar-inverse .navbar-nav>.active>a, .navbar-inverse {
  color: #82C332;
  font-weight: 500;
}

.navbar-inverse .navbar-nav .dropdown-menu .divider {
  background-color: #000;
}

.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
  background-color: #fff;
}

.open .dropdown-menu>li>a {
  color: #000;
}

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    Toggle navigation

     </button>

FORSIDE

          SERVICE

Alle reparationer

Computer Reparationer

Backup

Virus fjernelse

Backup

Data Recovery

Rensning PC (Støv)

Geninstallering af system

Info

Portfolio 1

Portfolio 2

Priser

OM OS

KONTAKT

I hope you understand what i mean.

Kind Regards

Thomas

Body:
In Bootstrap 4.0.0-beta.2 you can use:

<div class="dropdown-divider" style="border-color:black;"></div>


问:
Quick successful exit from C++ with lots of objects allocated
I'm looking for a way to quickly exit a C++ that has allocated a lot of structures in memory using C++ classes.  The program finishes correctly, but after the final "return" in the program, all of the auto-destructors kick in.  The problem is the program has allocated about 15GB of memory through lots of C++ class structures, and this auto-destruct process takes about 1 more hour itself to complete as it walks through all of the structures - even though I don't care about the results.  The program only took 1 hour to complete the task up to this point.  I would like to just return to the OS and let it do its normal wholesale process allocation deletion - which is very quick.  I've been doing this by manually killing the process during the cleanup stage - but am looking for a better programic solution.

I would like to return a success to the OS, but don't care to keep any of the memory content.  The program does perform a lot of dynamic allocation/deallocation during the normal processing, so it's not just simple heap management.

Any opinions?

答: C++0x std::quick_exit is what you are looking for if your compiler already supports it (g++-4.4.5 does).</p>


答:
Your variable is getting the different values assigned correctly but you are showing all three instances inside the same DOM element. Each time you assign it, the current value overwrites the last value. And it is happening so fast, that you only see the last one ("John").

Why don't you put each one in a different DOM element?

```<code>var x;
document.getElementById("demo1").innerHTML = x;
x = 5;
document.getElementById("demo2").innerHTML = x;
x = "John";
document.getElementById("demo3").innerHTML = x;
</code>```

Title: how to display different data type values with same variable in javascript

Body:
Your variable is getting the different values assigned correctly but you are showing all three instances inside the same DOM element. Each time you assign it, the current value overwrites the last value. And it is happening so fast, that you only see the last one ("John").

Why don't you put each one in a different DOM element?

var x;
document.getElementById("demo1").innerHTML = x;
x = 5;
document.getElementById("demo2").innerHTML = x;
x = "John";
document.getElementById("demo3").innerHTML = x;


问:
How to join pthread which ended from array of running pthread
I have a chat server written in c++ and i have a problem with phtreads.
This server suppose to handle multiple connections so i created array of pthread. when a new client connects it gives one pthread to this client from the array and it calls handle function where is comunication inplemented. but when this client disconect i dont know how to find which pthread ended and which index to a pthread array is empty. i know this code is horrible but i really want to make this program better

so my question is that can i do it this way that when one pthread ends i will empty that index to array of pthread for potencial next client conected in and when more that lets say 100 people connect i will realloc the array ?

how do i find which pthread ended for joining that pthread and for finding which index is now free to use again ?

```<code>struct parsing{
     int socket;
};

int i = 0;
int strop = 100;
pthread_t *thread;
thread = (pthread_t*)malloc(sizeof(pthread_t)*100);
struct parsing args;
while (1)
{
    if((client_sock = accept(socket_desc, (struct sockaddr *)&socket_addr, (socklen_t *)&client_sock_len)) < 0)
    {
        fprintf(stderr,"Accept Error");
        return 5;
    }
    printf("connected %d",client_sock);
    args.socket = client_sock;
    pthread_create(&thread[i], NULL, &handle_connection, (void *)&args);
    i++;
    if (i == strop)
    {
        strop = strop + 100;
        void * ptr = (pthread_t*)realloc(thread,sizeof(pthread_t)*strop);
    }
}
</code>```

答:
how do i find which pthread ended for joining that pthread and for finding which index is now free to use again ?

The pthreads API does not provide a way to discover terminated threads.  Glibc has has a non-portable extension by which you can attempt a non-blocking join of a specific thread (see pthread_tryjoin_np()), and if that's available to you then you could build a polling-based solution around it.

But I'd say the right way to accomplish this is to establish a mechanism for worker threads to tell the main thread that they are done.  For instance, they might add their own thread ID to a linked list that the main thread can also see, and then send a signal or use pthread_cond_signal() to get the main thread's attention.  Do be sure to provide proper synchronization for multi-threaded access to shared variables.

Body:
I have a chat server written in c++ and i have a problem with phtreads.
This server suppose to handle multiple connections so i created array of pthread. when a new client connects it gives one pthread to this client from the array and it calls handle function where is comunication inplemented. but when this client disconect i dont know how to find which pthread ended and which index to a pthread array is empty. i know this code is horrible but i really want to make this program better

so my question is that can i do it this way that when one pthread ends i will empty that index to array of pthread for potencial next client conected in and when more that lets say 100 people connect i will realloc the array ?

how do i find which pthread ended for joining that pthread and for finding which index is now free to use again ?

struct parsing{
     int socket;
};

int i = 0;
int strop = 100;
pthread_t *thread;
thread = (pthread_t*)malloc(sizeof(pthread_t)*100);
struct parsing args;
while (1)
{
    if((client_sock = accept(socket_desc, (struct sockaddr *)&socket_addr, (socklen_t *)&client_sock_len)) < 0)
    {
        fprintf(stderr,"Accept Error");
        return 5;
    }
    printf("connected %d",client_sock);
    args.socket = client_sock;
    pthread_create(&thread[i], NULL, &handle_connection, (void *)&args);
    i++;
    if (i == strop)
    {
        strop = strop + 100;
        void * ptr = (pthread_t*)realloc(thread,sizeof(pthread_t)*strop);
    }
}


问:
gform_get_meta and wp_rg_lead_meta are empty
I'm trying to use https://docs.gravityforms.com/gform_get_meta/ API to get the Zoho CRM inserted ID using 'zohocrm_contact_id' as the meta key.

But, I get a false response and When I look at the wp_rg_lead_meta table, it is empty. Any Idea why this is happening and How to rectify it? Below is my PHP code for your reference

```<code>$my_form_id = '1';
$search_criteria = array();
$search_criteria['field_filters'][] = array( 'key' => '3', 'value' =>
$_POST['email']);
$form_data = GFAPI::get_entries( $my_form_id , $search_criteria );
$meta_value = gform_get_meta( $form_data[0]['id'], 'zohocrm_contact_id'
);//entry_id is 43
echo $meta_value;//false
</code>```

答:
I would like to answer my own question from the answer I got from Grav Form priority support.

The GFAPI::add_entry method only adds the entry directly to the database, it does not trigger any add-on integrations. If you need the Zoho add-on integration to be triggered you would need to use the GFAPI::submit_form method or manually trigger feed processing for the entry like so:

```<code>$entry_id = GFAPI::add_entry($data);
if ( ! is_wp_error( $entry_id ) && function_exists( 'gf_zohocrm' ) ) {
    $entry = GFAPI::get_entry( $entry_id );
    $form = GFAPI::get_form( $entry['form_id'] );
    gf_zohocrm()->maybe_process_feed( $entry, $form );
}
</code>```

Body:
I'm trying to use https://docs.gravityforms.com/gform_get_meta/ API to get the Zoho CRM inserted ID using 'zohocrm_contact_id' as the meta key.

But, I get a false response and When I look at the wp_rg_lead_meta table, it is empty. Any Idea why this is happening and How to rectify it? Below is my PHP code for your reference

$my_form_id = '1';
$search_criteria = array();
$search_criteria['field_filters'][] = array( 'key' => '3', 'value' =>
$_POST['email']);
$form_data = GFAPI::get_entries( $my_form_id , $search_criteria );
$meta_value = gform_get_meta( $form_data[0]['id'], 'zohocrm_contact_id'
);//entry_id is 43
echo $meta_value;//false

Body:
I would like to answer my own question from the answer I got from Grav Form priority support.

The GFAPI::add_entry method only adds the entry directly to the database, it does not trigger any add-on integrations. If you need the Zoho add-on integration to be triggered you would need to use the GFAPI::submit_form method or manually trigger feed processing for the entry like so:

$entry_id = GFAPI::add_entry($data);
if ( ! is_wp_error( $entry_id ) && function_exists( 'gf_zohocrm' ) ) {
    $entry = GFAPI::get_entry( $entry_id );
    $form = GFAPI::get_form( $entry['form_id'] );
    gf_zohocrm()->maybe_process_feed( $entry, $form );
}


问:
looping date with statement from database table in codeigniter
i'm newbie Programmer Codeigniter

i want to show all days from 1 month and give statement from the table of holiday date (i have 46 holiday). i want if holiday, the date show is red.

my controller like this

```<code>function attendance()
{
    $data = $this->page();
    $data['this_month'] = date('m');
    $data['this_year']  = date('Y');
    $data['this_day']   = date('d');
    $this_month = date('m');
    $month = $this->m_date->month($this_month)->row_array();
    $data['day_total'] = $month['day_total'];
    $data['holiday'] = $this->m_date->holiday()->result_array();
    $data['attendance']= $this->m_module->attendance()->result_array();
    $data['employee']= $this->m_module->employee()->result_array();
    $this->template->display($data['link'],$data);
}
</code>```

this is my view

```<code><?php for($m=1; $m <= $day_total; $m++){ ?>
                <?php foreach ($holiday AS $date){ ?>
                    <?php if ($date['tgl'] === date('Y-m-d', strtotime($this_year.'-'.$this_month.'-'.$m))){
                        echo '<th bgcolor="red">'.$m.'</th>';
                    }else{
                        echo '<th bgcolor="">'.$m.'</th>';
                    } ?>
                <?php } ?>
            <?php } ?>
</code>```

but when i run in the browser, show like this

error looping image

please help me for this problem.

Thank you.

答:
I updated the code

in your holiday-loop you echo the date in every iteration, try something like this:

```<code><?php
 for($m=1; $m <= $day_total; $m++){
     $color ="";
     foreach ($holiday AS $date){
           if ($date['tgl'] === date('Y-m-d', strtotime($this_year.'-'.$this_month.'-'.$m))){
               $color="red";
           }
      }
     echo '<th bgcolor="'. $color  .'">'.$m.'</th>';
  }
?>
</code>```

Body:
i'm newbie Programmer Codeigniter

i want to show all days from 1 month and give statement from the table of holiday date (i have 46 holiday). i want if holiday, the date show is red.

my controller like this

function attendance()
{
    $data = $this->page();
    $data['this_month'] = date('m');
    $data['this_year']  = date('Y');
    $data['this_day']   = date('d');
    $this_month = date('m');
    $month = $this->m_date->month($this_month)->row_array();
    $data['day_total'] = $month['day_total'];
    $data['holiday'] = $this->m_date->holiday()->result_array();
    $data['attendance']= $this->m_module->attendance()->result_array();
    $data['employee']= $this->m_module->employee()->result_array();
    $this->template->display($data['link'],$data);
}

this is my view

<?php for($m=1; $m <= $day_total; $m++){ ?>
                <?php foreach ($holiday AS $date){ ?>
                    <?php if ($date['tgl'] === date('Y-m-d', strtotime($this_year.'-'.$this_month.'-'.$m))){
                        echo ''.$m.'	';
                    }else{
                        echo ''.$m.'	';
                    } ?>
                <?php } ?>
            <?php } ?>

but when i run in the browser, show like this

error looping image

please help me for this problem.

Thank you.

Body:
I updated the code

in your holiday-loop you echo the date in every iteration, try something like this:

<?php
 for($m=1; $m <= $day_total; $m++){
     $color ="";
     foreach ($holiday AS $date){
           if ($date['tgl'] === date('Y-m-d', strtotime($this_year.'-'.$this_month.'-'.$m))){
               $color="red";
           }
      }
     echo '<th bgcolor="'. $color  .'">'.$m.'</th>';
  }
?>


问:
How to show symfony validation errors?
I try to visualize my error messages from the validator.
When i write the following example:-

```<code>{{ form_errors(form.pGWeek) }}
</code>```

it works fine and i get the message. But my form has 200 fields and so it's not practical.

So i want to iterate over an Array with all messages, at the end of the form like this:

```<code>{% if form.name.vars.errors|length > 0 %}
  <ul class="form-errors name">
   {% for error in form.name.vars.errors %}
        {{ error }}
 {% endfor %}
  </ul>
{% endif %}
</code>```

But i did not get some messages. As well i tried some another versions.. but nothing worked. I'm using Symfony 2.7.

Can give me somebody a tip?

Thanks for a short feedback.

答:
So you just want to show all errors for all children of a form without displaying them beside each input field?

Then you could iterate over all the children of your form, check if any errors appeared on this children and if so, iterate over all errors of this children. That could be something like that:

```<code>   {% for children in form.children %}
       {% if children.vars.errors is defined %}
           {% for error in children.vars.errors %}
               {#{{ dump(children) }}#}
               {#{{ dump(error) }}#}
               {{ dump(children.vars.name ~ ': ' ~ error.message) }}
            {% endfor %}
        {% endif %}
   {% endfor %}
</code>```

Which result in an error like description: This value should not be blank..

Title: How to show symfony validation errors?

Body:
I try to visualize my error messages from the validator.
When i write the following example:-

{{ form_errors(form.pGWeek) }}

it works fine and i get the message. But my form has 200 fields and so it's not practical.

So i want to iterate over an Array with all messages, at the end of the form like this:

{% if form.name.vars.errors|length > 0 %}

   {% for error in form.name.vars.errors %}
        {{ error }}
 {% endfor %}

{% endif %}

But i did not get some messages. As well i tried some another versions.. but nothing worked. I'm using Symfony 2.7.

Can give me somebody a tip?

Thanks for a short feedback.

Body:
So you just want to show all errors for all children of a form without displaying them beside each input field?

Then you could iterate over all the children of your form, check if any errors appeared on this children and if so, iterate over all errors of this children. That could be something like that:

   {% for children in form.children %}
       {% if children.vars.errors is defined %}
           {% for error in children.vars.errors %}
               {#{{ dump(children) }}#}
               {#{{ dump(error) }}#}
               {{ dump(children.vars.name ~ ': ' ~ error.message) }}
            {% endfor %}
        {% endif %}
   {% endfor %}

Which result in an error like description: This value should not be blank..


问:
Copy cell and adjacent cell and insert as new row: Excel VBA
I'm trying to copy a cell and the adjacent cell in a row and insert it as a new row with all the data to the right of this cell also copied over. My data looks like this after mining.

and im trying to get my data to look like this:

the image above is just one record but essentially its moving all the people and their corresponding position in the original row to a new row. In each row there are about 5 employees and their positions.

thanks

EDIT Attempted code for just 2 cols. 1 position. the idea was to create the empty rows and just copy the rest of the data with auto fill, then work from there

```<code>Sub TransposeInsertRows()
    Dim rng As Range
    Dim i As Long, j As Long, k As Long
    Dim x As Long, y As Long
    Set rng = Application.InputBox _
    (Prompt:="Range Selection...", _
    Title:="Enter the name col and pos col", Type:=8)
    Application.ScreenUpdating = False
    x = rng(1, 1).Column + 2
    y = rng(1, rng.Columns.Count).Column
    For i = rng(rng.Rows.Count, 1).Row To rng(1, 1).Row Step -1
        If Cells(i, x) <> "" And Cells(i, x + 1) <> "" Then
            k = Cells(i, x - 2).End(xlToRight).Column
            If k > y Then k = y
            For j = k To x + 1 Step -1
                Cells(i + 1, 1).EntireRow.Insert
                With Cells(i + 1, x - 2)
                    .Value = .Offset(-1, 0)
                    .Offset(0, 1) = .Offset(-1, 1)
                    .Offset(0, 2) = Cells(i, j)
                End With
                Cells(i, j).ClearContents
            Next j
        End If
    Next i
    Application.ScreenUpdating = True
End Sub
</code>```

答:
If there are always 5 people in each row then this should do it:</p>

```<code>Sub foo()
LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row
For i = 1 To LastRow 'loop through rows
    For x = 1 To 10 Step 2 'loop through columns
        LastRow2 = Sheet2.Cells(Sheet2.Rows.Count, "A").End(xlUp).Row + 1 'find the next free row on Sheet2
        Sheet2.Cells(LastRow2, 1).Value = Sheet1.Cells(i, x).Value 'add Person Name to Sheet2
        Sheet2.Cells(LastRow2, 2).Value = Sheet1.Cells(i, x + 1).Value 'add position to Sheet2
        Sheet1.Range("K" & i & ":U" & i).Copy Destination:=Sheet2.Cells(LastRow2, 3) 'copy range from K to U to Sheet2
    Next x
Next i
End Sub
</code>```

Body:
I'm trying to copy a cell and the adjacent cell in a row and insert it as a new row with all the data to the right of this cell also copied over. My data looks like this after mining.

and im trying to get my data to look like this:

the image above is just one record but essentially its moving all the people and their corresponding position in the original row to a new row. In each row there are about 5 employees and their positions.

thanks

EDIT Attempted code for just 2 cols. 1 position. the idea was to create the empty rows and just copy the rest of the data with auto fill, then work from there

Sub TransposeInsertRows()
    Dim rng As Range
    Dim i As Long, j As Long, k As Long
    Dim x As Long, y As Long
    Set rng = Application.InputBox _
    (Prompt:="Range Selection...", _
    Title:="Enter the name col and pos col", Type:=8)
    Application.ScreenUpdating = False
    x = rng(1, 1).Column + 2
    y = rng(1, rng.Columns.Count).Column
    For i = rng(rng.Rows.Count, 1).Row To rng(1, 1).Row Step -1
        If Cells(i, x) <> "" And Cells(i, x + 1) <> "" Then
            k = Cells(i, x - 2).End(xlToRight).Column
            If k > y Then k = y
            For j = k To x + 1 Step -1
                Cells(i + 1, 1).EntireRow.Insert
                With Cells(i + 1, x - 2)
                    .Value = .Offset(-1, 0)
                    .Offset(0, 1) = .Offset(-1, 1)
                    .Offset(0, 2) = Cells(i, j)
                End With
                Cells(i, j).ClearContents
            Next j
        End If
    Next i
    Application.ScreenUpdating = True
End Sub

Body:
If there are always 5 people in each row then this should do it:

Sub foo()
LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row
For i = 1 To LastRow 'loop through rows
    For x = 1 To 10 Step 2 'loop through columns
        LastRow2 = Sheet2.Cells(Sheet2.Rows.Count, "A").End(xlUp).Row + 1 'find the next free row on Sheet2
        Sheet2.Cells(LastRow2, 1).Value = Sheet1.Cells(i, x).Value 'add Person Name to Sheet2
        Sheet2.Cells(LastRow2, 2).Value = Sheet1.Cells(i, x + 1).Value 'add position to Sheet2
        Sheet1.Range("K" & i & ":U" & i).Copy Destination:=Sheet2.Cells(LastRow2, 3) 'copy range from K to U to Sheet2
    Next x
Next i
End Sub


问:
Should I Ajax or should I store the whole collection into a variable ?
I am building a single page app.
The app has a list of 7000 ports stored in a MongoDB database.
I need to be able to search for those ports with autocomplete on the search.

Should I Ajax the autocomplete results ?

OR

Should I retrieve the whole collection of ports, store it in a variable, plug my autocomplete on this array ?

What's the best practice ?
What's the smartest performance wise ?

答:
Best practice and smartest performance wise is to:

Send the search string to an API resource, example:

```<code>/autocomplete?search=portname1
</code>```

Retrieve the autocomplete results and visualize them

You can use existing JS libraries for autocomplete (avoid discovering the hot water)

Body:
Best practice and smartest performance wise is to:

Send the search string to an API resource, example:

/autocomplete?search=portname1

Retrieve the autocomplete results and visualize them

You can use existing JS libraries for autocomplete (avoid discovering the hot water)


问:
How to format a string containing numbers and characters
I have the following string "2017-2" and I need to format it as "2017-02".

```<code>var period = "2017-2";
var periodFormatted = String.Format("{0:0000-00}", period);
</code>```

periodFormatted returns "2017-2"

What is the correct syntax to get the period formatted as "2017-02"?

答:
You can parse the input-string as DateTime and format it in a second step.

```<code>string period = "2017-2";
DateTime temp = DateTime.ParseExact(period, "yyyy-M", CultureInfo.InvariantCulture );
string result = temp.ToString("yyyy-MM");
</code>```

Note: M defines the month without leading 0 and MM is always 2 digit month.

Reference: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

Body:
I have the following string "2017-2" and I need to format it as "2017-02".

var period = "2017-2";
var periodFormatted = String.Format("{0:0000-00}", period);

periodFormatted returns "2017-2"

What is the correct syntax to get the period formatted as "2017-02"?

Body:
You can parse the input-string as DateTime and format it in a second step.

string period = "2017-2";
DateTime temp = DateTime.ParseExact(period, "yyyy-M", CultureInfo.InvariantCulture );
string result = temp.ToString("yyyy-MM");

Note: M defines the month without leading 0 and MM is always 2 digit month.

Reference: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings


问:
jQuery - building a banner with a timeout
I want to build a banner that says "Loading", and hides when the application is done.

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

function ajaxBanner(action, confirmMsg) {

    if (action == 'show') {
        $('#msg').text('Loading...');
        $('#ajaxBanner').show();
    } else if (action == 'hide') {
        $('#ajaxBanner').fadeOut();
    } else if (confirmMsg == true) {
        $('#ajaxBanner').show();
        ajaxBanner_timeout = setTimeout(ajaxBanner('hide'), 2000);
    }
};
</code>```

The function shows a "Loading" banner message to the user and later hides it. The thing is, I also want to use this space for confirmation messages, like "XXXX Added to XXX".

The problem is, when confirmMsg is true, it is getting killed by a subsequent AJAX call with does Action show.

How can I say only do action==show or action==hide when the ajaxBanner_timeout is complete?

答:
```<code>var ajaxBanner_callback = function (){};
function ajaxBanner(action, confirmMsg) {

  if (action == 'show') {
      var ajaxBanner_callback = function () {
        $('#msg').text('Loading...');
        $('#ajaxBanner').show();
      }
     if (!ajaxBanner_timeout) ajaxBanner_callback();
  }
  else if (action == 'hide') {
      var ajaxBanner_callback = function () {
        $('#ajaxBanner').fadeOut();
      }
     if (!ajaxBanner_timeout) ajaxBanner_callback();
  }
  else if (confirmMsg == true) {
      $('#ajaxBanner').show();
      ajaxBanner_timeout = setTimeout(function () {
        ajaxBanner_callback();
        clearTimeout(ajaxBanner_timeout);
        ajaxBanner_callback = function (){};
      }, 2000);
  }
};
</code>```

You can do the same to the confirmMsg if you want.

It might be useful investigating into $.queue()

Body:
I want to build a banner that says "Loading", and hides when the application is done.

function ajaxBanner(action, confirmMsg) {

    if (action == 'show') {
        $('#msg').text('Loading...');
        $('#ajaxBanner').show();
    } else if (action == 'hide') {
        $('#ajaxBanner').fadeOut();
    } else if (confirmMsg == true) {
        $('#ajaxBanner').show();
        ajaxBanner_timeout = setTimeout(ajaxBanner('hide'), 2000);
    }
};

The function shows a "Loading" banner message to the user and later hides it. The thing is, I also want to use this space for confirmation messages, like "XXXX Added to XXX".

The problem is, when confirmMsg is true, it is getting killed by a subsequent AJAX call with does Action show.

How can I say only do action==show or action==hide when the ajaxBanner_timeout is complete?

Body:
var ajaxBanner_callback = function (){};
function ajaxBanner(action, confirmMsg) {

  if (action == 'show') {
      var ajaxBanner_callback = function () {
        $('#msg').text('Loading...');
        $('#ajaxBanner').show();
      }
     if (!ajaxBanner_timeout) ajaxBanner_callback();
  }
  else if (action == 'hide') {
      var ajaxBanner_callback = function () {
        $('#ajaxBanner').fadeOut();
      }
     if (!ajaxBanner_timeout) ajaxBanner_callback();
  }
  else if (confirmMsg == true) {
      $('#ajaxBanner').show();
      ajaxBanner_timeout = setTimeout(function () {
        ajaxBanner_callback();
        clearTimeout(ajaxBanner_timeout);
        ajaxBanner_callback = function (){};
      }, 2000);
  }
};

You can do the same to the confirmMsg if you want.

It might be useful investigating into $.queue()


问:
aspect ratio div inside another aspect ratio div not working as intended
What is wrong with my code, please? Why is the inner div(two) fill the outer div instead of keeping its aspect ratio by padding-bottom?

.one {
  position: relative;
  background: #990000;
  background-size: contain;
}

.one:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 40%;
}

.one:after {
  content: "";
  display: table;
  clear: both;
}

.two {
  position: relative;
  top: 0;
  background: #009900;
}

.two:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 20%;
}

.two:after {
  content: "";
  display: table;
  clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="one">
  <div class="two"></div>
</div></code>```

https://jsfiddle.net/mhk99j8z/

答:
It's because you don't clear your one:before float - your one:after comes after two - :after appends at the end of an element (after all other elements)

.one {
  position: relative;
  background: #990000;
  background-size: contain;
}

.one:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 40%;
}

.two {
  clear:left;             /* remove one:after and clear on two */
  position: relative;
  top: 0;
  background: #009900;
}

.two:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 20%;
}

.two:after {
  content: "";
  display: table;
  clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="one">
  <div class="two"></div>
</div></code>```

Body:
What is wrong with my code, please? Why is the inner div(two) fill the outer div instead of keeping its aspect ratio by padding-bottom?

.one {
  position: relative;
  background: #990000;
  background-size: contain;
}

.one:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 40%;
}

.one:after {
  content: "";
  display: table;
  clear: both;
}

.two {
  position: relative;
  top: 0;
  background: #009900;
}

.two:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 20%;
}

.two:after {
  content: "";
  display: table;
  clear: both;
}

https://jsfiddle.net/mhk99j8z/

Body:
It's because you don't clear your one:before float - your one:after comes after two - :after appends at the end of an element (after all other elements)

.one {
  position: relative;
  background: #990000;
  background-size: contain;
}

.one:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 40%;
}

.two {
  clear:left;             /* remove one:after and clear on two */
  position: relative;
  top: 0;
  background: #009900;
}

.two:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 20%;
}

.two:after {
  content: "";
  display: table;
  clear: both;
}

<div class="one">
  <div class="two"></div>
</div>


问:
run time annotation scanning when Dynamic class loading
```<code>import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

// declare a new annotation
@Retention(RetentionPolicy.RUNTIME)
@interface Demo {
   String str();
   int val();
}

public class PackageDemo {

   // set values for the annotation
   @Demo(str = "Demo Annotation", val = 100)
   // a method to call in the main
   public static void example() {
      PackageDemo ob = new PackageDemo();

      try {
         Class c = ob.getClass();

         // get the method example
         Method m = c.getMethod("example");

         // get the annotation for class Demo
         Demo annotation = m.getAnnotation(Demo.class);

         // print the annotation
         System.out.println(annotation.str() + " " + annotation.val());
      } catch (NoSuchMethodException exc) {
         exc.printStackTrace();
      }
   }
   public static void main(String args[]) {
      example();
   }
}
</code>```

My objective is to check the annotation on few methods and if it exists on the annotation , I need to get the annotation.

```<code>Demo annotation = m.getAnnotation(Demo.class);
</code>```

In the above example , the annotation is declared in the same file. If annotation is in a different package I can do something like

```<code>import com.this.class.DemoClass
try {
         Class c = ob.getClass();

         // get the method example
         Method m = c.getMethod("example");

         // get the annotation for class Demo
         Demo annotation = m.getAnnotation(Demo.class);
</code>```

But if I want to load the DemoClass/AnnotationClass dynamically like

```<code>Class<?> Demo = Class.forName("com.this.class.DemoClass")
</code>```

How do I get the annotation on the methods. I think the below line doesn't works in this case

```<code>Demo annotation = m.getAnnotation(Demo.class);
</code>```

答:
When the annotation is loaded dynamically into variable, Demo, then use that variable to get the annotation:

```<code>Class<?> Demo = Class.forName("com.this.class.DemoClass");
Demo annotation = m.getAnnotation(Demo);
</code>```

Body:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

// declare a new annotation
@Retention(RetentionPolicy.RUNTIME)
@interface Demo {
   String str();
   int val();
}

public class PackageDemo {

   // set values for the annotation
   @Demo(str = "Demo Annotation", val = 100)
   // a method to call in the main
   public static void example() {
      PackageDemo ob = new PackageDemo();

      try {
         Class c = ob.getClass();

         // get the method example
         Method m = c.getMethod("example");

         // get the annotation for class Demo
         Demo annotation = m.getAnnotation(Demo.class);

         // print the annotation
         System.out.println(annotation.str() + " " + annotation.val());
      } catch (NoSuchMethodException exc) {
         exc.printStackTrace();
      }
   }
   public static void main(String args[]) {
      example();
   }
}

My objective is to check the annotation on few methods and if it exists on the annotation , I need to get the annotation.

Demo annotation = m.getAnnotation(Demo.class);

In the above example , the annotation is declared in the same file. If annotation is in a different package I can do something like

import com.this.class.DemoClass
try {
         Class c = ob.getClass();

         // get the method example
         Method m = c.getMethod("example");

         // get the annotation for class Demo
         Demo annotation = m.getAnnotation(Demo.class);

But if I want to load the DemoClass/AnnotationClass dynamically like

Class<?> Demo = Class.forName("com.this.class.DemoClass")

How do I get the annotation on the methods. I think the below line doesn't works in this case

Demo annotation = m.getAnnotation(Demo.class);

Body:
When the annotation is loaded dynamically into variable, Demo, then use that variable to get the annotation:

Class<?> Demo = Class.forName("com.this.class.DemoClass");
Demo annotation = m.getAnnotation(Demo);


问:
Asp.net Core Error when publish on IIS 10
I published my application and got this error:

An error occurred while starting the application.

.NET Core X64 v4.1.1.0    |   Microsoft.AspNetCore.Hosting version 1.1.1    |    Microsoft Windows 10.0.14393    |   Need help?

See the log File:

```<code>Application startup exception: System.FormatException: Could not parse the JSON file. Error on line number '9': '"ConnectionStrings": {
"EstudantesCV21Context": "Provider=SQLOLEDB.1;Password=******;Persist Security Info=True;User ID=sa;Initial Catalog=EstudantesCV21Context-241ea716-db64-402d-955f-be4b264ce053;Data Source=*********"'. ---> Newtonsoft.Json.JsonReaderException: Bad JSON escape sequence: \S. Path 'ConnectionStrings.EstudantesCV21Context', line 9, position 209.
   at Newtonsoft.Json.JsonTextReader.ReadStringIntoBuffer(Char quote)
   at Newtonsoft.Json.JsonTextReader.ParseString(Char quote, ReadType readType)
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.Linq.JContainer.ReadContentFrom(JsonReader r, JsonLoadSettings settings)
   at Newtonsoft.Json.Linq.JContainer.ReadTokenFrom(JsonReader reader, JsonLoadSettings options)
   at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader, JsonLoadSettings settings)
   at Microsoft.Extensions.Configuration.Json.JsonConfigurationFileParser.Parse(Stream input)
   at Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider.Load(Stream stream)
   --- End of inner exception stack trace ---
   at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
   at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
   at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
   at EstudantesCV21.Startup..ctor(IHostingEnvironment env) in C:\Users\erito\onedrive\documentos\visual studio 2017\Projects\CadastroCV21\EstudantesCV21\Startup.cs:line 26
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.AspNetCore.Hosting.Internal.StartupLoader.LoadMethods(IServiceProvider hostingServiceProvider, Type startupType, String environmentName)
   at Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.<>c__DisplayClass1_0.<UseStartup>b__1(IServiceProvider sp)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureStartup()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: C:\WebSite
Now listening on: http://localhost:18998
Application started. Press Ctrl+C to shut down.
</code>```

connection string:

```<code>{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "EstudantesCV21Context": "Server=myserver\SQLEXPRESS;Database=mydatabase;userid=myid;password=mypass"
  }
}
</code>```

答:
I don't know if you still need an answer to this problem. I had this problem and I solved it by changing my connection string like this.  Add double back slashes

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "EstudantesCV21Context": "Server=myserver\\SQLEXPRESS;Database=mydatabase;userid=myid;password=mypass"
  }
}

Body:
I published my application and got this error:

An error occurred while starting the application.

.NET Core X64 v4.1.1.0    |   Microsoft.AspNetCore.Hosting version 1.1.1    |    Microsoft Windows 10.0.14393    |   Need help?

See the log File:

Application startup exception: System.FormatException: Could not parse the JSON file. Error on line number '9': '"ConnectionStrings": {
"EstudantesCV21Context": "Provider=SQLOLEDB.1;Password=******;Persist Security Info=True;User ID=sa;Initial Catalog=EstudantesCV21Context-241ea716-db64-402d-955f-be4b264ce053;Data Source=*********"'. ---> Newtonsoft.Json.JsonReaderException: Bad JSON escape sequence: \S. Path 'ConnectionStrings.EstudantesCV21Context', line 9, position 209.
   at Newtonsoft.Json.JsonTextReader.ReadStringIntoBuffer(Char quote)
   at Newtonsoft.Json.JsonTextReader.ParseString(Char quote, ReadType readType)
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.Linq.JContainer.ReadContentFrom(JsonReader r, JsonLoadSettings settings)
   at Newtonsoft.Json.Linq.JContainer.ReadTokenFrom(JsonReader reader, JsonLoadSettings options)
   at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader, JsonLoadSettings settings)
   at Microsoft.Extensions.Configuration.Json.JsonConfigurationFileParser.Parse(Stream input)
   at Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider.Load(Stream stream)
   --- End of inner exception stack trace ---
   at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
   at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
   at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
   at EstudantesCV21.Startup..ctor(IHostingEnvironment env) in C:\Users\erito\onedrive\documentos\visual studio 2017\Projects\CadastroCV21\EstudantesCV21\Startup.cs:line 26
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.AspNetCore.Hosting.Internal.StartupLoader.LoadMethods(IServiceProvider hostingServiceProvider, Type startupType, String environmentName)
   at Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.<>c__DisplayClass1_0.<UseStartup>b__1(IServiceProvider sp)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureStartup()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: C:\WebSite
Now listening on: http://localhost:18998
Application started. Press Ctrl+C to shut down.

connection string:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "EstudantesCV21Context": "Server=myserver\SQLEXPRESS;Database=mydatabase;userid=myid;password=mypass"
  }
}


问:
C string arrays

Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

```<code>char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";
</code>```

It won't compile saying Incompatible types in assignment. What am I doing wrong?

答:
You probably wanted:

```<code>char* result[3];
result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";
</code>```

What you did was wrong for two reasons.

First, you can't "assign" a string to a char array like that, you'd have to use, for example, strcpy.

Second, your array dimension was also wrong, char array[4] obviously won't hold "horse" or "chicken", so it wouldn't work even if you corrected what I said above (it would compile, but you would be writing to memory you shouldn't be writing to).

What the corrected code does, is instead of storing the char array per se, it stores a pointer to the location in memory where "horse", etc., are stored. Therefore, it just stores an address, and you can then use the = operator.

Title: C string arrays

Body:
Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

It won't compile saying Incompatible types in assignment. What am I doing wrong?

Body:
You probably wanted:

char* result[3];
result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

What you did was wrong for two reasons.

First, you can't "assign" a string to a char array like that, you'd have to use, for example, strcpy.

Second, your array dimension was also wrong, char array[4] obviously won't hold "horse" or "chicken", so it wouldn't work even if you corrected what I said above (it would compile, but you would be writing to memory you shouldn't be writing to).

What the corrected code does, is instead of storing the char array per se, it stores a pointer to the location in memory where "horse", etc., are stored. Therefore, it just stores an address, and you can then use the = operator.


问:
Execute Multiple Asynchronous Route Guards in Order
I know angular route guards execute in the specified order when the canActivate function returns a simple boolean, however, what if the guards return type Observable<boolean> or Promise<boolean>?

Example in route:

```<code>{
    path: 'confirm',
    canActivate: [AuthGuard, SessionExpiredAuthGuard, CheckoutAuthGuard],
    component: CheckoutReviewOrderComponent
},
</code>```

SessionExpiredAuthGuard and CheckoutAuthGuard both return type Observable<boolean>. I don't want the CheckoutAuthGuard to be executed before the SessionExpiredAuthGuard is finished retrieving it's data from the asynchronous http request.

Is there any way to force these asynchronous guards to execute in order?

答:
Problem

First of all, angular doesn't support the feature to call the guards in tandem. So if first guard is asynchronous and is trying to make ajax calls, all the remaining guards will get fired even before completion of the ajax request in guard 1.

I faced the similar problem and this is how I solved it -

Solution

The idea is to create a master guard and let the master guard handle the execution of other guards.

The routing configuration in this case, will contain master guard as the only guard.

To let master guard know about the guards to be triggered for specific routes, add a data property in Route.

The data property is a key value pair that allows us to attach data with the routes.

The data can then be accessed in the guards using ActivatedRouteSnapshot parameter of canActivate method in the guard.

The solution looks complicated but it will assure proper working of guards once it is integrated in the application.

Following example explains this approach -

Example

1. Constants Object to map all application guards -

```<code>export const GUARDS = {
    GUARD1: "GUARD1",
    GUARD2: "GUARD2",
    GUARD3: "GUARD3",
    GUARD4: "GUARD4",
}
</code>```

2. Application Guard -

```<code>import { Injectable } from "@angular/core";
import { Guard4DependencyService } from "./guard4dependency";

@Injectable()
export class Guard4 implements CanActivate {
    //A  guard with dependency
    constructor(private _Guard4DependencyService:  Guard4DependencyService) {}

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        return new Promise((resolve: Function, reject: Function) => {
            //logic of guard 4 here
            if (this._Guard4DependencyService.valid()) {
                resolve(true);
            } else {
                reject(false);
            }
        });
    }
}
</code>```

3. Routing Configuration -

```<code>import { Route } from "@angular/router";
import { View1Component } from "./view1";
import { View2Component } from "./view2";
import { MasterGuard, GUARDS } from "./master-guard";
export const routes: Route[] = [
    {
        path: "view1",
        component: View1Component,
        //attach master guard here
        canActivate: [MasterGuard],
        //this is the data object which will be used by
        //masteer guard to execute guard1 and guard 2
        data: {
            guards: [
                GUARDS.GUARD1,
                GUARDS.GUARD2
            ]
        }
    },
    {
        path: "view2",
        component: View2Component,
        //attach master guard here
        canActivate: [MasterGuard],
        //this is the data object which will be used by
        //masteer guard to execute guard1, guard 2, guard 3 & guard 4
        data: {
            guards: [
                GUARDS.GUARD1,
                GUARDS.GUARD2,
                GUARDS.GUARD3,
                GUARDS.GUARD4
            ]
        }
    }
];
</code>```

4. Master Guard -

```<code>import { Injectable } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";

//import all the guards in the application
import { Guard1 } from "./guard1";
import { Guard2 } from "./guard2";
import { Guard3 } from "./guard3";
import { Guard4 } from "./guard4";

import { Guard4DependencyService } from "./guard4dependency";

@Injectable()
export class MasterGuard implements CanActivate {

    //you may need to include dependencies of individual guards if specified in guard constructor
    constructor(private _Guard4DependencyService:  Guard4DependencyService) {}

    private route: ActivatedRouteSnapshot;
    private state: RouterStateSnapshot;

    //This method gets triggered when the route is hit
    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {

        this.route = route;
        this.state = state;

        if (!route.data) {
            Promise.resolve(true);
            return;
        }

        //this.route.data.guards is an array of strings set in routing configuration

        if (!this.route.data.guards || !this.route.data.guards.length) {
            Promise.resolve(true);
            return;
        }
        return this.executeGuards();
    }

    //Execute the guards sent in the route data
    private executeGuards(guardIndex: number = 0): Promise<boolean> {
        return this.activateGuard(this.route.data.guards[guardIndex])
            .then(() => {
                if (guardIndex < this.route.data.guards.length - 1) {
                    return this.executeGuards(guardIndex + 1);
                } else {
                    return Promise.resolve(true);
                }
            })
            .catch(() => {
                return Promise.reject(false);
            });
    }

    //Create an instance of the guard and fire canActivate method returning a promise
    private activateGuard(guardKey: string): Promise<boolean> {

        let guard: Guard1 | Guard2 | Guard3 | Guard4;

        switch (guardKey) {
            case GUARDS.GUARD1:
                guard = new Guard1();
                break;
            case GUARDS.GUARD2:
                guard = new Guard2();
                break;
            case GUARDS.GUARD3:
                guard = new Guard3();
                break;
            case GUARDS.GUARD4:
                guard = new Guard4(this._Guard4DependencyService);
                break;
            default:
                break;
        }
        return guard.canActivate(this.route, this.state);
    }
}
</code>```

Challenges

One of the challenges  in this  approach is refactoring of existing routing model. However, it can be done in parts as the changes are non-breaking.

I hope this helps.

Body:
I know angular route guards execute in the specified order when the canActivate function returns a simple boolean, however, what if the guards return type Observable<boolean> or Promise<boolean>?

Example in route:

{
    path: 'confirm',
    canActivate: [AuthGuard, SessionExpiredAuthGuard, CheckoutAuthGuard],
    component: CheckoutReviewOrderComponent
},

SessionExpiredAuthGuard and CheckoutAuthGuard both return type Observable<boolean>. I don't want the CheckoutAuthGuard to be executed before the SessionExpiredAuthGuard is finished retrieving it's data from the asynchronous http request.

Is there any way to force these asynchronous guards to execute in order?

Body:
Problem

First of all, angular doesn't support the feature to call the guards in tandem. So if first guard is asynchronous and is trying to make ajax calls, all the remaining guards will get fired even before completion of the ajax request in guard 1.

I faced the similar problem and this is how I solved it -

Solution

The idea is to create a master guard and let the master guard handle the execution of other guards.

The routing configuration in this case, will contain master guard as the only guard.

To let master guard know about the guards to be triggered for specific routes, add a data property in Route.

The data property is a key value pair that allows us to attach data with the routes.

The data can then be accessed in the guards using ActivatedRouteSnapshot parameter of canActivate method in the guard.

The solution looks complicated but it will assure proper working of guards once it is integrated in the application.

Following example explains this approach -

Example

1. Constants Object to map all application guards -

export const GUARDS = {
    GUARD1: "GUARD1",
    GUARD2: "GUARD2",
    GUARD3: "GUARD3",
    GUARD4: "GUARD4",
}

2. Application Guard -

import { Injectable } from "@angular/core";
import { Guard4DependencyService } from "./guard4dependency";

@Injectable()
export class Guard4 implements CanActivate {
    //A  guard with dependency
    constructor(private _Guard4DependencyService:  Guard4DependencyService) {}

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        return new Promise((resolve: Function, reject: Function) => {
            //logic of guard 4 here
            if (this._Guard4DependencyService.valid()) {
                resolve(true);
            } else {
                reject(false);
            }
        });
    }
}

3. Routing Configuration -

import { Route } from "@angular/router";
import { View1Component } from "./view1";
import { View2Component } from "./view2";
import { MasterGuard, GUARDS } from "./master-guard";
export const routes: Route[] = [
    {
        path: "view1",
        component: View1Component,
        //attach master guard here
        canActivate: [MasterGuard],
        //this is the data object which will be used by
        //masteer guard to execute guard1 and guard 2
        data: {
            guards: [
                GUARDS.GUARD1,
                GUARDS.GUARD2
            ]
        }
    },
    {
        path: "view2",
        component: View2Component,
        //attach master guard here
        canActivate: [MasterGuard],
        //this is the data object which will be used by
        //masteer guard to execute guard1, guard 2, guard 3 & guard 4
        data: {
            guards: [
                GUARDS.GUARD1,
                GUARDS.GUARD2,
                GUARDS.GUARD3,
                GUARDS.GUARD4
            ]
        }
    }
];

4. Master Guard -

import { Injectable } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";

//import all the guards in the application
import { Guard1 } from "./guard1";
import { Guard2 } from "./guard2";
import { Guard3 } from "./guard3";
import { Guard4 } from "./guard4";

import { Guard4DependencyService } from "./guard4dependency";

@Injectable()
export class MasterGuard implements CanActivate {

    //you may need to include dependencies of individual guards if specified in guard constructor
    constructor(private _Guard4DependencyService:  Guard4DependencyService) {}

    private route: ActivatedRouteSnapshot;
    private state: RouterStateSnapshot;

    //This method gets triggered when the route is hit
    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {

        this.route = route;
        this.state = state;

        if (!route.data) {
            Promise.resolve(true);
            return;
        }

        //this.route.data.guards is an array of strings set in routing configuration

        if (!this.route.data.guards || !this.route.data.guards.length) {
            Promise.resolve(true);
            return;
        }
        return this.executeGuards();
    }

    //Execute the guards sent in the route data
    private executeGuards(guardIndex: number = 0): Promise<boolean> {
        return this.activateGuard(this.route.data.guards[guardIndex])
            .then(() => {
                if (guardIndex < this.route.data.guards.length - 1) {
                    return this.executeGuards(guardIndex + 1);
                } else {
                    return Promise.resolve(true);
                }
            })
            .catch(() => {
                return Promise.reject(false);
            });
    }

    //Create an instance of the guard and fire canActivate method returning a promise
    private activateGuard(guardKey: string): Promise<boolean> {

        let guard: Guard1 | Guard2 | Guard3 | Guard4;

        switch (guardKey) {
            case GUARDS.GUARD1:
                guard = new Guard1();
                break;
            case GUARDS.GUARD2:
                guard = new Guard2();
                break;
            case GUARDS.GUARD3:
                guard = new Guard3();
                break;
            case GUARDS.GUARD4:
                guard = new Guard4(this._Guard4DependencyService);
                break;
            default:
                break;
        }
        return guard.canActivate(this.route, this.state);
    }
}

Challenges

One of the challenges  in this  approach is refactoring of existing routing model. However, it can be done in parts as the changes are non-breaking.

I hope this helps.