问:
how to prove a task is done in minimum required commands
Is it possible to show that a task is done in the minimum amount of required commands or lines of code in a language, it is obvious that if you can do a task in one command this is the shortest way to do so but this is only going to be true of tasks like addition, if I say created an algorithm for sorting how would I know that there does or does not exist a faster way to carry out this task?</p>

答:
First off, minimum number of lines of code does not necessarily mean minimum number of commands. (i.e. processor commands) As the former is not really significant in an algorithmic sense, I am assuming that you are trying to find out the latter.

On that note, there are a variety of techniques to prove the minimum number of steps(not commands) needed to do some complex tasks. Finding the minimal number of steps necessary to achieve a task does not directly correspond to the minimum number of commands; but it should be relatively trivial to modify these techniques to find out the minimum number of commands essential to solve the problem. Note that these techniques may not necessarily yield a lower bound for every complex task, and whether a lower bound can be found depends on the specific task.

Incidentally, (comparison-based) sorting, which was mentioned in your question, is one of the tasks for which there is such a proof method, namely decision trees. You may find a more detailed description of the method on many sources including here but the method simply tries to find the least number of comparisons that has to be made in order to sort an array. It is a well-known technique lying at the heart of proving why comparison-based sorting algorithms have a time complexity lower bound of NlogN.


来源: stackexchange

问:
How can I switch to another branch in git?
Which one of these lines is correct?

```<code>git checkout 'another_branch'
</code>```

or

```<code>git checkout origin 'another_branch'
</code>```

or

```<code>git checkout origin/'another_branch'
</code>```

And what is the difference between them?

答:
If another_branch already exists locally and you are not on this branch, then git checkout another_branch switches to the branch.

If another_branch does not exist but origin/another_branch does, then git checkout another_branch is equivalent to git checkout -b another_branch origin/another_branch; git branch -u origin/another_branch. That's to create another_branch from origin/another_branch and set origin/another_branch as the upstream of another_branch.

If neither exists, git checkout another_branch returns error.

git checkout origin another_branch returns error in most cases. If origin is a revision and another_branch is a file, then it checks out the file of that revision but most probably that's not what you expect. origin is mostly used in git fetch, git pull and git push as a remote, an alias of the url to the remote repository.

git checkout origin/another_branch succeeds if origin/another_branch exists. It leads to be in detached HEAD state, not on any branch. If you make new commits, the new commits are not reachable from any existing branches and none of the branches will be updated.

UPDATE:

As 2.23.0 has been released, with it we can also use git switch to create and switch branches.

If foo exists, try to switch to foo:

```<code>git switch foo
</code>```

If foo does not exist and origin/foo exists, try to create foo from origin/foo and then switch to foo:

```<code>git switch -c foo origin/foo
# or simply
git switch foo
</code>```

More generally, if foo does not exist, try to create foo from a known ref or commit and then switch to foo:

```<code>git switch -c foo <ref>
git switch -c foo <commit>
</code>```

If we maintain a repository in Gitlab and Github at the same time, the local repository may have two remotes, for example, origin for Gitlab and github for Github. In this case the repository has origin/foo and github/foo. git switch foo will complain fatal: invalid reference: foo, because it does not known from which ref, origin/foo or github/foo, to create foo. We need to specify it with git switch -c foo origin/foo or git switch -c foo github/foo according to the need. If we want to create branches from both remote branches, it's better to use distinguishing names for the new branches:

```<code>git switch -c gitlab_foo origin/foo
git switch -c github_foo github/foo
</code>```

If foo exists, try to recreate/force-create foo from (or reset foo to) a known ref or commit and then switch to foo:

```<code>git switch -C foo <ref>
git switch -C foo <commit>
</code>```

which are equivalent to:

```<code>git switch foo
git reset [<ref>|<commit>] --hard
</code>```

Try to switch to a detached HEAD of a known ref or commit:

```<code>git switch -d <ref>
git switch -d <commit>
</code>```

If you just want to create a branch but not switch to it, use git branch instead. Try to create a branch from a known ref or commit:

```<code>git branch foo <ref>
git branch foo <commit>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Which one of these lines is correct?

git checkout 'another_branch'

or

git checkout origin 'another_branch'

or

git checkout origin/'another_branch'

And what is the difference between them?

Body:
If another_branch already exists locally and you are not on this branch, then git checkout another_branch switches to the branch.

If another_branch does not exist but origin/another_branch does, then git checkout another_branch is equivalent to git checkout -b another_branch origin/another_branch; git branch -u origin/another_branch. That's to create another_branch from origin/another_branch and set origin/another_branch as the upstream of another_branch.

If neither exists, git checkout another_branch returns error.

git checkout origin another_branch returns error in most cases. If origin is a revision and another_branch is a file, then it checks out the file of that revision but most probably that's not what you expect. origin is mostly used in git fetch, git pull and git push as a remote, an alias of the url to the remote repository.

git checkout origin/another_branch succeeds if origin/another_branch exists. It leads to be in detached HEAD state, not on any branch. If you make new commits, the new commits are not reachable from any existing branches and none of the branches will be updated.

UPDATE:

As 2.23.0 has been released, with it we can also use git switch to create and switch branches.

If foo exists, try to switch to foo:

git switch foo

If foo does not exist and origin/foo exists, try to create foo from origin/foo and then switch to foo:

git switch -c foo origin/foo
# or simply
git switch foo

More generally, if foo does not exist, try to create foo from a known ref or commit and then switch to foo:

git switch -c foo <ref>
git switch -c foo <commit>

If we maintain a repository in Gitlab and Github at the same time, the local repository may have two remotes, for example, origin for Gitlab and github for Github. In this case the repository has origin/foo and github/foo. git switch foo will complain fatal: invalid reference: foo, because it does not known from which ref, origin/foo or github/foo, to create foo. We need to specify it with git switch -c foo origin/foo or git switch -c foo github/foo according to the need. If we want to create branches from both remote branches, it's better to use distinguishing names for the new branches:

git switch -c gitlab_foo origin/foo
git switch -c github_foo github/foo

If foo exists, try to recreate/force-create foo from (or reset foo to) a known ref or commit and then switch to foo:

git switch -C foo <ref>
git switch -C foo <commit>

which are equivalent to:

git switch foo
git reset [<ref>|<commit>] --hard

Try to switch to a detached HEAD of a known ref or commit:

git switch -d <ref>
git switch -d <commit>

If you just want to create a branch but not switch to it, use git branch instead. Try to create a branch from a known ref or commit:

git branch foo <ref>
git branch foo <commit>


问:
Bootstrap 4 collapsed navbar not working
I have problem with collapsed navbar in Bootstrap4.

```<code><nav class="navbar navbar-toggleable-md navbar-inverse fixed-top bg-inverse">
      <button class="navbar-toggler navbar-toggler-right collapsed" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <a class="  navbar-brand" href="#myCarousel">
        <img src="image/logo.svg" height="50">
      </a>
      <div class="collapse navbar-collapse" id="navbarCollapse">
        <ul class="navbar-nav nav mr-auto">
           <li class="nav-item">
            <a class="nav-link" href="#2"  data-toggle="collapse" data-target=".navbar-collapse.show">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#3"  data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#4"  data-toggle="collapse" data-target=".navbar-collapse.show">Contact</a>
          </li>
        </ul>

      </div>
    </nav>
</code>```

Of course ihave added right id to another elements, like:

```<code><div class="container marketing" id="2">
</code>```

Menu doesn't work. When i click on element of navbar, menu close but doesn't move to right site.

When delete collapse's attributes:

```<code>data-toggle="collapse" data-target=".navbar-collapse.show"
</code>```

menu doesn't close on click but move to right site.

Thanks :)

答:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <button class="navbar-toggler navbar-toggler-right collapsed" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home

            About

            Contact

    ```

ContentLicense: CC BY-SA 3.0

Body:
I have problem with collapsed navbar in Bootstrap4.

      <button class="navbar-toggler navbar-toggler-right collapsed" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home

            About

            Contact

Of course ihave added right id to another elements, like:

Menu doesn't work. When i click on element of navbar, menu close but doesn't move to right site.

When delete collapse's attributes:

data-toggle="collapse" data-target=".navbar-collapse.show"

menu doesn't close on click but move to right site.

Thanks :)

Body:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

 <nav class="navbar navbar-toggleable-md navbar-inverse fixed-top bg-inverse">
      <button class="navbar-toggler navbar-toggler-right collapsed" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <a class="  navbar-brand" href="#myCarousel">
        <img src="image/techNET.svg" height="50">
      </a>
      <div class="collapse navbar-collapse" id="navbarCollapse">
        <ul class="navbar-nav nav mr-auto">
           <li class="nav-item">
            <a class="nav-link" href="#2"  data-toggle="collapse" data-target=".navbar-collapse.show">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#3"  data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#4">Contact</a>
          </li>
        </ul>

      </div>
    </nav>


问:
SimpleExpandableListAdapter sections titles
I implemented my SimpleExpandableListAdapter, and I'm trying to customize the section titles. To do this I pass to the constructor the id of a custom TextView for the groupTo parameter:

```<code>    setListAdapter( new SimpleExpandableListAdapter(this,
                                                    groupsData,
                                                    android.R.layout.simple_expandable_list_item_1,
                                                    new String[]{SECTION},
                                                    new int[]{R.id.list_group_title},
                                                    innerData,
                                                    0,
                                                    null,
                                                    new int[]{}){ /*my code here*/ });

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_group_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20dip" />
</code>```

Problem is, nothing is showing up! The whole thing is blank, as if the view wasn't there.
Any idea on why, or any link I could read up to solve this? Thanks!

