问:
manually entering option fields based on the number of option
I need your help.I need to enter some elements(words) based on the number of elements.This element number is given as option.for example if the option chosen is 4, 4 empty fields should appear,where the elements to be filled. Can anyone help me?</p>

答:
You can do this all via JavaScript/HTML.

document.getElementById("create").addEventListener("click", function () {
  var container = document.getElementById("container");

  for (var i = 0, len = document.getElementById('fields').value; i < len; i++) {
    var inputElement = document.createElement('input');
    inputElement.type = "text";
    container.appendChild(inputElement)
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Fields needed: <input type="text" id="fields" value="4" /><br />
<button id="create">create</button>
<div id="container">

</div></code>```

If you're interested in jQuery:

$("#create").click(function () {
  $container = $('#container');
  for (var i = 0, len = parseInt($("#fields").val()); i < len; i++) {
    $('<input>')
      .attr('type','text')
      .appendTo($container);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fields needed: <input type="text" id="fields" value="9" /><br />
<button id="create">create</button>
<div id="container">

</div></code>```

Body:
You can do this all via JavaScript/HTML.

document.getElementById("create").addEventListener("click", function () {
  var container = document.getElementById("container");

  for (var i = 0, len = document.getElementById('fields').value; i < len; i++) {
    var inputElement = document.createElement('input');
    inputElement.type = "text";
    container.appendChild(inputElement)
  }
});

Fields needed: <input type="text" id="fields" value="4" /><br />
<button id="create">create</button>
<div id="container">

</div>

If you're interested in jQuery:

$("#create").click(function () {
  $container = $('#container');
  for (var i = 0, len = parseInt($("#fields").val()); i < len; i++) {
    $('<input>')
      .attr('type','text')
      .appendTo($container);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fields needed: <input type="text" id="fields" value="9" /><br />
<button id="create">create</button>
<div id="container">

</div>


来源: stackexchange

问:
Android paired Bluetooth disappears when device reboots
I want the connected device to get BluetoothDevice device information without scanning Bluetooth, so I store all Bluetooth-connected devices.

However, while other devices behave as expected, one type of Bluetooth devices will lose their paired information when the phone is rebooted.

Do anyone know why this may happen or have an alternative way to obtain Bluetooth Device information without scanning?

答:
You can use BluetoothAdapter.

```<code>BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(mac);
device.connectGatt(mContext, false, mGattCallback);

// TODO your code
</code>```

If the bluetooth device is not around, in BluetoothGattCallback's onConnectionStateChange will report BluetoothGatt.STATE_DISCONNECTED.

BluetoothDevice's creator has packages scope. But the source code of BluetoothAdapter's getRemoteDevice is:

```<code>public BluetoothDevice getRemoteDevice(String address) {
    return new BluetoothDevice(address);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use BluetoothAdapter.

BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(mac);
device.connectGatt(mContext, false, mGattCallback);

// TODO your code

If the bluetooth device is not around, in BluetoothGattCallback's onConnectionStateChange will report BluetoothGatt.STATE_DISCONNECTED.

BluetoothDevice's creator has packages scope. But the source code of BluetoothAdapter's getRemoteDevice is:

public BluetoothDevice getRemoteDevice(String address) {
    return new BluetoothDevice(address);
}


问:
How to call two tags at same time on active: to make changes in css
I'm having a little problem. As, I'm currently working on a left side menu, and am trying to call the two tags li and a at the same time on :active in css. I searched a lot but couldn't get anything working for me. What I want is to change the color of the whole row of li and a on :active (when the user clicks on the button).

Here is my code:

.sub-menu li,
a:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-list">
  <ul id="menu-content" class="menu-content collapse out">
    <li data-toggle="collapse" class="collapsed">
      <a><i class="<?=$MainObj['Icon'];?>" style="color:#9f9e9e !important"></i><?=$MainObj['GroupMenuName'];?> <span class="arrow" style="color:#9f9e9e !important">
    </span></a>
      <ul class="sub-menu collapse" id="a">
        <li>check1</li>
        <li>check2</li>
        <li>check3</li>
        <li>check4</li>
      </ul>
    </li>

    <li>

        <i class="fa fa-user fa-lg" style="color:#9f9e9e !important"></i> Profile

    </li>

    <li>

        <i class="fa fa-users fa-lg" style="color:#9f9e9e !important"></i> Users

    </li>
  </ul>
  <span class="collapse-expand" data-ember-action="" data-ember-action-1815="1815"></span>

</div></code>```

答:
Declare your :active pseudo-state rule on the containing parent list item element, then just allow your nested anchor tag to inherit the styles of the parent.

```<code>.sub-menu li:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}

.sub-menu li a {
  color: inherit;
}
</code>```

.sub-menu li:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}

.sub-menu li a {
  color: inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-list">
  <ul id="menu-content" class="menu-content collapse out">
    <li data-toggle="collapse" class="collapsed">
      <a><i class="<?=$MainObj['Icon'];?>" style="color:#9f9e9e !important"></i><?=$MainObj['GroupMenuName'];?> <span class="arrow" style="color:#9f9e9e !important">
    </span></a>
      <ul class="sub-menu collapse" id="a">
        <li>check1</li>
        <li>check2</li>
        <li>check3</li>
        <li>check4</li>
      </ul>
    </li>

    <li>

        <i class="fa fa-user fa-lg" style="color:#9f9e9e !important"></i> Profile

    </li>

    <li>

        <i class="fa fa-users fa-lg" style="color:#9f9e9e !important"></i> Users

    </li>
  </ul>
  <span class="collapse-expand" data-ember-action="" data-ember-action-1815="1815"></span>

</div></code>```

Body:
I'm having a little problem. As, I'm currently working on a left side menu, and am trying to call the two tags li and a at the same time on :active in css. I searched a lot but couldn't get anything working for me. What I want is to change the color of the whole row of li and a on :active (when the user clicks on the button).

Here is my code:

.sub-menu li,
a:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}

      <i class="<?=$MainObj['Icon'];?>" style="color:#9f9e9e !important"><?=$MainObj['GroupMenuName'];?>

check1

check2

check3

check4

         Profile

         Users

Body:
Declare your :active pseudo-state rule on the containing parent list item element, then just allow your nested anchor tag to inherit the styles of the parent.

.sub-menu li:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}

.sub-menu li a {
  color: inherit;
}

.sub-menu li:active {
  color: #f1f1f1 !important;
  background-color: #2e8fda !important;
}

.sub-menu li a {
  color: inherit;
}

<div class="menu-list">
  <ul id="menu-content" class="menu-content collapse out">
    <li data-toggle="collapse" class="collapsed">
      <a><i class="<?=$MainObj['Icon'];?>" style="color:#9f9e9e !important"></i><?=$MainObj['GroupMenuName'];?> <span class="arrow" style="color:#9f9e9e !important">
    </span></a>
      <ul class="sub-menu collapse" id="a">
        <li><a href="#">check1</a></li>
        <li><a href="#">check2</a></li>
        <li><a href="#">check3</a></li>
        <li><a href="#">check4</a></li>
      </ul>
    </li>

    <li>
      <a href="#">
        <i class="fa fa-user fa-lg" style="color:#9f9e9e !important"></i> Profile
      </a>
    </li>

    <li>
      <a href="#">
        <i class="fa fa-users fa-lg" style="color:#9f9e9e !important"></i> Users
      </a>
    </li>
  </ul>
  <span class="collapse-expand" data-ember-action="" data-ember-action-1815="1815"></span>

</div>


问:
Parse Approved-By from git log or git show
Using --pretty=format, you can format git log or git show stdout as you like.

```<code>git log \
--pretty=format:'{%n  "commit": "%H",%n  "author": "%an <%ae>",%n  "date": "%ad",%n  "message": "%f"%n},' \
$@ | \
perl -pe 'BEGIN{print "["}; END{print "]\n"}' | \
perl -pe 's/},]/}]/'
</code>```

Example above parses author, commit, date, message values. How can we parse the value of Approved-by which is available when a pull-request is approved.

Even the official documentation does not mention that

答:
Approved-by is not a builtin field so Git doesn't have a placeholder for it. We could use other methods to get the fields and format the output.

Suppose the Approved-by line looks like:

Approved-by: Someone Nice

Here is a bash sample:

```<code>for commit in $(git log --pretty=%H);do
  echo -e "{\n\
    \"commit\": \"$commit\",\n\
    \"author\": \"$(git log -1 $commit --pretty=%an)\",\n\
    \"date\": \"$(git log -1 $commit --pretty=%cd)\",\n\
    \"message\": \"$(git log -1 $commit --pretty=%f)\",\n\
    \"approved-by\": \"$(git log -1 $commit --pretty=%b | grep Approved-by | awk -F ': ' '{print $NF","}' | xargs echo | sed -e 's/,$//')\"\n\
},"
done | \
perl -pe 'BEGIN{print "["}' | \
sed -e '$s/},/}]/'
</code>```

It needs improvement to meet your real needs, especially the \"approved-by\" line. Basically it gets all the commit sha1 values first and then parse them to get the fields of each commit and then format the output.

Body:
Using --pretty=format, you can format git log or git show stdout as you like.

git log \
--pretty=format:'{%n  "commit": "%H",%n  "author": "%an <%ae>",%n  "date": "%ad",%n  "message": "%f"%n},' \
$@ | \
perl -pe 'BEGIN{print "["}; END{print "]\n"}' | \
perl -pe 's/},]/}]/'

Example above parses author, commit, date, message values. How can we parse the value of Approved-by which is available when a pull-request is approved.

Even the official documentation does not mention that

Body:
Approved-by is not a builtin field so Git doesn't have a placeholder for it. We could use other methods to get the fields and format the output.

Suppose the Approved-by line looks like:

Approved-by: Someone Nice

Here is a bash sample:

for commit in $(git log --pretty=%H);do
  echo -e "{\n\
    \"commit\": \"$commit\",\n\
    \"author\": \"$(git log -1 $commit --pretty=%an)\",\n\
    \"date\": \"$(git log -1 $commit --pretty=%cd)\",\n\
    \"message\": \"$(git log -1 $commit --pretty=%f)\",\n\
    \"approved-by\": \"$(git log -1 $commit --pretty=%b | grep Approved-by | awk -F ': ' '{print $NF","}' | xargs echo | sed -e 's/,$//')\"\n\
},"
done | \
perl -pe 'BEGIN{print "["}' | \
sed -e '$s/},/}]/'

It needs improvement to meet your real needs, especially the \"approved-by\" line. Basically it gets all the commit sha1 values first and then parse them to get the fields of each commit and then format the output.


问:
How to use basic auth with username, password plus token in angular 4
I have developed a form using Angular 4. In that form i have to send the form data using the post method using Angular 4. For that, i have tested with Postman and the data is coming properly. I have to use the Authorization type as Basic Auth with username and password.

And in the headers, i have to pass Content-Type as application/hal+json, Authorization as Basic  and X-CSRF-Token as  and lastly in the body i have to send some raw json data. Please have a look at the below screens shared.

So using Angular how to achieve this? Can anybody help mein this? I am struck at this point to achieve this.

The form which i have used is a dialog box:

```<code><div class="container">
<app-dialog [(visible)]="showDialog">
    <form class="form-horizontal">
    <div style="background-color:#363636; color:#ffffff; padding: 7px;
    margin: -12px -12px 12px -12px;">ADD NEW INVOICE</div>
    <div><label>Request ID *</label><input type="text"></div>
    <div><label>Date *</label>

      <my-date-picker name="mydate" [options]="myDatePickerOptions"
      required></my-date-picker>

    </div>
    <div><label>Category *</label></div>
    <div><label>Details *</label></div>
    <div><label>Job (Optional)*</label></div>
    <div><label>Select Upload</label>
  <p>
    Single: <input type="checkbox" name="uploadtype" value="single" />
    Weekly: <input type="checkbox" checked name="uploadtype" value="weekly" />
    Monthly: <input type="checkbox" name="uploadtype" value="monthly" /><br />
  </p>
    </div>
    <div>Upload Document *: <span>
      <input type="file" name="pic" accept="image/*">

    </span></div>
    <div>Amount *</div>
    <button type="submit" class="btn btn-success" (click)="onSubmit()">Submit</button>
  </form>
  </app-dialog>
</div>
</code>```

So my question is how do i send the form data to server.

The service i have created is:

```<code>private headers = new Headers();
    headers.append("Authorization", "Basic " + btoa(username + ":" + password));
    headers.append("Content-Type", "application/x-www-form-urlencoded");
    getInvoiceDetails(){
            let headers = new Headers();
            this.createAuthorizationHeader(headers);
            return this.http.get(this.config.apiUrl + 'api/supplier-invoice/121', { headers: headers })
            .map(response => response.json());
        }
</code>```

I am very much puzzled about this as i am very novice user to this Angular and authentication concept. Can anyone help me?

答:
Use Post request if you want send data in body and I am also seeing the postman screen shot as post requestion but in the code you are using get request. PFB the sample code for post request</p>

```<code>registerUser(registration: RegistrationTO): Promise<String> {
    let headers = new Headers();
    let body = JSON.stringify(
      {
        "userName": registration.userId,
        "emailId": registration.emailId,
        "userId": registration.userId
      }
    );
    headers.append('Content-Type', 'application/json');
    let params:URLSearchParams = new URLSearchParams();
    let requestOption: RequestOptionsArgs =
      {search: params,  headers: headers };
    return this.http
      .post(RegistrationUrl, body, requestOption)
      .toPromise()
      .then(res => res.json())
      .catch((err)=>{
        this.handleError(err);
      });
  }
</code>```

Body:
I have developed a form using Angular 4. In that form i have to send the form data using the post method using Angular 4. For that, i have tested with Postman and the data is coming properly. I have to use the Authorization type as Basic Auth with username and password.

And in the headers, i have to pass Content-Type as application/hal+json, Authorization as Basic  and X-CSRF-Token as  and lastly in the body i have to send some raw json data. Please have a look at the below screens shared.

So using Angular how to achieve this? Can anybody help mein this? I am struck at this point to achieve this.

The form which i have used is a dialog box:

<app-dialog [(visible)]="showDialog">
    <form class="form-horizontal">

ADD NEW INVOICE

Request ID *<input type="text">

Date *

      <my-date-picker name="mydate" [options]="myDatePickerOptions"
      required></my-date-picker>

Category *

Details *

Job (Optional)*

Select Upload

    Single: <input type="checkbox" name="uploadtype" value="single" />
    Weekly: <input type="checkbox" checked name="uploadtype" value="weekly" />
    Monthly: <input type="checkbox" name="uploadtype" value="monthly" />

Upload Document *:
      <input type="file" name="pic" accept="image/*">

Amount *

    <button type="submit" class="btn btn-success" (click)="onSubmit()">Submit</button>
  </form>
  </app-dialog>

So my question is how do i send the form data to server.

The service i have created is:

private headers = new Headers();
    headers.append("Authorization", "Basic " + btoa(username + ":" + password));
    headers.append("Content-Type", "application/x-www-form-urlencoded");
    getInvoiceDetails(){
            let headers = new Headers();
            this.createAuthorizationHeader(headers);
            return this.http.get(this.config.apiUrl + 'api/supplier-invoice/121', { headers: headers })
            .map(response => response.json());
        }

I am very much puzzled about this as i am very novice user to this Angular and authentication concept. Can anyone help me?

Body:
Use Post request if you want send data in body and I am also seeing the postman screen shot as post requestion but in the code you are using get request. PFB the sample code for post request

registerUser(registration: RegistrationTO): Promise<String> {
    let headers = new Headers();
    let body = JSON.stringify(
      {
        "userName": registration.userId,
        "emailId": registration.emailId,
        "userId": registration.userId
      }
    );
    headers.append('Content-Type', 'application/json');
    let params:URLSearchParams = new URLSearchParams();
    let requestOption: RequestOptionsArgs =
      {search: params,  headers: headers };
    return this.http
      .post(RegistrationUrl, body, requestOption)
      .toPromise()
      .then(res => res.json())
      .catch((err)=>{
        this.handleError(err);
      });
  }


问:
Get visual studio debug event in VS extension
How do I write an extension to Visual Studio that will run during debug?
I saw kinds of UI or code editor options, but not the software events.</p>

答:
DTE.Events.DebuggerEvents gives you access to VS debugger events:</p>

```<code>    events = DTE.Events;
    debuggerEvents = events.DebuggerEvents;
    debuggerEvents.OnEnterRunMode += OnEnterRunMode;
</code>```

Body:
DTE.Events.DebuggerEvents gives you access to VS debugger events:

    events = DTE.Events;
    debuggerEvents = events.DebuggerEvents;
    debuggerEvents.OnEnterRunMode += OnEnterRunMode;


问:
AngularJS dropdown select input with predetermined or custom input options
I'm trying to make a dropdown md-select input box filled with a few pre-determined options, but I also would like the user to be able to type in their own options.

I'm close here in this Plunkr, but I can't quite get it to work right. I'm having two issues:

When the user selects the "other..." option, the dropdown collapses before they have time to enter anything.

Even if I sneak in an entry before the dropdown closes, I can't get my value to persist and show up.

The HTML:

```<code><div layout="row">
    <md-select ng-model="ctrl.userCountry">
      <md-option>
        <em>None</em>
      </md-option>
      <md-option value="india">india</md-option>
      <md-option value="china">bangladesh</md-option>
      <md-option ng-blur="ctrl.customEntry({{customText}})">
        <input placeholder="other..." ng-model="customText" type="text">
      </md-option>
      </md-select>
  </div>
</code>```

The js file:

```<code>var app = angular.module('app', ["ngMaterial"]);
app.controller('AppCtrl', function($scope) {

  this.userCountry = 'india';

  this.customEntry = function(input) {
   userCountry = input;
  };

});
</code>```

Any suggestions?

答:
Try this solution, where input is already focused, when md-select have expanded, so user can select plain md-option, just clicking on it, as always do, or immediately start to type #other option into input, then he will click on it or outside, at both cases, value will be assigned to  userCountry:

HTML:

```<code><body ng-controller="AppCtrl as ctrl">
  <div layout="row">
    <md-select ng-model="ctrl.userCountry" ng-click='ctrl.focus()'>
      <md-option>
        <em>None</em>
      </md-option>
      <md-option value="india">india</md-option>
      <md-option value="china">bangladesh</md-option>
      <md-option ng-click='ctrl.optionClick(temp)'>
        <input id='other' placeholder="other..." type="text" ng-model='temp' ng-change='ctrl.customEntry(temp)'>
      </md-option>
      </md-select>
  </div>

  <div layout="row">
    return value: {{ctrl.userCountry}}
  </div>
</body>
</code>```

Javascript:

```<code>var app = angular.module('app', ["ngMaterial"]);
app.controller('AppCtrl', function($scope, $timeout) {
  self = this;
  this.userCountry = 'india';

  this.customEntry = function(input) {
   this.userCountry = input;
  };

  this.optionClick = function(input) {
    $timeout(function(){
      self.userCountry = input;
    }, 100);
  };

  this.focus = function(){
    setTimeout(function(){
      document.getElementById("other").focus();
    }, 100);
  }

});
</code>```

Body:
I'm trying to make a dropdown md-select input box filled with a few pre-determined options, but I also would like the user to be able to type in their own options.

I'm close here in this Plunkr, but I can't quite get it to work right. I'm having two issues:

When the user selects the "other..." option, the dropdown collapses before they have time to enter anything.

Even if I sneak in an entry before the dropdown closes, I can't get my value to persist and show up.

The HTML:

    <md-select ng-model="ctrl.userCountry">
      <md-option>
        None
      </md-option>
      <md-option value="india">india</md-option>
      <md-option value="china">bangladesh</md-option>
      <md-option ng-blur="ctrl.customEntry({{customText}})">
        <input placeholder="other..." ng-model="customText" type="text">
      </md-option>
      </md-select>

The js file:

var app = angular.module('app', ["ngMaterial"]);
app.controller('AppCtrl', function($scope) {

  this.userCountry = 'india';

  this.customEntry = function(input) {
   userCountry = input;
  };

});

Any suggestions?

Body:
Try this solution, where input is already focused, when md-select have expanded, so user can select plain md-option, just clicking on it, as always do, or immediately start to type #other option into input, then he will click on it or outside, at both cases, value will be assigned to  userCountry:

HTML:

<body ng-controller="AppCtrl as ctrl">
  <div layout="row">
    <md-select ng-model="ctrl.userCountry" ng-click='ctrl.focus()'>
      <md-option>
        <em>None</em>
      </md-option>
      <md-option value="india">india</md-option>
      <md-option value="china">bangladesh</md-option>
      <md-option ng-click='ctrl.optionClick(temp)'>
        <input id='other' placeholder="other..." type="text" ng-model='temp' ng-change='ctrl.customEntry(temp)'>
      </md-option>
      </md-select>
  </div>

  <div layout="row">
    return value: {{ctrl.userCountry}}
  </div>
</body>

Javascript:

var app = angular.module('app', ["ngMaterial"]);
app.controller('AppCtrl', function($scope, $timeout) {
  self = this;
  this.userCountry = 'india';

  this.customEntry = function(input) {
   this.userCountry = input;
  };

  this.optionClick = function(input) {
    $timeout(function(){
      self.userCountry = input;
    }, 100);
  };

  this.focus = function(){
    setTimeout(function(){
      document.getElementById("other").focus();
    }, 100);
  }

});


问:
CSS Selector issue with list items
I am facing a problem with CSS selector. I have content in "list Items(LI)" and "list Items(LI)" having class"child". I need to style for first "list Items(LI)" with the class name ".child". only in CSS.

ul{margin:0;padding:0 32px 0 32px}
li{ color:red;}
.child{
  color:green;
  background:red;
  width:100%;
}
li.child ~ .child{
  color:#fff;
  font-size:20px;
  background:green;
  width:10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li class="child">
This need to be Red Color
  </li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul></code>```

答: You can try with your class name then next element in it .child > div

Title: CSS Selector issue with list items

Body:
I am facing a problem with CSS selector. I have content in "list Items(LI)" and "list Items(LI)" having class"child". I need to style for first "list Items(LI)" with the class name ".child". only in CSS.

ul{margin:0;padding:0 32px 0 32px}
li{ color:red;}
.child{
  color:green;
  background:red;
  width:100%;
}
li.child ~ .child{
  color:#fff;
  font-size:20px;
  background:green;
  width:10px;
}

hellow

hellow

hellow

hellow

hellow

hellow

hellow

This need to be Red Color

sub text

sub text

sub text


问:
How to call a function after failure of selenium,junit,cucumber and maven project
I have created a java cucumber maven project. Now I want to add a listener or any way so my screenshot capture function invokes if any of cucumber step/Test will fail.

I am not using @RunWith(Cucumber.class) in Junit's TestRunner class. I have integrated @RunWith(ExtendedCucumberRunner.class)

1st try:
Here I tried to override below function in ExtendedCucumberRunner class :-

```<code>import org.junit.runner.notification.Failure;

public void testFailure(Failure failure){
}
</code>```

But If I am trying to override an error is appearing as :

The method testFailure(Failure) of type ExtendedCucumberRunner must
  override or implement a supertype method.

2nd try:

I have also tried to extend RunListener class still it is not working.

The Code I am trying to add Lister is as below:

```<code>import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

import automationframework.AutomationLog;
import automationframework.ScreenshotAndTestNgReporterListener;

public class JUnitExecutionListener extends RunListener{
    /**
     *  Called when an atomic test fails.
     *  https://howtodoinjava.com/junit/how-to-add-listner-in-junit-testcases/
     * */
    @Override
    public void testFailure(Failure failure) throws java.lang.Exception{
        super.testFailure(failure);
        if (!failure.getDescription().isSuite()) {
            ScreenshotAndTestNgReporterListener.customScreenshot();
            AutomationLog.error("In Custom Failer Class of Junit");
            System.out.println("FAILED!!!!!"); //Here pass your screenshot capture event
        }
        ScreenshotAndTestNgReporterListener.customScreenshot();
        AutomationLog.error("In Custom Failer Class of Junit");
        System.out.println("FAILED!!!!!"); //Here pass your screenshot capture event
    }
}
</code>```

3rd try:

I have also tried to add below rule in TestRunner class

```<code>@Rule
public TestWatcher watchman= new TestWatcher() {
    private String watchedLog;
    @Override
    protected void failed(Throwable e, Description description) {
        ScreenshotAndTestNgReporterListener.customScreenshot();
        AutomationLog.error(e.getMessage());
        watchedLog+= description + "\n";
    }

    @Override
    protected void succeeded(Description description) {
        watchedLog+= description + " " + "success!\n";
       }
   };
</code>```

I do not want to add @After method as it will call at every time even if any testcase success.

I want to capture screenshot only if test case fails

Can anyone tell me any way around so I can achieve same?.

答:
As @Grasshopper rightly point out. Use below function once in any of your step definitions. Cucumber will identify the hook and will run below function after each testcase run. In case it fails scenario will run the if condition and you can write any code you want to run after it.

By ref:

Hook up in cucumber check for scenario failure in java

Code:

```<code>@After
public void afterMethod(Scenario scenario) {
    if(scenario.isFailed()) {

    }
}
</code>```

Import:

```<code>import cucumber.api.java.After;
</code>```

Body:
I have created a java cucumber maven project. Now I want to add a listener or any way so my screenshot capture function invokes if any of cucumber step/Test will fail.

I am not using @RunWith(Cucumber.class) in Junit's TestRunner class. I have integrated @RunWith(ExtendedCucumberRunner.class)

1st try:
Here I tried to override below function in ExtendedCucumberRunner class :-

import org.junit.runner.notification.Failure;

public void testFailure(Failure failure){
}

But If I am trying to override an error is appearing as :

The method testFailure(Failure) of type ExtendedCucumberRunner must
  override or implement a supertype method.

2nd try:

I have also tried to extend RunListener class still it is not working.

The Code I am trying to add Lister is as below:

import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

import automationframework.AutomationLog;
import automationframework.ScreenshotAndTestNgReporterListener;

public class JUnitExecutionListener extends RunListener{
    /**
     *  Called when an atomic test fails.
     *  https://howtodoinjava.com/junit/how-to-add-listner-in-junit-testcases/
     * */
    @Override
    public void testFailure(Failure failure) throws java.lang.Exception{
        super.testFailure(failure);
        if (!failure.getDescription().isSuite()) {
            ScreenshotAndTestNgReporterListener.customScreenshot();
            AutomationLog.error("In Custom Failer Class of Junit");
            System.out.println("FAILED!!!!!"); //Here pass your screenshot capture event
        }
        ScreenshotAndTestNgReporterListener.customScreenshot();
        AutomationLog.error("In Custom Failer Class of Junit");
        System.out.println("FAILED!!!!!"); //Here pass your screenshot capture event
    }
}

3rd try:

I have also tried to add below rule in TestRunner class

@Rule
public TestWatcher watchman= new TestWatcher() {
    private String watchedLog;
    @Override
    protected void failed(Throwable e, Description description) {
        ScreenshotAndTestNgReporterListener.customScreenshot();
        AutomationLog.error(e.getMessage());
        watchedLog+= description + "\n";
    }

    @Override
    protected void succeeded(Description description) {
        watchedLog+= description + " " + "success!\n";
       }
   };

I do not want to add @After method as it will call at every time even if any testcase success.

I want to capture screenshot only if test case fails

Can anyone tell me any way around so I can achieve same?.

Body:
As @Grasshopper rightly point out. Use below function once in any of your step definitions. Cucumber will identify the hook and will run below function after each testcase run. In case it fails scenario will run the if condition and you can write any code you want to run after it.

By ref:

Hook up in cucumber check for scenario failure in java

Code:

@After
public void afterMethod(Scenario scenario) {
    if(scenario.isFailed()) {

    }
}

Import:

import cucumber.api.java.After;


问:
SQLAlchemy Session handling in a multi thread app
I define my data model on module level like this

```<code>from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('cx_oracle://username:password@dsn')
Session = sessionmaker(bind=engine)

... data model located on engine
</code>```

and then I start some threads like this

```<code>threads = []

# start threads
for i in range(4):

    # each thread needs it own session
    thread = threading.Thread(target=fn, args=(in, ))
    thread.start()
    threads.append(thread)

# wait for threads to finish
for thread in threads:
    thread.join()
</code>```

where fn(in) is some method where I use session = Session(), which are then used for various purposes.

With this I get various errors, which only occurs sometimes. It can be

DatabaseError: (cx_Oracle.DatabaseError) DPI-1002: invalid OCI handle

DBAPIError: (sqlalchemy.exc.ResourceClosedError) This Connection is closed

InvalidRequestError: Session is already flushing

I really don't know how to fix this issue though

答: We have been having some similar issues with our application and cx_Oracle 6.x which was updated to use a new C interface to the Oracle OCI (ODPI-C) that has some references to that error in it's release notes. We downgraded cx_Oracle and the issue disappeared.</p>

Body:
I define my data model on module level like this

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('cx_oracle://username:password@dsn')
Session = sessionmaker(bind=engine)

... data model located on engine

and then I start some threads like this

threads = []

# start threads
for i in range(4):

    # each thread needs it own session
    thread = threading.Thread(target=fn, args=(in, ))
    thread.start()
    threads.append(thread)

# wait for threads to finish
for thread in threads:
    thread.join()

where fn(in) is some method where I use session = Session(), which are then used for various purposes.

With this I get various errors, which only occurs sometimes. It can be

DatabaseError: (cx_Oracle.DatabaseError) DPI-1002: invalid OCI handle

DBAPIError: (sqlalchemy.exc.ResourceClosedError) This Connection is closed

InvalidRequestError: Session is already flushing

I really don't know how to fix this issue though


问:
How to save auth tokens in libgdx for Android and iOS?
I am using Bearer token for authentication in my libgdx based app and I am not 100% sure if I am doing it correctly when it comes to saving the auth token. </p>

<p>So libgdx provides Preferences method but I can't anywhere if it is private mode or not. Would it be safe and secure for me to store user auth tokens in libgdx preferences? </p>

答:
It would be save to store the tokens in the preferences as long as the users phone isn't rooted. Because then they have access to the savefiles and every app using root maybe has access too.
So you can use the preferences as long as you encrypt your tokens.</p>

Body:
I am using Bearer token for authentication in my libgdx based app and I am not 100% sure if I am doing it correctly when it comes to saving the auth token.

So libgdx provides Preferences method but I can't anywhere if it is private mode or not. Would it be safe and secure for me to store user auth tokens in libgdx preferences?


问:
android studio, c++, windows, filename too long
I'm building c++ application for android using Android Studio 2.3.3. Build fails with error:

Fatal error: can't create
  CMakeFiles/kore.dir/C_/ab/android-native-build/Sources/src/banan/server/serverData/ServerCompound_banan_server_serverdata_ListValue_IdInt_banan_server_serverdata_ServerCompound_serverdata_ServerAchieve.cpp.o:
  No such file or directory clang++.exe: error: assembler command failed
  with exit code 1 (use -v to see invocation)

The directory in which this file should be created exists and some other files were successfully created there.

I think this is because of path is too long. I've seen such messages previously and moving project to another directory with shorter path have solved the issue. But now I've already done this.

答: shorter your project location because path maximum 256 char long is accepted.</p>


问:
git hooks / pre-receive - how to get all the commit messages on a newly created branch?
i' d like to get all the commit messages (like with git log --format=%s) on a newly created branch. Let' s suppose i' ve 2 commits:

```<code>abcd - from yesterday
bcde - from today
</code>```

. With this code:

```<code>while read old new ref; do
    ....
done
</code>```

old will be 40 zeros, and new will be bcde. How can i get all the commit messages in this case?

Usecase:

```<code>git checkout master
git checkout -b new_branch
some_work
git add; git commit
some_other_work
git add; git commit
git push origin new_branch
</code>```

.

Many thanks.

答:
Well, i could use this if $old is zero:

```<code>if [ $old = $z40 ]; then
    old=`$(git rev-list --boundary $newrev --not --all | sed -n 's/^-//p'`
fi
</code>```

.

Body:
i' d like to get all the commit messages (like with git log --format=%s) on a newly created branch. Let' s suppose i' ve 2 commits:

abcd - from yesterday
bcde - from today

. With this code:

while read old new ref; do
    ....
done

old will be 40 zeros, and new will be bcde. How can i get all the commit messages in this case?

Usecase:

git checkout master
git checkout -b new_branch
some_work
git add; git commit
some_other_work
git add; git commit
git push origin new_branch

.

Many thanks.

Body:
Well, i could use this if $old is zero:

if [ $old = $z40 ]; then
    old=`$(git rev-list --boundary $newrev --not --all | sed -n 's/^-//p'`
fi

.


问:
Android and getting a view with id cast as a string
In the Java code of an Android project if you want the reference for a view resource you can do something like:

```<code>View addButton = findViewById(R.id.button_0);
</code>```

In the above R.id.button_0 is not a String. Is it possible to dynamically refer to a resource by a string, such as "R.id.button_0"?

I'd like to refer to a button by "R.id.button_%i" where %i is replaced by some valid index.

答:
```<code>int resID = getResources().getIdentifier("button_%i",
    "id", getPackageName());
View addButton = findViewById(resID);
</code>```

where %i is replaced by some valid index.

The getResources() method belongs to the Context class, so you can use that directly from an Activity. If you are not inside an activity, then use a context to access: (myCtxt.getResources()).

ContentLicense: CC BY-SA 2.5

Body:
In the Java code of an Android project if you want the reference for a view resource you can do something like:

View addButton = findViewById(R.id.button_0);

In the above R.id.button_0 is not a String. Is it possible to dynamically refer to a resource by a string, such as "R.id.button_0"?

I'd like to refer to a button by "R.id.button_%i" where %i is replaced by some valid index.

Body:
int resID = getResources().getIdentifier("button_%i",
    "id", getPackageName());
View addButton = findViewById(resID);

where %i is replaced by some valid index.

The getResources() method belongs to the Context class, so you can use that directly from an Activity. If you are not inside an activity, then use a context to access: (myCtxt.getResources()).


问:
(Python) Rtree intersection and fiona questions
I'm trying to create a function for an intersection where the input file is of some urban area, and a query box is used to create an output file that has the intersection containing just the buildings found in that query box. </p>

```<code>import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.basemap import Basemap
import fiona
import fiona.crs
import rtree

input_file = 'se_england_clean.shp'
out_file = 'se_england_out'
file_index = 'Rtree_index_east.idx'

query_box = [-0.0957870483,51.5134165224,-0.08664608,51.5192383994]

def write_clipped_file(name_file_in, out_file, file_index):
 idx = rtree.index.Index(file_index)
 idx.insert(0, (input_file))
 list(idx.intersection((query_box)))[0]
 count = 0
 with fiona.open(input_file, 'w') as out_file :  #?
    for building in out_file: #?
</code>```

<p>No idea if my code is right so far, but I have two immediate problems:
First, I don't know how to open with Fiona the input shapefile and the new (clipped) shapefile that I want to produce in output. I want to cycle the list of indices, select the desired buildings, and write them in the new file 'out_file'. Second, I get an error: </p>

```<code> RTreeError: Coordinates must be in the form (minx, miny, maxx, maxy)
</code>```

答:
```<code>idx.insert(0, (input_file))
</code>```

You need to insert coordinates into the tree, not a file name.

Body:
I'm trying to create a function for an intersection where the input file is of some urban area, and a query box is used to create an output file that has the intersection containing just the buildings found in that query box.

import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.basemap import Basemap
import fiona
import fiona.crs
import rtree

input_file = 'se_england_clean.shp'
out_file = 'se_england_out'
file_index = 'Rtree_index_east.idx'

query_box = [-0.0957870483,51.5134165224,-0.08664608,51.5192383994]

def write_clipped_file(name_file_in, out_file, file_index):
 idx = rtree.index.Index(file_index)
 idx.insert(0, (input_file))
 list(idx.intersection((query_box)))[0]
 count = 0
 with fiona.open(input_file, 'w') as out_file :  #?
    for building in out_file: #?

No idea if my code is right so far, but I have two immediate problems:
First, I don't know how to open with Fiona the input shapefile and the new (clipped) shapefile that I want to produce in output. I want to cycle the list of indices, select the desired buildings, and write them in the new file 'out_file'. Second, I get an error:

 RTreeError: Coordinates must be in the form (minx, miny, maxx, maxy)

Body:
idx.insert(0, (input_file))

You need to insert coordinates into the tree, not a file name.


问:
How do I return the previous Sunday from 7 days ago using PHP date()?
Here is what I have so far:

```<code>$date = date('Y-m-d h:i:s', strtotime('-7 days'));
$start = date('Y-m-d h:i:s', strtotime($date,'previous Sunday'));
</code>```

When outputting $start, it returns: 1969-12-31 06:00:00

What am I doing wrong?

答:
$date needs to e a timestamp

```<code>$date = strtotime('-7 days');
$start = date('Y-m-d h:i:s', strtotime('previous Sunday',$date));
</code>```

Body:
Here is what I have so far:

$date = date('Y-m-d h:i:s', strtotime('-7 days'));
$start = date('Y-m-d h:i:s', strtotime($date,'previous Sunday'));

When outputting $start, it returns: 1969-12-31 06:00:00

What am I doing wrong?

Body:
$date needs to e a timestamp

$date = strtotime('-7 days');
$start = date('Y-m-d h:i:s', strtotime('previous Sunday',$date));


问:
FancyImpute installation in Anaconda
I was trying to install fancyimpute library on my Windows system. I am using Spyder on the Anaconda Navigator. I have tried the following on the command prompt as Administrator, still it shows

```<code>ModuleNotFoundError: No module named 'fancyimpute'

conda install -c https://conda.binstar.org/eswears cvxopt
pip install keras
pip install fancyimpute
Also installed Visual C++ Compiler for Python 2.7
I am using Python 3.6.1
</code>```

Kindly help :)

答: you can do pip install fancyimpute-0.0.4.tar.gz to install the package after downloading fancyimpute-0.0.4.tar.gz. </p>

Title: FancyImpute installation in Anaconda

Body:
I was trying to install fancyimpute library on my Windows system. I am using Spyder on the Anaconda Navigator. I have tried the following on the command prompt as Administrator, still it shows

ModuleNotFoundError: No module named 'fancyimpute'

conda install -c https://conda.binstar.org/eswears cvxopt
pip install keras
pip install fancyimpute
Also installed Visual C++ Compiler for Python 2.7
I am using Python 3.6.1

Kindly help :)


问:
How to handle xamarin android push notification click handler when application is not running on backgroud
I am try to navigate to specific screen when user click on push notification. It's works fine when application is running in background but when I remove application from background while click on push notification it is navigate to first page of the application instead of specific page. Please suggest any idea to navigate to specific page when application is not running in background also.</p>

答:
I used below Code and working fine for me

```<code> Intent i = new Intent(context, typeof(SpecificActiivty));
 i.SetFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop);
 PendingIntent intent = PendingIntent.GetActivity(context, 0, i, PendingIntentFlags.UpdateCurrent);
 builder.SetContentIntent(intent);
</code>```

MyEdited Answer

```<code>namespace Example
{
    [Service]
    public class GcmService : GcmServiceBase
    {

        protected override void OnMessage(Context context, Intent intent)
        {
              NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
              Intent i;
              DateTime date = DateTime.Now;
              i = new Intent(context, typeof(SpecificActiivty));
              i.SetFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop);
              PendingIntent intent = PendingIntent.GetActivity(context, 0, i, PendingIntentFlags.UpdateCurrent);
              builder.SetContentIntent(intent);
              builder.SetSmallIcon(Resource.Drawable.ic_notificationicon);

              builder.SetAutoCancel(true);
              Notification notification = builder.Build();
              builder.SetSound(Settings.System.DefaultNotificationUri);
              Android.Net.Uri notify = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
              Ringtone r = RingtoneManager.GetRingtone(context, notify);
              r.Play();
              NotificationManager nm = GetSystemService(Context.NotificationService) as NotificationManager;
              int customid = date.Day + date.Month + date.Hour + date.Minute + date.Millisecond;
              nm.Notify(customid, notification);
        }
    }
}
</code>```

Here SpecificActiivty is your specific page which you want to open on the tap of notification

Body:
I used below Code and working fine for me

 Intent i = new Intent(context, typeof(SpecificActiivty));
 i.SetFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop);
 PendingIntent intent = PendingIntent.GetActivity(context, 0, i, PendingIntentFlags.UpdateCurrent);
 builder.SetContentIntent(intent);

MyEdited Answer

namespace Example
{
    [Service]
    public class GcmService : GcmServiceBase
    {

        protected override void OnMessage(Context context, Intent intent)
        {
              NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
              Intent i;
              DateTime date = DateTime.Now;
              i = new Intent(context, typeof(SpecificActiivty));
              i.SetFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop);
              PendingIntent intent = PendingIntent.GetActivity(context, 0, i, PendingIntentFlags.UpdateCurrent);
              builder.SetContentIntent(intent);
              builder.SetSmallIcon(Resource.Drawable.ic_notificationicon);

              builder.SetAutoCancel(true);
              Notification notification = builder.Build();
              builder.SetSound(Settings.System.DefaultNotificationUri);
              Android.Net.Uri notify = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
              Ringtone r = RingtoneManager.GetRingtone(context, notify);
              r.Play();
              NotificationManager nm = GetSystemService(Context.NotificationService) as NotificationManager;
              int customid = date.Day + date.Month + date.Hour + date.Minute + date.Millisecond;
              nm.Notify(customid, notification);
        }
    }
}

Here SpecificActiivty is your specific page which you want to open on the tap of notification


问:
Comment in .blade.php template
I am new in blade template. How i comment here?

PHP i can comment like this

```<code><?php // echo $games;?>
</code>```

Laravel Blade

{{ $game }}

答:
In blade syntax, a comment starts with {{-- and ends with --}}

```<code>{{-- this is a comment --}}
</code>```

But to comment out multiple lines, use standard PHP block comments instead, like:

<?php /*
@if ($condition)
    {{ HTML::form("foo") }};
@endif
*/ ?>
```

And never nest Blade and/or PHP code inside of Blade comments.

See also stackoverflow.com/Why Blade comment causes page to crash?

Title: Comment in .blade.php template

Body:
I am new in blade template. How i comment here?

PHP i can comment like this

<?php // echo $games;?>

Laravel Blade

{{ $game }}

Body:
In blade syntax, a comment starts with {{-- and ends with --}}

{{-- this is a comment --}}

But to comment out multiple lines, use standard PHP block comments instead, like:

<?php /*
@if ($condition)
    {{ HTML::form("foo") }};
@endif
*/ ?>

And never nest Blade and/or PHP code inside of Blade comments.

See also stackoverflow.com/Why Blade comment causes page to crash?

ContentLicense: CC BY-SA 4.0


问:
Hibernate Save Entity to Mysql
Here is my project structure:

I'm trying to save a Patient Entity to my database using hibernate:

PatientController.java

```<code>@RestController
public class PatientController {

    @Autowired
    PatientRepository patientRepository;

    @GetMapping("/patients")
    public List<Patient> getPatients(){

        SessionFactory factory = new Configuration().configure("/com/nbu/projects/dentistappointmentsys/hibernate.cfg.xml")
                .buildSessionFactory();
        Session session = factory.openSession();

        //Add new Patient object
        Patient p1 = new Patient();
        p1.setEmail("lokesh@mail.com");
        p1.setFirstName("lokesh");
        p1.setLastName("gupta");
        p1.setPassword("gupta123");

        //Save the patient in database
        session.save(p1);

        session.flush();
        session.close();

        return patientRepository.findAll();
    }
</code>```

Patient.java

```<code>@Entity
public class Patient {
    @Id
    @GeneratedValue
    Long id;

    String firstName;

    String lastName;

    String email;

    String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Patient(){}

    public Patient(String firstName, String lastName, String email, String password) {

        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
    }
}
</code>```

PatientRepository

public interface PatientRepository extends JpaRepository {
}

hibernate.cfg.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dentist-appointment-sys</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="connection.autocommit">true</property>
        <mapping class="com.nbu.projects.dentistappointmentsys.models.Patient"></mapping>
    </session-factory>
</hibernate-configuration>
</code>```

HibernateUtil

```<code>public class HibernateUtil
{
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory()
    {
        try {

            return new Configuration().configure("/com/nbu/projects/dentistappointmentsys/hibernate.cfg.xml").buildSessionFactory();

        } catch (Throwable ex) {

            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}
</code>```

In the fron end I have an http get like so:

```<code>  public getPatients(): Observable<Patient[]> {
    return this.httpClient.get('patients');
  }
</code>```

So far I was able to read my Patient data from my db, but now that I've tried to update the db I get the This Error

Can anybody tell me what I'm doing wrong, since I'm new to hibernate and I'm probably mistaking in my configuration etc..

答:
You can paste your "hibernate.cfg.xml" file to the src\main\resources\hibernate.cfg.xml:

Then in the HibernateUtil file,please change as below:
return new Configuration().configure().buildSessionFactory().openSession();

Title: Hibernate Save Entity to Mysql

Body:
Here is my project structure:

I'm trying to save a Patient Entity to my database using hibernate:

PatientController.java

@RestController
public class PatientController {

    @Autowired
    PatientRepository patientRepository;

    @GetMapping("/patients")
    public List<Patient> getPatients(){

        SessionFactory factory = new Configuration().configure("/com/nbu/projects/dentistappointmentsys/hibernate.cfg.xml")
                .buildSessionFactory();
        Session session = factory.openSession();

        //Add new Patient object
        Patient p1 = new Patient();
        p1.setEmail("lokesh@mail.com");
        p1.setFirstName("lokesh");
        p1.setLastName("gupta");
        p1.setPassword("gupta123");

        //Save the patient in database
        session.save(p1);

        session.flush();
        session.close();

        return patientRepository.findAll();
    }

Patient.java

@Entity
public class Patient {
    @Id
    @GeneratedValue
    Long id;

    String firstName;

    String lastName;

    String email;

    String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Patient(){}

    public Patient(String firstName, String lastName, String email, String password) {

        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
    }
}

PatientRepository

public interface PatientRepository extends JpaRepository {
}

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dentist-appointment-sys</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="connection.autocommit">true</property>
        <mapping class="com.nbu.projects.dentistappointmentsys.models.Patient"></mapping>
    </session-factory>
</hibernate-configuration>

HibernateUtil

public class HibernateUtil
{
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory()
    {
        try {

            return new Configuration().configure("/com/nbu/projects/dentistappointmentsys/hibernate.cfg.xml").buildSessionFactory();

        } catch (Throwable ex) {

            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}

In the fron end I have an http get like so:

  public getPatients(): Observable<Patient[]> {
    return this.httpClient.get('patients');
  }

So far I was able to read my Patient data from my db, but now that I've tried to update the db I get the This Error

Can anybody tell me what I'm doing wrong, since I'm new to hibernate and I'm probably mistaking in my configuration etc..


问:
could not get input field value in jquery
I am creating an input field using foreach loop like this

```<code><?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
</code>```

$data is Array

```<code>(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)
</code>```

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

```<code><script type="text/javascript">
 $(document).ready(function () {
           var typename = $('#typename').val();
           alert(typename);
});
</script>
</code>```

i have to disable this input field when value is 'Generator'

答:
Element id should be unique. And try it inside on event because dynamically adding elements will not grab ready state.

http://api.jquery.com/live/

Body:
I am creating an input field using foreach loop like this

<?php foreach($data as $key=>$val) { ?>

<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">

<?php } ?>

$data is Array

(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

i have to disable this input field when value is 'Generator'


问:
Trying to implement a speech to text, don't know what is wrong
New to Android development, trying to implement a speech to text that will print the words on the screen in real time but getting the below error. Can't seem to understand where the problem is. Is it because I am calling the startRecording() and stopRecording() from the togglebutton events or is is it something else entirely.

com.example.android.moviebud E/SpeechRecognizer: not connected to the recognition service

```<code>package com.example.android.moviebud;

import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity implements RecognitionListener {
    ToggleButton recBtn;
    SpeechRecognizer recognizer;
    Intent recognitionIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        recognizer = SpeechRecognizer.createSpeechRecognizer(this);
        recognizer.setRecognitionListener(this);
        recognitionIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recBtn = (ToggleButton) findViewById(R.id.recBtn);
        recBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    recognizer.startListening(recognitionIntent);
                } else {
                    recognizer.stopListening();
                    recognizer.destroy();
                }
            }
        });
    }

    @Override
    public void onReadyForSpeech(Bundle bundle) {
        Toast.makeText(getApplicationContext(), "READY", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBeginningOfSpeech() {
        Toast.makeText(getApplicationContext(), "Speech recognition started", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRmsChanged(float v) {

    }

    @Override
    public void onBufferReceived(byte[] bytes) {

    }

    @Override
    public void onEndOfSpeech() {

    }

    @Override
    public void onError(int i) {
        Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResults(Bundle bundle) {
        TextView v = (TextView) findViewById(R.id.speech);
        StringBuilder sb = new StringBuilder("");
        for (String s : bundle.getStringArrayList(recognizer.RESULTS_RECOGNITION)) {
            sb.append(s);
        }
        v.setText(sb.toString());
    }

    @Override
    public void onPartialResults(Bundle bundle) {

    }

    @Override**strong text**
    public void onEvent(int i, Bundle bundle) {

    }
}
</code>```

答:
Try this code it is working, I have done it.

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPermission();

        final EditText editText = findViewById(R.id.editText);

        final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);

        final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
                Locale.getDefault());

        mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle bundle) {

            }

            @Override
            public void onBeginningOfSpeech() {

            }

            @Override
            public void onRmsChanged(float v) {

            }

            @Override
            public void onBufferReceived(byte[] bytes) {

            }

            @Override
            public void onEndOfSpeech() {

            }

            @Override
            public void onError(int i) {

            }

            @Override
            public void onResults(Bundle bundle) {
                //getting all the matches
                ArrayList<String> matches = bundle
                        .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

                //displaying the first match
                if (matches != null)
                    editText.setText(matches.get(0));
            }

            @Override
            public void onPartialResults(Bundle bundle) {

            }

            @Override
            public void onEvent(int i, Bundle bundle) {

            }
        });

        findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_UP:
                        mSpeechRecognizer.stopListening();
                        editText.setHint("You will see input here");
                        break;

                    case MotionEvent.ACTION_DOWN:
                        mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
                        editText.setText("");
                        editText.setHint("Listening...");
                        break;
                }
                return false;
            }
        });
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                        Uri.parse("package:" + getPackageName()));
                startActivity(intent);
                finish();
            }
        }
    }
}
</code>```

Fore more details you can visit my blog post - Android Speech To Text Tutorial.

Body:
New to Android development, trying to implement a speech to text that will print the words on the screen in real time but getting the below error. Can't seem to understand where the problem is. Is it because I am calling the startRecording() and stopRecording() from the togglebutton events or is is it something else entirely.

com.example.android.moviebud E/SpeechRecognizer: not connected to the recognition service

package com.example.android.moviebud;

import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity implements RecognitionListener {
    ToggleButton recBtn;
    SpeechRecognizer recognizer;
    Intent recognitionIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        recognizer = SpeechRecognizer.createSpeechRecognizer(this);
        recognizer.setRecognitionListener(this);
        recognitionIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recBtn = (ToggleButton) findViewById(R.id.recBtn);
        recBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    recognizer.startListening(recognitionIntent);
                } else {
                    recognizer.stopListening();
                    recognizer.destroy();
                }
            }
        });
    }

    @Override
    public void onReadyForSpeech(Bundle bundle) {
        Toast.makeText(getApplicationContext(), "READY", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBeginningOfSpeech() {
        Toast.makeText(getApplicationContext(), "Speech recognition started", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRmsChanged(float v) {

    }

    @Override
    public void onBufferReceived(byte[] bytes) {

    }

    @Override
    public void onEndOfSpeech() {

    }

    @Override
    public void onError(int i) {
        Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResults(Bundle bundle) {
        TextView v = (TextView) findViewById(R.id.speech);
        StringBuilder sb = new StringBuilder("");
        for (String s : bundle.getStringArrayList(recognizer.RESULTS_RECOGNITION)) {
            sb.append(s);
        }
        v.setText(sb.toString());
    }

    @Override
    public void onPartialResults(Bundle bundle) {

    }

    @Override**strong text**
    public void onEvent(int i, Bundle bundle) {

    }
}

Body:
Try this code it is working, I have done it.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPermission();

        final EditText editText = findViewById(R.id.editText);

        final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);

        final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
                Locale.getDefault());

        mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle bundle) {

            }

            @Override
            public void onBeginningOfSpeech() {

            }

            @Override
            public void onRmsChanged(float v) {

            }

            @Override
            public void onBufferReceived(byte[] bytes) {

            }

            @Override
            public void onEndOfSpeech() {

            }

            @Override
            public void onError(int i) {

            }

            @Override
            public void onResults(Bundle bundle) {
                //getting all the matches
                ArrayList<String> matches = bundle
                        .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

                //displaying the first match
                if (matches != null)
                    editText.setText(matches.get(0));
            }

            @Override
            public void onPartialResults(Bundle bundle) {

            }

            @Override
            public void onEvent(int i, Bundle bundle) {

            }
        });

        findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_UP:
                        mSpeechRecognizer.stopListening();
                        editText.setHint("You will see input here");
                        break;

                    case MotionEvent.ACTION_DOWN:
                        mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
                        editText.setText("");
                        editText.setHint("Listening...");
                        break;
                }
                return false;
            }
        });
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                        Uri.parse("package:" + getPackageName()));
                startActivity(intent);
                finish();
            }
        }
    }
}

Fore more details you can visit my blog post - Android Speech To Text Tutorial.


问:
C# Reflection Property.GetValue() Problem
I am having a problem with the following code:

```<code>int errorCount = 0;
foreach (var cinf in client.GetType().GetProperties())
{
    var vinf = viewModel.GetType().GetProperty(cinf.Name);
    if (vinf != null)
    {
        if (cinf.GetValue(client, null) != vinf.GetValue(viewModel, null))
        {
            errorCount++;
        }
    }
}
</code>```

It's for an automated test to see whether mapping a model object from a DTO has worked.  If I use the more cumbersome approch of writing this for each property:

```<code>Assert.AreEqual(viewModel.ClientCompanyID, client.ClientCompanyID);
</code>```

This works fine.

The problem is: the reflection code evaluates "if val1 != val2" statement incorrectly (or so it seems).  If I step through this code, the evaluation basically says "1 does not equal 1", and incorrectly adds an error.  Furthermore, if I test this with this code, I get the same seemingly false result:

```<code>var clientEx = client.GetType().GetProperty("ClientCompanyID");
var viewModelEx = viewModel.GetType().GetProperty("ClientCompanyID");
var clientVal = clientEx.GetValue(client, null);
var viewModelVal = viewModelEx.GetValue(viewModel, null);
bool test = (clientVal == viewModelVal);
</code>```

The bool returns false even when, stepping through the code, clientVal = 1 and viewModelVal = 1.  See attached picture.

Any help with this would be greatly appreciated!

Thanks guys.

Tim.

EDIT:  Could have given you all the answer.  Glad it was simple in the end.  Thanks alot for your help.  Cheers.

答:
This is only natural. If you compare to objects together using ==, it will compare their reference which is different.

Use objectA.Equals(objectB).

Body:
I am having a problem with the following code:

int errorCount = 0;
foreach (var cinf in client.GetType().GetProperties())
{
    var vinf = viewModel.GetType().GetProperty(cinf.Name);
    if (vinf != null)
    {
        if (cinf.GetValue(client, null) != vinf.GetValue(viewModel, null))
        {
            errorCount++;
        }
    }
}

It's for an automated test to see whether mapping a model object from a DTO has worked.  If I use the more cumbersome approch of writing this for each property:

Assert.AreEqual(viewModel.ClientCompanyID, client.ClientCompanyID);

This works fine.

The problem is: the reflection code evaluates "if val1 != val2" statement incorrectly (or so it seems).  If I step through this code, the evaluation basically says "1 does not equal 1", and incorrectly adds an error.  Furthermore, if I test this with this code, I get the same seemingly false result:

var clientEx = client.GetType().GetProperty("ClientCompanyID");
var viewModelEx = viewModel.GetType().GetProperty("ClientCompanyID");
var clientVal = clientEx.GetValue(client, null);
var viewModelVal = viewModelEx.GetValue(viewModel, null);
bool test = (clientVal == viewModelVal);

The bool returns false even when, stepping through the code, clientVal = 1 and viewModelVal = 1.  See attached picture.

Any help with this would be greatly appreciated!

Thanks guys.

Tim.

EDIT:  Could have given you all the answer.  Glad it was simple in the end.  Thanks alot for your help.  Cheers.


问:
How can I make design as shown in the attached image?

I want to design a screen like this. For displaying the grid items, I am using recycle view. But my concern is how to apply pagination and implement slide for next section of items when user swipe.

In case swipe is not possible, at least on click of the dots below the layout.

答:
You Should Use GridLayoutManager with RecyclerView

GridLayoutManager is a RecyclerView.LayoutManager implementations that lays out items in a grid.

just  set GridLayoutManager  to your  recyclerView.setLayoutManager

```<code>private RecyclerView mRecyclerView;
mRecyclerView = (RecyclerView) findViewById(R.id.collection_recyclerview);
GridLayoutManager  gridLayoutManager = new GridLayoutManager(YourActivity.this, 2);
//                                                           --Context--,--No of Columns--

