问:
trigger onresize in cross browser compatible manner
I would like to trigger the onresize event from my C# code behind. I think this can be done with

```<code>Page.clientScript.RegisterScriptBlock(this.getType(), "id", "javascript code");
</code>```

I have tried element.onresize() but it doesnt seem to work in firefox. What is the correct way to trigger an onresize event similar to the following jQuery?

```<code>$("body").trigger("resize");
</code>```

Using jQuery itself isn't an option.

答:
This should do the trick, DOM Level 2, no idea whether this works in IE6, quirks mode still has no information on this stuff:

```<code>if (document.createEvent) {
    var e = document.createEvent('HTMLEvents');
    e.initEvent('resize', true, false);
    document.body.dispatchEvent(e);

} else if (document.createEventObject) {
    document.body.fireEvent('onresize');
}
</code>```

Tested in FF, Chrome and Opera.

Body:
I would like to trigger the onresize event from my C# code behind. I think this can be done with

Page.clientScript.RegisterScriptBlock(this.getType(), "id", "javascript code");

I have tried element.onresize() but it doesnt seem to work in firefox. What is the correct way to trigger an onresize event similar to the following jQuery?

$("body").trigger("resize");

Using jQuery itself isn't an option.

Body:
This should do the trick, DOM Level 2, no idea whether this works in IE6, quirks mode still has no information on this stuff:

if (document.createEvent) {
    var e = document.createEvent('HTMLEvents');
    e.initEvent('resize', true, false);
    document.body.dispatchEvent(e);

} else if (document.createEventObject) {
    document.body.fireEvent('onresize');
}

Tested in FF, Chrome and Opera.


来源: stackexchange

问:
In a if statement how to concatenate all the messagebox in only one? c#
I have a if statement that prints a messagebox everytime it loops and i want it to print only once, in this case, when the loop ends. And i want to concatenate every information that was printing before in only one messagebox.

Thats my code:

```<code>private void PrintInOrder(Node node) //   In-order
    {
        string nome = "";
        bool flag = false;
        //do
        //{
        //    PrintInOrder(node.lChild);
        //    Console.WriteLine(" " + node.value);
        //    nome += node.value;
        //    PrintInOrder(node.rChild);
        //} while (node != null);
        if (node != null)
        {
            PrintInOrder(node.lChild);
            //Console.WriteLine(" " + node.value);
            //nome += Environment.NewLine + node.value;

            PrintInOrder(node.rChild);
            flag = true;
        }
        if (flag) MessageBox.Show("" + node.value);

    }
</code>```

Thank you.

答:
How about something similar to this???</p>

```<code>private void PrintInOrder(Node node, ref string currentLogMessage)
{
    string nome = "";
    bool flag = false;
    if (node != null)
    {
        PrintInOrder(node.lChild, ref currentLogMessage);
        PrintInOrder(node.rChild, ref currentLogMessage);
        flag = true;
    }
    if (flag) currentLogMessage += node.value + " ";
}

/*****************************************/

var logMessage = "";
PrintInOrder(myNode, ref logMessage);
MessageBox.Show(logMessage);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a if statement that prints a messagebox everytime it loops and i want it to print only once, in this case, when the loop ends. And i want to concatenate every information that was printing before in only one messagebox.

Thats my code:

private void PrintInOrder(Node node) //   In-order
    {
        string nome = "";
        bool flag = false;
        //do
        //{
        //    PrintInOrder(node.lChild);
        //    Console.WriteLine(" " + node.value);
        //    nome += node.value;
        //    PrintInOrder(node.rChild);
        //} while (node != null);
        if (node != null)
        {
            PrintInOrder(node.lChild);
            //Console.WriteLine(" " + node.value);
            //nome += Environment.NewLine + node.value;

            PrintInOrder(node.rChild);
            flag = true;
        }
        if (flag) MessageBox.Show("" + node.value);

    }

Thank you.

Body:
How about something similar to this???

private void PrintInOrder(Node node, ref string currentLogMessage)
{
    string nome = "";
    bool flag = false;
    if (node != null)
    {
        PrintInOrder(node.lChild, ref currentLogMessage);
        PrintInOrder(node.rChild, ref currentLogMessage);
        flag = true;
    }
    if (flag) currentLogMessage += node.value + " ";
}

/*****************************************/

var logMessage = "";
PrintInOrder(myNode, ref logMessage);
MessageBox.Show(logMessage);


问:
ReferenceError: success is not defined - Angularjs
I am getting "ReferenceError: success is not defined" when doing a Restful call from controller to my node.js back end as follows:

authControllers.js:

```<code>authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
  $scope.me = function() {
    UserService.me(function(res) {
      $scope.myDetails = res;
    }, function() {
      console.log('Failed to fetch details');
      $rootScope.error = 'Failed to fetch details';
    })
  };
}]);
</code>```

html:

```<code><div class="row" data-ng-controller="authCtrl" data-ng-init="me()">
    <div class="col-lg-12">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <strong>Your Details</strong>
            </div>
            <div class="panel-body">
                <p>{{myDetails.data.username}}</p>
                <p>{{myDetails.data.email}}</p>
            </div>
        </div>
    </div>
</div>
</code>```

authServices.js:

```<code>authServices.factory('UserService',['$http', function($http) {
  return {
    me:function() {
    return $http.get(options.api.base_url + '/me').success(success).error(error)
    }
  }
}]);
</code>```

A successful nodeJs call is being received and it's returning data as well, but couldn't get it in the front end. Please help !

答:
You cannot connect to mongo directly from the angular application, you can use nodejs to connect to the mongodb and fetch data. Go through the following link,

NODE TODO LIST APP WITH MONGODB

Body:
I am getting "ReferenceError: success is not defined" when doing a Restful call from controller to my node.js back end as follows:

authControllers.js:

authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
  $scope.me = function() {
    UserService.me(function(res) {
      $scope.myDetails = res;
    }, function() {
      console.log('Failed to fetch details');
      $rootScope.error = 'Failed to fetch details';
    })
  };
}]);

html:

                Your Details

{{myDetails.data.username}}

{{myDetails.data.email}}

authServices.js:

authServices.factory('UserService',['$http', function($http) {
  return {
    me:function() {
    return $http.get(options.api.base_url + '/me').success(success).error(error)
    }
  }
}]);

A successful nodeJs call is being received and it's returning data as well, but couldn't get it in the front end. Please help !


问:
Why CakePHP is not allowing to create MySQL table names without plural?
Putting "_ underscore" is old school. Why CakePHP is using it till now. And also why CakePHP is not allowing to create MySQL table names without plural. Is this mandatory ?</p>

答:
This is the default naming convention for cakephp. If you don't want to use default then use this method

For cakephp 3 details here

```<code>$this->setTable('my_table');

// Prior to 3.4.0
$this->table('my_table');
</code>```

For cakephp 2 details here

```<code>class Example extends AppModel {
    public $useTable = 'exmp'; // This model uses a database table 'exmp'
}
</code>```

Body:
This is the default naming convention for cakephp. If you don't want to use default then use this method

For cakephp 3 details here

$this->setTable('my_table');

// Prior to 3.4.0
$this->table('my_table');

For cakephp 2 details here

class Example extends AppModel {
    public $useTable = 'exmp'; // This model uses a database table 'exmp'
}


问:
How do I include a self-reference to a server control in an external method call?
I have an Asp.Net TextBox control whose enabled property I need to evaluate using a separate (from the code-behind of the containing page) class. The way I want to do this is:

```<code><asp:TextBox ID="myTB" runat="server" Enabled="<% ToggleControl(this, "someBusinessValue") %>" ... />
</code>```

The reason I need to pass a reference to the calling control is to see if there are other properties I may need to consider before disabling it. The 'this' keyword, however, refers to the page as a whole. And since my TextBox can be within a FormView, or GridView, I can't easily just get the control by examining 'page.myTB'. I don't want to have to start ploughing through GridViews on the receiving class file just to retrieve a reference to the TextBox.

Does anyone know how to refer to the control inline in this way?

EDIT 1: This will need to be done to several different types of server control, such as ListBox, CheckBox, RadioButtonList, etc.

EDIT 2: The best I've come up with so far is:

```<code><asp:TextBox ID="myTB" runat="server" Enabled="<% ToggleControl(myGridView.FindControl("myTB") as WebControl, "someBusinessValue") %>"
</code>```

which isn't too elegant, but it does give me that auto-reference that I need.

答:
I think there is an issue of UI/Data/Code separation.

I think you need to write a wrapper for your data source so that all data is available to it before it binds. This will avoid having to find nested controls and so forth...

===========================================================

You never want to pass controls to any other object. The reason is that if you have to change the application's UI, you have to rebuild everything that has reference to that UI element.

Here is a simpler approach to display that data:

DataSource(table)->ORM/Custom Data Object or Collection->Instance Of Object/Collection On Page->UI.

Your UI idealy needs to bind to that object instance which hypothetically will be saved (and wrapped in a public or protected property) to any of the state objects provided by asp.net on the page (Session/AppState/ViewState).

Updates in the UI can be propagated via a transaction (using System.Transaction.TransactionScope) to the object stored in the state as well as the data source, which would ensure that your data source is the same as your disconnected data , while providing graceful degradation in case of failure.

When accessing the instance of the object/collection by your runtime/other pages a public property or variable will facilitate this objective.

This concept removes the need to pass controls. You are only passing data objects back and forth between objects/ui elements that consume them or take actions on their behalf.

Updates that occur inside two or more runtime components can be advertised to others via the Observer pattern or simple delegates...

ContentLicense: CC BY-SA 2.5

Body:
I have an Asp.Net TextBox control whose enabled property I need to evaluate using a separate (from the code-behind of the containing page) class. The way I want to do this is:

<asp:TextBox ID="myTB" runat="server" Enabled="<% ToggleControl(this, "someBusinessValue") %>" ... />

The reason I need to pass a reference to the calling control is to see if there are other properties I may need to consider before disabling it. The 'this' keyword, however, refers to the page as a whole. And since my TextBox can be within a FormView, or GridView, I can't easily just get the control by examining 'page.myTB'. I don't want to have to start ploughing through GridViews on the receiving class file just to retrieve a reference to the TextBox.

Does anyone know how to refer to the control inline in this way?

EDIT 1: This will need to be done to several different types of server control, such as ListBox, CheckBox, RadioButtonList, etc.

EDIT 2: The best I've come up with so far is:

<asp:TextBox ID="myTB" runat="server" Enabled="<% ToggleControl(myGridView.FindControl("myTB") as WebControl, "someBusinessValue") %>"

which isn't too elegant, but it does give me that auto-reference that I need.


问:
cordovaHTTP is not defined
I'm working with an HTTP request.

I have used this plugin:

https://github.com/panta/cordova-HTTP

```<code>angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','ngCordova','ja.qr','ngStorage','ngCordovaHTTP'])