答:
```<code>    MyAdapter ma = new MyAdapter(this,groupsData,android.R.layout.simple_expandable_list_item_1,new String[]{SECTION}, new int[]{R.layout.list_group_title},innerData,0,null,new int[]{});
    setListAdapter(ma);

    private static class MyAdapter extends SimpleExpandableListAdapter
    {
            LayoutInflater layoutInflater;
            int title;

            public MyAdapter(Context context,List<? extends Map<String, ?>> groupData,int groupLayout,String[ ] groupFrom,int[ ] groupTo,List<? extends List<? extends Map<String, ?>>> childData,int childLayout,String[ ] childFrom, int[ ] childTo)
            {
                super(context,groupData,groupLayout,groupFrom,groupTo,childData,childLayout,childFrom,childTo);
                title = groupTo[0];
                layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            }
            @Override
            public View getGroupView(int groupPosition,boolean isExpanded,View convertView,ViewGroup parent)
            {
                return (TextView)layoutInflater.inflate(title,null);
            }
    }
</code>```

Inflating it in getGroupView does the trick. Still, I don't understand why it is not passed automatically to the super constructor.

ContentLicense: CC BY-SA 2.5

Body:
I implemented my SimpleExpandableListAdapter, and I'm trying to customize the section titles. To do this I pass to the constructor the id of a custom TextView for the groupTo parameter:

    setListAdapter( new SimpleExpandableListAdapter(this,
                                                    groupsData,
                                                    android.R.layout.simple_expandable_list_item_1,
                                                    new String[]{SECTION},
                                                    new int[]{R.id.list_group_title},
                                                    innerData,
                                                    0,
                                                    null,
                                                    new int[]{}){ /*my code here*/ });

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_group_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20dip" />

Problem is, nothing is showing up! The whole thing is blank, as if the view wasn't there.
Any idea on why, or any link I could read up to solve this? Thanks!

Body:
    MyAdapter ma = new MyAdapter(this,groupsData,android.R.layout.simple_expandable_list_item_1,new String[]{SECTION}, new int[]{R.layout.list_group_title},innerData,0,null,new int[]{});
    setListAdapter(ma);

    private static class MyAdapter extends SimpleExpandableListAdapter
    {
            LayoutInflater layoutInflater;
            int title;

            public MyAdapter(Context context,List<? extends Map<String, ?>> groupData,int groupLayout,String[ ] groupFrom,int[ ] groupTo,List<? extends List<? extends Map<String, ?>>> childData,int childLayout,String[ ] childFrom, int[ ] childTo)
            {
                super(context,groupData,groupLayout,groupFrom,groupTo,childData,childLayout,childFrom,childTo);
                title = groupTo[0];
                layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            }
            @Override
            public View getGroupView(int groupPosition,boolean isExpanded,View convertView,ViewGroup parent)
            {
                return (TextView)layoutInflater.inflate(title,null);
            }
    }

Inflating it in getGroupView does the trick. Still, I don't understand why it is not passed automatically to the super constructor.


问:
Why does UPDATE statement give divide by zero even if that particular row doesn't exist?
Ok this may be idiot question but I want to know why does the update statement gives divided by 0 operation even thought there is no row in the table. Does it execute the set function first and then try to apply to the where clause.</p>

```<code>  CREATE TABLE #tmp
    (
    Id INT,
    Amount money
    )

    UPDATE t
    SET t.Amount=0/0
    FROM #tmp AS t
    WHERE t.Id=2

    DROP TABLE #tmp
</code>```

答:
In SQL, you tell the system what you want, not how to do it.

Integer division is deterministic and you have an expression (0/0) that has no dependency on row values. It therefore seems perfectly reasonable to extract the expression 0/0 out, perform that calculation first, and then use the result of that expression as it actually scans through the table. So you get an error because it's not even started any work of processing the table.

In Guido's answer, the optimizer found a WHERE clause that meant that it could already tell that the query would affect zero rows (without needing to access any statistics about the table) and so it was able to optimize its work even further.

Body:
Ok this may be idiot question but I want to know why does the update statement gives divided by 0 operation even thought there is no row in the table. Does it execute the set function first and then try to apply to the where clause.

  CREATE TABLE #tmp
    (
    Id INT,
    Amount money
    )

    UPDATE t
    SET t.Amount=0/0
    FROM #tmp AS t
    WHERE t.Id=2

    DROP TABLE #tmp


问:
pop up form data not insert in database
I'm trying to insert data  to my PHP using ajax post method.I have passed the first form data to hidden value in first script , but data is not inserted in database.Now I want to pass those variables (response.lastname, response.firstname ) into my database.Please help me to solve this issue. Any example will be very useful.. thank u in advance.

php ajax

```<code><div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            Confirm Submit
        </div>   <form role="form" id="add_name"  method="post"  enctype="multipart/form-data" action="">
        <div class="modal-body">
                          <table class="table">
                <tr>
                    <th>Last Name</th>
                    <td id="lname" name="lname" ></td>
                </tr>
                <tr>
                    <th>First Name</th>
                    <td id="fname" name="fname"></td>
                </tr>
                <tr><td>name</td>
                <td><input type="text" name="nam"></td>
                </tr>     </table>

        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal" >Cancel</button>
             <button    type="submit" class="btn btn-success" id="submit" name="submit"><i class="glyphicon glyphicon-inbox"></i> Submit</button>

        </div>
    </div>
  </form><div id="response"></div>

  <script>

   $(document).ready(function(){

        $('#submitBtn').click(function() {

            $('#lname').text($('#lastname').val());
        $('#fname').text($('#firstname').val());

            var fname = $('#firstname').val();
            $('#fname').val(fname);
            alert(fname);

            var laname = $('#lastname').val();
            $('#lname').val(laname);
            alert(laname);
        });

    });
</script>

 <script>
   $(document).ready(function(){
  $('#submit').click(function(){
       var lname = $('#lname').val();
       var fname = $('#fname').val();
     alert(lname);
            $.ajax({
                 url:"insert.php",
                 method:"POST",
                 data:$('#add_name').serialize(),
                 beforeSend:function(){
                      $('#response').html('<span class="text-info">Loading response...</span>');
                 },
                 success:function(data){
                      $('form').trigger("reset");
                      $('#response').fadeIn().html(data);
                      setTimeout(function(){
                           $('#response').fadeOut("slow");
                      }, 5000);
                 }
            });

  });
});
</code>```

```<code>  <?php
 //insert.php
 $connect = mysqli_connect("localhost", "root", "", "demoss");

  $name = mysqli_real_escape_string($connect, $_POST["lname"]);
  $message = mysqli_real_escape_string($connect, $_POST["fname"]);
  $query = "INSERT INTO tbl_form(name, message) VALUES ('".$name."', '".$message."')";
  if(mysqli_query($connect, $query))
  {
       echo '<p>You have entered</p>';
       echo '<p>Name:'.$name.'</p>';
       echo '<p>Message : '.$message.'</p>';
  }

 ?>
</code>```

答:
data:$('#add_name').serialize(), - this convert inputs / textareas in form to one string for url. Your form not have inputs. Try

alert($('#add_name').serialize()) or

alert($('#add_name').serialize().toSource()) // firefox

And, may be second problem, if you call two times $(document).ready, may be rewrite first code with second. Combine to one $(document).ready.

```<code> $(document).ready(function(){  callfunction1(); callfunction2(); }
</code>```

Title: pop up form data not insert in database

Body:
I'm trying to insert data  to my PHP using ajax post method.I have passed the first form data to hidden value in first script , but data is not inserted in database.Now I want to pass those variables (response.lastname, response.firstname ) into my database.Please help me to solve this issue. Any example will be very useful.. thank u in advance.

php ajax

            Confirm Submit

   <form role="form" id="add_name"  method="post"  enctype="multipart/form-data" action="">

                    Last Name

                    First Name

name
                <input type="text" name="nam">

            <button type="button" class="btn btn-default" data-dismiss="modal" >Cancel</button>
             <button    type="submit" class="btn btn-success" id="submit" name="submit"> Submit</button>

  </form>

Body:
data:$('#add_name').serialize(), - this convert inputs / textareas in form to one string for url. Your form not have inputs. Try

alert($('#add_name').serialize()) or<br>

alert($('#add_name').serialize().toSource()) // firefox <br>

