问:
Popper not loading before bootstrap in visual studio 2017 ASP.NET MVC
I'm trying to implement popouts but it seems like poppers.js doesn't want to load before bootstrap.js. I've tried to place the bundle before the bootstrap one but it doesn't want to load.
BundleConfig:

```<code>public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate*"));

    // Use the development version of Modernizr to develop with and learn from. Then, when you're
    // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
    bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                "~/Scripts/modernizr-*"));

    bundles.Add(new ScriptBundle("~/bundles/popper").Include(
              "~/Scripts/popper.js"
              ));

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
              "~/Scripts/bootstrap.js"
              ));

    bundles.Add(new StyleBundle("~/Content/css").Include(
              "~/Content/bootstrap.css",
              "~/Content/xbbcode.css",
              "~/Content/site.css"));

}
</code>```

_Layout:

```<code>@Scripts.Render("~/bundles/popper")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</code>```

I still get this error:

jQuery.Deferred exception: Bootstrap's tooltips require Popper.js (https://popper.js.org/) Tooltip@http://localhost:56609/Scripts/bootstrap.js:2836:15
  Popover@http://localhost:56609/Scripts/bootstrap.js:3509:14
  _jQueryInterface/<@http://localhost:56609/Scripts/bootstrap.js:3569:18
  each@http://localhost:56609/Scripts/jquery-3.3.1.js:354:10
  each@http://localhost:56609/Scripts/jquery-3.3.1.js:189:10
  _jQueryInterface@http://localhost:56609/Scripts/bootstrap.js:3559:14
  load/http://localhost:56609/:299:46
  mightThrow@http://localhost:56609/Scripts/jquery-3.3.1.js:3534:21
  resolve/http://localhost:56609/Scripts/jquery-3.3.1.js:3602:12
   undefined jquery-3.3.1.js:3818:3
  TypeError: Bootstrap's tooltips require Popper.js (https://popper.js.org/)

答:
This was doing my head in for about 30 mins but i managed to solve it. All i did was add the UMD version of popper.js and bundled it with the bootstrap.js.

What is UMD

The UMD pattern typically attempts to offer compatibility with
the most popular script loaders of the day (e.g RequireJS amongst
others). In many cases it uses AMD as a base, with special-casing
added to handle CommonJS compatibility.

So your BundleConfig.cs will look like this...

```<code>            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
            "~/Scripts/umd/popper.js",
            "~/Scripts/bootstrap.js"));
</code>```

I also tried bundling it on its own and it worked.

```<code>        bundles.Add(new ScriptBundle("~/bundles/popper").Include(
                    "~/Scripts/umd/popper.js"));
</code>```

Just remember to add it to your _Layout.cshtml. Also, i think order matters so try this order instead.

```<code>    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/popper")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</code>```

So jQuery first, popper and then bootstrap. Hope this helps

Body:
I'm trying to implement popouts but it seems like poppers.js doesn't want to load before bootstrap.js. I've tried to place the bundle before the bootstrap one but it doesn't want to load.
BundleConfig:

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate*"));

    // Use the development version of Modernizr to develop with and learn from. Then, when you're
    // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
    bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                "~/Scripts/modernizr-*"));

    bundles.Add(new ScriptBundle("~/bundles/popper").Include(
              "~/Scripts/popper.js"
              ));

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
              "~/Scripts/bootstrap.js"
              ));

    bundles.Add(new StyleBundle("~/Content/css").Include(
              "~/Content/bootstrap.css",
              "~/Content/xbbcode.css",
              "~/Content/site.css"));

}

_Layout:

@Scripts.Render("~/bundles/popper")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

I still get this error:

jQuery.Deferred exception: Bootstrap's tooltips require Popper.js (https://popper.js.org/) Tooltip@http://localhost:56609/Scripts/bootstrap.js:2836:15
  Popover@http://localhost:56609/Scripts/bootstrap.js:3509:14
  _jQueryInterface/<@http://localhost:56609/Scripts/bootstrap.js:3569:18
  each@http://localhost:56609/Scripts/jquery-3.3.1.js:354:10
  each@http://localhost:56609/Scripts/jquery-3.3.1.js:189:10
  _jQueryInterface@http://localhost:56609/Scripts/bootstrap.js:3559:14
  load/http://localhost:56609/:299:46
  mightThrow@http://localhost:56609/Scripts/jquery-3.3.1.js:3534:21
  resolve/http://localhost:56609/Scripts/jquery-3.3.1.js:3602:12
   undefined jquery-3.3.1.js:3818:3
  TypeError: Bootstrap's tooltips require Popper.js (https://popper.js.org/)

Body:
This was doing my head in for about 30 mins but i managed to solve it. All i did was add the UMD version of popper.js and bundled it with the bootstrap.js.

What is UMD

The UMD pattern typically attempts to offer compatibility with
the most popular script loaders of the day (e.g RequireJS amongst
others). In many cases it uses AMD as a base, with special-casing
added to handle CommonJS compatibility.

So your BundleConfig.cs will look like this...

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
            "~/Scripts/umd/popper.js",
            "~/Scripts/bootstrap.js"));

I also tried bundling it on its own and it worked.

        bundles.Add(new ScriptBundle("~/bundles/popper").Include(
                    "~/Scripts/umd/popper.js"));

Just remember to add it to your _Layout.cshtml. Also, i think order matters so try this order instead.

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/popper")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

So jQuery first, popper and then bootstrap. Hope this helps


来源: stackexchange

问:
Accessing dict_keys element by index in Python3
I'm trying to access a dict_key's element by its index:

```<code>test = {'foo': 'bar', 'hello': 'world'}
keys = test.keys()  # dict_keys object

keys.index(0)
AttributeError: 'dict_keys' object has no attribute 'index'
</code>```

I want to get foo.

same with:

```<code>keys[0]
TypeError: 'dict_keys' object does not support indexing
</code>```

How can I do this?

答:
In many cases, this may be an XY Problem.  Why are you indexing your dictionary keys by position?  Do you really need to?  Until recently, dictionaries were not even ordered in Python, so accessing the first element was arbitrary.

I just translated some Python 2 code to Python 3:

```<code>keys = d.keys()
for (i, res) in enumerate(some_list):
    k = keys[i]
    # ...
</code>```

which is not pretty, but not very bad either.  At first, I was about to replace it by the monstrous

```<code>    k = next(itertools.islice(iter(keys), i, None))
</code>```

before I realised this is all much better written as

```<code>for (k, res) in zip(d.keys(), some_list):
</code>```

which works just fine.

I believe that in many other cases, indexing dictionary keys by position can be avoided.  Although dictionaries are ordered in Python 3.7, relying on that is not pretty.  The code above only works because the contents of some_list had been recently produced from the contents of d.

Have a hard look at your code if you really need to access a disk_keys element by index.  Perhaps you don't need to.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to access a dict_key's element by its index:

test = {'foo': 'bar', 'hello': 'world'}
keys = test.keys()  # dict_keys object

keys.index(0)
AttributeError: 'dict_keys' object has no attribute 'index'

I want to get foo.

same with:

keys[0]
TypeError: 'dict_keys' object does not support indexing

How can I do this?

Body:
In many cases, this may be an XY Problem.  Why are you indexing your dictionary keys by position?  Do you really need to?  Until recently, dictionaries were not even ordered in Python, so accessing the first element was arbitrary.

I just translated some Python 2 code to Python 3:

keys = d.keys()
for (i, res) in enumerate(some_list):
    k = keys[i]
    # ...

which is not pretty, but not very bad either.  At first, I was about to replace it by the monstrous

    k = next(itertools.islice(iter(keys), i, None))

before I realised this is all much better written as

for (k, res) in zip(d.keys(), some_list):

which works just fine.

I believe that in many other cases, indexing dictionary keys by position can be avoided.  Although dictionaries are ordered in Python 3.7, relying on that is not pretty.  The code above only works because the contents of some_list had been recently produced from the contents of d.

Have a hard look at your code if you really need to access a disk_keys element by index.  Perhaps you don't need to.

ContentLicense: CC BY-SA 4.0


问:
C++ Heap Corruption
I haven't done any C++ in a while, but decided to finish a big project I was working on for someone. I am getting the following error message now though...