.run(function($ionicPlatform,$rootScope,$localStorage) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)

    console.log(cordovaHTTP);
</code>```

But it throws an error:

cordovaHTTP is undefined

In index.html

```<code><script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="js/ng-cordova-http.js"></script>

<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
</code>```

答: cordovaHTTP is not the right naming for plugin clobber, "CordovaHttpPlugin" is the right one and is defined in window object.</p>

Title: cordovaHTTP is not defined

Body:
I'm working with an HTTP request.

I have used this plugin:

https://github.com/panta/cordova-HTTP

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','ngCordova','ja.qr','ngStorage','ngCordovaHTTP'])

.run(function($ionicPlatform,$rootScope,$localStorage) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)

    console.log(cordovaHTTP);

But it throws an error:

cordovaHTTP is undefined

In index.html


问:
Angular 2 TypeScript how to find element in Array
I have a Component and a Service:

Component:

export class WebUserProfileViewComponent {
    persons: Person [];
    personId: number;
    constructor( params: RouteParams, private personService: PersonService) {

           this.personId = params.get('id');
           this.persons =  this. personService.getPersons();
           console.log(this.personId);
        }
}```
</div>
</div>
</p>
<p>Service:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>@Injectable()
export class PersonService {
      getPersons(){
        var persons: Person[] = [
            {id: 1, firstName:'Hans', lastName:'Mustermann', email: 'mustermann@test.com', company:'Test', country:'DE'},
            {id: 2, firstName:'Muster', lastName:'Mustermann', email: 'mustermann@test.com', company:'test', country:'DE'},
            {id:3, firstName:'Thomas', lastName:'Mustermann', email: 'mustermannt@tesrt.com', company:'test', country:'DE'}
        ];

        return persons;
      }
}</code>```

I want to get the Person item with the ID ('personID'). The personID I get from Routeparams. For that I need the foreach loop? But I haven't found a solution for this.

答:
Transform the data structure to a map if you frequently use this search</p>

```<code>mapPersons: Map<number, Person>;