And, may be second problem, if you call two times $(document).ready, may be rewrite first code with second. Combine to one $(document).ready.<br>

 $(document).ready(function(){  callfunction1(); callfunction2(); }


问:
In laravel 5.5 use carbon to compare 2 dates
In laravel 5.5 I use carbon to compare 2 dates, but the thing is that createFromFormat returns timestamp and I do not know

how to set time to “00:00:00” . I make :

```<code>echo 'passes ```$value::'.print_r($value, true).'```';
// output 2018-08-01

$postgresql_format = config('app.postgresql_date_format', 'Y-m-d');

echo '```$postgresql_format::'.print_r($postgresql_format,true).'```';
// output $postgresql_format::Y-m-d

$A = preg_split("/ /", $value);
if (count($A) == 2) {
    $value= $A[0];
}

$a= Carbon::createFromFormat($postgresql_format, $value);

echo '```$a->isPast()::'.print_r($a->isPast(),true).'```';
//output $a->isPast():: - seems it is does not work

$today= Carbon::today();
echo '```$today::'.print_r($today,true).'```';
/* Output:
$today::Carbon\Carbon Object
(
    [date] => 2017-12-04 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)
 */

var_dump($today->lt($a)); // bool(false)
echo '```$a::'.print_r($a,true).'```';

/*
$a::Carbon\Carbon Object
(
    [date] => 2018-08-01 08:41:56.000000
    [timezone_type] => 3
    [timezone] => UTC
)
 */
</code>```

How to set time of $a to “00:00:00” to exclude time from comparison ?

PS: $a->isPast() does not seems to work

Thanks!

答:
You can solve it by using like this.

Carbon::parse('2018-08-01 08:41:56.000000')->format('Y/m/d');

further reference is here and here

For the comparison you can do it like so

    $date = Carbon::parse('2016-09-17 11:00:00');
    $now = Carbon::now();

    $diff = $date->diffInDays($now);
```

Body:
In laravel 5.5 I use carbon to compare 2 dates, but the thing is that createFromFormat returns timestamp and I do not know

how to set time to “00:00:00” . I make :

echo 'passes
$value::'.print_r($value, true).'
';
// output 2018-08-01

$postgresql_format = config('app.postgresql_date_format', 'Y-m-d');

echo '
$postgresql_format::'.print_r($postgresql_format,true).'
';
// output $postgresql_format::Y-m-d

$A = preg_split("/ /", $value);
if (count($A) == 2) {
    $value= $A[0];
}

$a= Carbon::createFromFormat($postgresql_format, $value);

echo '
$a->isPast()::'.print_r($a->isPast(),true).'
';
//output $a->isPast():: - seems it is does not work

$today= Carbon::today();
echo '
$today::'.print_r($today,true).'
';
/* Output:
$today::Carbon\Carbon Object
(
    [date] => 2017-12-04 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)
 */

var_dump($today->lt($a)); // bool(false)
echo '
$a::'.print_r($a,true).'
';

/*
$a::Carbon\Carbon Object
(
    [date] => 2018-08-01 08:41:56.000000
    [timezone_type] => 3
    [timezone] => UTC
)
 */

How to set time of $a to “00:00:00” to exclude time from comparison ?

PS: $a->isPast() does not seems to work

Thanks!


问:
ZXing.Net.Mobile : Using GenericMultipleBarcodeReader for scanning Multiple barcodes
I am new to ZXing.net library and I am trying to use it to read multiple barcodes(for now it is 3 barcodes) in one go, I got to know that I need to use the feature, GenericMultipleBarcodeReader. Has anyone tried that and could possibly share some sample code?

I tried to use ScanContinuously and I don't think it suits my purpose of scanning in one go. Could you please help?

Thanks

答:
All that you need is here :

https://components.xamarin.com/gettingstarted/zxing.net.mobile

https://github.com/Redth/ZXing.Net.Mobile

The Github example code has all you might need.


问:
Not able to load servlet context in Spring
I'm trying to load the properties data on server startup. For this I have created a class that implements ServletContextListener. This will load all the properties.

And in my DaoImpl class, I'm trying to get the properties data and get initialized to some of the strings. But it throws the exception

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testController': Unsatisfied dependency expressed through field 'bbService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bbService': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'BBDAO' defined in ServletContext resource [/WEB-INF/spring-web-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bb.dao.BBDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
</code>```

Here is my Config class

```<code>public class Config implements ServletContextListener {

private static final String ATTRIBUTE_NAME = "config";
private Properties config = new Properties();

@Override
public void contextInitialized(ServletContextEvent event){
    try {
        Resource resource = new ClassPathResource("/uat.properties");
        config = PropertiesLoaderUtils.loadProperties(resource);
    } catch (IOException e) {
        try {
            throw new QiibException("Loading config failed");
        } catch (QiibException e1) {
            e1.printStackTrace();
        }
    }
    event.getServletContext().setAttribute(ATTRIBUTE_NAME, this);
}

@Override
public void contextDestroyed(ServletContextEvent event) {
}

public static Config getInstance(ServletContext context) {
    return (Config) context.getAttribute(ATTRIBUTE_NAME);
}

public String getProperty(String key) {
    return config.getProperty(key);
}
}
</code>```

The DAOImpl class is

```<code>public class BBDaoImpl extends JdbcDaoSupport implements BBDao, ServletContextAware  {

Properties properties = null;

@Autowired
private ServletContext ctx;

public void setServletContext(ServletContext servletContext) {
    this.ctx = servletContext;
}

public BBDaoImpl() throws IOException {
    super();
    Config config = Config.getInstance(ctx); --> ctx is null here.
</code>```

What is wrong here?

Any ideas would be greatly appreciated.

答:
Noticed that you just want to get some properties and initialize your class,why don't achieve this in a spring way

put your properties in spring property file , and make BBDaoImpl  implement EnvironmentAware interface and InitializingBean interface,then you can initialize BBDaoImpl in afterPropertiesSet method  declared in InitializingBean.The key process is implementing EnvironmentAware ,thus you get the reference of environment object, by which you can  get your properties

Or you can implement ServletConfigAware, it's similar to the above

Body:
I'm trying to load the properties data on server startup. For this I have created a class that implements ServletContextListener. This will load all the properties.

And in my DaoImpl class, I'm trying to get the properties data and get initialized to some of the strings. But it throws the exception

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testController': Unsatisfied dependency expressed through field 'bbService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bbService': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'BBDAO' defined in ServletContext resource [/WEB-INF/spring-web-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bb.dao.BBDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException

Here is my Config class

public class Config implements ServletContextListener {

private static final String ATTRIBUTE_NAME = "config";
private Properties config = new Properties();

@Override
public void contextInitialized(ServletContextEvent event){
    try {
        Resource resource = new ClassPathResource("/uat.properties");
        config = PropertiesLoaderUtils.loadProperties(resource);
    } catch (IOException e) {
        try {
            throw new QiibException("Loading config failed");
        } catch (QiibException e1) {
            e1.printStackTrace();
        }
    }
    event.getServletContext().setAttribute(ATTRIBUTE_NAME, this);
}

@Override
public void contextDestroyed(ServletContextEvent event) {
}

public static Config getInstance(ServletContext context) {
    return (Config) context.getAttribute(ATTRIBUTE_NAME);
}

public String getProperty(String key) {
    return config.getProperty(key);
}
}

The DAOImpl class is

public class BBDaoImpl extends JdbcDaoSupport implements BBDao, ServletContextAware  {

Properties properties = null;

@Autowired
private ServletContext ctx;

public void setServletContext(ServletContext servletContext) {
    this.ctx = servletContext;
}

public BBDaoImpl() throws IOException {
    super();
    Config config = Config.getInstance(ctx); --> ctx is null here.

What is wrong here?

Any ideas would be greatly appreciated.


问:
Date Formatting in jquery datepicker
everybody...
I was wondering how I could format the a date in the datepicker 'd de MM de yy' in stead of 'dd/MM/yy'.

(suppose the date is 21/01/2011 (in spanish) .. so:
$("#element").datepicker({
     dateFormat:'d de MM de yy'
});

It will output : 21 21e Enero 21e yy

The question is.. is there an escape character so I can format the date?
Thanks, sorry for my English, hope you guys understand

答:
Try this for date format and year till the current year</p>

```<code>$('#element').datepicker({
        dateFormat: "dd M yy",
        changeMonth: true,
        changeYear: true,
        yearRange: "1920:+nn",
        maxDate: 0
    });
</code>```

Title: Date Formatting in jquery datepicker

Body:
Try this for date format and year till the current year

$('#element').datepicker({
        dateFormat: "dd M yy",
        changeMonth: true,
        changeYear: true,
        yearRange: "1920:+nn",
        maxDate: 0
    });


问:
Unable to increment a global variable
I need a variable to be passed along several functions & if statements, i'm going to keep it short.
I start off with initializing a static counter which i will use to keep track of the case number in my mysql database;

```<code>static $counter = 1;
</code>```

then i write my function in which i try to simply increment my global variable (this is in an if statement inside my function);

```<code>$counter++;
</code>```

Now my code compiles and runs perfectly but the counter seems to never increment and give every case id 1.
Anyone know how i managed to mess this up?

EDIT (Current structure):

```<code><?php
static $counter = 1;
function frontend($connection){
   global $counter;
   (...)
   if(isset($_POST['submit'])){
       (...)
       if(isset($_POST['betaald'])){
           $counter++;
       }
    }
} ...
</code>```

Now this code makes a neat database of all i need except the counter which seems to be unchangeable.

答:
Explain more about your code and see the example.

```<code>    <?php
   function keep_track() {
      STATIC $count = 0;
      $count++;
      print $count;
      print "<br />";
   }

   keep_track();
   keep_track();
   keep_track();
?>
</code>```

This will produce the following result −

```<code>1
2
3
</code>```

Title: Unable to increment a global variable

Body:
I need a variable to be passed along several functions & if statements, i'm going to keep it short.
I start off with initializing a static counter which i will use to keep track of the case number in my mysql database;

static $counter = 1;

then i write my function in which i try to simply increment my global variable (this is in an if statement inside my function);

$counter++;

Now my code compiles and runs perfectly but the counter seems to never increment and give every case id 1.
Anyone know how i managed to mess this up?

EDIT (Current structure):

<?php
static $counter = 1;
function frontend($connection){
   global $counter;
   (...)
   if(isset($_POST['submit'])){
       (...)
       if(isset($_POST['betaald'])){
           $counter++;
       }
    }
} ...

Now this code makes a neat database of all i need except the counter which seems to be unchangeable.

Body:
Explain more about your code and see the example.

    <?php
   function keep_track() {
      STATIC $count = 0;
      $count++;
      print $count;
      print "<br />";
   }

   keep_track();
   keep_track();
   keep_track();
?>

This will produce the following result −

1
2
3


问:
How to get rid of denominator in numerator and denominator in mathematica
I have the following expression

```<code>(-1 + 1/p)^B/(-1 + (-1 + 1/p)^(A + B))
</code>```

How can I multiply both the denominator and numberator by p^(A+B), i.e. to get rid of the denominators in both numerator and denominator? I tried varous Expand, Factor, Simplify etc. but none of them worked.

Thanks!

答:
If I understand you question, you may teach Mma some algebra:

```<code>r = {(k__ + Power[a_, b_]) Power[c_, b_] -> (k Power[c, b] + Power[a c, b]),
      p_^(a_ + b_) q_^a_ -> p^b ( q p)^(a),
      (a_ + b_) c_ -> (a c + b c)
    }
</code>```

and then define

```<code>s1 = ((-1 + 1/p)^B/(-1 + (-1 + 1/p)^(A + B)))

f[a_, c_] := (Numerator[a ] c //. r)/(Denominator[a ] c //. r)
</code>```

So that

```<code>f[s1, p^(A + B)]
</code>```

is

```<code>((1 - p)^B*p^A)/((1 - p)^(A + B) - p^(A + B))
</code>```

Body:
I have the following expression

(-1 + 1/p)^B/(-1 + (-1 + 1/p)^(A + B))

How can I multiply both the denominator and numberator by p^(A+B), i.e. to get rid of the denominators in both numerator and denominator? I tried varous Expand, Factor, Simplify etc. but none of them worked.

Thanks!

Body:
If I understand you question, you may teach Mma some algebra:

r = {(k__ + Power[a_, b_]) Power[c_, b_] -> (k Power[c, b] + Power[a c, b]),
      p_^(a_ + b_) q_^a_ -> p^b ( q p)^(a),
      (a_ + b_) c_ -> (a c + b c)
    }

and then define

s1 = ((-1 + 1/p)^B/(-1 + (-1 + 1/p)^(A + B)))

f[a_, c_] := (Numerator[a ] c //. r)/(Denominator[a ] c //. r)

So that

f[s1, p^(A + B)]

is

((1 - p)^B*p^A)/((1 - p)^(A + B) - p^(A + B))


问:
Android: Get a DAO in a ViewModel
What is the best way to get a Android Room DAO in a ViewModel?

Based on the paging library example I wrote this ViewModel:

```<code>class MyViewModel(myDao: MyDao) : ViewModel() {

    val data = myDao.get().create(
            /* initial load position */ 0,
            PagedList.Config.Builder()
                    .setPageSize(50)
                    .setPrefetchDistance(50)
                    .build())
}
</code>```

I then try to get an instance

```<code>val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
</code>```

Trying to run this I get an exception:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{....MyActivity}: java.lang.RuntimeException: Cannot create an instance of class ...MyViewModel
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: java.lang.RuntimeException: Cannot create an instance of class ...MyViewModel
    at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:145)
    at android.arch.lifecycle.ViewModelProviders$DefaultFactory.create(ViewModelProviders.java:158)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:128)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:96)
    ...
 Caused by: java.lang.InstantiationException: java.lang.Class<...MyViewModel> has no zero argument constructor
</code>```

From the paging library example it is not apparent how the view model gets a copy of the DAO, and apparently it fails. Question is if I have missed something, or is the example incomplete?

Googling the exception I find suggestions to use a ViewModelProvider.Factory, only the example did not use this. In the example code the view model looks like this:

```<code>class MyViewModel extends ViewModel {
    public final LiveData<PagedList<User>> usersList;
    public MyViewModel(UserDao userDao) {
        usersList = userDao.usersByLastName().create(
                /* initial load position */ 0,
                new PagedList.Config.Builder()
                        .setPageSize(50)
                        .setPrefetchDistance(50)
                        .build());
    }
}
</code>```

And is retreived like this

```<code>MyViewModel viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
</code>```

My dependencies

```<code>def roomVersion = "1.0.0"
implementation "android.arch.persistence.room:runtime:$roomVersion"
annotationProcessor "android.arch.persistence.room:compiler:$roomVersion"
kapt "android.arch.persistence.room:compiler:$roomVersion"
implementation "android.arch.paging:runtime:1.0.0-alpha3"
</code>```

答:
In your code, you have parameterized constructor in your ViewModel class for that you need to pass parameter while initializing ViewModel.

Below is the code in java

```<code>public class UserInfoViewModel extends AndroidViewModel {

    LiveData<PagedList<UserInfo>> usersForList;
    private PersonRepository personRepository;

    public UserInfoViewModel(@NonNull Application application) {
        super(application);
        personRepository = new PersonRepository(application);
    }

    public static class Factory extends ViewModelProvider.NewInstanceFactory {

        @NonNull
        private final Application mApplication;

        public Factory(@NonNull Application application) {
            mApplication = application;
        }

        @Override
        public <T extends ViewModel> T create(Class<T> modelClass) {
            //noinspection unchecked
            return (T) new UserInfoViewModel(mApplication);
        }
    }

    public void init() {

            usersForList = personRepository.getAllPersonsForList().create(0,
                    new PagedList.Config.Builder()
                            .setEnablePlaceholders(true)
                            .setPageSize(50)
                            .setPrefetchDistance(10)
                            .build());

    }
}
</code>```

In your Activity, you can access the ViewModel as shown in below code

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

        UserInfoViewModel.Factory factory = new UserInfoViewModel.Factory(
                this.getApplication());
        userInfoViewModel = ViewModelProviders.of(this,factory)
                .get(UserInfoViewModel.class);
        userInfoViewModel.init();
    }
</code>```

Here is my repository object in repository using DAO object as shown in below code

PersonRepository.java

```<code>public class PersonRepository {

    private final ChatListDAO personDAO;

    public PersonRepository(Context context) {
        personDAO = DatabaseCreator.getChatDatabase(context).ChatDatabase();
    }
}
</code>```

DAO.java class

```<code>@Dao
public interface DAO{

    @Insert(onConflict = OnConflictStrategy.REPLACE)
     long insertPerson(UserInfo person);

    @Update
     void updatePerson(UserInfo person);

    @Delete
     void deletePerson(UserInfo person);

    @Query("SELECT * FROM person")
     LiveData<List<UserInfo>> getAllPersons();

    @Query("SELECT count(*) FROM person")
     LiveData<Integer> getAllPersonsCount();

    @Query("SELECT * FROM person where number = :mobileIn")
     LiveData<UserInfo> getPersonByMobile(String mobileIn);

    @Query("SELECT * FROM person")
    public abstract LivePagedListProvider<Integer,UserInfo> getUsersForList();
}
</code>```

Title: Android: Get a DAO in a ViewModel

Body:
What is the best way to get a Android Room DAO in a ViewModel?

Based on the paging library example I wrote this ViewModel:

class MyViewModel(myDao: MyDao) : ViewModel() {

    val data = myDao.get().create(
            /* initial load position */ 0,
            PagedList.Config.Builder()
                    .setPageSize(50)
                    .setPrefetchDistance(50)
                    .build())
}

I then try to get an instance

val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)

Trying to run this I get an exception:

java.lang.RuntimeException: Unable to start activity ComponentInfo{....MyActivity}: java.lang.RuntimeException: Cannot create an instance of class ...MyViewModel
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: java.lang.RuntimeException: Cannot create an instance of class ...MyViewModel
    at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:145)
    at android.arch.lifecycle.ViewModelProviders$DefaultFactory.create(ViewModelProviders.java:158)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:128)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:96)
    ...
 Caused by: java.lang.InstantiationException: java.lang.Class<...MyViewModel> has no zero argument constructor