mRecyclerView.setLayoutManager(gridLayoutManager);
</code>```

tutorial demo of  GridLayoutManager with RecyclerView

Body:
You Should Use GridLayoutManager with RecyclerView

GridLayoutManager is a RecyclerView.LayoutManager implementations that lays out items in a grid.

just  set GridLayoutManager  to your  recyclerView.setLayoutManager

private RecyclerView mRecyclerView;
mRecyclerView = (RecyclerView) findViewById(R.id.collection_recyclerview);
GridLayoutManager  gridLayoutManager = new GridLayoutManager(YourActivity.this, 2);
//                                                           --Context--,--No of Columns--

mRecyclerView.setLayoutManager(gridLayoutManager);

tutorial demo of  GridLayoutManager with RecyclerView


问:
Pip not working in my system,
I am getting the following error while using pip command, in anaconda.

```<code>C:\Users\name>pip install xmlschema
Traceback (most recent call last):
  File "C:\ANACONDA2\Scripts\pip-script.py", line 9, in <module>
    load_entry_point('pip==9.0.1', 'console_scripts', 'pip')()
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 558, in load_entry_point
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2682, in load_entry_point
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2355, in load
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2361, in resolve
  File "c:\anaconda2\lib\site-packages\pip\__init__.py", line 28, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "c:\anaconda2\lib\site-packages\pip\vcs\subversion.py", line 9, in <module>
    from pip.index import Link
  File "c:\anaconda2\lib\site-packages\pip\index.py", line 33, in <module>
    from pip._vendor import html5lib, requests, six
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\__init__.py", line 19, in <module>
    from .serializer import serialize
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\serializer\__init__.py", line 5, in <module>
    from .htmlserializer import HTMLSerializer
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\serializer\htmlserializer.py", line 11, in <module>
    from .. import utils
