问:
hiding/showing navigation in a angularjs page
I have a navigation in my main page which is only necessary for logged in users.Now i want to hide the navigation from the login page.So initially i am using an undefined flag variable to hide the navigation in the login page.Then after user login i am setting the flag value as 1 and redirecting to dashboard page so that for the dashboard page the navigation appear.But the problem is though i am successfully setting the flag value the navigation menu is no more appearing.It seems the flag value is making no effect.

In a nutshell my goal is to hide navigation menu from login page but show  this to all other page.So how to solve the issue ? am i moving to the right direction or there are better ways to achieve this ?

Index.htm

```<code><body ng-app="myApp">
  <div ng-controller="logCtrl">
    <div ng-if="flag==1">
      <p><a href="#/">Main</a></p>
      <a href="#login">Login</a>
      <a href="#dashboard">dashborad</a>
    </div>
  </div>

  <div ng-view></div>
  <script>
    var app = angular.module("myApp", ["ngRoute"]);
    app.config(function($routeProvider) {
      $routeProvider
        .when("/", {
          templateUrl : "login.htm"
        })
        .when("/login", {
          templateUrl : "login.htm",
          controller : "logCtrl"
        })
        .when("/dashborad", {
          templateUrl : "dashborad.htm",
          controller : "dashboradCtrl"
        });
    });

    app.controller('logCtrl', function ($scope,$location,$http) {
      $scope.login = function () {
        var request = $http({
          method: "post",
          url: "ajax/login.php",
          data: {
            username: $scope.username,
            password: $scope.password
          },
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        });

        request.success(function (data) {
          if(data == "1") {
            $scope.flag=1;
            $location.path('/dashboard');
          } else {
            $scope.flag=0;
          }
        });
      }
    });

  </script>
</body>
</code>```

login.htm

```<code><div class="panel panel-body login-form">
  <div class="form-group has-feedback has-feedback-left">
    <input type="text" class="form-control"  ng-model="username" placeholder="Username">
  </div>
  <div class="form-control-feedback">
      <i class="icon-user text-muted"></i>
  </div>
</div>

<div class="form-group has-feedback has-feedback-left">
  <input type="password" class="form-control" ng-model="password" placeholder="Password">
  <div class="form-control-feedback">
    <i class="icon-lock2 text-muted"></i>
  </div>
</div>
<span>{{responseMessage }}{{flag}}</span>
  <div class="form-group">
    <button type="submit" class="btn btn-primary btn-block" ng-click="login()">Sign in</button>
  </div>
</div>
</code>```

答:
Just an advice:
You better use the usual boolean value for that like $scope.flag = true or $scope.flag = false. And in you ng-if:

```<code><div ng-controller="logCtrl" ng-if="flag">
</code>```

In your controller:

```<code>app.controller('logCtrl', function ($scope,$http) {
        $scope.login = function () {
                var request = $http({
                    method: "post",
                    url: "ajax/login.php",
                    data: {
                        username: $scope.username,
                        password: $scope.password
                    },
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                });

                request.success(function (data) {
                    if(data == "1"){
                       $scope.flag = true;
                    }
                    else {
                        $scope.flag = false;
                    }
                });
        }
});
</code>```

And I agree with @StanislavKvitash, it's not a good idea to use ng-if and ng-controller on the same tag. Better add another one inner div and set ng-if to it. So try to use this HTML:

```<code><body ng-app="myApp">
    <div ng-controller="logCtrl">
        <div ng-if="flag">
            <p><a href="#/">Main</a></p>

            <a href="#login">Red</a>
            <a href="#dashboard">Green</a>
        </div>
    </div>

   <div ng-view></div>
   ...
</body>
</code>```

"My goal is to hide navigation menu from login page but show this to all other page"

If you want to hide navigation only for /login, you can simply hardcode flag value at the beginning of your logCtrl like this: $scope.flag = 0 and the navigation will be hidden when /login (and you doesn't need if/else statement, just hardcode the flag value).

Body:
I have a navigation in my main page which is only necessary for logged in users.Now i want to hide the navigation from the login page.So initially i am using an undefined flag variable to hide the navigation in the login page.Then after user login i am setting the flag value as 1 and redirecting to dashboard page so that for the dashboard page the navigation appear.But the problem is though i am successfully setting the flag value the navigation menu is no more appearing.It seems the flag value is making no effect.

In a nutshell my goal is to hide navigation menu from login page but show  this to all other page.So how to solve the issue ? am i moving to the right direction or there are better ways to achieve this ?

Index.htm

Main

      Login
      dashborad

login.htm

    <input type="text" class="form-control"  ng-model="username" placeholder="Username">

  <input type="password" class="form-control" ng-model="password" placeholder="Password">

{{responseMessage }}{{flag}}

    <button type="submit" class="btn btn-primary btn-block" ng-click="login()">Sign in</button>

Body:
Just an advice:
You better use the usual boolean value for that like $scope.flag = true or $scope.flag = false. And in you ng-if:

<div ng-controller="logCtrl" ng-if="flag">

In your controller:

app.controller('logCtrl', function ($scope,$http) {
        $scope.login = function () {
                var request = $http({
                    method: "post",
                    url: "ajax/login.php",
                    data: {
                        username: $scope.username,
                        password: $scope.password
                    },
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                });

                request.success(function (data) {
                    if(data == "1"){
                       $scope.flag = true;
                    }
                    else {
                        $scope.flag = false;
                    }
                });
        }
});

And I agree with @StanislavKvitash, it's not a good idea to use ng-if and ng-controller on the same tag. Better add another one inner div and set ng-if to it. So try to use this HTML:

<body ng-app="myApp">
    <div ng-controller="logCtrl">
        <div ng-if="flag">
            <p><a href="#/">Main</a></p>

            <a href="#login">Red</a>
            <a href="#dashboard">Green</a>
        </div>
    </div>

   <div ng-view></div>
   ...
</body>

"My goal is to hide navigation menu from login page but show this to all other page"

If you want to hide navigation only for /login, you can simply hardcode flag value at the beginning of your logCtrl like this: $scope.flag = 0 and the navigation will be hidden when /login (and you doesn't need if/else statement, just hardcode the flag value).


来源: stackexchange

问:
silverstripe dynamic backend for flexible frontend
I'm searching for a while, but didn't find a practical answer for the following problem:
An Articlepage in the Frontend can contain different types of sections. For example a block text section and than a text section with left photo an at the end an wallpaper photo.
Now I want to implement this in my backend dynamically, so that I can choose, which type of section and -even more important- how many sections my article should contain.

In my recent project I've solved the problem as an Articlesection with a Dropdown, wich contains the different section styles. And one article hat xy Artilesections as childpages. In the frontend I included all Childpages of the Article - so to speak the Articlesections, where I've checked with if conditions, which sectionsystyle I have in this Section and here I styled the section as I want.
For example Artilce1 has 2 Childpages: Articlesection1 and Artilcesection2.
In AS1 I have choose in the dropdown: right text with left photo and check with if conditions, to style the section. The same with AS2, that is for example a wallpaper photo.

This semiprofessional solution worked, but there are some bugs with displaying the Article correct in the backend, because I have to declare the Articlesections as Includes and not native childpages. And in generell this don't seems like the developers of silverstripe want the users to do it this way..

Are there better ways to implement a dynamically changing backend, so I can decide, which and how much sections I have in the frontend.

答:
Thank you for your reply, but there is a problem, because I don't work a lot with the terminal and the composer. In principle I want to install sheadawsons silverstripe-block. I have installed the composer and run the command:
"composer require sheadawson/silverstripe-blocks" it seems like it installed that correctly, because I became no errors, but what then? With dev/build -to refresh the database- happened nothing and the following instructions in the readmy chanced nothing. Should I copy any files in my Sivlerstripe web folder or what else..? I'm a bit desperate, because there is such a poor documentation.

Tank you

ContentLicense: CC BY-SA 3.0


问:
How to set separate behaviours for different sets of tabs?
I am developing a functionality where I have different sets of tabs.
And I want every set of tabs to behave by itself. I mean: any of the other set of tabs have to interfere with the behaviour of the other sets.

The only error I have in the code so far is that when you click on any of the tabs of the first set, the content of the select tabs of the other sets disappear.

And I need the first tab of every set to be always selected by default.

Here is a JSFiddle I have created.

$(document).ready(function() {

  $('.tabs a:not(:first)').addClass('inactive');
  $('.container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //this is the start of our condition
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().nextAll('.container').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}</code>```

  test1
  test2
  test3
  test4

1Some content

2Some content

3Some content

4Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content
```

答:
I've removed the ids and replaced them by data-tab, because id should be unique and I wrapped all tabs to get only the clicked scope.

$(document).ready(function() {

  $('.tabs a').addClass('inactive');
  $('.tabs a:first-child').removeClass('inactive');
  $('.tab-container .container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').on('click', function() {
    var $tabContainer = $(this).parents('.tab-container');
    var tabId = $(this).data('tab');

    $tabContainer.find('.tabs a').addClass('inactive');
    $(this).removeClass('inactive');

    $tabContainer.find('.container').hide();
    $tabContainer.find('.container[data-tab="'+tabId+'"]').fadeIn('slow');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}</code>```

    test1
    test2
    test3
    test4

5Some content

6Some content

7Some content

8Some content

    test1
    test2
    test3
    test4

5Some content

6Some content

7Some content

8Some content

    test1
    test2
    test3
    test4

5Some content

6Some content

7Some content

8Some content

```

Body:
I am developing a functionality where I have different sets of tabs.
And I want every set of tabs to behave by itself. I mean: any of the other set of tabs have to interfere with the behaviour of the other sets.

The only error I have in the code so far is that when you click on any of the tabs of the first set, the content of the select tabs of the other sets disappear.

And I need the first tab of every set to be always selected by default.

Here is a JSFiddle I have created.

$(document).ready(function() {

  $('.tabs a:not(:first)').addClass('inactive');
  $('.container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //this is the start of our condition
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().nextAll('.container').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});

.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}

  test1
  test2
  test3
  test4

1Some content

2Some content

3Some content

4Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content

Body:
I've removed the ids and replaced them by data-tab, because id should be unique and I wrapped all tabs to get only the clicked scope.

$(document).ready(function() {

  $('.tabs a').addClass('inactive');
  $('.tabs a:first-child').removeClass('inactive');
  $('.tab-container .container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').on('click', function() {
    var $tabContainer = $(this).parents('.tab-container');
    var tabId = $(this).data('tab');

    $tabContainer.find('.tabs a').addClass('inactive');
    $(this).removeClass('inactive');

    $tabContainer.find('.container').hide();
    $tabContainer.find('.container[data-tab="'+tabId+'"]').fadeIn('slow');
  });
});

.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}

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

<div class="tab-container">
  <div class="tabs">
    <a data-tab="tab5">test1</a>
    <a data-tab="tab6">test2</a>
    <a data-tab="tab7">test3</a>
    <a data-tab="tab8">test4</a>
  </div>

  <div class="container" data-tab="tab5">5Some content</div>
  <div class="container" data-tab="tab6">6Some content</div>
  <div class="container" data-tab="tab7">7Some content</div>
  <div class="container" data-tab="tab8">8Some content</div>
</div>

<div class="tab-container">
  <div class="tabs">
    <a data-tab="tab5">test1</a>
    <a data-tab="tab6">test2</a>
    <a data-tab="tab7">test3</a>
    <a data-tab="tab8">test4</a>
  </div>

  <div class="container" data-tab="tab5">5Some content</div>
  <div class="container" data-tab="tab6">6Some content</div>
  <div class="container" data-tab="tab7">7Some content</div>
  <div class="container" data-tab="tab8">8Some content</div>
</div>

<div class="tab-container">
  <div class="tabs">
    <a data-tab="tab5">test1</a>
    <a data-tab="tab6">test2</a>
    <a data-tab="tab7">test3</a>
    <a data-tab="tab8">test4</a>
  </div>

  <div class="container" data-tab="tab5">5Some content</div>
  <div class="container" data-tab="tab6">6Some content</div>
  <div class="container" data-tab="tab7">7Some content</div>
  <div class="container" data-tab="tab8">8Some content</div>
</div>


问:
Horizontal and vertical sortable divs
I'd like to get an answer to my problem with a sortable grid. I'm having 2 rows with both containing 3 columns.

```<code><div id="sortable" class="connectedSortable">
<div class="row">
    <div class="column">column</div>
    <div class="column">column</div>
    <div class="column">column</div>
</div>
<div class="row">
    <div class="column">column</div>
    <div class="column">column</div>
    <div class="column">column</div>
</div>
</div>
</code>```

I'd like these to be sortable vertically(the columns) and horizontally(the rows)
Here is my CSS:

```<code>    .row {  height: 200px;  }

    .row:nth-child(even) {  background: lightgray;  }

    #sortable {  height: 100px;  }

    .column {
        float: left;
        display: inline-block;
        width: 33.3%;
        height: 200px;
    }
    .column:nth-child(odd) {  background: red;  }

    .row:nth-child(2){
        background:yellow;
    }

    .row:nth-child(2) .column:nth-child(odd) {  background: pink;  }
</code>```

Which looks like this:

I am unable to select the first or second row to change positions vertically, i think it's because of the columns that can be sortable too, and the colums are using full width of the row.

The only jQuery that I'm using is the following (with jQueryUI):

```<code>$(function () {
        $("#sortable, .row").sortable({
            connectWith: ".connectedSortable"
        }).disableSelection();
    });
</code>```

Jsfiddle:
JsFiddle

答:
I've kinda hacked my problem by using 'items' and a placeholder div. Somehow using a placeholderdiv makes me able to select the row block. Now I can select a row (by holding mouse close to the top of the row) and the first column.

```<code>    $("#sortable, .row").sortable({
            items: ".row, .column"
    });
</code>```

See JSFiddle https://jsfiddle.net/ort8zLmf/5/

But I would like to have a better solution.

Title: Horizontal and vertical sortable divs

Body:
I'd like to get an answer to my problem with a sortable grid. I'm having 2 rows with both containing 3 columns.

column

column

column

column

column

column

I'd like these to be sortable vertically(the columns) and horizontally(the rows)
Here is my CSS:

    .row {  height: 200px;  }

    .row:nth-child(even) {  background: lightgray;  }

    #sortable {  height: 100px;  }

    .column {
        float: left;
        display: inline-block;
        width: 33.3%;
        height: 200px;
    }
    .column:nth-child(odd) {  background: red;  }

    .row:nth-child(2){
        background:yellow;
    }

    .row:nth-child(2) .column:nth-child(odd) {  background: pink;  }

Which looks like this:

I am unable to select the first or second row to change positions vertically, i think it's because of the columns that can be sortable too, and the colums are using full width of the row.

The only jQuery that I'm using is the following (with jQueryUI):

$(function () {
        $("#sortable, .row").sortable({
            connectWith: ".connectedSortable"
        }).disableSelection();
    });

Jsfiddle:
JsFiddle

Body:
I've kinda hacked my problem by using 'items' and a placeholder div. Somehow using a placeholderdiv makes me able to select the row block. Now I can select a row (by holding mouse close to the top of the row) and the first column.

    $("#sortable, .row").sortable({
            items: ".row, .column"
    });

See JSFiddle https://jsfiddle.net/ort8zLmf/5/

But I would like to have a better solution.


问:
Saving Password with Md5
I am using Postgresql,hibernate and Java and I need to store a password. Can someone suggest me how to encrypt the password with md5. Else is there a better way to store secure password in the database

Thanks

答:
1) There is no decrypt for MD5.

2) MD5 is old technology which is excellent for checking to see if two strings are the same.

3) MD5 is subject to dictionary assaults.

4) MD5 can be made more secure by using a salt.

5) We use MD5 for low level security because the hash can be easily duplicated across platforms. (C++, vb.net, VB6, C#, php ...)

ContentLicense: CC BY-SA 2.5

Title: Saving Password with Md5


问:
npm can't find dependencies for some react-native modules
I'm creating a react native app using create-react-native-app

```<code>npm create-react-native-app
</code>```

I updated react-native version to 0.44.0, which requires to update react version to 16.0.0-alpha.6
This is my package.json

```<code>{
  "name": "test",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-native-scripts": "0.0.29",
    "jest-expo": "^0.4.0",
    "react-test-renderer": "~15.5.4"
  },
  "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "start": "react-native-scripts start",
    "eject": "react-native-scripts eject",
    "android": "react-native-scripts android",
    "ios": "react-native-scripts ios",
    "test": "node node_modules/jest/bin/jest.js --watch"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/ex-navigation": "^2.11.1",
    "babel-preset-react-native-stage-0": "^1.0.1",
    "expo": "^16.0.0",
    "react": "~16.0.0-alpha.6",
    "react-native": "0.44.0"
  }
}
</code>```

Running npm install gives me following errors

```<code>C:\dev\repo\test>npm install
npm WARN lottie-react-native@1.1.1 requires a peer of react@>=15.3.1 but none was installed.
npm WARN react-native-maps@0.12.2 requires a peer of react@>=15.4.0 but none was installed.
npm WARN react-native-svg@4.4.1 requires a peer of react@>=15.4.0 but none was installed.
npm WARN react-static-container@1.0.1 requires a peer of react@^0.13.0 || ^0.14.0 || ^15.0.0 but none was installed.
</code>```

It looks like react version 16.0.0-alpha.6 is not recognized by lottie-react-native, react-native-maps, react-native-svg, and react-static-container. I'm not sure if major version (15) must be met, or the alpha version 16 is not picked up by those libraries, or something else. Does anyone know how to fix this? Thanks.

答:
I have a similar problem, actually right now I get this problem, whenever I try to create a new application with create-react-native-app.
The only solution (hack) I have found right now is:

Delete node_modules (for me it's not enough to just do npm install)

Do npm install

Body:
I'm creating a react native app using create-react-native-app

npm create-react-native-app

I updated react-native version to 0.44.0, which requires to update react version to 16.0.0-alpha.6
This is my package.json

{
  "name": "test",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-native-scripts": "0.0.29",
    "jest-expo": "^0.4.0",
    "react-test-renderer": "~15.5.4"
  },
  "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "start": "react-native-scripts start",
    "eject": "react-native-scripts eject",
    "android": "react-native-scripts android",
    "ios": "react-native-scripts ios",
    "test": "node node_modules/jest/bin/jest.js --watch"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/ex-navigation": "^2.11.1",
    "babel-preset-react-native-stage-0": "^1.0.1",
    "expo": "^16.0.0",
    "react": "~16.0.0-alpha.6",
    "react-native": "0.44.0"
  }
}

Running npm install gives me following errors

C:\dev\repo\test>npm install
npm WARN lottie-react-native@1.1.1 requires a peer of react@>=15.3.1 but none was installed.
npm WARN react-native-maps@0.12.2 requires a peer of react@>=15.4.0 but none was installed.
npm WARN react-native-svg@4.4.1 requires a peer of react@>=15.4.0 but none was installed.
npm WARN react-static-container@1.0.1 requires a peer of react@^0.13.0 || ^0.14.0 || ^15.0.0 but none was installed.

It looks like react version 16.0.0-alpha.6 is not recognized by lottie-react-native, react-native-maps, react-native-svg, and react-static-container. I'm not sure if major version (15) must be met, or the alpha version 16 is not picked up by those libraries, or something else. Does anyone know how to fix this? Thanks.


问:
Rename a grid in acumatica using event row selected
I tried to rename the display name in acumatica using this code below

```<code>PXUIFieldAttribute.SetDisplayName<BOMMaterial.qtys>(this.MaterialDetail.Cache, "test");
</code>```

and

```<code>PXUIFieldAttribute.SetDisplayName(this.Caches[typeof(BOMMaterial)], typeof(BOMMaterial.qtys).Name , "test");
</code>```

It does work if I put the code outside the event, so it will change when the screen is loaded. However, if I put it inside rowselected event and use validation, it doesn't change the display name. And it doesn't show any error.

答: Make sure to set RepaitColumns property to True of PXGrid Control as well.

Body:
I tried to rename the display name in acumatica using this code below

PXUIFieldAttribute.SetDisplayName<BOMMaterial.qtys>(this.MaterialDetail.Cache, "test");

and

PXUIFieldAttribute.SetDisplayName(this.Caches[typeof(BOMMaterial)], typeof(BOMMaterial.qtys).Name , "test");

It does work if I put the code outside the event, so it will change when the screen is loaded. However, if I put it inside rowselected event and use validation, it doesn't change the display name. And it doesn't show any error.


问:
Use Google NDB to connect to cloud storage
I maintain older app using Python, webapp2 and ndb. When running the app locally from PyCharm, dev_appserver uses local version of datastore but I'd like to use cloud datastore. Is this possible? In the end, when I run the app locally, it should access datastore of deployed app instead of local one.

This tutorial shows the solution but it is using datastore from google.cloud while my app uses ndb from google.appengine.ext.

答:
In order to access cloud storage from outside of GAE (locally) you need to switch to the datastore API.

See this thread: what's the difference between google.appengine.ext.ndb and gcloud.datastore?


问:
Edit Function for SAP Fiori Template with ODATA
In the Web IDE it is very easy to create a Fiori App from a Master Detail Template and adding an ODATA service.
But this new created app only displays the data from the ODATA service.
What is the correct way to add a Create or Edit function after adding the new view and a save button?
How should the onSavePressed function look like?
Do I have to create an ODataModel in this function or is it already present anywhere in the template?
Is the structure of this template already correct and complete or do I have to change it?
I only read about createEntry() and submitChanges() in the documentations but not how to use/implement them.
Are there any simple instructions or demo apps?

Thanks in advance!

答:
In the WebIDE you can also: File -> New -> Project from Sample Application
Do you find an app called “Manage Products”?
When you run it, do you find an “Edit”-button in the bottom right corner?
Is this, what you are looking for?</p>


问:
Apache Camel upload email attachment to ftp
I'm using the following processor to fetch the first attachement of an email and upload it to a ftp-server.

Route configuration

```<code><from uri="imaps://...
<to uri="ejb:java:global/Dms/MailProcessor"/>
<to uri="ftp://....
</code>```

MailProcessor

```<code>@Named("MailProcessor")
@Stateless
public class MailProcessor implements Processor {

    @Override
    public void process(Exchange exchange) throws Exception {

        exchange.getOut().setHeaders(exchange.getIn().getHeaders());

        Map<String, DataHandler> attachments = exchange.getIn().getAttachments();
        if (attachments.size() > 0) {
            for (String name : attachments.keySet()) {
                DataHandler dataHandler = attachments.get(name);

                // SET ATTACHMENT FILENAME TO OUTPUT FILENAME HEADER
                String filename = dataHandler.getName();
                filename = MimeUtility.decodeText(filename);
                exchange.getOut().setHeader("filename", filename);

                // SET INPUT ATTACHMENT TO OUTPUT BODY
                byte[] data = exchange.getContext().getTypeConverter().convertTo(byte[].class, dataHandler.getInputStream());
                exchange.getOut().setBody(data);

                // SET ONLY THE FIRST ATTACHMENT
                break;
            }
        }else{
            exchange.getOut().setBody(exchange.getIn().getBody());
    }

}
</code>```

This works in general, but it takes literally forever for "big" attachments. (half an hour for just a 5 mb attachment)

Log

```<code>TRACE [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) Changing directory: upload
TRACE [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) doStoreFile(ID-example-local-59752-1494841993139-21-11)
DEBUG [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) About to store file: ID-example-local-59752-1494841993139-21-11 using stream: com.sun.mail.util.BASE64DecoderStream@601a11dc
TRACE [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) Client storeFile: ID-example-local-59752-1494841993139-21-11
 -- long pause --
</code>```

I've also tried to convert the attachment like this:

```<code>byte[] data = exchange.getContext().getTypeConverter().convertTo( byte[].class, dataHandler.getInputStream() );
exchange.getOut().setBody(data);
</code>```

but this gives me the following:

```<code>2017-05-15 11:23:20,968 TRACE [org.apache.camel.impl.converter.DefaultTypeConverter] (Camel (example) thread #133 - imaps://mail.example.com) Converting org.apache.camel.Processor$$$view63 -> org.apache.camel.Processor with value: Proxy for view class: org.apache.camel.Processor of EJB: MailProcessor
2017-05-15 11:23:20,968 TRACE [org.apache.camel.component.bean.BeanProcessor] (Camel (example) thread #133 - imaps://mail.example.com) Using a custom adapter as bean invocation: Proxy for view class: org.apache.camel.Processor of EJB: MailProcessor
2017-05-15 11:23:20,990 TRACE [org.apache.camel.impl.converter.DefaultTypeConverter] (Camel (example) thread #133 - imaps://mail.example.com) Converting com.sun.mail.util.BASE64DecoderStream -> byte[] with value: com.sun.mail.util.BASE64DecoderStream@28442828
2017-05-15 11:23:20,990 TRACE [org.apache.camel.impl.converter.DefaultTypeConverter] (Camel (example) thread #133 - imaps://mail.example.com) Using converter: StaticMethodTypeConverter: public static byte[] org.apache.camel.converter.IOConverter.toBytes(java.io.InputStream) throws java.io.IOException to convert [class com.sun.mail.util.BASE64DecoderStream=>class [B]
2017-05-15 11:23:20,990 TRACE [org.apache.camel.util.IOHelper] (Camel (example) thread #133 - imaps://mail.example.com) Copying InputStream: java.io.BufferedInputStream@24b2cffb -> OutputStream:  with buffer: 4096 and flush on each write false
-- long pause --
</code>```

Uploading to the ftp server using Filezilla works like a charm. Also when I use camel-ftp in another route ( triggered by a file upload ) the upload to the ftp server works pretty fast.
So I have a feeling that it's the conversion of the attachment which slows things down.

Questions:

Is my assumption correct and how can I speed things up?

答:
Solution was to use <from uri="imaps://...&mail.imaps.partialfetch=false.

https://community.oracle.com/thread/2604843?start=0&tstart=0

Body:
I'm using the following processor to fetch the first attachement of an email and upload it to a ftp-server.

Route configuration

<from uri="imaps://...
<to uri="ejb:java:global/Dms/MailProcessor"/>
<to uri="ftp://....

MailProcessor

@Named("MailProcessor")
@Stateless
public class MailProcessor implements Processor {

    @Override
    public void process(Exchange exchange) throws Exception {

        exchange.getOut().setHeaders(exchange.getIn().getHeaders());

        Map<String, DataHandler> attachments = exchange.getIn().getAttachments();
        if (attachments.size() > 0) {
            for (String name : attachments.keySet()) {
                DataHandler dataHandler = attachments.get(name);

                // SET ATTACHMENT FILENAME TO OUTPUT FILENAME HEADER
                String filename = dataHandler.getName();
                filename = MimeUtility.decodeText(filename);
                exchange.getOut().setHeader("filename", filename);

                // SET INPUT ATTACHMENT TO OUTPUT BODY
                byte[] data = exchange.getContext().getTypeConverter().convertTo(byte[].class, dataHandler.getInputStream());
                exchange.getOut().setBody(data);

                // SET ONLY THE FIRST ATTACHMENT
                break;
            }
        }else{
            exchange.getOut().setBody(exchange.getIn().getBody());
    }

}

This works in general, but it takes literally forever for "big" attachments. (half an hour for just a 5 mb attachment)

Log

TRACE [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) Changing directory: upload
TRACE [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) doStoreFile(ID-example-local-59752-1494841993139-21-11)
DEBUG [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) About to store file: ID-example-local-59752-1494841993139-21-11 using stream: com.sun.mail.util.BASE64DecoderStream@601a11dc
TRACE [org.apache.camel.component.file.remote.FtpOperations] (Camel (example) thread #119 - imaps://mail.example.com) Client storeFile: ID-example-local-59752-1494841993139-21-11
 -- long pause --

I've also tried to convert the attachment like this:

byte[] data = exchange.getContext().getTypeConverter().convertTo( byte[].class, dataHandler.getInputStream() );
exchange.getOut().setBody(data);

but this gives me the following:

2017-05-15 11:23:20,968 TRACE [org.apache.camel.impl.converter.DefaultTypeConverter] (Camel (example) thread #133 - imaps://mail.example.com) Converting org.apache.camel.Processor$$$view63 -> org.apache.camel.Processor with value: Proxy for view class: org.apache.camel.Processor of EJB: MailProcessor
2017-05-15 11:23:20,968 TRACE [org.apache.camel.component.bean.BeanProcessor] (Camel (example) thread #133 - imaps://mail.example.com) Using a custom adapter as bean invocation: Proxy for view class: org.apache.camel.Processor of EJB: MailProcessor
2017-05-15 11:23:20,990 TRACE [org.apache.camel.impl.converter.DefaultTypeConverter] (Camel (example) thread #133 - imaps://mail.example.com) Converting com.sun.mail.util.BASE64DecoderStream -> byte[] with value: com.sun.mail.util.BASE64DecoderStream@28442828
2017-05-15 11:23:20,990 TRACE [org.apache.camel.impl.converter.DefaultTypeConverter] (Camel (example) thread #133 - imaps://mail.example.com) Using converter: StaticMethodTypeConverter: public static byte[] org.apache.camel.converter.IOConverter.toBytes(java.io.InputStream) throws java.io.IOException to convert [class com.sun.mail.util.BASE64DecoderStream=>class [B]
2017-05-15 11:23:20,990 TRACE [org.apache.camel.util.IOHelper] (Camel (example) thread #133 - imaps://mail.example.com) Copying InputStream: java.io.BufferedInputStream@24b2cffb -> OutputStream:  with buffer: 4096 and flush on each write false
-- long pause --

Uploading to the ftp server using Filezilla works like a charm. Also when I use camel-ftp in another route ( triggered by a file upload ) the upload to the ftp server works pretty fast.
So I have a feeling that it's the conversion of the attachment which slows things down.

Questions:

Is my assumption correct and how can I speed things up?


问:
Why would this function be getting called twice?
I have a dialog bot that asks for an email, in this function, at the end it appends a button into the chat. It only repeats this for the email function, but all others only rune once. What could be causing this?

My Setup (email conditional)

```<code>  if (email.length > 0 && email_confirmed == true) {
    $("#message").hide();
    send_msg(
      "One second, let me go check and see where your practicum is in the queue.",
      function() {
        send_msg(
          "It looks like your practicum will be graded by {{ DATE }}", function(){
          send_msg("If this seems too long we may be in a bit of a delay as our team grades all these by hand. ", function(){
            send_msg("If it is longer than 10 business days please post in our community as you may have submitted with another email address", function() {
            email_confirmed = false;
            $("#message").hide();
            $("#controls").append(
            '<button class="options one" value="certifications" type="button">My Certifications</button>'
            );
            })
          })
          })
        });
      }
</code>```

The problem occurs when you click the button "my certifications". It calls this conditional

My Certs conditional

```<code>//If user has certification issues
if (b_val == 'certifications'){
    send_msg('Awesome! Did you know we have over 75,000 certified users?', function(){
    send_msg('Please select which area of the certification process you are having trouble with', function(){
        $("#controls").append(
        '<button class="options one" value="practicum" type="button">Practicum status</button>' +
        '<button class="options one" value="exams" type="button">Exam issues</button>' +
        '<button class="options one" value="badges" type="button">Badge problems</button>'
        );
    })
  })
}
</code>```

This is how I execute my clicks

```<code>  // Pushes user's selected values as text chats
  $("#controls").on("click", ".options", function() {
    // Remove buttons on click
    $("#controls button.options").remove();
    var text = $(this).text();
    var b_val = $(this).val();

    // Set user's name in front of each message
    var userName = "<span class='username user-dialog dialog'> Me: </span>";
    var newMsg = text;

    var prevState = $("#conversation").html();
    if (prevState.length > 3) {
      prevState = prevState;
    }
    $("#conversation").html(
      prevState +
        "<div class='user-log'>" +
        "<span class='currentmsg user-dialog dialog' style='right:-40px; position:relative;'><span class='user-di-arrow'></span>" +
        newMsg +
        "</span> </div>"
    );
    // conditional codes
});
</code>```

Here is my fiddle as well. To see what I am experiencing follow these steps:

enter name

click my certifications

click practicum issues

enter email

click my certifications

EDIT: here is a video of the problem

答:
In your JSFiddle, you have

```<code>  if (email.length > 0 && email_confirmed == true) {
    $("#message").hide();
    send_msg(
      "One second, let me go check and see where your practicum is in the queue.",
      function() {
        send_msg(
          "It looks like your practicum will be graded by {{ DATE }}", function(){
          send_msg("If this seems too long we may be in a bit of a delay as our team grades all these by hand. ", function(){
            send_msg("If it is longer than 10 business days please post in our community as you may have submitted with another email address", function() {
            email_confirmed = false;
            $("#message").hide();
            **$("#controls").append(
            '<button class="options one" value="certifications" type="button">My Certifications</button>'
            );**
            })
          })
          })
        });
      }
</code>```

After it is done asking, it calls

```<code>$("#controls").append(
                '<button class="options one" value="certifications" type="button">My Certifications</button>'
                );
</code>```

so that in turn calls the same function twice. You want to remove. If you don't want it to go back and starting again.

I hope this helps.

Body:
I have a dialog bot that asks for an email, in this function, at the end it appends a button into the chat. It only repeats this for the email function, but all others only rune once. What could be causing this?

My Setup (email conditional)

  if (email.length > 0 && email_confirmed == true) {
    $("#message").hide();
    send_msg(
      "One second, let me go check and see where your practicum is in the queue.",
      function() {
        send_msg(
          "It looks like your practicum will be graded by {{ DATE }}", function(){
          send_msg("If this seems too long we may be in a bit of a delay as our team grades all these by hand. ", function(){
            send_msg("If it is longer than 10 business days please post in our community as you may have submitted with another email address", function() {
            email_confirmed = false;
            $("#message").hide();
            $("#controls").append(
            '<button class="options one" value="certifications" type="button">My Certifications</button>'
            );
            })
          })
          })
        });
      }

The problem occurs when you click the button "my certifications". It calls this conditional

My Certs conditional

//If user has certification issues
if (b_val == 'certifications'){
    send_msg('Awesome! Did you know we have over 75,000 certified users?', function(){
    send_msg('Please select which area of the certification process you are having trouble with', function(){
        $("#controls").append(
        '<button class="options one" value="practicum" type="button">Practicum status</button>' +
        '<button class="options one" value="exams" type="button">Exam issues</button>' +
        '<button class="options one" value="badges" type="button">Badge problems</button>'
        );
    })
  })
}

This is how I execute my clicks

  // Pushes user's selected values as text chats
  $("#controls").on("click", ".options", function() {
    // Remove buttons on click
    $("#controls button.options").remove();
    var text = $(this).text();
    var b_val = $(this).val();

    // Set user's name in front of each message
    var userName = " Me: ";
    var newMsg = text;

    var prevState = $("#conversation").html();
    if (prevState.length > 3) {
      prevState = prevState;
    }
    $("#conversation").html(
      prevState +
        "
" +
        "" +
        newMsg +
        "
"
    );
    // conditional codes
});

Here is my fiddle as well. To see what I am experiencing follow these steps:

enter name

click my certifications

click practicum issues

enter email

click my certifications

EDIT: here is a video of the problem

Body:
In your JSFiddle, you have

  if (email.length > 0 && email_confirmed == true) {
    $("#message").hide();
    send_msg(
      "One second, let me go check and see where your practicum is in the queue.",
      function() {
        send_msg(
          "It looks like your practicum will be graded by {{ DATE }}", function(){
          send_msg("If this seems too long we may be in a bit of a delay as our team grades all these by hand. ", function(){
            send_msg("If it is longer than 10 business days please post in our community as you may have submitted with another email address", function() {
            email_confirmed = false;
            $("#message").hide();
            **$("#controls").append(
            '<button class="options one" value="certifications" type="button">My Certifications</button>'
            );**
            })
          })
          })
        });
      }

After it is done asking, it calls

$("#controls").append(
                '<button class="options one" value="certifications" type="button">My Certifications</button>'
                );

so that in turn calls the same function twice. You want to remove. If you don't want it to go back and starting again.

I hope this helps.


问:
React cannot find entry file in any of the roots update
I have the following warning when running react-native run-ios:

I know that the question was asked before, but the solutions doesn't seem to work for me... I restarted my OS and it's still not working...

Any ideas?

答:
The issue now is with the current version of react-native: 0.45.0.

I downgraded to the 0.44.0 version with react-native-git-upgrade 0.44.0 and it works fine now!


问:
Rails: Can you check the syntax for a simple string comparison method?
It compares the actual password stored in the database (@submission.password) with the password entered by the user from the view (params[:password]).
If they are equal, the submission is deleted.

This is the string comparison method.

```<code>def compare_password
    if @submission.password == params[:password] # This line is wrong.
        @submission = Submission.find(params[:id])
        @submission.destroy
        redirect_to(@submission, :notice => 'Listing deleted successfully')
    else
        redirect_to(@submission, :alert => 'Password is incorrect.')
    end
end
</code>```

This is the view.

```<code><%form_tag "/submissions/compare_password" do%>
<%=text_field_tag :password, params[:password]%>
<%=submit_tag "Delete"%>
<%end%>
</code>```

Execution error I get is this.

```<code>undefined method `password' for nil:NilClass
</code>```

edit

Originally my routes.rb looked like this

```<code>resources :submissions do
    collection do

        post :compare_password
    end
end
</code>```

Now I changed to

```<code>resources :submissions do
    member do

        post :compare_password
    end
end
</code>```

答:
@submission is nil - you need to find this before checking the password value - </p>

```<code>def compare_password
    @submission = Submission.find(params[:id]) # it is nil till you get it here
    if @submission && (@submission.password == params[:password])
        @submission.destroy
        redirect_to(@submission, :notice => 'Listing deleted successfully')
    else
        redirect_to(@submission, :alert => 'Password is incorrect.')
    end
end
</code>```

Body:
It compares the actual password stored in the database (@submission.password) with the password entered by the user from the view (params[:password]).
If they are equal, the submission is deleted.

This is the string comparison method.

def compare_password
    if @submission.password == params[:password] # This line is wrong.
        @submission = Submission.find(params[:id])
        @submission.destroy
        redirect_to(@submission, :notice => 'Listing deleted successfully')
    else
        redirect_to(@submission, :alert => 'Password is incorrect.')
    end
end

This is the view.

<%form_tag "/submissions/compare_password" do%>
<%=text_field_tag :password, params[:password]%>
<%=submit_tag "Delete"%>
<%end%>

Execution error I get is this.

undefined method `password' for nil:NilClass

edit

Originally my routes.rb looked like this

resources :submissions do
    collection do

        post :compare_password
    end
end

Now I changed to

resources :submissions do
    member do

        post :compare_password
    end
end

Body:
@submission is nil - you need to find this before checking the password value -

def compare_password
    @submission = Submission.find(params[:id]) # it is nil till you get it here
    if @submission && (@submission.password == params[:password])
        @submission.destroy
        redirect_to(@submission, :notice => 'Listing deleted successfully')
    else
        redirect_to(@submission, :alert => 'Password is incorrect.')
    end
end


问:
Codeigniter : array to string conversion error
Here is my model:

```<code>public function count_diabetic(){
    $query = $this->db->query("Select count(diabetic) as count_diabetic from member where diabetic is not NULL");

    return $query->result_array();
}

public function count_hypertensive(){
    $query = $this->db->query("Select count(hypertensive) as count_hypertensive from member where hypertensive is not NULL");

    return $query->result();
}
</code>```

here is my controller:

```<code>public function home(){
             $this->load->model('Jsv_model');
             $data = array(

                'count_diabetic' => $this->Jsv_model->count_diabetic(),
                'count_hypertensive' => $this->Jsv_model->count_hypertensive()

             );

             $this->session->set_userdata($data);

            $this->load->view('home');
    }
</code>```

Here is my view with in php tag:

```<code> echo $this->session->userdata('count_diabetic');
</code>```

But Here it shows error that array to string conversion error..
please help me

答:
In PHP, you can display arrays by using the print_r function instead of echo.

For example, you have to change your code to:

```<code>print_r($this->session->userdata['count_diabetic']);
</code>```

Body:
Here is my model:

public function count_diabetic(){
    $query = $this->db->query("Select count(diabetic) as count_diabetic from member where diabetic is not NULL");

    return $query->result_array();
}

public function count_hypertensive(){
    $query = $this->db->query("Select count(hypertensive) as count_hypertensive from member where hypertensive is not NULL");

    return $query->result();
}

here is my controller:

public function home(){
             $this->load->model('Jsv_model');
             $data = array(

                'count_diabetic' => $this->Jsv_model->count_diabetic(),
                'count_hypertensive' => $this->Jsv_model->count_hypertensive()

             );

             $this->session->set_userdata($data);

            $this->load->view('home');
    }

Here is my view with in php tag:

 echo $this->session->userdata('count_diabetic');

But Here it shows error that array to string conversion error..
please help me

Body:
In PHP, you can display arrays by using the print_r function instead of echo.

For example, you have to change your code to:

print_r($this->session->userdata['count_diabetic']);


问:
Get schema name from a properties file
I'm having an issue at the moment that I've been doing alot of searching on but still havent found an answer.

Backgorund of problem: We have multiple DB schemas at the one URL including test copies of schemas (e.g schema1, schema2, schema1_test, schema2_test are all at the same url). I'm trying to make which version of each schema is used configurable via a properties file.

We are using Spring and mybatis, and unfortunately i'm new to both (so please excuse my ignorance or any mistakes i make describing the issue!)

So in my spring config file, which is stored under /src/main/resources, I have the following snippets:
(I only added "configLocation" property and later added "sqlSessionFactoryBeanName" property)

```<code><!-- define the SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="typeAliasesPackage" value="com.example.domain" />
    <property name="configLocation" value="classpath:mybatisConfig.xml" />
</bean>

<!-- scan for mappers and let them be autowired -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.example.something.persistence" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</code>```

My mybatisConfig.xml (which is stored under /src/main/resources, which should be on the class path)

```<code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="sqlmapconfig.properties" />
</configuration>
</code>```

sqlmapconfig.properties (in same folder)

```<code>schema1=schema1_test
</code>```

And I try reference the property in one of the mapper files in com.example.something.persistence:

```<code> <select id="test" resultType="result" parameterType="long">
    select ${schema1}.table.col
    from ${schema1}.table
 </select>
</code>```

When I try build with maven it fails a test:

```<code>org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'schema1' in 'class java.lang.Long'
</code>```

Any suggestions would be greatly appreciated!

答:
I had similar issue and managed to do this by creating custom LanguageDriver. Language drivers in mybatis have few hook methods. The interesting one is createSqlSource which is called while loading every defined sql statement. This allows you to modify the statement at this point. The best way to do this is to extend the XMLLanguageDriver which is the default driver which interprets the queries defined in xml files and in annotations.

The first thing to do is to modify your queries by adding some marker which will be replaced with schema (SCHEMA_MARKER is imported from custom laguage driver class which is presented below):

```<code>public interface MyMabatisMapper {
  @Select("select * from " + SCHEMA_MARKER + ".myTable ")
  List<MyObjects> getObjects();
}
</code>```

Now we create custom language driver which will replace the marker with given schema.

Example:

```<code>public class QueriesModifyingDriver extends XMLLanguageDriver {

  public static final String SCHEMA_MARKER = "###MY_SCHEMA###";
  public static final String SCHEMA_MARKER_PATTERN = SCHEMA.replaceAll("#", "\\#");

  private final String schemaName;

  // NOTE: Name of the schema passed in constructor !!!
  public QueriesModifyingDriver(String schemaName) {
    this.schemaName = schemaName;
  }

  @Override
  public SqlSource createSqlSource(org.apache.ibatis.session.Configuration configuration, String script, Class<?> parameterType) {
    String modifiedScript = script.replaceAll(SCHEMA_MARKER_PATTERN, schemaName);

    return super.createSqlSource(configuration, modifiedScript, parameterType);
  }
};
</code>```

Above we passed the name of our schema via constructor to our language driver. Now all we need to do is to install this language driver to mybatis. Example below assumes that Spring is used using annotations configuration. Schema name is read from property my.schema.name, but it can be obtained from any source of course:

```<code>  @Bean
  public SqlSessionFactory mybatisSqlSessionFactory(DataSource dataSource, @Value("${my.schema.name}") String schemaName) throws Exception {

    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);

    org.apache.ibatis.session.Configuration mybatisConfiguration = sqlSessionFactoryBean.getObject().getConfiguration();

    QueriesModifyingDriver queriesModifyingDriver = new QueriesModifyingDriver(schemaName);
    mybatisConfiguration.getLanguageRegistry().register(queriesModifyingDriver);

    mybatisConfiguration.setDefaultScriptingLanguage(QueriesModifyingDriver.class);

    return sqlSessionFactoryBean.getObject();
  }
</code>```

Please note that this is quite effective way because language driver processes every queryonly once (on startup) and this modified queries are later reused by mybatis.

Title: Get schema name from a properties file

Body:
I'm having an issue at the moment that I've been doing alot of searching on but still havent found an answer.

Backgorund of problem: We have multiple DB schemas at the one URL including test copies of schemas (e.g schema1, schema2, schema1_test, schema2_test are all at the same url). I'm trying to make which version of each schema is used configurable via a properties file.

We are using Spring and mybatis, and unfortunately i'm new to both (so please excuse my ignorance or any mistakes i make describing the issue!)

So in my spring config file, which is stored under /src/main/resources, I have the following snippets:
(I only added "configLocation" property and later added "sqlSessionFactoryBeanName" property)

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="typeAliasesPackage" value="com.example.domain" />
    <property name="configLocation" value="classpath:mybatisConfig.xml" />
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.example.something.persistence" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

My mybatisConfig.xml (which is stored under /src/main/resources, which should be on the class path)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="sqlmapconfig.properties" />
</configuration>

sqlmapconfig.properties (in same folder)

schema1=schema1_test

And I try reference the property in one of the mapper files in com.example.something.persistence:

 <select id="test" resultType="result" parameterType="long">
    select ${schema1}.table.col
    from ${schema1}.table
 </select>

When I try build with maven it fails a test:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'schema1' in 'class java.lang.Long'

Any suggestions would be greatly appreciated!

Body:
I had similar issue and managed to do this by creating custom LanguageDriver. Language drivers in mybatis have few hook methods. The interesting one is createSqlSource which is called while loading every defined sql statement. This allows you to modify the statement at this point. The best way to do this is to extend the XMLLanguageDriver which is the default driver which interprets the queries defined in xml files and in annotations.

The first thing to do is to modify your queries by adding some marker which will be replaced with schema (SCHEMA_MARKER is imported from custom laguage driver class which is presented below):

public interface MyMabatisMapper {
  @Select("select * from " + SCHEMA_MARKER + ".myTable ")
  List<MyObjects> getObjects();
}

Now we create custom language driver which will replace the marker with given schema.

Example:

public class QueriesModifyingDriver extends XMLLanguageDriver {

  public static final String SCHEMA_MARKER = "###MY_SCHEMA###";
  public static final String SCHEMA_MARKER_PATTERN = SCHEMA.replaceAll("#", "\\#");

  private final String schemaName;

  // NOTE: Name of the schema passed in constructor !!!
  public QueriesModifyingDriver(String schemaName) {
    this.schemaName = schemaName;
  }

  @Override
  public SqlSource createSqlSource(org.apache.ibatis.session.Configuration configuration, String script, Class<?> parameterType) {
    String modifiedScript = script.replaceAll(SCHEMA_MARKER_PATTERN, schemaName);

    return super.createSqlSource(configuration, modifiedScript, parameterType);
  }
};

Above we passed the name of our schema via constructor to our language driver. Now all we need to do is to install this language driver to mybatis. Example below assumes that Spring is used using annotations configuration. Schema name is read from property my.schema.name, but it can be obtained from any source of course:

  @Bean
  public SqlSessionFactory mybatisSqlSessionFactory(DataSource dataSource, @Value("${my.schema.name}") String schemaName) throws Exception {

    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);

    org.apache.ibatis.session.Configuration mybatisConfiguration = sqlSessionFactoryBean.getObject().getConfiguration();

    QueriesModifyingDriver queriesModifyingDriver = new QueriesModifyingDriver(schemaName);
    mybatisConfiguration.getLanguageRegistry().register(queriesModifyingDriver);

    mybatisConfiguration.setDefaultScriptingLanguage(QueriesModifyingDriver.class);

    return sqlSessionFactoryBean.getObject();
  }

Please note that this is quite effective way because language driver processes every queryonly once (on startup) and this modified queries are later reused by mybatis.


问:
How to define two angular apps / modules in one page?
I'm trying to add two angular apps / modules to one page.
In the fiddles below you can see that always only the first module, referenced in the html code, will work correctly, whereas the second is not recognized by angular.

In this fiddle we can only execute the doSearch2 method, whereas in this fiddle only the doSearch method works correctly.

I'm looking for the way how to correctly place two angular modules into one page.

答:
I made a POC for an Angular application using multiple modules and router-outlets to nest sub apps in a single page app.
You can get the source code at: https://github.com/AhmedBahet/ng-sub-apps

Hope this will help


问:
Java static method vs function
What is difference between this codes in java 8 :

This  :

```<code>public class Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}
</code>```

and this :

```<code>public interface Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}
</code>```

This is main class :

```<code>public class MainClass {
    public static void main(String[] args) {
            Hello.sayHello(); //for function
            Hello.sayHello(); //for class
    }
}
</code>```

答:
There is no difference between the two.

The first example shows a static method implemented in a class while the second one shows a static method implemented in an interface. The second example wouldn't compile if you use JDK 7 or below because as others have already said, static method support in interfaces was only added in Java 8. Here is a very useful StackOverflow article that explains why the support for static and default methods in interfaces was added in Java 8.

The choice of whether you want to keep your static method, which may be a utility method, in a class or an interface, depends on the circumstances. E.g. if you want to add a new common method to a set of classes that do not extend a common base class but do implement a common interface. You might add the common method to the interface since there is no common base class.

Title: Java static method vs function

Body:
What is difference between this codes in java 8 :

This  :

public class Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}

and this :

public interface Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}

This is main class :

public class MainClass {
    public static void main(String[] args) {
            Hello.sayHello(); //for function
            Hello.sayHello(); //for class
    }
}


问:
How to use PDFkit library with webpack?
I want to print some pdf documents programmatically. and I'm trying for hours now to make this PDFkit library working with webpack.

I've gone form:

Can't resolve 'fs' in ..

to

fs.readFileSync is not a function

then to the warning

```<code>[BABEL] Note: The code generator has deoptimised the styling of "E:/MyProjects/accountingsystem/node_modules/brotli/dec/dictionary-da
ta.js" as it exceeds the max of "500KB".
</code>```

then to

require is not defined - i'm stuck here. All this errors are coming form within the library itself.

I have just one file - app.js with just a single line of code, which is:

const PDFDocument = require('pdfkit');

My final webpack.config.js looks like this:

```<code>module.exports = {
// devtool: 'source-map',

entry: './src/app.js',
output: {
    path: path.resolve (__dirname, "dist"),
    filename: "bundle.js"
},

// node: {
//     console: true,
//     fs: 'empty',
//     net: 'empty',
//     tls: 'empty'
// },

// i've added 'target' - following the advice form some github comments.
target: 'node',
module : {
    rules : [
        { test: /\.js$/, loader: 'babel-loader' },
        {
            test : /\.html$/,
            use : [ 'html-loader' ]
        },

        // then i've added this 2 loaders also:
        { test: /\.json$/, loader: 'json-loader' },
        { test: /pdfkit|png-js/, loader: "transform-loader?brfs" }
    ]
},
plugins:[
    new HtmlWebpackPlugin ({
          template : `src/app.html`
    })
],
</code>```

};

This is literally a 1 line app, and i'm hitting the wall for hours now. I've seen that many users are having issues with fs core module and webpack - and i tried every solution i could find. How hard can it be? What is actually happening here? Any insight is appreciated, Thanks.

答:
It's possible to make it work with webpack.

pdfmake is a wrapper around pdfkit which works with webpack. As you can see, the webpack.config.js is kind of hacky:

https://github.com/bpampuch/pdfmake/blob/master/webpack.config.js

Personally, I ended up working with pdfmake, which provides a built js file.
I you do so, you will have to tweak your webpack.config, use the resolve.alias field to point to the pdfmake built js file.

Title: How to use PDFkit library with webpack?

Body:
I want to print some pdf documents programmatically. and I'm trying for hours now to make this PDFkit library working with webpack.

I've gone form:

Can't resolve 'fs' in ..

to

fs.readFileSync is not a function

then to the warning

[BABEL] Note: The code generator has deoptimised the styling of "E:/MyProjects/accountingsystem/node_modules/brotli/dec/dictionary-da
ta.js" as it exceeds the max of "500KB".

then to

require is not defined - i'm stuck here. All this errors are coming form within the library itself.

I have just one file - app.js with just a single line of code, which is:

const PDFDocument = require('pdfkit');

My final webpack.config.js looks like this:

module.exports = {
// devtool: 'source-map',

entry: './src/app.js',
output: {
    path: path.resolve (__dirname, "dist"),
    filename: "bundle.js"
},

// node: {
//     console: true,
//     fs: 'empty',
//     net: 'empty',
//     tls: 'empty'
// },

// i've added 'target' - following the advice form some github comments.
target: 'node',
module : {
    rules : [
        { test: /\.js$/, loader: 'babel-loader' },
        {
            test : /\.html$/,
            use : [ 'html-loader' ]
        },

        // then i've added this 2 loaders also:
        { test: /\.json$/, loader: 'json-loader' },
        { test: /pdfkit|png-js/, loader: "transform-loader?brfs" }
    ]
},
plugins:[
    new HtmlWebpackPlugin ({
          template : `src/app.html`
    })
],

};

This is literally a 1 line app, and i'm hitting the wall for hours now. I've seen that many users are having issues with fs core module and webpack - and i tried every solution i could find. How hard can it be? What is actually happening here? Any insight is appreciated, Thanks.


问:
Zend Forms - Element ID modification to allow re-use
I have a Zend_Form object that I want to re-use several times in one page.  The problem I'm having is that each time it's rendered it has the same element IDs.  I've been unable to find a method for giving all the IDs a unique prefix or suffix each time I render the form.

Complete Solution

Subclass Zend_Form:

```<code>class My_Form extends Zend_Form
{
    protected $_idSuffix = null;

    /**
     * Set form and element ID suffix
     *
     * @param string $suffix
     * @return My_Form
     */
    public function setIdSuffix($suffix)
    {
        $this->_idSuffix = $suffix;
        return $this;
    }

    /**
     * Render form
     *
     * @param Zend_View_Interface $view
     * @return string
     */
    public function render(Zend_View_Interface $view = null)
    {
        if (!is_null($this->_idSuffix)) {
            // form
            $formId = $this->getId();
            if (0 < strlen($formId)) {
                $this->setAttrib('id', $formId . '_' . $this->_idSuffix);
            }

            // elements
            $elements = $this->getElements();
            foreach ($elements as $element) {
                $element->setAttrib('id', $element->getId() . '_' . $this->_idSuffix);
            }
        }

        return parent::render($view);
    }
}
</code>```

Loop in the view script:

```<code><?php foreach ($this->rows as $row) : ?>
    <?php echo $this->form->setDefaults($row->toArray())->setIdSuffix($row->id); ?>
<?php endforeach; ?>
</code>```

答:
You may subclass Zend_Form and overload render method to generate id's automatically:

```<code>public function render()
{
    $elements = $this->getElements();
    foreach ($elements as $element) {
        $element->setAttrib('id', $this->getName() . '_' . $element->getId();
    }
}
</code>```

This is just a pseudo-code. Of course, you may modify this to suit your needs.

Body:
I have a Zend_Form object that I want to re-use several times in one page.  The problem I'm having is that each time it's rendered it has the same element IDs.  I've been unable to find a method for giving all the IDs a unique prefix or suffix each time I render the form.

Complete Solution

Subclass Zend_Form:

class My_Form extends Zend_Form
{
    protected $_idSuffix = null;

    /**
     * Set form and element ID suffix
     *
     * @param string $suffix
     * @return My_Form
     */
    public function setIdSuffix($suffix)
    {
        $this->_idSuffix = $suffix;
        return $this;
    }

    /**
     * Render form
     *
     * @param Zend_View_Interface $view
     * @return string
     */
    public function render(Zend_View_Interface $view = null)
    {
        if (!is_null($this->_idSuffix)) {
            // form
            $formId = $this->getId();
            if (0 < strlen($formId)) {
                $this->setAttrib('id', $formId . '_' . $this->_idSuffix);
            }

            // elements
            $elements = $this->getElements();
            foreach ($elements as $element) {
                $element->setAttrib('id', $element->getId() . '_' . $this->_idSuffix);
            }
        }

        return parent::render($view);
    }
}

Loop in the view script:

<?php foreach ($this->rows as $row) : ?>
    <?php echo $this->form->setDefaults($row->toArray())->setIdSuffix($row->id); ?>
<?php endforeach; ?>

Body:
You may subclass Zend_Form and overload render method to generate id's automatically:

public function render()
{
    $elements = $this->getElements();
    foreach ($elements as $element) {
        $element->setAttrib('id', $this->getName() . '_' . $element->getId();
    }
}

This is just a pseudo-code. Of course, you may modify this to suit your needs.


问:
Detect UIWebView links without click
I was wondering is there any possible way to detect a link in UIWebView without click on  urls ? for example if page has PDF file automatically get its link. I know with webview's delegate I can detect clicked urls like this :

```<code>  func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {

        if navigationType == .linkClicked
        {
            print(request.url?.absoluteString)
        }
        return true
    }
</code>```

but is there any possible way to detect links without click ?

答:
You can use NSDataDetector for link types NSTextCheckingResult.CheckingType.link. You just need to download your url data and get all the link matches from it:

```<code>extension String {
    var detectURLs: [URL] {
        return (try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue))?
            .matches(in: self, range: NSRange(location: 0, length: utf16.count))
            .compactMap{ $0.url } ?? []
    }
}
extension Data {
    var string: String { return String(data: self, encoding: .utf8) ?? "" }
}
</code>```

Playground Testing:

```<code>import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

// add the extensions above here

URLSession.shared.dataTask(with: URL(string: "http://www.example.com/downloads/")!) { data, response, error in
    guard let data = data, error == nil else { return }
    let pdfs = data.string.detectURLs.filter{$0.pathExtension.lowercased() == "pdf"}

    print(pdfs)  // print(urls)  // "[http://www.sample-videos.com/pdf/Sample-pdf-5mb.pdf]\n"
}.resume()
</code>```

Title: Detect UIWebView links without click

Body:
I was wondering is there any possible way to detect a link in UIWebView without click on  urls ? for example if page has PDF file automatically get its link. I know with webview's delegate I can detect clicked urls like this :

  func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {

        if navigationType == .linkClicked
        {
            print(request.url?.absoluteString)
        }
        return true
    }

but is there any possible way to detect links without click ?

Body:
You can use NSDataDetector for link types NSTextCheckingResult.CheckingType.link. You just need to download your url data and get all the link matches from it:

extension String {
    var detectURLs: [URL] {
        return (try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue))?
            .matches(in: self, range: NSRange(location: 0, length: utf16.count))
            .compactMap{ $0.url } ?? []
    }
}
extension Data {
    var string: String { return String(data: self, encoding: .utf8) ?? "" }
}

Playground Testing:

import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

// add the extensions above here

URLSession.shared.dataTask(with: URL(string: "http://www.example.com/downloads/")!) { data, response, error in
    guard let data = data, error == nil else { return }
    let pdfs = data.string.detectURLs.filter{$0.pathExtension.lowercased() == "pdf"}

    print(pdfs)  // print(urls)  // "[http://www.sample-videos.com/pdf/Sample-pdf-5mb.pdf]\n"
}.resume()

ContentLicense: CC BY-SA 4.0


问:
EF6, Code First. How to set alternative data source for GridControl column using XAML Devexpress
I have two related entities:

```<code>public class Event
{
    public string ID { get; set; }
    public DateTime EventDate { get; set; }
    public string EventData { get; set; }
    public string DocID1 { get; set; }
    public int DocID2 { get; set; }
    public virtual Document Document1 { get; set; }
    public virtual Document Document2 { get; set; }

}

public class Document
{

    public string ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Number { get; set; }

}
</code>```

Also created List to display data in WPF:

```<code>private ObservableCollection<Event> eventList;
public ObservableCollection<Event> EventList
        {
            get { return eventList; }
            set
            {
                if (value != eventList)
                {
                    eventList = value;
                }
                RaisePropertyChanged(nameof(EventList));
            }
        }
</code>```

data for my EventList is taken from entity Event:

```<code>var query = DBContext.Events.Select(x => x).AsQueryable();
EventList = query.ToList();
</code>```

What I need is how to set GridControl Column "colFirstName" value to be equal "Document1.FirstName" if DocID1 is not null and "Document2.FirstName" if DocID2 is not null. My XAML code for GridControl is below, could You help how to do it in Xaml, not in ViewModel, or if there is no way to do it in Xaml, what is the best way to do it in ViewModel.

```<code><dxg:GridControl AutoPopulateColumns="False"
ItemsSource="{Binding EventList, UpdateSourceTrigger=PropertyChanged}">

                        <dxg:GridControl.Columns>
                            <dxg:GridColumn
                                x:Name="colEventData"
                                Width="120"
                                FieldName="EventData"
                                 Header =" Event data"
                                Visible="True" >
                        </dxg:GridColumn>

                        <dxg:GridColumn
                                x:Name="colFirsnName"
                                Width="120"
                                FieldName="Document1.FirstName"
                                Header="First Name"
                                Visible="True"
                                VisibleIndex="1" />
                          </dxg:GridControl.Columns>
                        </dxg:GridControl>
</code>```

答:
You can use the UnboundExpression property to create a column with a custom expression. For example, to conditionally show values from different properties, use the Iif function:

```<code><dxg:GridColumn FieldName="CustomColumn" x:Name="colFirsnName"
                UnboundExpression="Iif(IsNullOrEmpty([DocID1]), [Document2.FirstName], [Document1.FirstName])"
                UnboundType="String"/>
</code>```

Body:
I have two related entities:

public class Event
{
    public string ID { get; set; }
    public DateTime EventDate { get; set; }
    public string EventData { get; set; }
    public string DocID1 { get; set; }
    public int DocID2 { get; set; }
    public virtual Document Document1 { get; set; }
    public virtual Document Document2 { get; set; }

}

public class Document
{

    public string ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Number { get; set; }

}

Also created List to display data in WPF:

private ObservableCollection<Event> eventList;
public ObservableCollection<Event> EventList
        {
            get { return eventList; }
            set
            {
                if (value != eventList)
                {
                    eventList = value;
                }
                RaisePropertyChanged(nameof(EventList));
            }
        }

data for my EventList is taken from entity Event:

var query = DBContext.Events.Select(x => x).AsQueryable();
EventList = query.ToList();

What I need is how to set GridControl Column "colFirstName" value to be equal "Document1.FirstName" if DocID1 is not null and "Document2.FirstName" if DocID2 is not null. My XAML code for GridControl is below, could You help how to do it in Xaml, not in ViewModel, or if there is no way to do it in Xaml, what is the best way to do it in ViewModel.

<dxg:GridControl AutoPopulateColumns="False"
ItemsSource="{Binding EventList, UpdateSourceTrigger=PropertyChanged}">

                        <dxg:GridControl.Columns>
                            <dxg:GridColumn
                                x:Name="colEventData"
                                Width="120"
                                FieldName="EventData"
                                 Header =" Event data"
                                Visible="True" >
                        </dxg:GridColumn>

                        <dxg:GridColumn
                                x:Name="colFirsnName"
                                Width="120"
                                FieldName="Document1.FirstName"
                                Header="First Name"
                                Visible="True"
                                VisibleIndex="1" />
                          </dxg:GridControl.Columns>
                        </dxg:GridControl>

Body:
You can use the UnboundExpression property to create a column with a custom expression. For example, to conditionally show values from different properties, use the Iif function:

<dxg:GridColumn FieldName="CustomColumn" x:Name="colFirsnName"
                UnboundExpression="Iif(IsNullOrEmpty([DocID1]), [Document2.FirstName], [Document1.FirstName])"
                UnboundType="String"/>


问:
jQuery filter data by color with option of multiselect
I am trying to create multiselect filter that can filter data by color.
For example when "Black" is selected only black has to be shown or when "Black" is deselected then all colors should be displayed, or if "Black" and "Blue" is selected then black and blue should be displayed.

Filter HTML

```<code><ul id="color-filter">
    <li data-filter="black">Black</li>
    <li data-filter="blue">Blue</li>
    <li data-filter="brown">Brown</li>
</ul>
</code>```

Page Body HTML

```<code><div class="material-tiles">
    <div class="grid-3 samples" data-color="black" data-popularity="0">
    ....
    </div>
    <div class="grid-3 samples" data-color="black" data-popularity="0">
    ....
    </div>
    <div class="grid-3 samples" data-color="blue" data-popularity="0">
    ....
    </div>
    <div class="grid-3 samples" data-color="blue" data-popularity="0">
    ....
    </div>
    <div class="grid-3 samples" data-color="blue" data-popularity="0">
    ....
    </div>
    <div class="grid-3 samples" data-color="brown" data-popularity="0">
    ....
    </div>
</div>
</code>```

jQuery

```<code>//Materials filter selector script//
    function checkboxSellector (obj) {
        var formCheckbox = obj.find('.form-checkmark');
        var checkBox = obj.find('.checkbox');
        $(function() {
            $(formCheckbox).click(function() {
                $(this).closest(formCheckbox).toggleClass('is-selected');
                $(this).find(checkBox).toggleClass('checkmark');
            });
        });
    }
    checkboxSellector($(this));

function onGridChangeRequest() {
        $('.material-tiles > .samples').each(function(key, item) {
            item = $(item);
            if (validateByColor(item, selectedColor) && validateByType(item, selectedMaterial)) {
                item.show();
            } else {
                item.hide();
            }
        });
    }
    $('#color-filter > li').on('click', function(e) {
        selectedColor = $(this).data('filter');
        onGridChangeRequest();
    });
</code>```

The filter that I currently have can only select one color at a time and will not reset if unselected, I have tried to change it, but have not much experience with jQuery or javascript.

Help Please.

答:
```<code>var $colorFilter = $('#color-filter'),
    $materialTiles = $('.material-tiles'),
    selected = [];

function onGridChangeRequest() {
   selected = [];
   $colorFilter.find('.selected').each(function(i, el) {
     selected.push($(this).attr('data-filter'));
   })

   $materialTiles.find('.samples').each(function(i, el) {
      if(selected.length) {
        if (selected.indexOf($(el).attr('data-color')) !== -1) {
          $(el).show();
          return;
       }
       $(el).hide();
       return;
      }
      $(el).show();
   })
}

$('#color-filter > li').on('click', function(e) {
  $(this).toggleClass('selected');
  onGridChangeRequest();
});
</code>```

this is the best thing that i can think of. study the code so you would learn how it works. :D

Body:
I am trying to create multiselect filter that can filter data by color.
For example when "Black" is selected only black has to be shown or when "Black" is deselected then all colors should be displayed, or if "Black" and "Blue" is selected then black and blue should be displayed.

Filter HTML

Black

Blue

Brown

Page Body HTML

    ....

    ....

    ....

    ....

    ....

    ....

jQuery

//Materials filter selector script//
    function checkboxSellector (obj) {
        var formCheckbox = obj.find('.form-checkmark');
        var checkBox = obj.find('.checkbox');
        $(function() {
            $(formCheckbox).click(function() {
                $(this).closest(formCheckbox).toggleClass('is-selected');
                $(this).find(checkBox).toggleClass('checkmark');
            });
        });
    }
    checkboxSellector($(this));

function onGridChangeRequest() {
        $('.material-tiles > .samples').each(function(key, item) {
            item = $(item);
            if (validateByColor(item, selectedColor) && validateByType(item, selectedMaterial)) {
                item.show();
            } else {
                item.hide();
            }
        });
    }
    $('#color-filter > li').on('click', function(e) {
        selectedColor = $(this).data('filter');
        onGridChangeRequest();
    });

The filter that I currently have can only select one color at a time and will not reset if unselected, I have tried to change it, but have not much experience with jQuery or javascript.

Help Please.

Body:
var $colorFilter = $('#color-filter'),
    $materialTiles = $('.material-tiles'),
    selected = [];

function onGridChangeRequest() {
   selected = [];
   $colorFilter.find('.selected').each(function(i, el) {
     selected.push($(this).attr('data-filter'));
   })

   $materialTiles.find('.samples').each(function(i, el) {
      if(selected.length) {
        if (selected.indexOf($(el).attr('data-color')) !== -1) {
          $(el).show();
          return;
       }
       $(el).hide();
       return;
      }
      $(el).show();
   })
}

$('#color-filter > li').on('click', function(e) {
  $(this).toggleClass('selected');
  onGridChangeRequest();
});

this is the best thing that i can think of. study the code so you would learn how it works. :D


问:
Exclude certain env vars from artifactory publish
I have a Gradle build script which puts some artifacts in Artifactory. I am passing the Artifactory credentials as environment variables (windows only shop). Is there any way to control that certain enviromental variables DO NOT get published by the clientConfig.setIncludeEnvVars? Obviously, I want to hide those Artifactory credentials.
I have tried some Ant-style exclude patterns, but it either doesn't work, or I have some syntax problem:

```<code>clientConfig.setIncludeEnvVars(true, excludes: ['*PASS*'])
</code>```

How the plugin is configured in the script:

```<code>artifactory {
    contextUrl = "${artifactory_contextUrl}"
    publish {
        repository {
            repoKey = 'maven-~~~'
            username = System.env.ARTIFACTORY_USER ? System.env.ARTIFACTORY_USER : ${artifactory_user}
            password = System.env.ARTIFACTORY_PASS ? System.env.ARTIFACTORY_PASS : ${artifactory_password}
            maven = true
            defaults {
                publications('mavenJava')
                publishArtifacts = true
                publishBuildInfo = true
                publishPom = true
                publishIvy = false
            }
        }
    }
    resolve {
        repository {
            repoKey = 'maven-d~~~'
            username = System.env.ARTIFACTORY_USER ? System.env.ARTIFACTORY_USER : ${artifactory_user}
            password = System.env.ARTIFACTORY_PASS ? System.env.ARTIFACTORY_PASS : ${artifactory_password}
            maven = true
        }
    }
    clientConfig.setIncludeEnvVars(false) // caution: true exposes passwords which are envs!
}
</code>```

答:
clientConfig.setIncludeEnvVars() accepts a boolean values and control whether to include the env vars as part of the build info.

You should use either:

```<code>clientConfig.setEnvVarsExcludePatterns('*password*,*secret*')
</code>```

or

```<code>clientConfig.setEnvVarsIncludePatterns('*not-secret*')
</code>```

Both methods accepts a string which contains a comma delimited set of patterns. The patterns use star (*) as a wildcard.

Body:
I have a Gradle build script which puts some artifacts in Artifactory. I am passing the Artifactory credentials as environment variables (windows only shop). Is there any way to control that certain enviromental variables DO NOT get published by the clientConfig.setIncludeEnvVars? Obviously, I want to hide those Artifactory credentials.
I have tried some Ant-style exclude patterns, but it either doesn't work, or I have some syntax problem:

clientConfig.setIncludeEnvVars(true, excludes: ['*PASS*'])

How the plugin is configured in the script:

artifactory {
    contextUrl = "${artifactory_contextUrl}"
    publish {
        repository {
            repoKey = 'maven-~~~'
            username = System.env.ARTIFACTORY_USER ? System.env.ARTIFACTORY_USER : ${artifactory_user}
            password = System.env.ARTIFACTORY_PASS ? System.env.ARTIFACTORY_PASS : ${artifactory_password}
            maven = true
            defaults {
                publications('mavenJava')
                publishArtifacts = true
                publishBuildInfo = true
                publishPom = true
                publishIvy = false
            }
        }
    }
    resolve {
        repository {
            repoKey = 'maven-d~~~'
            username = System.env.ARTIFACTORY_USER ? System.env.ARTIFACTORY_USER : ${artifactory_user}
            password = System.env.ARTIFACTORY_PASS ? System.env.ARTIFACTORY_PASS : ${artifactory_password}
            maven = true
        }
    }
    clientConfig.setIncludeEnvVars(false) // caution: true exposes passwords which are envs!
}

Body:
clientConfig.setIncludeEnvVars() accepts a boolean values and control whether to include the env vars as part of the build info.

You should use either:

clientConfig.setEnvVarsExcludePatterns('*password*,*secret*')

or

clientConfig.setEnvVarsIncludePatterns('*not-secret*')

Both methods accepts a string which contains a comma delimited set of patterns. The patterns use star (*) as a wildcard.


问:
Broadcastreceiver for a downloaded image
Basically I want to set a Broadcastreceiver that gets triggered when the user downloads an image into gallery/phone from chrome, facebook, twitter..etc

when the photo is finished downloading , and the actions is triggered, I want access to the downloaded image for extra work such as editing and stuff..!

I'm thinking this can be accomplished by Broadcastreceiver, that listens for the image and then do the actions that needed..!

I've tried to search for action to be added in the Manifest inside the receiver intent-filter , but I don't which one?

```<code><receiver
    android:enabled="true"
    android:exported="true"
    android:name=".MyReceiver">
    <inent-filter>
       <action android:name="??????"/>
    </inent-filter>
</code>```

I've read almost all the intent action here, but couldn't find the one..!

答:
Older android versions used

```<code><receiver
        android:name=".NewPictureReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.hardware.action.NEW_PICTURE" />
            <data android:mimeType="image/jpeg" />
        </intent-filter>
</receiver>
</code>```

to get informed that the camera has shot a new photo. I do not know if this get also triggered by a downloaded image.

taken from https://github.com/M66B/FineGeotag/ that adds gps data to jpg

This will not work any more with newer android version.

Not a working solution but some hints how to find a solution.

The android media scanner updates the android internal media database and you can register an image-contentprovder-observer that tells your that media database MediaStore.Images.Media.EXTERNAL_CONTENT_URI has changed. you can query then the media db order by last modify date descending. The top rows should be the new images.

Body:
Basically I want to set a Broadcastreceiver that gets triggered when the user downloads an image into gallery/phone from chrome, facebook, twitter..etc

when the photo is finished downloading , and the actions is triggered, I want access to the downloaded image for extra work such as editing and stuff..!

I'm thinking this can be accomplished by Broadcastreceiver, that listens for the image and then do the actions that needed..!

I've tried to search for action to be added in the Manifest inside the receiver intent-filter , but I don't which one?

<receiver
    android:enabled="true"
    android:exported="true"
    android:name=".MyReceiver">
    <inent-filter>
       <action android:name="??????"/>
    </inent-filter>

I've read almost all the intent action here, but couldn't find the one..!

Body:
Older android versions used

<receiver
        android:name=".NewPictureReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.hardware.action.NEW_PICTURE" />
            <data android:mimeType="image/jpeg" />
        </intent-filter>
</receiver>

to get informed that the camera has shot a new photo. I do not know if this get also triggered by a downloaded image.

taken from https://github.com/M66B/FineGeotag/ that adds gps data to jpg

This will not work any more with newer android version.

Not a working solution but some hints how to find a solution.

The android media scanner updates the android internal media database and you can register an image-contentprovder-observer that tells your that media database MediaStore.Images.Media.EXTERNAL_CONTENT_URI has changed. you can query then the media db order by last modify date descending. The top rows should be the new images.