From the paging library example it is not apparent how the view model gets a copy of the DAO, and apparently it fails. Question is if I have missed something, or is the example incomplete?

Googling the exception I find suggestions to use a ViewModelProvider.Factory, only the example did not use this. In the example code the view model looks like this:

class MyViewModel extends ViewModel {
    public final LiveData<PagedList<User>> usersList;
    public MyViewModel(UserDao userDao) {
        usersList = userDao.usersByLastName().create(
                /* initial load position */ 0,
                new PagedList.Config.Builder()
                        .setPageSize(50)
                        .setPrefetchDistance(50)
                        .build());
    }
}

And is retreived like this

MyViewModel viewModel = ViewModelProviders.of(this).get(MyViewModel.class);

My dependencies

def roomVersion = "1.0.0"
implementation "android.arch.persistence.room:runtime:$roomVersion"
annotationProcessor "android.arch.persistence.room:compiler:$roomVersion"
kapt "android.arch.persistence.room:compiler:$roomVersion"
implementation "android.arch.paging:runtime:1.0.0-alpha3"

Body:
In your code, you have parameterized constructor in your ViewModel class for that you need to pass parameter while initializing ViewModel.

Below is the code in java

public class UserInfoViewModel extends AndroidViewModel {

    LiveData<PagedList<UserInfo>> usersForList;
    private PersonRepository personRepository;

    public UserInfoViewModel(@NonNull Application application) {
        super(application);
        personRepository = new PersonRepository(application);
    }

    public static class Factory extends ViewModelProvider.NewInstanceFactory {

        @NonNull
        private final Application mApplication;

        public Factory(@NonNull Application application) {
            mApplication = application;
        }

        @Override
        public <T extends ViewModel> T create(Class<T> modelClass) {
            //noinspection unchecked
            return (T) new UserInfoViewModel(mApplication);
        }
    }

    public void init() {

            usersForList = personRepository.getAllPersonsForList().create(0,
                    new PagedList.Config.Builder()
                            .setEnablePlaceholders(true)
                            .setPageSize(50)
                            .setPrefetchDistance(10)
                            .build());

    }
}

In your Activity, you can access the ViewModel as shown in below code

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

        UserInfoViewModel.Factory factory = new UserInfoViewModel.Factory(
                this.getApplication());
        userInfoViewModel = ViewModelProviders.of(this,factory)
                .get(UserInfoViewModel.class);
        userInfoViewModel.init();
    }

Here is my repository object in repository using DAO object as shown in below code

PersonRepository.java

public class PersonRepository {

    private final ChatListDAO personDAO;

    public PersonRepository(Context context) {
        personDAO = DatabaseCreator.getChatDatabase(context).ChatDatabase();
    }
}

DAO.java class

@Dao
public interface DAO{

    @Insert(onConflict = OnConflictStrategy.REPLACE)
     long insertPerson(UserInfo person);

    @Update
     void updatePerson(UserInfo person);

    @Delete
     void deletePerson(UserInfo person);

    @Query("SELECT * FROM person")
     LiveData<List<UserInfo>> getAllPersons();

    @Query("SELECT count(*) FROM person")
     LiveData<Integer> getAllPersonsCount();

    @Query("SELECT * FROM person where number = :mobileIn")
     LiveData<UserInfo> getPersonByMobile(String mobileIn);

