问:
?Why is my CSS not applying?
For some reason, my CSS is not applying to my HTML.

HTML:

```<code><textarea class="overlay-display-hide preview-caption" placeholder="Add Your Caption here..."></textarea>
</code>```

CSS:

```<code>.overlay-display-hide {
    display: hide !important;
}
.preview-caption {
    position: absolute;
    width: 360px;
    height: 260px;
    background-color:transparent;
    border-style: none;
    color: white;
    font-size: 14px;
    padding: 20px;
    resize: none;
    overflow: hidden;
}
</code>```

And for some reason, the "overlay-display-hide" class does not show up in the element when inspecting. Do you have any ideas? I bet I just oversaw something.

答:
It actually does render correctly, and I can also see the class in the Chrome inspector. But the browser will ignore your property of display: hide because it is the wrong syntax. You can read here, what values are supported, but hide is none of them.

I assume you are looking for display: none. You can see the element in DOM Tree of the inspector of your browser, but it will not be applied to the page.
The other option is visibility: hidden, which will just dont display the element, but it acutally takes the space in the page, so it is there, but not visible.

See the following example to understand the difference between display: none and visibility: hidden

.col {
  width: 50%;
  float: left;
}

.elem {
  width: 90%;
  margin: 10px auto;
  height: 50px;
  background: green;
}

.hidden {
  visibility: hidden;
}