ImportError: cannot import name utils
</code>```

I am having utils package, but still throwing ImportError: cannot import name utils

答:
you can try this commands to fix it:

```<code> pip uninstall requests
 pip install --upgrade requests
</code>```

if you have trouble about to execute pip command on windows, check this link

Title: Pip not working in my system,

Body:
I am getting the following error while using pip command, in anaconda.

C:\Users\name>pip install xmlschema
Traceback (most recent call last):
  File "C:\ANACONDA2\Scripts\pip-script.py", line 9, in <module>
    load_entry_point('pip==9.0.1', 'console_scripts', 'pip')()
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 558, in load_entry_point
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2682, in load_entry_point
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2355, in load
  File "C:\ANACONDA2\lib\site-packages\setuptools-18.4-py2.7.egg\pkg_resources\__init__.py", line 2361, in resolve
  File "c:\anaconda2\lib\site-packages\pip\__init__.py", line 28, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "c:\anaconda2\lib\site-packages\pip\vcs\subversion.py", line 9, in <module>
    from pip.index import Link
  File "c:\anaconda2\lib\site-packages\pip\index.py", line 33, in <module>
    from pip._vendor import html5lib, requests, six
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\__init__.py", line 19, in <module>
    from .serializer import serialize
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\serializer\__init__.py", line 5, in <module>
    from .htmlserializer import HTMLSerializer
  File "c:\anaconda2\lib\site-packages\pip\_vendor\html5lib\serializer\htmlserializer.py", line 11, in <module>
    from .. import utils
ImportError: cannot import name utils

I am having utils package, but still throwing ImportError: cannot import name utils

Body:
you can try this commands to fix it:

 pip uninstall requests
 pip install --upgrade requests

if you have trouble about to execute pip command on windows, check this link


问:
Adding days to date jquery or JS
I have a select to add days from an input on 'dd/mm/yy' format to show the result in another input, I tried to do this but this is not working.</p>

```<code><input type="text" id="startdate" value="15/11/17">

