问:
knockout js image styling checkbox group with select/deselect all checkbox
I'm new to knockout js and I need help!
I have a list of books (for example) and my wish is to mark several or select/deselect all. I need to style the checkboxes with an image. When I do this everything breaking up. I`m uploading big part of my code here. Thank You for your time!

  // Main JS - Step`s Wizard
  // defines a single step in the wizard
  function Step(id, type, template) {
      var self = this;
      // step id
      self.id = id;
      // indicates wether this is a common or a specific type
      self.templateType = type;
      // the template name
      self.template = template;
      // just a helper to check whether this is a common or not
      self.common = (type == 0);
  }

  // this is our ko view model
  var createCustomer = function() {
      var self = this;

      // create a new customer object
      self.CustomerType = ko.observable();
      self.Registration = ko.observable();
      self.Tax = ko.observable();
      self.Name = ko.observable();
      self.Contact = ko.observable();
      self.Address = ko.observable();
      self.searchForMarketingListFolder = ko.observable("");

      self.navSteps = ko.observableArray([{
          "name": "Marketing Lists",
          "step": 1
      }, {
          "name": "Map Fields",
          "step": 2
      }, {
          "name": "Confirm and import",
          "step": 3
      }]);
      // a simple validation method
      self.IsValid = function() {
          return true //!!self.CustomerType();
      };
      // define the customer types (ideally get them from the server)
      self.MarketingList = ko.observableArray([
          new MarketingList("cbML1", "Summer Events Invitees"),
          new MarketingList("cbML2", "Monthly Newsletter"),
          new MarketingList("cbML3", "Interests - Dynamics Solution")
      ]);
      self.filteredMarketingList = ko.computed(function() {
          var filter = self.searchForMarketingListFolder().toLowerCase();

          if (!filter) {
              return self.MarketingList();
          } else {
              return ko.utils.arrayFilter(self.MarketingList(), function(item) {
                  return item.Name.toLowerCase().indexOf(filter) !== -1;
              });
          }
      });

      self.sendFieldsForMapping = ko.observableArray([{
          SendID: 1,
          SendFieldName: "First Name",
          CRMID: ko.observable()
      }, {
          SendID: 2,
          SendFieldName: "Last Name",
          CRMID: ko.observable()
      }, {
          SendID: 3,
          SendFieldName: "Email",
          CRMID: ko.observable()
      }]);
      self.fieldMapListDropDown = ko.observableArray([
          new fieldMapListDropDown(111111, "First Name"),
          new fieldMapListDropDown(222222, "Last Name"),
          new fieldMapListDropDown(333333, "Email")
      ]);

      // define the steps
      self.stepModels = ko.observableArray([
          new Step(1, 0, "step1Tmpl"),
          new Step(2, 1, "step2Tmpl"),
          new Step(3, 1, "step3Tmpl"),
      ]);

      // set the current step to the 1st initially
      self.currentStep = ko.observable(self.stepModels()[0]);
      // get the current step index (0 based)
      self.currentIndex = ko.computed(function() {
          return self.stepModels.indexOf(self.currentStep());
      });
      // get current step template
      self.getTemplate = function(data) {
          return self.currentStep().template;
      };
      // check whether theres another step we can goto
      self.canGoNext = ko.computed(function() {
          return self.currentIndex() < self.stepModels().length - 1;
      });
      // check whether theres another step we can go back to
      self.canGoPrevious = ko.computed(function() {
          return self.currentIndex() > 0;
      });
      self.checkCurrentStep = function(step) {
          return self.currentIndex() === step - 1;
      };
      self.showImportBtn = function() {
          return self.currentIndex() === self.stepModels().length - 1;
      };
      // go back one step
      // here we need to take the customer type into account
      self.GoBack = function() {
          var d = ko.toJS(self); // convenience

          // proceed only if we can go back
          if (self.canGoPrevious()) {
              var prev;
              if (d.CustomerType == 2) { // residential
                  // use underscore.js filter method
                  prev = _.filter(self.stepModels(), function(m) {
                      // get the common ones and skip the business ones
                      return (m.id <= self.currentIndex() + 1) && (m.templateType == 0 || m.common);
                  });
              } else {
                  prev = _.filter(self.stepModels(), function(m) {
                      // get the common ones AND business ones.
                      return (m.id <= self.currentIndex() + 1) && (m.templateType == 1 || m.common);
                  });
              }

              // filtering will give us every step we have to take in this
              // route upto where we are already
              // so the last in the list will be the current step
              // so, reverse it, get the 1st one (0th is current)
              self.currentStep(prev.reverse()[1]);
          }
      };
      self.GoNext = function() {
          // run validations:
          if (!self.IsValid()) {
              alert("Select customer type");
              return;
          }
          // same logic as in GoBack()
          // except we check for larger than current ids.
          var d = ko.toJS(self);

          if (self.canGoNext()) {
              var nxt;
              if (d.CustomerType == 2) {
                  nxt = _.find(self.stepModels(), function(m) {
                      return (m.id > self.currentIndex() + 1) && (m.templateType == 0 || m.common);
                  });
              } else {
                  nxt = _.find(self.stepModels(), function(m) {
                      return (m.id > self.currentIndex() + 1) && (m.templateType == 1 || m.common);
                  });
              }
              self.currentStep(nxt);
          }
      };
      self.SelectAll = ko.observable({
          'Selected': ko.observable(false)
      });
      //   self.SelectAll = ko.computed({
      //       read: function() {
      //           var tmpElement = document.getElementById('cbML0');
      //           var item = ko.utils.arrayFirst(self.MarketingList(), function(item) {
      //               if (tmpElement != null) {
      //                   if (item.Selected()) {
      //                       tmpElement.classList.remove('unchecked');
      //                       tmpElement.classList.add('tdCheckbox');
      //                   } else {
      //                       tmpElement.classList.remove('tdCheckbox');
      //                       tmpElement.classList.add('unchecked');
      //                   }
      //               }
      //               return !item.Selected();
      //           });
      //           return item == null;
      //       },
      //       write: function(value) {
      //           ko.utils.arrayForEach(self.MarketingList(), function(list) {
      //               list.Selected(value);
      //           });
      //       }
      //   });

      self.ImportData = function() {
          var tmpMarketingList = ko.toJS(self.MarketingList());
          var tmpSelectedFieldMaps = ko.toJS(self.sendFieldsForMapping());
          var tmpFieldMapListDropDown = ko.toJS(self.fieldMapListDropDown());

          self.confirmAndImport = new confirmAndImport(tmpMarketingList, tmpSelectedFieldMaps, tmpFieldMapListDropDown);
          console.log('self.confirmAndImport');
          console.log(self.confirmAndImport);
          console.log("******* 2 ***********");
          new ImportDataFromInterAction(self.confirmAndImport);

      };
  };

  var MarketingList = function(id, name) {
      this.id = id;
      this.Name = name;
      this.Selected = ko.observable(true);
  };
  var fieldMapListDropDown = function(id, name) {
      this.CRMID = id;
      this.CRMName = name;
      this.CRMSelected = ko.observable();
  };

  var ImportDataFromInterAction = function(data) {
      console.log(data);
  }
  var viewModel = new createCustomer();
  ko.applyBindings(viewModel, $("#IA-Main-Container")[0]);

  function confirmAndImport(MarketingList, tmpSelectedFieldMaps, tmpFieldMapListDropDown) {

      var showConfirmAndImportData = new Object;
      showConfirmAndImportData.MarketingList = [];
      showConfirmAndImportData.MapFields = [];

      Object.keys(MarketingList).map(function(objectKey, index) {
          if (MarketingList[index].Selected) {
              showConfirmAndImportData.MarketingList.push(MarketingList[index]);
          }
      });
      Object.keys(tmpSelectedFieldMaps).map(function(objectKey, index) {
          var match = ko.utils.arrayFirst(tmpFieldMapListDropDown, function(item) {
              return item.CRMID == tmpSelectedFieldMaps[index].CRMID;
          });
          showConfirmAndImportData.MapFields.push({
              'fieldName': tmpSelectedFieldMaps[index].SendFieldName,
              'connectedToCRMID': match.CRMID,
              'connectedToCRMName': match.CRMName,
          });
      });

      return showConfirmAndImportData;
  }

  function toggleClassesOnMarketingListCheckBoxes(pressedId) {

      var tmpData = viewModel.MarketingList()
      tmpData.forEach(function(objectKey, index) {
          if (pressedId != 'cbML0') {
              if (objectKey.id == pressedId) {
                  viewModel.MarketingList()[index].Selected(!objectKey.Selected());
                  toggleClassesOnMarketingListCheckBoxesInnerFunction(viewModel.MarketingList()[index].Selected(), pressedId);
              }
          } else {
              viewModel.MarketingList()[index].Selected(viewModel.SelectAll().Selected());
              toggleClassesOnMarketingListCheckBoxesInnerFunction(!viewModel.SelectAll().Selected(), viewModel.MarketingList()[index].id);
          }
      });

      if (pressedId == 'cbML0') {
          //viewModel.SelectAll.Selected() && tmpElement.classList.contains('unchecked')
          var tmp = viewModel.SelectAll();
          toggleClassesOnMarketingListCheckBoxesInnerFunction(tmp.Selected(), pressedId);
          viewModel.SelectAll().Selected(!viewModel.SelectAll().Selected());
      }
  };

  function toggleClassesOnMarketingListCheckBoxesInnerFunction(bool, pressedId) {
      var tmpElement = document.getElementById(pressedId);
      if (tmpElement != null) {
          if (bool) {
              tmpElement.classList.remove('unchecked');
              tmpElement.classList.add('tdCheckbox');
          } else {
              tmpElement.classList.remove('tdCheckbox');
              tmpElement.classList.add('unchecked');
          }
      }
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#IA-Main-Container {
  width: 800px;
  height: 500px;
  background: lightgoldenrodyellow;
  margin: auto;
  padding: 5px;
  border: 3px solid silver;
  border-style: solid;
  border-color: #d7d9db;
  color: #3c4650;
  font-family: Arial, Verdana, Sans-Serif;
}