.none {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col">
  <h1>visibility: hidden</h1>
  <div class="elem"></div>
  <div class="elem hidden"></div>
  <div class="elem"></div>
</div>
<div class="col">
  <h1>display: none</h1>
  <div class="elem"></div>
  <div class="elem none"></div>
  <div class="elem"></div>
</div></code>```

Title: ?Why is my CSS not applying?

Body:
For some reason, my CSS is not applying to my HTML.

HTML:

<textarea class="overlay-display-hide preview-caption" placeholder="Add Your Caption here..."></textarea>

CSS:

.overlay-display-hide {
    display: hide !important;
}
.preview-caption {
    position: absolute;
    width: 360px;
    height: 260px;
    background-color:transparent;
    border-style: none;
    color: white;
    font-size: 14px;
    padding: 20px;
    resize: none;
    overflow: hidden;
}

And for some reason, the "overlay-display-hide" class does not show up in the element when inspecting. Do you have any ideas? I bet I just oversaw something.

Body:
It actually does render correctly, and I can also see the class in the Chrome inspector. But the browser will ignore your property of display: hide because it is the wrong syntax. You can read here, what values are supported, but hide is none of them.

I assume you are looking for display: none. You can see the element in DOM Tree of the inspector of your browser, but it will not be applied to the page.
The other option is visibility: hidden, which will just dont display the element, but it acutally takes the space in the page, so it is there, but not visible.

See the following example to understand the difference between display: none and visibility: hidden

.col {
  width: 50%;
  float: left;
}

.elem {
  width: 90%;
  margin: 10px auto;
  height: 50px;
  background: green;
}

.hidden {
  visibility: hidden;
}

.none {
  display: none;
}

<div class="col">
  <h1>visibility: hidden</h1>
  <div class="elem"></div>
  <div class="elem hidden"></div>
  <div class="elem"></div>
</div>
<div class="col">
  <h1>display: none</h1>
  <div class="elem"></div>
  <div class="elem none"></div>
  <div class="elem"></div>
</div>


来源: stackexchange

问:
Datatable Cell Centre Alignment for createdRow
I have a the following datatable with bootstrap 4. On one of my columns ('Status') I use a createdRow to add a bootstrap badge class. The problem is that the alignment of the badge is a bit off:

I've tried adding 'align-centre', 'text-align' etc to this createdRow add class function, but the badge still remains in the top left corner.

```<code><script>
$(document).ready(function() {
    $('#dataTable').DataTable( {
        responsive: true,
        columnDefs: [
            { responsivePriority: 1, targets: 0 },
            { responsivePriority: 3, targets: 5 },
            { responsivePriority: 2, targets: -1 }
        ],
         "createdRow": function ( row, data, index ) {
            if ( data[6] == 'FB-PAYG' ) {
                $('td', row).eq(6).addClass('badge badge-info');
            }
        }
    } );
} );
</script>
</code>```

HTML:

```<code><div class="card mb-3">
<div class="card-header">
  <i class="fa fa-table"></i> Client Database</div>
<div class="card-body">
  <div class="table">
    <table class="table table-striped table-bordered display no-wrap" id="dataTable" width="100%" cellspacing="0">
    <thead>
        <tr>
          <th>Address</th>
          <th>Location</th>
          <th>Name</th>
          <th>Joining Date</th>
          <th>Phone</th>
          <th>DB Serial</th>
          <th>Status</th>
          <th>Contract Payments</th>
          <th>Battery Reserve</th>
          <th>Action</th>
        </tr>
    </thead>
    <?php
    if($result = $mysqli->query($sql)){
      if($result->num_rows > 0) {
        while($row = $result->fetch_array()) {
        echo '
        <tr>
          <td>'.$row["client_address"].'</td>
          <td>'.$row["client_location"].'</td>
          <td>'.$row["client_name"].'</td>
          <td>'.$row["client_joining_date"].'</td>
          <td>'.$row["client_cell"].'</td>
          <td>'.$row["client_db_number"].'</td>
          <td>'.$row["client_status"].'</td>
          <td>'.$row["client_contract_payments"].'</td>
          <td>'.$row["client_battery_reserve"].'</td>
          <td><a href="clientdetails.php?client_id='. $row["client_id"] .'" title="View Client" type="button" data-toggle="tooltip"><span class="btn btn-primary btn-xs">View</span></a></td>
        </tr>
        ';
        }
      } else {echo "<p class='lead'><em>No records were found.</em></p>";}
     }
     $mysqli->close();
    ?>
    </table>
</code>```

With the following:

```<code><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.0/css/responsive.bootstrap4.min.css"/>

<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.0/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.0/js/responsive.bootstrap4.min.js"></script>
    <!-- Custom scripts for all pages-->
    <script src="js/sb-admin.min.js"></script>
</code>```

答:
It just looks like the alignment is off, the problem is that you are in fact attach bootstraps badge classes to the  itself, not the content of the , or whats inside. You could do this instead :

```<code>createdRow: function ( row, data, index ) {
  if ( data[6] == 'FB-PAYG' ) {
    var content = $('td', row).eq(6).text();
    $('td', row).eq(6).html('<span class="badge badge-info">'+content+'</span>')
  }
}
</code>```

I would love a chained oneliner that uses .wrap(), but this is not possible with text() or html().

ContentLicense: CC BY-SA 3.0

Body:
I have a the following datatable with bootstrap 4. On one of my columns ('Status') I use a createdRow to add a bootstrap badge class. The problem is that the alignment of the badge is a bit off:

I've tried adding 'align-centre', 'text-align' etc to this createdRow add class function, but the badge still remains in the top left corner.

HTML:

   Client Database

          Address
          Location
          Name
          Joining Date
          Phone
          DB Serial
          Status
          Contract Payments
          Battery Reserve
          Action

    <?php
    if($result = $mysqli->query($sql)){
      if($result->num_rows > 0) {
        while($row = $result->fetch_array()) {
        echo '

          '.$row["client_address"].'
          '.$row["client_location"].'
          '.$row["client_name"].'
          '.$row["client_joining_date"].'
          '.$row["client_cell"].'
          '.$row["client_db_number"].'
          '.$row["client_status"].'
          '.$row["client_contract_payments"].'
          '.$row["client_battery_reserve"].'
          View

        ';
        }
      } else {echo "
No records were found.
";}
     }
     $mysqli->close();
    ?>

With the following:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.0/css/responsive.bootstrap4.min.css"/>

Body:
It just looks like the alignment is off, the problem is that you are in fact attach bootstraps badge classes to the <td> itself, not the content of the <td>, or whats inside. You could do this instead :

createdRow: function ( row, data, index ) {
  if ( data[6] == 'FB-PAYG' ) {
    var content = $('td', row).eq(6).text();
    $('td', row).eq(6).html('<span class="badge badge-info">'+content+'</span>')
  }
}

I would love a chained oneliner that uses .wrap(), but this is not possible with text() or html().


问:
Spring data - enable optimistic locking
Note:
I DON'T NEED AN EXPLANATION CONCERNING THE OPTIMISTIC LOCKING.
This question is about what seems to be a specific Spring Data behavior when using optimistic locking.

From the jpa specs whenever an entity has a @Version annotated field, optimistic locking should be enabled automatically on the entity.

If I do this in a spring data test project using Repositories, the locking seems to not be activated. Infact no OptimisticLockException is thrown while doing a Non Repetable Read test (see P2 on page 93 of the JPA specs)

However, from spring docs I see that if we annotate a single method with @Lock(LockModeType.OPTIMISTIC) then the underlying system correctly throws an OptimisticLockException (that is then catch by spring and propagated up the stack in a slightly different form).

Is this normal or did I miss something? Are we obliged to annotate all our methods (or to create a base repository implementation that takes the lock) to have optimistic behavior enabled with spring data?

I'm using spring data in the context of a spring boot project, version 1.4.5.

The test:

```<code>public class OptimisticLockExceptionTest {

    static class ReadWithSleepRunnable extends Thread {

        private OptimisticLockExceptionService service;

        private int id;

        UserRepository userRepository;

        public ReadWithSleepRunnable(OptimisticLockExceptionService service, int id, UserRepository userRepository) {
            this.service = service;
            this.id = id;
            this.userRepository = userRepository;
        }

        @Override
        public void run() {
            this.service.readWithSleep(this.userRepository, this.id);
        }

    }

    static class ModifyRunnable extends Thread {

        private OptimisticLockExceptionService service;

        private int id;

        UserRepository userRepository;

        public ModifyRunnable(OptimisticLockExceptionService service, int id, UserRepository userRepository) {
            this.service = service;
            this.id = id;
            this.userRepository = userRepository;
        }

        @Override
        public void run() {
            this.service.modifyUser(this.userRepository, this.id);
        }

    }

    @Inject
    private OptimisticLockExceptionService service;

    @Inject
    private UserRepository userRepository;

    private User u;

    @Test(expected = ObjectOptimisticLockingFailureException.class)
    public void thatOptimisticLockExceptionIsThrown() throws Exception {

        this.u = new User("email", "p");
        this.u = this.userRepository.save(this.u);

        try {
            Thread t1 = new ReadWithSleepRunnable(this.service, this.u.getId(), this.userRepository);
            t1.start();
            Thread.sleep(50);// To be sure the submitted thread starts
            assertTrue(t1.isAlive());
            Thread t2 = new ModifyRunnable(this.service, this.u.getId(), this.userRepository);
            t2.start();
            t2.join();
            assertTrue(t1.isAlive());
            t1.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
</code>```

The test service:

```<code>@Component
public class OptimisticLockExceptionService {

    @Transactional
    public User readWithSleep(UserRepository userRepo, int id) {

        System.err.println("started read");
        User op = userRepo.findOne(id);
        Thread.currentThread();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.err.println("read end");
        return op;

    }

    @Transactional
    public User modifyUser(UserRepository userRepo, int id) {

        System.err.println("started modify");
        User op = userRepo.findOne(id);

        op.setPassword("p2");

        System.err.println("modify end");
        return userRepo.save(op);

    }
}
</code>```

The repository:

```<code>@Repository
public interface UserRepository extends CrudRepository<User, Integer> {
}
</code>```

答:
The reason behind optimistic lock is to prevent updates on a table from previous state. For example:

You get user with id 1

Another user updates and commit user with id 1 to a new state

You update user 1 (which you loaded in step 1) and try to commit it to the database

In this case in step 3 you will override the changes the other guy did in step 2 and instead you need to throw an exception.

I believe spring does it with the @version property which corresponds to a version column in the database. The result is something like:

```<code>update users set password="p2" where id=1 and version=1;
</code>```

I think spring actually uses string for version but I am not sure. Probably a timestamp too but that's the general idea.

You don't get an exception because only one of your threads is manipulating the data.  You read it in thread 1 and current version is for example 1, then in thread 2 you read it - version is still 1. Then when you try to save it compares the version in the hibernate session to the one in the database and they match - everything is in order so it continues without exception. Try to make it updateWithSleep() and you should get the expected exception.

Title: Spring data - enable optimistic locking

Body:
Note:
I DON'T NEED AN EXPLANATION CONCERNING THE OPTIMISTIC LOCKING.
This question is about what seems to be a specific Spring Data behavior when using optimistic locking.

From the jpa specs whenever an entity has a @Version annotated field, optimistic locking should be enabled automatically on the entity.

If I do this in a spring data test project using Repositories, the locking seems to not be activated. Infact no OptimisticLockException is thrown while doing a Non Repetable Read test (see P2 on page 93 of the JPA specs)

However, from spring docs I see that if we annotate a single method with @Lock(LockModeType.OPTIMISTIC) then the underlying system correctly throws an OptimisticLockException (that is then catch by spring and propagated up the stack in a slightly different form).

Is this normal or did I miss something? Are we obliged to annotate all our methods (or to create a base repository implementation that takes the lock) to have optimistic behavior enabled with spring data?

I'm using spring data in the context of a spring boot project, version 1.4.5.

The test:

public class OptimisticLockExceptionTest {

    static class ReadWithSleepRunnable extends Thread {

        private OptimisticLockExceptionService service;

        private int id;

        UserRepository userRepository;

        public ReadWithSleepRunnable(OptimisticLockExceptionService service, int id, UserRepository userRepository) {
            this.service = service;
            this.id = id;
            this.userRepository = userRepository;
        }

        @Override
        public void run() {
            this.service.readWithSleep(this.userRepository, this.id);
        }

    }

    static class ModifyRunnable extends Thread {

        private OptimisticLockExceptionService service;

        private int id;

        UserRepository userRepository;

        public ModifyRunnable(OptimisticLockExceptionService service, int id, UserRepository userRepository) {
            this.service = service;
            this.id = id;
            this.userRepository = userRepository;
        }

        @Override
        public void run() {
            this.service.modifyUser(this.userRepository, this.id);
        }

    }

    @Inject
    private OptimisticLockExceptionService service;

    @Inject
    private UserRepository userRepository;

    private User u;

    @Test(expected = ObjectOptimisticLockingFailureException.class)
    public void thatOptimisticLockExceptionIsThrown() throws Exception {

        this.u = new User("email", "p");
        this.u = this.userRepository.save(this.u);

        try {
            Thread t1 = new ReadWithSleepRunnable(this.service, this.u.getId(), this.userRepository);
            t1.start();
            Thread.sleep(50);// To be sure the submitted thread starts
            assertTrue(t1.isAlive());
            Thread t2 = new ModifyRunnable(this.service, this.u.getId(), this.userRepository);
            t2.start();
            t2.join();
            assertTrue(t1.isAlive());
            t1.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

The test service:

@Component
public class OptimisticLockExceptionService {

    @Transactional
    public User readWithSleep(UserRepository userRepo, int id) {

        System.err.println("started read");
        User op = userRepo.findOne(id);
        Thread.currentThread();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.err.println("read end");
        return op;

    }

    @Transactional
    public User modifyUser(UserRepository userRepo, int id) {

        System.err.println("started modify");
        User op = userRepo.findOne(id);

        op.setPassword("p2");

        System.err.println("modify end");
        return userRepo.save(op);

    }
}

The repository:

@Repository
public interface UserRepository extends CrudRepository<User, Integer> {
}

Body:
The reason behind optimistic lock is to prevent updates on a table from previous state. For example:

You get user with id 1

Another user updates and commit user with id 1 to a new state

You update user 1 (which you loaded in step 1) and try to commit it to the database

In this case in step 3 you will override the changes the other guy did in step 2 and instead you need to throw an exception.

I believe spring does it with the @version property which corresponds to a version column in the database. The result is something like:

update users set password="p2" where id=1 and version=1;

I think spring actually uses string for version but I am not sure. Probably a timestamp too but that's the general idea.

You don't get an exception because only one of your threads is manipulating the data.  You read it in thread 1 and current version is for example 1, then in thread 2 you read it - version is still 1. Then when you try to save it compares the version in the hibernate session to the one in the database and they match - everything is in order so it continues without exception. Try to make it updateWithSleep() and you should get the expected exception.


问:
Remove NaN from input while calculation
I have a javascript function in which I need to remove the NaN from textbox after calculation ?

```<code>function calculateInterest() {

    var repay_period = parseInt(document.getElementById("emp_loan_repayment_method_id").value);
    var loan_amount = parseInt(document.getElementById("maximum_loan_amount").value);
    var rate_of_interest = parseInt(document.getElementById("rate_of_interest").value);
    var no_of_months = parseInt(document.getElementById("repayment_periods").value);
    var repay_month_amount = parseInt(document.getElementById("repayment_amount").value);
    var no_of_periods = no_of_months / 12;

    {
        var payable_interest = (loan_amount * no_of_periods * rate_of_interest) / 100;

        var pay_interest = payable_interest.toFixed(2);

        document.getElementById("total_payable_interest").value = pay_interest;

        var repay_amount = (loan_amount / no_of_months).toFixed(2);

        document.getElementById("repayment_amount").value = repay_amount;

        var total_payable_amount = (payable_interest + loan_amount).toFixed(2);

        document.getElementById("total_payable_amount").value = total_payable_amount;

    }
}
</code>```

答:
you can change your code like below using isNaN() method of javascript

```<code>{
        var payable_interest = (loan_amount * no_of_periods * rate_of_interest) / 100;

        var pay_interest = payable_interest.toFixed(2);

        document.getElementById("total_payable_interest").value = isNaN(pay_interest) ? 0 : pay_interest;

        var repay_amount = (loan_amount / no_of_months).toFixed(2);

        document.getElementById("repayment_amount").value = isNaN(repay_amount) ? 0 : repay_amount;

        var total_payable_amount = (payable_interest + loan_amount).toFixed(2);

        document.getElementById("total_payable_amount").value = isNaN(total_payable_amount) ? 0 : total_payable_amount;

    }
</code>```

Title: Remove NaN from input while calculation

Body:
I have a javascript function in which I need to remove the NaN from textbox after calculation ?

function calculateInterest() {

    var repay_period = parseInt(document.getElementById("emp_loan_repayment_method_id").value);
    var loan_amount = parseInt(document.getElementById("maximum_loan_amount").value);
    var rate_of_interest = parseInt(document.getElementById("rate_of_interest").value);
    var no_of_months = parseInt(document.getElementById("repayment_periods").value);
    var repay_month_amount = parseInt(document.getElementById("repayment_amount").value);
    var no_of_periods = no_of_months / 12;

    {
        var payable_interest = (loan_amount * no_of_periods * rate_of_interest) / 100;

        var pay_interest = payable_interest.toFixed(2);

        document.getElementById("total_payable_interest").value = pay_interest;

        var repay_amount = (loan_amount / no_of_months).toFixed(2);

        document.getElementById("repayment_amount").value = repay_amount;

        var total_payable_amount = (payable_interest + loan_amount).toFixed(2);

        document.getElementById("total_payable_amount").value = total_payable_amount;

    }
}

Body:
you can change your code like below using isNaN() method of javascript

{
        var payable_interest = (loan_amount * no_of_periods * rate_of_interest) / 100;

        var pay_interest = payable_interest.toFixed(2);

        document.getElementById("total_payable_interest").value = isNaN(pay_interest) ? 0 : pay_interest;

        var repay_amount = (loan_amount / no_of_months).toFixed(2);

        document.getElementById("repayment_amount").value = isNaN(repay_amount) ? 0 : repay_amount;

        var total_payable_amount = (payable_interest + loan_amount).toFixed(2);

        document.getElementById("total_payable_amount").value = isNaN(total_payable_amount) ? 0 : total_payable_amount;

    }


问:
ansible: how to access ansible_env when gather_facts: false
I would like to have a minimal fact gathering that would only. I'm actually only interested in accessing the variables defined in ansible_env.

I've tried to use the setup module with filter: ansible_env and gather_subset: min but It didn't work for me...

any hint would be greatly appreciated

Thanks!

答:
I report below a minimal  example:</p>

```<code>- hosts: localhost
  gather_facts: false
  tasks:
    - setup:
        filter: ansible_env
    - debug:
        var=ansible_env
</code>```

Body:
I report below a minimal  example:

- hosts: localhost
  gather_facts: false
  tasks:
    - setup:
        filter: ansible_env
    - debug:
        var=ansible_env


问:
Simple HTML Dom - Fatal error when using load_file
I'm trying to parse an HTML file that has terrible (believe me, it is) HTML structure and because of this and my lack of knowledge, I couldn't write my own parser. Later I tried using Simple HTML Dom parser, because a lot of people (on SO as well) recommend it.

I required the simple_html_dom.php, then created the object. They seem to work, the require() function returns "1" and var_dump()-ing the object returns an object.

After this I tried to load the URL as it was done in the manual, but I got a fatal error, no matter what URL I tried. The error was the following:

```<code>Fatal error: Call to undefined function mb_detect_encoding() in
             /home/fema/web/subdomain/devel/www_root/parser/
             simplehtmldom_1_5/simple_html_dom.php on line 988
</code>```

I checked what's on line 988 and it is the following:

```<code>// Have php try to detect the encoding from the text given to us.
        $charset = mb_detect_encoding($this->root->plaintext . "ascii",
                   $encoding_list = array( "UTF-8", "CP1252" ) );
</code>```

I understand that this is about character encoding, but that's all. I haven't found anything about this neither with google or on SO.

My whole code is (placeholder URL):

```<code><?php

require('simplehtmldom_1_5/simple_html_dom.php');

// Create a DOM object
$dom = new simple_html_dom();

$dom->load_file('http://www.google.com/');

?>
</code>```

Could anyone please tell me what to do? Or some kind of advice when something like this happens.

Thanks in advance.

答:
Remove the trailing forward slash (/) in your URL string provided in the load_file() method and it works.<br>
Apparently, the load_file() method of the Simple HTML DOM Library has an issue with forward slashes being appended to the end of a URL string.  </p>

Body:
I'm trying to parse an HTML file that has terrible (believe me, it is) HTML structure and because of this and my lack of knowledge, I couldn't write my own parser. Later I tried using Simple HTML Dom parser, because a lot of people (on SO as well) recommend it.

I required the simple_html_dom.php, then created the object. They seem to work, the require() function returns "1" and var_dump()-ing the object returns an object.

After this I tried to load the URL as it was done in the manual, but I got a fatal error, no matter what URL I tried. The error was the following:

Fatal error: Call to undefined function mb_detect_encoding() in
             /home/fema/web/subdomain/devel/www_root/parser/
             simplehtmldom_1_5/simple_html_dom.php on line 988

I checked what's on line 988 and it is the following:

// Have php try to detect the encoding from the text given to us.
        $charset = mb_detect_encoding($this->root->plaintext . "ascii",
                   $encoding_list = array( "UTF-8", "CP1252" ) );

I understand that this is about character encoding, but that's all. I haven't found anything about this neither with google or on SO.

My whole code is (placeholder URL):

<?php

require('simplehtmldom_1_5/simple_html_dom.php');

// Create a DOM object
$dom = new simple_html_dom();

$dom->load_file('http://www.google.com/');

?>

Could anyone please tell me what to do? Or some kind of advice when something like this happens.

Thanks in advance.

Body:
Remove the trailing forward slash (/) in your URL string provided in the load_file() method and it works.

Apparently, the load_file() method of the Simple HTML DOM Library has an issue with forward slashes being appended to the end of a URL string.


问:
Race condition Node JS
I have been going through documentation but for whatever reason I cannot see what is happening here.

I have two functions, 1 downloads a csv file via a url and the next function takes that csv file and converts it to JSON

FileDownload.js

```<code>const http = require('http');
const fs = require('fs');

module.exports = function(url, dest){
  var file = fs.createWriteStream(dest);
  return new Promise((resolve, reject) => {
  var responseSent = false; // flag to make sure that response is sent only once.
  http.get(url, response => {
    response.pipe(file);
      file.on('finish', () =>{
        file.close(() => {
          if(responseSent)  return;
            responseSent = true;
            resolve();
          });
       });
     }).on('error', err => {
       if(responseSent)  return;
         responseSent = true;
         reject(err);
       });
     });
}
</code>```

CSVToJson.js

```<code>const csvjson = require('csvjson');
const fs = require('fs');
const write_file = require('../helpers/WriteToFile');

function csvToJson(csv_file, json_path) {

  var data = fs.readFileSync(csv_file, { encoding : 'utf8'});
  var options = {
    delimiter : ',',
    quote     : '"'
  };
  const json_data = csvjson.toObject(data, options);
  write_file(json_path, json_data)
}

module.exports = {
 csvToJson: csvToJson
}
</code>```

I then call these functions in succession, but CSVToJson finishes before FileDownload, thus causing a failure (no data to convert)

data.js

```<code>const premier_league = require('./scripts/getCSVData')
const csv_to_json = require('./scripts/csvToJson')

const pl_json_path = './team_data/premier_league/clubs/all/premier_league.json'
const pl_csv_path = './csv/premier_league/premier_league.csv'

// Get Premier League CSV file
premier_league.getPremierLeagueData();

// Convert CSV Data to json
csv_to_json.csvToJson(pl_csv_path, pl_json_path )
</code>```

What am I doing wrong at the file download stage? I haven't quite got my head around callbacks and I only want to execute the csv conversion once the file has been downloaded.

答:
You are using Node so the integration of Promises to handle these async issue is pretty easy.

You can then basically do then FileDownLoad.then(CSVToJson)

99% of JS issues seem to boil down to async problems :D

Having looked further into the code I see you have this line as well.

fs.readFileSync(csv_file, { encoding : 'utf8'});

This is another async issue - you cant be sure this is done before you call csvjson method. Again need promises.

======= Update ==========

```<code>function csvToJson(csvFile, jsonPath) {
    fs.readFile(csvFile, 'utf8', (err, data) => {
        if(err) //handle me

        const options = {
            delimiter : ',',
            quote     : '"'
          };
        const jsonData = csvjson.toObject(data, options);
        write_file(jsonPath, jsonData)
    });
}
</code>```

I guess something like the above. You could wrap in some promises and make the api a nice promised based one which is always nice ;)

ContentLicense: CC BY-SA 4.0

Title: Race condition Node JS

Body:
I have been going through documentation but for whatever reason I cannot see what is happening here.

I have two functions, 1 downloads a csv file via a url and the next function takes that csv file and converts it to JSON

FileDownload.js

const http = require('http');
const fs = require('fs');

module.exports = function(url, dest){
  var file = fs.createWriteStream(dest);
  return new Promise((resolve, reject) => {
  var responseSent = false; // flag to make sure that response is sent only once.
  http.get(url, response => {
    response.pipe(file);
      file.on('finish', () =>{
        file.close(() => {
          if(responseSent)  return;
            responseSent = true;
            resolve();
          });
       });
     }).on('error', err => {
       if(responseSent)  return;
         responseSent = true;
         reject(err);
       });
     });
}

CSVToJson.js

const csvjson = require('csvjson');
const fs = require('fs');
const write_file = require('../helpers/WriteToFile');

function csvToJson(csv_file, json_path) {

  var data = fs.readFileSync(csv_file, { encoding : 'utf8'});
  var options = {
    delimiter : ',',
    quote     : '"'
  };
  const json_data = csvjson.toObject(data, options);
  write_file(json_path, json_data)
}

module.exports = {
 csvToJson: csvToJson
}

I then call these functions in succession, but CSVToJson finishes before FileDownload, thus causing a failure (no data to convert)

data.js

const premier_league = require('./scripts/getCSVData')
const csv_to_json = require('./scripts/csvToJson')

const pl_json_path = './team_data/premier_league/clubs/all/premier_league.json'
const pl_csv_path = './csv/premier_league/premier_league.csv'

// Get Premier League CSV file
premier_league.getPremierLeagueData();

// Convert CSV Data to json
csv_to_json.csvToJson(pl_csv_path, pl_json_path )

What am I doing wrong at the file download stage? I haven't quite got my head around callbacks and I only want to execute the csv conversion once the file has been downloaded.

Body:
You are using Node so the integration of Promises to handle these async issue is pretty easy.

You can then basically do then FileDownLoad.then(CSVToJson)

99% of JS issues seem to boil down to async problems :D

Having looked further into the code I see you have this line as well.

fs.readFileSync(csv_file, { encoding : 'utf8'});

This is another async issue - you cant be sure this is done before you call csvjson method. Again need promises.

======= Update ==========

function csvToJson(csvFile, jsonPath) {
    fs.readFile(csvFile, 'utf8', (err, data) => {
        if(err) //handle me

        const options = {
            delimiter : ',',
            quote     : '"'
          };
        const jsonData = csvjson.toObject(data, options);
        write_file(jsonPath, jsonData)
    });
}

I guess something like the above. You could wrap in some promises and make the api a nice promised based one which is always nice ;)


问:
Using the ContactsContract cursor to get the contacts by group
How would I filter the returned contacts by the groupName?

```<code>@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
        long id) {
    String groupName = parent.getItemAtPosition(pos).toString();
    Log.i(this.toString(), String.format("Show Group: %s", groupName));

    Cursor cur = this.getContentResolver().query(
            ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String name = cur
                    .getString(cur
                            .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (name != null) {
                Log.i(this.toString(), String.format("Show: %s", name));
            }
        }

        cur.close();
    }
}
</code>```

答:
I was able to filter contacts by group by using the following query:

```<code>Cursor c = this.managedQuery(Data.CONTENT_URI, new String[] {
                    Contacts.DISPLAY_NAME, Contacts._ID },
                    GroupMembership.GROUP_ROW_ID + " = ?",
                    new String[] { groupId }, Phone.TIMES_CONTACTED + " DESC");
</code>```

Obviously you need to know the Group Id in order to complete this, how I did this was used a SimpleCursorAdapter to a Spinner w/the following Cursor:

```<code>Cursor c = managedQuery(Groups.CONTENT_URI,
                        new String[] { Groups.SYSTEM_ID, Groups._ID,},
                        Groups.SYSTEM_ID + " NOT NULL",
                        null, null);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How would I filter the returned contacts by the groupName?

@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
        long id) {
    String groupName = parent.getItemAtPosition(pos).toString();
    Log.i(this.toString(), String.format("Show Group: %s", groupName));

    Cursor cur = this.getContentResolver().query(
            ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String name = cur
                    .getString(cur
                            .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (name != null) {
                Log.i(this.toString(), String.format("Show: %s", name));
            }
        }

        cur.close();
    }
}

Body:
I was able to filter contacts by group by using the following query:

Cursor c = this.managedQuery(Data.CONTENT_URI, new String[] {
                    Contacts.DISPLAY_NAME, Contacts._ID },
                    GroupMembership.GROUP_ROW_ID + " = ?",
                    new String[] { groupId }, Phone.TIMES_CONTACTED + " DESC");

Obviously you need to know the Group Id in order to complete this, how I did this was used a SimpleCursorAdapter to a Spinner w/the following Cursor:

Cursor c = managedQuery(Groups.CONTENT_URI,
                        new String[] { Groups.SYSTEM_ID, Groups._ID,},
                        Groups.SYSTEM_ID + " NOT NULL",
                        null, null);


问:
Sharing config between node app and client side javascript
I need to have some config object both in the node app and in the browser. Here is the path and the content of the config:

path: [app]/public/js/config.js

content:

```<code>var config = {
    "foo": "bar",
    "num": 42,
    "list": ["a","b","f"]
};
var isBrowser=new Function("try {return this===window;}catch(e){ return false;}");
if(!isBrowser) {
    module.exports = config;
}
</code>```

In my html I just add a script element and it works fine:

```<code><script src="/js/config.js"></script>
</code>```

In node app however I do not seem to have imported the object and I get an empty object:

```<code>var config = require('./public/js/config.js');
console.log('config:', config); // gives config: {}
</code>```

What am I doing wrong?

答:
The code should have been

```<code>if(!isBrowser()) {
    module.exports = config;
}
</code>```

isBrowser is a function here. Since in your version !isBrowser always return false so module.exports = config is never executed.

Body:
I need to have some config object both in the node app and in the browser. Here is the path and the content of the config:

path: [app]/public/js/config.js

content:

var config = {
    "foo": "bar",
    "num": 42,
    "list": ["a","b","f"]
};
var isBrowser=new Function("try {return this===window;}catch(e){ return false;}");
if(!isBrowser) {
    module.exports = config;
}

In my html I just add a script element and it works fine:

In node app however I do not seem to have imported the object and I get an empty object:

var config = require('./public/js/config.js');
console.log('config:', config); // gives config: {}

What am I doing wrong?

Body:
The code should have been

if(!isBrowser()) {
    module.exports = config;
}

isBrowser is a function here. Since in your version !isBrowser always return false so module.exports = config is never executed.


问:
Spring shutdown on start up
Below is what I get
Audit4j:INFO Initializing Audit4j...
Audit4j:INFO Loading Configurations...
Audit4j:INFO Validating Configurations...
Audit4j:INFO Initializing Handlers...
Audit4j:INFO org.audit4j.core.handler.ConsoleAuditHandler Initialized.
Audit4j:INFO org.audit4j.core.handler.file.FileAuditHandler Initialized.
Audit4j:INFO Initializing Layout...
Audit4j:INFO org.audit4j.core.layout.SimpleLayout Initialized.
Audit4j:INFO Initializing Streams...
Audit4j:INFO Audit Streams Initialized.
Audit4j:INFO Executing Schedulers...
Audit4j:INFO Audit4j initialized. Total time: 651ms
Exception in Application start method
2017-11-14 12:36:33.599  INFO 4068 --- [lication Thread] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@1318c18e: startup date [Tue Nov 14 12:35:49 EAT 2017]; root of context hierarchy
2017-11-14 12:36:33.602  INFO 4068 --- [lication Thread] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

Process finished with exit code 0

Kindly assist

答: Clean your project once . And restart it . The error seems like spring is not picking up some inbuilt class . </p>

Title: Spring shutdown on start up


答:
Replace if block

```<code>if(!isBrowser) {
    module.exports = config;
}
</code>```

to

```<code>if(!isBrowser()) {//this isBrowser() function
    module.exports = config;
}
</code>```

Title: Sharing config between node app and client side javascript

Body:
Replace if block

if(!isBrowser) {
    module.exports = config;
}

to

if(!isBrowser()) {//this isBrowser() function
    module.exports = config;
}


问:
Sorted Dictionary - C#
I'm trying to figure out how to create a sorted dictionary where the key is sorted in a non-alphabetical manner.  Is there a way I can define the way I want it to sort?

For example, the keys might be in order like the following:

```<code>AAA1X
AAB1Y
AAC1Y
AAA2X
AAB2Y
AAC2X
</code>```

Although the first three letters are alphabetical, if I sort as is it will lump them in the wrong order (due to the number). Also note, that there is either a X or Y at the end.  In the code, there will only ever be an X or a Y.

Even if I can write an enumeration for the ordering of all possible combinations I'd be willing to do that as well, but I'm not sure how I can use the sorted dictionary and an enumeration...

I know this is a bit vague, but any help would be much appreciated!

Cheers!

答:
You can :

Create a class that encapsulates those keys and override the == operator, Object.Equals method and the Object.GetHashCode method. Also have the class implement the IComparable interface such that the rules for equality will automatically sort your keys the right way. Now you can simply place those keys in a SortedDictionary or SortedList and it will automatically sort the way you want.

OR

Implement an IComparer object that compares those strings the way you want, and specify the IComparer when constructing a SortedDictionaryor SortedList.

Title: Sorted Dictionary - C#

Body:
I'm trying to figure out how to create a sorted dictionary where the key is sorted in a non-alphabetical manner.  Is there a way I can define the way I want it to sort?

For example, the keys might be in order like the following:

AAA1X
AAB1Y
AAC1Y
AAA2X
AAB2Y
AAC2X

Although the first three letters are alphabetical, if I sort as is it will lump them in the wrong order (due to the number). Also note, that there is either a X or Y at the end.  In the code, there will only ever be an X or a Y.

Even if I can write an enumeration for the ordering of all possible combinations I'd be willing to do that as well, but I'm not sure how I can use the sorted dictionary and an enumeration...

I know this is a bit vague, but any help would be much appreciated!

Cheers!


问:
Dagger do not generates _MembersInjector classes for simple Java project
I'm trying to add Dagger 2 to a simple Java project. It goes like that:

build.gradle

```<code>apply plugin: 'java'

dependencies {
    compileOnly "com.google.dagger:dagger-compiler:2.12"
    compile "com.google.dagger:dagger:2.12"
}
</code>```

MainModule

```<code>@Module
class MainModule {
    @Provides
    public String providesString () { return "some_string"; }
}
</code>```

MainComponent

```<code>@Singleton
@Component (module = MainModule.class)
interface MainComponent {
    void inject (MainClass main);
}
</code>```

MainClass

```<code>public class MainClass {
    @Inject String sampleDependency;

    public MainClass () {
        DaggerMainComponent
        .builder()
        .build()
        .inject(this);
    }
}
</code>```

On IntelliJ it looks ok, however, when I try to run it I get:

```<code>Caused by: java.lang.NoClassDefFoundError: MainClass_MembersInjector
</code>```

Any ideas?

答: Actually the files were being generated but IntelliJ wasn't recognizing them. To solve the problem I went to Project Structure (cmd + ; for Mac users) → Add content root → Choose the folder that contains dagger2 generated classes.

Body:
I'm trying to add Dagger 2 to a simple Java project. It goes like that:

build.gradle

apply plugin: 'java'

dependencies {
    compileOnly "com.google.dagger:dagger-compiler:2.12"
    compile "com.google.dagger:dagger:2.12"
}

MainModule

@Module
class MainModule {
    @Provides
    public String providesString () { return "some_string"; }
}

MainComponent

@Singleton
@Component (module = MainModule.class)
interface MainComponent {
    void inject (MainClass main);
}

MainClass

public class MainClass {
    @Inject String sampleDependency;

    public MainClass () {
        DaggerMainComponent
        .builder()
        .build()
        .inject(this);
    }
}

On IntelliJ it looks ok, however, when I try to run it I get:

Caused by: java.lang.NoClassDefFoundError: MainClass_MembersInjector

Any ideas?


问:
How to center placeholder text in UISearchBar iOS 11
With iOS 11, searchBars are defaulting to a left aligned text. While this looks good with the rest of the native changes to iOS, it doesn't really fit my design, and I would like it to be center, as it was before.

I can't find any such alignment attributes on UISearchBar. Am I missing something, or is it simply not possible? Do I have to create my own custom search bar e.g derived from a UITextField to achieve this?

答:
I had exactly the same problem - I'm struggling to understand why the default alignment would be changed without allowing us to easily set this back to centered.

The below works for me (Swift):

```<code>let placeholderWidth = 200 // Replace with whatever value works for your placeholder text
var offset = UIOffset()

override func viewDidLoad() {
    offset = UIOffset(horizontal: (searchBar.frame.width - placeholderWidth) / 2, vertical: 0)
    searchBar.setPositionAdjustment(offset, for: .search)
}

func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
    let noOffset = UIOffset(horizontal: 0, vertical: 0)
    searchBar.setPositionAdjustment(noOffset, for: .search)

    return true
}

func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
    searchBar.setPositionAdjustment(offset, for: .search)

    return true
}
</code>```

Body:
I had exactly the same problem - I'm struggling to understand why the default alignment would be changed without allowing us to easily set this back to centered.

The below works for me (Swift):

let placeholderWidth = 200 // Replace with whatever value works for your placeholder text
var offset = UIOffset()

override func viewDidLoad() {
    offset = UIOffset(horizontal: (searchBar.frame.width - placeholderWidth) / 2, vertical: 0)
    searchBar.setPositionAdjustment(offset, for: .search)
}

func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
    let noOffset = UIOffset(horizontal: 0, vertical: 0)
    searchBar.setPositionAdjustment(noOffset, for: .search)

    return true
}

func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
    searchBar.setPositionAdjustment(offset, for: .search)

    return true
}