HEAP CORRUPTION DETECTED: after Normal Block (#1761) at 0x17DEB940.
CRT Detected that the application wrote to memory after end of heap buffer.

I have been stepping through all of the functions I thought might have caused it but I am at a loss. Is there any way using the more advanced debugging features to hunt this down?

答: On Linux I would recommend valgrind as a tool that would tell you exactly what went wrong. You may look into some Windows alternatives for it here.</p>

Title: C++ Heap Corruption


问:
How do I avoid getting "Missing return statement" when calling a method that throws an exception, from within another method?
I have a method that handles different error codes and always throws unchecked exception. This method is used in many places across the class. When I try to call it inside another method that has not void return type as shown below:

```<code>public Object someMethod() {
   ....
   if(success){
     return result;
   } else {
      callMethodThatAlwaysThrowsUncheckedExceptions();
   }
}
</code>```

java compiler says that the method is missing return statement.

Only two options come to my mind how to solve this problem:

replace method call with its content

add a return statement just after method call that returns an empty object

However I don't really like any of these options: the first one because of code duplication and the second one because of the need to write code that will never be executed.

Is there any other way to solve this problem?

答:
Next to the great answer already provided by Slawomir Chodnicki, here's another suggestion.

Change your callMethodThatAlwaysThrowsUncheckedExceptions() which somewhere throws an Exception into a factory method. E.g: change this:

```<code>// somewhere in callMethodThatAlwaysThrowsUncheckedExceptions
throw new MyException();
</code>```

To:

```<code>return new MyException();
</code>```

That way you can call that method like this:

```<code>throw callMethodThatAlwaysThrowsUncheckedExceptions();
</code>```

And thus will help the compiler to see that this is the last statement of that execution branch.

This also works greatly with different exceptions, just return instead of throw

Body:
I have a method that handles different error codes and always throws unchecked exception. This method is used in many places across the class. When I try to call it inside another method that has not void return type as shown below:

public Object someMethod() {
   ....
   if(success){
     return result;
   } else {
      callMethodThatAlwaysThrowsUncheckedExceptions();
   }
}

java compiler says that the method is missing return statement.

Only two options come to my mind how to solve this problem:

replace method call with its content

add a return statement just after method call that returns an empty object

However I don't really like any of these options: the first one because of code duplication and the second one because of the need to write code that will never be executed.

Is there any other way to solve this problem?

Body:
Next to the great answer already provided by Slawomir Chodnicki, here's another suggestion.

Change your callMethodThatAlwaysThrowsUncheckedExceptions() which somewhere throws an Exception into a factory method. E.g: change this:

// somewhere in callMethodThatAlwaysThrowsUncheckedExceptions
throw new MyException();

To:

return new MyException();

That way you can call that method like this:

throw callMethodThatAlwaysThrowsUncheckedExceptions();

And thus will help the compiler to see that this is the last statement of that execution branch.

This also works greatly with different exceptions, just return instead of throw


问:
Setting DownloadRequest's URL
I'm developing a resume function for file downloads. It looks good for the most of it (getting the resume data of the cancelled request, etc.), but when I'm creating the request for resuming the download, its URL is nil.

The code for creating the request is pretty straightforward:

```<code>let downloadRequest = sessionManager.download(resumingWith: resumableData)
</code>```

The downloadRequest object has a URLRequest variable but it is get-only.

I've read the doc but found no answer there.

Please note that the first request (the one that was cancelled) was created using this code:

```<code>let dataRequest = sessionManager.request(urlRequest)
</code>```

How is the DownloadRequest object getting its url? Am I missing something obvious?

答:
The answer lies in the first request made. When first starting to download the file, even if you don't plan to resume it later, you need to create an Alamofire.DownloadRequest (URLSessionDownloadTask) and not an Alamofire.DataRequest (URLSessionDataTask). The rest is the same: you capture the resume data when it fails (or if you cancel it by producing resume data), then you create the next request with that data.

Hope this helps!

Title: Setting DownloadRequest's URL

Body:
I'm developing a resume function for file downloads. It looks good for the most of it (getting the resume data of the cancelled request, etc.), but when I'm creating the request for resuming the download, its URL is nil.

The code for creating the request is pretty straightforward:

let downloadRequest = sessionManager.download(resumingWith: resumableData)

The downloadRequest object has a URLRequest variable but it is get-only.

I've read the doc but found no answer there.

Please note that the first request (the one that was cancelled) was created using this code:

let dataRequest = sessionManager.request(urlRequest)

How is the DownloadRequest object getting its url? Am I missing something obvious?


问:
How to reset PhpStorm's theme to the default?
I recently installed the following theme (Material Theme UI): https://plugins.jetbrains.com/plugin/8006-material-theme-ui but now it has totally screwed my install and I can't understand the menus.

The editing section is fine but everything else is messed up.

How do I reset PhpStorm to the default?

答:
Another option would be a hard reset on the PhpStorm installation:

uninstall phpStorm

delete the settings, caches, plugins and logs files
(more details about these files (for Win, Linux and Mac) can be found here)

This worked for me.

Be sure to make a list of all plugins you have installed or project(s) preferences you have configured in the global scope, because after the hard reset your IDE will be clean as a whistle (you will lose all your customisations).


问:
How do I add textboxes dynamically in Javascript?
By default I have 5 textboxes. When a user clicks on a button, one textbox should be added. </p>

<p>How could I do this? </p>

答:
by change for loop values we can generate textboxes dynamically

function addFunction() {
  var table = document.getElementById("textbox");
  var rowlen = table.rows.length;
  var row = table.insertRow(rowlen);
  row.id = rowlen;
  var arr = ['textboxfiledname'];
  for (i = 0; i < 2; i++) {
    var x = row.insertCell(i)
    if (i == 1) {
      x.innerHTML = "<input type='button' onclick='removeCell(" + row.id + ")' value=Delete>"
    } else {
      x.innerHTML = "" + arr[i] + ":<input type='textbox' name='" + arr[i] + "'>"
    }
  }
}

function removeCell(rowid) {
  var table = document.getElementById(rowid).remove();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input[type=text] {
  width: 100%;
  height: 50%;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: vertical;
}

label {
  padding: 12px 12px 12px 0;
  display: inline-block;
  font-family: sans-serif;
}

input[type=button] {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 6px 20px;
  text-decoration: none;
  margin: 4px 2px;
  cursor: pointer;
}</code>```

<fieldset style="margin-left:20%;margin-right:20%;font-family:sans-serif;padding:15px;border-radius:5px;background:#f2f2f2;border:5px solid #1F497D">
  <legend style="background:#1F497D;color:#fff;padding:5px 10px;font-size:22px;border-radius:5px;margin-left:20px;box-shadow:0 0 0 5px #ddd">DynamicTextbox</legend>

        <input type="button" onclick="addFunction()" value="AddTextbox" />

</fieldset>```

ContentLicense: CC BY-SA 2.5

Body:
By default I have 5 textboxes. When a user clicks on a button, one textbox should be added.

How could I do this?

Body:
by change for loop values we can generate textboxes dynamically

function addFunction() {
  var table = document.getElementById("textbox");
  var rowlen = table.rows.length;
  var row = table.insertRow(rowlen);
  row.id = rowlen;
  var arr = ['textboxfiledname'];
  for (i = 0; i < 2; i++) {
    var x = row.insertCell(i)
    if (i == 1) {
      x.innerHTML = "<input type='button' onclick='removeCell(" + row.id + ")' value=Delete>"
    } else {
      x.innerHTML = "<label>" + arr[i] + ":</label><input type='textbox' name='" + arr[i] + "'>"
    }
  }
}

function removeCell(rowid) {
  var table = document.getElementById(rowid).remove();
}

input[type=text] {
  width: 100%;
  height: 50%;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: vertical;
}

label {
  padding: 12px 12px 12px 0;
  display: inline-block;
  font-family: sans-serif;
}

input[type=button] {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 6px 20px;
  text-decoration: none;
  margin: 4px 2px;
  cursor: pointer;
}

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

<fieldset style="margin-left:20%;margin-right:20%;font-family:sans-serif;padding:15px;border-radius:5px;background:#f2f2f2;border:5px solid #1F497D">
  <legend style="background:#1F497D;color:#fff;padding:5px 10px;font-size:22px;border-radius:5px;margin-left:20px;box-shadow:0 0 0 5px #ddd">DynamicTextbox</legend>
  <table id="textbox">
    <tr>
      <td>
        <input type="button" onclick="addFunction()" value="AddTextbox" />
      </td>
    </tr>
  </table>
</fieldset>


问:
How can I give the suggestion for a textbox based on search from JSON datasource
I am having a datasource something like this.

```<code>0: {id: 12, productNumber: "FGC 101 89/1A380", rstate: "R1B", functionDesignation: "J-VPN 1.0 WIND",…}
acronym: "vpn"
code: null
functionDesignation: "J-VPN 1.0 WIND"
id: 12
prCode: null
productNumber: "FGC 101 89/1A380"
reCode: "DS4"
rstate: "R1B"
versionDesignationText: ""
1: {id: 13, productNumber: "FGC 101 89/1A380", rstate: "R1A", functionDesignation: "J-VPN 1.0 WIND",…}
acronym: "vpn"
code: null
functionDesignation: "J-VPN 1.0 WIND"
id: 13
prCode: null
productNumber: "FGC 101 89/1A380"
reCode: "DS4"
rstate: "R1A"
versionDesignationText: ""

</code>```

I also have a textbox like below.

              Product Name
                <input type="text" class="form-control" id="emsProductName" />

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

<p>Now when the user types in Acronym(vpn) or Function designation(J-VPN 1.0 WIND),then how can i show the suggestion of first four columns which is matching.</p>

<p>I have done it in the below way</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $("#emsProductName").autocomplete({
      source: function (request, response) {
       console.log(request.term);
          var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
          $.ajax({
           type : 'POST',
                    url : config.vnfURL + 'vnf/getPRIM',
              dataType: "json",
              contentType: "application/json; charset=utf-8",
               data: {
                q: request.term
                },
              success: function (data) {
               console.log(response);
                  response($.map(data, function(v,i){
                      var text = v.acronym;
                      if ( text && ( !request.term || matcher.test(text) ) ) {
                          return {
                                  label: v.acronym+"_"+v.productNumber+"_"+v.functionDesignation+"_"+v.rstate+ "_" +v.versionDesignationText,
                                  value: v.productNumber+"_"+v.functionDesignation+"_"+v.rstate+ "_" +v.versionDesignationText

                                 };

                      }
                  }));
              }
          });
      }
  });     </code>```

It works perfectly fine but the complete value is saved in emsProductName textbox.

How can i split the value and put only functionDesignation in emsProductName(textbox),rstate in Rstate(textbox) ,prodcutNumber in prodcutNumber textboxes respectively.

答:
Below is a sample code of autocomplete but you need to convert it according to your need.

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Custom data and display</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

<input id="project">
<input type="hidden" id="project-id">

```

Body:
I am having a datasource something like this.

0: {id: 12, productNumber: "FGC 101 89/1A380", rstate: "R1B", functionDesignation: "J-VPN 1.0 WIND",…}
acronym: "vpn"
code: null
functionDesignation: "J-VPN 1.0 WIND"
id: 12
prCode: null
productNumber: "FGC 101 89/1A380"
reCode: "DS4"
rstate: "R1B"
versionDesignationText: ""
1: {id: 13, productNumber: "FGC 101 89/1A380", rstate: "R1A", functionDesignation: "J-VPN 1.0 WIND",…}
acronym: "vpn"
code: null
functionDesignation: "J-VPN 1.0 WIND"
id: 13
prCode: null
productNumber: "FGC 101 89/1A380"
reCode: "DS4"
rstate: "R1A"
versionDesignationText: ""

I also have a textbox like below.

              Product Name
                <input type="text" class="form-control" id="emsProductName" />

Now when the user types in Acronym(vpn) or Function designation(J-VPN 1.0 WIND),then how can i show the suggestion of first four columns which is matching.

I have done it in the below way

 $("#emsProductName").autocomplete({
      source: function (request, response) {
       console.log(request.term);
          var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
          $.ajax({
           type : 'POST',
                    url : config.vnfURL + 'vnf/getPRIM',
              dataType: "json",
              contentType: "application/json; charset=utf-8",
               data: {
                q: request.term
                },
              success: function (data) {
               console.log(response);
                  response($.map(data, function(v,i){
                      var text = v.acronym;
                      if ( text && ( !request.term || matcher.test(text) ) ) {
                          return {
                                  label: v.acronym+"_"+v.productNumber+"_"+v.functionDesignation+"_"+v.rstate+ "_" +v.versionDesignationText,
                                  value: v.productNumber+"_"+v.functionDesignation+"_"+v.rstate+ "_" +v.versionDesignationText

                                 };

                      }
                  }));
              }
          });
      }
  });

It works perfectly fine but the complete value is saved in emsProductName textbox.

How can i split the value and put only functionDesignation in emsProductName(textbox),rstate in Rstate(textbox) ,prodcutNumber in prodcutNumber textboxes respectively.

Body:
Below is a sample code of autocomplete but you need to convert it according to your need.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Custom data and display</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  #project-label {
    display: block;
    font-weight: bold;
    margin-bottom: 1em;
  }
  #project-icon {
    float: left;
    height: 32px;
    width: 32px;
  }
  #project-description {
    margin: 0;
    padding: 0;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var projects = [
      {
        functiondesignation: "ericson software",
        accrname: "SDI",
        rstate: "R10A",
        productnumber: "FGC 101 2997"
      },
       {
       functiondesignation: "ericson software",
        accrname: "SDI",
        rstate: "R9A",
        productnumber: "FGC 101 2997"
      },
       {
       functiondesignation: "ericson software",
        accrname: "SDI",
        rstate: "R9A",
        productnumber: "FGC 101 2997"
      },
       {
        accrname: "SDN",
        functiondesignation: "ericson software",
        rstate: "R3A",
        productnumber: "FGC 101 3031/6"
      }
    ];

    $( "#project" ).autocomplete({
      minLength: 1,
      source: projects,
      focus: function( event, ui ) {
        $( "#project" ).val( ui.item.accrname );
        return false;
      },
      select: function( event, ui ) {
        $( "#project" ).val( ui.item.functiondesignation );
        $( "#project-description" ).html( ui.item.accrname +ui.item.rstate + ui.item.productnumber );
        return false;
      }
    })
    .autocomplete( "instance" )._renderItem = function( ul, item ) {
      return $( "<li>" )
        .append( "<div>" + item.accrname +  item.rstate + item.productnumber+ "</div>")
        .appendTo( ul );
    };
  } );
  </script>