<select name="Select1" id="days">
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
</select>

<input type="text" id="fdate" value="">

$( "#days" ).change(function() {
var sta = $('#startdate').val()
var sel = parseInt($(this).val())
$('#fdate').val(sta+sel )
});
</code>```

答:
Use setDate to add the days

Demo

$("#days").change(function() {
  var staItems = $('#startdate').val().split("/");
  var date = new Date(  Number(staItems[2]), Number(staItems[1])-1, Number(staItems[0]) );
  date.setDate( date.getDate() + parseInt($(this).val()) );
  $('#fdate').val( date.getDate() + "/" + (date.getMonth() + 1 ) + "/" + date.getYear() )
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="startdate" value="15/11/17">

<select name="Select1" id="days">
<option value="0">0 day</option>
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
<option value="6">6 days</option>
<option value="7">7 days</option>
<option value="8">8 days</option>
</select>

<input type="text" id="fdate" value=""></code>```

Title: Adding days to date jquery or JS

Body:
I have a select to add days from an input on 'dd/mm/yy' format to show the result in another input, I tried to do this but this is not working.

<input type="text" id="startdate" value="15/11/17">

<select name="Select1" id="days">
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
</select>

<input type="text" id="fdate" value="">

$( "#days" ).change(function() {
var sta = $('#startdate').val()
var sel = parseInt($(this).val())
$('#fdate').val(sta+sel )
});