问:
Select entire group if one selection has the given value
```<code> datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-08-02                                 HSBC   5 - Proposal Awarded            5     6          1
 9 2016-12-13                                 HSBC   6 - Delivery Phase 1            6     7          1
10 2017-08-07                                 HSBC       7 - Phase 1 Live            7    NA         NA
11 2016-07-22                                Lowes      Pre-Qualification            0    NA         NA
12 2016-08-02                          Danske Bank   6 - Delivery Phase 1            6    NA         NA
13 2016-07-22 AP Moller Maersk (IT Transformation)  3 - Commercial Review            3    NA         NA
14 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
15 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
16 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2
</code>```

I would like to create a new data frame off of this one that selects only the "labels" that have a negative "difference" value. However, I want to select ALL of the similar "labels" like so:

```<code> datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
 9 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
10 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2
</code>```

I'm not sure how to do this in dplyr....would SQL be better for this? (I haven't used the sql package in R much)

答:
Try subset function</p>

```<code>df <- subset(df, sign(df$diff) == -1)
</code>```

Body:
 datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-08-02                                 HSBC   5 - Proposal Awarded            5     6          1
 9 2016-12-13                                 HSBC   6 - Delivery Phase 1            6     7          1
10 2017-08-07                                 HSBC       7 - Phase 1 Live            7    NA         NA
11 2016-07-22                                Lowes      Pre-Qualification            0    NA         NA
12 2016-08-02                          Danske Bank   6 - Delivery Phase 1            6    NA         NA
13 2016-07-22 AP Moller Maersk (IT Transformation)  3 - Commercial Review            3    NA         NA
14 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
15 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
16 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2