</head>
<body>
<input id="project">
<input type="hidden" id="project-id">
<p id="project-description"></p>

</body>
</html>


问:
Regular expression to replace content between parentheses ()
I tried this code:

```<code>string.replaceAll("\\(.*?)","");
</code>```

But it returns null. What am I missing?

答:
Try:

```<code>string.replaceAll("\\(.*?\\)","");
</code>```

You didn't escape the second parenthesis and you didn't add an additional "\" to the first one.

Body:
I tried this code:

string.replaceAll("\\(.*?)","");

But it returns null. What am I missing?

Body:
Try:

string.replaceAll("\\(.*?\\)","");

You didn't escape the second parenthesis and you didn't add an additional "\" to the first one.


问:
String is immutable?
Just have a problem with this, how do we rewrite the above code so that only a single String object is created?

String is immutable, isnt studentDetails already one single String object

```<code>public void displayString(Student[] students)
{
   String studentDetails = "";
   for (Student stu : students)
   {
       studentDetails += stu.getFirstName();
       studentDetails += " ";
       studentDetails += stu.getLastName();
       studentDetails += " ";
       studentDetails += stu.getAge();
       studentDetails += "\n";
   }
   System.out.println("Student Details are: ");
   System.out.println(studentDetails);
}
</code>```

答:
Yes , The string object in java is immutable.
The any change in the string will create the new string object.
Whereas, the stringBuilder and StringBuffer are mutable</p>

Title: String is immutable?

Body:
Just have a problem with this, how do we rewrite the above code so that only a single String object is created?

String is immutable, isnt studentDetails already one single String object

public void displayString(Student[] students)
{
   String studentDetails = "";
   for (Student stu : students)
   {
       studentDetails += stu.getFirstName();
       studentDetails += " ";
       studentDetails += stu.getLastName();
       studentDetails += " ";
       studentDetails += stu.getAge();
       studentDetails += "\n";
   }
   System.out.println("Student Details are: ");
   System.out.println(studentDetails);
}


问:
Display all item which is created in 2013
I have a table Policy, and I want to display all policy which is created in 2013.

```<code>select DAT_IZD from AUTO.KPOL   WHERE DAT_IZD='2013'
</code>```

But the problem is that this format of date can not be represent like this.
Any idea how to figure out this ?

答:
Try This

```<code>SELECT DAT_IZD FROM AUTO.KPOL  WHERE EXTRACT(YEAR FROM DAT_IZD)= '2013' ;
</code>```

or

```<code>SELECT DAT_IZD FROM AUTO.KPOL  WHERE YEAR(DAT_IZD)= '2013' ;
</code>```

I hope this will help you

Body:
I have a table Policy, and I want to display all policy which is created in 2013.

select DAT_IZD from AUTO.KPOL   WHERE DAT_IZD='2013'

But the problem is that this format of date can not be represent like this.
Any idea how to figure out this ?

Body:
Try This

SELECT DAT_IZD FROM AUTO.KPOL  WHERE EXTRACT(YEAR FROM DAT_IZD)= '2013' ;

or

SELECT DAT_IZD FROM AUTO.KPOL  WHERE YEAR(DAT_IZD)= '2013' ;

I hope this will help you


问:
Microsoft Graph Subscriptions - Not receiving calendar events notifications
We are using a multitenant application.
We created a subscription to listen to calendar events for a particular user, but we are not receiving the notifications.

The user accepted the following scopes: Calendars.Read Calendars.ReadWrite Calendars.Read.Shared Calendars.ReadWrite.Shared offline_access User.Read.All

When we call to POST https://graph.microsoft.com/v1.0/subscriptions
BODY:

```<code>{
"resource": "/users/31c61efc-bc28-4552-9f0d-1a8735767c4e/calendars/AAMkAGRjZjY3OGRmLWU3MjAtNGExYy1hOTk0LTNkNjExOWVhZmYyNQBGAAAAAAD3yBF0B84VRJLe9CCZ4-ajBwDf5J1F10FqQ6VkC14neUWZAAAAAAEGAADf5J1F10FqQ6VkC14neUWZAABEL_2XAAA\u003d/events",
"changeType": "created,updated,deleted",
"clientState": "XXXXXX",
"notificationUrl": "https://XXXXX.ngrok.io/notification/event",
"expirationDateTime": "2019-05-31T14:42:08.651Z"
}
</code>```

Then the notificationUrl is called and we receive the validation token:
Validation: Testing client application reachability for subscription Request-Id: 9d020355-7589-4485-ba29-62d1ec899723

But when we login into the 31c61efc-bc28-4552-9f0d-1a8735767c4e account and update or create an event, no notification is beign sent.

If we call to GET https://graph.microsoft.com/v1.0/subscriptions the subscription is created:

```<code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#subscriptions",
    "value": [
        {
            "id": "b92d909e-b1b5-49b8-af54-74b7956d6565",
            "resource": "/users/31c61efc-bc28-4552-9f0d-1a8735767c4e/calendars/AAMkAGRjZjY3OGRmLWU3MjAtNGExYy1hOTk0LTNkNjExOWVhZmYyNQBGAAAAAAD3yBF0B84VRJLe9CCZ4-ajBwDf5J1F10FqQ6VkC14neUWZAAAAAAEGAADf5J1F10FqQ6VkC14neUWZAABEL_2XAAA=/events",
            "applicationId": "XXXX",
            "changeType": "created,updated,deleted",
            "clientState": null,
            "notificationUrl": "https://XXXX.ngrok.io/notification/event",
            "expirationDateTime": "2019-05-31T14:42:08.651Z",
            "creatorId": "31c61efc-bc28-4552-9f0d-1a8735767c4e"
        }
    ]
}
</code>```

Monitoring the ngrok calls, there is no failing call to the notification events endpoint.

Is there any console log we can verify to understand what the problem could be?

We tried to create subscriptions for different accounts with no success.
We also tried to subcribe to /me/events

答:
Just wondering if it could the cause, but the calendar id to whom you're subscribing to is ending with \u003d instead of =. Encoding stuff. Might not be it, but for me its working well with this.

Hope its just this!
JS

Body:
We are using a multitenant application.
We created a subscription to listen to calendar events for a particular user, but we are not receiving the notifications.

The user accepted the following scopes: Calendars.Read Calendars.ReadWrite Calendars.Read.Shared Calendars.ReadWrite.Shared offline_access User.Read.All

When we call to POST https://graph.microsoft.com/v1.0/subscriptions
BODY:

{
"resource": "/users/31c61efc-bc28-4552-9f0d-1a8735767c4e/calendars/AAMkAGRjZjY3OGRmLWU3MjAtNGExYy1hOTk0LTNkNjExOWVhZmYyNQBGAAAAAAD3yBF0B84VRJLe9CCZ4-ajBwDf5J1F10FqQ6VkC14neUWZAAAAAAEGAADf5J1F10FqQ6VkC14neUWZAABEL_2XAAA\u003d/events",
"changeType": "created,updated,deleted",
"clientState": "XXXXXX",
"notificationUrl": "https://XXXXX.ngrok.io/notification/event",
"expirationDateTime": "2019-05-31T14:42:08.651Z"
}

Then the notificationUrl is called and we receive the validation token:
Validation: Testing client application reachability for subscription Request-Id: 9d020355-7589-4485-ba29-62d1ec899723

But when we login into the 31c61efc-bc28-4552-9f0d-1a8735767c4e account and update or create an event, no notification is beign sent.

If we call to GET https://graph.microsoft.com/v1.0/subscriptions the subscription is created:

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#subscriptions",
    "value": [
        {
            "id": "b92d909e-b1b5-49b8-af54-74b7956d6565",
            "resource": "/users/31c61efc-bc28-4552-9f0d-1a8735767c4e/calendars/AAMkAGRjZjY3OGRmLWU3MjAtNGExYy1hOTk0LTNkNjExOWVhZmYyNQBGAAAAAAD3yBF0B84VRJLe9CCZ4-ajBwDf5J1F10FqQ6VkC14neUWZAAAAAAEGAADf5J1F10FqQ6VkC14neUWZAABEL_2XAAA=/events",
            "applicationId": "XXXX",
            "changeType": "created,updated,deleted",
            "clientState": null,
            "notificationUrl": "https://XXXX.ngrok.io/notification/event",
            "expirationDateTime": "2019-05-31T14:42:08.651Z",
            "creatorId": "31c61efc-bc28-4552-9f0d-1a8735767c4e"
        }
    ]
}