Body:
Use setDate to add the days

Demo

$("#days").change(function() {
  var staItems = $('#startdate').val().split("/");
  var date = new Date(  Number(staItems[2]), Number(staItems[1])-1, Number(staItems[0]) );
  date.setDate( date.getDate() + parseInt($(this).val()) );
  $('#fdate').val( date.getDate() + "/" + (date.getMonth() + 1 ) + "/" + date.getYear() )
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="startdate" value="15/11/17">

<select name="Select1" id="days">
<option value="0">0 day</option>
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
<option value="6">6 days</option>
<option value="7">7 days</option>
<option value="8">8 days</option>
</select>

<input type="text" id="fdate" value="">


问:
Change adaptive brightness level programmatically
How can I change the adaptive brightness level programmatically, on Android Lollipop?

I know how to change the manual brightness level, and to toggle on or off the adaptive brightness. It is done like that:
Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS, newLevel);

However, with adaptive brightness is enabled, the OS combines it with another brightness level which is different than the manual one.

Is there a way to do this?

Target/min/max SDK is 21.

答:
If your app targetSdkVersion is 23+, Settings.System.putFloat(contentResolver, "screen_auto_brightness_adj", value) won't work as Android disables you to modify any "hidden" settings.

Read frameworks\base\packages\SettingsProvider\src\com\android\providers\settings\SettingsProvider.java warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk() for details.


问:
Flat File Connection Manager in SSIS package shows "Valid File Name Must be Selected"
```
                      (Flat File Location)
                    Samba Share | Windows Share
(SSIS)           _______________________________
                |               |
XP 32bit        |  Works        |  Works
                |               |
2003 Serv 32bit |  Works        |  Works
                |               |
Vista 64bit     |  ERROR        |  Works
                |               |
Win 7 64bit     |  ERROR        |  Works
                |               |
2008 Serv 64bit |  ERROR        |  Works
```

I created an SSIS package in VS 2008 that parses a flat file from a shared folder and puts the records into a SQL Server db.

I recently installed Windows 7 and VS 2008 on a new workstation.  When I import the package from TFS and open it, I get the error

Validation error. Parse and Import
  Catalog Flat File: MySSISPackage: The
  file name "\\shared\flatfile.txt"
  specified in the connection was not
  valid.

When I open the Flat File Connection Manager Editor, there is an error stating:

A valid file name must be selected

I can browse to and select the file from inside the editor, but I cannot change any properties, or move away from the General tab because of this error.

If I go back to my laptop (Windows XP), where the package was first created, there is no error.  Both workstations are on the same domain, and I'm logging in using the same credentials.

Any ideas as to why I would receive this error from one workstation and not another?

UPDATE:
If I take the .dtsx package from the running workstation and load it into SSIS on the server, I get the following errors when it tries to run:

Error: The file name "\\shared\flatfile.txt" specified in the connection was not valid.

and...

Error: Connection "MySSISPackage" failed validation.

and...

Error: The file name property is not valid.  The file name is a device or contains invalid characters.

UPDATE 2:

a) The Shared folder I'm trying to pull the flat file from is a Samba share on a Unix box.