I would like to create a new data frame off of this one that selects only the "labels" that have a negative "difference" value. However, I want to select ALL of the similar "labels" like so:

 datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
 9 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
10 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2

I'm not sure how to do this in dplyr....would SQL be better for this? (I haven't used the sql package in R much)

Body:
Try subset function

df <- subset(df, sign(df$diff) == -1)


问:
How can I update the [[UIApplication sharedApplication] scheduledLocalNotifications] array?
This may be more of a question regarding how to update arrays in general, but I have an app that is utilizing UILocalNotifications, and I want to allow users to select the notifications they have set, and edit them.

So what could I do to update an object at an index?

```<code>[[[UIApplication sharedApplication] scheduledLocalNotifications] ??];
</code>```

Thanks for any help!

答:
Once you get the UILocalNotification object, you can "reschedule" it by canceling the old notification with:

[[UIApplication sharedApplication] cancelLocalNotification:aNotification];

and scheduling a new one:

[[UIApplication sharedApplication] scheduleLocalNotification:aNotification];

Body:
This may be more of a question regarding how to update arrays in general, but I have an app that is utilizing UILocalNotifications, and I want to allow users to select the notifications they have set, and edit them.

So what could I do to update an object at an index?

[[[UIApplication sharedApplication] scheduledLocalNotifications] ??];