Monitoring the ngrok calls, there is no failing call to the notification events endpoint.

Is there any console log we can verify to understand what the problem could be?

We tried to create subscriptions for different accounts with no success.
We also tried to subcribe to /me/events


问:
How to create multirow & multicolumn bitmap layout on Blackberry
I have 8 bitmap and i want to put 4 of them to the first row, rest to the second row...

Can you help me to use TableLayoutManager?

答:
See the BlackBerry developer knowledgebase article:

Create a rich UI layout with TableLayoutManager

It's a pretty simple class to work with, if you're familiar with RIM's thought process (lol)


问:
Material Ui code is working perfectly in codepen but not in VSCODE?
I am using Material-UI to create "Material Tabs" in my ReactJS project, this code is working properly in SANDBOX, but not in my VS CODE. What should I do?

I checked Node to be installed, checked and install all dependencies versions from NPM.
   I also checked it out. check it, but I couldn't understand it.

```<code>import React from "react";
import PropTypes from "prop-types";
import SwipeableViews from "react-swipeable-views";
import { makeStyles } from "@material-ui/core/styles";
import { withStyles } from "@material-ui/styles";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import Typography from "@material-ui/core/Typography";
function TabContainer({ children, dir }) {
  return (
    <Typography component="div" dir={dir} style={{ padding: 8 * 3 }}>
      {children}
    </Typography>
  );
}
const useStyles = makeStyles(theme => ({
  root: {
    backgroundColor: theme.palette.background.paper,
    width: 500
  }
}));

class Feature extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: 0 };
  }
  handleChange() {
    this.state.value === 0
      ? this.setState({ value: 1 })
      : this.setState({ value: 0 });
  }
  render() {
    const classes = this.props;
    const theme = this.props;
    return (
      <div className={classes.root}>
        <Tabs
          value={this.state.value}
          onChange={this.handleChange.bind(this)}
          indicatorColor="primary"
          textColor="primary"
        >
          <Tab label="A" />
          <Tab label="B" />
        </Tabs>
        <SwipeableViews
          axis={theme.direction === "rtl" ? "x-reverse" : "x"}
          index={this.state.value}
        >
          <TabContainer dir={theme.direction}>Item One</TabContainer>
          <TabContainer dir={theme.direction}>Item Two</TabContainer>
        </SwipeableViews>
      </div>
    );
  }
}
Feature.propTypes = {
  classes: PropTypes.object.isRequired
};
export default withStyles(useStyles)(Feature);
</code>```

And my package.json looks like

```<code>  "dependencies": {
    "@material-ui/core": "^3.9.2",
    "@material-ui/docs": "^3.0.0-alpha.9",
    "@material-ui/styles": "^4.0.1",
    "prop-types": "^15.7.2",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-redux": "^6.0.1",
    "react-router-dom": "^5.0.0",
    "react-scripts": "2.1.8",
    "react-slick": "^0.23.2",
    "react-swipeable-views": "^0.13.3",
    "redux": "^4.0.1",
    "styled-components": "^4.2.0"
  }
</code>```

I expect the output as given by SANDBOX, but got this error instead

```<code>TypeError: Object(...) is not a function
const useStyles = makeStyles(theme => ({
  root: {
    backgroundColor: theme.palette.background.paper,
    width: 500
  }
}));
</code>```

in above code.

答:
In your sandbox you are using @material-ui/core latest version (which currently is 4.0.1) and in your VS Code package.json it's version 3.9.2. I'm pretty sure that's the issue, try both with the exact same version instead of using latest.

See here : https://codesandbox.io/embed/material-demo-1j37n

Body:
I am using Material-UI to create "Material Tabs" in my ReactJS project, this code is working properly in SANDBOX, but not in my VS CODE. What should I do?

I checked Node to be installed, checked and install all dependencies versions from NPM.
   I also checked it out. check it, but I couldn't understand it.

import React from "react";
import PropTypes from "prop-types";
import SwipeableViews from "react-swipeable-views";
import { makeStyles } from "@material-ui/core/styles";
import { withStyles } from "@material-ui/styles";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import Typography from "@material-ui/core/Typography";
function TabContainer({ children, dir }) {
  return (
    <Typography component="div" dir={dir} style={{ padding: 8 * 3 }}>
      {children}
    </Typography>
  );
}
const useStyles = makeStyles(theme => ({
  root: {
    backgroundColor: theme.palette.background.paper,
    width: 500
  }
}));

class Feature extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: 0 };
  }
  handleChange() {
    this.state.value === 0
      ? this.setState({ value: 1 })
      : this.setState({ value: 0 });
  }
  render() {
    const classes = this.props;
    const theme = this.props;
    return (

        <Tabs
          value={this.state.value}
          onChange={this.handleChange.bind(this)}
          indicatorColor="primary"
          textColor="primary"
        >
          <Tab label="A" />
          <Tab label="B" />
        </Tabs>
        <SwipeableViews
          axis={theme.direction === "rtl" ? "x-reverse" : "x"}
          index={this.state.value}
        >
          <TabContainer dir={theme.direction}>Item One</TabContainer>
          <TabContainer dir={theme.direction}>Item Two</TabContainer>
        </SwipeableViews>

    );
  }
}
Feature.propTypes = {
  classes: PropTypes.object.isRequired
};
export default withStyles(useStyles)(Feature);

And my package.json looks like

  "dependencies": {
    "@material-ui/core": "^3.9.2",
    "@material-ui/docs": "^3.0.0-alpha.9",
    "@material-ui/styles": "^4.0.1",
    "prop-types": "^15.7.2",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-redux": "^6.0.1",
    "react-router-dom": "^5.0.0",
    "react-scripts": "2.1.8",
    "react-slick": "^0.23.2",
    "react-swipeable-views": "^0.13.3",
    "redux": "^4.0.1",
    "styled-components": "^4.2.0"
  }

I expect the output as given by SANDBOX, but got this error instead

TypeError: Object(...) is not a function
const useStyles = makeStyles(theme => ({
  root: {
    backgroundColor: theme.palette.background.paper,
    width: 500
  }
}));

in above code.


问:
Boost Python "cannot open source file 'pyconfig.h'" when importing using "#include <boost\python.hpp>"
I am attempting to use Boost Python for a project. I have downloaded and build version 1.70 on Windows 10, and I am using Visual Studio Code. When attempting to import boost into my c++ project with the line:

```<code>#include <boost\python.hpp>
</code>```

, I receive the following error:

```<code>cannot open source file "pyconfig.h" (dependency of "boost\python.hpp")
</code>```

I have looked into similar issues, and the primary solution I have found was to edit user-config.jam to include the location of my python installation. I have done so, and the line within user-config.jam looks like this:

```<code>using python : 3.7 : C:\Users\broke\AppData\Local\Programs\Python\Python37 ;
</code>```

After adding this line, I rebuilt Boost Python. This did nothing to remedy the issue. I would greatly appreciate help on this matter. Thank you.

答: you need to make sure the python/include folder is added to your includes. C:\Python\Python37\include for me on windows. You will also need to link the python library.

Body:
I am attempting to use Boost Python for a project. I have downloaded and build version 1.70 on Windows 10, and I am using Visual Studio Code. When attempting to import boost into my c++ project with the line:

#include <boost\python.hpp>

, I receive the following error:

cannot open source file "pyconfig.h" (dependency of "boost\python.hpp")

I have looked into similar issues, and the primary solution I have found was to edit user-config.jam to include the location of my python installation. I have done so, and the line within user-config.jam looks like this:

using python : 3.7 : C:\Users\broke\AppData\Local\Programs\Python\Python37 ;

After adding this line, I rebuilt Boost Python. This did nothing to remedy the issue. I would greatly appreciate help on this matter. Thank you.


问:
Java8 streams with Map?
I have the following Map (each key is a String and each value is a List<Message>)

My map is like this :

```<code>1st entry :"MONDAY" -> [message1, message2, message3]
2nd entry : "TUESDAY" -> [message4, message5]
...
</code>```

My goal is to change each message content :

I was thinking about this :

```<code>map.entrySet().stream().peek(entry -> {
    entry.getValue().stream().peek(m -> m.setMessage(changeMessage()))
})
</code>```

But don't know how to finish and do it properly.

答:
Unfortunately, java-stream doesn't provide a straightforward way to change the Map values without violating the Side-effects principle:

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.

Here is a possible solution:

```<code>Map<String, List<Message>> = map.entrySet().stream()
    .map(e -> {                                                      // iterate entries
            e.setValue(e.getValue().stream()                         // set a new value
                .map(message -> {
                    message  -> message.setMessage(changeMessage()); // .. update message
                    return message;})                                // .. use it
                .collect(Collectors.toList()));                      // return as a List
            return e;})                                              // return an updated value
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));      // collec to a Map
</code>```

However, Java provides a well-known for-each feature to achieve your goal in a more direct way which is more readable:

```<code>for (List<Message> list: map.values()) {
    for (Message message: list) {
        message.setMessage(changeMessage());
    }
}
</code>```

Title: Java8 streams with Map?

Body:
I have the following Map (each key is a String and each value is a List<Message>)

My map is like this :

1st entry :"MONDAY" -> [message1, message2, message3]
2nd entry : "TUESDAY" -> [message4, message5]
...

My goal is to change each message content :

I was thinking about this :

map.entrySet().stream().peek(entry -> {
    entry.getValue().stream().peek(m -> m.setMessage(changeMessage()))
})

But don't know how to finish and do it properly.

Body:
Unfortunately, java-stream doesn't provide a straightforward way to change the Map values without violating the Side-effects principle:

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.

Here is a possible solution:

Map<String, List<Message>> = map.entrySet().stream()
    .map(e -> {                                                      // iterate entries
            e.setValue(e.getValue().stream()                         // set a new value
                .map(message -> {
                    message  -> message.setMessage(changeMessage()); // .. update message
                    return message;})                                // .. use it
                .collect(Collectors.toList()));                      // return as a List
            return e;})                                              // return an updated value
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));      // collec to a Map