#IA-Main-Container .searchForm#marketingListSearchForm {
  height: 23px;
  line-height: 23px;
  padding: 5px;
  border: 1px solid;
  margin-bottom: 10px;
  background-color: #d7d9db;
  border-color: #d7d9db;
  text-align: right;
}

#IA-Main-Container input[type=checkbox] {
  /*display: none;*/
}

#IA-Main-Container input[type=checkbox].unchecked+label {
  width: 14px;
  height: 14px;
  background-image: url('https://c.contentsvr.com/skins/common/images/icons/common.png');
  background-position: 0px -14px;
  background-repeat: no-repeat;
  background-color: transparent;
  cursor: pointer;
  display: inline-block;
  font-size: 14px;
  height: 14px;
  line-height: 14px;
  padding: 0;
  text-align: left;
  text-decoration: none;
  text-indent: -9999px;
  width: 14px;
}

#IA-Main-Container input[type=checkbox].tdCheckbox:checked+label {
  width: 14px;
  height: 14px;
  background-image: url('https://c.contentsvr.com/skins/common/images/icons/common.png');
  background-position: -14px -14px;
  background-repeat: no-repeat;
  background-color: transparent;
  cursor: pointer;
  display: inline-block;
  font-size: 14px;
  height: 14px;
  line-height: 14px;
  padding: 0;
  text-align: left;
  text-decoration: none;
  text-indent: -9999px;
  width: 14px;
}

#IA-Main-Container .searchForm#marketingListSearchForm input {
  border: 1px solid #7F8084;
  margin: 3px 0 0;
  padding: 1px;
}

#IA-Main-Container .searchForm#marketingListSearchForm input::-webkit-input-placeholder {
  color: #999;
  padding-left: 3px;
}

#IA-Main-Container header {
  height: 34px;
  background-color: #FFF;
  border-color: #FFF;
  color: #00aae6;
  font-size: 1.2em;
  display: block;
  clear: both;
  margin-bottom: 10px;
  padding: 5px;
}

#IA-Main-Container header .title {
  width: 80%;
  float: left;
  line-height: 34px;
  font-weight: 700;
  margin: 0 5px 0 0;
}

#IA-Main-Container tbody {
  overflow-y: auto;
  overflow-x: hidden;
}

#IA-Main-Container .nav-stepContainer {
  margin-top: 10px;
  margin-bottom: 16px;
  height: 27px;
}

#IA-Main-Container .nav-stepContainer nav ul {
  font-size: 1em;
  float: left;
  list-style: none;
  width: auto;
  display: block;
  padding: 0px;
  margin: 0px;
}

#IA-Main-Container .nav-stepContainer nav ul li {
  font-size: 1em;
  float: left;
  list-style: none;
  width: auto;
}

#IA-Main-Container .nav-stepContainer nav ul li a {
  border-bottom: 5px solid;
  border-color: #DDD;
  color: #999;
  text-decoration: none;
  padding-bottom: 4px;
}

/*#IA-Main-Container .nav-stepContainer nav ul li .selected_navigationBar {*/

.selected_navigationBar {
  border-color: #00aae6 !important;
  color: black !important;
}

#IA-Main-Container .nav-stepContainer nav ul li:not(:first-child)
/*:not(:last-of-type)*/

{
  background-image: url('https://d3dcudlcyz9qvm.cloudfront.net/skins/_common/5/images/brand.png');
  background-position: 5px -232px;
  padding-left: 15px;
}

.innerScreen {
  height: 325px;
  padding: 2px;
  border: 2px solid #9FADAC;
}

.innerScreen table tbody tr {
  border-bottom: 1px solid #9FADAC;
}

.footer {
  text-align: right
}</code>```

             Import InterAction List

            Cancel
            <button id="updateContactBtn" class="btn btn-primary" data-bind="click: GoBack, visible: currentIndex() > 0">« Previous Step</button>
            <button id="updateContactBtn" class="btn btn-primary" data-bind="click: GoNext, visible: canGoNext() ">Next Step »</button>
            <button id="updateContactBtn" class="btn btn-primary" data-bind="click: ImportData, visible: showImportBtn() ">Import</button>

    ```

答:
I haven't read through all of your code, but this might help:

To have a checkbox that can toggle a "select all" you can use a computed observable that has a read and a write function.

The read function checks whether all items are Selected and returns true if they are, and false if they're not.

The write value marks all items Selected when passed true, and deselects all items when passed false.

I.e.:

```<code>this.SelectAll = ko.computed({
  read: function() {
    return this.MarketingList().every(function(item) {
      return item.Selected();
    });
  },
  write: function(val) {
    this.MarketingList().forEach(function(item) {
      item.Selected(val);
    });
  }
}, this);
</code>```

In a working example:

function Item(name) {
  this.name = name;
  this.selected = ko.observable(false);
};

function App() {

  this.items = ko.observableArray([
    new Item(1),
    new Item(2),
    new Item(3)
  ]);

  this.allSelected = ko.computed({
    read: function() {
      return this.items().every(function(item) {
        return item.selected();
      });
    },
    write: function(val) {
      this.items().forEach(function(item) {
        item.selected(val);
      });
    }
  }, this);
}

ko.applyBindings(new App());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<label>
  <input type="checkbox" data-bind="checked: allSelected">
  <span>select all</span>
</label>

<ul data-bind="foreach: items">
  <li>
    <label>
      <input type="checkbox" data-bind="checked: selected">
      <span data-bind="text: name"></span>
    </label>
  </li>