Thanks for any help!


问:
How to set up Mockito for Kotlin and Android
I want to use Mockito for unit testing, so I added the Mockito library into my gradle dependencies.

```<code>testImplementation 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:2.12.0'
</code>```

But still, I can not use any Mockito annotations.

/androidTest/ExampleTest.kt

```<code>@RunWith(MockitoJUnitRunner::class) // Unresolved reference MockitoJUnitRunner
@Mock // Unresolved reference Mock
</code>```

What I'm missing it?

答:
You need to add the following dependencies in your app's build.gradle:

```<code>dependencies {
    // ... more entries
    testCompile 'junit:junit:4.12'

    // required if you want to use Mockito for unit tests
    testImplementation 'org.mockito:mockito-core:2.24.5'
    // required if you want to use Mockito for Android tests
    androidTestImplementation 'org.mockito:mockito-android:2.24.5'
}
</code>```

And click on sync

Body:
I want to use Mockito for unit testing, so I added the Mockito library into my gradle dependencies.

testImplementation 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:2.12.0'

But still, I can not use any Mockito annotations.

/androidTest/ExampleTest.kt

@RunWith(MockitoJUnitRunner::class) // Unresolved reference MockitoJUnitRunner
@Mock // Unresolved reference Mock

What I'm missing it?

Body:
You need to add the following dependencies in your app's build.gradle:

dependencies {
    // ... more entries
    testCompile 'junit:junit:4.12'

    // required if you want to use Mockito for unit tests
    testImplementation 'org.mockito:mockito-core:2.24.5'
    // required if you want to use Mockito for Android tests
    androidTestImplementation 'org.mockito:mockito-android:2.24.5'
}

And click on sync


问:
Why if open popup, theTextarea is less than the text in it?
I have text area:

function textAreaAdjust(o) {
    o.style.height = "1px";
    o.style.height = (25 + o.scrollHeight) + "px";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea#commentText {
        height: auto;
        width: 570px!important;
 }</code>```

<textarea name="bookId" id="commentText" value="" class="form-control" ng-maxlength="1000" maxlength="1000" rows="3" onkeyup="textAreaAdjust(this)" style="overflow:hidden"></textarea>

        ```

And if i open popup window, I get such a result:

How do I make the required textarea size when I open it?
I specified the auto size in css but nothing happened.

答:
You can just run the function on document ready too:

function textAreaAdjust(o) {
  o.style.height = "1px";
  o.style.height = (25 + o.scrollHeight) + "px";
}

// this will run on first load
(function() {
   textAreaAdjust(document.getElementById('commentText'));
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea#commentText {
  height: auto;
  width: 570px!important;
}</code>```

<textarea name="bookId" id="commentText" value="" class="form-control" ng-maxlength="1000" maxlength="1000" rows="3" onkeyup="textAreaAdjust(this)" style="overflow:hidden">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed varius lorem sed metus lacinia, et tempor odio posuere. Cras dictum, odio et tristique iaculis, tellus tortor molestie sapien, at pharetra quam quam in enim. Nunc placerat quam vitae elit maximus ornare. Aenean dapibus, purus a tincidunt fermentum, diam est aliquam orci, eu laoreet nulla est sed leo. Ut laoreet facilisis feugiat. Mauris tortor tortor, iaculis ut mi sit amet, consectetur gravida sem. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer sed fermentum turpis. Cras ac libero at augue rutrum sagittis sit amet vitae magna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras at odio odio. Cras porttitor sit amet odio eu imperdiet. Vestibulum dignissim tempus rutrum.</textarea>```

Body:
I have text area:

function textAreaAdjust(o) {
    o.style.height = "1px";
    o.style.height = (25 + o.scrollHeight) + "px";
}

textarea#commentText {
        height: auto;
        width: 570px!important;
 }

<textarea name="bookId" id="commentText" value="" class="form-control" ng-maxlength="1000" maxlength="1000" rows="3" onkeyup="textAreaAdjust(this)" style="overflow:hidden"></textarea>

And if i open popup window, I get such a result:

How do I make the required textarea size when I open it?
I specified the auto size in css but nothing happened.

Body:
You can just run the function on document ready too:

function textAreaAdjust(o) {
  o.style.height = "1px";
  o.style.height = (25 + o.scrollHeight) + "px";
}

// this will run on first load
(function() {
   textAreaAdjust(document.getElementById('commentText'));
})();

textarea#commentText {
  height: auto;
  width: 570px!important;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<textarea name="bookId" id="commentText" value="" class="form-control" ng-maxlength="1000" maxlength="1000" rows="3" onkeyup="textAreaAdjust(this)" style="overflow:hidden">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed varius lorem sed metus lacinia, et tempor odio posuere. Cras dictum, odio et tristique iaculis, tellus tortor molestie sapien, at pharetra quam quam in enim. Nunc placerat quam vitae elit maximus ornare. Aenean dapibus, purus a tincidunt fermentum, diam est aliquam orci, eu laoreet nulla est sed leo. Ut laoreet facilisis feugiat. Mauris tortor tortor, iaculis ut mi sit amet, consectetur gravida sem. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer sed fermentum turpis. Cras ac libero at augue rutrum sagittis sit amet vitae magna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras at odio odio. Cras porttitor sit amet odio eu imperdiet. Vestibulum dignissim tempus rutrum.</textarea>


问:
JAVA - File I/O cant get file to read
I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.

```<code>public int readInventory(Automobile[] inventory)
{
    final String FILENAME = "inventory.csv";
    int size = 0;

    Scanner input = new Scanner("inventory.csv");
    try
    {
        input = new Scanner(new File(FILENAME));
    }
    catch (FileNotFoundException e)
    {
        System.out.println("Unable to open file " + FILENAME + ".");
    }
    // ...
    return size;
}
</code>```

Here is the output I'm getting with no syntax errors.