However, Java provides a well-known for-each feature to achieve your goal in a more direct way which is more readable:

for (List<Message> list: map.values()) {
    for (Message message: list) {
        message.setMessage(changeMessage());
    }
}


问:
UIButton state selected
I've seen a lot of info on changing the button image for selected but being a new I'm having a bit of trouble implementing a simpler version of it.

When the button is pressed it goes dark and I would like it to stay that way once it's been selected. So there are a few questions.

Do I create IBOutlet for the button and then and IBAction to change the state with something like button.state = SELECTED.

Sorry for the complete lack of any code to look at.

Edit: (id)sender is the button object right?

```<code>-(IBAction)journalEntryViewControllerClick: (id)sender
{
    UIButton *button = (id)sender;

    [button setSelected:YES];

}
</code>```

答:
Yes that could be one way of doing it. If you want a "stateswitch" kind of look.

However you set the button.selected = YES;

Title: UIButton state selected

Body:
I've seen a lot of info on changing the button image for selected but being a new I'm having a bit of trouble implementing a simpler version of it.

When the button is pressed it goes dark and I would like it to stay that way once it's been selected. So there are a few questions.

Do I create IBOutlet for the button and then and IBAction to change the state with something like button.state = SELECTED.

Sorry for the complete lack of any code to look at.

Edit: (id)sender is the button object right?

-(IBAction)journalEntryViewControllerClick: (id)sender
{
    UIButton *button = (id)sender;

    [button setSelected:YES];

}


问:
postgreSQL: primary key doesn't start on 1
I made a primary key called t_id in the table of DB by using the query  t_id SERIAL PRIMARY KEY.
At the very first time, it started well on 1. Then I deleted all the data and from then, it starts on 2 even though I set it on 1.

Here's the screenshot of what I did on seq - definition on pgAdmin4 :

Anyone has an idea where is the problem ?

Thanks a lot!!

答:
The current value is 1, so the next value that will be served is 2. This is expected.

The doc is helpful on this topic.

Remember that the sequence will always give you a value that was not used before. So if you insert 10 rows, then delete them, the next sequence value will still be 11 (the last served value + 1)

To reset the sequence so the next time it is called it returns 1, you would do

```<code>SELECT setval('my_sequence_name', 1, false);
</code>```

Body:
The current value is 1, so the next value that will be served is 2. This is expected.

The doc is helpful on this topic.

Remember that the sequence will always give you a value that was not used before. So if you insert 10 rows, then delete them, the next sequence value will still be 11 (the last served value + 1)

To reset the sequence so the next time it is called it returns 1, you would do

SELECT setval('my_sequence_name', 1, false);


问:
Add external JAR's to a Gluon project using Eclipse IDE?
I'm trying to include EasyModbusJava.jar and commons-lang3-3.8.1.jar in a JavaFX Gluon project using Eclipse. But when I compile, I get this:

```<code>/home/dell/Dokument/eclipse-workspace-2018-09/OKIDERAMPC/OKIDERAMPCApp/src/main/java/com/gluonapplication/thread/ModbusConnection.java:6: error: package org.apache.commons.lang3 does not exist
import org.apache.commons.lang3.ArrayUtils;

/home/dell/Dokument/eclipse-workspace-2018-09/OKIDERAMPC/OKIDERAMPCApp/src/main/java/com/gluonapplication/thread/ModbusConnection.java:8: error: package de.re.easymodbus.modbusclient does not exist
import de.re.easymodbus.modbusclient.ModbusClient;
</code>```

How can I in a very easy and proper way, using Eclipse, to include JAR files into a Gluon project? I don't want to include the JAR files with a non-standard way, like editing an file and copy and paste. It can break my project. It's better to use the tools from the IDE instead.

picture

答:
The only way that I know is to include the respective jars in the build.gradle

```<code>dependencies {
    compile 'com.gluonhq:charm:5.0.1'
    compile files('<Path_to_jar>/EasyModbusJava.jar'
                    , '<Path_to_jar>/commons-lang3-3.8.1.jar'
    )
}
</code>```

The jars show in eclipse under "Project and External dependencies" and their properties (e.g. path to javadoc) can not be edited.
To achieve this you can add

```<code>apply plugin: 'eclipse'
</code>```

and

```<code>eclipse  {
    classpath {
       downloadJavadoc = true // to get the Gluon mobile (charm...) javadocs;
       file {
            whenMerged { cp ->
                // Add other javadoc and sources to classpath entry
                def fileReferenceFactory = new org.gradle.plugins.ide.eclipse.model.internal.FileReferenceFactory()

                def defvar1 = cp.entries.find{ defvar1 -> defvar1.path.endsWith('EasyModbusJava.jar') }
                // add javadoc path
                defvar1.javadocPath = fileReferenceFactory.fromPath('<Path_to_javadoc>')
                // add source path
                defvar1.sourcePath = fileReferenceFactory.fromPath('<Path_to_javasource>')
        }
    }
}
</code>```

to gradle.build

Body:
I'm trying to include EasyModbusJava.jar and commons-lang3-3.8.1.jar in a JavaFX Gluon project using Eclipse. But when I compile, I get this:

/home/dell/Dokument/eclipse-workspace-2018-09/OKIDERAMPC/OKIDERAMPCApp/src/main/java/com/gluonapplication/thread/ModbusConnection.java:6: error: package org.apache.commons.lang3 does not exist
import org.apache.commons.lang3.ArrayUtils;

/home/dell/Dokument/eclipse-workspace-2018-09/OKIDERAMPC/OKIDERAMPCApp/src/main/java/com/gluonapplication/thread/ModbusConnection.java:8: error: package de.re.easymodbus.modbusclient does not exist
import de.re.easymodbus.modbusclient.ModbusClient;

How can I in a very easy and proper way, using Eclipse, to include JAR files into a Gluon project? I don't want to include the JAR files with a non-standard way, like editing an file and copy and paste. It can break my project. It's better to use the tools from the IDE instead.

picture

Body:
The only way that I know is to include the respective jars in the build.gradle

dependencies {
    compile 'com.gluonhq:charm:5.0.1'
    compile files('<Path_to_jar>/EasyModbusJava.jar'
                    , '<Path_to_jar>/commons-lang3-3.8.1.jar'
    )
}

The jars show in eclipse under "Project and External dependencies" and their properties (e.g. path to javadoc) can not be edited.
To achieve this you can add

apply plugin: 'eclipse'

and

eclipse  {
    classpath {
       downloadJavadoc = true // to get the Gluon mobile (charm...) javadocs;
       file {
            whenMerged { cp ->
                // Add other javadoc and sources to classpath entry
                def fileReferenceFactory = new org.gradle.plugins.ide.eclipse.model.internal.FileReferenceFactory()

                def defvar1 = cp.entries.find{ defvar1 -> defvar1.path.endsWith('EasyModbusJava.jar') }
                // add javadoc path
                defvar1.javadocPath = fileReferenceFactory.fromPath('<Path_to_javadoc>')
                // add source path
                defvar1.sourcePath = fileReferenceFactory.fromPath('<Path_to_javasource>')
        }
    }
}

to gradle.build


答:
Just swap around the terms, you'll never get to return if the method throws.

```<code> if(!success){
   callMethodThatAlwaysThrowsUncheckedExceptions();
 }

 return result;
</code>```

Or even

```<code> callMethodThatAlwaysThrowsUncheckedExceptions(succes);
 return result;
</code>```

Just check the success condition in your throwing method.

Title: How do I avoid getting "Missing return statement" when calling a method that throws an exception, from within another method?

Body:
I have a method that handles different error codes and always throws unchecked exception. This method is used in many places across the class. When I try to call it inside another method that has not void return type as shown below:

public Object someMethod() {
   ....
   if(success){
     return result;
   } else {
      callMethodThatAlwaysThrowsUncheckedExceptions();
   }
}

java compiler says that the method is missing return statement.

Only two options come to my mind how to solve this problem:

replace method call with its content

add a return statement just after method call that returns an empty object

However I don't really like any of these options: the first one because of code duplication and the second one because of the need to write code that will never be executed.

Is there any other way to solve this problem?

Body:
Just swap around the terms, you'll never get to return if the method throws.

 if(!success){
   callMethodThatAlwaysThrowsUncheckedExceptions();
 }

 return result;

Or even

 callMethodThatAlwaysThrowsUncheckedExceptions(succes);
 return result;

Just check the success condition in your throwing method.


问:
How to handle the case when FirebaseAuth sign in fails due to network being offline?
I am trying to implement sign in authentication with FirebaseAuth using signInWithEmailAndPassword() for my Android app. How can I handle the case when Internet connection is offline so that I can generate a Toast message regarding network issue.

答:
You can use this code snippet:

```<code>public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
        Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
    Log.d(LOG_TAG, "No network available!");
    }
    return false;
}
</code>```

and also add this in your Manifest.xml:

```<code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
</code>```

Body:
You can use this code snippet:

public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
        Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
    Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

and also add this in your Manifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


问:
Not able to add data to a file Tcl using expect statement
I am trying to create a script and that run a program and when this program is run it says either DB already running or Port is already being used by another process(Means already running)

If it is already running I wish to create a if- else statement and wish to add 1 to a file if already running but if not running add 0 to file

This is my tcl file named test

```<code>    #!/usr/bin/expect -f
    set f [open a2.txt w]
    cd /opt/Uni-SON/
    spawn ./Aprogram start
    expect {
       "Port is already being used by another process"

        puts $f 1
        puts "sadsadasdsaa"
    }

    puts $f 0
</code>```

This is my test2 file which is bash file

```<code>#!/bin/bash
./test
value=$(<a2.txt)
rm -rf a2.txt
if [ $value -eq 0 ]
then
        echo Not being used
else
        echo Already Being used
fi
</code>```

ERROR :It is not adding data to the file but if I put the exact same statement puts $f 1outside the expect brackets it works

What is wrong ?

How do I do it?

答:
The problem with this statement:

```<code>expect {
   "Port is already being used by another process"

    puts $f 1
    puts "sadsadasdsaa"
}
</code>```

is that it's triggering the case where you have a set of things to wait for. You probably want to change it to:

```<code>expect {
    "Port is already being used by another process" {
        puts $f 1
        puts "sadsadasdsaa"
    }
}
</code>```

Which is to say when that message is found, do the little script (two puts calls) associated with it. You can wait for several things at once too, and that's where expect becomes very powerful!

Body:
I am trying to create a script and that run a program and when this program is run it says either DB already running or Port is already being used by another process(Means already running)

If it is already running I wish to create a if- else statement and wish to add 1 to a file if already running but if not running add 0 to file

This is my tcl file named test

    #!/usr/bin/expect -f
    set f [open a2.txt w]
    cd /opt/Uni-SON/
    spawn ./Aprogram start
    expect {
       "Port is already being used by another process"

        puts $f 1
        puts "sadsadasdsaa"
    }

    puts $f 0

This is my test2 file which is bash file

#!/bin/bash
./test
value=$(<a2.txt)
rm -rf a2.txt
if [ $value -eq 0 ]
then
        echo Not being used
else
        echo Already Being used
fi

ERROR :It is not adding data to the file but if I put the exact same statement puts $f 1outside the expect brackets it works

What is wrong ?

How do I do it?

Body:
The problem with this statement:

expect {
   "Port is already being used by another process"

    puts $f 1
    puts "sadsadasdsaa"
}

is that it's triggering the case where you have a set of things to wait for. You probably want to change it to:

expect {
    "Port is already being used by another process" {
        puts $f 1
        puts "sadsadasdsaa"
    }
}

Which is to say when that message is found, do the little script (two puts calls) associated with it. You can wait for several things at once too, and that's where expect becomes very powerful!


问:
How to namespace the _nghost/_ngcontent props in Angular?
I'm currently doing some experiments with sharing Angular apps as Web Components and I've faced an issue with the styles of one app affecting the other one.

Given the fact that I use the emulated view encapsulation, Angular will add special _nghost-c# and _ngcontent-c# props to my elements and also update the styles to use them. Now, since I may have multiple angular apps in a single page, those selectors can affect the other apps.

I've seen a few examples on the web where those props have a namespace in it, like _nghost-XXX-#, but I couldn't find a way to customize it.

答:
The fix for this issue was just released in Angular v8.

It was introduced in beta 12.

For previous versions of Angular, there's no way to solve, without introducing the changes by yourself.


问:
How do I parse Array within Array
I am trying to parse information that is inside an Array. The array comes from an RSS feed that I have converted into a json. The array is:

```<code><channel>
<item>
    <title> Title A </title>
    <description> Description A </description>
    <stuff url="google.com" type="search engine">
</item>

<item>
    <title> Title B </title>
    <description> Description B </description>
    <stuff url="yahoo.com" type="old stuff">
</item>
....

</channel>
</code>```

I am parsing using something like:

```<code>$newsoutput = json_decode(json_encode($the_RSS_Link), TRUE);

foreach ($newsoutput['channel']['item'] as $item) {
   echo $item['title'];
   echo "<br>";
   echo $item['description'];
   echo "<br>";
   echo $item['stuff']['url'];
   echo "<br>";
}
</code>```

I can get both "title" and "description"; but I cannot extract the "url" values inside "stuff". I have tried various combinations without luck

Please advise.

Thank you,

H.

答:
Assuming you have valid XML (which you should if it is a valid RSS fee) you can use the SimpleXML parser:

```<code>$xml = '<channel>
<item>
    <title> Title A </title>
    <description> Description A </description>
    <stuff url="google.com" type="search engine"/>
</item>

<item>
    <title> Title B </title>
    <description> Description B </description>
    <stuff url="yahoo.com" type="old stuff"/>
</item></channel>';
$x = new simplexmlelement($xml);
foreach($x->item as $item){
    echo $item->title . ' ' . $item->stuff['url'] . ' ' . $item->stuff['type'] . PHP_EOL;
}
</code>```

https://3v4l.org/6ICrG

Note the stuff element here has been modified so it is self-closing.

Title: How do I parse Array within Array

Body:
I am trying to parse information that is inside an Array. The array comes from an RSS feed that I have converted into a json. The array is:

<channel>
<item>
    <title> Title A </title>
    <description> Description A </description>
    <stuff url="google.com" type="search engine">
</item>

<item>
    <title> Title B </title>
    <description> Description B </description>
    <stuff url="yahoo.com" type="old stuff">
</item>
....

</channel>

I am parsing using something like:

$newsoutput = json_decode(json_encode($the_RSS_Link), TRUE);

foreach ($newsoutput['channel']['item'] as $item) {
   echo $item['title'];
   echo "
";
   echo $item['description'];
   echo "
";
   echo $item['stuff']['url'];
   echo "
";
}

I can get both "title" and "description"; but I cannot extract the "url" values inside "stuff". I have tried various combinations without luck

Please advise.

Thank you,

H.

Body:
Assuming you have valid XML (which you should if it is a valid RSS fee) you can use the SimpleXML parser:

$xml = '<channel>
<item>
    <title> Title A </title>
    <description> Description A </description>
    <stuff url="google.com" type="search engine"/>
</item>

<item>
    <title> Title B </title>
    <description> Description B </description>
    <stuff url="yahoo.com" type="old stuff"/>
</item></channel>';
$x = new simplexmlelement($xml);
foreach($x->item as $item){
    echo $item->title . ' ' . $item->stuff['url'] . ' ' . $item->stuff['type'] . PHP_EOL;
}

https://3v4l.org/6ICrG

Note the stuff element here has been modified so it is self-closing.


问:
How to execute one function whether it normal or carried and yield the same result?
What would be the body of a the multiply function that if executed in both ways below would give the same result. So either calling multiply(2,4) or multiply(2)(4) would output 8?

答:
Fairly simple - check if the second argument exists, and modify the return value accordingly:

const multiply = (a, b) => b ? a * b : c => a * c;
console.log(multiply(2, 3));
console.log(multiply(2)(4));```
</div>
</div>
</p>

<p>This can also be extended fairly simply to take three arguments:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const multiply = (a, b, c) => c ? a * b * c : (b ? (d => a * b * d) : (d, e) => a ? d * e : f => d * f);
console.log(multiply(2, 3, 4));
console.log(multiply(2, 5)(3));
console.log(multiply(2)(6, 3));</code>```

Body:
Fairly simple - check if the second argument exists, and modify the return value accordingly:

const multiply = (a, b) => b ? a * b : c => a * c;
console.log(multiply(2, 3));
console.log(multiply(2)(4));

This can also be extended fairly simply to take three arguments:

const multiply = (a, b, c) => c ? a * b * c : (b ? (d => a * b * d) : (d, e) => a ? d * e : f => d * f);
console.log(multiply(2, 3, 4));
console.log(multiply(2, 5)(3));
console.log(multiply(2)(6, 3));


问:
Application doesn't work in iPad Simulator, fine in iPhone Simulator
I created an application and it runs OK when I use the iPhone Simulator. When I try to run it on the iPad Simulator it doesn't work.

Several things that may assist anyone who tries to assist with this issue:

In the iPhone Simulator I tried to change the Hardware settings - selecting Device---iPad and also changing the Version (3.2 and 4.0). did not do any difference.

When it runs with the Device---iPad selection it simply opens it with iPhone Simulator

When I open the iPad Simulator without Build and Run from XCode I don't see my app in the applications list on the simulator view.

Should I define something in XCode or in the simulator (like saying "this application should also run in iPad")?

May the problem be related to versions issue? Any other ideas?

答:
The simulator will open to which ever device the project target is set to. Therefore, if you set it to iPhone it will always open in the iPhone simulator. Similarly if you set it to iPad it will only open in the iPad simulator. If you set it to be Universal, then it will support both.

It has nothing to do with which hardware type you select in the simulator. You have to change the target Devices.


问:
How to fix the gap in between elements in the form?
The flexbox form has gap in between form items when there is radio button or checkbox. Is there any option to avoid the gap whether using flex or any other method?

form {
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

form>div {
  box-sizing: border-box;
  padding: 0.5rem;
  -ms-flex-preferred-size: 50%;
  flex-basis: 50%;
}

form>div input:not([type=checkbox]):not([type=radio]),
form>div textarea {
  background-color: rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.1);
  padding: 0.25rem;
  min-height: 40px;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <div><input placeholder="First Name" /></div>
  <div><input placeholder="Last Name" /></div>
  <div>
    <ul class="radio_list">
      <li><input name="form" type="radio" value="0"> <label>Male</label></li>
      <li><input name="form" type="radio" value="1"> <label>Female</label></li>
      <li><input name="form" type="radio" value="2"> <label>gfdg</label></li>
      <li><input name="form" type="radio" value="3"> <label>gfdg</label></li>
      <li><input name="form" type="radio" value="4"> <label>gfd</label></li>
    </ul>
  </div>
  <div><input placeholder="Phone" type="phone" /></div>
  <div><input placeholder="Email" type="email" /></div>
  <div>
    <ul class="checkbox_list">
      <li><input name="form_3" type="checkbox" value="0" checked="checked" required="required"> <label>Checkbox 1</label></li>
      <li><input name="form_3" type="checkbox" value="1" checked="checked"> <label>Checkbox 2</label></li>
      <li><input name="form_3" type="checkbox" value="2" checked="checked"> <label>Checkbox 3</label></li>
    </ul>
  </div>
  <div><textarea rows="4" cols="30" placeholder="Coment"></textarea></div>
</form></code>```

答:
Use CSS grid check out the fiddle

Note: I have also rearranged the checkbox div

```<code>form {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 10px;
}
</code>```

You can specify the rowspan and colspan with CSS grid

```<code>.span-col {
  grid-column: span 2
}

.span-row {
  grid-row: span 2;
}
</code>```

I have added the span-col class to the textarea div, if you remove the class it will align in 2 columns.

Read more about : CSS Grid

Body:
The flexbox form has gap in between form items when there is radio button or checkbox. Is there any option to avoid the gap whether using flex or any other method?

form {
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

form>div {
  box-sizing: border-box;
  padding: 0.5rem;
  -ms-flex-preferred-size: 50%;
  flex-basis: 50%;
}

form>div input:not([type=checkbox]):not([type=radio]),
form>div textarea {
  background-color: rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.1);
  padding: 0.25rem;
  min-height: 40px;
  width: 100%;
}

<form>

<input placeholder="First Name" />

<input placeholder="Last Name" />

<input name="form" type="radio" value="0"> Male

<input name="form" type="radio" value="1"> Female

<input name="form" type="radio" value="2"> gfdg

<input name="form" type="radio" value="3"> gfdg

<input name="form" type="radio" value="4"> gfd

<input placeholder="Phone" type="phone" />

<input placeholder="Email" type="email" />

<input name="form_3" type="checkbox" value="0" checked="checked" required="required"> Checkbox 1

<input name="form_3" type="checkbox" value="1" checked="checked"> Checkbox 2

<input name="form_3" type="checkbox" value="2" checked="checked"> Checkbox 3

<textarea rows="4" cols="30" placeholder="Coment"></textarea>

</form>

Body:
Use CSS grid check out the fiddle

Note: I have also rearranged the checkbox div

form {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 10px;
}

You can specify the rowspan and colspan with CSS grid

.span-col {
  grid-column: span 2
}

.span-row {
  grid-row: span 2;
}

I have added the span-col class to the textarea div, if you remove the class it will align in 2 columns.

Read more about : CSS Grid


问:
kubernetes: precedence of environmental variables
Assuming a pod has an environmental variable set both in its spec, as e.g. below

```<code>spec:
  containers:
  - name: env-print-demo
    image: bash
    env:
    - name: FOO
      value: "BAR"
</code>```

as also injected to it via a ConfigMap (but with a different value) which is the one that will be taken into account?

答: the value that will be taken is the config map because config map will override the env value that have the same key </p>

Body:
Assuming a pod has an environmental variable set both in its spec, as e.g. below

spec:
  containers:
  - name: env-print-demo
    image: bash
    env:
    - name: FOO
      value: "BAR"

as also injected to it via a ConfigMap (but with a different value) which is the one that will be taken into account?


问:
Using lombok annotations with DynamoDB annotations [aws-dynamodb-encryption]
I am using AWS encryption client.The below code throwing error as

Error : @DoNotTouch not applicable on field

```<code>@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Getter
@DynamoDBTable(tableName = "jktest")
public class DataPoJo {

    private String title;

    @DynamoDBHashKey(attributeName = "dummyname")
    private String dummyname;

    @DynamoDBAttribute(attributeName = "example")
    private String example;

    @DoNotEncrypt
    @DynamoDBAttribute(attributeName = "title")
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @DoNotTouch
    @DynamoDBAttribute(attributeName="someProp")
    private String someProp;

}
</code>```

However If i give @DoNotTouch config as below [with getters and setters]

```<code>private String someProp;
@DoNotTouch
@DynamoDBAttribute(attributeName="someProp")
public String getSomeProp() {
    return someProp;
}

public void setSomeProp(String someProp) {
    this.someProp = someProp;
}
</code>```

This is working fine.I guess getters and setters generated by lombok is not recognized by AmazonEncryptionclient

I am following this aws doc :  https://aws.amazon.com/blogs/developer/client-side-encryption-for-amazon-dynamodb/

Did any one faced this issue ? how to fix this ?

答:
We have to use onX feature of lombok.below code fixed the problem</p>

```<code>@Getter(onMethod = @_(@DoNotTouch))
 @DynamoDBAttribute(attributeName="someProp")
 private String someProp;
</code>```

Body:
I am using AWS encryption client.The below code throwing error as

Error : @DoNotTouch not applicable on field

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Getter
@DynamoDBTable(tableName = "jktest")
public class DataPoJo {

    private String title;

    @DynamoDBHashKey(attributeName = "dummyname")
    private String dummyname;

    @DynamoDBAttribute(attributeName = "example")
    private String example;

    @DoNotEncrypt
    @DynamoDBAttribute(attributeName = "title")
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @DoNotTouch
    @DynamoDBAttribute(attributeName="someProp")
    private String someProp;

}

However If i give @DoNotTouch config as below [with getters and setters]

private String someProp;
@DoNotTouch
@DynamoDBAttribute(attributeName="someProp")
public String getSomeProp() {
    return someProp;
}

public void setSomeProp(String someProp) {
    this.someProp = someProp;
}

This is working fine.I guess getters and setters generated by lombok is not recognized by AmazonEncryptionclient

I am following this aws doc :  https://aws.amazon.com/blogs/developer/client-side-encryption-for-amazon-dynamodb/

Did any one faced this issue ? how to fix this ?

Body:
We have to use onX feature of lombok.below code fixed the problem

@Getter(onMethod = @_(@DoNotTouch))
 @DynamoDBAttribute(attributeName="someProp")
 private String someProp;


问:
Formula for one cell containing letter "T" and another cell in the same row containing "*T-T*"
I would like to write a formula that is counting the number of times in which

(1)I have rows with cells in one column  having their content equal to the string "T" and

(2) cells within the same row with their text containing "T-T"(there could be something else before or after T-T).

Here is the formula I am using which is not working:

```<code>   =COUNTIFS($BI$2:$BO$6016,"*T-T*", $BG$2:$BG$6016,"T")
</code>```

I am searching for "T-T" in columns BI through BO and I am searching for "T" only in column BG and I want both of them to coincide in the same row

答:
Perhaps you can try SUMPRODUCT like below.

=SUMPRODUCT(--ISNUMBER(SEARCH("T-T",$BI$2:$BO$6016,1))*($BG$2:$BG$6016="T"))

Body:
I would like to write a formula that is counting the number of times in which

(1)I have rows with cells in one column  having their content equal to the string "T" and

(2) cells within the same row with their text containing "T-T"(there could be something else before or after T-T).

Here is the formula I am using which is not working:

   =COUNTIFS($BI$2:$BO$6016,"*T-T*", $BG$2:$BG$6016,"T")

I am searching for "T-T" in columns BI through BO and I am searching for "T" only in column BG and I want both of them to coincide in the same row


问:
CSS Two columns layout + gradient separation
I am trying to show a gradient vertical separation between two columns, and a bottom horizontal gradient separation between the divs.
The following code (scss) doesn't show the bottom border:

```<code>.col-container {
    .column-box {
        border-width: 2px;
        border-style: solid;
        border-image: linear-gradient(to right, white, #efedf4, white) 1 stretch;
        min-height: 200px;
    }
    & > div:nth-child(odd)  {
        border-width: 2px;
        border-style: solid;
        border-image: linear-gradient(to bottom, white, #efedf4) 0 90%;
     }}
</code>```

While the following code only shows the bottom border:

```<code>.col-container {
    .column-box {
        border-width: 2px;
        border-style: solid;
        border-image: linear-gradient(to right, white, #efedf4, white) 1 stretch;
        min-height: 200px;
    }}
</code>```

Here is the code, as you will see the left div losses its bottom border:
https://jsfiddle.net/0nsvzqxg/

Any idea how to show only the vertical separator in between the 2 divs and the bottom border on all of them?

Thanks

答:
You have 2 things to solve.

draw the border on two sides but from the same gradient

select the right boxes via the nth-child() selector

Since the width of the border image is quiet small, the gradient can be drawn like a diagonal. from a top corner to the opposite bottom corner and repeated once . It could be  linear-gradient(to bottom left,   white, #efedf4, white, #efedf4, white).

while you need to draw one or 2 borders, you need to update the slice values for each borders. See https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-slice

When four positions are specified, they create slices measured from the top, right, bottom, and left in that order (clockwise)

div {
  border-width: 2px;
  border-style: solid;
  border-image: linear-gradient(to bottom left, red, blue, red, blue, red)1 / 2px 2px 2px 2px stretch;
  /* what would be gradient image */
  background: linear-gradient(to bottom/* or top */ left/* or right*/ , blue, red, blue, red, blue);
  box-shadow: inset 0 0 0 2px white;/* break border from background */

  /* demo purpose */
  height: 50vh;
  width: 50vw;
  padding: 1em;
  color: white;
}

html,
div {
  display: flex;
  align-items: center;
  justify-content: center;
}

p {
  margin: 1em;
  padding: 1em;
}

html {
  min-height: 100vh;
}

/* end demo */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>To figure out the gradient image needed for the border, you may draw it in the background to tune it</p>
  <p> from horizontal / vertical to diagonal, it needs to be repeated at least once.</p>
</div></code>```

Note: shorthand values : border-image:/* source | slice | width | outset | repeat */

About the nth-child() selector, you can use a counter CSS to see better where each child stands .

.col-container {
  counter-reset: box
}

.column-box:nth-child(odd) {
  color: tomato
}

.column-box::before {
  counter-increment: box;
  content: 'child N°:'counter(box)' ';
  color: green
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-container">
  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>
  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div></code>```

Once put together, it can be :

.col-container {
  overflow: auto;
}

.col-container > * {
  float: left;
  width: 50%;
  box-sizing: border-box;
}

.col-container .column-box {
  border-width: 2px;
  border-style: solid;

  border-image: linear-gradient(to bottom left, white, #efedf4, white, #efedf4, white)
    2/ 0 0 2px 0 stretch;
  min-height: 30vh;
}
.col-container > div:nth-child(odd) {
  border-width: 2px;
  border-style: solid;

  border-image: linear-gradient(to bottom left, white, #efedf4, white, #efedf4, white)
    2/0 2px 2px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-container">
  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>
  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>
</div></code>```

Note: flex + flex-wrap would be a better option than float, each boxes of each rows will be the same height.

Body:
I am trying to show a gradient vertical separation between two columns, and a bottom horizontal gradient separation between the divs.
The following code (scss) doesn't show the bottom border:

.col-container {
    .column-box {
        border-width: 2px;
        border-style: solid;
        border-image: linear-gradient(to right, white, #efedf4, white) 1 stretch;
        min-height: 200px;
    }
    & > div:nth-child(odd)  {
        border-width: 2px;
        border-style: solid;
        border-image: linear-gradient(to bottom, white, #efedf4) 0 90%;
     }}

While the following code only shows the bottom border:

.col-container {
    .column-box {
        border-width: 2px;
        border-style: solid;
        border-image: linear-gradient(to right, white, #efedf4, white) 1 stretch;
        min-height: 200px;
    }}

Here is the code, as you will see the left div losses its bottom border:
https://jsfiddle.net/0nsvzqxg/

Any idea how to show only the vertical separator in between the 2 divs and the bottom border on all of them?

Thanks

Body:
You have 2 things to solve.

draw the border on two sides but from the same gradient

select the right boxes via the nth-child() selector

Since the width of the border image is quiet small, the gradient can be drawn like a diagonal. from a top corner to the opposite bottom corner and repeated once . It could be  linear-gradient(to bottom left,   white, #efedf4, white, #efedf4, white).

while you need to draw one or 2 borders, you need to update the slice values for each borders. See https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-slice

When four positions are specified, they create slices measured from the top, right, bottom, and left in that order (clockwise)

div {
  border-width: 2px;
  border-style: solid;
  border-image: linear-gradient(to bottom left, red, blue, red, blue, red)1 / 2px 2px 2px 2px stretch;
  /* what would be gradient image */
  background: linear-gradient(to bottom/* or top */ left/* or right*/ , blue, red, blue, red, blue);
  box-shadow: inset 0 0 0 2px white;/* break border from background */

  /* demo purpose */
  height: 50vh;
  width: 50vw;
  padding: 1em;
  color: white;
}

html,
div {
  display: flex;
  align-items: center;
  justify-content: center;
}

p {
  margin: 1em;
  padding: 1em;
}

html {
  min-height: 100vh;
}

/* end demo */

<div>
  <p>To figure out the gradient image needed for the border, you may draw it in the background to tune it</p>
  <p> from horizontal / vertical to diagonal, it needs to be repeated at least once.</p>
</div>

Note: shorthand values : border-image:/* source | slice | width | outset | repeat */

About the nth-child() selector, you can use a counter CSS to see better where each child stands .

.col-container {
  counter-reset: box
}

.column-box:nth-child(odd) {
  color: tomato
}

.column-box::before {
  counter-increment: box;
  content: 'child N°:'counter(box)' ';
  color: green
}

<div class="col-container">
  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>
  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

Once put together, it can be :

.col-container {
  overflow: auto;
}

.col-container > * {
  float: left;
  width: 50%;
  box-sizing: border-box;
}

.col-container .column-box {
  border-width: 2px;
  border-style: solid;

  border-image: linear-gradient(to bottom left, white, #efedf4, white, #efedf4, white)
    2/ 0 0 2px 0 stretch;
  min-height: 30vh;
}
.col-container > div:nth-child(odd) {
  border-width: 2px;
  border-style: solid;

  border-image: linear-gradient(to bottom left, white, #efedf4, white, #efedf4, white)
    2/0 2px 2px 0;
}

<div class="col-container">
  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>
  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>

  <div class="column-box">
    <div class="cover">
      Image
    </div>
  </div>
</div>

Note: flex + flex-wrap would be a better option than float, each boxes of each rows will be the same height.


问:
return last word in a file that starts with capital letter
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

```<code>def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "
</code>```

but this isn't working.

I also tried this:

```<code>    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "
</code>```

Any help?

答:
Looks like you need reversed.

Ex:

```<code>def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in reversed(word_list):   #reversed
            if word[0].isupper():
                return word
    return " "
</code>```

Body:
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "

but this isn't working.

I also tried this:

    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "

Any help?

Body:
Looks like you need reversed.

Ex:

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in reversed(word_list):   #reversed
            if word[0].isupper():
                return word
    return " "


问:
Binary Search Tree remove node function
I am working on a binary search tree and i have been given an insertnode function that looks like

```<code>  void insertNode(Node **t, Node *n)
  {
       if(!(*t))
     *t=n;

     else if((*t)->key<n->key)insertNode(&(*t)->right,n);
     else if((*t)->key>n->key) insertNode(&(*t)->left,n);
  }
</code>```

I am trying to write a function that removes nodes recursively so far i have come up with:

```<code>     void remove(int huntKey,Node **t)
   {
bool keyFound=false;
if(!(*t))
         cout<<"There are no nodes"<<endl;

    while(keyFound==false)
    {
        if((*t)->key==huntKey)
        {
            keyFound=true;
            (*t)->key=0;
        }
        else if((*t)->key < huntKey)remove(huntKey,&(*t)->right);
        else if((*t)->key> huntKey) remove(huntKey,&(*t)->left);
    }
       }
</code>```

Both of these functions are getting called from a switch in my main function which looks like:

```<code>    int main()
    {
 int key=0,countCatch=0;char q;
 Node *t, *n;
 t=0;
 while((q=menu()) !=0)
 {
     switch(q)
     {
     case'?': menu(); break;
     case'i': inOrderPrint(t); break;
     case'a': preOrderPrint(t); break;
     case'b': postOrderPrint(t); break;
     case'c': {cout<<"enter key: ";cin>>key;
     n=createNode(key);insertNode(&t,n);break;}

     case'r':{cout<<"enter the key you want removed: ";
     cin>>key;
     remove(key,&t);
     break;}

     case'n': {countCatch=countNodes(t);cout<<countCatch<<"\n"; };break;
     }
 }

 return 0;
     }
</code>```

my remove node function is not working properly....any advice would help....

答:
Look at the code, it is not recursive though
http://code.google.com/p/cstl/source/browse/src/c_rb.c</p>

Title: Binary Search Tree remove node function

Body:
I am working on a binary search tree and i have been given an insertnode function that looks like

  void insertNode(Node **t, Node *n)
  {
       if(!(*t))
     *t=n;

     else if((*t)->key<n->key)insertNode(&(*t)->right,n);
     else if((*t)->key>n->key) insertNode(&(*t)->left,n);
  }

I am trying to write a function that removes nodes recursively so far i have come up with:

     void remove(int huntKey,Node **t)
   {
bool keyFound=false;
if(!(*t))
         cout<<"There are no nodes"<<endl;

    while(keyFound==false)
    {
        if((*t)->key==huntKey)
        {
            keyFound=true;
            (*t)->key=0;
        }
        else if((*t)->key < huntKey)remove(huntKey,&(*t)->right);
        else if((*t)->key> huntKey) remove(huntKey,&(*t)->left);
    }
       }

Both of these functions are getting called from a switch in my main function which looks like:

    int main()
    {
 int key=0,countCatch=0;char q;
 Node *t, *n;
 t=0;
 while((q=menu()) !=0)
 {
     switch(q)
     {
     case'?': menu(); break;
     case'i': inOrderPrint(t); break;
     case'a': preOrderPrint(t); break;
     case'b': postOrderPrint(t); break;
     case'c': {cout<<"enter key: ";cin>>key;
     n=createNode(key);insertNode(&t,n);break;}

     case'r':{cout<<"enter the key you want removed: ";
     cin>>key;
     remove(key,&t);
     break;}

     case'n': {countCatch=countNodes(t);cout<<countCatch<<"\n"; };break;
     }
 }

 return 0;
     }

my remove node function is not working properly....any advice would help....


问:
Restrict full screen element render from external SDK
I'm using an SDK that renders a full screen element on the page (100% width and height). I want to restrict this.
I'm using Vue.js in this project.

I tried to render inside an iframe following this demo:

Vue.component('i-frame', {

  render(h) {
    return h('iframe', {
      on: { load: this.renderChildren }
    })
  },
  beforeUpdate() {
    //freezing to prevent unnessessary Reactifiation of vNodes
    this.iApp.children = Object.freeze(this.$slots.default)
  },
  methods: {
    renderChildren() {
      const children = this.$slots.default
      const body = this.$el.contentDocument.body
      const el = document.createElement('DIV') // we will mount or nested app to this element
      body.appendChild(el)

      const iApp = new Vue({
        name: 'iApp',
        //freezing to prevent unnessessary Reactifiation of vNodes
        data: { children: Object.freeze(children) },
        render(h) {
          return h('div', this.children)
        },
      })

      iApp.$mount(el) // mount into iframe

      this.iApp = iApp // cache instance for later updates

    }
  }
})

Vue.component('test-child', {
  template: `

{{ title }}

      <slot/>

`,
  props: ['title'],
  methods: {
    log: _.debounce(function () {
      console.log('resize!')
    }, 200)
  },
  mounted() {
    this.$nextTick(() => {
      const doc = this.$el.ownerDocument
      const win = doc.defaultView
      win.addEventListener('resize', this.log)
    })
  },
  beforeDestroy() {
    const doc = this.$el.ownerDocument
    const win = doc.defaultView
    win.removeEventListener('resize', this.log)
  }
})

new Vue({
  el: '#app',
  data: {
    dynamicPart: 'InputContent',
    show: false,
  }
})
```

https://jsfiddle.net/Linusborg/ohznser9/

And read this question:
Render Component in iframe using vuejs without src attribute

But nothing restricts this behavior.
The SDK in question is the Zoom Web SDK

答:
I think you should give it a shot using A Modal to control views and what to show. I use it for a current project to display different view I have full control over how much of the screen it should take
Try this plugin Vue-js-modal. It is very nice and well documented</p>

Body:
I'm using an SDK that renders a full screen element on the page (100% width and height). I want to restrict this.
I'm using Vue.js in this project.

I tried to render inside an iframe following this demo:

Vue.component('i-frame', {

  render(h) {
    return h('iframe', {
      on: { load: this.renderChildren }
    })
  },
  beforeUpdate() {
    //freezing to prevent unnessessary Reactifiation of vNodes
    this.iApp.children = Object.freeze(this.$slots.default)
  },
  methods: {
    renderChildren() {
      const children = this.$slots.default
      const body = this.$el.contentDocument.body
      const el = document.createElement('DIV') // we will mount or nested app to this element
      body.appendChild(el)

      const iApp = new Vue({
        name: 'iApp',
        //freezing to prevent unnessessary Reactifiation of vNodes
        data: { children: Object.freeze(children) },
        render(h) {
          return h('div', this.children)
        },
      })

      iApp.$mount(el) // mount into iframe

      this.iApp = iApp // cache instance for later updates

    }
  }
})

Vue.component('test-child', {
  template: `

{{ title }}

      <slot/>

`,
  props: ['title'],
  methods: {
    log: _.debounce(function () {
      console.log('resize!')
    }, 200)
  },
  mounted() {
    this.$nextTick(() => {
      const doc = this.$el.ownerDocument
      const win = doc.defaultView
      win.addEventListener('resize', this.log)
    })
  },
  beforeDestroy() {
    const doc = this.$el.ownerDocument
    const win = doc.defaultView
    win.removeEventListener('resize', this.log)
  }
})

new Vue({
  el: '#app',
  data: {
    dynamicPart: 'InputContent',
    show: false,
  }
})

https://jsfiddle.net/Linusborg/ohznser9/

And read this question:
Render Component in iframe using vuejs without src attribute

But nothing restricts this behavior.
The SDK in question is the Zoom Web SDK