// prepare the map - call once or when person array change
populateMap() : void {
    this.mapPersons = new Map();
    for (let o of this.personService.getPersons()) this.mapPersons.set(o.id, o);
}
getPerson(id: number) : Person {
    return this.mapPersons.get(id);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Component and a Service:

Component:

export class WebUserProfileViewComponent {
    persons: Person [];
    personId: number;
    constructor( params: RouteParams, private personService: PersonService) {

           this.personId = params.get('id');
           this.persons =  this. personService.getPersons();
           console.log(this.personId);
        }
}

Service:

@Injectable()
export class PersonService {
      getPersons(){
        var persons: Person[] = [
            {id: 1, firstName:'Hans', lastName:'Mustermann', email: 'mustermann@test.com', company:'Test', country:'DE'},
            {id: 2, firstName:'Muster', lastName:'Mustermann', email: 'mustermann@test.com', company:'test', country:'DE'},
            {id:3, firstName:'Thomas', lastName:'Mustermann', email: 'mustermannt@tesrt.com', company:'test', country:'DE'}
        ];

        return persons;
      }
}

I want to get the Person item with the ID ('personID'). The personID I get from Routeparams. For that I need the foreach loop? But I haven't found a solution for this.

Body:
Transform the data structure to a map if you frequently use this search

mapPersons: Map<number, Person>;

// prepare the map - call once or when person array change
populateMap() : void {
    this.mapPersons = new Map();
    for (let o of this.personService.getPersons()) this.mapPersons.set(o.id, o);
}
getPerson(id: number) : Person {
    return this.mapPersons.get(id);
}


问:
A PHP Error was encountered Severity: Notice Message: Undefined variable: result

A PHP Error was encountered Severity: Notice

Message: Undefined variable: result

Filename: user/messages.php

Line Number: 87

Backtrace:

File: E:\xampp\htdocs\ci\application\views\user\messages.php Line: 87
  Function: _error_handler

File: E:\xampp\htdocs\ci\application\controllers\users\Dashboard.php
  Line: 12 Function: view

File: E:\xampp\htdocs\ci\index.php Line: 315 Function: require_once

here is my code
Controller

```<code>      <?php defined('BASEPATH') OR exit('No direct script access allowed');
        class Bills extends CI_Controller{
       function __construct(){
      parent::__construct();
     }

     public function bill(){
     $id = $this->session->userdata('email');
     $this->load->database();
     $this->load->helper(array('form', 'url', 'html'));
     $this->load->model('fuser/Bill');
     $data['result'] = $this->Bill->bills();
     $this->load->view('user/messages',$data);
      }
      }
      ?>

**Model**

      <?php
     class Bill extends CI_Model
     {
      function __construct()
      {
         // Call the Model constructor
         parent::__construct();
      }
      //we will use the select function
      public function bills($id)
      {
         //data is retrive from this query

     $query = $this->db->get('invoices');
       return $query->result();
      }

      }
     ?>

**View**
      <div class="billing_tabs_text_part">
                <?php foreach($result as $row){?>
                  <p><?php echo $row['book_id']; }?></p>
                </div>
</code>```

答: What gives you $query->result(); try to print in model itself</p>

Body:
A PHP Error was encountered Severity: Notice

Message: Undefined variable: result

Filename: user/messages.php

Line Number: 87

Backtrace:

File: E:\xampp\htdocs\ci\application\views\user\messages.php Line: 87
  Function: _error_handler

File: E:\xampp\htdocs\ci\application\controllers\users\Dashboard.php
  Line: 12 Function: view

File: E:\xampp\htdocs\ci\index.php Line: 315 Function: require_once

here is my code
Controller

      <?php defined('BASEPATH') OR exit('No direct script access allowed');
        class Bills extends CI_Controller{
       function __construct(){
      parent::__construct();
     }

     public function bill(){
     $id = $this->session->userdata('email');
     $this->load->database();
     $this->load->helper(array('form', 'url', 'html'));
     $this->load->model('fuser/Bill');
     $data['result'] = $this->Bill->bills();
     $this->load->view('user/messages',$data);
      }
      }
      ?>

**Model**

      <?php
     class Bill extends CI_Model
     {
      function __construct()
      {
         // Call the Model constructor
         parent::__construct();
      }
      //we will use the select function
      public function bills($id)
      {
         //data is retrive from this query

     $query = $this->db->get('invoices');
       return $query->result();
      }

      }
     ?>

**View**

                <?php foreach($result as $row){?>

<?php echo $row['book_id']; }?>


问:
Issue in converting received ajax data
Ajax is used to retrieve data from server.

Data is displayed successfully on alert as

```<code>data: {"status": "Active","broadcastmsg": "msg"}
</code>```

But in html i.e.

 it is displayed as undefined.

Looks like a minor issue , though I have been trying to solve this since last 24 hours and nothing seems to be working. Please suggest what's going wrong.

Client.php

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<body>
<script>
    function myFunction(val) {

            $.post("test.php",
            {
              d_id: 1,
              date: val
            },
            function(hstatus){
                alert(hstatus);
                myJSON = JSON.stringify(hstatus);
                localStorage.setItem("testJSON", myJSON);

                //Retrieving data:
                text = localStorage.getItem("testJSON");
                obj = JSON.parse(text);
                document.getElementById("demo").innerHTML = obj.status;
            });
        }

    </script>
        <p id="demo"></p>
        <div id="future_date" style="display:block;" class="col-xs-12">
            <input type="date" name="txt" value="" onchange="myFunction(this.value)">
        </div>

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

EDIT

if we pass hstatus = {"status": "Active","broadcastmsg": "msg"} manually it's showing result.

Thus issue is in converting from

data: {"status": "Active","broadcastmsg": "msg"}

to

{"status": "Active","broadcastmsg": "msg"}

答:
Update:

If you have the "data: " part in front of the JSON data, you have to trim:

```<code>myJSON = hstatus.substring(6);
</code>```

see: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring

Option A:
You should include one more (dataType) parameter in the $.post call, so the jQuery knows the content type, otherwise you will get the response as plain text.
https://api.jquery.com/jquery.post/

```<code>$.post("test.php", {
     d_id: 1,
     date: val
}, function() { /*...*/ },
"json");
</code>```

You should also check your test.php and ensure that you are sending the Content-Type: application/json http header (see: http://php.net/manual/en/function.header.php).

Option B: (not recommended)
Just remove the JSON.stringify() part from the callback function:

```<code>function(hstatus){
    localStorage.setItem("testJSON", hstatus);
    //Retrieving data:
    text = localStorage.getItem("testJSON");
    obj = JSON.parse(text);
    document.getElementById("demo").innerHTML = obj.status;
});
</code>```

Just a tip:

Use the console.log() command for debug variable values so you can see the exact, typed value in your browser console (press F12 in most browser).
The alert() function automatically converts everything into strings so it usually show misleading results.

Title: Issue in converting received ajax data

Body:
Ajax is used to retrieve data from server.

Data is displayed successfully on alert as

data: {"status": "Active","broadcastmsg": "msg"}

But in html i.e.

 it is displayed as undefined.

Looks like a minor issue , though I have been trying to solve this since last 24 hours and nothing seems to be working. Please suggest what's going wrong.

Client.php

<!DOCTYPE html>

            <input type="date" name="txt" value="" onchange="myFunction(this.value)">

EDIT

if we pass hstatus = {"status": "Active","broadcastmsg": "msg"} manually it's showing result.

Thus issue is in converting from

data: {"status": "Active","broadcastmsg": "msg"}

to

{"status": "Active","broadcastmsg": "msg"}

Body:
Update:

If you have the "data: " part in front of the JSON data, you have to trim:

myJSON = hstatus.substring(6);

see: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring

Option A:
You should include one more (dataType) parameter in the $.post call, so the jQuery knows the content type, otherwise you will get the response as plain text.
https://api.jquery.com/jquery.post/

$.post("test.php", {
     d_id: 1,
     date: val
}, function() { /*...*/ },
"json");

You should also check your test.php and ensure that you are sending the Content-Type: application/json http header (see: http://php.net/manual/en/function.header.php).

Option B: (not recommended)
Just remove the JSON.stringify() part from the callback function:

function(hstatus){
    localStorage.setItem("testJSON", hstatus);
    //Retrieving data:
    text = localStorage.getItem("testJSON");
    obj = JSON.parse(text);
    document.getElementById("demo").innerHTML = obj.status;
});

Just a tip:

Use the console.log() command for debug variable values so you can see the exact, typed value in your browser console (press F12 in most browser).
The alert() function automatically converts everything into strings so it usually show misleading results.


问:
html5 video not playing in ipad simulator?
I created xcode universal project, I am trying to load HTML5 page in UIWebView  the

problem is i cant see any control to play movie, and i am getting blank screen on the video

place, in ipad and iphone simulator,

my .html file

```<code>    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <!-- Change this if you want to allow scaling -->
    <meta name="viewport"
        content="width=default-width; user-scalable=no" />

    <meta http-equiv="Content-type"
        content="text/html; charset=utf-8">

    <title>Web App Demo</title>

  </head>
  <body>
    <h1>Video Test</h1>
    <p>This is a video test.</p>
    <video width="320" height="240" controls= "controls">
        <source src="video.ogv" type="video/ogg" />
        <source src="video.mp4" type="video/mp4"/>
             browser not supports the video
    </video>
    </br> <br/>
    <h1>This is Audio </h1>
    <b>Testing Audio </b>
    <audio controls="controls">
        <source src="audio.ogg" type="audio/ogg" />
        <source src="audio.mp3" type="audio/mpeg"/>
        browser not supporting audio
    </audio>

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

Any help why its not playing in simulator.

Thanks in advance.

答:
I am playing an m4v file in my uiwebview, but the translucent 'play' button does not appear in my simulator. It does work on the device itself, though....</p>

```<code>        <video id="VideoDiv" preload src="http://www.movietime.com/movie.m4v" controls width="480px" height="270" poster="poster.png"></video>
</code>```

Body:
I created xcode universal project, I am trying to load HTML5 page in UIWebView  the

problem is i cant see any control to play movie, and i am getting blank screen on the video

place, in ipad and iphone simulator,

my .html file

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">

    <meta name="viewport"
        content="width=default-width; user-scalable=no" />

    <meta http-equiv="Content-type"
        content="text/html; charset=utf-8">

    <title>Web App Demo</title>

Video Test

This is a video test.

    <video width="320" height="240" controls= "controls">
        <source src="video.ogv" type="video/ogg" />
        <source src="video.mp4" type="video/mp4"/>
             browser not supports the video
    </video>

This is Audio

    Testing Audio
    <audio controls="controls">
        <source src="audio.ogg" type="audio/ogg" />
        <source src="audio.mp3" type="audio/mpeg"/>
        browser not supporting audio
    </audio>

Any help why its not playing in simulator.

Thanks in advance.

Body:
I am playing an m4v file in my uiwebview, but the translucent 'play' button does not appear in my simulator. It does work on the device itself, though....

        <video id="VideoDiv" preload src="http://www.movietime.com/movie.m4v" controls width="480px" height="270" poster="poster.png"></video>


问:
jquery can't alert ajax response
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

```<code>    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }
</code>```

However, if the above code was written without

```<code>    if (response == 'false') {

    }
</code>```

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

答:
Finally figured out the problem.

The response returns a string as value rather than a boolean.
So I changed its data type to boolean before it is received by ajax (from 'false' with quotes to false without quotes), and i was able to evaluate it as a boolean with

```<code>if (response == false) {
    alert(response);
}
</code>```

Thanks to everyone who contributed.

Title: jquery can't alert ajax response

Body:
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }

However, if the above code was written without

    if (response == 'false') {

    }

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

Body:
Finally figured out the problem.

The response returns a string as value rather than a boolean.
So I changed its data type to boolean before it is received by ajax (from 'false' with quotes to false without quotes), and i was able to evaluate it as a boolean with

if (response == false) {
    alert(response);
}

Thanks to everyone who contributed.


问:
Sorting a multidimensional array in javascript?
I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks</p>

```<code>     var nestedArr = [[[1,2],[3,4]],[[5,6]]];
     var nestedArrOne = nestedArr[0];
     var nestedArrTwo = nestedArr[1];
     var newArr = nestedArrOne.concat(nestedArrTwo);
      function showAll(){
        for(var i=0; i<newArr.length; i++){
        for(var j=0; j<newArr[i].length; j++){
        console.log(newArr[i][j]);
                }
            }
       }

       showAll();
</code>```

答:
A fancy Haskellesque approach with "pattern matching by rest operator" could be.

var flat = ([x,...xs]) => x ? [...Array.isArray(x) ? flat(x) : [x], ...flat(xs)] : [];
    na   = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
    fa   = flat(na);
console.log(...fa);```

Body:
I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks

     var nestedArr = [[[1,2],[3,4]],[[5,6]]];
     var nestedArrOne = nestedArr[0];
     var nestedArrTwo = nestedArr[1];
     var newArr = nestedArrOne.concat(nestedArrTwo);
      function showAll(){
        for(var i=0; i<newArr.length; i++){
        for(var j=0; j<newArr[i].length; j++){
        console.log(newArr[i][j]);
                }
            }
       }

       showAll();


问:
Function to generate ordered combinations
What R command generates all possible ordered combinations of length k?

For example from this vector:

```<code>a,b,c,d
</code>```

It want to generate all combinations of length 3 but only those ones where the order is conserved:

```<code>a,b,c
a,b,d
a,c,d
b,c,d
</code>```

Or If I have this vector

```<code>a,b,7,d,e
</code>```

I want to do the same for length 2:

```<code>a,b
a,7
a,d
a,e
b,7
b,d
b,e
7,d
7,e
d,e
</code>```

combn doesn't work here because it gives you all possible combinations including reversed ones such as

c,b

In simple cases I could try to do it with expand.grid but both methods would need further processing.

Maybe there is a base function (or package) able to do what I want or even accepting more complex conditions.

PD: When I say "ordered" I'm speaking about the order of appearance in the starting vector. I don't mean the typographic order, though in my example they are the same.

Body:
What R command generates all possible ordered combinations of length k?

For example from this vector:

a,b,c,d

It want to generate all combinations of length 3 but only those ones where the order is conserved:

a,b,c
a,b,d
a,c,d
b,c,d

Or If I have this vector

a,b,7,d,e

I want to do the same for length 2:

a,b
a,7
a,d
a,e
b,7
b,d
b,e
7,d
7,e
d,e

combn doesn't work here because it gives you all possible combinations including reversed ones such as

c,b

In simple cases I could try to do it with expand.grid but both methods would need further processing.

Maybe there is a base function (or package) able to do what I want or even accepting more complex conditions.

PD: When I say "ordered" I'm speaking about the order of appearance in the starting vector. I don't mean the typographic order, though in my example they are the same.

Body:
You can use combn in base R:

vec <- c("a", "b", "c", "d")
len <- 2
combn(length(vec), len, function(x) vec[x])

#    [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] "a"  "a"  "a"  "b"  "b"  "c"
#[2,] "b"  "c"  "d"  "c"  "d"  "d"

Of length 3:

combn(length(vec), 3, function(x) vec[x])

#     [,1] [,2] [,3] [,4]
#[1,] "a"  "a"  "a"  "b"
#[2,] "b"  "b"  "c"  "c"
#[3,] "c"  "d"  "d"  "d"

OR as @Sotos pointed out in the comments:

combn(vec, len)


问:
I have a list of datatable, how can I copy that list into single datatable in c#
```<code>public DataTable LoadPaymentsList()
{
   List< DataTable > lstDts = new List< DataTable >();
   // Copy into  dt
   Datatable dt=new Datatable();
   return dt;
}
</code>```

答:
You want to have a look into merging tables . Check this for further info on dataTable Merging, http://www.c-sharpcorner.com/UploadFile/0c1bb2/merging-multiple-datatables-into-single-datatable-using-asp/</p>

```<code>//merging first data table into second data table
         dt2.Merge(dt);
         dt2.AcceptChanges();
</code>```

Body:
You want to have a look into merging tables . Check this for further info on dataTable Merging, http://www.c-sharpcorner.com/UploadFile/0c1bb2/merging-multiple-datatables-into-single-datatable-using-asp/

//merging first data table into second data table
         dt2.Merge(dt);
         dt2.AcceptChanges();


问:
Where the status of the system is stored when an android application is running?
i want to know where the status of the system like the memory usages, stack details, memory spaces, address spaces, etc.. of the system are stored when an android application is running and crashing. please help me..</p>

答: If the purpose of the question is to know why your app is crashing, I suggest to just use http://fabric.io or the Crash Reporting section of https://console.firebase.google.com</p>


问:
How would I create this EditorTemplate for a collection?
So I have a custom ViewModel (CompanySalaryDataViewModel) that has a collection of other ViewModels on it (PersonalIncomeViewModel). Ultimately, I want to have an EditorTemplate for a CompanySalaryDataViewModel that consumes an EditorTemplate for a PersonalIncomeViewModel somehow in a way that it provides 2-way binding to my ViewModel when it's passed back into my POST controller.

For example, let's say it's something like this:

```<code>public class CompanySalaryDataViewModel
{
    string CompanyName { get; set; }
    IList<PersonalIncomeViewModel> AllSalaryData { get; set; }
}

public class PersonalIncomeViewModel
{
    long UniqueID { get; set; }
    string PersonName { get; set; }
    int JanIncome { get; set; }
    int FebIncome { get; set; }
    int MarIncome { get; set; }
    int AprIncome { get; set; }
    int MayIncome { get; set; }
    int JunIncome { get; set; }
    int JulIncome { get; set; }
    int AugIncome { get; set; }
    int SepIncome { get; set; }
    int OctIncome { get; set; }
    int NovIncome { get; set; }
    int DecIncome { get; set; }
}
</code>```

I want this done in a way where it's similar to the following markup but works:

```<code><%= Html.TextBoxFor(x => x.CompanyName) %>
    <table cellspacing="0">
        <thead>
            <tr class="t-grid-header">
                <th class="t-header">ID</th>
                <th class="t-header">Person</th>
                <th class="t-header">Jan</th>
                <th class="t-header">Feb</th>
                <th class="t-header">Mar</th>
                <th class="t-header">Apr</th>
                <th class="t-header">May</th>
                <th class="t-header">Jun</th>
                <th class="t-header">Jul</th>
                <th class="t-header">Aug</th>
                <th class="t-header">Sep</th>
                <th class="t-header">Oct</th>
                <th class="t-header">Nov</th>
                <th class="t-header">Dec</th>
            </tr>
        </thead>
    <%
    var isAlt = false;
    foreach (var salaryData in Model.AllSalaryData)
    {
        var salary = salaryData;
        if (isAlt)
        {%>
            <tr class="t-alt">
        <%
        }
        else
        {%>
            <tr>
        <%
        }

        isAlt = !isAlt;
        %>
                <td><%=Html.TextBoxFor(x => salary.UniqueID)%></td>
                <td><%=Html.TextBoxFor(x => salary.PersonName)%></td>
                <td><%=Html.TextBoxFor(x => salary.JanIncome, new {id = salary.PersonName + "_1", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.FebIncome, new {id = salary.PersonName + "_2", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.MarIncome, new {id = salary.PersonName + "_3", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.AprIncome, new {id = salary.PersonName + "_4", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.MayIncome, new {id = salary.PersonName + "_5", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.JunIncome, new {id = salary.PersonName + "_6", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.JulIncome, new {id = salary.PersonName + "_7", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.AugIncome, new {id = salary.PersonName + "_8", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.SepIncome, new {id = salary.PersonName + "_9", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.OctIncome, new {id = salary.PersonName + "_10", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.NovIncome, new {id = salary.PersonName + "_11", style = "width: 45px;"})%></td>
                <td><%=Html.TextBoxFor(x => salary.DecIncome, new {id = salary.PersonName + "_12", style = "width: 45px;"})%></td>
            </tr>
    <%
    }%>
    </table>
</code>```

The problems with this code are:

Each "January" textbox has the same name (salary.JanIncome - doesn't include anything to differentiate it from another salary). Same problem with every month.

Perhaps because of problem #1, this doesn't bind back to the ViewModel when I post - my AllSalaryData collection is null.

All of this seems VERY non-best-practice and like there should be a better way to do this.

Ultimately, I guess I need to better understand using templates with collections but the other part of it is the "logic" to properly apply the t-alt class to the appropriate table row.

NOTE #1: I set the HTML IDs this way for some javascript stuff I have interacting with these textboxes.

NOTE #2: I'm not really doing this with salary data.

答:
Not clear with your question:
1. 'ViewModels' are view models - at least from design point of view. Is your intent to be able to 'batch' update the collection/list or your post back to send collection of the same object type?
2. Let's assume your model - PersonalIncome[ViewModel] is persistable. So, you will be editing one record at time and the editor template you will be using will be just for an item in the collection.

Can you elaborate the intent not just what you want to do - there could be other alternatives than creating a 'list' view with Textboxes.

Body:
So I have a custom ViewModel (CompanySalaryDataViewModel) that has a collection of other ViewModels on it (PersonalIncomeViewModel). Ultimately, I want to have an EditorTemplate for a CompanySalaryDataViewModel that consumes an EditorTemplate for a PersonalIncomeViewModel somehow in a way that it provides 2-way binding to my ViewModel when it's passed back into my POST controller.

For example, let's say it's something like this:

public class CompanySalaryDataViewModel
{
    string CompanyName { get; set; }
    IList<PersonalIncomeViewModel> AllSalaryData { get; set; }
}

public class PersonalIncomeViewModel
{
    long UniqueID { get; set; }
    string PersonName { get; set; }
    int JanIncome { get; set; }
    int FebIncome { get; set; }
    int MarIncome { get; set; }
    int AprIncome { get; set; }
    int MayIncome { get; set; }
    int JunIncome { get; set; }
    int JulIncome { get; set; }
    int AugIncome { get; set; }
    int SepIncome { get; set; }
    int OctIncome { get; set; }
    int NovIncome { get; set; }
    int DecIncome { get; set; }
}

I want this done in a way where it's similar to the following markup but works:

<%= Html.TextBoxFor(x => x.CompanyName) %>

                ID
                Person
                Jan
                Feb
                Mar
                Apr
                May
                Jun
                Jul
                Aug
                Sep
                Oct
                Nov
                Dec

    <%
    var isAlt = false;
    foreach (var salaryData in Model.AllSalaryData)
    {
        var salary = salaryData;
        if (isAlt)
        {%>

        <%
        }
        else
        {%>

        <%
        }

        isAlt = !isAlt;
        %>
                <%=Html.TextBoxFor(x => salary.UniqueID)%>
                <%=Html.TextBoxFor(x => salary.PersonName)%>
                <%=Html.TextBoxFor(x => salary.JanIncome, new {id = salary.PersonName + "_1", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.FebIncome, new {id = salary.PersonName + "_2", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.MarIncome, new {id = salary.PersonName + "_3", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.AprIncome, new {id = salary.PersonName + "_4", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.MayIncome, new {id = salary.PersonName + "_5", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.JunIncome, new {id = salary.PersonName + "_6", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.JulIncome, new {id = salary.PersonName + "_7", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.AugIncome, new {id = salary.PersonName + "_8", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.SepIncome, new {id = salary.PersonName + "_9", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.OctIncome, new {id = salary.PersonName + "_10", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.NovIncome, new {id = salary.PersonName + "_11", style = "width: 45px;"})%>
                <%=Html.TextBoxFor(x => salary.DecIncome, new {id = salary.PersonName + "_12", style = "width: 45px;"})%>

    <%
    }%>

The problems with this code are:

Each "January" textbox has the same name (salary.JanIncome - doesn't include anything to differentiate it from another salary). Same problem with every month.

Perhaps because of problem #1, this doesn't bind back to the ViewModel when I post - my AllSalaryData collection is null.

All of this seems VERY non-best-practice and like there should be a better way to do this.

Ultimately, I guess I need to better understand using templates with collections but the other part of it is the "logic" to properly apply the t-alt class to the appropriate table row.

NOTE #1: I set the HTML IDs this way for some javascript stuff I have interacting with these textboxes.

NOTE #2: I'm not really doing this with salary data.


问:
Android FirebaseRecyclerAdapter in Fragment
I'm using the Android Studio provided class for a tabbed activity that uses ActionBar Tabs with ViewPager. Inside this activity, I'm trying to initialize a RecyclerView & CardView with data from a Firebase database.

Problem: RecyclerView is empty as shown below.

empty screen but scroll works fine.

and this is my code

```<code>public class Produce extends Fragment {

    private DatabaseReference mDatabase;
    private FirebaseRecyclerAdapter<ProduceSetting, ProduceViewHolder> mFirebaseAdapter;
    private RecyclerView mProduceList = null;
    private View rootView;

    private Context c;
    private LinearLayoutManager manager;

    public Produce() {}

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_produce, container, false);
        c = getContext();
        mProduceList = (RecyclerView) rootView.findViewById(R.id.produce_recycler_view);
        manager = new LinearLayoutManager(c);
        mProduceList.setHasFixedSize(true);

        mDatabase = FirebaseDatabase.getInstance().getReference().child("Produce");

        mFirebaseAdapter = new FirebaseRecyclerAdapter<ProduceSetting, ProduceViewHolder>(

                ProduceSetting.class, R.layout.card_item_produce, ProduceViewHolder.class, mDatabase

        ) {
            @Override
            protected void populateViewHolder(ProduceViewHolder viewHolder, ProduceSetting model, int position) {
                viewHolder.setName(model.getGameName());
                viewHolder.setType(model.getGameType());
                viewHolder.setImage(getActivity().getApplicationContext(), model.getImage());
            }
        };

        mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                super.onItemRangeInserted(positionStart, itemCount);
                int friendlyMessageCount = mFirebaseAdapter.getItemCount();
                int lastVisiblePosition =
                        manager.findLastCompletelyVisibleItemPosition();
                // If the recycler view is initially being loaded or the
                // user is at the bottom of the list, scroll to the bottom
                // of the list to show the newly added message.
                if (lastVisiblePosition == -1 ||
                        (positionStart >= (friendlyMessageCount - 1) &&
                                lastVisiblePosition == (positionStart - 1))) {
                    mProduceList.scrollToPosition(positionStart);
                }
            }
        });

        mProduceList.setLayoutManager(manager);
        mProduceList.setAdapter(mFirebaseAdapter);

        return rootView;
    }

    public static class ProduceViewHolder extends RecyclerView.ViewHolder {

        View mView;
        public ProduceViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }
        public void setName(String name) {
            TextView post_name = (TextView) mView.findViewById(R.id.post_name);
            post_name.setText(name);
        }
        public void setType(String type) {
            TextView post_type = (TextView) mView.findViewById(R.id.post_type);
            post_type.setText(type);
        }
        public void setImage(Context ctx, String image) {
            ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
            Picasso.with(ctx).load(image).into(post_image);
        }
    }
}
</code>```

and here is my getter and setter

```<code>public class ProduceSetting {

    private String GameName;
    private String GameType;
    private String image;

    public ProduceSetting(){}

    public ProduceSetting(String gameName, String gameType, String image) {
        GameName = gameName;
        GameType = gameType;
        this.image = image;
    }

    public String getGameName() {
        return GameName;
    }

    public void setGameName(String gameName) {
        GameName = gameName;
    }

    public String getGameType() {
        return GameType;
    }

    public void setGameType(String gameType) {
        GameType = gameType;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

}
</code>```

help me please.

答:
i was wrong.

mDatabase = FirebaseDatabase.getInstance().getReference().child("Produce");

mDatabase = FirebaseDatabase.getInstance().getReference().child("Product");

Body:
I'm using the Android Studio provided class for a tabbed activity that uses ActionBar Tabs with ViewPager. Inside this activity, I'm trying to initialize a RecyclerView & CardView with data from a Firebase database.

Problem: RecyclerView is empty as shown below.

empty screen but scroll works fine.

and this is my code

public class Produce extends Fragment {

    private DatabaseReference mDatabase;
    private FirebaseRecyclerAdapter<ProduceSetting, ProduceViewHolder> mFirebaseAdapter;
    private RecyclerView mProduceList = null;
    private View rootView;

    private Context c;
    private LinearLayoutManager manager;

    public Produce() {}

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_produce, container, false);
        c = getContext();
        mProduceList = (RecyclerView) rootView.findViewById(R.id.produce_recycler_view);
        manager = new LinearLayoutManager(c);
        mProduceList.setHasFixedSize(true);

        mDatabase = FirebaseDatabase.getInstance().getReference().child("Produce");

        mFirebaseAdapter = new FirebaseRecyclerAdapter<ProduceSetting, ProduceViewHolder>(

                ProduceSetting.class, R.layout.card_item_produce, ProduceViewHolder.class, mDatabase

        ) {
            @Override
            protected void populateViewHolder(ProduceViewHolder viewHolder, ProduceSetting model, int position) {
                viewHolder.setName(model.getGameName());
                viewHolder.setType(model.getGameType());
                viewHolder.setImage(getActivity().getApplicationContext(), model.getImage());
            }
        };

        mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                super.onItemRangeInserted(positionStart, itemCount);
                int friendlyMessageCount = mFirebaseAdapter.getItemCount();
                int lastVisiblePosition =
                        manager.findLastCompletelyVisibleItemPosition();
                // If the recycler view is initially being loaded or the
                // user is at the bottom of the list, scroll to the bottom
                // of the list to show the newly added message.
                if (lastVisiblePosition == -1 ||
                        (positionStart >= (friendlyMessageCount - 1) &&
                                lastVisiblePosition == (positionStart - 1))) {
                    mProduceList.scrollToPosition(positionStart);
                }
            }
        });

        mProduceList.setLayoutManager(manager);
        mProduceList.setAdapter(mFirebaseAdapter);

        return rootView;
    }

    public static class ProduceViewHolder extends RecyclerView.ViewHolder {

        View mView;
        public ProduceViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }
        public void setName(String name) {
            TextView post_name = (TextView) mView.findViewById(R.id.post_name);
            post_name.setText(name);
        }
        public void setType(String type) {
            TextView post_type = (TextView) mView.findViewById(R.id.post_type);
            post_type.setText(type);
        }
        public void setImage(Context ctx, String image) {
            ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
            Picasso.with(ctx).load(image).into(post_image);
        }
    }
}

and here is my getter and setter

public class ProduceSetting {

    private String GameName;
    private String GameType;
    private String image;

    public ProduceSetting(){}

    public ProduceSetting(String gameName, String gameType, String image) {
        GameName = gameName;
        GameType = gameType;
        this.image = image;
    }

    public String getGameName() {
        return GameName;
    }

    public void setGameName(String gameName) {
        GameName = gameName;
    }

    public String getGameType() {
        return GameType;
    }

    public void setGameType(String gameType) {
        GameType = gameType;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

}

help me please.


问:
How to get filtered VM list on vcenter with python
I'm trying to get a list of registered virtual machines - by their name - in my vcenter. The problem that I have many vms (~5K), and I am doing it a lot of times (O(1000)/hour).

The SDKs I'm using causing it a lot of traffic (1-2MB/request):

pysphere: which ask for all vms, and filters on client side.

pyVmomi, which need to use recursion to list all vms (I saw SI.content.searchIndex.FindByDnsName on reboot_vm.py, but my machines' DNS configuration is not true)

Looking into SOAP documentation didn't help (got into RetrievePropertiesEx.objectSet but it doesn't looks to filter anything), and the new REST (v6.5) didn't help too (since I need to get its "datastore path", and all I can get is the name)

答: vAPI is based on REST, even more, it does network requests every time, so it will be slow. Another way is to use VCDB, where are stored all VMs (there us such one, but I can not help you here more), see https://pubs.vmware.com/vsphere-4-esx-vcenter/index.jsp?topic=/com.vmware.vsphere.installclassic.doc_41/install/prep_db/c_preparing_the_vmware_infrastructure_databases.html or https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1025914</p>


问:
How to Use Virtual Mode for large data in DataGridView
I am posting to see if there is a way to improve some legacy code. The code will populate a DataGridView with x amount of rows. Initially, the code worked fine as the populating data was of a small quantity. However, there has been an extreme increase in data and I am finding that the performance in populating the DataGridView to be very slow.

Basically, I know there are several considerations (Virtual Mode, for instance). However, the approach that I want to take is using an array or List (and then convert it to an array) and add the range of the row by calling Rows.AddRange(array). However, I am having trouble implementing it.

As it stands, this is what code exists:

```<code>if (value !=0)
{
 int row = 0;
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}

if (valueTwo !=0)
{
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}
</code>```

So, this is not efficient at all, of course. I know .AddRow() is a taxing method in itself and individually adding rows, one-by-one is not great.

I have tried something like:

```<code>object[] data = {"Test", 9, "Test Two", "Test Three"};
List<DataGridViewRow> list = new List<DataGridViewRow>();
for (int i = 0; i < data.Length; i++)
{
  DataGridViewRow row = new DataGridViewRow();
  row.SetValues(data[i]);
  list.Add(row);
 }
 dataGridViewRow1.Rows.AddRange(list.ToArray());
</code>```

However, doing this gets me a NullPointerException on the SetValues line.

I understand that the best way of doing this is either make a DataTable or use Virtual Mode but I want to try out using this method of adding the range and passing in a container for the data, rather than adding a row.

I hope I am clear with my explanation. Let me know if I need to further explain.

EDIT: I think using Virtual Mode is the best way to go. I am not sure how to really do it, though. I checked MSN's tutorial but I was slightly confused by it. If I were to implement Virtual Mode for 100,000 rows, how would I go about doing it. Nothing really fancy, just displaying a total of 10,000 rows.

答:
i can prefer DataTable is the correct approach,
but still if you want to add data to your gridView dynamically,
first you need to add columns then rows.

```<code>private void Form5_Load(object sender, EventArgs e)
        {
            var lstTemp = new List<test>();

            for (int i = 0; i < 10; i++)
                lstTemp.Add(new test() { Name = "Test", No = i, Desc = "Desc " + i, Desc1 = "Desc1 " + i });

            dataGridView1.Columns.Add("Name", "Name");
            dataGridView1.Columns.Add("No", "Number");
            dataGridView1.Columns.Add("Desc", "Description1");
            dataGridView1.Columns.Add("Desc1", "Description2");

            foreach (var temp in lstTemp)
            {
                DataGridViewRow row = (DataGridViewRow) dataGridView1.Rows[0].Clone();
                row.Cells[0].Value = temp.Name;
                row.Cells[1].Value = temp.No;
                row.Cells[2].Value = temp.Desc;
                row.Cells[3].Value = temp.Desc1;
                dataGridView1.Rows.Add(row);
            }
        }

        public class test
        {
            public string Name { get; set; }
            public int No { get; set; }
            public string Desc { get; set; }
            public string Desc1 { get; set; }
        }
</code>```

this might help you,

Body:
I am posting to see if there is a way to improve some legacy code. The code will populate a DataGridView with x amount of rows. Initially, the code worked fine as the populating data was of a small quantity. However, there has been an extreme increase in data and I am finding that the performance in populating the DataGridView to be very slow.

Basically, I know there are several considerations (Virtual Mode, for instance). However, the approach that I want to take is using an array or List (and then convert it to an array) and add the range of the row by calling Rows.AddRange(array). However, I am having trouble implementing it.

As it stands, this is what code exists:

if (value !=0)
{
 int row = 0;
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}

if (valueTwo !=0)
{
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}

So, this is not efficient at all, of course. I know .AddRow() is a taxing method in itself and individually adding rows, one-by-one is not great.

I have tried something like:

object[] data = {"Test", 9, "Test Two", "Test Three"};
List<DataGridViewRow> list = new List<DataGridViewRow>();
for (int i = 0; i < data.Length; i++)
{
  DataGridViewRow row = new DataGridViewRow();
  row.SetValues(data[i]);
  list.Add(row);
 }
 dataGridViewRow1.Rows.AddRange(list.ToArray());

However, doing this gets me a NullPointerException on the SetValues line.

I understand that the best way of doing this is either make a DataTable or use Virtual Mode but I want to try out using this method of adding the range and passing in a container for the data, rather than adding a row.

I hope I am clear with my explanation. Let me know if I need to further explain.

EDIT: I think using Virtual Mode is the best way to go. I am not sure how to really do it, though. I checked MSN's tutorial but I was slightly confused by it. If I were to implement Virtual Mode for 100,000 rows, how would I go about doing it. Nothing really fancy, just displaying a total of 10,000 rows.

Body:
i can prefer DataTable is the correct approach,
but still if you want to add data to your gridView dynamically,
first you need to add columns then rows.

private void Form5_Load(object sender, EventArgs e)
        {
            var lstTemp = new List<test>();

            for (int i = 0; i < 10; i++)
                lstTemp.Add(new test() { Name = "Test", No = i, Desc = "Desc " + i, Desc1 = "Desc1 " + i });

            dataGridView1.Columns.Add("Name", "Name");
            dataGridView1.Columns.Add("No", "Number");
            dataGridView1.Columns.Add("Desc", "Description1");
            dataGridView1.Columns.Add("Desc1", "Description2");

            foreach (var temp in lstTemp)
            {
                DataGridViewRow row = (DataGridViewRow) dataGridView1.Rows[0].Clone();
                row.Cells[0].Value = temp.Name;
                row.Cells[1].Value = temp.No;
                row.Cells[2].Value = temp.Desc;
                row.Cells[3].Value = temp.Desc1;
                dataGridView1.Rows.Add(row);
            }
        }

        public class test
        {
            public string Name { get; set; }
            public int No { get; set; }
            public string Desc { get; set; }
            public string Desc1 { get; set; }
        }

this might help you,


问:
Change colorbar gradient in matplotlib
I have a grid of weights (Y) evolving with time (X):

I cannot distinguish correctly the variations of weights as the distribution is asymmetric between positive and negative weights; the null weights should be recognized as it means the given variables are not used.

For these reasons, I would like to change the color gradient to get something like those (either a or b):

Any idea on how to approach this?

答:
You can use a custom normalizer. Conveniently, the example for this in the docs is already an 'alternative midpoint' normalizer. The example is made by Joe Kington, so all credits to him.

See the bottom of this page:
https://matplotlib.org/users/colormapnorms.html

```<code>import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
</code>```

Custom normalize class:

```<code>class MidpointNormalize(mpl.colors.Normalize):
    ## class from the mpl docs:
    # https://matplotlib.org/users/colormapnorms.html

    def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
        self.midpoint = midpoint
        super().__init__(vmin, vmax, clip)

    def __call__(self, value, clip=None):
        # I'm ignoring masked values and all kinds of edge cases to make a
        # simple example...
        x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
        return np.ma.masked_array(np.interp(value, x, y))
</code>```

The result:

```<code>data = np.linspace(-5,1,100)[None,:]

fig, axs = plt.subplots(2,1, figsize=(5,2), facecolor='w', subplot_kw=dict(xticks=[], yticks=[]))

props = dict(aspect=15, cmap=plt.cm.coolwarm)

axs[0].imshow(data, **props)
axs[1].imshow(data, norm=MidpointNormalize(midpoint=0), **props)
</code>```

This is a relative simple example, but more complex scalings can be achieved in a similar matter.

Title: Change colorbar gradient in matplotlib

Body:
You can use a custom normalizer. Conveniently, the example for this in the docs is already an 'alternative midpoint' normalizer. The example is made by Joe Kington, so all credits to him.

See the bottom of this page:
https://matplotlib.org/users/colormapnorms.html

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

Custom normalize class:

class MidpointNormalize(mpl.colors.Normalize):
    ## class from the mpl docs:
    # https://matplotlib.org/users/colormapnorms.html

    def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
        self.midpoint = midpoint
        super().__init__(vmin, vmax, clip)

    def __call__(self, value, clip=None):
        # I'm ignoring masked values and all kinds of edge cases to make a
        # simple example...
        x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
        return np.ma.masked_array(np.interp(value, x, y))

The result:

data = np.linspace(-5,1,100)[None,:]

fig, axs = plt.subplots(2,1, figsize=(5,2), facecolor='w', subplot_kw=dict(xticks=[], yticks=[]))

props = dict(aspect=15, cmap=plt.cm.coolwarm)

axs[0].imshow(data, **props)
axs[1].imshow(data, norm=MidpointNormalize(midpoint=0), **props)

This is a relative simple example, but more complex scalings can be achieved in a similar matter.


问:
Using Spatialite in Android
I want to develop an Android app with offline routing. I want to use Spatialite as the database in the client side. I am confused after reading their web. Since it is running on the Android side(cell phone), why the installation requirs to install many dependent softwares. Are they used for compilation only?  Can it be running on the android side?</p>

答:
You can use spatialite on android!

You can see the official manual here:
https://www.gaia-gis.it/fossil/libspatialite/wiki?name=spatialite-android-tutorial

But also compare to this geopaparazzi project also utilizing spatialite:https://github.com/geopaparazzi/geopaparazzi/tree/master/geopaparazzispatialitelibrary

You should use the native spatialite libraries (libjsqlite.so) and the basic API classes, in the jsqlite package in the geopaparazzi project.

Title: Using Spatialite in Android


问:
FSharp Interactive won't start; can't find System.Runtime.dll
I've installed FSharp 4.1 through the Visual Studio 2017 installer, but FSI refuses to start:

```<code>PS C:\Program Files (x86)\Microsoft SDKs\F#\4.1\Framework\v4.0> .\fsi

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly
'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one
of its dependencies. The system cannot find the file specified.
   at Microsoft.FSharp.Compiler.Interactive.Shell.MainMain(String[] argv)
</code>```

I assume I'm missing something in a PATH variable or something, but despite several reinstalls and repairs I can't get past this error.

Where is FSI looking for this dll, and what should I install to put it there?

Update:

I've tried a few things, with no change to the outcome:

Remove F# 4.1 through the VS 2017 installer, verify that C:\Program Files (x86)\Microsoft SDKs\F#\4.1 did not exist, and reinstall F# 4.1

Uninstall all versions of .NET Core I had installed

Remove the C:\Program Files (x86)\Microsoft SDKs\F#\4.0 directory that doesn't seem to have an installer that cares for it. (FSI in that directory worked prior to removal...)

I've dumped the fusion logs to a zip file and put it on my Google Drive. There's a whole bunch of failed bindings, System.Runtime, Version 4.1.0.0 being one of them.

Issue filed here: https://github.com/Microsoft/visualfsharp/issues/3178

答:
This has now been resolved over at github, but for completeness, here's a summary.

The problem was that I, for some reason, had registered FSharp.Core 4.1.0.0 in the GAC:

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise>gacutil /l FSharp.Core
Microsoft (R) .NET Global Assembly Cache Utility.  Version 4.0.30319.0
Copyright (c) Microsoft Corporation.  All rights reserved.

The Global Assembly Cache contains the following assemblies:
  FSharp.Core, Version=2.3.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL
  FSharp.Core, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL
  FSharp.Core, Version=4.4.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL

Number of items = 3
</code>```

The third entry should not be there. I removed that:

```<code>gacutil /uf "FSharp.Core, Version=4.4.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
</code>```

After that, FSI and dotnet new started working correctly. To get Visual Studio to work, I also had to repair my VS installation and reboot, and now everything works.

Body:
I've installed FSharp 4.1 through the Visual Studio 2017 installer, but FSI refuses to start:

PS C:\Program Files (x86)\Microsoft SDKs\F#\4.1\Framework\v4.0> .\fsi

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly
'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one
of its dependencies. The system cannot find the file specified.
   at Microsoft.FSharp.Compiler.Interactive.Shell.MainMain(String[] argv)

I assume I'm missing something in a PATH variable or something, but despite several reinstalls and repairs I can't get past this error.

Where is FSI looking for this dll, and what should I install to put it there?

Update:

I've tried a few things, with no change to the outcome:

Remove F# 4.1 through the VS 2017 installer, verify that C:\Program Files (x86)\Microsoft SDKs\F#\4.1 did not exist, and reinstall F# 4.1

Uninstall all versions of .NET Core I had installed

Remove the C:\Program Files (x86)\Microsoft SDKs\F#\4.0 directory that doesn't seem to have an installer that cares for it. (FSI in that directory worked prior to removal...)

I've dumped the fusion logs to a zip file and put it on my Google Drive. There's a whole bunch of failed bindings, System.Runtime, Version 4.1.0.0 being one of them.

Issue filed here: https://github.com/Microsoft/visualfsharp/issues/3178

Body:
This has now been resolved over at github, but for completeness, here's a summary.

The problem was that I, for some reason, had registered FSharp.Core 4.1.0.0 in the GAC:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise>gacutil /l FSharp.Core
Microsoft (R) .NET Global Assembly Cache Utility.  Version 4.0.30319.0
Copyright (c) Microsoft Corporation.  All rights reserved.

The Global Assembly Cache contains the following assemblies:
  FSharp.Core, Version=2.3.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL
  FSharp.Core, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL
  FSharp.Core, Version=4.4.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL

Number of items = 3

The third entry should not be there. I removed that:

gacutil /uf "FSharp.Core, Version=4.4.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"

After that, FSI and dotnet new started working correctly. To get Visual Studio to work, I also had to repair my VS installation and reboot, and now everything works.


问:
How to enable sorting on a protected worksheet in Excel 2013
Hi  I'm new to VBA but have found numerous answers here to queries before, but there's one issue I can't resolve.  I've managed to enable outlining and filtering but can't get the code correct to enable sorting on unprotected cells within a sheet.  The code I have so far, which works exactly how required, is:

```<code>Private Sub Workbook_Open()

    For Each ws In Sheets
        With ws
            .Unprotect Password:="password"

            .Protect Password:="password", UserInterfaceOnly:=True

            .EnableOutlining = True
            .EnableAutoFilter = True
        End With
    Next ws

End Sub
</code>```

I've tried EnableSort = True, EnableSorting = True but neither works.  The code is within the Visual Basic and not a Macro (I hope this makes sense)

Any help would be greatly appreciated

答:
Try:</p>

```<code>AllowSorting:=True, AllowFiltering:=True
</code>```

Body:
Hi  I'm new to VBA but have found numerous answers here to queries before, but there's one issue I can't resolve.  I've managed to enable outlining and filtering but can't get the code correct to enable sorting on unprotected cells within a sheet.  The code I have so far, which works exactly how required, is:

Private Sub Workbook_Open()

    For Each ws In Sheets
        With ws
            .Unprotect Password:="password"

            .Protect Password:="password", UserInterfaceOnly:=True

            .EnableOutlining = True
            .EnableAutoFilter = True
        End With
    Next ws

End Sub

I've tried EnableSort = True, EnableSorting = True but neither works.  The code is within the Visual Basic and not a Macro (I hope this makes sense)

Any help would be greatly appreciated

Body:
Try:

AllowSorting:=True, AllowFiltering:=True


问:
How to use JUnit 5 with Gradle?
I am trying to use JUnit 5 with Gradle after I succeeded in running a JUnit 4 test.

Expected result: Tthe JUnit 4 test gave a nice 'passed' in the output and an html report in build/reports/tests.

Actual result: The JUnit 5 test as below does not output anything besides (...) build succesful, while I know the test is not actually run since there is no test log output passed/skipped/failed, and putting a fail in the test keeps the build successful.

Running gradle test --info yields Skipping task ':testClasses' as it has no actions. among a lot of I think mostly unrelevant output.
Surprisingly, it also says Executing task ':test' and Generating HTML test report... Finished generating test html results and similar for the xml in build/test-results/test, while the xml is not generated, the html shows no tests run and no errors, and the test is indeed not run.

What I also think very interesting, is that gradle test --debug yields

```<code>[TestEventLogger] Gradle Test Run :test STARTED
[org.gradle.api.internal.tasks.testing.junit.JUnitDetector] test-class-
scan : failed to scan parent class java/lang/Object, could not find the class file
[TestEventLogger]
[TestEventLogger] Gradle Test Run :test PASSED
</code>```

while my only test contains

```<code>fail("test fails");
</code>```

which I think is very strange!

My build file is

apply plugin: 'java'

test {
    dependsOn 'cleanTest' // run tests every time

}

sourceSets {
    main {
        java {
            srcDirs 'src'
        }
    }
    test {
        java {
            srcDirs 'test'
        }
    }
}

repositories {
    mavenCentral()
}

dependencies {
    // when using this, it worked with a junit 4 test
//    testCompile 'junit:junit:4.10'
    // this should be needed for junit 5 (using M4 is required since IJ 2017.1.2
    testCompile("org.junit.jupiter:junit-jupiter-api:5.0.0-M4")
}

test {
    testLogging {
        events "passed", "skipped", "failed"
    }
}
```

<p>My test is</p>

```package mypackage;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class HelloWorldTest {
    @Test
    public void testHelloWorld(){
        assertEquals(2, 1+1, "message");
    }
}
```

<p>My folder structure is, using package <code>mypackage</code>,</p>

```java-template-project
--- src
    --- mypackage
        --- HelloWorld.java
--- test
    --- mypackage
        --- HelloWorldTest.java
```

<p>and in IntelliJ 2017.1.3, which I am using, the module structure looks like this</p>

```java-template-project
--- java-template-project_main
    --- src/mypackage
        --- HelloWorld(.java)
--- java-template-project_test
    --- test/mypackage
        --- HelloWorldTest(.java)
```

<p>because Gradle nowadays wants the source and tests in their own package.</p>

<p><strong>What I tried</strong></p>

<p>Obviously this is not the first question about this topic, all the relevant questions I found are</p>

<ul>
<li><p>Gradle project running jUnit 5 tests in IntelliJ</p>

<p>But as you can see this is for older versions of IntelliJ, and I am already using the syntax for IJ 2016.3.3 and higher according to one of the answers, in  in the one JUnit dependency line, so that should be okay.</p></li>
<li><p>Upgrade from JUnit 4 to JUnit 5 in intellij with gradle</p>

<p>Links back to above question, and links to this Jetbrains blog which uses the same line as above question. Also links to:</p></li>
<li><p>Integrate JUnit 5 tests results with Intellij test report
This one shows, in the question, as dependency also</p>

```testRuntime("org.junit.vintage:junit-vintage-engine:5.0.0-M1")
```

<p>which is explained in Why were JUnit Jupiter and JUnit Vintage separated When I Running TestCase in IntelliJ?
Well, when I ran it, the output showed it couldn't find this version but according to the Maven Repository this one is for JUnit 5:</p>

```testRuntime("org.junit.vintage:junit-vintage-engine:4.12.0-M4")
```

<p>The answers there note that you can just run the tests within IntelliJ since the later versions have JUnit 5 support. I know, and the test runs fine when I run from within IntelliJ. But I want to use Gradle (and Travis, which needs dependency management).</p></li>
<li><p>How to capture stdout/stderr in junit 5 gradle test report?</p>

<p>I tried using </p>

```testCompile("org.junit.platform:junit-platform-gradle-plugin:1.0.0-M3")
testCompile("org.junit.jupiter:junit-jupiter-engine:5.0.0-M3")
```

but results didn't change.

My template project is located on https://github.com/PHPirates/java-template-project but this question should contain all information necessary.

答:
You need the engines for both JUnit versions, and you need to apply the JUnit platform gradle plugin. I do not see that in your gradle file. Here is a working gradle build executing both JUnit 4 and 5:

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath ("org.junit.platform:junit-platform-gradle-plugin:1.0.0-M4")
    }
}

apply plugin: 'org.junit.platform.gradle.plugin'
...

dependencies {
...
    testCompile("junit:junit:4.12")
    testRuntime("org.junit.vintage:junit-vintage-engine:4.12.0-M4")

    testCompile("org.junit.jupiter:junit-jupiter-api:5.0.0-M4")
    testRuntime("org.junit.jupiter:junit-jupiter-engine:5.0.0-M4")

    // Enable use of the JUnitPlatform Runner within the IDE
    testCompile("org.junit.platform:junit-platform-runner:1.0.0-M4")
}

junitPlatform {
    details 'tree'
}
</code>```

See the JUnit doc form more information on that.

Title: How to use JUnit 5 with Gradle?

Body:
I am trying to use JUnit 5 with Gradle after I succeeded in running a JUnit 4 test.

Expected result: Tthe JUnit 4 test gave a nice 'passed' in the output and an html report in build/reports/tests.

Actual result: The JUnit 5 test as below does not output anything besides (...) build succesful, while I know the test is not actually run since there is no test log output passed/skipped/failed, and putting a fail in the test keeps the build successful.

Running gradle test --info yields Skipping task ':testClasses' as it has no actions. among a lot of I think mostly unrelevant output.
Surprisingly, it also says Executing task ':test' and Generating HTML test report... Finished generating test html results and similar for the xml in build/test-results/test, while the xml is not generated, the html shows no tests run and no errors, and the test is indeed not run.

What I also think very interesting, is that gradle test --debug yields

[TestEventLogger] Gradle Test Run :test STARTED
[org.gradle.api.internal.tasks.testing.junit.JUnitDetector] test-class-
scan : failed to scan parent class java/lang/Object, could not find the class file
[TestEventLogger]
[TestEventLogger] Gradle Test Run :test PASSED

while my only test contains

fail("test fails");

which I think is very strange!

My build file is

apply plugin: 'java'

test {
    dependsOn 'cleanTest' // run tests every time

}

sourceSets {
    main {
        java {
            srcDirs 'src'
        }
    }
    test {
        java {
            srcDirs 'test'
        }
    }
}

repositories {
    mavenCentral()
}

dependencies {
    // when using this, it worked with a junit 4 test
//    testCompile 'junit:junit:4.10'
    // this should be needed for junit 5 (using M4 is required since IJ 2017.1.2
    testCompile("org.junit.jupiter:junit-jupiter-api:5.0.0-M4")
}

test {
    testLogging {
        events "passed", "skipped", "failed"
    }
}

My test is

package mypackage;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class HelloWorldTest {
    @Test
    public void testHelloWorld(){
        assertEquals(2, 1+1, "message");
    }
}

My folder structure is, using package mypackage,

java-template-project
--- src
    --- mypackage
        --- HelloWorld.java
--- test
    --- mypackage
        --- HelloWorldTest.java

and in IntelliJ 2017.1.3, which I am using, the module structure looks like this

java-template-project
--- java-template-project_main
    --- src/mypackage
        --- HelloWorld(.java)
--- java-template-project_test
    --- test/mypackage
        --- HelloWorldTest(.java)

because Gradle nowadays wants the source and tests in their own package.

What I tried

Obviously this is not the first question about this topic, all the relevant questions I found are

Gradle project running jUnit 5 tests in IntelliJ

But as you can see this is for older versions of IntelliJ, and I am already using the syntax for IJ 2016.3.3 and higher according to one of the answers, in  in the one JUnit dependency line, so that should be okay.

Upgrade from JUnit 4 to JUnit 5 in intellij with gradle

Links back to above question, and links to this Jetbrains blog which uses the same line as above question. Also links to:

Integrate JUnit 5 tests results with Intellij test report
This one shows, in the question, as dependency also

testRuntime("org.junit.vintage:junit-vintage-engine:5.0.0-M1")

which is explained in Why were JUnit Jupiter and JUnit Vintage separated When I Running TestCase in IntelliJ?
Well, when I ran it, the output showed it couldn't find this version but according to the Maven Repository this one is for JUnit 5:

testRuntime("org.junit.vintage:junit-vintage-engine:4.12.0-M4")

The answers there note that you can just run the tests within IntelliJ since the later versions have JUnit 5 support. I know, and the test runs fine when I run from within IntelliJ. But I want to use Gradle (and Travis, which needs dependency management).

How to capture stdout/stderr in junit 5 gradle test report?

I tried using

testCompile("org.junit.platform:junit-platform-gradle-plugin:1.0.0-M3")
testCompile("org.junit.jupiter:junit-jupiter-engine:5.0.0-M3")

but results didn't change.

My template project is located on https://github.com/PHPirates/java-template-project but this question should contain all information necessary.

Body:
You need the engines for both JUnit versions, and you need to apply the JUnit platform gradle plugin. I do not see that in your gradle file. Here is a working gradle build executing both JUnit 4 and 5:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath ("org.junit.platform:junit-platform-gradle-plugin:1.0.0-M4")
    }
}

apply plugin: 'org.junit.platform.gradle.plugin'
...

dependencies {
...
    testCompile("junit:junit:4.12")
    testRuntime("org.junit.vintage:junit-vintage-engine:4.12.0-M4")

    testCompile("org.junit.jupiter:junit-jupiter-api:5.0.0-M4")
    testRuntime("org.junit.jupiter:junit-jupiter-engine:5.0.0-M4")

    // Enable use of the JUnitPlatform Runner within the IDE
    testCompile("org.junit.platform:junit-platform-runner:1.0.0-M4")
}

junitPlatform {
    details 'tree'
}

See the JUnit doc form more information on that.