Unable to open file inventory.csv.
```

答:
You should try this</p>

```<code>        try{
        FileReader fr=new FileReader(filename);
        BufferedReader br =new BufferedReader(fr)
       String lime=br.readLine();
       br.close();
       catch(Exeption e){}
</code>```

Title: JAVA - File I/O cant get file to read

Body:
I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.

public int readInventory(Automobile[] inventory)
{
    final String FILENAME = "inventory.csv";
    int size = 0;

    Scanner input = new Scanner("inventory.csv");
    try
    {
        input = new Scanner(new File(FILENAME));
    }
    catch (FileNotFoundException e)
    {
        System.out.println("Unable to open file " + FILENAME + ".");
    }
    // ...
    return size;
}

Here is the output I'm getting with no syntax errors.

Unable to open file inventory.csv.

Body:
You should try this

        try{
        FileReader fr=new FileReader(filename);
        BufferedReader br =new BufferedReader(fr)
       String lime=br.readLine();
       br.close();
       catch(Exeption e){}


问:
Disabling the squiggly green line in Angular 2+ html template
How can I get rid of the following squiggly green line while I am editing the html template of an Angular 2+ >= v2 (v2 or higher) project without changing the template itself:
Lets say I have the following line:

```<code>         <textarea [(ngModel)]="jobDescription"  cols="40" rows="5" (ngModelChange)="textAreaEmpty()"></textarea>
         <br/>
</code>```

Above line inside Visual Studio Code (1.11.1) Editor looks like the following

Notice the green squiggly line? If I hover over it I see the following hint:

Suggesting : "The attribute name of [[(ngModel)]] must be in lowercase. I want to ignore this suggestion. How can I achieve this without turning off the entire editor suggestions?

I am happy with other potential editor suggestions but for this particular one I would like to turn this green alert off.

Update 1:
my workspace settings looks like the following now

```<code>{
    "files.exclude": {
        "**/.git": true,
        "**/.svn": true,
        "**/.hg": true,
        "**/CVS": true,
        "**/*.js.map": true,
        "**/.DS_Store": true,
        "**/*.js": { "when": "$(basename).ts"}
    },
    "window.zoomLevel": 0,
    "html.suggest.angular1": false
}
</code>```

Update 2: Even adding "html.suggest.angular1": false did not disable these warning and I still see them in my editor:

Note: I have the following Extensions installed:

Angular TypeScript Snippets for VS Code

angular2-inline

Azure Functions Tools - Extensions for VS Code

VS Code - Debugger for Chrome

VS Code ESLint extension

Git History (including git log)

Visual Studio Code HTML Snippets

vscode-htmlhint

IntelliSense for CSS class names

Latest TypeScript and Javascript Grammer

Visual Studio Team Services Extension

Visual Studio Team Services Status Extension for Visual Studio Code

Final Update:

In my case the HTMLHint was the culprit. I disabled the extension and reloaded the work space and now I do not see any more squiggly green line.

答:
I managed to get rid of the annotations by adding a .htmlhintrc file to the root path in my project and adding the following values:

{
    "attr-lowercase": false,
    "doctype-first": false
}

Body:
How can I get rid of the following squiggly green line while I am editing the html template of an Angular 2+ >= v2 (v2 or higher) project without changing the template itself:
Lets say I have the following line:

         <textarea [(ngModel)]="jobDescription"  cols="40" rows="5" (ngModelChange)="textAreaEmpty()"></textarea>

Above line inside Visual Studio Code (1.11.1) Editor looks like the following

Notice the green squiggly line? If I hover over it I see the following hint:

Suggesting : "The attribute name of [[(ngModel)]] must be in lowercase. I want to ignore this suggestion. How can I achieve this without turning off the entire editor suggestions?

I am happy with other potential editor suggestions but for this particular one I would like to turn this green alert off.

Update 1:
my workspace settings looks like the following now

{
    "files.exclude": {
        "**/.git": true,
        "**/.svn": true,
        "**/.hg": true,
        "**/CVS": true,
        "**/*.js.map": true,
        "**/.DS_Store": true,
        "**/*.js": { "when": "$(basename).ts"}
    },
    "window.zoomLevel": 0,
    "html.suggest.angular1": false
}

Update 2: Even adding "html.suggest.angular1": false did not disable these warning and I still see them in my editor:

Note: I have the following Extensions installed:

Angular TypeScript Snippets for VS Code

angular2-inline

Azure Functions Tools - Extensions for VS Code

VS Code - Debugger for Chrome

VS Code ESLint extension

Git History (including git log)

Visual Studio Code HTML Snippets

vscode-htmlhint

IntelliSense for CSS class names

Latest TypeScript and Javascript Grammer

Visual Studio Team Services Extension

Visual Studio Team Services Status Extension for Visual Studio Code

Final Update:

In my case the HTMLHint was the culprit. I disabled the extension and reloaded the work space and now I do not see any more squiggly green line.


答:
Use isNaN() function

Example:

```<code> var repay_amount = (loan_amount / no_of_months).toFixed(2);

 if(!isNaN(repay_amount)) //if is NaN don't set value
   document.getElementById("repayment_amount").value = repay_amount;
</code>```

Title: Remove NaN from input while calculation

Body:
I have a javascript function in which I need to remove the NaN from textbox after calculation ?

function calculateInterest() {

    var repay_period = parseInt(document.getElementById("emp_loan_repayment_method_id").value);
    var loan_amount = parseInt(document.getElementById("maximum_loan_amount").value);
    var rate_of_interest = parseInt(document.getElementById("rate_of_interest").value);
    var no_of_months = parseInt(document.getElementById("repayment_periods").value);
    var repay_month_amount = parseInt(document.getElementById("repayment_amount").value);
    var no_of_periods = no_of_months / 12;

    {
        var payable_interest = (loan_amount * no_of_periods * rate_of_interest) / 100;

        var pay_interest = payable_interest.toFixed(2);

        document.getElementById("total_payable_interest").value = pay_interest;

        var repay_amount = (loan_amount / no_of_months).toFixed(2);

        document.getElementById("repayment_amount").value = repay_amount;

        var total_payable_amount = (payable_interest + loan_amount).toFixed(2);

        document.getElementById("total_payable_amount").value = total_payable_amount;

    }
}

Body:
Use isNaN() function

Example:

 var repay_amount = (loan_amount / no_of_months).toFixed(2);

 if(!isNaN(repay_amount)) //if is NaN don't set value
   document.getElementById("repayment_amount").value = repay_amount;


问:
Place a breakpoint on the NSNotificationCenter
Is there any way to break on the NSNotificationCenter posting a Note with a certain name? I have a class that for some reason don't receive en expected note...

Edit for clarification:

I have added an observer for the MPMoviePlayerPlaybackDidFinishNotification, but for some reason it seems as if the Notification isn't sent as expected. A normal fault here is that my object for some reason has unsubscribed itself as an observer (even though I find my code on that part to look valid). So, my intention was whether or not it is possible to break on the NSNotificationCenter actually passing on a NotificationName of a certain type, in this case MPMoviePlayerPlaybackDidFinishNotification...

答: Add a breakpoint in Xcode with the name "-[NSNotificationCenter postNotification:]" using the box displayed in the screenshot. Just remember that this will stop for every notification posted, so you might want to have the debugger log the arguments and autocontinue.


问:
Entity manager get or create
How can I make sure if the object already exist its not created again.

```<code>@Component
public class ProductServiceImpl implements ProductService
{
    @PersistenceContext
    private EntityManager em;

    public Product getOrCreateProduct(String productName, String peoductDescr)
    {
        Product product =(new Product (productName, peoductDescr));
        em.merge(product);
        return product;
    }
}
</code>```

I did this way but as it is still keep creating new db entries instead of returning the new one.

答:
While John's answer will work in most cases there is a multi threading issue, that might cause one call to fail, if two threads invoke getOrCreateProduct simultaneously. Both threads might try to find an existing product and enter the NoResultException block, if there is none. Then both will create a new product and try to merge it. On transaction.commit() only one will succeed and the other thread will enter the PersistenceException block.

This can be either handled by synchronizing your method (with impacts on performance) optionally with double checked locking or as you're already using spring, you could use spring's @Retryable feature.

Here are examples for the different ways. All of the methods will be thread safe and working. But performance wise the getOrCreateProductWithSynchronization will be worst as it synchronizes every call. The getOrCreateProductWithDoubleCheckedLocking and getOrCreateProductWithRetryable should almost be the same from a performance perspective. That is you have to decide whether to go with the additional code complexity introduced by the double-checked-locking or the usage of the spring-only @Retryable feature.

```<code>@Transactional(propagation = Propagation.REQUIRES_NEW)
public synchronized Product getOrCreateProductWithSynchronization(final String productName, final String productDescr) {

  Product product = findProduct(productName);
  if (product != null) {
    return product;
  }

  product = new Product(productName, productDescr);
  em.persist(product);

  return product;
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public Product getOrCreateProductWithDoubleCheckedLocking(final String productName, final String productDescr) {

  Product product = findProduct(productName);
  if (product != null) {
    return product;
  }

  synchronized (this) {
    product = findProduct(productName);
    if (product != null) {
      return product;
    }

    product = new Product(productName, productDescr);
    em.persist(product);
  }

  return product;
}

@Retryable(include = DataIntegrityViolationException.class, maxAttempts = 2)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Product getOrCreateProductWithRetryable(final String productName, final String productDescr) {

  Product product = findProduct(productName);
  if (product != null) {
    return product;
  }

  product = new Product(productName, productDescr);
  em.persist(product);
  return product;
}

private Product findProduct(final String productName) {
  // try to find an existing product by name or return null
}
</code>```

UPDATE:
One more thing to note. The implementations using synchronized will only work correctly, if you got only one instance of your service. That is in a distributed setup these methods still might fail, if invoked in parallel on two ore more instances of your service. The @Retryable solution will handle this correctly as well and thus should be the preferred solution.

Title: Entity manager get or create

Body:
How can I make sure if the object already exist its not created again.

@Component
public class ProductServiceImpl implements ProductService
{
    @PersistenceContext
    private EntityManager em;

    public Product getOrCreateProduct(String productName, String peoductDescr)
    {
        Product product =(new Product (productName, peoductDescr));
        em.merge(product);
        return product;
    }
}

I did this way but as it is still keep creating new db entries instead of returning the new one.

Body:
While John's answer will work in most cases there is a multi threading issue, that might cause one call to fail, if two threads invoke getOrCreateProduct simultaneously. Both threads might try to find an existing product and enter the NoResultException block, if there is none. Then both will create a new product and try to merge it. On transaction.commit() only one will succeed and the other thread will enter the PersistenceException block.

This can be either handled by synchronizing your method (with impacts on performance) optionally with double checked locking or as you're already using spring, you could use spring's @Retryable feature.

Here are examples for the different ways. All of the methods will be thread safe and working. But performance wise the getOrCreateProductWithSynchronization will be worst as it synchronizes every call. The getOrCreateProductWithDoubleCheckedLocking and getOrCreateProductWithRetryable should almost be the same from a performance perspective. That is you have to decide whether to go with the additional code complexity introduced by the double-checked-locking or the usage of the spring-only @Retryable feature.

@Transactional(propagation = Propagation.REQUIRES_NEW)
public synchronized Product getOrCreateProductWithSynchronization(final String productName, final String productDescr) {

  Product product = findProduct(productName);
  if (product != null) {
    return product;
  }

  product = new Product(productName, productDescr);
  em.persist(product);

  return product;
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public Product getOrCreateProductWithDoubleCheckedLocking(final String productName, final String productDescr) {

  Product product = findProduct(productName);
  if (product != null) {
    return product;
  }

  synchronized (this) {
    product = findProduct(productName);
    if (product != null) {
      return product;
    }

    product = new Product(productName, productDescr);
    em.persist(product);
  }

  return product;
}

@Retryable(include = DataIntegrityViolationException.class, maxAttempts = 2)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Product getOrCreateProductWithRetryable(final String productName, final String productDescr) {

  Product product = findProduct(productName);
  if (product != null) {
    return product;
  }

  product = new Product(productName, productDescr);
  em.persist(product);
  return product;
}

private Product findProduct(final String productName) {
  // try to find an existing product by name or return null
}

UPDATE:
One more thing to note. The implementations using synchronized will only work correctly, if you got only one instance of your service. That is in a distributed setup these methods still might fail, if invoked in parallel on two ore more instances of your service. The @Retryable solution will handle this correctly as well and thus should be the preferred solution.


问:
remove white space before after of data in text area
I input string to textarea such as below:

```<code>         email1@gmail.com
   email@gmail.com
 email3@gmail.com
      email4@gmail.com
</code>```

How to format they to:

```<code>email1@gmail.com
email@gmail.com
email3@gmail.com
email4@gmail.com
</code>```

One email in one line in textarea. I want use PHP to make it.
Please help me about solution, thanks you.

答:
If you want to remove all whitespace:

$str = preg_replace('/\s+/', '', $yourstring);
```

Body:
I input string to textarea such as below:

         email1@gmail.com
   email@gmail.com
 email3@gmail.com
      email4@gmail.com

How to format they to:

email1@gmail.com
email@gmail.com
email3@gmail.com
email4@gmail.com

One email in one line in textarea. I want use PHP to make it.
Please help me about solution, thanks you.


问:
ASCII files, how to deal with separator in quoted string?
I have an ASCII file (csv, for instance) that uses , as separator, however this char is also present in quoted strings:

```<code>3,       "hh,1,foo",            foo
"5,,,5", "1,2,3d,,,something ", foo2
test,    "col3",                foo3
</code>```

To avoid such ambiguity I want to replace the , separator by the ; one. How to do that with command line? (under linux).

UPDATE/extra question:

There are at least two options using sed or awk.

My extra question is which one is the fastest? (this can be important for big csv files).

答:
Considering your Input_file will be same as sample shown, if yes then following awk may help you in same too.

```<code>awk -F"\"" '{for(i=1;i<=NF;i+=2){gsub(/,/,";",$i)}} 1' OFS="\""   Input_file
</code>```

Output will be as follows.

```<code>3;       "hh,1,foo";            foo
"5,,,5"; "1,2,3d,,,something "; foo2
test;    "col3";                foo3
</code>```

EDIT: Adding explanation with non-one liner form of solution too here.

```<code>awk -F"\"" '{           ##Making " as a field separator as all the liens in Input_file.
for(i=1;i<=NF;i+=2){    ##Starting a for loop here from variable i value 1 to till value of NF(number of fields in a line) incrementing variable i by 2 here, so that we will NOT touch those commas which are coming in side " " here.
  gsub(/,/,";",$i)      ##Now using gsub functionality of awk which will globally substitute comma with semi colon in current fields value.
}}                      ##closing the block of for loop here.
1                       ##awk works on method of condition then action, so mentioning 1 means I am making condition as TRUE and NO action is defined so by default print of current line of Input_file will happen.
' OFS="\"" Input_file   ##Setting OFS(output field separator) as " and mentioning Inut_file name here.
</code>```

Body:
I have an ASCII file (csv, for instance) that uses , as separator, however this char is also present in quoted strings:

3,       "hh,1,foo",            foo
"5,,,5", "1,2,3d,,,something ", foo2
test,    "col3",                foo3

To avoid such ambiguity I want to replace the , separator by the ; one. How to do that with command line? (under linux).

UPDATE/extra question:

There are at least two options using sed or awk.

My extra question is which one is the fastest? (this can be important for big csv files).

Body:
Considering your Input_file will be same as sample shown, if yes then following awk may help you in same too.

awk -F"\"" '{for(i=1;i<=NF;i+=2){gsub(/,/,";",$i)}} 1' OFS="\""   Input_file

Output will be as follows.

3;       "hh,1,foo";            foo
"5,,,5"; "1,2,3d,,,something "; foo2
test;    "col3";                foo3

EDIT: Adding explanation with non-one liner form of solution too here.

awk -F"\"" '{           ##Making " as a field separator as all the liens in Input_file.
for(i=1;i<=NF;i+=2){    ##Starting a for loop here from variable i value 1 to till value of NF(number of fields in a line) incrementing variable i by 2 here, so that we will NOT touch those commas which are coming in side " " here.
  gsub(/,/,";",$i)      ##Now using gsub functionality of awk which will globally substitute comma with semi colon in current fields value.
}}                      ##closing the block of for loop here.
1                       ##awk works on method of condition then action, so mentioning 1 means I am making condition as TRUE and NO action is defined so by default print of current line of Input_file will happen.
' OFS="\"" Input_file   ##Setting OFS(output field separator) as " and mentioning Inut_file name here.


问:
Added fragment scrolled down
I have two fragments the first fragment contains list of linear layouts and the whole fragment is in scroll view the second fragment is added and the first is hidden on choosing item from the first.
The problem is the second fragment is created scrolled down if the first fragment was scrolled down.
I tried the ways to force second fragment to be scrolled to (0,0) but failed.

the code used to add the second fragment

```<code>public void setActionOnClick(String id) {
     CommentFragment frag = new CommentFragment();
     Bundle bundle = new Bundle();
     bundle.putString("id", id);
     bundle.putString("TAG", TAG_NEWS_STORY);
     ((MainActivity) getActivity()).setCurrentTag(TAG_NEWS_STORY);
     frag.setArguments(bundle);
     android.support.v4.app.FragmentTransaction fragmentTransaction =
     getActivity().getSupportFragmentManager().beginTransaction();
     fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
     android.R.anim.fade_out);
     fragmentTransaction.add(R.id.main_content, frag, TAG_NEWS_STORY);
     fragmentTransaction.addToBackStack(null);
     fragmentTransaction.commit();
}
</code>```

on Attach of second fragment the first fragment is hidden.
I don't want to use fragmentTransaction.replace because there are calls to the api which I don't want to reload.

答:
Before this:

```<code>android.support.v4.app.FragmentTransaction fragmentTransaction =
 getActivity().getSupportFragmentManager().beginTransaction();
</code>```

Add code to remove old fragment:

```<code>getSupportFragmentManager().beginTransaction().remove(yourOldFragment).commitAllowingStateLoss();
</code>```

Title: Added fragment scrolled down

Body:
I have two fragments the first fragment contains list of linear layouts and the whole fragment is in scroll view the second fragment is added and the first is hidden on choosing item from the first.
The problem is the second fragment is created scrolled down if the first fragment was scrolled down.
I tried the ways to force second fragment to be scrolled to (0,0) but failed.

the code used to add the second fragment

public void setActionOnClick(String id) {
     CommentFragment frag = new CommentFragment();
     Bundle bundle = new Bundle();
     bundle.putString("id", id);
     bundle.putString("TAG", TAG_NEWS_STORY);
     ((MainActivity) getActivity()).setCurrentTag(TAG_NEWS_STORY);
     frag.setArguments(bundle);
     android.support.v4.app.FragmentTransaction fragmentTransaction =
     getActivity().getSupportFragmentManager().beginTransaction();
     fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
     android.R.anim.fade_out);
     fragmentTransaction.add(R.id.main_content, frag, TAG_NEWS_STORY);
     fragmentTransaction.addToBackStack(null);
     fragmentTransaction.commit();
}