b) If I access the file using SSIS on any 64-bit platform (Windows 7 64-bit, Vista 64-bit, Windows Server 2008) I get the error "A valid file name must be selected."

c) Accessing the file using SSIS from 32-bit environments (Windows XP 32-bit, Windows Server 2003 32-bit) there is no problem.

d) If I move the file to a shared folder on a Windows server, 64-bit SSIS recognizes the file.

答: I had a similar problem.  What I did was in Solution Explorer I right-clicked on the project name and selected properties.  I then clicked Debugging and the set the Run64BitRuntime property = 'False'.  The Excel file is 32 bit so running SSIS as a 64 bit application won't work in this scenario.</p>

Body:
                      (Flat File Location)
                    Samba Share | Windows Share
(SSIS)           _______________________________
                |               |
XP 32bit        |  Works        |  Works
                |               |
2003 Serv 32bit |  Works        |  Works
                |               |
Vista 64bit     |  ERROR        |  Works
                |               |
Win 7 64bit     |  ERROR        |  Works
                |               |
2008 Serv 64bit |  ERROR        |  Works

I created an SSIS package in VS 2008 that parses a flat file from a shared folder and puts the records into a SQL Server db.

I recently installed Windows 7 and VS 2008 on a new workstation.  When I import the package from TFS and open it, I get the error