</ul></code>```

p.s. If I were you, I'd rename my properties to start with a lowercase character so they don't get mixed up with constructor methods.

Body:
I'm new to knockout js and I need help!
I have a list of books (for example) and my wish is to mark several or select/deselect all. I need to style the checkboxes with an image. When I do this everything breaking up. I`m uploading big part of my code here. Thank You for your time!

  // Main JS - Step`s Wizard
  // defines a single step in the wizard
  function Step(id, type, template) {
      var self = this;
      // step id
      self.id = id;
      // indicates wether this is a common or a specific type
      self.templateType = type;
      // the template name
      self.template = template;
      // just a helper to check whether this is a common or not
      self.common = (type == 0);
  }

  // this is our ko view model
  var createCustomer = function() {
      var self = this;

      // create a new customer object
      self.CustomerType = ko.observable();
      self.Registration = ko.observable();
      self.Tax = ko.observable();
      self.Name = ko.observable();
      self.Contact = ko.observable();
      self.Address = ko.observable();
      self.searchForMarketingListFolder = ko.observable("");

      self.navSteps = ko.observableArray([{
          "name": "Marketing Lists",
          "step": 1
      }, {
          "name": "Map Fields",
          "step": 2
      }, {
          "name": "Confirm and import",
          "step": 3
      }]);
      // a simple validation method
      self.IsValid = function() {
          return true //!!self.CustomerType();
      };
      // define the customer types (ideally get them from the server)
      self.MarketingList = ko.observableArray([
          new MarketingList("cbML1", "Summer Events Invitees"),
          new MarketingList("cbML2", "Monthly Newsletter"),
          new MarketingList("cbML3", "Interests - Dynamics Solution")
      ]);
      self.filteredMarketingList = ko.computed(function() {
          var filter = self.searchForMarketingListFolder().toLowerCase();

          if (!filter) {
              return self.MarketingList();
          } else {
              return ko.utils.arrayFilter(self.MarketingList(), function(item) {
                  return item.Name.toLowerCase().indexOf(filter) !== -1;
              });
          }
      });

      self.sendFieldsForMapping = ko.observableArray([{
          SendID: 1,
          SendFieldName: "First Name",
          CRMID: ko.observable()
      }, {
          SendID: 2,
          SendFieldName: "Last Name",
          CRMID: ko.observable()
      }, {
          SendID: 3,
          SendFieldName: "Email",
          CRMID: ko.observable()
      }]);
      self.fieldMapListDropDown = ko.observableArray([
          new fieldMapListDropDown(111111, "First Name"),
          new fieldMapListDropDown(222222, "Last Name"),
          new fieldMapListDropDown(333333, "Email")
      ]);

      // define the steps
      self.stepModels = ko.observableArray([
          new Step(1, 0, "step1Tmpl"),
          new Step(2, 1, "step2Tmpl"),
          new Step(3, 1, "step3Tmpl"),
      ]);

      // set the current step to the 1st initially
      self.currentStep = ko.observable(self.stepModels()[0]);
      // get the current step index (0 based)
      self.currentIndex = ko.computed(function() {
          return self.stepModels.indexOf(self.currentStep());
      });
      // get current step template
      self.getTemplate = function(data) {
          return self.currentStep().template;
      };
      // check whether theres another step we can goto
      self.canGoNext = ko.computed(function() {
          return self.currentIndex() < self.stepModels().length - 1;
      });
      // check whether theres another step we can go back to
      self.canGoPrevious = ko.computed(function() {
          return self.currentIndex() > 0;
      });
      self.checkCurrentStep = function(step) {
          return self.currentIndex() === step - 1;
      };
      self.showImportBtn = function() {
          return self.currentIndex() === self.stepModels().length - 1;
      };
      // go back one step
      // here we need to take the customer type into account
      self.GoBack = function() {
          var d = ko.toJS(self); // convenience

          // proceed only if we can go back
          if (self.canGoPrevious()) {
              var prev;
              if (d.CustomerType == 2) { // residential
                  // use underscore.js filter method
                  prev = _.filter(self.stepModels(), function(m) {
                      // get the common ones and skip the business ones
                      return (m.id <= self.currentIndex() + 1) && (m.templateType == 0 || m.common);
                  });
              } else {
                  prev = _.filter(self.stepModels(), function(m) {
                      // get the common ones AND business ones.
                      return (m.id <= self.currentIndex() + 1) && (m.templateType == 1 || m.common);
                  });
              }

              // filtering will give us every step we have to take in this
              // route upto where we are already
              // so the last in the list will be the current step
              // so, reverse it, get the 1st one (0th is current)
              self.currentStep(prev.reverse()[1]);
          }
      };
      self.GoNext = function() {
          // run validations:
          if (!self.IsValid()) {
              alert("Select customer type");
              return;
          }
          // same logic as in GoBack()
          // except we check for larger than current ids.
          var d = ko.toJS(self);

          if (self.canGoNext()) {
              var nxt;
              if (d.CustomerType == 2) {
                  nxt = _.find(self.stepModels(), function(m) {
                      return (m.id > self.currentIndex() + 1) && (m.templateType == 0 || m.common);
                  });
              } else {
                  nxt = _.find(self.stepModels(), function(m) {
                      return (m.id > self.currentIndex() + 1) && (m.templateType == 1 || m.common);
                  });
              }
              self.currentStep(nxt);
          }
      };
      self.SelectAll = ko.observable({
          'Selected': ko.observable(false)
      });
      //   self.SelectAll = ko.computed({
      //       read: function() {
      //           var tmpElement = document.getElementById('cbML0');
      //           var item = ko.utils.arrayFirst(self.MarketingList(), function(item) {
      //               if (tmpElement != null) {
      //                   if (item.Selected()) {
      //                       tmpElement.classList.remove('unchecked');
      //                       tmpElement.classList.add('tdCheckbox');
      //                   } else {
      //                       tmpElement.classList.remove('tdCheckbox');
      //                       tmpElement.classList.add('unchecked');
      //                   }
      //               }
      //               return !item.Selected();
      //           });
      //           return item == null;
      //       },
      //       write: function(value) {
      //           ko.utils.arrayForEach(self.MarketingList(), function(list) {
      //               list.Selected(value);
      //           });
      //       }
      //   });

      self.ImportData = function() {
          var tmpMarketingList = ko.toJS(self.MarketingList());
          var tmpSelectedFieldMaps = ko.toJS(self.sendFieldsForMapping());
          var tmpFieldMapListDropDown = ko.toJS(self.fieldMapListDropDown());

          self.confirmAndImport = new confirmAndImport(tmpMarketingList, tmpSelectedFieldMaps, tmpFieldMapListDropDown);
          console.log('self.confirmAndImport');
          console.log(self.confirmAndImport);
          console.log("******* 2 ***********");
          new ImportDataFromInterAction(self.confirmAndImport);

      };
  };

  var MarketingList = function(id, name) {
      this.id = id;
      this.Name = name;
      this.Selected = ko.observable(true);
  };
  var fieldMapListDropDown = function(id, name) {
      this.CRMID = id;
      this.CRMName = name;
      this.CRMSelected = ko.observable();
  };

  var ImportDataFromInterAction = function(data) {
      console.log(data);
  }
  var viewModel = new createCustomer();
  ko.applyBindings(viewModel, $("#IA-Main-Container")[0]);

  function confirmAndImport(MarketingList, tmpSelectedFieldMaps, tmpFieldMapListDropDown) {

      var showConfirmAndImportData = new Object;
      showConfirmAndImportData.MarketingList = [];
      showConfirmAndImportData.MapFields = [];

      Object.keys(MarketingList).map(function(objectKey, index) {
          if (MarketingList[index].Selected) {
              showConfirmAndImportData.MarketingList.push(MarketingList[index]);
          }
      });
      Object.keys(tmpSelectedFieldMaps).map(function(objectKey, index) {
          var match = ko.utils.arrayFirst(tmpFieldMapListDropDown, function(item) {
              return item.CRMID == tmpSelectedFieldMaps[index].CRMID;
          });
          showConfirmAndImportData.MapFields.push({
              'fieldName': tmpSelectedFieldMaps[index].SendFieldName,
              'connectedToCRMID': match.CRMID,
              'connectedToCRMName': match.CRMName,
          });
      });

      return showConfirmAndImportData;
  }

  function toggleClassesOnMarketingListCheckBoxes(pressedId) {

      var tmpData = viewModel.MarketingList()
      tmpData.forEach(function(objectKey, index) {
          if (pressedId != 'cbML0') {
              if (objectKey.id == pressedId) {
                  viewModel.MarketingList()[index].Selected(!objectKey.Selected());
                  toggleClassesOnMarketingListCheckBoxesInnerFunction(viewModel.MarketingList()[index].Selected(), pressedId);
              }
          } else {
              viewModel.MarketingList()[index].Selected(viewModel.SelectAll().Selected());
              toggleClassesOnMarketingListCheckBoxesInnerFunction(!viewModel.SelectAll().Selected(), viewModel.MarketingList()[index].id);
          }
      });

      if (pressedId == 'cbML0') {
          //viewModel.SelectAll.Selected() && tmpElement.classList.contains('unchecked')
          var tmp = viewModel.SelectAll();
          toggleClassesOnMarketingListCheckBoxesInnerFunction(tmp.Selected(), pressedId);
          viewModel.SelectAll().Selected(!viewModel.SelectAll().Selected());
      }
  };

  function toggleClassesOnMarketingListCheckBoxesInnerFunction(bool, pressedId) {
      var tmpElement = document.getElementById(pressedId);
      if (tmpElement != null) {
          if (bool) {
              tmpElement.classList.remove('unchecked');
              tmpElement.classList.add('tdCheckbox');
          } else {
              tmpElement.classList.remove('tdCheckbox');
              tmpElement.classList.add('unchecked');
          }
      }
  }

#IA-Main-Container {
  width: 800px;
  height: 500px;
  background: lightgoldenrodyellow;
  margin: auto;
  padding: 5px;
  border: 3px solid silver;
  border-style: solid;
  border-color: #d7d9db;
  color: #3c4650;
  font-family: Arial, Verdana, Sans-Serif;
}

#IA-Main-Container .searchForm#marketingListSearchForm {
  height: 23px;
  line-height: 23px;
  padding: 5px;
  border: 1px solid;
  margin-bottom: 10px;
  background-color: #d7d9db;
  border-color: #d7d9db;
  text-align: right;
}

#IA-Main-Container input[type=checkbox] {
  /*display: none;*/
}

#IA-Main-Container input[type=checkbox].unchecked+label {
  width: 14px;
  height: 14px;
  background-image: url('https://c.contentsvr.com/skins/common/images/icons/common.png');
  background-position: 0px -14px;
  background-repeat: no-repeat;
  background-color: transparent;
  cursor: pointer;
  display: inline-block;
  font-size: 14px;
  height: 14px;
  line-height: 14px;
  padding: 0;
  text-align: left;
  text-decoration: none;
  text-indent: -9999px;
  width: 14px;
}

#IA-Main-Container input[type=checkbox].tdCheckbox:checked+label {
  width: 14px;
  height: 14px;
  background-image: url('https://c.contentsvr.com/skins/common/images/icons/common.png');
  background-position: -14px -14px;
  background-repeat: no-repeat;
  background-color: transparent;
  cursor: pointer;
  display: inline-block;
  font-size: 14px;
  height: 14px;
  line-height: 14px;
  padding: 0;
  text-align: left;
  text-decoration: none;
  text-indent: -9999px;
  width: 14px;
}

#IA-Main-Container .searchForm#marketingListSearchForm input {
  border: 1px solid #7F8084;
  margin: 3px 0 0;
  padding: 1px;
}

#IA-Main-Container .searchForm#marketingListSearchForm input::-webkit-input-placeholder {
  color: #999;
  padding-left: 3px;
}

#IA-Main-Container header {
  height: 34px;
  background-color: #FFF;
  border-color: #FFF;
  color: #00aae6;
  font-size: 1.2em;
  display: block;
  clear: both;
  margin-bottom: 10px;
  padding: 5px;
}

#IA-Main-Container header .title {
  width: 80%;
  float: left;
  line-height: 34px;
  font-weight: 700;
  margin: 0 5px 0 0;
}

#IA-Main-Container tbody {
  overflow-y: auto;
  overflow-x: hidden;
}

#IA-Main-Container .nav-stepContainer {
  margin-top: 10px;
  margin-bottom: 16px;
  height: 27px;
}

#IA-Main-Container .nav-stepContainer nav ul {
  font-size: 1em;
  float: left;
  list-style: none;
  width: auto;
  display: block;
  padding: 0px;
  margin: 0px;
}

#IA-Main-Container .nav-stepContainer nav ul li {
  font-size: 1em;
  float: left;
  list-style: none;
  width: auto;
}

#IA-Main-Container .nav-stepContainer nav ul li a {
  border-bottom: 5px solid;
  border-color: #DDD;
  color: #999;
  text-decoration: none;
  padding-bottom: 4px;
}

/*#IA-Main-Container .nav-stepContainer nav ul li .selected_navigationBar {*/

.selected_navigationBar {
  border-color: #00aae6 !important;
  color: black !important;
}

#IA-Main-Container .nav-stepContainer nav ul li:not(:first-child)
/*:not(:last-of-type)*/

{
  background-image: url('https://d3dcudlcyz9qvm.cloudfront.net/skins/_common/5/images/brand.png');
  background-position: 5px -232px;
  padding-left: 15px;
}

.innerScreen {
  height: 325px;
  padding: 2px;
  border: 2px solid #9FADAC;
}

.innerScreen table tbody tr {
  border-bottom: 1px solid #9FADAC;
}

.footer {
  text-align: right
}

             Import InterAction List

            Cancel
            <button id="updateContactBtn" class="btn btn-primary" data-bind="click: GoBack, visible: currentIndex() > 0">« Previous Step</button>
            <button id="updateContactBtn" class="btn btn-primary" data-bind="click: GoNext, visible: canGoNext() ">Next Step »</button>
            <button id="updateContactBtn" class="btn btn-primary" data-bind="click: ImportData, visible: showImportBtn() ">Import</button>

Body:
I haven't read through all of your code, but this might help:

To have a checkbox that can toggle a "select all" you can use a computed observable that has a read and a write function.

The read function checks whether all items are Selected and returns true if they are, and false if they're not.

The write value marks all items Selected when passed true, and deselects all items when passed false.

I.e.:

this.SelectAll = ko.computed({
  read: function() {
    return this.MarketingList().every(function(item) {
      return item.Selected();
    });
  },
  write: function(val) {
    this.MarketingList().forEach(function(item) {
      item.Selected(val);
    });
  }
}, this);

In a working example:

function Item(name) {
  this.name = name;
  this.selected = ko.observable(false);
};

function App() {

  this.items = ko.observableArray([
    new Item(1),
    new Item(2),
    new Item(3)
  ]);

  this.allSelected = ko.computed({
    read: function() {
      return this.items().every(function(item) {
        return item.selected();
      });
    },
    write: function(val) {
      this.items().forEach(function(item) {
        item.selected(val);
      });
    }
  }, this);
}

ko.applyBindings(new App());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<label>
  <input type="checkbox" data-bind="checked: allSelected">
  <span>select all</span>
</label>

<ul data-bind="foreach: items">
  <li>
    <label>
      <input type="checkbox" data-bind="checked: selected">
      <span data-bind="text: name"></span>
    </label>
  </li>
</ul>

p.s. If I were you, I'd rename my properties to start with a lowercase character so they don't get mixed up with constructor methods.


来源: stackexchange

问:
How to pass to URLSession.shared.dataTask called in a loop?
I am downloading image from server and when image is downloaded I have to save that image in coredata with id. Here is the code

```<code>for actionDict:JSON in actionData
  {
    if(actionDict["ProtocolImage"].stringValue.isValidURL())
      {
          URLSession.shared.sessionDescription = "\(actionDict["Id"].intValue)"
            URLSession.shared.dataTask(with: URL(string: actionDict["ProtocolImage"].stringValue)!, completionHandler: { (data, response, error) in
                if data != nil{
                    let image = UIImage(data: data!)
                    if image != nil{
                       ProtocolActionModel.updateValueWhere(id: Int64(URLSession.shared.sessionDescription!)!, key: "protocolImage", value:( UIImagePNGRepresentation(image!)! as NSData))
                    }
                }
            }).resume()
      }
  }
</code>```