on Attach of second fragment the first fragment is hidden.
I don't want to use fragmentTransaction.replace because there are calls to the api which I don't want to reload.

Body:
Before this:

android.support.v4.app.FragmentTransaction fragmentTransaction =
 getActivity().getSupportFragmentManager().beginTransaction();

Add code to remove old fragment:

getSupportFragmentManager().beginTransaction().remove(yourOldFragment).commitAllowingStateLoss();


问:
keystroke generation
I have a scenario where i need to generate all possible keystrokes using numbers 2 to 9. The possible keystrokes should generate 2-git, 3-digit etc upto 32-digit numbers. can anybody tell me what is the best way to solve this problem.

Thanks,
Pdit

答:
I'd take a simple recursive approach, here with characters, but you could build your numbers using other means as well..

in C:

```<code>#include <stdio.h>
void keystrokes(int x, int lo, int hi, char array[]) {
  int i;
  if (x > hi)
    return;
  if (x >= lo) {
    array[x] = 0;
    printf ("%s\n", array);
  }
  for (i = 2; i < 10; i++) {
    array[x] = i+'0';
    keystrokes (x+1, lo, hi, array);
  }
}
int main(void)
{
  char array[33];
  keystrokes(0, 2, 32, array);

  return 0;
}
</code>```

It can be optimized a bit (for example, for all 32-digit numbers, it'll still make 10 extra recursive calls), but it'll still take forever to compute all possible combinations.

OwnerDisplayName: Pdit

Title: keystroke generation

Body:
I'd take a simple recursive approach, here with characters, but you could build your numbers using other means as well..

in C:

#include <stdio.h>
void keystrokes(int x, int lo, int hi, char array[]) {
  int i;
  if (x > hi)
    return;
  if (x >= lo) {
    array[x] = 0;
    printf ("%s\n", array);
  }
  for (i = 2; i < 10; i++) {
    array[x] = i+'0';
    keystrokes (x+1, lo, hi, array);
  }
}
int main(void)
{
  char array[33];
  keystrokes(0, 2, 32, array);

  return 0;
}

It can be optimized a bit (for example, for all 32-digit numbers, it'll still make 10 extra recursive calls), but it'll still take forever to compute all possible combinations.

OwnerDisplayName: roe


问:
hibernate named queries
In hibernate, when we do, session.getNamedQuery(QUERY_NAME), we do not need to pass in the name of the hbm.xml file where the named query is stored. The name of the hbm.xml is mentioned in the cfg file.

The question is, if there are 5 hbm.xml files for named queries, and there is a name conflict with respect to the query name(i.e. same QUERY_NAME in all 5 files), how hibernate will resolve it?

Intuitively, it appears before doing session.getNamedQuery(QUERY_NAME), one should need to explicitly load the particular hbm.xml file where the query is written.

答: Hibernate aggregates all the named queries across all hbm file it has loaded under one logical namespace (think of it as a Map with name as the key but with a duplicate check on the key before put(..)). So the names should be unique across a given session factory. So make sure all your named queries are unique.</p>

Title: hibernate named queries


答:
If your dataframe is called df then this should do the trick:

```<code>aux <- df$label[df$difference < 0]
df2 <- df[df$label %in% aux,]
</code>```

aux contains all labels where df$difference < 0. So df2 contains all rows from df with the labels of aux. Of course this could also be put as a single command:

```<code>df2 <- df[df$label %in% df$label[df$difference < 0],]
</code>```

or

```<code>df <- df[df$label %in% df$label[df$difference < 0],]
</code>```

A quick test:

```<code>> df
  label difference
1   test          2
2  test2          3
3  test2         -1
4  test3         -1
5  test4          4
6  test4          5
</code>```

turns into the following df2:

```<code>> df2
  label difference
2  test2          3
3  test2         -1
4  test3         -1
</code>```

As you can see the row numbering is wrong now. this is fixed using row.names(df2) <- 1:NROW(df2)

```<code>> df2
  label difference
1  test2          3
2  test2         -1
3  test3         -1
</code>```

Title: Select entire group if one selection has the given value

Body:
 datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-08-02                                 HSBC   5 - Proposal Awarded            5     6          1
 9 2016-12-13                                 HSBC   6 - Delivery Phase 1            6     7          1
10 2017-08-07                                 HSBC       7 - Phase 1 Live            7    NA         NA
11 2016-07-22                                Lowes      Pre-Qualification            0    NA         NA
12 2016-08-02                          Danske Bank   6 - Delivery Phase 1            6    NA         NA
13 2016-07-22 AP Moller Maersk (IT Transformation)  3 - Commercial Review            3    NA         NA
14 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
15 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
16 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2

I would like to create a new data frame off of this one that selects only the "labels" that have a negative "difference" value. However, I want to select ALL of the similar "labels" like so:

 datetime                                label            option_title option_value  lead difference

 1 2016-07-22                                   GE  3 - Commercial Review            3     2         -1
 2 2017-02-20                                   GE    2 - Solution Review            2     1         -1
 3 2017-02-20                                   GE 1 - Opportunity Review            1     2          1
 4 2017-04-18                                   GE    2 - Solution Review            2     3          1
 5 2017-04-19                                   GE  3 - Commercial Review            3     4          1
 6 2017-04-19                                   GE    4 - Submit Proposal            4     5          1
 7 2017-08-08                                   GE   5 - Proposal Awarded            5    NA         NA
 8 2016-07-22                   BHP Billiton - APJ      Pre-Qualification            0     2          2
 9 2016-07-26                   BHP Billiton - APJ    2 - Solution Review            2     0         -2
10 2016-07-26                   BHP Billiton - APJ      Pre-Qualification            0     2          2

I'm not sure how to do this in dplyr....would SQL be better for this? (I haven't used the sql package in R much)

Body:
If your dataframe is called df then this should do the trick:

aux <- df$label[df$difference < 0]
df2 <- df[df$label %in% aux,]

aux contains all labels where df$difference < 0. So df2 contains all rows from df with the labels of aux. Of course this could also be put as a single command:

df2 <- df[df$label %in% df$label[df$difference < 0],]

or

df <- df[df$label %in% df$label[df$difference < 0],]

A quick test:

> df
  label difference
1   test          2
2  test2          3
3  test2         -1
4  test3         -1
5  test4          4
6  test4          5

turns into the following df2:

> df2
  label difference
2  test2          3
3  test2         -1
4  test3         -1

As you can see the row numbering is wrong now. this is fixed using row.names(df2) <- 1:NROW(df2)

> df2
  label difference
1  test2          3
2  test2         -1
3  test3         -1


问:
clear cache of clients browsers when making changes
When developing a website using HTML/CSS, during the development phase it makes sense to prevent caching as people viewing the website would otherwise see old versions. Ive seen threads on this before using meta tags ie:

```<code><meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />enter code here
</code>```

However this dosent seem to work with HTML5 and similarly I only want to clear clients cache to empty once Ive made an update.

For example if I have an image in index.html and update this image (same filename different content) then clients would see the previous image

Is there a way I can version html pages such that the clients browser would cache version 1 then on reloading If I change the html to version 2 the cache would be emptied and the new website with all changes would be loaded?

Seems this would need to be the case in most web developments otherwise clients would never see changes

答:
You have the possibility to edit the <link> file in the index page (or wherever you load in the  file in. After the .css you need to enter a query like ?v=...

So like this:

OLD FILE: <link href="/css/TestFile.css" rel="stylesheet">

After editing it to refresh the cache: <link href="/css/TestFile.css?v=1" rel="stylesheet"> v standing for version, you can use any character.

This resets the cache for everyone visiting the website and make them see the new version instead of the old version

Body:
When developing a website using HTML/CSS, during the development phase it makes sense to prevent caching as people viewing the website would otherwise see old versions. Ive seen threads on this before using meta tags ie:

<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />enter code here

However this dosent seem to work with HTML5 and similarly I only want to clear clients cache to empty once Ive made an update.

For example if I have an image in index.html and update this image (same filename different content) then clients would see the previous image

Is there a way I can version html pages such that the clients browser would cache version 1 then on reloading If I change the html to version 2 the cache would be emptied and the new website with all changes would be loaded?

Seems this would need to be the case in most web developments otherwise clients would never see changes


问:
Nested properties are not reactive in Vue
I have a component with nested properties:

```<code> data () {
   return {
     config: {
       headers: ['a', 'b', 'c'],
       pagination: {
         currentPage: externalService.data.page
         totalPages: externalService.data.totalPages
       }
     }
   }
 }
</code>```

When externalService.data.totalPages is changed (by other component), the child components are not reactive to this, since maybe the nested reference in config was changed, but not config itself.

I can use watchers to solve it, but I wish to know what would be the declarative (and optimal) solution for it. I'm not a fan of imperative approach when it comes to ClientSide.

答: I assume that externalService.data.totalPages is an integer. Integer are passed by value and not by reference. So it's a completely normal behavior an you should indeed use a watcher.

Body:
I have a component with nested properties:

 data () {
   return {
     config: {
       headers: ['a', 'b', 'c'],
       pagination: {
         currentPage: externalService.data.page
         totalPages: externalService.data.totalPages
       }
     }
   }
 }

When externalService.data.totalPages is changed (by other component), the child components are not reactive to this, since maybe the nested reference in config was changed, but not config itself.

I can use watchers to solve it, but I wish to know what would be the declarative (and optimal) solution for it. I'm not a fan of imperative approach when it comes to ClientSide.


问:
How to show the long blob image from database in phpexcel?
I have a table store the data of image in long blob type, how to retrieve image show in phpexcel? My sample of code:</p>

```<code>$order = "SELECT * FROM tblorder";

$tblorder = $conn->query($order);
$row_order = $tblorder->fetch(PDO::FETCH_ASSOC);
$image =$row_order["image"];
$data = base64_encode($image);

$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
$objDrawing->setName('image');
$objDrawing->setDescription('image');
$objDrawing->getIndexedFilename($data);
$objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
$objDrawing->setCoordinates('A85');
$objDrawing->setWorksheet($sheet->getActiveSheet());
</code>```

答:
<pre class="lang-php prettyprint-override"><code>$pExcel = new PHPExcel();

$pExcel->setActiveSheetIndex(0);

$aSheet = $pExcel->getActiveSheet();

$aSheet->setTitle('Name');

$data ='data://image/jpg;base64,'.base64_encode($row['Picture']);

$gdImage = imagecreatefromjpeg($data);

$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();

$objDrawing->setName('Sample image');

$objDrawing->setDescription('Sample image');

$objDrawing->setImageResource($gdImage);

$objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);

$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);

$objDrawing->setHeight(150);

$objDrawing->setCoordinates('I1');

$objDrawing->setWorksheet($aSheet);
</code>```

Body:
I have a table store the data of image in long blob type, how to retrieve image show in phpexcel? My sample of code:

$order = "SELECT * FROM tblorder";

$tblorder = $conn->query($order);
$row_order = $tblorder->fetch(PDO::FETCH_ASSOC);
$image =$row_order["image"];
$data = base64_encode($image);

$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
$objDrawing->setName('image');
$objDrawing->setDescription('image');
$objDrawing->getIndexedFilename($data);
$objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
$objDrawing->setCoordinates('A85');
$objDrawing->setWorksheet($sheet->getActiveSheet());