    @Query("SELECT * FROM person")
    public abstract LivePagedListProvider<Integer,UserInfo> getUsersForList();
}


问:
Not allowed to load blob pdf resource in Microsoft Edge
This app is used to collect information from a DB and make a .pdf file from it.

```<code>this.reportsService.getTelerikReport({ reportId: this.selectReportId, startDate: this.startDate, endDate: this.endDate, ReportItems: listCheckItems})
        .then(response => {
            this.fileLoading = false;
            var file = new Blob([response], { type: "application/pdf" });
            this.fileUrl = this.$sce.trustAsResourceUrl(URL.createObjectURL(file));
            this.isReportGenerated = true;
</code>```

I'm receiving an error only in the Microsoft Edge console. A lot of people say it's a security problem with the Edge browser.

Can anyone provide me help for this?

答:
The old solution for Microsoft browsers still applies:

```<code>if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob);
}
else {
    var objectUrl = URL.createObjectURL(blob);
    window.open(objectUrl);
}
</code>```

Source here

Body:
This app is used to collect information from a DB and make a .pdf file from it.

this.reportsService.getTelerikReport({ reportId: this.selectReportId, startDate: this.startDate, endDate: this.endDate, ReportItems: listCheckItems})
        .then(response => {
            this.fileLoading = false;
            var file = new Blob([response], { type: "application/pdf" });
            this.fileUrl = this.$sce.trustAsResourceUrl(URL.createObjectURL(file));
            this.isReportGenerated = true;

I'm receiving an error only in the Microsoft Edge console. A lot of people say it's a security problem with the Edge browser.

Can anyone provide me help for this?

Body:
The old solution for Microsoft browsers still applies:

if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob);
}
else {
    var objectUrl = URL.createObjectURL(blob);
    window.open(objectUrl);
}

Source here


问:
Getting a split out of a string into a new column
I'm working on a data.frame trying to extract a part of a string between , and . and putting that into a neww column. I would like to use dplyr.

```<code>library(dplyr)

name <- c("Cumings, Mrs. John Bradley","Heikkinen, Miss. Laina","Moran, Mr. James","Allen, Mr. William Henry","Futrelle, Mrs. Jacques Heath (Lily May Peel)")
sex <- c("female","female","male","male","female")
age <- c(22,23,24,37,42)
data <- data.frame(name,sex,age)
</code>```

So I want to extract Mrs, Misss, Mr and so on into a own column.

```<code>data %>%
  mutate(title = strsplit(name, split = "[,.]")) %>%
  select(name,title)
</code>```

答: guess something like this: data %>% mutate(title = gsub(".*, |\\..*", "", name))

Body:
I'm working on a data.frame trying to extract a part of a string between , and . and putting that into a neww column. I would like to use dplyr.

library(dplyr)

name <- c("Cumings, Mrs. John Bradley","Heikkinen, Miss. Laina","Moran, Mr. James","Allen, Mr. William Henry","Futrelle, Mrs. Jacques Heath (Lily May Peel)")
sex <- c("female","female","male","male","female")
age <- c(22,23,24,37,42)
data <- data.frame(name,sex,age)

So I want to extract Mrs, Misss, Mr and so on into a own column.

data %>%
  mutate(title = strsplit(name, split = "[,.]")) %>%
  select(name,title)


问:
Asp.Net MVC 3 - @Html.Action won't render/return any HTML
I've been moving a fairly new project from ViewPages to Razor today, and all seems to be going well. Except I'm trying to use Html.Action to render a user control and it won't render anything.

So I have a Shared/_Layout.cshtml file which is referenced in Home/Index.cshtml

Index.cshtml has the following:

```<code><article>

@Html.Action("LatestBlogsMainPanelWidget", "Blogs")

...

</article>
</code>```

I've put traps in the BlogsController, so I know that's being requested. I also know that a model is being returned, that the LatestBlogsMainPanelWidget is being found by the view engine, and even some dummy Razor syntax code is being run:
@{
var s = "hello";
}

but the plain html in this file isn't making it to the browser. I've tried other (previously working) partials too and they won't appear either (view source on the page confirms it's not there).

I've also tried substituting for
@{ Html.RenderAction(...); } without success. HTML either side of the @Html.Action is appearing, so I know Index.cshtml is displaying properly.

Even more strangely the _Layout file also has Html.Action commands and they do appear fine.

I'm really not sure what else to check, or how to confirm that the pipeline is getting the HTML. Can anyone help at all?

Thanks!

答: Put a Layout = null on the partial view and it will work fine.</p>

Body:
I've been moving a fairly new project from ViewPages to Razor today, and all seems to be going well. Except I'm trying to use Html.Action to render a user control and it won't render anything.

So I have a Shared/_Layout.cshtml file which is referenced in Home/Index.cshtml

Index.cshtml has the following:

@Html.Action("LatestBlogsMainPanelWidget", "Blogs")

...

I've put traps in the BlogsController, so I know that's being requested. I also know that a model is being returned, that the LatestBlogsMainPanelWidget is being found by the view engine, and even some dummy Razor syntax code is being run:
@{
var s = "hello";
}

but the plain html in this file isn't making it to the browser. I've tried other (previously working) partials too and they won't appear either (view source on the page confirms it's not there).

I've also tried substituting for
@{ Html.RenderAction(...); } without success. HTML either side of the @Html.Action is appearing, so I know Index.cshtml is displaying properly.

Even more strangely the _Layout file also has Html.Action commands and they do appear fine.

I'm really not sure what else to check, or how to confirm that the pipeline is getting the HTML. Can anyone help at all?

Thanks!


问:
How to get JSON Data sent through postman tool using post method?
I'm trying to get a JSON data which is sent as JSON data using postman tool and trying to receive it my post() method.

```<code>    var express = require('express');
    var app = express();

    app.post('/myData',function(req,res){
        console.log("--->",req.body);
    });

var server = app.listen(8080,function(){});
</code>```

This is the JSON data sent through postman tool

I'm getting undefined in my console as
"---> undefined"

I'm trying to retrieve the JSON data set in my postman tool to either my console or browser

答:
Express usually uses a middleware called body-parser to parse the received JSON content. req.body will be empty if you don't enable body-parser or something similar. body-parser is built in for the latest versions of Express. It's enabled like this:

```<code>app.use(express.urlencoded({ extended: false }));
app.use(express.json());
</code>```

So the final code is like this:

```<code>var express = require('express');
var app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.post('/myData',function(req,res){
    console.log("--->", req.body);
    res.send('data received');
});

var server = app.listen(8080,function(){});
</code>```

I've also added res.send('data received');, because you should send a response when you get a request on a valid endpoint.

Body:
I'm trying to get a JSON data which is sent as JSON data using postman tool and trying to receive it my post() method.

    var express = require('express');
    var app = express();

    app.post('/myData',function(req,res){
        console.log("--->",req.body);
    });

var server = app.listen(8080,function(){});

This is the JSON data sent through postman tool

I'm getting undefined in my console as
"---> undefined"

I'm trying to retrieve the JSON data set in my postman tool to either my console or browser

Body:
Express usually uses a middleware called body-parser to parse the received JSON content. req.body will be empty if you don't enable body-parser or something similar. body-parser is built in for the latest versions of Express. It's enabled like this:

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

So the final code is like this:

var express = require('express');
var app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.post('/myData',function(req,res){
    console.log("--->", req.body);
    res.send('data received');
});

var server = app.listen(8080,function(){});

I've also added res.send('data received');, because you should send a response when you get a request on a valid endpoint.


问:
Matlab: Search everywhere shortcut
Is there any shortcut in Matlab comparable to Search Everywhere in the JetBrains universe or Control-P in Sublime?

A shortcut that searches for files/ folder/ functions etc. in the current directory and makes it possible to switch there by pressing enter?

答:
I think this is what you are looking for: Find Files and Folders. And you probably want to use the advanced features:

To conduct an advanced search for files, you can use the Find Files
  tool. Use the Find Files tool to:

Search for specific text in file names and within files

Include or exclude specified file types from your search

Search in specified folders

Exclude large files from your search

To open the Find Files tool, on the Home tab, in the File section,
  click Find Files. Enter your search criteria in the dialog box that
  opens.

The keyboard shortcut shoud be CTRL+SHIFT+F but I'm not sure.

Title: Matlab: Search everywhere shortcut


问:
How to configure Managed App Configuration in a Cordova app?
I am working on an ionic-cordova app and I want to use AirWatch MDM to deploy the app: https://www.air-watch.com/faq/what-is-mdm

I see that there is a plugin for Cordova that might possibly help with this task:
https://github.com/apla/me.apla.cordova.app-preferences
but it doesn't say where to put the key-value pairs.

It seems inconvenient and unmaintainable to have to change the build files each time I do either an Android or an iOS build.

Is there a place I can put an XML file for this and do it automatically on each build?

答:
TL;DR: No.

I suggest using Cordova AppConfig Plugin by Oracle to implement App configuration.

iOS setup (easy):
Handles the configuration via Managed AppConfig. Just add the Key-value pairs in the assignment tab from AirWatch when you publish the app.

Android (a bit harder):
Android relies on App Restrictions so you'll need to edit the Android studio project (follow the instructions from the link).
The tricky part is that the key-value pairs must be validated by google. Thus you'll have to upload the ap to Google Play Store or to Android for Work private store to read them from the app.