Validation error. Parse and Import
  Catalog Flat File: MySSISPackage: The
  file name "\\shared\flatfile.txt"
  specified in the connection was not
  valid.

When I open the Flat File Connection Manager Editor, there is an error stating:

A valid file name must be selected

I can browse to and select the file from inside the editor, but I cannot change any properties, or move away from the General tab because of this error.

If I go back to my laptop (Windows XP), where the package was first created, there is no error.  Both workstations are on the same domain, and I'm logging in using the same credentials.

Any ideas as to why I would receive this error from one workstation and not another?

UPDATE:
If I take the .dtsx package from the running workstation and load it into SSIS on the server, I get the following errors when it tries to run:

Error: The file name "\\shared\flatfile.txt" specified in the connection was not valid.

and...

Error: Connection "MySSISPackage" failed validation.

and...

Error: The file name property is not valid.  The file name is a device or contains invalid characters.

UPDATE 2:

a) The Shared folder I'm trying to pull the flat file from is a Samba share on a Unix box.

b) If I access the file using SSIS on any 64-bit platform (Windows 7 64-bit, Vista 64-bit, Windows Server 2008) I get the error "A valid file name must be selected."

c) Accessing the file using SSIS from 32-bit environments (Windows XP 32-bit, Windows Server 2003 32-bit) there is no problem.