(actionDict["Id"].intValue is id associated with image that I want to save in coredata with image but when I save it is always set to last item id of for loop.

actionData is

```<code>{
    data =     (
                {
            CheckDesc = vcnhfgb;
            CheckName = hjnhfnmjh;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1487201399293)/";
            Id = 3;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/522cb086-0b0d-4ad9-b5ae-79f6f9a9fbf2.jpg";
            Sorting = "<null>";
        },
                {
            CheckDesc = bfghrthbn;
            CheckName = ddfgb;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167861457)/";
            Id = 71;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/860e68e4-187c-4e49-a936-088c97c500b2.png";
            Sorting = 41;
        },
                {
            CheckDesc = bnvbncyh;
            CheckName = nbnyhjhg;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167894280)/";
            Id = 72;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/e4311494-27ad-4d12-958b-68e0c705a94d.png";
            Sorting = 42;
        },
                {
            CheckDesc = hjbnvbytuu;
            CheckName = nmnmhjgh;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167918147)/";
            Id = 73;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/15ac0300-8877-4503-8c6d-957b5248e829.png";
            Sorting = 43;
        },
                {
            CheckDesc = "";
            CheckName = tyres;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499172466890)/";
            Id = 74;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "<null>";
            Sorting = 44;
        }
    );
    message = success;
    status = 1;
}
</code>```

reponse

```<code><NSHTTPURLResponse: 0x600000634720> { URL: http://example/ApplicationImages/860e68e4-187c-4e49-a936-088c97c500b2.png } { status code: 200, headers {
    "Accept-Ranges" = bytes;
    "Content-Length" = 254882;
    "Content-Type" = "image/png";
    Date = "Wed, 05 Jul 2017 05:31:46 GMT";
    Etag = "\"e09aa43b9f4d21:0\"";
    "Last-Modified" = "Tue, 04 Jul 2017 11:31:01 GMT";
    Server = "Microsoft-IIS/7.5";
    "X-Powered-By" = "ASP.NET";
    "X-Powered-By-Plesk" = PleskWin;
} }
</code>```

Please provide any solution that will solve my problem.

答:
Instead of URLSession.shared.dataTask i am using  NSData(contentsOf: url as URL) to download images from URL.

for eg:

I am just doing with static data replace it with dynamic

```<code>   var resultArray = [Dictionary<String,Any>]()
     var resultDict1 = Dictionary<String,Any>()
     resultDict1["Id"] = 3
     resultDict1["ProtocolImage"] = "https://alperkayabasi.files.wordpress.com/2014/10/asd.png"

     var resultDict2 = Dictionary<String,Any>()
     resultDict2["Id"] = 7
     resultDict2["ProtocolImage"] = "https://alperkayabasi.files.wordpress.com/2014/10/ios-simulator-screen-shot-08-oct-2014-16-39-03.png"

     var resultDict3 = Dictionary<String,Any>()
     resultDict3["Id"] = 9
     resultDict3["ProtocolImage"] = "https://alperkayabasi.files.wordpress.com/2015/02/screen-shot-2015-02-13-at-10-18-12.png"

     resultArray.append(contentsOf: [resultDict1,resultDict2,resultDict3])

     for actionDict in resultArray {
         //here check your URL is valid one
         if let url = URL(string: (actionDict["ProtocolImage"] as? String ?? "".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))!) {

                DispatchQueue.global(qos: .background).async {
                    // Background Thread
                    let imageData = NSData(contentsOf: url as URL)
                    if let data = imageData {
                        if let image = UIImage(data: data as Data) {
                            print(actionDict["Id"] as? Int ?? 0)
                            print(actionDict["ProtocolImage"] as? String ?? "")

                            //here itself you can able to save image to coredata
                            DispatchQueue.main.async {
                                //update UI part if requires
                            }
                        }
                    }
                }
            }
        }
</code>```

The output :

here you will get correct id for image.

```<code>7
https://alperkayabasi.files.wordpress.com/2014/10/ios-simulator-screen-shot-08-oct-2014-16-39-03.png
9
https://alperkayabasi.files.wordpress.com/2015/02/screen-shot-2015-02-13-at-10-18-12.png
3
https://alperkayabasi.files.wordpress.com/2014/10/asd.png
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am downloading image from server and when image is downloaded I have to save that image in coredata with id. Here is the code

for actionDict:JSON in actionData
  {
    if(actionDict["ProtocolImage"].stringValue.isValidURL())
      {
          URLSession.shared.sessionDescription = "\(actionDict["Id"].intValue)"
            URLSession.shared.dataTask(with: URL(string: actionDict["ProtocolImage"].stringValue)!, completionHandler: { (data, response, error) in
                if data != nil{
                    let image = UIImage(data: data!)
                    if image != nil{
                       ProtocolActionModel.updateValueWhere(id: Int64(URLSession.shared.sessionDescription!)!, key: "protocolImage", value:( UIImagePNGRepresentation(image!)! as NSData))
                    }
                }
            }).resume()
      }
  }

(actionDict["Id"].intValue is id associated with image that I want to save in coredata with image but when I save it is always set to last item id of for loop.

actionData is

{
    data =     (
                {
            CheckDesc = vcnhfgb;
            CheckName = hjnhfnmjh;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1487201399293)/";
            Id = 3;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/522cb086-0b0d-4ad9-b5ae-79f6f9a9fbf2.jpg";
            Sorting = "<null>";
        },
                {
            CheckDesc = bfghrthbn;
            CheckName = ddfgb;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167861457)/";
            Id = 71;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/860e68e4-187c-4e49-a936-088c97c500b2.png";
            Sorting = 41;
        },
                {
            CheckDesc = bnvbncyh;
            CheckName = nbnyhjhg;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167894280)/";
            Id = 72;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/e4311494-27ad-4d12-958b-68e0c705a94d.png";
            Sorting = 42;
        },
                {
            CheckDesc = hjbnvbytuu;
            CheckName = nmnmhjgh;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499167918147)/";
            Id = 73;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "http://example.com/ApplicationImages/15ac0300-8877-4503-8c6d-957b5248e829.png";
            Sorting = 43;
        },
                {
            CheckDesc = "";
            CheckName = tyres;
            CheckedImage =             (
            );
            CreatedDate = "/Date(1499172466890)/";
            Id = 74;
            IsChecked = 0;
            ProtocolId = 4;
            ProtocolImage = "<null>";
            Sorting = 44;
        }
    );
    message = success;
    status = 1;
}

reponse

<NSHTTPURLResponse: 0x600000634720> { URL: http://example/ApplicationImages/860e68e4-187c-4e49-a936-088c97c500b2.png } { status code: 200, headers {
    "Accept-Ranges" = bytes;
    "Content-Length" = 254882;
    "Content-Type" = "image/png";
    Date = "Wed, 05 Jul 2017 05:31:46 GMT";
    Etag = "\"e09aa43b9f4d21:0\"";
    "Last-Modified" = "Tue, 04 Jul 2017 11:31:01 GMT";
    Server = "Microsoft-IIS/7.5";
    "X-Powered-By" = "ASP.NET";
    "X-Powered-By-Plesk" = PleskWin;
} }

Please provide any solution that will solve my problem.

Body:
Instead of URLSession.shared.dataTask i am using  NSData(contentsOf: url as URL) to download images from URL.

for eg:

I am just doing with static data replace it with dynamic

   var resultArray = [Dictionary<String,Any>]()
     var resultDict1 = Dictionary<String,Any>()
     resultDict1["Id"] = 3
     resultDict1["ProtocolImage"] = "https://alperkayabasi.files.wordpress.com/2014/10/asd.png"

     var resultDict2 = Dictionary<String,Any>()
     resultDict2["Id"] = 7
     resultDict2["ProtocolImage"] = "https://alperkayabasi.files.wordpress.com/2014/10/ios-simulator-screen-shot-08-oct-2014-16-39-03.png"

     var resultDict3 = Dictionary<String,Any>()
     resultDict3["Id"] = 9
     resultDict3["ProtocolImage"] = "https://alperkayabasi.files.wordpress.com/2015/02/screen-shot-2015-02-13-at-10-18-12.png"

     resultArray.append(contentsOf: [resultDict1,resultDict2,resultDict3])

     for actionDict in resultArray {
         //here check your URL is valid one
         if let url = URL(string: (actionDict["ProtocolImage"] as? String ?? "".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))!) {

                DispatchQueue.global(qos: .background).async {
                    // Background Thread
                    let imageData = NSData(contentsOf: url as URL)
                    if let data = imageData {
                        if let image = UIImage(data: data as Data) {
                            print(actionDict["Id"] as? Int ?? 0)
                            print(actionDict["ProtocolImage"] as? String ?? "")

                            //here itself you can able to save image to coredata
                            DispatchQueue.main.async {
                                //update UI part if requires
                            }
                        }
                    }
                }
            }
        }

The output :

here you will get correct id for image.

7
https://alperkayabasi.files.wordpress.com/2014/10/ios-simulator-screen-shot-08-oct-2014-16-39-03.png
9
https://alperkayabasi.files.wordpress.com/2015/02/screen-shot-2015-02-13-at-10-18-12.png
3
https://alperkayabasi.files.wordpress.com/2014/10/asd.png


问:
How to add multiple classes to a ReactJS Component?
I am new to ReactJS and JSX and I am having a little problem with the code below.

I am trying to add multiple classes to the className attribute on each li:

```

<p>My React component is:</p>

<pre class="lang-jsx prettyprint-override"><code>var AccountMainMenu = React.createClass({
  getInitialState: function() {
    return { focused: 0 };
  },

  clicked: function(index) {
    this.setState({ focused: index });
  },

  render: function() {
    var self = this;
    var accountMenuData = [
      {
        name: "My Account",
        icon: "icon-account"
      },
      {
        name: "Messages",
        icon: "icon-message"
      },
      {
        name: "Settings",
        icon: "icon-settings"
      }
    /*{
        name:"Help & Support   <span class='font-awesome icon-support'></span>(888) 664.6261",
        listClass:"no-mobile last help-support last"
      }*/
    ];

    return (
      <div className="acc-header-wrapper clearfix">
        <ul className="acc-btns-container">
          {accountMenuData.map(function(data, index) {
            var activeClass = "";

            if (self.state.focused == index) {
              activeClass = "active";
            }

            return (
              <li
                key={index}
                className={activeClass}
                onClick={self.clicked.bind(self, index)}
              >

                  {data.name}

              </li>
            );
          })}
        </ul>
      </div>
    );
  }
});

ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));
</code>```

答:
Late to the party, but why use third party for such a simple problem?

You could either do it as @Huw Davies mentioned - the best way

```<code>1. <i className={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>
2. <i className={[styles['foo-bar-baz'], 'fa fa-user', 'fa-2x'].join(' ')}
</code>```

Both are good. But writing can become complex for a large app. To make it optimal, I do the same above things but put it in a helper class

Using my below helper function, allows me to keep the logic separate for future editing, and also gives me multiple ways to add the classes

```<code>classNames(styles['foo-bar-baz], 'fa fa-user', 'fa-2x')
</code>```

or

```<code>classNames([styles['foo-bar-baz], 'fa fa-user', 'fa-2x'])
</code>```

This is my helper function below. I've put it in a helper.js where I keep all my common methods. Being such a simple function, I avoided using 3rd party to keep control

```<code>export function classNames (classes) {
    if(classes && classes.constructor === Array) {
        return classes.join(' ')
    } else if(arguments[0] !== undefined) {
        return [...arguments].join(' ')
    }
    return ''
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to ReactJS and JSX and I am having a little problem with the code below.

I am trying to add multiple classes to the className attribute on each li:

My React component is:

var AccountMainMenu = React.createClass({
  getInitialState: function() {
    return { focused: 0 };
  },

  clicked: function(index) {
    this.setState({ focused: index });
  },

  render: function() {
    var self = this;
    var accountMenuData = [
      {
        name: "My Account",
        icon: "icon-account"
      },
      {
        name: "Messages",
        icon: "icon-message"
      },
      {
        name: "Settings",
        icon: "icon-settings"
      }
    /*{
        name:"Help & Support   (888) 664.6261",
        listClass:"no-mobile last help-support last"
      }*/
    ];

    return (

          {accountMenuData.map(function(data, index) {
            var activeClass = "";

            if (self.state.focused == index) {
              activeClass = "active";
            }

            return (

                  {data.name}

            );
          })}

    );
  }
});

ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));

Body:
Late to the party, but why use third party for such a simple problem?

You could either do it as @Huw Davies mentioned - the best way

1. <i className={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>
2. <i className={[styles['foo-bar-baz'], 'fa fa-user', 'fa-2x'].join(' ')}

Both are good. But writing can become complex for a large app. To make it optimal, I do the same above things but put it in a helper class

Using my below helper function, allows me to keep the logic separate for future editing, and also gives me multiple ways to add the classes

classNames(styles['foo-bar-baz], 'fa fa-user', 'fa-2x')

or

classNames([styles['foo-bar-baz], 'fa fa-user', 'fa-2x'])

This is my helper function below. I've put it in a helper.js where I keep all my common methods. Being such a simple function, I avoided using 3rd party to keep control

export function classNames (classes) {
    if(classes && classes.constructor === Array) {
        return classes.join(' ')
    } else if(arguments[0] !== undefined) {
        return [...arguments].join(' ')
    }
    return ''
}


问:
Numpy's float32 and float comparisons
Continuing from Difference between Python float and numpy float32:

```<code>import numpy as np

a = 58682.7578125
print(type(a), a)
float_32 = np.float32(a)
print(type(float_32), float_32)
print(float_32 == a)
</code>```

Prints:

```<code><class 'float'> 58682.7578125
<class 'numpy.float32'> 58682.8
True
</code>```

I fully understand that comparing floats for equality is not a good idea but still shouldn't this be False (we're talking about differences in the first decimal digit, not in 0.000000001) ? Is it system dependent ? Is this behavior somewhere documented ?

EDIT: Well it's the third decimal:

```<code>print(repr(float_32), repr(a))
# 58682.758 58682.7578125
</code>```

but can I trust repr ? How are those stored internally in the final end ?

EDIT2: people insist that printing float_32 with more precision will give me its representation. However as I already commented according to nympy's docs:

the % formatting operator requires its arguments to be converted to standard python types

and:

```<code>print(repr(float(float_32)))
</code>```

prints

58682.7578125

An interesting insight is given by @MarkDickinson here, apparently repr should be faithful (then he says it's not faithful for np.float32).

So let me reiterate my question as follows:

How can I get at the exact internal representation of float_32 and a in the example ? If these are the same, then problem solved if not,

What are the exact rules for up/downcasting in a comparison between python's float and np.float32 ? I 'd guess that it upcasts float_32 to float although @WillemVanOnsem suggests in the comments it's the other way round

My python version:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32

答:
The decimal 58682.7578125 is the exact fraction (7511393/128).

The denominator is a power of 2 (2**7), and the numerator span 23 bits. So this decimal value can be represented exactly both in float32 (which has 24 bits significand) and float64.

Thus the answer of Victor T is correct: in internal representation, it's the same value.

The fact that equality answer true for same value, even for different types is a good thing IMO, what do you expect of (2 == 2.0)?

Title: Numpy's float32 and float comparisons

Body:
Continuing from Difference between Python float and numpy float32:

import numpy as np

a = 58682.7578125
print(type(a), a)
float_32 = np.float32(a)
print(type(float_32), float_32)
print(float_32 == a)

Prints:

<class 'float'> 58682.7578125
<class 'numpy.float32'> 58682.8
True

I fully understand that comparing floats for equality is not a good idea but still shouldn't this be False (we're talking about differences in the first decimal digit, not in 0.000000001) ? Is it system dependent ? Is this behavior somewhere documented ?

EDIT: Well it's the third decimal:

print(repr(float_32), repr(a))
# 58682.758 58682.7578125

but can I trust repr ? How are those stored internally in the final end ?

EDIT2: people insist that printing float_32 with more precision will give me its representation. However as I already commented according to nympy's docs:

the % formatting operator requires its arguments to be converted to standard python types

and:

print(repr(float(float_32)))

prints

58682.7578125

An interesting insight is given by @MarkDickinson here, apparently repr should be faithful (then he says it's not faithful for np.float32).

So let me reiterate my question as follows:

How can I get at the exact internal representation of float_32 and a in the example ? If these are the same, then problem solved if not,

What are the exact rules for up/downcasting in a comparison between python's float and np.float32 ? I 'd guess that it upcasts float_32 to float although @WillemVanOnsem suggests in the comments it's the other way round

My python version:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32


问:
Why does flexbox not center my image?
```<code>section
{
background-color: #EEEEEE;
margin: 10vmin 5vmin;
padding: 2vmin;
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
}

img
{
height: 30vmax;
border: 1vmin solid black;
border-radius: 30vmax;
margin: 1vmin;
}
</code>```

Entire source code available here : https://codepen.io/de_arth/pen/dvLoyO/

Basically, I'm able to center everything BUT an image, (and a link in the very last section) with flexbox, even though it should be in a single straight line on mobile and desktop displays. What am I doing wrong?

答:
you need to add text-align

set text-align:center in your css section part

for ex:

```<code>section
{
background-color: #EEEEEE;
margin: 10vmin 5vmin;
padding: 2vmin;
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
text-align:center;
}
</code>```

Title: Why does flexbox not center my image?

Body:
section
{
background-color: #EEEEEE;
margin: 10vmin 5vmin;
padding: 2vmin;
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
}

img
{
height: 30vmax;
border: 1vmin solid black;
border-radius: 30vmax;
margin: 1vmin;
}

Entire source code available here : https://codepen.io/de_arth/pen/dvLoyO/

Basically, I'm able to center everything BUT an image, (and a link in the very last section) with flexbox, even though it should be in a single straight line on mobile and desktop displays. What am I doing wrong?

Body:
you need to add text-align

set text-align:center in your css section part

for ex:

section
{
background-color: #EEEEEE;
margin: 10vmin 5vmin;
padding: 2vmin;
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
text-align:center;
}


问:
TCL TDom: Looping through Objects
Using TDom, I would like to cycle through a list of objects in the following format:

```<code>    <object>
      <type>Hardware</type>
      <name>System Name</name>
      <description>Basic Description of System.</description>
      <attributes>
          <vendor>Dell</vendor>
          <contract>MM/DD/YY</contract>
          <supportExpiration>MM/DD/YY</supportExpiration>
          <location>Building 123</location>
          <serial>xxx-xxx-xxxx</serial>
          <mac>some-mac-address</mac>
      </attributes>
    </object>

    <object>
      <type>Software</type>
      <name>Second Object</name>
    ...
</code>```

Then I use TDom to make a list of objects:

```<code>set dom [dom parse $xml]
set doc [$dom documentElement]

set nodeList [$doc selectNodes /systems/object]
</code>```

So far I've done this to (theoretically) select every "Object" node from the list.  How can I loop through them?  Is it just:

```<code>foreach node $nodeList {
</code>```

For each object, I need to retrieve the association of each attribute.  From the example, I need to remember that the "name" is "System Name", "vendor" is "Dell", etc.

I'm new to TCL but in other languages I would use an object or an associative list to store these.  Is this possible?  Can you show me an example of the syntax to select an attribute in this manner?

答:
```<code>set doc [$dom documentElement]
set nodeList [$doc selectNodes /systems/object]

foreach node [$nodeList childNodes] {
    set nodename [$node nodeName]
    if {$nodename eq "attributes"} {
        foreach attr_node [$node childNodes] {
            set attr_nodename [$attr_node nodeName]
            set attr_nodetext [[$attr_node selectNodes text()] nodeValue]
            puts "$attr_nodename : $attr_nodetext"
        }
    } else {
        set node_text [[$node selectNodes text()] nodeValue]
        puts "$nodename : $node_text"
    }
}
</code>```

check this out for the quick reference https://tdom.github.io/domDoc.html

ContentLicense: CC BY-SA 2.5

Title: TCL TDom: Looping through Objects

Body:
Using TDom, I would like to cycle through a list of objects in the following format:

    <object>
      <type>Hardware</type>
      <name>System Name</name>
      <description>Basic Description of System.</description>
      <attributes>
          <vendor>Dell</vendor>
          <contract>MM/DD/YY</contract>
          <supportExpiration>MM/DD/YY</supportExpiration>
          <location>Building 123</location>
          <serial>xxx-xxx-xxxx</serial>
          <mac>some-mac-address</mac>
      </attributes>
    </object>

    <object>
      <type>Software</type>
      <name>Second Object</name>
    ...

Then I use TDom to make a list of objects:

set dom [dom parse $xml]
set doc [$dom documentElement]

set nodeList [$doc selectNodes /systems/object]

So far I've done this to (theoretically) select every "Object" node from the list.  How can I loop through them?  Is it just:

foreach node $nodeList {

For each object, I need to retrieve the association of each attribute.  From the example, I need to remember that the "name" is "System Name", "vendor" is "Dell", etc.

I'm new to TCL but in other languages I would use an object or an associative list to store these.  Is this possible?  Can you show me an example of the syntax to select an attribute in this manner?

Body:
set doc [$dom documentElement]
set nodeList [$doc selectNodes /systems/object]

foreach node [$nodeList childNodes] {
    set nodename [$node nodeName]
    if {$nodename eq "attributes"} {
        foreach attr_node [$node childNodes] {
            set attr_nodename [$attr_node nodeName]
            set attr_nodetext [[$attr_node selectNodes text()] nodeValue]
            puts "$attr_nodename : $attr_nodetext"
        }
    } else {
        set node_text [[$node selectNodes text()] nodeValue]
        puts "$nodename : $node_text"
    }
}

check this out for the quick reference https://tdom.github.io/domDoc.html


问:
how to stable hover effect even after mouse out
how to set my hover effect stable even after mouse out ???
    code is working fine but after mouse out div element comes to its
    original state ??

html

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

css

```<code>#sme{
    width: 400px;
    height: 400px;
    border: 20px solid #06c999;
/* Rotate */
}
#sme:hover{
transition: all 1.9s ease;
 -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);

}
</code>```

答:
I think you are looking for this

$(function(){
    $('#sme').on('mouseenter', function(){
 $(this).addClass('hoverd');
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sme {
  width: 400px;
  height: 400px;
  border: 20px solid #06c999;
  transition: all 1.9s ease;
}

.hoverd {
  -webkit-transform: rotate(180deg);
  -moz-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  -o-transform: rotate(180deg);
  transform: rotate(180deg);
}</code>```

```

Body:
how to set my hover effect stable even after mouse out ???
    code is working fine but after mouse out div element comes to its
    original state ??

html

css

#sme{
    width: 400px;
    height: 400px;
    border: 20px solid #06c999;
/* Rotate */
}
#sme:hover{
transition: all 1.9s ease;
 -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);

}

Body:
I think you are looking for this

$(function(){
    $('#sme').on('mouseenter', function(){
 $(this).addClass('hoverd');
    });
});

#sme {
  width: 400px;
  height: 400px;
  border: 20px solid #06c999;
  transition: all 1.9s ease;
}

.hoverd {
  -webkit-transform: rotate(180deg);
  -moz-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  -o-transform: rotate(180deg);
  transform: rotate(180deg);
}

<div id="sme"></div>

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


问:
I am using FCM.how can i display notification tittle in alert dialogue or custom Toast when app is in foreground rather than on status bar?
Right now i am using this when app is in foreground it gives me status on status bar now i want alert dialogue r custom popup for notification when appp is in foreground</p>

```<code>    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message

            try
            {
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", title);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
                NotificationCompat.Builder builder = new  NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.imgpsh_fullsize)
                        .setContentTitle(title);
                NotificationManager manager = (NotificationManager)     getSystemService(NOTIFICATION_SERVICE);
                manager.notify(0, builder.build());

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
</code>```

答:
It is very easy if your check for app is in the foreground is correct..
instead of displaying notification just create alert dialog having title and all required field as per your need and show it...

if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {

try {

            new AlertDialog.Builder(this)

                    .setTitle("Your title")

                    .setMessage("Your messae")

                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).setNegativeButton("No", null).show();\

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//here click of negative button is not added but you can add as per your need...
```
<p>Please ask if any doubt again...</p>
<p>put above in some method say <code>showAlertMessage()</code> and call method from handler like this</p>
```Handler uiHandler = new Handler(Looper.getMainLooper());

        uiHandler.post(new Runnable() {

            @Override
            public void run() {

                showAlertMessage();

            }
        });
```

Body:
Right now i am using this when app is in foreground it gives me status on status bar now i want alert dialogue r custom popup for notification when appp is in foreground

    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message

            try
            {
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", title);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
                NotificationCompat.Builder builder = new  NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.imgpsh_fullsize)
                        .setContentTitle(title);
                NotificationManager manager = (NotificationManager)     getSystemService(NOTIFICATION_SERVICE);
                manager.notify(0, builder.build());

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

Body:
It is very easy if your check for app is in the foreground is correct..
instead of displaying notification just create alert dialog having title and all required field as per your need and show it...

if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {

try {

            new AlertDialog.Builder(this)

                    .setTitle("Your title")

                    .setMessage("Your messae")

                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).setNegativeButton("No", null).show();\

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//here click of negative button is not added but you can add as per your need...

Please ask if any doubt again...

put above in some method say showAlertMessage() and call method from handler like this

Handler uiHandler = new Handler(Looper.getMainLooper());

        uiHandler.post(new Runnable() {

            @Override
            public void run() {

                showAlertMessage();

            }
        });


问:
Create new event from another one in Javascript NOT byRef (ie7 compatible)
I'm trying to create a new object (event) in my javascript code from an another event (window.event). I would like to create this one new event byVal e not byRef because i need this event also window.event were dead.
This code must be ie7 compatible.

I tryied this but doesn't work :-(

```<code>function copyMyEvent(p) {
  if (!p) throw Error('no type');
  function f() {};
  f.prototype = p;
  return new f();
};

var event = copyMyEvent( window.event );
</code>```

Thx

答:
I am not 100% sure, but you might want to stringify and then re-evaluate the code to make this happen. You should try some of the polyfills for deep object copy.

Check this question:
What is the most efficient way to deep clone an object in JavaScript?

Body:
I'm trying to create a new object (event) in my javascript code from an another event (window.event). I would like to create this one new event byVal e not byRef because i need this event also window.event were dead.
This code must be ie7 compatible.

I tryied this but doesn't work :-(

function copyMyEvent(p) {
  if (!p) throw Error('no type');
  function f() {};
  f.prototype = p;
  return new f();
};

var event = copyMyEvent( window.event );

Thx


问:
Postman/Newman junit report customization
I'm using postman and newman to perform automated  tests and I do a JUnit export in order to exploit them in TFS.
However, when I open my .xml report, failures are indicated as follows:

```<code>-<failure type="AssertionFailure">
    -<![CDATA[Failed 1 times.]]>
</failure>
</code>```

I would like to know if it is possible to customize the "Failed 1 times." information in order to pass more relevant data about the failure (ie. json body error and description)

Thank you

Alexandre

答:
Well, finally I found out how to proceed (not a clean way but sufficient for my purpose, so far):

I impact the file C:\Users\<myself>\AppData\Roaming\npm\node_modules\newman\lib\reporters\junit\index.js

Request's data and response can be recovered from 'executions' object:

stringExecutions = JSON.stringify(executions); //provide information about the arguments of the object "executions"

from this I can take general information by json-parsing this element and extracting what I want:

```<code>jsonExecutions = JSON.parse(stringExecutions)
jsonExecutions[0].response._details.code // gives me the http return code,
jsonExecutions[0].response._details.name // gives me the status,
jsonExecutions[0].response._details.detail //gives a bit more details
</code>```

Error data (at test case/testsuite level) can be recovered from the 'err.error' object:

```<code>stringData = JSON.stringify(err.error); jsonData = JSON.parse(stringData);
</code>```

from that I extract the data I need, ie.

```<code>jsonData.name // the error type
jsonData.message // the error detail
jsonData.stacktrace // the error stack
</code>```

by the way, in the original file, stack cannot be displayed as there is no 'stack' argument in error.err (it is named 'stacktrace').

Finally failure data (at test step/testcase level) can be recovered from the 'failures' object:

```<code>stringFailure = JSON.stringify(failures); jsonFailure = JSON.parse(stringFailure);
</code>```

from this I extract:

```<code>jsonFailure[0].name // the failure type
jsonFailure[0].stack // the failure stack
</code>```

For my purpose, I add response details from jsonExecutions to my testsuite error data, which is much more verbose in the XML report than previousely.

If there is a cleaner/smarter way to perform this, do not hesitate to tell me, I'll be grateful

Next step : do it clean by creating a custom reporter. :)

Alexandre

Body:
I'm using postman and newman to perform automated  tests and I do a JUnit export in order to exploit them in TFS.
However, when I open my .xml report, failures are indicated as follows:

-<failure type="AssertionFailure">
    -<![CDATA[Failed 1 times.]]>
</failure>

I would like to know if it is possible to customize the "Failed 1 times." information in order to pass more relevant data about the failure (ie. json body error and description)

Thank you

Alexandre

Body:
Well, finally I found out how to proceed (not a clean way but sufficient for my purpose, so far):

I impact the file C:\Users\<myself>\AppData\Roaming\npm\node_modules\newman\lib\reporters\junit\index.js

Request's data and response can be recovered from 'executions' object:

stringExecutions = JSON.stringify(executions); //provide information about the arguments of the object "executions"

from this I can take general information by json-parsing this element and extracting what I want:

jsonExecutions = JSON.parse(stringExecutions)
jsonExecutions[0].response._details.code // gives me the http return code,
jsonExecutions[0].response._details.name // gives me the status,
jsonExecutions[0].response._details.detail //gives a bit more details

Error data (at test case/testsuite level) can be recovered from the 'err.error' object:

stringData = JSON.stringify(err.error); jsonData = JSON.parse(stringData);

from that I extract the data I need, ie.

jsonData.name // the error type
jsonData.message // the error detail
jsonData.stacktrace // the error stack

by the way, in the original file, stack cannot be displayed as there is no 'stack' argument in error.err (it is named 'stacktrace').

Finally failure data (at test step/testcase level) can be recovered from the 'failures' object:

stringFailure = JSON.stringify(failures); jsonFailure = JSON.parse(stringFailure);

from this I extract:

jsonFailure[0].name // the failure type
jsonFailure[0].stack // the failure stack

For my purpose, I add response details from jsonExecutions to my testsuite error data, which is much more verbose in the XML report than previousely.

If there is a cleaner/smarter way to perform this, do not hesitate to tell me, I'll be grateful

Next step : do it clean by creating a custom reporter. :)

Alexandre


问:
What value can a Rails route helper have as a parameter?
I'm working on a Rails tutorial and I don't understand the value a route helper can have as parameter.

Why is it correct for the "article_path" to have "article" as its parameter?

```<code><ul id=“articles”>
    <% @articles.each do |article| %>
        <li>
            <%= link_to article.title, article_path(article) %>
        </li>
    <% end %>
</ul>
</code>```

答:
```<code>article_path(article)
</code>```

Is valid Because you are passing the whole object as a parameter when parameters come to the controller, controller get the id from parameter and give a particular record.

I suggest you follow the standard way using article_path(article.id) because if you have number of fields in article model (table) then all filed are pass in the parameter.

Body:
I'm working on a Rails tutorial and I don't understand the value a route helper can have as parameter.

Why is it correct for the "article_path" to have "article" as its parameter?

    <% @articles.each do |article| %>

            <%= link_to article.title, article_path(article) %>

    <% end %>

Body:
article_path(article)

Is valid Because you are passing the whole object as a parameter when parameters come to the controller, controller get the id from parameter and give a particular record.

I suggest you follow the standard way using article_path(article.id) because if you have number of fields in article model (table) then all filed are pass in the parameter.


问:
Can a module be reloaded from a different location, from within the module?
I have an API A::B that's "use"d by others in their scripts like so:

```<code>use A::B;
my $out = A::B->new(dir => $dir);
...
</code>```

Now, I want a different version of A::B to be used depending on some parameter of the attribute $dir passed to the constructor.  The user of this module has no need to know this - all he has to do is

use A::B

in his code, and expect that the module is picked up from the right location.  Is it possible to do this?

答:
If you allow a different package name of the other version internally (while the user still uses A::B and does not know about the different names of the same module), you could achieve this. For example, let's say the different version of the module is internally called A::B::C. Then package A::B could be like this:

```<code>package A::B;

sub new {
    my ( $class, %opts ) = @_;

    if ( $opts{dir} eq "dir1" ) {
        require A::B::C;
        return A::B::C->new();
    }
    else {
        my $self = {};
        return bless $self, $class;
    }
}

1;
</code>```

Body:
I have an API A::B that's "use"d by others in their scripts like so:

use A::B;
my $out = A::B->new(dir => $dir);
...

Now, I want a different version of A::B to be used depending on some parameter of the attribute $dir passed to the constructor.  The user of this module has no need to know this - all he has to do is

use A::B

in his code, and expect that the module is picked up from the right location.  Is it possible to do this?

Body:
If you allow a different package name of the other version internally (while the user still uses A::B and does not know about the different names of the same module), you could achieve this. For example, let's say the different version of the module is internally called A::B::C. Then package A::B could be like this:

package A::B;

sub new {
    my ( $class, %opts ) = @_;

    if ( $opts{dir} eq "dir1" ) {
        require A::B::C;
        return A::B::C->new();
    }
    else {
        my $self = {};
        return bless $self, $class;
    }
}

1;


问:
UI boostrap modal with component cause "One of template or templateUrl options is required." error
I have a separate component js

uploadImage.js

```<code>'use strict'

imageListApp.controller('uploadImageController', function ($scope, Upload) {
    var $ctrl = this;

    $ctrl.$onInit = function () {

    }
    $ctrl.ok = function (file) {
        $scope.f = file;

        if (file) {
            file.upload = Upload.upload({
                url: '/api/images/upload',
                data: { title: $scope.picTitle, files: file }
            });

            file.upload.then(function (response) {

                $ctrl.close({ $value: response.data })

            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 *
                    evt.loaded / evt.total));
            });
        }
    }

    $ctrl.cancel = function () {
        $ctrl.dismiss({ $value: 'cancel' });
    }

})

imageListApp.component('uploadImage', {
    templateUrl: 'js/components/uploadImage/uploadImage.html',
    bindings: {
        resolve: '<',
        close: '&',
        dismiss: '&'
    },
    controller: 'uploadImageController'
})
</code>```

And in other controller js, I use $uib.open to open modal with this component

```<code>$scope.openUploadModal = function () {
            var uploadModalInstance = $uibModal.open({
                component:'uploadImage',
                resolve: {
                    title: function () {
                        return $scope.title;
                    }
                }
            });

            uploadModalInstance.result.then(function () {
                console.log("upload success");
            },
            function () {
                console.log("upload cancel");
            })

        }
</code>```

I ensure all javascript are include properly in index.html

When I invoke the open modal function, I get the errors:

```<code>angular.js:14525 Error: One of template or templateUrl options is required.
    at Object.$modal.open (ui-bootstrap-tpls.js:3742)
    at Scope.$scope.openUploadModal (imageListController.js:58)
    at fn (eval at compile (angular.js:15358), <anonymous>:4:165)
    at callback (angular.js:26994)
    at Scope.$eval (angular.js:18161)
    at Scope.$apply (angular.js:18261)
    at HTMLInputElement.<anonymous> (angular.js:26999)
    at HTMLInputElement.dispatch (jquery.js:5206)
    at HTMLInputElement.elemData.handle (jquery.js:5014)
</code>```

What means of the error and what problem to cause this error?

答:
template (Type: string) - Inline template representing the modal's
  content.

templateUrl (Type: string) - A path to a template representing modal's
  content. You need either a template or templateUrl.

Add a template for your modal options (or templateUrl)

Body:
I have a separate component js

uploadImage.js

'use strict'

imageListApp.controller('uploadImageController', function ($scope, Upload) {
    var $ctrl = this;

    $ctrl.$onInit = function () {

    }
    $ctrl.ok = function (file) {
        $scope.f = file;

        if (file) {
            file.upload = Upload.upload({
                url: '/api/images/upload',
                data: { title: $scope.picTitle, files: file }
            });

            file.upload.then(function (response) {

                $ctrl.close({ $value: response.data })

            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 *
                    evt.loaded / evt.total));
            });
        }
    }

    $ctrl.cancel = function () {
        $ctrl.dismiss({ $value: 'cancel' });
    }

})

imageListApp.component('uploadImage', {
    templateUrl: 'js/components/uploadImage/uploadImage.html',
    bindings: {
        resolve: '<',
        close: '&',
        dismiss: '&'
    },
    controller: 'uploadImageController'
})

And in other controller js, I use $uib.open to open modal with this component

$scope.openUploadModal = function () {
            var uploadModalInstance = $uibModal.open({
                component:'uploadImage',
                resolve: {
                    title: function () {
                        return $scope.title;
                    }
                }
            });

            uploadModalInstance.result.then(function () {
                console.log("upload success");
            },
            function () {
                console.log("upload cancel");
            })

        }

I ensure all javascript are include properly in index.html

When I invoke the open modal function, I get the errors:

angular.js:14525 Error: One of template or templateUrl options is required.
    at Object.$modal.open (ui-bootstrap-tpls.js:3742)
    at Scope.$scope.openUploadModal (imageListController.js:58)
    at fn (eval at compile (angular.js:15358), <anonymous>:4:165)
    at callback (angular.js:26994)
    at Scope.$eval (angular.js:18161)
    at Scope.$apply (angular.js:18261)
    at HTMLInputElement.<anonymous> (angular.js:26999)
    at HTMLInputElement.dispatch (jquery.js:5206)
    at HTMLInputElement.elemData.handle (jquery.js:5014)

What means of the error and what problem to cause this error?


问:
'An item with the same key has already been added.' -- Which key?
The following code:

```<code>var rnd = new Random();
Enumerable.Range(1,20).Select(x => rnd.Next(10)).ToDictionary(x => x, x => "");
</code>```

will inevitably fail with the following exception:

System.ArgumentException: 'An item with the same key has already been added.'

Is there any way to use the Visual Studio IDE while debugging, to find out the attempted key? Is the key stored somewhere in the exception details -- some internal / private field perhaps; which can be read using the exception details window?

I can't change the source of ToDictionary to include the key in the thrown exception.

Note: I am aware that I can rewrite this in a debuggable fashion, using a For Each loop instead of LINQ. But I am asking about the general case -- when this exception is thrown, and the source code is not under my control, is there some way to access the key?

Using VS 2017 Community Edition.

答:
It is possible using the IDE, at least for a System.Collections.Generic.Dictionary<TKey,TValue>. Presumably the attempted key could be found in a similar fashion for other dictionary types:

Enable .NET Framework Source debugging. The instructions appear to be still valid, even though they are for Visual Studio 2013. (NB. I had to clear the symbol cache.)

The exception (at least for this code) will be thrown at the following line:

```<code>throw new ArgumentException(Environment.GetResourceString(GetResourceName(resource)));
</code>```

Backtracking one level up in the call stack to this line, I get to the following block of code:

```<code>for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
    if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
        if (add) {
            ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
        }
</code>```

Most of the local variables are unavailable -- the Watch and Local windows give the following message:

Cannot obtain value of the local variable or argument because it is not available at this instruction pointer, possibly because it has been optimized away.

But i is available, and so is entries. The following expression in the Watch window returns the duplicate key:

```<code>entries[i].key
</code>```

Body:
The following code:

var rnd = new Random();
Enumerable.Range(1,20).Select(x => rnd.Next(10)).ToDictionary(x => x, x => "");

will inevitably fail with the following exception:

System.ArgumentException: 'An item with the same key has already been added.'

Is there any way to use the Visual Studio IDE while debugging, to find out the attempted key? Is the key stored somewhere in the exception details -- some internal / private field perhaps; which can be read using the exception details window?

I can't change the source of ToDictionary to include the key in the thrown exception.

Note: I am aware that I can rewrite this in a debuggable fashion, using a For Each loop instead of LINQ. But I am asking about the general case -- when this exception is thrown, and the source code is not under my control, is there some way to access the key?

Using VS 2017 Community Edition.

Body:
It is possible using the IDE, at least for a System.Collections.Generic.Dictionary<TKey,TValue>. Presumably the attempted key could be found in a similar fashion for other dictionary types:

Enable .NET Framework Source debugging. The instructions appear to be still valid, even though they are for Visual Studio 2013. (NB. I had to clear the symbol cache.)

The exception (at least for this code) will be thrown at the following line:

throw new ArgumentException(Environment.GetResourceString(GetResourceName(resource)));

Backtracking one level up in the call stack to this line, I get to the following block of code:

for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
    if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
        if (add) {
            ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
        }

Most of the local variables are unavailable -- the Watch and Local windows give the following message:

Cannot obtain value of the local variable or argument because it is not available at this instruction pointer, possibly because it has been optimized away.

But i is available, and so is entries. The following expression in the Watch window returns the duplicate key:

entries[i].key


问:
Javascript and website loading time optimization
I know that best practice for including javascript is having all code in a separate .js file and allowing browsers to cache that file.

But when we begin to use many jquery plugins which have their own .js, and our functions depend on them, wouldn't it be better to load dynamically only the js function and the required .js for the current page?

Wouldn't that be faster, in a page, if I only need one function to load dynamically embedding it in html with the script tag instead of loading the whole js with the js plugins?

In other words, aren't there any cases in which there are better practices than keeping our whole javascript code in a separate .js?

答:
It would seem at first glance that this would be a good idea, but in fact it would actually make matters worse.  For example, if one page needs plugins 1, 2 and 3, then a file would be build server side with those plugins in it.  Now, the browser goes to another page that needs plugins 2 and 4.  This would cause another file to be built, this new file would be different from the first one, but it would also contain the code for plugin 2 so the same code ends up getting downloaded twice, bypassing the version that the browser already has.

You are best off leaving the caching to the browser, rather than trying to second-guess it.  However, there are options to improve things.

Top of the list is using a CDN.  If the plugins you are using are fairly popular ones, then the chances are that they are being hosted with a CDN.  If you link to the CDN-hosted plugins, then any visitors who are hitting your site for the first time and who have also happened to have hit another site that's also using the same plugins from the same CDN, the plugins will already be cached.

There are, of course, other things you can to to speed your javascript up.  Best practice includes placing all your script include tags as close to the bottom of the document as possible, so as to not hold up page rendering.  You should also look into lazy initialization.  This involves, for any stuff that needs significant setup to work, attaching a minimalist event handler that when triggered removes itself and sets up the real event handler.


问:
Webpack Breaks Mocha in Node.js App
I have a node.js app that uses Mocha and Expect for testing. All the tests work great, until I installed webpack for react. Now when I run "npm test" I get the following error:

```<code>Error: Cannot find module 'should'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\watchpack\test\DirectoryWatcher.test.js:2:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:230:27
    at Array.forEach (native)
    at Mocha.loadFiles (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:227:14)
    at Mocha.run (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:495:10)
    at Object.<anonymous> (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\bin\_mocha:469:18)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:508:3
npm ERR! Test failed.  See above for more details.
</code>```

Below is my package.json:

```<code>{
  "name": "cool-map",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node server.js",
    "test": "export NODE_ENV=test || SET \"NODE_ENV=test\" && mocha **/*.test.js",
    "test-watch": "nodemon --exec \"npm test\""
  },
  "engines": {
    "node": "6.2.2"
  },
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.3.0",
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "jsonwebtoken": "^7.1.9",
    "lodash": "^4.15.0",
    "mongodb": "^2.2.5",
    "mongoose": "^4.5.9",
    "validator": "^5.6.0",
    "hbs": "^4.0.0",
    "babel-preset-stage-0": "^6.24.1",
    "express": "^4.15.2",
    "react": "^0.14.7",
    "react-dom": "^0.14.7"
  },
  "devDependencies": {
    "expect": "^1.20.2",
    "mocha": "^3.0.2",
    "nodemon": "^1.10.2",
    "supertest": "^2.0.0",
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "webpack": "^1.12.13"
  }
}
</code>```

I'm not sure if webpack.config is necessary to post, but just in case:

```<code>module.exports = {
    entry: './app/app.jsx',
    output: {
        path: __dirname,
        filename: './public/bundle.js'
    },
    resolve: {
        root: __dirname,
        alias: {
            AdminUserTable: 'app/components/AdminUserTable.jsx'
        },
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            {
                    loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015']
                },
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/
            }
        ]
    }
};
</code>```

Running the command npm test works great when I uninstall webpack, I'm not sure why It's breaking mocha.

答:
Your package.json is missing should as a dependency.

Install it via;

npm install --save-dev should

Also I would recommend you look into chai which in my opinion provides a slightly different API.

Title: Webpack Breaks Mocha in Node.js App

Body:
I have a node.js app that uses Mocha and Expect for testing. All the tests work great, until I installed webpack for react. Now when I run "npm test" I get the following error:

Error: Cannot find module 'should'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\watchpack\test\DirectoryWatcher.test.js:2:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:230:27
    at Array.forEach (native)
    at Mocha.loadFiles (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:227:14)
    at Mocha.run (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:495:10)
    at Object.<anonymous> (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\bin\_mocha:469:18)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:508:3
npm ERR! Test failed.  See above for more details.

Below is my package.json:

{
  "name": "cool-map",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node server.js",
    "test": "export NODE_ENV=test || SET \"NODE_ENV=test\" && mocha **/*.test.js",
    "test-watch": "nodemon --exec \"npm test\""
  },
  "engines": {
    "node": "6.2.2"
  },
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.3.0",
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "jsonwebtoken": "^7.1.9",
    "lodash": "^4.15.0",
    "mongodb": "^2.2.5",
    "mongoose": "^4.5.9",
    "validator": "^5.6.0",
    "hbs": "^4.0.0",
    "babel-preset-stage-0": "^6.24.1",
    "express": "^4.15.2",
    "react": "^0.14.7",
    "react-dom": "^0.14.7"
  },
  "devDependencies": {
    "expect": "^1.20.2",
    "mocha": "^3.0.2",
    "nodemon": "^1.10.2",
    "supertest": "^2.0.0",
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "webpack": "^1.12.13"
  }
}

I'm not sure if webpack.config is necessary to post, but just in case:

module.exports = {
    entry: './app/app.jsx',
    output: {
        path: __dirname,
        filename: './public/bundle.js'
    },
    resolve: {
        root: __dirname,
        alias: {
            AdminUserTable: 'app/components/AdminUserTable.jsx'
        },
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            {
                    loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015']
                },
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/
            }
        ]
    }
};

Running the command npm test works great when I uninstall webpack, I'm not sure why It's breaking mocha.