Common: Read the values using the linked plugin (one line of code, see example in the plugin's page).


问:
How to disable the shadow around card view in android
I am working on demo application in which I am using the card view of the support library. By default, it is adding a shadow around it. I want to remove this shadow & should looks like simple.

I tried this (not working for me):

```<code>CardView cardView = (CardView) v.findViewById(R.id.cardView);
cardView.setElevation(0);
</code>```

After doing these I am getting crash

```<code>11-06 15:12:17.018: E/AndroidRuntime(24315): FATAL EXCEPTION: main
11-06 15:12:17.018: E/AndroidRuntime(24315): Process: com.xyz, PID: 24315
11-06 15:12:17.018: E/AndroidRuntime(24315): java.lang.NoSuchMethodError: android.support.v7.widget.CardView.setElevation
11-06 15:12:17.018: E/AndroidRuntime(24315):    at com.xyz.adapters.RecycleViewAdapter.onCreateViewHolder(RecycleViewAdapter.java:85)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at com.xyz.adapters.RecycleViewAdapter.onCreateViewHolder(RecycleViewAdapter.java:1)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:2915)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:2511)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.LinearLayoutManager$RenderState.next(LinearLayoutManager.java:1425)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.LinearLayoutManager$RenderState.next(LinearLayoutManager.java:1425)
</code>```

layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res/com.xyz"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:orientation="horizontal" >
</code>```

答:
Just put this line inside your CardView:

```<code>app:cardElevation="0dp"
</code>```

Hope it will help you.

Body:
I am working on demo application in which I am using the card view of the support library. By default, it is adding a shadow around it. I want to remove this shadow & should looks like simple.

I tried this (not working for me):

CardView cardView = (CardView) v.findViewById(R.id.cardView);
cardView.setElevation(0);

After doing these I am getting crash

11-06 15:12:17.018: E/AndroidRuntime(24315): FATAL EXCEPTION: main
11-06 15:12:17.018: E/AndroidRuntime(24315): Process: com.xyz, PID: 24315
11-06 15:12:17.018: E/AndroidRuntime(24315): java.lang.NoSuchMethodError: android.support.v7.widget.CardView.setElevation
11-06 15:12:17.018: E/AndroidRuntime(24315):    at com.xyz.adapters.RecycleViewAdapter.onCreateViewHolder(RecycleViewAdapter.java:85)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at com.xyz.adapters.RecycleViewAdapter.onCreateViewHolder(RecycleViewAdapter.java:1)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:2915)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:2511)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.LinearLayoutManager$RenderState.next(LinearLayoutManager.java:1425)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.LinearLayoutManager$RenderState.next(LinearLayoutManager.java:1425)

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res/com.xyz"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:orientation="horizontal" >

Body:
Just put this line inside your CardView:

app:cardElevation="0dp"

Hope it will help you.


问:
Adding data to Highcharts after initial rendering
I'm using Highcharts and initializing the data using;

```<code>var graph = Highcharts.chart('container', {
................
    series: [{
        color: 'red',
        data: [[5, 2],  [800, 2], [801, 1],[802, 3],[803, 2],[804, 2],[1200, 3]]
    },
.............
}
</code>```

The problem I have is when I want to add more data dynamically, after rendering the initial chart.

In this case I'm using the update;

```<code>graph.update(
{
    series: [{
        color: 'blue',
        data: [[100, 2],  [101, 2], [102, 1] ]
    },
});
</code>```

And this works but it replaces the entire data set.
So, how should I use the update() function to add points and not replace them?

I saw people are using other functions such as addPoint() and setData() but I couldn't make them work properly...
Thanks in advance
Gus

答:
Refer to this live demo: http://jsfiddle.net/kkulig/opr4Lgpe/

I add all the points in a loop. redraw argument (second one) of the addPoint function is set to false - there's no need to redraw the chart after each addition. The redraw is performed only once in the end.

```<code>var chart = Highcharts.chart('container', {

  series: [{
    data: [1, 2]
  }]
});

var pointsToAdd = [4, 5, 6, 6, 7];

pointsToAdd.forEach(function(p) {
    chart.series[0].addPoint(p, false);
});

chart.redraw();
</code>```

API reference:
https://api.highcharts.com/class-reference/Highcharts.Series#addPoint

Body:
I'm using Highcharts and initializing the data using;

var graph = Highcharts.chart('container', {
................
    series: [{
        color: 'red',
        data: [[5, 2],  [800, 2], [801, 1],[802, 3],[803, 2],[804, 2],[1200, 3]]
    },
.............
}

The problem I have is when I want to add more data dynamically, after rendering the initial chart.

In this case I'm using the update;

graph.update(
{
    series: [{
        color: 'blue',
        data: [[100, 2],  [101, 2], [102, 1] ]
    },
});

And this works but it replaces the entire data set.
So, how should I use the update() function to add points and not replace them?

I saw people are using other functions such as addPoint() and setData() but I couldn't make them work properly...
Thanks in advance
Gus

Body:
Refer to this live demo: http://jsfiddle.net/kkulig/opr4Lgpe/

I add all the points in a loop. redraw argument (second one) of the addPoint function is set to false - there's no need to redraw the chart after each addition. The redraw is performed only once in the end.

var chart = Highcharts.chart('container', {

  series: [{
    data: [1, 2]
  }]
});

var pointsToAdd = [4, 5, 6, 6, 7];

pointsToAdd.forEach(function(p) {
    chart.series[0].addPoint(p, false);
});

chart.redraw();

API reference:
https://api.highcharts.com/class-reference/Highcharts.Series#addPoint


问:
Custom Control Overridden Text Property Default Value
I have created a user control that has a textbox inside of it. I have overridden the Text property of the base control like the following:

```<code>    [Browsable(true)]
    [DefaultValue("")]
    [Description("Test1"), Category("Test")]
    public new string Text
    {
        get
        {
            return textBox1.Text;
        }
        set
        {
            textBox1.Text= value;
        }
    }
</code>```

Now, I am having this issue where any instances i create of the control in a form, the Text always have a value of the controlname + number (of instance). I want to know why is this happening, and how to remove this default value? Thanks.

答: Initial hunch is that it is calling ToString() on the object. Override ToString() to return your desired value.

Body:
I have created a user control that has a textbox inside of it. I have overridden the Text property of the base control like the following:

    [Browsable(true)]
    [DefaultValue("")]
    [Description("Test1"), Category("Test")]
    public new string Text
    {
        get
        {
            return textBox1.Text;
        }
        set
        {
            textBox1.Text= value;
        }
    }

Now, I am having this issue where any instances i create of the control in a form, the Text always have a value of the controlname + number (of instance). I want to know why is this happening, and how to remove this default value? Thanks.


问:
GridSearchCV error "Too many indices in the array"
I am using a supervised learning algorithm Random Forest classifier for training the data.

```<code>    clf = RandomForestClassifier(n_estimators=50, n_jobs=3, random_state=42)
</code>```

Different parameter in the grid are:

```<code>    param_grid = {
    'n_estimators': [200, 700],
    'max_features': ['auto', 'sqrt', 'log2'],
    'max_depth': [5,10],
    'min_samples_split': [5,10]
    }
</code>```

Classifier "clf" and parameter grid "param_grid" are passed in the GridSearhCV method.

```<code>    clf_rfc = GridSearchCV(estimator=clf, param_grid=param_grid)
</code>```

When I fit the features with labels using

```<code>    clf_rfc.fit(X_train, y_train)
</code>```

I get the error "Too many indices in the array". Shape of X_train is (204,3) and of y_train is (204,1).

Tried with the option   clf_rfc.fit(X_train.values, y_train.values) but could not get rid of the error.

Any suggestions would be appreciated !!

答:
y_train should be a 1-dimensional array

I have tried clf_rfc.fit(X_train, y_train.flatten()), and it did work!

Body:
I am using a supervised learning algorithm Random Forest classifier for training the data.

    clf = RandomForestClassifier(n_estimators=50, n_jobs=3, random_state=42)

Different parameter in the grid are:

    param_grid = {
    'n_estimators': [200, 700],
    'max_features': ['auto', 'sqrt', 'log2'],
    'max_depth': [5,10],
    'min_samples_split': [5,10]
    }

Classifier "clf" and parameter grid "param_grid" are passed in the GridSearhCV method.

    clf_rfc = GridSearchCV(estimator=clf, param_grid=param_grid)

When I fit the features with labels using

    clf_rfc.fit(X_train, y_train)

I get the error "Too many indices in the array". Shape of X_train is (204,3) and of y_train is (204,1).

Tried with the option   clf_rfc.fit(X_train.values, y_train.values) but could not get rid of the error.

Any suggestions would be appreciated !!


问:
HTML <range> initial value is jQuery
I'm using the  element as a video seek bar, and am using the below jQuery to update the position of the 'thumb' during playback. However, this code is causing the element to ignore it's initial set value of "0", and instead positions the thumb in the center of the 'track'.

Can I update this code to ensure the initial value is respected?

Thanks

HTML

```<code><input type="range" id="seek-bar" value="0" step="0.05">
</code>```

jQuery

```<code>var video = document.getElementById('video');

video.addEventListener("timeupdate", function() {
  // Calculate the slider value
  var value = (100 / video.duration) * video.currentTime;

  // Update the slider value
  seekBar.value = value;
});
</code>```

答:
I would add an oncanplay listener to the video, and additionally only update the range input if the video is not paused. Also, I'd add the min and max attributes to the range input to make sure it goes from 0 to 100.

var video = document.getElementById('video');
var seekBar = document.getElementById("seekBar");

video.addEventListener("canplay", function() {
  video.addEventListener("timeupdate", function() {

    if (!video.paused) {
      // Calculate the slider value
      var value = (100 / video.duration) * video.currentTime;

      // Update the slider value
      seekBar.value = value;
    }
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video id="video" style="width:600px;max-width:100%;" controls="">
    <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
    <source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
    Your browser does not support HTML5 video.
  </video>

<input id="seekBar" type="range" min="0" max="100" value="0" /></code>```

Title: HTML <range> initial value is jQuery

Body:
I'm using the  element as a video seek bar, and am using the below jQuery to update the position of the 'thumb' during playback. However, this code is causing the element to ignore it's initial set value of "0", and instead positions the thumb in the center of the 'track'.

Can I update this code to ensure the initial value is respected?

Thanks

HTML

<input type="range" id="seek-bar" value="0" step="0.05">

jQuery

var video = document.getElementById('video');

video.addEventListener("timeupdate", function() {
  // Calculate the slider value
  var value = (100 / video.duration) * video.currentTime;

  // Update the slider value
  seekBar.value = value;
});

Body:
I would add an oncanplay listener to the video, and additionally only update the range input if the video is not paused. Also, I'd add the min and max attributes to the range input to make sure it goes from 0 to 100.

var video = document.getElementById('video');
var seekBar = document.getElementById("seekBar");

video.addEventListener("canplay", function() {
  video.addEventListener("timeupdate", function() {

    if (!video.paused) {
      // Calculate the slider value
      var value = (100 / video.duration) * video.currentTime;

      // Update the slider value
      seekBar.value = value;
    }
  });
})

<video id="video" style="width:600px;max-width:100%;" controls="">
    <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
    <source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
    Your browser does not support HTML5 video.
  </video>

<input id="seekBar" type="range" min="0" max="100" value="0" />


问:
How to Capture screenshot on Emulator/Real device using extended report
I am trying to capture screenshot on the IOS and Android emulators on Test failure but my driver returns Null. When i run the code on Chrome on my computer it runs fine and takes the screenshot on failure, the problem is when it runs on emulators. see the code below to take screenshots where the driver returns Null.i am not sure what is it that i am doing wrong, please help me out.

```<code>public class GetScreenShot {

    public static String capture(WebDriver driver, String screenshotName) throws Exception
    {
        String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());

        TakesScreenshot ts = (TakesScreenshot)driver;
        File source = ts.getScreenshotAs(OutputType.FILE);

        String destination = System.getProperty("user.dir") + "/ErrorScreenshots/"+screenshotName+dateName+".png";
        File finalDestination = new File(destination);
        FileUtils.copyFile(source, finalDestination);

        return destination;
    }
}

And here is the code on the Report.

public class ExtentReportsClass{

    //AndroidDriver driver;
    public static ExtentHtmlReporter htmlReporter;
    public static ExtentReports extent;
    public static ExtentTest logger;
    public static WebDriver driver=null;

    @BeforeSuite
    public void config()
    {
        htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir") +"/test-output/ABSA_Test_Report.html");
        extent = new ExtentReports();

        extent.attachReporter(htmlReporter);
        extent.setSystemInfo("Host Name", "Software Testing");
        extent.setSystemInfo("Environment", "Production");
        extent.setSystemInfo("User Name", "Kgotso Mashabela");

        htmlReporter.config().setDocumentTitle("Automation Report");
        htmlReporter.config().setReportName("ABSA Automation Report");
        htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
        htmlReporter.config().setTheme(Theme.STANDARD);
    }

    @AfterMethod
    public void getResult(ITestResult result) throws Exception
    {
        if (result.getStatus() == ITestResult.FAILURE)
        {

            String screenShotPath = GetScreenShot.capture(driver, result.getName());
            logger.log(Status.FAIL, MarkupHelper.createLabel(result.getName()+" Test case FAILED due to below issues:", ExtentColor.RED));
            logger.fail(result.getThrowable());
            logger.fail("Snapshot below: " + logger.addScreenCaptureFromPath(screenShotPath));
            //test.fail("Screenshot below: " + test.addScreenCaptureFromPath(takeScreenShot(result.getMethod().getMethodName())));

        }
        else if(result.getStatus() == ITestResult.SUCCESS)
        {
            logger.log(Status.PASS, MarkupHelper.createLabel(result.getName()+" Test Case PASSED", ExtentColor.GREEN));
        }
        else
        {
            logger.log(Status.SKIP, MarkupHelper.createLabel(result.getName()+" Test Case SKIPPED", ExtentColor.ORANGE));
            logger.skip(result.getThrowable());
        }

    }

    @AfterSuite
    public void tearDown()
    {
        extent.flush();
    }
}
</code>```

And here is my class.

public class IOSClass extends ExtentReportsClass{

```<code>AppiumDriver driver;
Map<String, Object[]> data = new HashMap<String, Object[]>();
DesiredCapabilities capabilities = new DesiredCapabilities();

@BeforeTest
public void OpenSafari() throws MalformedURLException {
    System.out.println("********************");
    System.out.println("Running Safari on IOS...");
    logger = extent.createTest("OpenSafari");

    capabilities.setCapability(CapabilityType.BROWSER_NAME, "Safari");
    capabilities.setCapability("platformName", "iOS");
    capabilities.setCapability("platformVersion", "11.1");
    capabilities.setCapability("deviceName", "iPhone 6");
    capabilities.setCapability("udid", "B7D8F638-F689-4155-BA7F-F7CDD149D75D");

    driver = new IOSDriver(new URL("http://0.0.0.0:4723/wd/hub"),capabilities);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    logger.log(Status.PASS,"Capabilities Configured Successfully ");

}

@Test(priority=1, dataProvider = "MultiBrowser")
public void OpenSafariBrowser(String AppURL,String Ffacebook,String FUsername,String FPassword)throws Exception {

    Thread.sleep(5000);
    SearchFacebook(AppURL,Ffacebook);

    Thread.sleep(5000);
    SignUp(FUsername,FPassword);

    Thread.sleep(5000);
    //Mmessage.PopUpMessage(driver);
    WriteIntoExcel();

}

@DataProvider(name = "MultiBrowser")
public Object[][] provideTestParam(ITestContext context) {
    String ExcelLocation = context.getCurrentXmlTest().getParameter("ExcelLocation");
    Object[][] retObjArr =  {{ ExcelLocation }};

    try
    {
        File path = new File("/Users/Documents/Screenshots/TestData.xlsx");
        FileInputStream file = new FileInputStream(path);

        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);

        retObjArr = new Object[sheet.getPhysicalNumberOfRows() - 1][4];

        for(int rownum = 0; rownum < sheet.getPhysicalNumberOfRows() - 1; rownum++){
            Row row = sheet.getRow(rownum + 1);

            retObjArr[rownum][0] = row.getCell(0).getStringCellValue();
            retObjArr[rownum][1] = row.getCell(1).getStringCellValue();
            retObjArr[rownum][2] = row.getCell(2).getStringCellValue();
            retObjArr[rownum][3] = row.getCell(3).getStringCellValue();
        }
        file.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return(retObjArr);
}

public void SearchFacebook(String AppURL,String Ffacebook) throws InterruptedException{

    logger = extent.createTest("SearchFacebook");
    System.out.println("Search for Facebook...");

    driver.navigate().to(AppURL);
   // logger.log(Status.PASS,"Browser Launched Successfully ");
    //logger.log(Status.PASS,"The Current URL of the Web page is : "+AppURL);
    String strPageTitle = driver.getTitle();
    System.out.println("Page tittle "+strPageTitle);
    Thread.sleep(5000);
    Assert.assertTrue(0 > 1);
   // CaptureScreenShort.captureScreenShot(driver);

    Thread.sleep(5000);
    data.put("1", new Object[] {1d, "Test Description", "Test Step","Screenshots"});

    driver.findElement(By.id("lst-ib")).sendKeys(Ffacebook);
    data.put("2", new Object[] {1d, "User entered " + Ffacebook +" to Search", "Field Validation: Text Entered Successfully"});
   // CaptureScreenShort.captureScreenShot(driver);

    driver.findElement(By.cssSelector("#tsbb")).click();
    data.put("3", new Object[] {1d, "User Clicked Button to Search", "Button Validation: Button clicked Successfully"});
   // CaptureScreenShort.captureScreenShot(driver);

    driver.findElement(By.partialLinkText("Facebook")).click();
    data.put("4", new Object[] {1d, "User Facebook Link to Open", "Link Validation: Link clicked Successfully"});
   // CaptureScreenShort.captureScreenShot(driver);
    Thread.sleep(5000);
    Assert.assertTrue(0 > 1);
    Thread.sleep(5000);

    String title = driver.getTitle();
    Assert.assertEquals("facebook - Google Search1", title);

    System.out.println("Successfully opened Facebook");
    System.out.println("********************");

}
</code>```

See the logs below.

```<code>java.lang.NullPointerException
    at com.example.helloworld.GetScreenShot.capture(GetScreenShot.java:20)
    at com.example.helloworld.ExtentReportsClass.getResult(ExtentReportsClass.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:703)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:774)
    at org.testng.TestRunner.run(TestRunner.java:624)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
    at org.testng.SuiteRunner.run(SuiteRunner.java:261)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
    at org.testng.TestNG.run(TestNG.java:1048)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
</code>```

答: Remove the driver field from IOSClass will make your case work

Body:
I am trying to capture screenshot on the IOS and Android emulators on Test failure but my driver returns Null. When i run the code on Chrome on my computer it runs fine and takes the screenshot on failure, the problem is when it runs on emulators. see the code below to take screenshots where the driver returns Null.i am not sure what is it that i am doing wrong, please help me out.

public class GetScreenShot {

    public static String capture(WebDriver driver, String screenshotName) throws Exception
    {
        String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());

        TakesScreenshot ts = (TakesScreenshot)driver;
        File source = ts.getScreenshotAs(OutputType.FILE);

        String destination = System.getProperty("user.dir") + "/ErrorScreenshots/"+screenshotName+dateName+".png";
        File finalDestination = new File(destination);
        FileUtils.copyFile(source, finalDestination);

        return destination;
    }
}

And here is the code on the Report.

public class ExtentReportsClass{

    //AndroidDriver driver;
    public static ExtentHtmlReporter htmlReporter;
    public static ExtentReports extent;
    public static ExtentTest logger;
    public static WebDriver driver=null;

    @BeforeSuite
    public void config()
    {
        htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir") +"/test-output/ABSA_Test_Report.html");
        extent = new ExtentReports();

        extent.attachReporter(htmlReporter);
        extent.setSystemInfo("Host Name", "Software Testing");
        extent.setSystemInfo("Environment", "Production");
        extent.setSystemInfo("User Name", "Kgotso Mashabela");

        htmlReporter.config().setDocumentTitle("Automation Report");
        htmlReporter.config().setReportName("ABSA Automation Report");
        htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
        htmlReporter.config().setTheme(Theme.STANDARD);
    }

    @AfterMethod
    public void getResult(ITestResult result) throws Exception
    {
        if (result.getStatus() == ITestResult.FAILURE)
        {

            String screenShotPath = GetScreenShot.capture(driver, result.getName());
            logger.log(Status.FAIL, MarkupHelper.createLabel(result.getName()+" Test case FAILED due to below issues:", ExtentColor.RED));
            logger.fail(result.getThrowable());
            logger.fail("Snapshot below: " + logger.addScreenCaptureFromPath(screenShotPath));
            //test.fail("Screenshot below: " + test.addScreenCaptureFromPath(takeScreenShot(result.getMethod().getMethodName())));

        }
        else if(result.getStatus() == ITestResult.SUCCESS)
        {
            logger.log(Status.PASS, MarkupHelper.createLabel(result.getName()+" Test Case PASSED", ExtentColor.GREEN));
        }
        else
        {
            logger.log(Status.SKIP, MarkupHelper.createLabel(result.getName()+" Test Case SKIPPED", ExtentColor.ORANGE));
            logger.skip(result.getThrowable());
        }

    }

    @AfterSuite
    public void tearDown()
    {
        extent.flush();
    }
}

And here is my class.

public class IOSClass extends ExtentReportsClass{

AppiumDriver driver;
Map<String, Object[]> data = new HashMap<String, Object[]>();
DesiredCapabilities capabilities = new DesiredCapabilities();

@BeforeTest
public void OpenSafari() throws MalformedURLException {
    System.out.println("********************");
    System.out.println("Running Safari on IOS...");
    logger = extent.createTest("OpenSafari");

    capabilities.setCapability(CapabilityType.BROWSER_NAME, "Safari");
    capabilities.setCapability("platformName", "iOS");
    capabilities.setCapability("platformVersion", "11.1");
    capabilities.setCapability("deviceName", "iPhone 6");
    capabilities.setCapability("udid", "B7D8F638-F689-4155-BA7F-F7CDD149D75D");

    driver = new IOSDriver(new URL("http://0.0.0.0:4723/wd/hub"),capabilities);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    logger.log(Status.PASS,"Capabilities Configured Successfully ");

}

@Test(priority=1, dataProvider = "MultiBrowser")
public void OpenSafariBrowser(String AppURL,String Ffacebook,String FUsername,String FPassword)throws Exception {

    Thread.sleep(5000);
    SearchFacebook(AppURL,Ffacebook);

    Thread.sleep(5000);
    SignUp(FUsername,FPassword);

    Thread.sleep(5000);
    //Mmessage.PopUpMessage(driver);
    WriteIntoExcel();

}

@DataProvider(name = "MultiBrowser")
public Object[][] provideTestParam(ITestContext context) {
    String ExcelLocation = context.getCurrentXmlTest().getParameter("ExcelLocation");
    Object[][] retObjArr =  {{ ExcelLocation }};

    try
    {
        File path = new File("/Users/Documents/Screenshots/TestData.xlsx");
        FileInputStream file = new FileInputStream(path);

        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);

        retObjArr = new Object[sheet.getPhysicalNumberOfRows() - 1][4];

        for(int rownum = 0; rownum < sheet.getPhysicalNumberOfRows() - 1; rownum++){
            Row row = sheet.getRow(rownum + 1);

            retObjArr[rownum][0] = row.getCell(0).getStringCellValue();
            retObjArr[rownum][1] = row.getCell(1).getStringCellValue();
            retObjArr[rownum][2] = row.getCell(2).getStringCellValue();
            retObjArr[rownum][3] = row.getCell(3).getStringCellValue();
        }
        file.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return(retObjArr);
}

public void SearchFacebook(String AppURL,String Ffacebook) throws InterruptedException{

    logger = extent.createTest("SearchFacebook");
    System.out.println("Search for Facebook...");

    driver.navigate().to(AppURL);
   // logger.log(Status.PASS,"Browser Launched Successfully ");
    //logger.log(Status.PASS,"The Current URL of the Web page is : "+AppURL);
    String strPageTitle = driver.getTitle();
    System.out.println("Page tittle "+strPageTitle);
    Thread.sleep(5000);
    Assert.assertTrue(0 > 1);
   // CaptureScreenShort.captureScreenShot(driver);

    Thread.sleep(5000);
    data.put("1", new Object[] {1d, "Test Description", "Test Step","Screenshots"});

    driver.findElement(By.id("lst-ib")).sendKeys(Ffacebook);
    data.put("2", new Object[] {1d, "User entered " + Ffacebook +" to Search", "Field Validation: Text Entered Successfully"});
   // CaptureScreenShort.captureScreenShot(driver);

    driver.findElement(By.cssSelector("#tsbb")).click();
    data.put("3", new Object[] {1d, "User Clicked Button to Search", "Button Validation: Button clicked Successfully"});
   // CaptureScreenShort.captureScreenShot(driver);

    driver.findElement(By.partialLinkText("Facebook")).click();
    data.put("4", new Object[] {1d, "User Facebook Link to Open", "Link Validation: Link clicked Successfully"});
   // CaptureScreenShort.captureScreenShot(driver);
    Thread.sleep(5000);
    Assert.assertTrue(0 > 1);
    Thread.sleep(5000);

    String title = driver.getTitle();
    Assert.assertEquals("facebook - Google Search1", title);

    System.out.println("Successfully opened Facebook");
    System.out.println("********************");

}

See the logs below.

java.lang.NullPointerException
    at com.example.helloworld.GetScreenShot.capture(GetScreenShot.java:20)
    at com.example.helloworld.ExtentReportsClass.getResult(ExtentReportsClass.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:703)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:774)
    at org.testng.TestRunner.run(TestRunner.java:624)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
    at org.testng.SuiteRunner.run(SuiteRunner.java:261)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
    at org.testng.TestNG.run(TestNG.java:1048)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)


问:
How to get the class of individual in OWL API

How to get the class of individual in owl with the reasoner

```<code>        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
        OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new StringDocumentSource(KOALA));

        IRI ontologyIRI = IRI.create("http://www.semanticweb.org/xxxxx/ontologies/2017/10/ontology");

        OWLDataFactory factory = manager.getOWLDataFactory();

        OWLIndividual john = factory.getOWLNamedIndividual(IRI.create(ontologyIRI + "#John"));

        OWLDataPropertyExpression hasConnexion= factory.getOWLDataProperty(IRI.create(ontologyIRI + "#hasConnexion"));

        OWLDataPropertyAssertionAxiom axiom = factory.getOWLDataPropertyAssertionAxiom(hasConnexion, john, 3);

        AddAxiom addAxiom = new AddAxiom(ontology, axiom);

        manager.applyChange(addAxiom);

        manager.saveOntology(ontology, new StreamDocumentTarget(System.out));

        //reasoner
        OWLReasonerFactory reasonerFactory = new StructuralReasonerFactory();
        OWLReasoner reasoner = reasonerFactory.createReasoner(ontology);

        OWLClass myClass= fac.getOWLClass(IRI.create("http://www.semanticweb.org/xxxxx/ontologies/2017/10/ontology#hasConnexion"));

        NodeSet<OWLNamedIndividual> individuals = reasoner.getInstances(myClass,
                false);
         for (Node<OWLNamedIndividual> i : individuals)
         {
             System.out.println(i.getClass());
         }
</code>```

I expect the result to be the class of every individual

but the reasoner gives no result. In protege it's work well but when i take my ontology and try to make it with owl api, i don't got any result

答:
Yes, that will not work. i.getClass() will give you the Java class rather than the asserted types of the individual. To get the asserted types of the individuals you will need to call ontology.axioms(i).collect(Collectors.toSet()). This will only return assertions that have been added to the ontology.

To get inferred types you will need to call reasoner.types(i).collect(Collectors.toSet()).

What bothers me is that you say you got no results. I would expect that you should get lots of wrong results (i.e. Java classes rather than OWL classes). Ok, so you are creating an ontology in the code snippet. The reason why you are not getting any results is that you have not added a class assertion axiom for john. You need to add a factory.getOWLClassAssertionAxiom(owlClassExpression, john) where owlClassExpression  represents a class in your ontology like Person.

Body:
How to get the class of individual in owl with the reasoner

        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
        OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new StringDocumentSource(KOALA));

        IRI ontologyIRI = IRI.create("http://www.semanticweb.org/xxxxx/ontologies/2017/10/ontology");

        OWLDataFactory factory = manager.getOWLDataFactory();

        OWLIndividual john = factory.getOWLNamedIndividual(IRI.create(ontologyIRI + "#John"));

        OWLDataPropertyExpression hasConnexion= factory.getOWLDataProperty(IRI.create(ontologyIRI + "#hasConnexion"));

        OWLDataPropertyAssertionAxiom axiom = factory.getOWLDataPropertyAssertionAxiom(hasConnexion, john, 3);

        AddAxiom addAxiom = new AddAxiom(ontology, axiom);

        manager.applyChange(addAxiom);

        manager.saveOntology(ontology, new StreamDocumentTarget(System.out));

        //reasoner
        OWLReasonerFactory reasonerFactory = new StructuralReasonerFactory();
        OWLReasoner reasoner = reasonerFactory.createReasoner(ontology);

        OWLClass myClass= fac.getOWLClass(IRI.create("http://www.semanticweb.org/xxxxx/ontologies/2017/10/ontology#hasConnexion"));

        NodeSet<OWLNamedIndividual> individuals = reasoner.getInstances(myClass,
                false);
         for (Node<OWLNamedIndividual> i : individuals)
         {
             System.out.println(i.getClass());
         }

I expect the result to be the class of every individual

but the reasoner gives no result. In protege it's work well but when i take my ontology and try to make it with owl api, i don't got any result