d) If I move the file to a shared folder on a Windows server, 64-bit SSIS recognizes the file.


问:
how to call a method automatically in every seconds using spring boot?
In Spring-boot project, is there a method that want to make it called every seconds automatically?

And make an rest-api to set calling term in same project?

答:
Here comes an example.

The greeting method will be executed every 5 seconds and it can be called when you visit /hello endpoint.

```<code>@SpringBootApplication
@EnableScheduling
@RestController
public class So47301079 {
    public static void main(String[] args) {
        SpringApplication.run(So47301079.class, args);
    }

    @Scheduled(fixedRate = 5000)
    @GetMapping(value="/hello")
    public void greeting() {
        System.out.println("Hello!!!");
    }
}
</code>```

Hope this helps you!

Body:
Here comes an example.

The greeting method will be executed every 5 seconds and it can be called when you visit /hello endpoint.

@SpringBootApplication
@EnableScheduling
@RestController
public class So47301079 {
    public static void main(String[] args) {
        SpringApplication.run(So47301079.class, args);
    }

    @Scheduled(fixedRate = 5000)
    @GetMapping(value="/hello")
    public void greeting() {
        System.out.println("Hello!!!");
    }
}

Hope this helps you!


问:
PHP round datetime to nearest 5 interval
Following is the requirement, i have given datetime in format

11/14/2017 22:36

it should be round of to the nearest 5 minutes interval like following:

```<code>11/14/2017 22:36  => Output Should be 11/14/2017 22:40
11/14/2017 11:23  => Output Should be 11/14/2017 11:25
</code>```

答:
Thanks to this post https://stackoverflow.com/a/26103014/3481654

The formula for that is

```<code>$time = round(time() / 300) * 300;
</code>```

In complete working code

```<code>function nearest5Mins($time) {
  $time = (round(strtotime($time) / 300)) * 300;
  return date('Y-M-d H:i', $time);
}
echo nearest5Mins('11/14/2017 22:48');
echo "<br>";
echo nearest5Mins('11/14/2017 11:23');
</code>```

 DEMO

Body:
Following is the requirement, i have given datetime in format

11/14/2017 22:36

it should be round of to the nearest 5 minutes interval like following:

11/14/2017 22:36  => Output Should be 11/14/2017 22:40
11/14/2017 11:23  => Output Should be 11/14/2017 11:25

Body:
Thanks to this post https://stackoverflow.com/a/26103014/3481654

The formula for that is

$time = round(time() / 300) * 300;

In complete working code

function nearest5Mins($time) {
  $time = (round(strtotime($time) / 300)) * 300;
  return date('Y-M-d H:i', $time);
}
echo nearest5Mins('11/14/2017 22:48');
echo "<br>";
echo nearest5Mins('11/14/2017 11:23');

 DEMO


问:
R matching of strings and deletion
I have a data frame that has both a list of scores and names corresponding to the scores.  Some individuals appear more than once, but I only want to take the best score from each individual.  A sample of the data frame is provided below.  </p>

```<code>      V1          Names
1574  98.76        Lebron James
1587  98.33        Lebron James
1588  97.32        Lebron James
1713  65.97        Dwyane Wade
1730  100.4        Chris Paul
1734  98.38        Chris Paul
</code>```

<p>So, in the final form of my data frame, all rows would be deleted except for rows 1574, 1713, and 1730 (keeping the highest score for each individual).  What is the best way to go about coding a problem like this one?               </p>

答:
An approach using tidyverse would be:

```<code>library(tidyverse)

df %>%
  group_by(Names) %>%
  summarise(maxd = max(V1))
</code>```

After grouping by Names variable summarize the groups by using the function max on variable V1 and store that in a new variable calling maxd

In base R:

```<code>aggregate(V1 ~ Names, data = df, max)
</code>```

Title: R matching of strings and deletion

Body:
I have a data frame that has both a list of scores and names corresponding to the scores.  Some individuals appear more than once, but I only want to take the best score from each individual.  A sample of the data frame is provided below.

      V1          Names
1574  98.76        Lebron James
1587  98.33        Lebron James
1588  97.32        Lebron James
1713  65.97        Dwyane Wade
1730  100.4        Chris Paul
1734  98.38        Chris Paul

So, in the final form of my data frame, all rows would be deleted except for rows 1574, 1713, and 1730 (keeping the highest score for each individual).  What is the best way to go about coding a problem like this one?

Body:
An approach using tidyverse would be:

library(tidyverse)

df %>%
  group_by(Names) %>%
  summarise(maxd = max(V1))

After grouping by Names variable summarize the groups by using the function max on variable V1 and store that in a new variable calling maxd

In base R:

aggregate(V1 ~ Names, data = df, max)


问:
Convert ntext column to xml and get a node's value in SQL
I want to get a node 'RID' from this xml :

```<code><ts:Status xmlns:ts="DistServices">
<RID>
5ec827e9-0429-4f5a-9d4b-16d3503ff07b
</RID>
<PIN>
5678
</PIN>
</ts:Status>
</code>```

I am using the following query in SQL server 2012:

```<code>DECLARE @data xml
DECLARE @RID varchar(256)
select @data = CAST(CAST(Data AS text) AS XML) from message where index=1
select @data
SET @RID =  @data.value('(/ReplicationStatus/RID)[1]', 'varchar(256)' )
SELECT @RID
</code>```

Here, Data is ntext. I casted it twice from ntext to text and then to xml. Now, I am getting @data in xml format. But RID returned is always null. Can someone help me with this?

答:
You could try after converting ntext data to xml :

```<code>DECLARE @DATA XML = '<ts:Status xmlns:ts="DistServices">
<RID>
5ec827e9-0429-4f5a-9d4b-16d3503ff07b
</RID>
<PIN>
5678
</PIN>
</ts:Status>'

SELECT
       a.value('./RID[1]', 'NVARCHAR(MAX)') [RID],
       a.value('./PIN[1]', 'NVARCHAR(MAX)') [PIN]
       FROM @DATA.nodes ('*') as split(a)
</code>```

Result :

```<code>RID                                   PIN
5ec827e9-0429-4f5a-9d4b-16d3503ff07b  5678
</code>```

Note :
IMPORTANT! ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

Read https://learn.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql

Body:
I want to get a node 'RID' from this xml :

<ts:Status xmlns:ts="DistServices">
<RID>
5ec827e9-0429-4f5a-9d4b-16d3503ff07b
</RID>
<PIN>
5678
</PIN>
</ts:Status>

I am using the following query in SQL server 2012:

DECLARE @data xml
DECLARE @RID varchar(256)
select @data = CAST(CAST(Data AS text) AS XML) from message where index=1
select @data
SET @RID =  @data.value('(/ReplicationStatus/RID)[1]', 'varchar(256)' )
SELECT @RID

Here, Data is ntext. I casted it twice from ntext to text and then to xml. Now, I am getting @data in xml format. But RID returned is always null. Can someone help me with this?

Body:
You could try after converting ntext data to xml :

DECLARE @DATA XML = '<ts:Status xmlns:ts="DistServices">
<RID>
5ec827e9-0429-4f5a-9d4b-16d3503ff07b
</RID>
<PIN>
5678
</PIN>
</ts:Status>'

SELECT
       a.value('./RID[1]', 'NVARCHAR(MAX)') [RID],
       a.value('./PIN[1]', 'NVARCHAR(MAX)') [PIN]
       FROM @DATA.nodes ('*') as split(a)

Result :

RID                                   PIN
5ec827e9-0429-4f5a-9d4b-16d3503ff07b  5678

Note :
IMPORTANT! ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

Read https://learn.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql