问:
Switch to parent frame webdriver
The issue I am having is switching to the parent frame or iFrame using webdriver.js. I tried implementing a function to do this and it does work but only up to the second level of frames. If I wanted to switch to the parent frame from a frame that is like 4 or 5 levels deep this function would be even fuglier than what it is now. One of the major issues is that I have to use a for loop to get the top level of frames and then loop through each of those frames to get there nested frames if they have any. I have to be able to keep looping until no frames have any frames that are nested. Also as you can tell the solution below has alot of redundant code and nested to the point of callback hell. I tried to extract the for loop process to a helper function but the problem I have with that is that I have to switch back to the top level and then navigate back down the frame ladder to check each frame for nested frames. I added comments to help with the ugliness.</p>

```<code>this.switchToParentFrame = function (frameOrIFrame) {
        //Keep local variable of current frame name
        var currentFrameName;
        //Get current frame name
        this.getCurrentFrameName().then(function (name) {
            currentFrameName = name;
            return driver.switchTo().defaultContent();
        }).then(function () {
            //Find top level frames
            return driver.findElements(webdriver.By.css(frameOrIFrame));
        }).then(function (frames) {
            //Loop through each top level frame to find nested frames
            frames.forEach(function (frame) {
                //Switch back to the default content to check each top level frame
                driver.switchTo().defaultContent().then(function () {
                    return driver.switchTo().frame(frame);
                }).then(function () {
                //Find the nested frames for each top level frame
                    return driver.findElements(webdriver.By.css(frameOrIFrame));
                }).then(function (nestFrames) {
                    //Check to make sure the top level frame has a nested frame
                    if (nestFrames.length > 0) {
                        //Loop through each nested frame to check its name with the current frame name var
                        nestFrames.forEach(function (nestFrame) {
                            //Switch to the default content to switch frames
                            driver.switchTo().defaultContent().then(function () {
                                //Switch to the top level frame
                                return driver.switchTo().frame(frame);
                            }).then(function() {
                                //switch to the nested frame
                                return driver.switchTo().frame(nestFrame);
                            }).then(function () {
                                //Get the nested frames name
                                return driver.executeScript('return self.name');
                            }).then(function (name) {
                                //Check to see if the nested frames name is equal to the current frame name var and if so set it equal to the parent frame
                                if (name === currentFrameName){
                                    currentFrameName = frame;
                                }
                            });
                        });
                    }
                });
            });
        }).then(function() {
           return driver.switchTo().defaultContent();
        }).then(function() {
           //Switch to the parent frame
           return driver.switchTo().frame(currentFrameName);
        });
    };
</code>```

答:
If anyone else drops by this question

```<code>driver.switchTo().parentFrame()
</code>```

does not work in NodeJS or Javascript but

```<code>driver.switchTo().defaultContent()
</code>```

does work.

Title: Switch to parent frame webdriver

Body:
The issue I am having is switching to the parent frame or iFrame using webdriver.js. I tried implementing a function to do this and it does work but only up to the second level of frames. If I wanted to switch to the parent frame from a frame that is like 4 or 5 levels deep this function would be even fuglier than what it is now. One of the major issues is that I have to use a for loop to get the top level of frames and then loop through each of those frames to get there nested frames if they have any. I have to be able to keep looping until no frames have any frames that are nested. Also as you can tell the solution below has alot of redundant code and nested to the point of callback hell. I tried to extract the for loop process to a helper function but the problem I have with that is that I have to switch back to the top level and then navigate back down the frame ladder to check each frame for nested frames. I added comments to help with the ugliness.

this.switchToParentFrame = function (frameOrIFrame) {
        //Keep local variable of current frame name
        var currentFrameName;
        //Get current frame name
        this.getCurrentFrameName().then(function (name) {
            currentFrameName = name;
            return driver.switchTo().defaultContent();
        }).then(function () {
            //Find top level frames
            return driver.findElements(webdriver.By.css(frameOrIFrame));
        }).then(function (frames) {
            //Loop through each top level frame to find nested frames
            frames.forEach(function (frame) {
                //Switch back to the default content to check each top level frame
                driver.switchTo().defaultContent().then(function () {
                    return driver.switchTo().frame(frame);
                }).then(function () {
                //Find the nested frames for each top level frame
                    return driver.findElements(webdriver.By.css(frameOrIFrame));
                }).then(function (nestFrames) {
                    //Check to make sure the top level frame has a nested frame
                    if (nestFrames.length > 0) {
                        //Loop through each nested frame to check its name with the current frame name var
                        nestFrames.forEach(function (nestFrame) {
                            //Switch to the default content to switch frames
                            driver.switchTo().defaultContent().then(function () {
                                //Switch to the top level frame
                                return driver.switchTo().frame(frame);
                            }).then(function() {
                                //switch to the nested frame
                                return driver.switchTo().frame(nestFrame);
                            }).then(function () {
                                //Get the nested frames name
                                return driver.executeScript('return self.name');
                            }).then(function (name) {
                                //Check to see if the nested frames name is equal to the current frame name var and if so set it equal to the parent frame
                                if (name === currentFrameName){
                                    currentFrameName = frame;
                                }
                            });
                        });
                    }
                });
            });
        }).then(function() {
           return driver.switchTo().defaultContent();
        }).then(function() {
           //Switch to the parent frame
           return driver.switchTo().frame(currentFrameName);
        });
    };

Body:
If anyone else drops by this question

driver.switchTo().parentFrame()

does not work in NodeJS or Javascript but

driver.switchTo().defaultContent()

does work.


来源: stackexchange

问:
How to make a jquery tab contain an html form that redirects inside the tab?
currently I have a section of my page with jquery tabs. The tabs reference html pages, and each contain a form for someone to enter their details. On clicking the submit button, ideally, their details should be submitted to a mySQL database, and they should then be redirected to a javascript form. I'm not bothered what happens after that, but everything there should happen inside the tab.

I've managed to get the mySQL submit working, and I've verified that it inserts the data into the database. However, it loads the php submit for the form as a whole new page, rather than staying in the tabs. It also doesn't redirect, although I may have mistyped something.

I've got links to work in the tabs, in that, I placed a link in there and got it to load inside the tab when I clicked on it. I just can't seem to work out this part though :S

For the form submit, I'm using a php page, which contains the php for writing to the database, followed by a javascript redirect in  tags.

Can anyone help? Thanks!

AWESOME guys, thanks loads! It's finally working. :)

If anyone's interested, this tutorial was pretty helpful. http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form

答:
I think you're using a regular submission instead of an AJAX one.
If so, read jQuery related documentation:

http://api.jquery.com/category/ajax/

http://api.jquery.com/serialize/

http://api.jquery.com/submit/

ContentLicense: CC BY-SA 3.0


问:
How to populate dynamically added input fields with Json object
I have a this table of input fields which I can add rows dynamically with help of KnockoutJS

```<code>     <table id="sTypeTable" class="table table-bordered" hidden="hidden">
         <tr>
             <th> Name </th>
             <th> Value </th>
             <th> <a class="btn btn-primary btn-sm"  onclick="addReqField(0);"><i class="fa fa-plus"></i></a></th>
         </tr>
<!-- ko foreach: {data: requestFields, as: 'reqField'} -->
        <tr id="sRow">
           <td>
              <input id="sName" data-bind="value: reqField[0]" onblur="createJSON()"/>
           </td>
           <td>
              <input id="sValue" data-bind="value: reqField[0]" onblur="createJSON()"/>
           </td>
           <td>
              <a class="btn btn-warning  btn-sm" data-bind="click: removeResField2" ><i class="glyphicon glyphicon-remove"></i></a>
          </td>
       </tr>
<!-- /ko -->
 </table>
  <div class="col-md-11 ">
    <textarea style="font-size: larger; min-height: 200px" class="form-control" id="requestData" oninput="storeValueOfTextArea()"></textarea>
  </div>
</code>```

From this inputs I'm generating
following Json object on textarea (id="requestData")

```<code>[
  {
    "users": [
      {
        "name": "John",
        "value": "12"
      },
      {
        "name": "Sarah",
        "value": "13"
      },
      {
        "name": "Tom",
        "value": "14"
      }
    ]
  }
]
</code>```

It works well, but now I need populate these input fields from Json object,
When object entered to textarea.
I have tried following way

```<code><script th:inline="javascript">

 function storeValueOfTextArea() {
      var lines = $('#requestData').val();
      var texts = JSON.parse(lines);

  for (var i=0; i!== texts[0].users.length;i++){
      addReqField();  // method for adding new row of input fields

      let  v = texts[0].users[i];
      $("tr[id=sRow]").each(function() {
          $("#sName").val(v.name);
          $("#sValue").val(v.value);
      });
  }
 </script>
</code>```

but in result  only first input field gets the last object

```<code>{
   "name": "Tom",
   "value": "14"
 }
</code>```

others stays empty

答:
```<code>$("tr[id=sRow]").each(function() {
      $("#sName").val(v.name);
      $("#sValue").val(v.value);
  });
</code>```

This doesn't seem to be good. You should get the row index you want, according to the index of the user for which data you want to fill. Right now what this does is to fill every row with the same user data, in all iterations of the for loop. In the end, the last user data will be in all rows.

ContentLicense: CC BY-SA 4.0

Body:
I have a this table of input fields which I can add rows dynamically with help of KnockoutJS

              Name
              Value

              <input id="sName" data-bind="value: reqField[0]" onblur="createJSON()"/>

              <input id="sValue" data-bind="value: reqField[0]" onblur="createJSON()"/>

    <textarea style="font-size: larger; min-height: 200px" class="form-control" id="requestData" oninput="storeValueOfTextArea()"></textarea>

From this inputs I'm generating
following Json object on textarea (id="requestData")

[
  {
    "users": [
      {
        "name": "John",
        "value": "12"
      },
      {
        "name": "Sarah",
        "value": "13"
      },
      {
        "name": "Tom",
        "value": "14"
      }
    ]
  }
]

It works well, but now I need populate these input fields from Json object,
When object entered to textarea.
I have tried following way

but in result  only first input field gets the last object

{
   "name": "Tom",
   "value": "14"
 }

others stays empty

Body:
$("tr[id=sRow]").each(function() {
      $("#sName").val(v.name);
      $("#sValue").val(v.value);
  });

This doesn't seem to be good. You should get the row index you want, according to the index of the user for which data you want to fill. Right now what this does is to fill every row with the same user data, in all iterations of the for loop. In the end, the last user data will be in all rows.


问:
Pycharm gets error "can't find '__main__' module"
Whenever I try to run script via Virtualenv in pycharm, i get this error:

```<code>C:\Users\Costello\PycharmProjects\test\venv\Scripts\python.exe C:/Users/Costello/PycharmProjects/test
C:\Users\Costello\PycharmProjects\test\venv\Scripts\python.exe: can't find '__main__' module in 'C:/Users/Costello/PycharmProjects/test'
</code>```

Everything works fine via idle, or vs code.
I figure it must be something with a way that I have setup my pycharm but have no idea what.

edit: this happens whatever I run, even simple print function.

edit: even with choosing regular python intepreteur, same happens just in pycharm

```<code>C:\Users\Costello\AppData\Local\Programs\Python\Python37\python.exe: can't find '__main__' module in 'C:/Users/Costello/PycharmProjects/test'
</code>```

答:
I fixed it by removing values from Interpreter options field in run/debug configurations. While trying to add an interpreter, I had added the python path to the mentioned field.

After clearing out the field all worked well.

You can find run/debug configuration settings in the drop-down left of run icon on top-right of pycharm window.

Body:
Whenever I try to run script via Virtualenv in pycharm, i get this error:

C:\Users\Costello\PycharmProjects\test\venv\Scripts\python.exe C:/Users/Costello/PycharmProjects/test
C:\Users\Costello\PycharmProjects\test\venv\Scripts\python.exe: can't find '__main__' module in 'C:/Users/Costello/PycharmProjects/test'

Everything works fine via idle, or vs code.
I figure it must be something with a way that I have setup my pycharm but have no idea what.

edit: this happens whatever I run, even simple print function.

edit: even with choosing regular python intepreteur, same happens just in pycharm

C:\Users\Costello\AppData\Local\Programs\Python\Python37\python.exe: can't find '__main__' module in 'C:/Users/Costello/PycharmProjects/test'


问:
How to deference member fields that have already been initialized when constructor throws an error
```<code>class XYZ {

   FileInputStream fis;  //opens a file stream
   DBConnection connection; //this is used to connect to a database

   XYZ(String fileName, String dbName) {
       fis = new FileInputStream(fileName);
       connection = getDBConnection(dbName); //assume that this line would throw error
   }
}
</code>```

Consider the following scenario: object of class XYZ is created as XYZ obj = new XYZ() - now during the object creation, when constructor is called, let us assume that fis is successfully initialized, but call to the next statement throws an error.
W.r.t to the above scenario:

Does fis contain a valid reference? (since the statement executed successfully but the next statement failed)

If fis holds a valid reference, how to ensure that fis would be closed, so as to not have a memory leak (One way would be to define a finalize method for this class, but Java GC does not guarantee finalize() would be called)

答:
Does fis contain a valid reference? (since the statement executed successfully but the next statement failed)

That is not really the point. The field fis doesn't exist after the constructor is "left" because of that exception. But the object that fis references to, that one is still around.

Until the garbage collector kicks in. When the GC removes that FileInputStream object, it will also return the corresponding file handle to the underlying OS (see here for further details).

The real catch here: you have no idea when the GC will kick in to return the file handle.

So, you can either do what the answer suggests (to put a try catch around the second call, and have a fis.close() in the catch block). Or you consider other ways of addressing this, for example by not having such complex operations taking place in the constructor of the object.

Body:
class XYZ {

   FileInputStream fis;  //opens a file stream
   DBConnection connection; //this is used to connect to a database

   XYZ(String fileName, String dbName) {
       fis = new FileInputStream(fileName);
       connection = getDBConnection(dbName); //assume that this line would throw error
   }
}

Consider the following scenario: object of class XYZ is created as XYZ obj = new XYZ() - now during the object creation, when constructor is called, let us assume that fis is successfully initialized, but call to the next statement throws an error.
W.r.t to the above scenario:

Does fis contain a valid reference? (since the statement executed successfully but the next statement failed)

If fis holds a valid reference, how to ensure that fis would be closed, so as to not have a memory leak (One way would be to define a finalize method for this class, but Java GC does not guarantee finalize() would be called)


问:
Blockchain representation
I am not able to understand the hashcode() part of the given code snippets.

I have tried searching about it but I am not able to figure it out.

```<code>    this.hash  = Arrays.hashCode(new Integer[]{data.hashCode(), previousHash});
</code>```

答:
Arrays-class implements a set of ready made and robust methods for calculating hash codes for arrays of different types. This example calls Arrays.hashCode(int[]).

Essentially, this is just a way for creating a hash code from two existing hash codes (data.hashCode() and previousHash).

Title: Blockchain representation

Body:
I am not able to understand the hashcode() part of the given code snippets.

I have tried searching about it but I am not able to figure it out.

    this.hash  = Arrays.hashCode(new Integer[]{data.hashCode(), previousHash});


问:
Excluding multiple urls in Strpos- why doesn't it work?
I'm trying to exclude several urls from appending a nofollow rule using strpos but it only works with 1 url, I can't get it to exclude all the urls I need to include.

This is the code that I've tried:

```<code>add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );
function my_custom_bbpress_nofollow( $nofollow, $href ) {

if ( strpos( $href, 'https://www.examplelink1.com' ) === false && strpos( $href, 'https://www.examplelink2.com' ) === false && strpos( $href, 'https://www.examplelink3.com' ) === false && strpos( $href, 'https://examplelink4.to' ) === false) {
       $nofollow = '';
   }

   return $nofollow;
}
</code>```

I've tried it with == false and !== false as well and those don't seem to work.

This one DOES work, but it only excludes a single domain, I need to be able to exclude 5 in all.

```<code>add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );
function my_custom_bbpress_nofollow( $nofollow, $href ) {

    if ( strpos( $href, 'http://your-domain.here' ) !== false ) {
        $nofollow = 'rel="dofollow"';
    }

    return $nofollow;
}
</code>```

What is the correct strpos syntax to include multiple urls,

```<code>https://www.examplelink1.com AND/OR
https://www.examplelink2.com AND/OR
https://www.examplelink3.com AND/OR
https://www.examplelink4.com
</code>```

答:
I believe you want to use || (OR) instead of && (AND) in your if statement.
Your $href will never match ALL conditions, so using AND will never return true. With OR you tell it to set $nofollow = '' if ANY of those URLs is found.

```<code>add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );
function my_custom_bbpress_nofollow( $nofollow, $href ) {

if ( strpos( $href, 'https://www.examplelink1.com' ) === false || strpos( $href, 'https://www.examplelink2.com' ) === false || strpos( $href, 'https://www.examplelink3.com' ) === false || strpos( $href, 'https://examplelink4.to' ) === false) {
   $nofollow = '';
}

return $nofollow;
}
</code>```

Edit: Actually, I'm not too sure what you're trying to do. Your 2 examples have opposite code, which is confusing. If you wish to return 'rel="nofollow"' if href equals ANY of the 5 urls, then try this:

```<code> add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );

 function my_custom_bbpress_nofollow( $nofollow, $href ) {
     $nofollow = '';
     if ( strpos( $href, 'http://your-domain.here' ) !== false ||
          strpos( $href, 'https://www.examplelink1.com' ) !== false ||
          strpos( $href, 'https://www.examplelink2.com' ) !== false ||
          strpos( $href, 'https://www.examplelink3.com' ) !== false ||
          strpos( $href, 'https://www.examplelink4.com' ) !== false
    ) {
         $nofollow = 'rel="dofollow"';
     }

    return $nofollow;
 }
</code>```

You should also define $nofollow at the start of the function, otherwise nothing can be returned if the condition doesn't match.

Body:
I'm trying to exclude several urls from appending a nofollow rule using strpos but it only works with 1 url, I can't get it to exclude all the urls I need to include.

This is the code that I've tried:

add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );
function my_custom_bbpress_nofollow( $nofollow, $href ) {

if ( strpos( $href, 'https://www.examplelink1.com' ) === false && strpos( $href, 'https://www.examplelink2.com' ) === false && strpos( $href, 'https://www.examplelink3.com' ) === false && strpos( $href, 'https://examplelink4.to' ) === false) {
       $nofollow = '';
   }

   return $nofollow;
}

I've tried it with == false and !== false as well and those don't seem to work.

This one DOES work, but it only excludes a single domain, I need to be able to exclude 5 in all.

add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );
function my_custom_bbpress_nofollow( $nofollow, $href ) {

    if ( strpos( $href, 'http://your-domain.here' ) !== false ) {
        $nofollow = 'rel="dofollow"';
    }

    return $nofollow;
}

What is the correct strpos syntax to include multiple urls,

https://www.examplelink1.com AND/OR
https://www.examplelink2.com AND/OR
https://www.examplelink3.com AND/OR
https://www.examplelink4.com

Body:
I believe you want to use || (OR) instead of && (AND) in your if statement.
Your $href will never match ALL conditions, so using AND will never return true. With OR you tell it to set $nofollow = '' if ANY of those URLs is found.

add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );
function my_custom_bbpress_nofollow( $nofollow, $href ) {

if ( strpos( $href, 'https://www.examplelink1.com' ) === false || strpos( $href, 'https://www.examplelink2.com' ) === false || strpos( $href, 'https://www.examplelink3.com' ) === false || strpos( $href, 'https://examplelink4.to' ) === false) {
   $nofollow = '';
}

return $nofollow;
}

Edit: Actually, I'm not too sure what you're trying to do. Your 2 examples have opposite code, which is confusing. If you wish to return 'rel="nofollow"' if href equals ANY of the 5 urls, then try this:

 add_filter( 'custom_bbpress_nofollow', 'my_custom_bbpress_nofollow', 15, 2 );

 function my_custom_bbpress_nofollow( $nofollow, $href ) {
     $nofollow = '';
     if ( strpos( $href, 'http://your-domain.here' ) !== false ||
          strpos( $href, 'https://www.examplelink1.com' ) !== false ||
          strpos( $href, 'https://www.examplelink2.com' ) !== false ||
          strpos( $href, 'https://www.examplelink3.com' ) !== false ||
          strpos( $href, 'https://www.examplelink4.com' ) !== false
    ) {
         $nofollow = 'rel="dofollow"';
     }

    return $nofollow;
 }

You should also define $nofollow at the start of the function, otherwise nothing can be returned if the condition doesn't match.


问:
How do I use Codable to decode json response which has changing keys?
I have a json response from the fixer api. And I want to decode it to the struct which is shown below. The issue is the values of "rates" in the json is an array of key:value pairs, which has varying keys.

I have the second structure which must be mapped from these key-values.

How can i do it using Codable?

```<code>{
    "success": true,
    "timestamp": 1558883585,
    "base": "EUR",
    "date": "2019-05-26",
    "rates": {
        "AED": 4.116371,
        "AFN": 90.160103,
        "ALL": 122.341655,
        "AMD": 536.359254,
        "ANG": 2.097299,
        "AOA": 368.543773,
        "ARS": 50.418429,
        "AUD": 1.618263,
        "AWG": 2.012124,
        "AZN": 1.910752,
        "BAM": 1.955812,
        "BBD": 2.227793,
        "BDT": 94.245988,
        "BGN": 1.956097,
        "BHD": 0.421705,
        "BIF": 2051.459244,
        "BMD": 1.120649,
        "BND": 1.539664,
        "BOB": 7.729394,
        "BRL": 4.508038,
        "BSD": 1.118587,
        "BTC": 0.00014,
        "BTN": 77.755286,
        "BWP": 12.040813,
        "BYN": 2.323273,
        "BYR": 21964.71167,
        "BZD": 2.254689
    }
}
</code>```

If i change the 'ExchangeRate' struct as below, it is easily decoded. But I have the requirement where the "rates" should be an array of "ConvertedRate" struct.

```<code>struct ExchangeRate : Codable {

    let base : String
    let date : String

    let rates : [String:Double]
}
</code>```

This is what i need.

```<code>struct ExchangeRate : Codable {

    let base : String
    let date : String

    let rates : [ConvertedRate] //keys are varied in json

}

struct ConvertedRate : Codable, Comparable{

   let currencyName : String

   let rate : Double

}
</code>```

答:
You'll have to write a custom init(from:) since you are not using the "default behavior".

More info on the Apple documentation.

Here is a possible solution:

```<code>struct ExchangeRate : Codable {

    let base : String
    let date : String

    let rates : [ConvertedRate]

    enum CodingKeys: String, CodingKey {
        case base
        case date
        case rates
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        base = try values.decode(String.self, forKey: .base)
        date = try values.decode(String.self, forKey: .date)
        let additionalInfo = try values.decode([String: Double].self, forKey: .rates)
        print(additionalInfo)
        rates = additionalInfo.map({ ConvertedRate(name: $0.key, rate: $0.value) })
    }
}

struct ConvertedRate : Codable {
    let currencyName : String
    let rate : Double

    init(name: String, rate: Double) {
        self.currencyName = name
        self.rate = rate
    }
}
</code>```

Side Note: The current code can decode your JSON as you want, but it doesn't re-encoded as it was, because it's replicating the Swift structure:

```<code>{
    "base": "EUR",
    "date": "2019-05-26",
    "rates": [{
        "currencyName": "BSD",
        "rate": 1.118587
    }, {
        "currencyName": "BWP",
        "rate": 12.040813
    }, {
        "currencyName": "BYN",
        "rate": 2.3232729999999999
    }, {
        "currencyName": "BBD",
        "rate": 2.2277930000000001
    }, {
        "currencyName": "BOB",
        "rate": 7.7293940000000001
    }, {
        "currencyName": "BAM",
        "rate": 1.9558120000000001
    }, {
        "currencyName": "AUD",
        "rate": 1.618263
    }, {
        "currencyName": "AFN",
        "rate": 90.160103000000007
    }, {
        "currencyName": "BYR",
        "rate": 21964.711670000001
    }, {
        "currencyName": "BRL",
        "rate": 4.508038
    }, {
        "currencyName": "BMD",
        "rate": 1.120649
    }, {
        "currencyName": "BGN",
        "rate": 1.956097
    }, {
        "currencyName": "BHD",
        "rate": 0.421705
    }, {
        "currencyName": "ANG",
        "rate": 2.097299
    }, {
        "currencyName": "AOA",
        "rate": 368.54377299999999
    }, {
        "currencyName": "BZD",
        "rate": 2.2546889999999999
    }, {
        "currencyName": "ARS",
        "rate": 50.418429000000003
    }, {
        "currencyName": "BTC",
        "rate": 0.00013999999999999999
    }, {
        "currencyName": "BIF",
        "rate": 2051.4592440000001
    }, {
        "currencyName": "AWG",
        "rate": 2.012124
    }, {
        "currencyName": "AED",
        "rate": 4.116371
    }, {
        "currencyName": "AMD",
        "rate": 536.35925399999996
    }, {
        "currencyName": "BDT",
        "rate": 94.245987999999997
    }, {
        "currencyName": "BND",
        "rate": 1.5396639999999999
    }, {
        "currencyName": "BTN",
        "rate": 77.755285999999998
    }, {
        "currencyName": "AZN",
        "rate": 1.910752
    }, {
        "currencyName": "ALL",
        "rate": 122.341655
    }]
}
</code>```

Body:
I have a json response from the fixer api. And I want to decode it to the struct which is shown below. The issue is the values of "rates" in the json is an array of key:value pairs, which has varying keys.

I have the second structure which must be mapped from these key-values.

How can i do it using Codable?

{
    "success": true,
    "timestamp": 1558883585,
    "base": "EUR",
    "date": "2019-05-26",
    "rates": {
        "AED": 4.116371,
        "AFN": 90.160103,
        "ALL": 122.341655,
        "AMD": 536.359254,
        "ANG": 2.097299,
        "AOA": 368.543773,
        "ARS": 50.418429,
        "AUD": 1.618263,
        "AWG": 2.012124,
        "AZN": 1.910752,
        "BAM": 1.955812,
        "BBD": 2.227793,
        "BDT": 94.245988,
        "BGN": 1.956097,
        "BHD": 0.421705,
        "BIF": 2051.459244,
        "BMD": 1.120649,
        "BND": 1.539664,
        "BOB": 7.729394,
        "BRL": 4.508038,
        "BSD": 1.118587,
        "BTC": 0.00014,
        "BTN": 77.755286,
        "BWP": 12.040813,
        "BYN": 2.323273,
        "BYR": 21964.71167,
        "BZD": 2.254689
    }
}

If i change the 'ExchangeRate' struct as below, it is easily decoded. But I have the requirement where the "rates" should be an array of "ConvertedRate" struct.

struct ExchangeRate : Codable {

    let base : String
    let date : String

    let rates : [String:Double]
}

This is what i need.

struct ExchangeRate : Codable {

    let base : String
    let date : String

    let rates : [ConvertedRate] //keys are varied in json

}

struct ConvertedRate : Codable, Comparable{

   let currencyName : String

   let rate : Double

}

Body:
You'll have to write a custom init(from:) since you are not using the "default behavior".

More info on the Apple documentation.

Here is a possible solution:

struct ExchangeRate : Codable {

    let base : String
    let date : String

    let rates : [ConvertedRate]

    enum CodingKeys: String, CodingKey {
        case base
        case date
        case rates
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        base = try values.decode(String.self, forKey: .base)
        date = try values.decode(String.self, forKey: .date)
        let additionalInfo = try values.decode([String: Double].self, forKey: .rates)
        print(additionalInfo)
        rates = additionalInfo.map({ ConvertedRate(name: $0.key, rate: $0.value) })
    }
}

struct ConvertedRate : Codable {
    let currencyName : String
    let rate : Double

    init(name: String, rate: Double) {
        self.currencyName = name
        self.rate = rate
    }
}

Side Note: The current code can decode your JSON as you want, but it doesn't re-encoded as it was, because it's replicating the Swift structure:

{
    "base": "EUR",
    "date": "2019-05-26",
    "rates": [{
        "currencyName": "BSD",
        "rate": 1.118587
    }, {
        "currencyName": "BWP",
        "rate": 12.040813
    }, {
        "currencyName": "BYN",
        "rate": 2.3232729999999999
    }, {
        "currencyName": "BBD",
        "rate": 2.2277930000000001
    }, {
        "currencyName": "BOB",
        "rate": 7.7293940000000001
    }, {
        "currencyName": "BAM",
        "rate": 1.9558120000000001
    }, {
        "currencyName": "AUD",
        "rate": 1.618263
    }, {
        "currencyName": "AFN",
        "rate": 90.160103000000007
    }, {
        "currencyName": "BYR",
        "rate": 21964.711670000001
    }, {
        "currencyName": "BRL",
        "rate": 4.508038
    }, {
        "currencyName": "BMD",
        "rate": 1.120649
    }, {
        "currencyName": "BGN",
        "rate": 1.956097
    }, {
        "currencyName": "BHD",
        "rate": 0.421705
    }, {
        "currencyName": "ANG",
        "rate": 2.097299
    }, {
        "currencyName": "AOA",
        "rate": 368.54377299999999
    }, {
        "currencyName": "BZD",
        "rate": 2.2546889999999999
    }, {
        "currencyName": "ARS",
        "rate": 50.418429000000003
    }, {
        "currencyName": "BTC",
        "rate": 0.00013999999999999999
    }, {
        "currencyName": "BIF",
        "rate": 2051.4592440000001
    }, {
        "currencyName": "AWG",
        "rate": 2.012124
    }, {
        "currencyName": "AED",
        "rate": 4.116371
    }, {
        "currencyName": "AMD",
        "rate": 536.35925399999996
    }, {
        "currencyName": "BDT",
        "rate": 94.245987999999997
    }, {
        "currencyName": "BND",
        "rate": 1.5396639999999999
    }, {
        "currencyName": "BTN",
        "rate": 77.755285999999998
    }, {
        "currencyName": "AZN",
        "rate": 1.910752
    }, {
        "currencyName": "ALL",
        "rate": 122.341655
    }]
}


问:
First Webview was working , but button are not clicking and not showing photos
i created a webview for my site , the page is hosted in my server, it works fine when inspecting element with mobile phone setting , but when the same page is loaded to the webview in android , the button when clicks does nothing and images are not loading

i added the lines

```<code> val mWebSettings = mWebView.getSettings()
        mWebSettings.setJavaScriptEnabled(true)
        mWebSettings.setDomStorageEnabled(true)
        mWebSettings.setSupportZoom(false)
        mWebSettings.setAllowFileAccess(true)
        mWebSettings.setAllowContentAccess(true)
</code>```

MainAcitvity

```<code>package com.example.student.myapplication

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import android.webkit.WebSettings

class MainActivity : AppCompatActivity() {

    var mWebView: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mWebView = findViewById<WebView>(R.id.webview);
        val mWebSettings = mWebView.getSettings()
        mWebSettings.setJavaScriptEnabled(true)
        mWebSettings.setDomStorageEnabled(true)
        mWebSettings.setSupportZoom(false)
        mWebSettings.setAllowFileAccess(true)
        mWebSettings.setAllowContentAccess(true)
        mWebView!!.webViewClient = object : WebViewClient(){
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean{
                view?.loadUrl(url)
                return true
            }
        }
        mWebView!!.loadUrl("https://qiwi.io/")
    }
}
</code>```

I am getting error in the line

```<code>val mWebSettings = mWebView.getSettings()
</code>```

答:
try following...

```<code>webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW)
</code>```

Kotlin

```<code>webView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
</code>```

Body:
i created a webview for my site , the page is hosted in my server, it works fine when inspecting element with mobile phone setting , but when the same page is loaded to the webview in android , the button when clicks does nothing and images are not loading

i added the lines

 val mWebSettings = mWebView.getSettings()
        mWebSettings.setJavaScriptEnabled(true)
        mWebSettings.setDomStorageEnabled(true)
        mWebSettings.setSupportZoom(false)
        mWebSettings.setAllowFileAccess(true)
        mWebSettings.setAllowContentAccess(true)

MainAcitvity

package com.example.student.myapplication

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import android.webkit.WebSettings

class MainActivity : AppCompatActivity() {

    var mWebView: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mWebView = findViewById<WebView>(R.id.webview);
        val mWebSettings = mWebView.getSettings()
        mWebSettings.setJavaScriptEnabled(true)
        mWebSettings.setDomStorageEnabled(true)
        mWebSettings.setSupportZoom(false)
        mWebSettings.setAllowFileAccess(true)
        mWebSettings.setAllowContentAccess(true)
        mWebView!!.webViewClient = object : WebViewClient(){
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean{
                view?.loadUrl(url)
                return true
            }
        }
        mWebView!!.loadUrl("https://qiwi.io/")
    }
}

I am getting error in the line

val mWebSettings = mWebView.getSettings()

Body:
try following...

webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW)

Kotlin

webView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW


问:
How to set a timeout for a popup?
I created a popup that appears when I click a button, but to make it disappear I have to click again.
Is there a way to set a timer and make it disappear?

This is the code:

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.popuptext {
  display: none;
}
.popuptext.show {
  display: block;
}</code>```

Click me to toggle the popup!
  A Simple Popup!

```

答:
This should work</p>

```<code>function myFunction() {
  var popup = document.getElementById("myPopup");
        document.getElementById("myPopup").style.display= "block"

    setTimeout(function(){
    document.getElementById("myPopup").style.display= "none"
   }, 3000);
}
</code>```

Title: How to set a timeout for a popup?

Body:
I created a popup that appears when I click a button, but to make it disappear I have to click again.
Is there a way to set a timer and make it disappear?

This is the code:

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}

.popuptext {
  display: none;
}
.popuptext.show {
  display: block;
}

Click me to toggle the popup!
  A Simple Popup!

Body:
This should work

function myFunction() {
  var popup = document.getElementById("myPopup");
        document.getElementById("myPopup").style.display= "block"

    setTimeout(function(){
    document.getElementById("myPopup").style.display= "none"
   }, 3000);
}


答:
You have to write a custom initializer which maps the dictionary key-value pairs to an array of the custom struct.

It's not necessary to adopt Codable in CurrencyRate because the instances are created manually

```<code>let jsonString = """
{
"success": true,
"timestamp": 1558883585,
"base": "EUR",
"date": "2019-05-26",
"rates": {
"AED": 4.116371,"AFN": 90.160103,"ALL": 122.341655,"AMD": 536.359254,"ANG": 2.097299,"AOA": 368.543773,"ARS": 50.418429,"AUD": 1.618263,"AWG": 2.012124,"AZN": 1.910752,"BAM": 1.955812,"BBD": 2.227793,"BDT": 94.245988,"BGN": 1.956097,"BHD": 0.421705,"BIF": 2051.459244,"BMD": 1.120649,"BND": 1.539664,"BOB": 7.729394,"BRL": 4.508038,"BSD": 1.118587,"BTC": 0.00014,"BTN": 77.755286,"BWP": 12.040813,"BYN": 2.323273,"BYR": 21964.71167,"BZD": 2.254689
}
}
"""

struct ExchangeData : Codable {

    let timestamp : Date
    let base : String
    let date : String

    let rates : [CurrencyRate]

    private enum CodingKeys: String, CodingKey { case timestamp, base, date, rates}

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        timestamp = try container.decode(Date.self, forKey: .timestamp)
        base = try container.decode(String.self, forKey: .base)
        date = try container.decode(String.self, forKey: .date)
        let rateData = try container.decode([String:Double].self, forKey: .rates)
        rates = rateData.map(CurrencyRate.init)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(timestamp, forKey: .timestamp)
        try container.encode(base, forKey: .base)
        try container.encode(date, forKey: .date)
        var rateData = [String:Double]()
        rates.forEach{ rateData[$0.name] = $0.rate }
        try container.encode(rateData, forKey: .rates)
    }
}

struct CurrencyRate {
    let name : String
    let rate : Double
}

let data = Data(jsonString.utf8)

do {
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .secondsSince1970
    let result = try decoder.decode(ExchangeData.self, from: data)
    print(result)
} catch {
    print(error)
}
</code>```

Title: How do I use Codable to decode json response which has changing keys?

Body:
You have to write a custom initializer which maps the dictionary key-value pairs to an array of the custom struct.

It's not necessary to adopt Codable in CurrencyRate because the instances are created manually

let jsonString = """
{
"success": true,
"timestamp": 1558883585,
"base": "EUR",
"date": "2019-05-26",
"rates": {
"AED": 4.116371,"AFN": 90.160103,"ALL": 122.341655,"AMD": 536.359254,"ANG": 2.097299,"AOA": 368.543773,"ARS": 50.418429,"AUD": 1.618263,"AWG": 2.012124,"AZN": 1.910752,"BAM": 1.955812,"BBD": 2.227793,"BDT": 94.245988,"BGN": 1.956097,"BHD": 0.421705,"BIF": 2051.459244,"BMD": 1.120649,"BND": 1.539664,"BOB": 7.729394,"BRL": 4.508038,"BSD": 1.118587,"BTC": 0.00014,"BTN": 77.755286,"BWP": 12.040813,"BYN": 2.323273,"BYR": 21964.71167,"BZD": 2.254689
}
}
"""

struct ExchangeData : Codable {

    let timestamp : Date
    let base : String
    let date : String

    let rates : [CurrencyRate]

    private enum CodingKeys: String, CodingKey { case timestamp, base, date, rates}

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        timestamp = try container.decode(Date.self, forKey: .timestamp)
        base = try container.decode(String.self, forKey: .base)
        date = try container.decode(String.self, forKey: .date)
        let rateData = try container.decode([String:Double].self, forKey: .rates)
        rates = rateData.map(CurrencyRate.init)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(timestamp, forKey: .timestamp)
        try container.encode(base, forKey: .base)
        try container.encode(date, forKey: .date)
        var rateData = [String:Double]()
        rates.forEach{ rateData[$0.name] = $0.rate }
        try container.encode(rateData, forKey: .rates)
    }
}

struct CurrencyRate {
    let name : String
    let rate : Double
}

let data = Data(jsonString.utf8)

do {
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .secondsSince1970
    let result = try decoder.decode(ExchangeData.self, from: data)
    print(result)
} catch {
    print(error)
}


问:
How to check if a List<List<int>> contains a List<int>
I have a List<List<int>> in which I would like to insert a new List<int>. I would like to check before adding the new List<int> if it already exists in the List<List<int>>.

For e.g.

```<code>List<List<int>> MasterList = new List<List<int>>();
List<int> childList = new List<int>();
</code>```

I have already tried

```<code>MaterList.Contains, MasterList.Any
</code>```

but nothing is helping

e.g.

```<code>MasterList(1)=1,2,3
MasterList(2)=4,5
</code>```

but when I see 1,2,3 or 4,5 is coming again then do not want to enter it as they are already there somewhere in MasterList

答:
This way:</p>

```<code>List<List<int>> listOfIntLists = new List<List<int>>() {
    new List<int>(){ 1,2 },
    new List<int>(){ 3,4 },
    new List<int>(){ 5,6 }
};

List<int> integers = new List<int>() { 1, 2 };

if(listOfIntLists.Any(x => x.All(y => integers.Any(z => z == y))) == false)
{
    listOfIntLists.Add(integers);
}
</code>```

Body:
I have a List<List<int>> in which I would like to insert a new List<int>. I would like to check before adding the new List<int> if it already exists in the List<List<int>>.

For e.g.

List<List<int>> MasterList = new List<List<int>>();
List<int> childList = new List<int>();

I have already tried

MaterList.Contains, MasterList.Any

but nothing is helping

e.g.

MasterList(1)=1,2,3
MasterList(2)=4,5

but when I see 1,2,3 or 4,5 is coming again then do not want to enter it as they are already there somewhere in MasterList

Body:
This way:

List<List<int>> listOfIntLists = new List<List<int>>() {
    new List<int>(){ 1,2 },
    new List<int>(){ 3,4 },
    new List<int>(){ 5,6 }
};

List<int> integers = new List<int>() { 1, 2 };

if(listOfIntLists.Any(x => x.All(y => integers.Any(z => z == y))) == false)
{
    listOfIntLists.Add(integers);
}


问:
How to use replace() function to change string items in global list?
I`ve tried to use replace function inside of while loop. My main aim is change specific index item with different string in a global list name is tryList in the code block.

when I checktryList[counter][3].replace(tryList[counter][3],newItem) output by using print() function;

I am able to see expected string value is given but at the end when I control global list, nothing is changed.

tryList=[["asd","poi","ujm","ytr"],["qaz","plm","rfv","wxs"],["edc","wer","cvc","yhn"]] #the list has 3 different list inside
newItem="ana" #this is the string which I want to replace with tryList`s each 3rd items of lists
loop=len(tryList)
counter=0
while counter<loop:
    tryList[counter][3].replace(tryList[counter][3],newItem)
    counter=counter+1
```

Could you please help me what am I doing wrong?

答:
Try this to change the 3rd element of each list to "ana":</p>

```<code>tryList=[["asd","poi","ujm","ytr"],["qaz","plm","rfv","wxs"],["edc","wer","cvc","yhn"]] #the list has 3 different list inside
newItem="ana" #this is the string which I want to replace with tryList`s each 3rd items of lists
loop=len(tryList)
counter=0
while counter<loop:
    tryList[counter][2] = tryList[counter][2].replace(tryList[counter][2],newItem)
    counter=counter+1
</code>```

Body:
I`ve tried to use replace function inside of while loop. My main aim is change specific index item with different string in a global list name is tryList in the code block.

when I checktryList[counter][3].replace(tryList[counter][3],newItem) output by using print() function;

I am able to see expected string value is given but at the end when I control global list, nothing is changed.

tryList=[["asd","poi","ujm","ytr"],["qaz","plm","rfv","wxs"],["edc","wer","cvc","yhn"]] #the list has 3 different list inside
newItem="ana" #this is the string which I want to replace with tryList`s each 3rd items of lists
loop=len(tryList)
counter=0
while counter<loop:
    tryList[counter][3].replace(tryList[counter][3],newItem)
    counter=counter+1

Could you please help me what am I doing wrong?

Body:
Try this to change the 3rd element of each list to "ana":

tryList=[["asd","poi","ujm","ytr"],["qaz","plm","rfv","wxs"],["edc","wer","cvc","yhn"]] #the list has 3 different list inside
newItem="ana" #this is the string which I want to replace with tryList`s each 3rd items of lists
loop=len(tryList)
counter=0
while counter<loop:
    tryList[counter][2] = tryList[counter][2].replace(tryList[counter][2],newItem)
    counter=counter+1


问:
NHibernate / ActiveRecord: How to set foreign key without getting entire object?
Let's say I've got the following ActiveRecord class:

```<code>[ActiveRecord]
public class Account
{
    ...

    [BelongsTo("CustomerId")]
    public Customer Customer { get; set; }
}
</code>```

Currently, to set the value of the CustomerId field I have to get the entire Customer object from the database and assign it to the Account:

```<code>Customer customer = Customer.FindById(1);
account.Customer = customer;
</code>```

This isn't very efficient. I'd rather set the value of CustomerId field directly without round-tripping the database, e.g.

```<code>account.CustomerId = 1;
</code>```

What's the correct way to do this?

答: I agree with Neil, but if you really want this, you can do it with IQuery.ExecuteUpdate()</p>

ContentLicense: CC BY-SA 2.5

Body:
Let's say I've got the following ActiveRecord class:

[ActiveRecord]
public class Account
{
    ...

    [BelongsTo("CustomerId")]
    public Customer Customer { get; set; }
}

Currently, to set the value of the CustomerId field I have to get the entire Customer object from the database and assign it to the Account:

Customer customer = Customer.FindById(1);
account.Customer = customer;

This isn't very efficient. I'd rather set the value of CustomerId field directly without round-tripping the database, e.g.

account.CustomerId = 1;

What's the correct way to do this?

OwnerDisplayName: mausch


问:
django sort object_list by through field
Say I have the good old person/group/membership relationship

```<code>class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)
</code>```

and i want a generic view that displays a list of persons belonging to a group (specified in the URL) sorted by the date_joined field of the Membership class. I figured I could just do a view like this

```<code>def group_list(request, pagina):
    return list_detail.object_list(
        request,
        queryset = Person.objects.filter(group__name = slug),
        template_object_name = 'person',
        extra_context = { 'membership' : Membership.objects.all() },

        )
</code>```

And then just access the date_joined in the template via  membership__date_joined but no luck

答:
One option would be to filter directly on the intermediary model:

```<code>members = [member.person for member in Membership.objects.filter(group__name=slug).order_by('-date_joined')]
</code>```

Or just members = Membership.objects.filter(group__name=slug).order_by('-date_joined')

Then you iterate over this list in your template like this:

```<code>{% for member in members %}
    {{ member.person.name }} : {{ member.date_joined }}
{% endfor %}
</code>```

Body:
Say I have the good old person/group/membership relationship

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

and i want a generic view that displays a list of persons belonging to a group (specified in the URL) sorted by the date_joined field of the Membership class. I figured I could just do a view like this

def group_list(request, pagina):
    return list_detail.object_list(
        request,
        queryset = Person.objects.filter(group__name = slug),
        template_object_name = 'person',
        extra_context = { 'membership' : Membership.objects.all() },

        )

And then just access the date_joined in the template via  membership__date_joined but no luck

Body:
One option would be to filter directly on the intermediary model:

members = [member.person for member in Membership.objects.filter(group__name=slug).order_by('-date_joined')]

Or just members = Membership.objects.filter(group__name=slug).order_by('-date_joined')

Then you iterate over this list in your template like this:

{% for member in members %}
    {{ member.person.name }} : {{ member.date_joined }}
{% endfor %}


问:
DisplayMember ComboBox For Which Contains List<Object> as item source
I have Comobox likes this

```<code> <dxe:ComboBoxEdit AutoComplete="True" IsTextEditable="False" ImmediatePopup="True" IncrementalFiltering="True" ItemsSource="{Binding Example}" />
</code>```

In Vm

```<code> public List<object> Example
            {
                get { return example; }
                set { example = value; OnPropertyChanged(new PropertyChangedEventArgs("Example")); }
            }
   public List<ArticlesStock> ArticlesStockList
        {
            get { return articlesStockList; }
            set
            {
                articlesStockList = value;
                OnPropertyChanged(new PropertyChangedEventArgs("ArticlesStockList"));
            }
        }

  Example.Add(ArticlesStockList);
</code>```

In ArticlesStock class, I have Prop Name Producer a string

How can I set this as my path in ComboBox?
normally we can just set this with props. but here I have a list .and inside I have one more list. in this list the first item value must be set.
C# Conversion how can I set this as Display member

```<code>((List<ArticlesStock>)Example[0])[0].WarehouseDeliveryNoteItem.Producer;
</code>```

答:
I would do the following: define a DataTemplate for your combobox's items and use a converter to retrieve the property you need.

DataTemplate definition:

<ComboBox ItemsSource="{Binding Example}">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="{x:Type List}">

            <TextBlock Text="{Binding Converter={StaticResource MyConv}}"></TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
```

<p>And the converter used to access the Producer property:</p>

<pre class="lang-cs prettyprint-override"><code>public class MyConv : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // here value will be an item of Example list, so a List<ArticlesStock>
        var val = value as List<ArticlesStock>;
        return val[0].Producer;
    }
}
</code>```

Note that I simplified your model structure for brevity.

Body:
I have Comobox likes this

 <dxe:ComboBoxEdit AutoComplete="True" IsTextEditable="False" ImmediatePopup="True" IncrementalFiltering="True" ItemsSource="{Binding Example}" />

In Vm

 public List<object> Example
            {
                get { return example; }
                set { example = value; OnPropertyChanged(new PropertyChangedEventArgs("Example")); }
            }
   public List<ArticlesStock> ArticlesStockList
        {
            get { return articlesStockList; }
            set
            {
                articlesStockList = value;
                OnPropertyChanged(new PropertyChangedEventArgs("ArticlesStockList"));
            }
        }

  Example.Add(ArticlesStockList);

In ArticlesStock class, I have Prop Name Producer a string

How can I set this as my path in ComboBox?
normally we can just set this with props. but here I have a list .and inside I have one more list. in this list the first item value must be set.
C# Conversion how can I set this as Display member

((List<ArticlesStock>)Example[0])[0].WarehouseDeliveryNoteItem.Producer;

Body:
I would do the following: define a DataTemplate for your combobox's items and use a converter to retrieve the property you need.

DataTemplate definition:

<ComboBox ItemsSource="{Binding Example}">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="{x:Type List}">
            <!--no Path is specified, which is equivalent to Path="."-->
            <TextBlock Text="{Binding Converter={StaticResource MyConv}}"></TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

And the converter used to access the Producer property:

public class MyConv : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // here value will be an item of Example list, so a List<ArticlesStock>
        var val = value as List<ArticlesStock>;
        return val[0].Producer;
    }
}

Note that I simplified your model structure for brevity.


问:
Traefik Kubernetes: Expose non Kubernetes service
I'm using Kubernetes with Traefik as Ingress Controller. I've some web services within my network that can't be containerized yet. Therefore I'm looking for a way to expose my non-Kubernetes web services through the Traefik Ingress. I've no more public IP's, so splitting both environments is not an option.

I've made an endpoint + service to solve this issue, but when I try to connect I get an SSL Protocol Error. Am I doing something wrong or does someone have another solution?

These are my (test)endpoints and service yaml:

```<code>kind: Endpoints
apiVersion: v1
metadata:
  name: my-service
subsets:
  - addresses:
      - ip: 10.4.0.6
    ports:
      - port: 443
---
kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  ports:
  - protocol: TCP
    port: 443
    name: https
    targetPort: 443
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
    kubernetes.io/ingress.class: traefik
spec:
  rules:
  - host: host.com
    http:
      paths:
      - path: /*
        backend:
          serviceName: my-service
          servicePort: 443
</code>```

答:
You could try this: Creating a K8s service of type ExternalName that binds to your external web service and add an Ingress as you would to with a "native" K8s service.

ExternalName Service --> https://kubernetes.io/docs/concepts/services-networking/service/#externalname

Exp.

```<code>apiVersion: v1
kind: Service
metadata:
  name: my-service
  namespace: prod
spec:
  type: ExternalName
  externalName: my.database.example.com
</code>```

Body:
I'm using Kubernetes with Traefik as Ingress Controller. I've some web services within my network that can't be containerized yet. Therefore I'm looking for a way to expose my non-Kubernetes web services through the Traefik Ingress. I've no more public IP's, so splitting both environments is not an option.

I've made an endpoint + service to solve this issue, but when I try to connect I get an SSL Protocol Error. Am I doing something wrong or does someone have another solution?

These are my (test)endpoints and service yaml:

kind: Endpoints
apiVersion: v1
metadata:
  name: my-service
subsets:
  - addresses:
      - ip: 10.4.0.6
    ports:
      - port: 443
---
kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  ports:
  - protocol: TCP
    port: 443
    name: https
    targetPort: 443
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
    kubernetes.io/ingress.class: traefik
spec:
  rules:
  - host: host.com
    http:
      paths:
      - path: /*
        backend:
          serviceName: my-service
          servicePort: 443

Body:
You could try this: Creating a K8s service of type ExternalName that binds to your external web service and add an Ingress as you would to with a "native" K8s service.

ExternalName Service --> https://kubernetes.io/docs/concepts/services-networking/service/#externalname

Exp.

apiVersion: v1
kind: Service
metadata:
  name: my-service
  namespace: prod
spec:
  type: ExternalName
  externalName: my.database.example.com


问:
Microsoft Teams Authentication : Unable to retrieve token in teams bot ( V4 SDK)
I have a Microsoft Teams bot and I am trying to authenticate the user using AAD (v2 endpoint). The bot uses V4 SDK and OauthPrompt.I am able to log in but unable to get the token.

I am using OAuth Card. The card is being rendered inside Teams. When the sign in button is clicked it goes to the Microsoft login page. After the user logins, the bot stops responding and hence I have no way to get the token.

The samples I am trying out are :
https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/18.bot-authentication
and
https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/24.bot-authentication-msgraph.

Both the samples are working inside the emulator.

Here is the code fragment:

```<code>               AddDialog(new OAuthPrompt(
            nameof(OAuthPrompt),
            new OAuthPromptSettings
            {
                ConnectionName = ConnectionName,
                Text = "Please Sign In",
                Title = "Sign In",
                Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
            }));

         AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

        AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
        {
            PromptStepAsync,
            LoginStepAsync,
            DisplayTokenPhase1Async,
            DisplayTokenPhase2Async,
        }));
</code>```

```<code>
 private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
           return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
        }

</code>```

It never reaches the code:

```<code>        private async Task<DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        // Get the token from the previous step. Note that we could also have gotten the
        // token directly from the prompt itself. There is an example of this in the next method.
        var tokenResponse = (TokenResponse)stepContext.Result;
        if (tokenResponse != null)
        {
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("You are now logged in."), cancellationToken);
            return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to view your token?") }, cancellationToken);
        }

        await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);
        return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
    }
</code>```

I expected that the token would be received in the code once the user signs in, but the bot just stops responding.

答:
It seems like this is a bug in the Bot framework, but there is already a pull request to fix this issue. You can find the pull request here.

Edit: They edited both authentication samples to fix this problem right now as you can see here.

Body:
I have a Microsoft Teams bot and I am trying to authenticate the user using AAD (v2 endpoint). The bot uses V4 SDK and OauthPrompt.I am able to log in but unable to get the token.

I am using OAuth Card. The card is being rendered inside Teams. When the sign in button is clicked it goes to the Microsoft login page. After the user logins, the bot stops responding and hence I have no way to get the token.

The samples I am trying out are :
https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/18.bot-authentication
and
https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/24.bot-authentication-msgraph.

Both the samples are working inside the emulator.

Here is the code fragment:

               AddDialog(new OAuthPrompt(
            nameof(OAuthPrompt),
            new OAuthPromptSettings
            {
                ConnectionName = ConnectionName,
                Text = "Please Sign In",
                Title = "Sign In",
                Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
            }));

         AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

        AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
        {
            PromptStepAsync,
            LoginStepAsync,
            DisplayTokenPhase1Async,
            DisplayTokenPhase2Async,
        }));

 private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
           return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
        }

It never reaches the code:

        private async Task<DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        // Get the token from the previous step. Note that we could also have gotten the
        // token directly from the prompt itself. There is an example of this in the next method.
        var tokenResponse = (TokenResponse)stepContext.Result;
        if (tokenResponse != null)
        {
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("You are now logged in."), cancellationToken);
            return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to view your token?") }, cancellationToken);
        }

        await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);
        return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
    }

I expected that the token would be received in the code once the user signs in, but the bot just stops responding.


问:
How to retrieve data inside a txt file stored in Firebase storage in react?
I have txt files stored inside Firebase storage. and I am able to store the download URL of each of these txt files in my firestore database. but I am not able to use the data inside the txt files stored inside firebase storage.

Problem **: I want to directly **get data from the txt file stored in the storage and display it in my reactjs web application page.

As of now, I am not able to  download the txt file by putting the url in an anchor tag and I dont know how to approach this problem as i want to download the file.

And also I am not able to get data directly form the txt file stored in storage so that I can display it in the web page.
.
I have already looked at the documentation but the demo there only shows how to display an image from storage by assigning download url to src attribute of img tag and not other file types like txt.

I tried to put download URL inside an anchor tag, but that wouldn't download the file.
and to retrieve data inside the txt file stored in storage I Couldn't find a good approach

Expected result: I want to get the data inside txt file stored in storage to display in my web page in reactjs.

Output result: not able to access the data inside the txt file in storage for viewing in the webpage.

Thank you for your time

答:
As mentioned above - you have 2 questions, but I'll try to answer them both.

Without code it is hard to see what you are doing, but you are saying that you have the "Download url". Are you sure? You have 2 "urls" with storage. One is the storage location starting with gs://... and the other is the download URL - which you can generate from the "storage location".

If you really have a download url -> putting it in anchor tag should enable someone to download this file. The browser will open the link and depending on the meta information it will initiate a download of the file or display it inline.

If that doesn't happen, you might be running in a cors issue. ( again no idea how you are trying to access the file. You might need to specify the urls for cors. More info here: https://cloud.google.com/storage/docs/cross-origin)

About displaying the content of the file. You need to download the file in your application. Once downloaded you can display the content of it. You can do it as suggested over here:
How to read a text file from server using JavaScript?


问:
Ruby two strings in an IF condition
In my rails project I've if statement with string conditions which doesn't work.

```<code>  if shop.details['company_role'] == 'CEO' || 'founder'
        'Other'
      else
        shop.details['customer_kind']
      end
  end
</code>```

When I've case with company_role = founder it didn't return me 'Other' but customer_kind

答:
```<code>%w(CEO founder).include?(shop.details['company_role']) ? 'Other' : shop.details['customer_kind']
</code>```

Title: Ruby two strings in an IF condition

Body:
In my rails project I've if statement with string conditions which doesn't work.

  if shop.details['company_role'] == 'CEO' || 'founder'
        'Other'
      else
        shop.details['customer_kind']
      end
  end

When I've case with company_role = founder it didn't return me 'Other' but customer_kind


问:
Sorting a slice based on the order of the elements in another slice
I am attempting to order a slice based on the order of the elements within another slice. My sort function works when I only have one of each type within my slice I want to order however when I start adding more elements the ordering breaks.

I have created an example within the Golang playground.

https://play.golang.org/p/e9sHIeV2qSf

I want to order my Variant slice by the Code field and have it the same as order as the codes appear in the Language struct.

Below is the sort function I am using:

```<code>sort.Slice(variants, func(i, j int) bool {
    for k, language := range languages {
        if language.Code == variants[i].Code {
            return i >= k
        }
    }

    return false
})
</code>```

The current order it's returning is:

Sorted slice: [{Code:en-GB} {Code:en-US} {Code:en-GB} {Code:es-ES}
  {Code:en-GB} {Code:en-GB} {Code:en-GB} {Code:en-GB} {Code:es-ES}]

When the order within my Language struct is:

"en-GB", "en-US", "fr-FR", "es-ES"

答:
I think to do this, you need to build a ranking of your languages:

```<code>var langMap map[string]int
for i, lang := range languages {
    langMap[lang.Code] = i
}
</code>```

With this, it becomes trivial to just look up the ranking of each item in variants, and return the appropriate value:

```<code>sort.Slice(variants, func(i, j int) bool {
    iRank, jRank := langMap[variants[i].Code], langMap[variants[j].Code]
    return iRank < jRank
})
</code>```

If there's a chance you may have inputs that are not in the pre-sorted list, you can sort them last:

```<code>sort.Slice(variants, func(i, j int) bool {
    iRank, iExists := langMap[variants[i].Code]
    jRank, jExists := langMap[variants[j].Code]
    switch (
    case iExists && jExists:
        // Both exist in the pre-ordered list, so sort by rank
        return iRank < jRank
    case !iExists && !jExists:
        // Neither exists in the pre-ordered list, sort alphabetically
        return variants[i].Code < variants[j].Code
    case iExists:
        // Only i exists, so sort it before j
        return true
    default: // jExists
        // Only j exists, so sort it after i
        return false
    )

})
</code>```

It is logically possible to do the same by looping through your reference list each time, as you're attempting, but it's much harder to reason about, and far less efficient.

Body:
I am attempting to order a slice based on the order of the elements within another slice. My sort function works when I only have one of each type within my slice I want to order however when I start adding more elements the ordering breaks.

I have created an example within the Golang playground.

https://play.golang.org/p/e9sHIeV2qSf

I want to order my Variant slice by the Code field and have it the same as order as the codes appear in the Language struct.

Below is the sort function I am using:

sort.Slice(variants, func(i, j int) bool {
    for k, language := range languages {
        if language.Code == variants[i].Code {
            return i >= k
        }
    }

    return false
})

The current order it's returning is:

Sorted slice: [{Code:en-GB} {Code:en-US} {Code:en-GB} {Code:es-ES}
  {Code:en-GB} {Code:en-GB} {Code:en-GB} {Code:en-GB} {Code:es-ES}]

When the order within my Language struct is:

"en-GB", "en-US", "fr-FR", "es-ES"

Body:
I think to do this, you need to build a ranking of your languages:

var langMap map[string]int
for i, lang := range languages {
    langMap[lang.Code] = i
}

With this, it becomes trivial to just look up the ranking of each item in variants, and return the appropriate value:

sort.Slice(variants, func(i, j int) bool {
    iRank, jRank := langMap[variants[i].Code], langMap[variants[j].Code]
    return iRank < jRank
})

If there's a chance you may have inputs that are not in the pre-sorted list, you can sort them last:

sort.Slice(variants, func(i, j int) bool {
    iRank, iExists := langMap[variants[i].Code]
    jRank, jExists := langMap[variants[j].Code]
    switch (
    case iExists && jExists:
        // Both exist in the pre-ordered list, so sort by rank
        return iRank < jRank
    case !iExists && !jExists:
        // Neither exists in the pre-ordered list, sort alphabetically
        return variants[i].Code < variants[j].Code
    case iExists:
        // Only i exists, so sort it before j
        return true
    default: // jExists
        // Only j exists, so sort it after i
        return false
    )

})

It is logically possible to do the same by looping through your reference list each time, as you're attempting, but it's much harder to reason about, and far less efficient.


问:
How do I define a concatenation in Javascript?
I only really know Lua, and HTML. But I'm trying to expand to Javascript.

How do I add a concatenation to the end of this? The ID is always a number.

How it would be done in lua (if this helps, make my point) "http://www.roblox.com/My/PrivateMessage.aspx?RecipientID="..X

答:
```<code>var s = "Hello";
s += "World";

document.write(s); // Prints HelloWorld
</code>```


问:
No errors with Carousel, Left/Right Buttons do not function
My Bootstrap Carousel Buttons are not working. Currently the first image shows and so do the buttons, however the image does not change by itself nor does it change when I press the buttons.

This is for a web application I am making, ran using Express. I've tried changing around some snippets of code but nothing makes the slides change. There are 3 images, the other 2 are not showing because they are not active, so I do have more than 1 image.

```<code>
<!--Dependencies -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script language="JavaScript" type="text/javascript">
  $(document).ready(function(){
    $('.carouselExampleControls').carousel({
      interval: 3000
    })
  })
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="/assets/css/main.css">

<!--Carousel Code -->
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(45).jpg"
        alt="First slide">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(46).jpg"
        alt="Second slide">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(47).jpg"
        alt="Third slide">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

</code>```

I expect to have the Carousel buttons functioning once the page is rendered, however there are no errors in the console.

答:
```<code> <!DOCTYPE html>
 <html lang="en">
 <head>
 <title>Bootstrap Carousel</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

 <script language="JavaScript" type="text/javascript">
  $(document).ready(function(){
    $('.carouselExampleControls').carousel({
    interval: 3000
    })
  })
 </script>

 </head>

 <body>

 <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">

     <ol class="carousel-indicators">
         <li data-target="#carouselExampleControls" data-slide-to="0" class="active"></li>
         <li data-target="#carouselExampleControls" data-slide-to="1"></li>
         <li data-target="#carouselExampleControls" data-slide-to="2"></li>
     </ol>

     <div class="carousel-inner">
         <div class="item active">
             <img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(45).jpg" alt="First slide">
         </div>
         <div class="item">
             <img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(46).jpg" alt="Second slide">
         </div>
         <div class="item">
             <img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(47).jpg" alt="Third slide">
         </div>
     </div>

     <a class="left carousel-control" href="#carouselExampleControls" role="button" data-slide="prev">
         <span class="glyphicon glyphicon-chevron-left"></span>
         <span class="sr-only">Previous</span>
     </a>
     <a class="right carousel-control" href="#carouselExampleControls" role="button" data-slide="next">
         <span class="glyphicon glyphicon-chevron-right"></span>
         <span class="sr-only">Next</span>
     </a>

 </div>

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

Body:
My Bootstrap Carousel Buttons are not working. Currently the first image shows and so do the buttons, however the image does not change by itself nor does it change when I press the buttons.

This is for a web application I am making, ran using Express. I've tried changing around some snippets of code but nothing makes the slides change. There are 3 images, the other 2 are not showing because they are not active, so I do have more than 1 image.

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

    Previous

    Next

I expect to have the Carousel buttons functioning once the page is rendered, however there are no errors in the console.


问:
Why module 'ui.bootstrap' is not available?
I am trying this simple tutorial to try UI Bootstrap:
https://scotch.io/tutorials/how-to-correctly-use-bootstrapjs-and-angularjs-together

But I am running into two problems.

SyntaxError: expected expression, got '<' at  ui-bootstrap-1.3.3.js:5:0

This is the first problem. I have not edited anything in the file, yet it says unexpected token for the very first line <!DOCTYPE html>

And the other one is as below:

Error: [$injector:modulerr] Failed to instantiate module app due to:
  [$injector:modulerr] Failed to instantiate module ui.bootstrap due to:
  [$injector:nomod] Module 'ui.bootstrap' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I saw answers to all the related questions, some of them suggesting to include the other dependencies while other suggesting to make sure of the order of the dependencies. Tried everything but no joy.

Below is my html and js code. Please have a look

HTML

```<code><html>
<head>
<style type="text/css">
            @import "css/bootstrap.css";
            @import "css/style.css";
        </style>
        <script src="js/angular.js"></script>
        <script src="js/angular-animate.js"></script>
        <script src="js/angular-touch.js"></script>
        <script src="js/ui-bootstrap-1.3.3.js"></script>
        <script src="js/app.js"></script>
</head>
<body>
<div class="container" ng-app="app" ng-controller="mainController">

  <div class="text-center">
    <p>Example of Angular and the normal Bootstrap JavaScript components</p>
    <p class="text-success">This will work</p>
  </div>

  <h2>Buttons</h2>
  <div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary" ng-model="bigData.breakfast" btn-checkbox>
      Breakfast
    </label>
    <label class="btn btn-primary" ng-model="bigData.lunch" btn-checkbox>
      Lunch
    </label>
    <label class="btn btn-primary" ng-model="bigData.dinner" btn-checkbox>
      Dinner
    </label>
  </div>

  ```{{ bigData | json }}```

  <h2>Collapse</h2>

    Toggle Panel

  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">

          Collapsible Group Item #1

      </h4>
    </div>
    <div collapse="isCollapsed">
      <div class="panel-body">Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>

  ```{{ isCollapsed }}```

</div>
</body>
</html>
</code>```

JS

```<code>angular.module('app', ['ngAnimate', 'ngTouch', 'ui.bootstrap'])

.controller('mainController', function($scope) {

  // BUTTONS ======================

  // define some random object
  $scope.bigData = {};

  $scope.bigData.breakfast = false;
  $scope.bigData.lunch = false;
  $scope.bigData.dinner = false;

  // COLLAPSE =====================
  $scope.isCollapsed = false;

});
</code>```

Not sure what's going wrong.

Edit
Version details area as follows

Bootstrap v3.3.6

angular

angular-animate

angular-touch
all are having version AngularJS v1.5.3

答:
In my case, in a legacy application (AngularJS 1.3), it was because I put angular-ui-bootstrap to bower.js rather than package.js.

After I put it to package.js, ran npm install, copied to some source directory, and added to imports, it worked.

```<code>import '../js/dependencies/ui-bootstrap-tpls-0.14.3.min'
</code>```

It is probably not the right way to do it, though.

I think it should be imported from bower_modules.

```<code>import '../bower_components/angular-ui-bootstrap/???';
</code>```

But, the Bower hosting does not work anymore and an attempt to install through bower install fails with HTTP 502.

Also, what's weird, it worked unless I registered a provider:

```<code>.config(['$tooltipProvider', function ($tooltipProvider) { ...
</code>```

This way, Angular started complaining that '$tooltipProvider' is not known.

Hope this helps, although I do not know much about the old AngularJS, so take it as potentially mediocre solution.

Body:
I am trying this simple tutorial to try UI Bootstrap:
https://scotch.io/tutorials/how-to-correctly-use-bootstrapjs-and-angularjs-together

But I am running into two problems.

SyntaxError: expected expression, got '<' at  ui-bootstrap-1.3.3.js:5:0

This is the first problem. I have not edited anything in the file, yet it says unexpected token for the very first line <!DOCTYPE html>

And the other one is as below:

Error: [$injector:modulerr] Failed to instantiate module app due to:
  [$injector:modulerr] Failed to instantiate module ui.bootstrap due to:
  [$injector:nomod] Module 'ui.bootstrap' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I saw answers to all the related questions, some of them suggesting to include the other dependencies while other suggesting to make sure of the order of the dependencies. Tried everything but no joy.

Below is my html and js code. Please have a look

HTML

Example of Angular and the normal Bootstrap JavaScript components

This will work

Buttons

      Breakfast

      Lunch

      Dinner

{{ bigData | json }}

Collapse

    Toggle Panel

          Collapsible Group Item #1

Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

{{ isCollapsed }}

JS

angular.module('app', ['ngAnimate', 'ngTouch', 'ui.bootstrap'])

.controller('mainController', function($scope) {

  // BUTTONS ======================

  // define some random object
  $scope.bigData = {};

  $scope.bigData.breakfast = false;
  $scope.bigData.lunch = false;
  $scope.bigData.dinner = false;

  // COLLAPSE =====================
  $scope.isCollapsed = false;

});

Not sure what's going wrong.

Edit
Version details area as follows

Bootstrap v3.3.6

angular

angular-animate

angular-touch
all are having version AngularJS v1.5.3

Body:
In my case, in a legacy application (AngularJS 1.3), it was because I put angular-ui-bootstrap to bower.js rather than package.js.

After I put it to package.js, ran npm install, copied to some source directory, and added to imports, it worked.

import '../js/dependencies/ui-bootstrap-tpls-0.14.3.min'

It is probably not the right way to do it, though.

I think it should be imported from bower_modules.

import '../bower_components/angular-ui-bootstrap/???';

But, the Bower hosting does not work anymore and an attempt to install through bower install fails with HTTP 502.

Also, what's weird, it worked unless I registered a provider:

.config(['$tooltipProvider', function ($tooltipProvider) { ...

This way, Angular started complaining that '$tooltipProvider' is not known.

Hope this helps, although I do not know much about the old AngularJS, so take it as potentially mediocre solution.


问:
How to visit a link inside an email using capybara
I am new to cucumber with capybara. I got an application to test whose flow is:'after submitting a form, an email will be sent to the user which contains the link to another app. In order to access the app we have to open the mail and click the link, which will redirect to the app.'. I don't have access to the mail Id. Is there any way to extract that link and continue with the flow?
Please, give some possible way to do it.

Regards,
Abhisek Das

答:
If you're using or willing to use the capybara-email gem, there's now a simpler way of doing this. Let's say you've generated an email to recipient@email.com, which contains the link 'fancy link'.

Then you can just do this in your test suite:

```<code>open_email('recipient@email.com') # Allows the current_email method
current_email.click_link 'fancy link'
</code>```

Body:
If you're using or willing to use the capybara-email gem, there's now a simpler way of doing this. Let's say you've generated an email to recipient@email.com, which contains the link 'fancy link'.

Then you can just do this in your test suite:

open_email('recipient@email.com') # Allows the current_email method
current_email.click_link 'fancy link'


问:
Receive input from command line with Spring Boot
So I have a really small Spring Boot command line application (There is no embedded tomcat server or anything that would make it a web application) with a single class where I try to use the Scanner class from java.util to read input from the user. This does not work at all. I thought it would be pretty basic stuff in Spring Boot, but all of my searches both on S.O or tutorials have yielded no results. What's the best way to go about it? or is Spring Boot just not for what I want to do?

Here's my class:

```<code>package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Scanner;

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory
        .getLogger(MyApplication.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("EXECUTING : command line runner");

        Scanner in = new Scanner(System.in);

        System.out.println("What is your name?");
        String name = in.next();
        System.out.println("Hello " + name + " welcome to spring boot" );
    }
}
</code>```

The exception being thrown is:

```<code>2019-05-29 11:31:29.116  INFO 4321 --- [           main] test.MyApplication  : EXECUTING : command line runner
2019-05-29 11:31:29.119  INFO 4321 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-29 11:31:29.124 ERROR 4321 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:816) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:324) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at com.jaletechs.png.PrimeNumberGeneratorApplication.main(MyApplication.java:19) [main/:na]
Caused by: java.util.NoSuchElementException: null
        at java.util.Scanner.throwFor(Scanner.java:862) ~[na:1.8.0_201]
        at java.util.Scanner.next(Scanner.java:1371) ~[na:1.8.0_201]
        at test.MyApplication.run(MyApplication.java:27) [main/:na]
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        ... 3 common frames omitted
</code>```

答:
or is Spring Boot just not for what I want to do?

You are right.

Spring Boot application is a server one (like any other .war) and runs in an embedded Tomcat. What kind of Scanner here can be?

If you want to interact with it - you should create REST controller and send/receive data through endpoints.

Body:
So I have a really small Spring Boot command line application (There is no embedded tomcat server or anything that would make it a web application) with a single class where I try to use the Scanner class from java.util to read input from the user. This does not work at all. I thought it would be pretty basic stuff in Spring Boot, but all of my searches both on S.O or tutorials have yielded no results. What's the best way to go about it? or is Spring Boot just not for what I want to do?

Here's my class:

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Scanner;

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory
        .getLogger(MyApplication.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("EXECUTING : command line runner");

        Scanner in = new Scanner(System.in);

        System.out.println("What is your name?");
        String name = in.next();
        System.out.println("Hello " + name + " welcome to spring boot" );
    }
}

The exception being thrown is:

2019-05-29 11:31:29.116  INFO 4321 --- [           main] test.MyApplication  : EXECUTING : command line runner
2019-05-29 11:31:29.119  INFO 4321 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-29 11:31:29.124 ERROR 4321 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:816) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:324) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at com.jaletechs.png.PrimeNumberGeneratorApplication.main(MyApplication.java:19) [main/:na]
Caused by: java.util.NoSuchElementException: null
        at java.util.Scanner.throwFor(Scanner.java:862) ~[na:1.8.0_201]
        at java.util.Scanner.next(Scanner.java:1371) ~[na:1.8.0_201]
        at test.MyApplication.run(MyApplication.java:27) [main/:na]
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        ... 3 common frames omitted