问:
Android: how to check if a View inside of ScrollView is visible?
I have a ScrollView which holds a series of Views.  I would like to be able to determine if a view is currently visible (if any part of it is currently displayed by the ScrollView). I would expect the below code to do this, surprisingly it does not:

```<code>Rect bounds = new Rect();
view.getDrawingRect(bounds);

Rect scrollBounds = new Rect(scroll.getScrollX(), scroll.getScrollY(),
        scroll.getScrollX() + scroll.getWidth(), scroll.getScrollY() + scroll.getHeight());

if(Rect.intersects(scrollBounds, bounds))
{
    //is  visible
}
</code>```

答:
I know its very late. But i have a good solution. Below is the code snippet for getting view visibility percentage in scroll view.

First of all set touch listener on scroll view for getting callback for scroll stop.

```<code>@Override
public boolean onTouch(View v, MotionEvent event) {
    switch ( event.getAction( ) ) {
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(mScrollView == null){
                        mScrollView = (ScrollView) findViewById(R.id.mScrollView);
                    }
                    int childCount = scrollViewRootChild.getChildCount();

                    //Scroll view location on screen
                    int[] scrollViewLocation = {0,0};
                    mScrollView.getLocationOnScreen(scrollViewLocation);

                    //Scroll view height
                    int scrollViewHeight = mScrollView.getHeight();
                    for (int i = 0; i < childCount; i++){
                        View child = scrollViewRootChild.getChildAt(i);
                        if(child != null && child.getVisibility() == View.VISIBLE){
                            int[] viewLocation = new int[2];
                            child.getLocationOnScreen(viewLocation);
                            int viewHeight = child.getHeight();
                            getViewVisibilityOnScrollStopped(scrollViewLocation, scrollViewHeight,
                                    viewLocation, viewHeight, (String) child.getTag(), (childCount - (i+1)));
                        }
                    }
                }
            }, 150);
            break;
    }
    return false;
}
</code>```

In above code snippet, we are getting call backs for scroll view touch events and post a runnable after 150 millis(Not mandatory) after getting the callback for scroll stopped. In that runnable we will get location of scroll view on the screen and scroll view height. Then get the direct child viewgroup instance of scroll view and get the child counts. In my case direct child of scroll view is LinearLayout named scrollViewRootChild. Then iterate all the child views of scrollViewRootChild. In above code snippet you can see I am getting the location of the child on the screen in a integer array named viewLocation, get height of view in variable name viewHeight. Then i called a private method getViewVisibilityOnScrollStopped. You can get the understanding of the internal working of this method by reading documentation.

```<code>/**
 * getViewVisibilityOnScrollStopped
 * @param scrollViewLocation location of scroll view on screen
 * @param scrollViewHeight height of scroll view
 * @param viewLocation location of view on screen, you can use the method of view claas's getLocationOnScreen method.
 * @param viewHeight height of view
 * @param tag tag on view
 * @param childPending number of views pending for iteration.
 */
void getViewVisibilityOnScrollStopped(int[] scrollViewLocation, int scrollViewHeight, int[] viewLocation, int viewHeight, String tag, int childPending) {
    float visiblePercent = 0f;
    int viewBottom = viewHeight + viewLocation[1]; //Get the bottom of view.
    if(viewLocation[1] >= scrollViewLocation[1]) {  //if view's top is inside the scroll view.
        visiblePercent = 100;
        int scrollBottom = scrollViewHeight + scrollViewLocation[1];    //Get the bottom of scroll view
        if (viewBottom >= scrollBottom) {   //If view's bottom is outside from scroll view
            int visiblePart = scrollBottom - viewLocation[1];  //Find the visible part of view by subtracting view's top from scrollview's bottom
            visiblePercent = (float) visiblePart / viewHeight * 100;
        }
    }else{      //if view's top is outside the scroll view.
        if(viewBottom > scrollViewLocation[1]){ //if view's bottom is outside the scroll view
            int visiblePart = viewBottom - scrollViewLocation[1]; //Find the visible part of view by subtracting scroll view's top from view's bottom
            visiblePercent = (float) visiblePart / viewHeight * 100;
        }
    }
    if(visiblePercent > 0f){
        visibleWidgets.add(tag);        //List of visible view.
    }
    if(childPending == 0){
        //Do after iterating all children.
    }
}
</code>```

If you feel any improvement in this code please contribute.

Body:
I have a ScrollView which holds a series of Views.  I would like to be able to determine if a view is currently visible (if any part of it is currently displayed by the ScrollView). I would expect the below code to do this, surprisingly it does not:

Rect bounds = new Rect();
view.getDrawingRect(bounds);

Rect scrollBounds = new Rect(scroll.getScrollX(), scroll.getScrollY(),
        scroll.getScrollX() + scroll.getWidth(), scroll.getScrollY() + scroll.getHeight());

if(Rect.intersects(scrollBounds, bounds))
{
    //is  visible
}

Body:
I know its very late. But i have a good solution. Below is the code snippet for getting view visibility percentage in scroll view.

First of all set touch listener on scroll view for getting callback for scroll stop.

@Override
public boolean onTouch(View v, MotionEvent event) {
    switch ( event.getAction( ) ) {
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(mScrollView == null){
                        mScrollView = (ScrollView) findViewById(R.id.mScrollView);
                    }
                    int childCount = scrollViewRootChild.getChildCount();

                    //Scroll view location on screen
                    int[] scrollViewLocation = {0,0};
                    mScrollView.getLocationOnScreen(scrollViewLocation);

                    //Scroll view height
                    int scrollViewHeight = mScrollView.getHeight();
                    for (int i = 0; i < childCount; i++){
                        View child = scrollViewRootChild.getChildAt(i);
                        if(child != null && child.getVisibility() == View.VISIBLE){
                            int[] viewLocation = new int[2];
                            child.getLocationOnScreen(viewLocation);
                            int viewHeight = child.getHeight();
                            getViewVisibilityOnScrollStopped(scrollViewLocation, scrollViewHeight,
                                    viewLocation, viewHeight, (String) child.getTag(), (childCount - (i+1)));
                        }
                    }
                }
            }, 150);
            break;
    }
    return false;
}

In above code snippet, we are getting call backs for scroll view touch events and post a runnable after 150 millis(Not mandatory) after getting the callback for scroll stopped. In that runnable we will get location of scroll view on the screen and scroll view height. Then get the direct child viewgroup instance of scroll view and get the child counts. In my case direct child of scroll view is LinearLayout named scrollViewRootChild. Then iterate all the child views of scrollViewRootChild. In above code snippet you can see I am getting the location of the child on the screen in a integer array named viewLocation, get height of view in variable name viewHeight. Then i called a private method getViewVisibilityOnScrollStopped. You can get the understanding of the internal working of this method by reading documentation.

/**
 * getViewVisibilityOnScrollStopped
 * @param scrollViewLocation location of scroll view on screen
 * @param scrollViewHeight height of scroll view
 * @param viewLocation location of view on screen, you can use the method of view claas's getLocationOnScreen method.
 * @param viewHeight height of view
 * @param tag tag on view
 * @param childPending number of views pending for iteration.
 */
void getViewVisibilityOnScrollStopped(int[] scrollViewLocation, int scrollViewHeight, int[] viewLocation, int viewHeight, String tag, int childPending) {
    float visiblePercent = 0f;
    int viewBottom = viewHeight + viewLocation[1]; //Get the bottom of view.
    if(viewLocation[1] >= scrollViewLocation[1]) {  //if view's top is inside the scroll view.
        visiblePercent = 100;
        int scrollBottom = scrollViewHeight + scrollViewLocation[1];    //Get the bottom of scroll view
        if (viewBottom >= scrollBottom) {   //If view's bottom is outside from scroll view
            int visiblePart = scrollBottom - viewLocation[1];  //Find the visible part of view by subtracting view's top from scrollview's bottom
            visiblePercent = (float) visiblePart / viewHeight * 100;
        }
    }else{      //if view's top is outside the scroll view.
        if(viewBottom > scrollViewLocation[1]){ //if view's bottom is outside the scroll view
            int visiblePart = viewBottom - scrollViewLocation[1]; //Find the visible part of view by subtracting scroll view's top from view's bottom
            visiblePercent = (float) visiblePart / viewHeight * 100;
        }
    }
    if(visiblePercent > 0f){
        visibleWidgets.add(tag);        //List of visible view.
    }
    if(childPending == 0){
        //Do after iterating all children.
    }
}

If you feel any improvement in this code please contribute.


来源: stackexchange

问:
Calculate all the subsets of a list in python using java approach
I'm working through some interview problems and one of the classic ones, which uses backtracking, is to calculate the powerset (all the subsets) of a list. I have the java solution for the problem:

```<code>    public List<List<Integer>> subsets(int[] nums) {
     List<List<Integer>> list = new ArrayList<>();
     Arrays.sort(nums);
     backtrack(list, new ArrayList<>(), nums, 0);
     return list;
    }

   private void backtrack(List<List<Integer>> list , List<Integer> {
     tempList, int [] nums, int start){
     list.add(new ArrayList<>(tempList));
     for(int i = start; i < nums.length; i++){
      tempList.add(nums[i]);
     backtrack(list, tempList, nums, i + 1);
     tempList.remove(tempList.size() - 1);
   }
 }
</code>```

I'm trying to do the same thing but using python instead:

```<code>class Solution:
  def subsets(self, nums):
   lista = []
   self.backtrack(lista, [], sorted(nums), 0)
   return lista
 def backtrack(self, lista, tempList, nums, start):
   lista.append(tempList)
   for i in range(start, len(nums)):
     tempList.append(nums[i])
     self.backtrack(lista, tempList, nums, i+1)
     tempList.pop()
</code>```

I printed the tempList and it seems to be working as expected. The problem I believe is that it lista.append(tempList) is not working as I expected. Is there some particularity in python that is yielding this different result? Thanks!

答:
```<code>list.add(new ArrayList<>(tempList));
</code>```

Makes a copy of tempList, which you ought to do in your Python version as well!

```<code>lista.append(tempList[:])
# OR
lista.append(list(tempList))  # which is closer in syntax to your java version
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working through some interview problems and one of the classic ones, which uses backtracking, is to calculate the powerset (all the subsets) of a list. I have the java solution for the problem:

    public List<List<Integer>> subsets(int[] nums) {
     List<List<Integer>> list = new ArrayList<>();
     Arrays.sort(nums);
     backtrack(list, new ArrayList<>(), nums, 0);
     return list;
    }

   private void backtrack(List<List<Integer>> list , List<Integer> {
     tempList, int [] nums, int start){
     list.add(new ArrayList<>(tempList));
     for(int i = start; i < nums.length; i++){
      tempList.add(nums[i]);
     backtrack(list, tempList, nums, i + 1);
     tempList.remove(tempList.size() - 1);
   }
 }

I'm trying to do the same thing but using python instead:

class Solution:
  def subsets(self, nums):
   lista = []
   self.backtrack(lista, [], sorted(nums), 0)
   return lista
 def backtrack(self, lista, tempList, nums, start):
   lista.append(tempList)
   for i in range(start, len(nums)):
     tempList.append(nums[i])
     self.backtrack(lista, tempList, nums, i+1)
     tempList.pop()

I printed the tempList and it seems to be working as expected. The problem I believe is that it lista.append(tempList) is not working as I expected. Is there some particularity in python that is yielding this different result? Thanks!

Body:
list.add(new ArrayList<>(tempList));

Makes a copy of tempList, which you ought to do in your Python version as well!

lista.append(tempList[:])
# OR
lista.append(list(tempList))  # which is closer in syntax to your java version


问:
Ajax and DefaultController Symfony
I use Symfony 3 and I try to call my function in the Default Controller with Ajax like this:

```<code>$(document).ready(function() {
    $.ajax({
        dataType: "json",
        type: "POST",
        data: {
            action: 'active'
        },
        url: '{{ path ('
        show_chat ')}}',
        success: function(active) {
            if (active === true)
                $('.message-box').fadeIn();
        },
        error: function() {
            console.log('error');
            return false;
        }
    });
});
</code>```

In the Default Controller I want to return a twig template and a variable which is true so my window for the chat can appear:

```<code>return $this->render('ChatBundle:Default:chat.html.twig',$online);
</code>```

I use  $presence = $request->get('active');  Symfony\Component\HttpFoundation\Response;

My method is POST but when I dump $request the method is GET. I do not understand what I am doing wrong and why it doesn't work ... Any ideas, please

Routing:

```<code>show_chat:
path:     /chat
defaults: { _controller: slackChatBundle:Default:chat}
methods: [POST,GET]
</code>```

If I put only POST method ,I have a message "No route found,Method Not Allowed (Allow: POST)

this is the dump of request:

dump request

答:
Can you provide more specific dumps request->request & request->query ?

And related to following post, I agree you should use FOSJsRoutingBundle. It let you expose symfony routing.

Title: Ajax and DefaultController Symfony

Body:
I use Symfony 3 and I try to call my function in the Default Controller with Ajax like this:

$(document).ready(function() {
    $.ajax({
        dataType: "json",
        type: "POST",
        data: {
            action: 'active'
        },
        url: '{{ path ('
        show_chat ')}}',
        success: function(active) {
            if (active === true)
                $('.message-box').fadeIn();
        },
        error: function() {
            console.log('error');
            return false;
        }
    });
});

In the Default Controller I want to return a twig template and a variable which is true so my window for the chat can appear:

return $this->render('ChatBundle:Default:chat.html.twig',$online);

I use  $presence = $request->get('active');  Symfony\Component\HttpFoundation\Response;

My method is POST but when I dump $request the method is GET. I do not understand what I am doing wrong and why it doesn't work ... Any ideas, please

Routing:

show_chat:
path:     /chat
defaults: { _controller: slackChatBundle:Default:chat}
methods: [POST,GET]

If I put only POST method ,I have a message "No route found,Method Not Allowed (Allow: POST)

this is the dump of request:

dump request


答:
You  could take a part of the string for year and month group in a hash table and take for every group a new array and put this array to the result set.

var data = [{ date: "2016-08-13" }, { date: "2016-07-23" }, { date: "2016-08-11" }, { date: "2016-08-10" }, { date: "2016-07-20" }, { date: "2016-07-21" }],
    hash = Object.create(null),
    result = [];

data.forEach(function (o) {
    var key = o.date.slice(0, 7);
    if (!hash[key]) {
        hash[key] = [];
        result.push(hash[key]);
    }
    hash[key].push(o);
});

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Group array of objects by string property value in JavaScript?

Body:
I hate this array of objects, each object has a date, I want to  be able to group these objects into months. Is there a way to convert this,

var data  = [
  { date: "2016-08-13",...},
  { date: "2016-07-23",...},
  { date: "2016-08-11",...},
  { date: "2016-08-10",...},
  { date: "2016-07-20",...},
  { date: "2016-07-21",...},
]

into something like this

var data  = [
  [{ date: "2016-08-13",...},
  { date: "2016-08-11",...},
  { date: "2016-08-10",...}],
  [{ date: "2016-07-20",...},
  { date: "2016-07-21",...},
  { date: "2016-07-23",...}[
]

Body:
You  could take a part of the string for year and month group in a hash table and take for every group a new array and put this array to the result set.

var data = [{ date: "2016-08-13" }, { date: "2016-07-23" }, { date: "2016-08-11" }, { date: "2016-08-10" }, { date: "2016-07-20" }, { date: "2016-07-21" }],
    hash = Object.create(null),
    result = [];

data.forEach(function (o) {
    var key = o.date.slice(0, 7);
    if (!hash[key]) {
        hash[key] = [];
        result.push(hash[key]);
    }
    hash[key].push(o);
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to change datepicker via select tag
I want to change the datepicker using select tag. for example I stay at the hotel only one night on the 14th and checkout automatically on the 15th. to change the auto checkout date already can .. but is it possible if i change the auto checkout date hotel by using select tag? for example if I select two nights then the checkout date becomes the 16th

The code I have provided in jsfiddle for example.

Thanks in advance

ex : https://jsfiddle.net/devefrontend/vaqdsmjk/7/

    $(document).ready(function() {

      $("#dateStart").datepicker({
        dateFormat: "dd-M-yy",
        minDate: 'dateToday',
        onSelect: function(date) {
          var date2 = $('#dateStart').datepicker('getDate');
          date2.setDate(date2.getDate() + 1);
          $('#dateEnd').datepicker('setDate', date2);
          //sets minDate to dt1 date + 1
          $('#dateEnd').datepicker('option', 'minDate', date2);
        }
      }).datepicker("setDate", new Date());
      $('#dateEnd').datepicker({
        dateFormat: "dd-M-yy",
        minDate: 1,
        onClose: function() {
          var dt1 = $('#dateStart').datepicker('getDate');
          console.log(dt1);
          var dt2 = $('#dateEnd').datepicker('getDate');
          if (dt2 <= dt1) {
            var minDate = $('#dateEnd').datepicker('option', 'minDate');
            $('#dateEnd').datepicker('setDate', minDate);
          }
        }
      }).datepicker("setDate", new Date());

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<label for="">start</label>
<input type="text" class="form-control" id="dateStart" name="start">
<label for="">end</label>
<input type="text" class="form-control" id="dateEnd" name="end">
<label for="">night</label>
<select name="night" id="night" class="form-control passenger">
  <option selected="selected">1 night</option>
  <option>2 night</option>
  <option>3 night</option>
  <option>4 night</option>
  <option>5 night</option>
  <option>6 night</option>
  <option>7 night</option>
  <option>8 night</option>
</select></code>```

答:
Extract everything from onSelect of #dateStart and convert that into a function. Call this function on change of the select and instead of hardcode addition of 1 night, you use the value selected from the dropdown:

function populateEndDate() {
  var date2 = $('#dateStart').datepicker('getDate');
  date2.setDate(date2.getDate() + parseInt($("#night").val()));
  $('#dateEnd').datepicker('setDate', date2);
}

$(document).ready(function() {

  $("#dateStart").datepicker({
    dateFormat: "dd-M-yy",
    minDate: 'dateToday',
    onSelect: function(date) {
      populateEndDate();
    }
  }).datepicker("setDate", new Date());
  $('#dateEnd').datepicker({
    dateFormat: "dd-M-yy",
    minDate: 1,
    onClose: function() {
      var dt1 = $('#dateStart').datepicker('getDate');
      console.log(dt1);
      var dt2 = $('#dateEnd').datepicker('getDate');
      if (dt2 <= dt1) {
        var minDate = $('#dateEnd').datepicker('option', 'minDate');
        $('#dateEnd').datepicker('setDate', minDate);
      }
    }
  }).datepicker("setDate", new Date());

});

$("#night").on('change', function() {
  populateEndDate();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<label for="">start</label>
<input type="text" class="form-control" id="dateStart" name="start">
<label for="">end</label>
<input type="text" class="form-control" id="dateEnd" name="end">
<label for="">night</label>
<select name="night" id="night" class="form-control passenger">
  <option selected="selected" value=1>1 night</option>
  <option value=2>2 night</option>
  <option value=3>3 night</option>
  <option value=4>4 night</option>
  <option value=5>5 night</option>
  <option value=6>6 night</option>
  <option value=7>7 night</option>
  <option value=8>8 night</option>
</select></code>```

Title: How to change datepicker via select tag

Body:
I want to change the datepicker using select tag. for example I stay at the hotel only one night on the 14th and checkout automatically on the 15th. to change the auto checkout date already can .. but is it possible if i change the auto checkout date hotel by using select tag? for example if I select two nights then the checkout date becomes the 16th

The code I have provided in jsfiddle for example.

Thanks in advance

ex : https://jsfiddle.net/devefrontend/vaqdsmjk/7/

    $(document).ready(function() {

      $("#dateStart").datepicker({
        dateFormat: "dd-M-yy",
        minDate: 'dateToday',
        onSelect: function(date) {
          var date2 = $('#dateStart').datepicker('getDate');
          date2.setDate(date2.getDate() + 1);
          $('#dateEnd').datepicker('setDate', date2);
          //sets minDate to dt1 date + 1
          $('#dateEnd').datepicker('option', 'minDate', date2);
        }
      }).datepicker("setDate", new Date());
      $('#dateEnd').datepicker({
        dateFormat: "dd-M-yy",
        minDate: 1,
        onClose: function() {
          var dt1 = $('#dateStart').datepicker('getDate');
          console.log(dt1);
          var dt2 = $('#dateEnd').datepicker('getDate');
          if (dt2 <= dt1) {
            var minDate = $('#dateEnd').datepicker('option', 'minDate');
            $('#dateEnd').datepicker('setDate', minDate);
          }
        }
      }).datepicker("setDate", new Date());

    });

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

start
<input type="text" class="form-control" id="dateStart" name="start">
end
<input type="text" class="form-control" id="dateEnd" name="end">
night
<select name="night" id="night" class="form-control passenger">
  <option selected="selected">1 night</option>
  <option>2 night</option>
  <option>3 night</option>
  <option>4 night</option>
  <option>5 night</option>
  <option>6 night</option>
  <option>7 night</option>
  <option>8 night</option>
</select>

Body:
Extract everything from onSelect of #dateStart and convert that into a function. Call this function on change of the select and instead of hardcode addition of 1 night, you use the value selected from the dropdown:

function populateEndDate() {
  var date2 = $('#dateStart').datepicker('getDate');
  date2.setDate(date2.getDate() + parseInt($("#night").val()));
  $('#dateEnd').datepicker('setDate', date2);
}

$(document).ready(function() {

  $("#dateStart").datepicker({
    dateFormat: "dd-M-yy",
    minDate: 'dateToday',
    onSelect: function(date) {
      populateEndDate();
    }
  }).datepicker("setDate", new Date());
  $('#dateEnd').datepicker({
    dateFormat: "dd-M-yy",
    minDate: 1,
    onClose: function() {
      var dt1 = $('#dateStart').datepicker('getDate');
      console.log(dt1);
      var dt2 = $('#dateEnd').datepicker('getDate');
      if (dt2 <= dt1) {
        var minDate = $('#dateEnd').datepicker('option', 'minDate');
        $('#dateEnd').datepicker('setDate', minDate);
      }
    }
  }).datepicker("setDate", new Date());

});

$("#night").on('change', function() {
  populateEndDate();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<label for="">start</label>
<input type="text" class="form-control" id="dateStart" name="start">
<label for="">end</label>
<input type="text" class="form-control" id="dateEnd" name="end">
<label for="">night</label>
<select name="night" id="night" class="form-control passenger">
  <option selected="selected" value=1>1 night</option>
  <option value=2>2 night</option>
  <option value=3>3 night</option>
  <option value=4>4 night</option>
  <option value=5>5 night</option>
  <option value=6>6 night</option>
  <option value=7>7 night</option>
  <option value=8>8 night</option>
</select>


问:
BatchUpdateException: the batch will not terminate
I have an application which processes a very large file and sends data to an oracle database (using Java 6, oracle 9).

In a loop, I use a PreparedStatement ps and create all SQL statements generated with ps.addBatch().

I have a situation where a BatchUpdateException bue is thrown somewhere during the ps.executeBatch(). At that point, the batch stops to be executed.

I'd like the batch execution to continue, so that I can then check on failed updates in a method processUpdateCounts(bue.getUpdateCounts()).

The javadoc about class BatchUpdateException says:

After a command in a batch update
  fails to execute properly and a
  BatchUpdateException is thrown, the
  driver may or may not continue to
  process the remaining commands in the
  batch.

Is there a way to enforce continuation or do I need to alter my program so that it will execute the statement individually?

答:
Oracle itself can, see here: http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14250/oci04sql.htm#sthref616

However, it doesn't seem that this functionality is exposed to JDBC, not even in the oracle specific classes.

Because of the rather useless JDBC error handling ("the driver may or may not continue"), I'm always setting a savepoint before the batch, and performing an rollback to that point on error. That's the only JDBC compliant way to establish a known state after an Oracle Batch Error--as far as I know.

ContentLicense: CC BY-SA 2.5


问:
Should I call a single sql statement to retrieve data for a service or different distinct calls
I have a requirement where I need to return some data from a web service (in .net). The response of the service would be a class having different attributes. Some of the attributes are complex and need data to be fetched for such types need separate call.
Ex:

```<code>Class getServiceData

{

    public int SimpleProperty1 {get;set;}

    public int SimpleProperty2 {get;set;}

    public IEnumerable<ComplexProperty> {get;set;}
  ...

}
</code>```

For getting the data for such class, I need to call the Oracle database. My question is whether I should bring all the data for the service in a single sql statement (please note the structure involves some hierarchy) or call separate statements for different attributes of the class.

thanks in advance

答:
If performance is the biggest criteria, then I would ask you to pull all the data in a single query itself.

Using Oracle to directly return data is easier than using any wrapper that would return data in parts.

However be careful if you are using a Stored Procedure with a lot of processing in it as this can become difficult to debug and has the tendency to become a black box while testing (hides the processing from code).

Body:
I have a requirement where I need to return some data from a web service (in .net). The response of the service would be a class having different attributes. Some of the attributes are complex and need data to be fetched for such types need separate call.
Ex:

Class getServiceData

{

    public int SimpleProperty1 {get;set;}

    public int SimpleProperty2 {get;set;}

    public IEnumerable<ComplexProperty> {get;set;}
  ...

}

For getting the data for such class, I need to call the Oracle database. My question is whether I should bring all the data for the service in a single sql statement (please note the structure involves some hierarchy) or call separate statements for different attributes of the class.

thanks in advance


问:
How to iterate over a file with huge no of lines to find a string?
Python:

I have a particular word which Iam looking in a text file of large size which is in millions of records.

So actually i wanted to search if a particular string is availabe in the file.

One way i did is :

```<code>with open('ip.log', 'r') as f:
     for line in f:
         if semething in line:
            break
     else:
         print 'Not found'
</code>```

But for small files this process will be fine,but when file size increases or records grow to tens of millions.Loading that big file into memory may not be a feasible solution.

Is there any better way to deal with this problem?

Observations:

If file is so huge of 1GB or something, it will slow up the system

Looking for one text we need to iterate over millions of records each time.

答:
Your worries are unfounded: your code does not load the entire file into memory-- try it! And the break in your loop will stop reading the file as soon as it finds the word you search for, so that's not a worry either.

In your code, f is a file object that reads one line at a time when used with a for-loop. If you had written f.readlines() or f.read(), then you would be reading the entire file.

The only potential problem is if your files do not contain newlines (e.g. if they are binary files, or enormous lists of words separated by spaces rather than newlines). In that case, you'd need to read blocks of characters with something like f.read(10000) (and deal with words being broken across blocks). Since your use case involves regular text files, there's no need to worry about that.

Body:
Python:

I have a particular word which Iam looking in a text file of large size which is in millions of records.

So actually i wanted to search if a particular string is availabe in the file.

One way i did is :

with open('ip.log', 'r') as f:
     for line in f:
         if semething in line:
            break
     else:
         print 'Not found'

But for small files this process will be fine,but when file size increases or records grow to tens of millions.Loading that big file into memory may not be a feasible solution.

Is there any better way to deal with this problem?

Observations:

If file is so huge of 1GB or something, it will slow up the system

Looking for one text we need to iterate over millions of records each time.


问:
Need Help in Integrating Javascript with Wordpress
I have wordpress account for blogging. Recently I have opted for PopUpAds. I have the javascript code with me which I received from PopUpAds.

Can any one please tell me how to integrate this code into wordpress??

Any informative links will also be very helpful.

Thank You In advance.

答:
Using a Wordpress plugin that lets you insert arbitrary HTML code as a shortcode is the best way to go IMO. That way the external code doesn't mess with the wysiwyg editor. I use this plugin: https://en-ca.wordpress.org/plugins/insert-html-snippet/

If the JavaScript code should be added to the head section of your page, there are plugins that do that as well.

Check out this useful blog post for adding external JS and CSS to Wordpress: http://blog.dynamicdrive.com/add-custom-javascript-css-wordpress/


问:
Angular ng-repeat not showing data on laravel?
The console shows that the posts were retrieved successfully, the backend works fine without the angular compatibility.

and its supposed to retrieve post data.

angular.js:12701 XHR finished loading: GET
  "http://127.0.0.1:8000/auth/posts".

however it shows 5 empty divs like the following

main.js

```<code>$http.get('/auth/posts').then(function(data){
    $scope.myposts = data;

});
</code>```

PostController

```<code>   public function getPosts()
    {

        $posts = Post::all();
        return json_encode($posts);
    }
</code>```

Route

Route::get('auth/posts', 'HomeController@getPosts');

the html file

```<code><div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
    <div id="eli-style-heading" class="panel-heading"><% post.title %></div>
        <div class="panel-body panel">
            <figure>
                <p> <% post.body %></p>

            </figure>
        </div>
</div>
</code>```

答:
You need to access the data property from the response, I think you need,</p>

```<code>$http.get('/auth/posts').then(function(data){
    $scope.myposts = data.data;

});
</code>```

Body:
The console shows that the posts were retrieved successfully, the backend works fine without the angular compatibility.

and its supposed to retrieve post data.

angular.js:12701 XHR finished loading: GET
  "http://127.0.0.1:8000/auth/posts".

however it shows 5 empty divs like the following

main.js

$http.get('/auth/posts').then(function(data){
    $scope.myposts = data;

});

PostController

   public function getPosts()
    {

        $posts = Post::all();
        return json_encode($posts);
    }

Route

Route::get('auth/posts', 'HomeController@getPosts');

the html file

<% post.title %>

 <% post.body %>

Body:
You need to access the data property from the response, I think you need,

$http.get('/auth/posts').then(function(data){
    $scope.myposts = data.data;

});


问:
StatFs returns different size from setting
I am trying to get the storage space on Android. Here is the solution I found.

```<code>StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath())
stat.getTotalBytes()
</code>```

It returns 774 MB while the setting app shows1 GB. In AVD Manager, size on disk is 1 GB. Is it possible to get the same value like setting app?

答:
Try,

```<code>StatFs stat1 = new StatFs("YOUR PATH HERE");
    long bytesAvailable1 = (long) stat1.getAvailableBlocks() * (long) stat1.getBlockSize();
    double spaceAvailableInSD1 = Double.parseDouble(new DecimalFormat("##.##").format(bytesAvailable1 / 1073741824d));  //return MB.
</code>```

I am getting exact available storage space in my case.

Body:
I am trying to get the storage space on Android. Here is the solution I found.

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath())
stat.getTotalBytes()

It returns 774 MB while the setting app shows1 GB. In AVD Manager, size on disk is 1 GB. Is it possible to get the same value like setting app?

Body:
Try,

StatFs stat1 = new StatFs("YOUR PATH HERE");
    long bytesAvailable1 = (long) stat1.getAvailableBlocks() * (long) stat1.getBlockSize();
    double spaceAvailableInSD1 = Double.parseDouble(new DecimalFormat("##.##").format(bytesAvailable1 / 1073741824d));  //return MB.

I am getting exact available storage space in my case.


问:
Why I am getting the bad length exception when I am running this application?
I want to communicate to a server from  J2me app using UDP.However, when I am running the app, I am getting a bad length exception.My codes and output are given below.

client code

```<code>import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import java.io.IOException;

public class DatagramTest extends MIDlet
implements CommandListener, Runnable
{
private static final int BUF_SIZE = 1024;
private static Command exit = new Command("Exit", Command.EXIT, 1);
private static DatagramTest instance;
private Display display;
private TextBox dgramText;

private DatagramConnection conn;

private Datagram dgram;

private String address = "datagram://myip:9876";

public DatagramTest()
{
super();
instance = this;
}

public DatagramTest(String service)
{
this();
address = service;
}
/**
Returns the single instance of this class. Calling
this method before constructing an object will return
a null pointer.
@return an instance of this class.
*/
public static DatagramTest getInstance()
{
return instance;
}
public void startApp()
{
display = Display.getDisplay(this);
dgramText = new TextBox("Datagram contents",
null,
2048,
TextField.ANY);
dgramText.setCommandListener(this);
display.setCurrent(dgramText);
System.out.println("Starting run....");
run();
System.out.println("Stopping run....");
}

public void run()
{
     System.out.println("In run....");
try
{
int maxLength;

conn = (DatagramConnection)Connector.open(address);
maxLength = conn.getMaximumLength();
dgram = conn.newDatagram(1024);

dgram.reset();

conn.send(dgram);

conn.receive(dgram);

byte[] data = dgram.getData();
// Extract the response string.
String str = new String(data);

System.out.println(str);

dgram.reset();
System.out.println("Exit run....");

}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
quit();
}
return;
}
public void pauseApp()
{
}
void quit()
{
destroyApp(true);
notifyDestroyed();
}
public void destroyApp(boolean destroy)
{
try
{
conn.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
public void display()
{
Display.getDisplay(this).setCurrent(dgramText);
}
public void commandAction(Command c, Displayable d)
{
if (c == exit)
{
quit();
}
}
}
</code>```

Server code

```<code>import java.io.*;
import java.net.*;

class UDPServer
{
   public static void main(String args[]) throws Exception
      {
         DatagramSocket serverSocket = new DatagramSocket(9876);
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            while(true)
               {
                  DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                  serverSocket.receive(receivePacket);
                  String sentence = new String( receivePacket.getData());
                  System.out.println("RECEIVED: " + sentence);
                  InetAddress IPAddress = receivePacket.getAddress();
                  int port = receivePacket.getPort();
                  String capitalizedSentence = sentence.toUpperCase();
                  sendData = capitalizedSentence.getBytes();
                  DatagramPacket sendPacket =
                  new DatagramPacket(sendData, sendData.length, IPAddress, port);
                  serverSocket.send(sendPacket);
               }
      }
}
</code>```

Output at clientside

Starting run.... In run.... Bad
  datagram length java.io.IOException:
  Bad datagram length
          at com.sun.midp.io.j2me.datagram.Protocol.receive(Protocol.java:367)
          at hello.DatagramTest.run(DatagramTest.java:89)
          at hello.DatagramTest.startApp(DatagramTest.java:69)
          at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:43)
          at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:374)
          at com.sun.midp.main.Main.runLocalClass(Main.java:466)
          at com.sun.midp.main.Main.main(Main.java:120)
  Stopping run....

Why I am getting this bad length exception and how do I sort it out?

答:
One thing you need to try is to send and receive datagrams in a separate thread.

The documentation for DatagramConnection.receive() says: "This method blocks until a datagram is received"

You are calling it from inside MIDlet.startApp().

Blocking the application management system thread that calls startApp() is bad practice.

Body:
I want to communicate to a server from  J2me app using UDP.However, when I am running the app, I am getting a bad length exception.My codes and output are given below.

client code

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import java.io.IOException;

public class DatagramTest extends MIDlet
implements CommandListener, Runnable
{
private static final int BUF_SIZE = 1024;
private static Command exit = new Command("Exit", Command.EXIT, 1);
private static DatagramTest instance;
private Display display;
private TextBox dgramText;

private DatagramConnection conn;

private Datagram dgram;

private String address = "datagram://myip:9876";

public DatagramTest()
{
super();
instance = this;
}

public DatagramTest(String service)
{
this();
address = service;
}
/**
Returns the single instance of this class. Calling
this method before constructing an object will return
a null pointer.
@return an instance of this class.
*/
public static DatagramTest getInstance()
{
return instance;
}
public void startApp()
{
display = Display.getDisplay(this);
dgramText = new TextBox("Datagram contents",
null,
2048,
TextField.ANY);
dgramText.setCommandListener(this);
display.setCurrent(dgramText);
System.out.println("Starting run....");
run();
System.out.println("Stopping run....");
}

public void run()
{
     System.out.println("In run....");
try
{
int maxLength;

conn = (DatagramConnection)Connector.open(address);
maxLength = conn.getMaximumLength();
dgram = conn.newDatagram(1024);

dgram.reset();

conn.send(dgram);

conn.receive(dgram);

byte[] data = dgram.getData();
// Extract the response string.
String str = new String(data);

System.out.println(str);

dgram.reset();
System.out.println("Exit run....");

}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
quit();
}
return;
}
public void pauseApp()
{
}
void quit()
{
destroyApp(true);
notifyDestroyed();
}
public void destroyApp(boolean destroy)
{
try
{
conn.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
public void display()
{
Display.getDisplay(this).setCurrent(dgramText);
}
public void commandAction(Command c, Displayable d)
{
if (c == exit)
{
quit();
}
}
}

Server code

import java.io.*;
import java.net.*;

class UDPServer
{
   public static void main(String args[]) throws Exception
      {
         DatagramSocket serverSocket = new DatagramSocket(9876);
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            while(true)
               {
                  DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                  serverSocket.receive(receivePacket);
                  String sentence = new String( receivePacket.getData());
                  System.out.println("RECEIVED: " + sentence);
                  InetAddress IPAddress = receivePacket.getAddress();
                  int port = receivePacket.getPort();
                  String capitalizedSentence = sentence.toUpperCase();
                  sendData = capitalizedSentence.getBytes();
                  DatagramPacket sendPacket =
                  new DatagramPacket(sendData, sendData.length, IPAddress, port);
                  serverSocket.send(sendPacket);
               }
      }
}

Output at clientside

Starting run.... In run.... Bad
  datagram length java.io.IOException:
  Bad datagram length
          at com.sun.midp.io.j2me.datagram.Protocol.receive(Protocol.java:367)
          at hello.DatagramTest.run(DatagramTest.java:89)
          at hello.DatagramTest.startApp(DatagramTest.java:69)
          at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:43)
          at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:374)
          at com.sun.midp.main.Main.runLocalClass(Main.java:466)
          at com.sun.midp.main.Main.main(Main.java:120)
  Stopping run....

Why I am getting this bad length exception and how do I sort it out?


问:
Clustering Category Purchases in Customer Data
I am attempting to cluster a group of customers based on spend, order frequency, order breadth and what % of purchases they make in each category (there are around 20).

It will probably be a simple answer but I cannot figure out whether I should standardize (subtract mean and divide by sd) the % category buy columns or not. When I dont standardize I can get around 90% of the variance explained in 4-5 principal components (using SVD), but when I standardize each column I only get around 40% for the same number of principal components. My worry is that because each column is related, I am removing the relationship by standardizing. At the same time I am worried that not standardizing will cause issues with the other variables in the data that I have standardized.

I would assume if others tried clustering in this way they would face a similar issue but I cant seem to find one so it might be that I just dont understand the situation. Thanks for any clarification in advance!

Chris,

答:
Percentage scale has a well defined range and nice properties.

By heuristically scaling these features you usually make things worse.


问:
Get binary mask in python
What is the easiest/fastest way to get a int in python which can be represented by all ones in binary. This is for generating N bit masks.

E.g:

```<code>If total number of bits is 4, then binary '1111' or int 15
If total number of bits is 8 then, binary '1111 1111' or 255
</code>```

I was under the impression ~0 is for that purpose, looks like that is not the case or I am missing something.

答:
it's very easy to achieve with bit shifting:

```<code>>>> (1<<4)-1
15
</code>```

shifting 4 times 1 to the left gives you 0b10000, substract 1 you get 0b1111 aka 15.

(the int("1"*4,2) method is overkill because it involves building a string and parsing it back)

Title: Get binary mask in python

Body:
What is the easiest/fastest way to get a int in python which can be represented by all ones in binary. This is for generating N bit masks.

E.g:

If total number of bits is 4, then binary '1111' or int 15
If total number of bits is 8 then, binary '1111 1111' or 255

I was under the impression ~0 is for that purpose, looks like that is not the case or I am missing something.

Body:
it's very easy to achieve with bit shifting:

>>> (1<<4)-1
15

shifting 4 times 1 to the left gives you 0b10000, substract 1 you get 0b1111 aka 15.

(the int("1"*4,2) method is overkill because it involves building a string and parsing it back)


问:
Xcode licence must be accepted error when trying to select Xamarin Agent
I am trying to create my first iOS app using C# and Visual Studio 2017, and I am receiving the following error when trying to connect to the mac:

"Xcode licence must be accepted in order to be connected and working against the Mac."

I am assuming that this means I have to install Xcode on the mac, but I can't find any tutorials which mention this, or how to get started. Even if you go to the Microsoft documentation for Visual Studio 2017, linked to on this page:

https://msdn.microsoft.com/en-us/library/dn879698.aspx

you end up on this page:

https://learn.microsoft.com/en-us/visualstudio/cross-platform/cross-platform-mobile-development-in-visual-studio

which mentions nothing about XCode, and tells you, "To get started, install Visual Studio 2015".

I have looked around for tutorials, but can't find any. I could just install XCode on the mac, but I don't want to run around just blindly installing things without knowing exactly what I'm doing.

Can anyone point me in the right direction?

答:
Use "xcode-select --install", as instructed by enter link description here

Switch the xcode "sudo xcode-select -s /Applications/Xcode.app/Contents/Developer" as instructed here

It worked for me.


问:
How to print a 2d array horizontally multiple times
I am using java and I would like to print a 2d array horizontally multiple time based on user input. However, my array prints vertically, can anyone help? </p>

```<code>    n=3; //user input
    char[][] board = new char[2][3];
    char[][] f = new char[board.length][n * board[0].length];
    for (int i = 1; i < n + 1; i++) {
        int Start = (i * board[0].length) - board[0].length;
        int End = i * board[0].length;
        for (int row = 0; row < f.length; row++) {
            for (int col = nStart; col < nEnd; col++) {
                f[row][col] = board[row][col - nStart];
                System.out.print(f[row][col]);
            }
            System.out.println();
        }
    }
For example board array =
xx
xx
I would like
xxxxxx
xxxxxx
</code>```

答:
Your solution works fine except that you made a little mistake in the last lines of your code. I think you want to print a space between every entry by using System.out.println() but println prints a line-break at the end. So your code should look like this:

```<code>n=3; //user input
char[][] board = new char[2][3];
char[][] f = new char[board.length][n * board[0].length];
for (int i = 1; i < n + 1; i++) {
    int Start = (i * board[0].length) - board[0].length;
    int End = i * board[0].length;
    for (int row = 0; row < f.length; row++) {
        for (int col = nStart; col < nEnd; col++) {
            f[row][col] = board[row][col - nStart];
            System.out.print(f[row][col]);
        }
        System.out.print(" "); // Print a space between every single output
    }
}
</code>```

Or if you dont wan't a space at all remove the line completely. Or change the space to a comma, point or whatever you need.

Body:
I am using java and I would like to print a 2d array horizontally multiple time based on user input. However, my array prints vertically, can anyone help?

    n=3; //user input
    char[][] board = new char[2][3];
    char[][] f = new char[board.length][n * board[0].length];
    for (int i = 1; i < n + 1; i++) {
        int Start = (i * board[0].length) - board[0].length;
        int End = i * board[0].length;
        for (int row = 0; row < f.length; row++) {
            for (int col = nStart; col < nEnd; col++) {
                f[row][col] = board[row][col - nStart];
                System.out.print(f[row][col]);
            }
            System.out.println();
        }
    }
For example board array =
xx
xx
I would like
xxxxxx
xxxxxx

Body:
Your solution works fine except that you made a little mistake in the last lines of your code. I think you want to print a space between every entry by using System.out.println() but println prints a line-break at the end. So your code should look like this:

n=3; //user input
char[][] board = new char[2][3];
char[][] f = new char[board.length][n * board[0].length];
for (int i = 1; i < n + 1; i++) {
    int Start = (i * board[0].length) - board[0].length;
    int End = i * board[0].length;
    for (int row = 0; row < f.length; row++) {
        for (int col = nStart; col < nEnd; col++) {
            f[row][col] = board[row][col - nStart];
            System.out.print(f[row][col]);
        }
        System.out.print(" "); // Print a space between every single output
    }
}

Or if you dont wan't a space at all remove the line completely. Or change the space to a comma, point or whatever you need.


答:
Removing the copied array f.
What you need is exchanging row,col in loop.</p>

```<code>n=3; //user input
char[][] board = new char[2][3];
for (int j = 0; j < board[0].length; j++) {
    for (int i = 0; i < n ; i++) {
            System.out.print(board[i][j]);
            System.out.print(" ");
    }
    System.out.println();
}
</code>```

Title: How to print a 2d array horizontally multiple times

Body:
Removing the copied array f.
What you need is exchanging row,col in loop.

n=3; //user input
char[][] board = new char[2][3];
for (int j = 0; j < board[0].length; j++) {
    for (int i = 0; i < n ; i++) {
            System.out.print(board[i][j]);
            System.out.print(" ");
    }
    System.out.println();
}


问:
Installing Ruby 1.9.2 through RVM never works!
When I do >rvm install 1.9.2 it all goes well.  Then I do >rvm use 1.9.2 and that goes well too.

When It comes to ruby -v though..

```<code>sam@sjones:~$ rvm install 1.9.2
/home/sam/.rvm/rubies/ruby-1.9.2-p136, this may take a while depending on your cpu(s)...

ruby-1.9.2-p136 - #fetching
ruby-1.9.2-p136 - #downloading ruby-1.9.2-p136, this may take a while depending on your connection...
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                               Dload  Upload   Total   Spent    Left  Speed
100 8612k  100 8612k    0     0   562k      0  0:00:15  0:00:15 --:--:-- 1305k
ruby-1.9.2-p136 - #extracting ruby-1.9.2-p136 to /home/sam/.rvm/src/ruby-1.9.2-p136
ruby-1.9.2-p136 - #extracted to /home/sam/.rvm/src/ruby-1.9.2-p136
ruby-1.9.2-p136 - #configuring
ruby-1.9.2-p136 - #compiling
ruby-1.9.2-p136 - #installing
ruby-1.9.2-p136 - updating #rubygems for /home/sam/.rvm/gems/ruby-1.9.2-p136@global
ruby-1.9.2-p136 - updating #rubygems for /home/sam/.rvm/gems/ruby-1.9.2-p136
ruby-1.9.2-p136 - adjusting #shebangs for (gem).
ruby-1.9.2-p136 - #importing default gemsets (/home/sam/.rvm/gemsets/)
Install of ruby-1.9.2-p136 - #complete
sam@sjones:~$ rvm use 1.9.2
Using /home/sam/.rvm/gems/ruby-1.9.2-p136
sam@sjones:~$ ruby -v
-bash: ruby: command not found
</code>```

What on earth do I do? I've been trying for a few hours now :P

--Edit--

Here is my rvm info output:

```<code> rvm info

 system:

 system:
    uname:       "Linux sjones 2.6.18-194.8.1.el5.028stab070.2 #1 SMP Tue Jul 6 14:55:39 MSD 2010 x86_64 GNU/Linux"
 bash:        "/bin/bash => GNU bash, version 3.2.39(1)-release (x86_64-pc-linux-gnu)"
 zsh:         " => not installed"

 rvm:
 version:      "rvm 1.2.2 by Wayne E. Seguin (wayneeseguin@gmail.com) [http://rvm.beginrescueend.com/]"

 homes:
 gem:          "not set"
 ruby:         "not set"

 binaries:
 ruby:         ""
 irb:          "/usr/local/bin/irb"
 gem:          ""
 rake:         "/usr/bin/rake"

 environment:
 PATH:         "/usr/local/bin:/usr/bin:/bin:/usr/games:/home/sam/.rvm/bin:/home/sam/.rvm/bin"
 GEM_HOME:     ""
 GEM_PATH:     ""
 MY_RUBY_HOME: ""
 IRBRC:        ""
 RUBYOPT:      ""
 gemset:       ""
</code>```

答:
Try this:

rvm --default use 1.9.2

--EDIT--
problem fixed, you need to run:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"

Body:
When I do >rvm install 1.9.2 it all goes well.  Then I do >rvm use 1.9.2 and that goes well too.

When It comes to ruby -v though..

sam@sjones:~$ rvm install 1.9.2
/home/sam/.rvm/rubies/ruby-1.9.2-p136, this may take a while depending on your cpu(s)...

ruby-1.9.2-p136 - #fetching
ruby-1.9.2-p136 - #downloading ruby-1.9.2-p136, this may take a while depending on your connection...
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                               Dload  Upload   Total   Spent    Left  Speed
100 8612k  100 8612k    0     0   562k      0  0:00:15  0:00:15 --:--:-- 1305k
ruby-1.9.2-p136 - #extracting ruby-1.9.2-p136 to /home/sam/.rvm/src/ruby-1.9.2-p136
ruby-1.9.2-p136 - #extracted to /home/sam/.rvm/src/ruby-1.9.2-p136
ruby-1.9.2-p136 - #configuring
ruby-1.9.2-p136 - #compiling
ruby-1.9.2-p136 - #installing
ruby-1.9.2-p136 - updating #rubygems for /home/sam/.rvm/gems/ruby-1.9.2-p136@global
ruby-1.9.2-p136 - updating #rubygems for /home/sam/.rvm/gems/ruby-1.9.2-p136
ruby-1.9.2-p136 - adjusting #shebangs for (gem).
ruby-1.9.2-p136 - #importing default gemsets (/home/sam/.rvm/gemsets/)
Install of ruby-1.9.2-p136 - #complete
sam@sjones:~$ rvm use 1.9.2
Using /home/sam/.rvm/gems/ruby-1.9.2-p136
sam@sjones:~$ ruby -v
-bash: ruby: command not found

What on earth do I do? I've been trying for a few hours now :P

--Edit--

Here is my rvm info output:

 rvm info

 system:

 system:
    uname:       "Linux sjones 2.6.18-194.8.1.el5.028stab070.2 #1 SMP Tue Jul 6 14:55:39 MSD 2010 x86_64 GNU/Linux"
 bash:        "/bin/bash => GNU bash, version 3.2.39(1)-release (x86_64-pc-linux-gnu)"
 zsh:         " => not installed"

 rvm:
 version:      "rvm 1.2.2 by Wayne E. Seguin (wayneeseguin@gmail.com) [http://rvm.beginrescueend.com/]"

 homes:
 gem:          "not set"
 ruby:         "not set"

 binaries:
 ruby:         ""
 irb:          "/usr/local/bin/irb"
 gem:          ""
 rake:         "/usr/bin/rake"

 environment:
 PATH:         "/usr/local/bin:/usr/bin:/bin:/usr/games:/home/sam/.rvm/bin:/home/sam/.rvm/bin"
 GEM_HOME:     ""
 GEM_PATH:     ""
 MY_RUBY_HOME: ""
 IRBRC:        ""
 RUBYOPT:      ""
 gemset:       ""


问:
android.bluetooth.device.action.ACL_CONNECTED received after device disconnected
I am working on Bluetooth Low Energy Device(Weight Scale).

I have observed few things. When I am trying to disconnect with BLE device, it disconnects. I also removing bond by calling following line.

```<code>method = mBluetoothGatt.getDevice().getClass().getMethod("removeBond", (Class[]) null);
method.invoke(mBluetoothGatt.getDevice(), (Object[]) null);
</code>```

But after few seconds suddenly it shows as it is connected with my Mobile device. When I turned OFF Bluetooth of my mobile device, it(scale) still shows connected symbol. It will only disconnects when I change my mobile device to Airplane mode.

I saw following logs in Android Monitor.

```<code>11-14 10:55:23.438 15152-15207/? W/bt_btif: bta_dm_bl_change_cback : reason=0
11-14 10:55:23.438 15152-15207/? W/bt_btm: btm_acl_update_busy_level :: evt.busy_level_flags : 0x0
11-14 10:55:23.438 15152-15207/? W/bt_btif: bta_dm_bl_change_cback : reason=0
11-14 10:55:23.439 15152-15207/? W/bt_smp: smp_br_connect_callback is called on unexpected transport 2
11-14 10:55:23.439 15152-15207/? W/bt_btif: bta_dm_acl_change info: 0x0
11-14 10:55:23.439 15152-15178/? W/bt_btif: btif_dm_upstreams_cback  ev: BTA_DM_LINK_UP_EVT
11-14 10:55:23.439 15152-15178/? W/bt_btif: BTA_DM_LINK_UP_EVT. Sending BT_ACL_STATE_CONNECTED
11-14 10:55:23.443 18042-18042/com.beurer.connect.healthmanager 11-14 10:55:23.449 15152-15178/? D/BluetoothUtils: getBtEnabledContainers(): btContainers = []
11-14 10:55:23.472 15152-15178/? E/BluetoothRemoteDevices: aclStateChangeCallback: State:Connected to Device:18:7A:93:4C:69:XX, linktype is 2
11-14 10:55:23.479 15152-15178/? D/BluetoothUtils: getBtEnabledContainers(): btContainers = []
11-14 10:55:23.481 15152-15178/? W/bt_btif: btif_dm_upstreams_cback  ev: BTA_DM_BUSY_LEVEL_EVT
11-14 10:55:23.482 15152-15178/? W/bt_btif: BTA_DM_BUSY_LEVEL_EVT :: p_data->busy_level.level_flags : 0x0
11-14 10:55:23.484 18107-18107/? D/oneconnect[1.6.05-45_2]: BluetoothHelper.mBtStateReceiver -  [action]android.bluetooth.device.action.ACL_CONNECTED [connState]0[address] - ($)
11-14 10:55:23.488 3763-3848/? D/CompatibilityInfo: mCompatibilityFlags - 0
11-14 10:55:23.488 3763-3848/? D/CompatibilityInfo: applicationDensity - 480
11-14 10:55:23.488 3763-3848/? D/CompatibilityInfo: applicationScale - 1.0
11-14 10:55:23.493 18107-18133/? D/BluetoothA2dp: getState(18:7A:93:4C:69:XX)
11-14 10:55:23.493 3763-3763/? D/KnoxKeyguardUpdateMonitor: BroadcastReceiver onReceive
11-14 10:55:23.493 3763-3763/? D/KnoxKeyguardUpdateMonitor: BroadcastReceiver onReceive action: android.bluetooth.device.action.ACL_CONNECTED
11-14 10:55:23.493 3763-3763/? D/KnoxKeyguardUpdateMonitor: BroadcastReceiver ACTION_ACL_CONNECTED
11-14 10:55:23.503 3763-4488/? D/CompatibilityInfo: mCompatibilityFlags - 0
11-14 10:55:23.503 3763-4488/? D/CompatibilityInfo: applicationDensity - 480
11-14 10:55:23.503 3763-4488/? D/CompatibilityInfo: applicationScale - 1.0
11-14 10:55:23.513 15152-15342/? D/A2dpStateMachine: getConnectionState: 0
11-14 10:55:23.514 3763-4436/? D/CompatibilityInfo: mCompatibilityFlags - 0
11-14 10:55:23.514 3763-4436/? D/CompatibilityInfo: applicationDensity - 480
11-14 10:55:23.515 3763-4436/? D/CompatibilityInfo: applicationScale - 1.0
11-14 10:55:23.519 18107-18133/? D/BluetoothHeadset: getConnectionState() in if statement
11-14 10:55:23.519 15152-15956/? W/HeadsetService: getConnectionState
11-14 10:55:23.523 15152-15956/? W/HeadsetService: get Service
11-14 10:55:23.523 15152-15956/? W/HeadsetService: service is not null
11-14 10:55:23.524 4983-4983/? W/SearchService: Abort, client detached.
11-14 10:55:23.524 15152-15956/? D/HeadsetService: enter getConnectionState
11-14 10:55:23.525 15152-15956/? D/HeadsetService: getConnectionState is 0
11-14 10:55:23.525 15152-15956/? W/HeadsetService: ret = 0
11-14 10:55:23.527 4983-4983/? I/BistoWorker: handleCommonBroadcastIntent: android.bluetooth.device.action.ACL_CONNECTED
11-14 10:55:23.532 15152-15354/? E/BluetoothRemoteDevices: getGearIsConnected false
11-14 10:55:23.532 18107-18133/? D/oneconnect[1.6.05-45_2]: BluetoothActionHelper.isConnected - ($)69:D4 NO profile connected
11-14 10:55:23.533 18107-18133/? D/oneconnect[1.6.05-45_2]: BluetoothActionHelper.isA2dpSinkConnected - ($)69:D4 mA2dpSlink not connected
11-14 10:55:23.542 4983-4983/? I/BistoWorker: Not a bisto device: 18:7A:93:4C:69:D4
</code>```

Ideally when I request for a connection, it should connect with the device. I don't know why android bluetooth is connecting with device without requesting for a connection.

Does anyone have any idea about this?

=========UPDATE==========

Another thing I found is when I tried to connect with the device(scale), it gives me

```<code>11-15 14:46:38.473 3770-3770/? D/KnoxKeyguardUpdateMonitor: BroadcastReceiver onReceive action: android.bluetooth.device.action.ACL_CONNECTED
</code>```

but on my Service it returned following value.

```<code>11-15 14:46:38.493 23031-23101/? D/BluetoothGatt: onClientConnectionState() - status=133 clientIf=8 device=18:7A:93:4B:E1:XX
</code>```

In the case of 133 GATT_FAILURE, I handled it by attempting 4 re-connects. But it still gave 133 error.

答:
Probably you have autoconnected set to true in your connection request. Be aware that mBluetoothGatt = device.connectGatt(this, false, mGattCallback); takes as second parameter, the autoconnect flag.

Please check [connectGatt](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback)).

Body:
I am working on Bluetooth Low Energy Device(Weight Scale).

I have observed few things. When I am trying to disconnect with BLE device, it disconnects. I also removing bond by calling following line.

method = mBluetoothGatt.getDevice().getClass().getMethod("removeBond", (Class[]) null);
method.invoke(mBluetoothGatt.getDevice(), (Object[]) null);

But after few seconds suddenly it shows as it is connected with my Mobile device. When I turned OFF Bluetooth of my mobile device, it(scale) still shows connected symbol. It will only disconnects when I change my mobile device to Airplane mode.

I saw following logs in Android Monitor.

11-14 10:55:23.438 15152-15207/? W/bt_btif: bta_dm_bl_change_cback : reason=0
11-14 10:55:23.438 15152-15207/? W/bt_btm: btm_acl_update_busy_level :: evt.busy_level_flags : 0x0
11-14 10:55:23.438 15152-15207/? W/bt_btif: bta_dm_bl_change_cback : reason=0
11-14 10:55:23.439 15152-15207/? W/bt_smp: smp_br_connect_callback is called on unexpected transport 2
11-14 10:55:23.439 15152-15207/? W/bt_btif: bta_dm_acl_change info: 0x0
11-14 10:55:23.439 15152-15178/? W/bt_btif: btif_dm_upstreams_cback  ev: BTA_DM_LINK_UP_EVT
11-14 10:55:23.439 15152-15178/? W/bt_btif: BTA_DM_LINK_UP_EVT. Sending BT_ACL_STATE_CONNECTED
11-14 10:55:23.443 18042-18042/com.beurer.connect.healthmanager 11-14 10:55:23.449 15152-15178/? D/BluetoothUtils: getBtEnabledContainers(): btContainers = []
11-14 10:55:23.472 15152-15178/? E/BluetoothRemoteDevices: aclStateChangeCallback: State:Connected to Device:18:7A:93:4C:69:XX, linktype is 2
11-14 10:55:23.479 15152-15178/? D/BluetoothUtils: getBtEnabledContainers(): btContainers = []
11-14 10:55:23.481 15152-15178/? W/bt_btif: btif_dm_upstreams_cback  ev: BTA_DM_BUSY_LEVEL_EVT
11-14 10:55:23.482 15152-15178/? W/bt_btif: BTA_DM_BUSY_LEVEL_EVT :: p_data->busy_level.level_flags : 0x0
11-14 10:55:23.484 18107-18107/? D/oneconnect[1.6.05-45_2]: BluetoothHelper.mBtStateReceiver -  [action]android.bluetooth.device.action.ACL_CONNECTED [connState]0[address] - ($)
11-14 10:55:23.488 3763-3848/? D/CompatibilityInfo: mCompatibilityFlags - 0
11-14 10:55:23.488 3763-3848/? D/CompatibilityInfo: applicationDensity - 480
11-14 10:55:23.488 3763-3848/? D/CompatibilityInfo: applicationScale - 1.0
11-14 10:55:23.493 18107-18133/? D/BluetoothA2dp: getState(18:7A:93:4C:69:XX)
11-14 10:55:23.493 3763-3763/? D/KnoxKeyguardUpdateMonitor: BroadcastReceiver onReceive
11-14 10:55:23.493 3763-3763/? D/KnoxKeyguardUpdateMonitor: BroadcastReceiver onReceive action: android.bluetooth.device.action.ACL_CONNECTED
11-14 10:55:23.493 3763-3763/? D/KnoxKeyguardUpdateMonitor: BroadcastReceiver ACTION_ACL_CONNECTED
11-14 10:55:23.503 3763-4488/? D/CompatibilityInfo: mCompatibilityFlags - 0
11-14 10:55:23.503 3763-4488/? D/CompatibilityInfo: applicationDensity - 480
11-14 10:55:23.503 3763-4488/? D/CompatibilityInfo: applicationScale - 1.0
11-14 10:55:23.513 15152-15342/? D/A2dpStateMachine: getConnectionState: 0
11-14 10:55:23.514 3763-4436/? D/CompatibilityInfo: mCompatibilityFlags - 0
11-14 10:55:23.514 3763-4436/? D/CompatibilityInfo: applicationDensity - 480
11-14 10:55:23.515 3763-4436/? D/CompatibilityInfo: applicationScale - 1.0
11-14 10:55:23.519 18107-18133/? D/BluetoothHeadset: getConnectionState() in if statement
11-14 10:55:23.519 15152-15956/? W/HeadsetService: getConnectionState
11-14 10:55:23.523 15152-15956/? W/HeadsetService: get Service
11-14 10:55:23.523 15152-15956/? W/HeadsetService: service is not null
11-14 10:55:23.524 4983-4983/? W/SearchService: Abort, client detached.
11-14 10:55:23.524 15152-15956/? D/HeadsetService: enter getConnectionState
11-14 10:55:23.525 15152-15956/? D/HeadsetService: getConnectionState is 0
11-14 10:55:23.525 15152-15956/? W/HeadsetService: ret = 0
11-14 10:55:23.527 4983-4983/? I/BistoWorker: handleCommonBroadcastIntent: android.bluetooth.device.action.ACL_CONNECTED
11-14 10:55:23.532 15152-15354/? E/BluetoothRemoteDevices: getGearIsConnected false
11-14 10:55:23.532 18107-18133/? D/oneconnect[1.6.05-45_2]: BluetoothActionHelper.isConnected - ($)69:D4 NO profile connected
11-14 10:55:23.533 18107-18133/? D/oneconnect[1.6.05-45_2]: BluetoothActionHelper.isA2dpSinkConnected - ($)69:D4 mA2dpSlink not connected
11-14 10:55:23.542 4983-4983/? I/BistoWorker: Not a bisto device: 18:7A:93:4C:69:D4

Ideally when I request for a connection, it should connect with the device. I don't know why android bluetooth is connecting with device without requesting for a connection.

Does anyone have any idea about this?

=========UPDATE==========

Another thing I found is when I tried to connect with the device(scale), it gives me

11-15 14:46:38.473 3770-3770/? D/KnoxKeyguardUpdateMonitor: BroadcastReceiver onReceive action: android.bluetooth.device.action.ACL_CONNECTED

but on my Service it returned following value.

11-15 14:46:38.493 23031-23101/? D/BluetoothGatt: onClientConnectionState() - status=133 clientIf=8 device=18:7A:93:4B:E1:XX

In the case of 133 GATT_FAILURE, I handled it by attempting 4 re-connects. But it still gave 133 error.


Body:
I hate this array of objects, each object has a date, I want to  be able to group these objects into months. Is there a way to convert this,

var data  = [
  { date: "2016-08-13",...},
  { date: "2016-07-23",...},
  { date: "2016-08-11",...},
  { date: "2016-08-10",...},
  { date: "2016-07-20",...},
  { date: "2016-07-21",...},
]

into something like this

var data  = [
  [{ date: "2016-08-13",...},
  { date: "2016-08-11",...},
  { date: "2016-08-10",...}],
  [{ date: "2016-07-20",...},
  { date: "2016-07-21",...},
  { date: "2016-07-23",...}[
]

Body:
var data  = [
  { date: "2016-08-13"},
  { date: "2016-07-23"},
  { date: "2016-08-11"},
  { date: "2016-08-10"},
  { date: "2016-07-20"},
  { date: "2016-07-21"},
];

data.sort(function(a, b) {
  var aDate = new Date(a.date);
  var bDate = new Date(b.date);
  return bDate - aDate;
});

console.log(data);


问:
How to write an SQL query that will grab hourly records from a database that updates every minute (and uses the current time)
I'm working on a java program that reads from a database that is keeping various measurements of a lake minute by minute.  I need to write a query that will list each variables by most recent time then skip 1 full hour and display the record at that new time, and repeat that process so I can retrieve the values hourly for the last 48 hours and store them as an array on the java side. The biggest thing is it needs to be real time.  (The DB records 3120 records each hour)

StreamID is that of the sensor, MeasurementID is given to a single measurement, MeasurementValue is the what the sensor returns, and MeasurementTime is using the datetime data type YYYY-MM-DD HH:MM:SS of the measurement

my current select statement is below, I will mostly likely have to do separate statements for each variable but if I can avoid that I would like to.

```<code>SELECT StreamID,MeasurementID,MeasurementValue,MeasurementTime

  FROM measurements

  WHERE StreamID IN (26,27,28,29,30,31,32,33,34,35,14,36,37,38,39,40,
   41,42,43,44,45,46,47,48,49,50,18,13,11,12)

  ORDER BY MeasurementTime DESC, StreamID;
</code>```

Here I have my reading of the db using result set, I'm not sure how to do multiple queries in a row to ignore "&&result2.next()"

```<code> while(result.next())//&&result2.next()

 System.out.println(result.getString(1)+"\t"+result.getString(2)
 +"\t"+result.getString(3)+"\t"+result.getString(4)
 +"/t"+result.getString(5)+"\n";

con.close();
</code>```

答:
I'm not sure I understand exactly what you need to get from the db, but to execute a query hourly you can use a ScheduledExecutorService.

```<code>    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    Runnable task = () -> {
        // Run query
    };
    executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.HOURS);
</code>```

This will create a new thread that runs the run() method at a fixed rate. The rate is specified by scheduleAtFixedRate(task to run, initial delay (before the first time you run it), delay (between every time you run it), unit).

For the query you can try using a PreparedStatement so that you can just update the parameters instead of making a new query, thought I'm not completely sure what you want to do on that part, how do you know what IDs to look for?

EDIT:
As I understand it, you're trying to get records hourly instead of every minute? The new Date and Time API has some pretty nifty tricks that can help you.

Here's a quick mockup I ran earlier:

```<code>String sql = "SELECT * FROM measurements ORDER BY Time";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet result = ps.executeQuery();
ArrayList<Integer> values = new ArrayList<>(); // This is where I store the values I want to keep, you can do it w/e way you want
LocalDateTime ldt1;
LocalDateTime ldt2;
// Take the earliest time
result.next(); // You might want to put that in an if() or catch Exceptions
ldt1 = LocalDateTime.parse(result.getString("Date"));
values.add(result.getInt("Value"));
// Increment throught the values until you find one with more than an hour difference with the first one, keep it and change that first one to this new one to continue
while (result.next()) {
    ldt2 = LocalDateTime.parse(result.getString("Date"));
    if (Duration.between(ldt1, ldt2).getSeconds() >= 60*60) {
        values.add(result.getInt("Value"));
        ldt1 = ldt2;
    }
}
System.out.println("values:\n");
System.out.println(values);
</code>```

My simplified db has theses values:

```<code>Date                    | Value
2017-11-15T22:32:13.590 | 0
2017-11-15T22:47:13.590 | 1
2017-11-15T23:02:13.590 | 2
2017-11-15T23:17:13.590 | 3
2017-11-15T23:32:13.590 | 4
2017-11-15T23:47:13.590 | 5
2017-11-16T00:02:13.590 | 6
2017-11-16T00:17:13.590 | 7
2017-11-16T00:32:13.590 | 8
2017-11-16T00:47:13.590 | 9
2017-11-16T01:02:13.590 | 10
2017-11-16T01:17:13.590 | 11
2017-11-16T01:32:13.590 | 12
2017-11-16T01:47:13.590 | 13
2017-11-16T02:02:13.590 | 14
2017-11-16T02:17:13.590 | 15
2017-11-16T02:32:13.590 | 16
2017-11-16T02:47:13.590 | 17
2017-11-16T03:02:13.590 | 18
2017-11-16T03:17:13.590 | 19
2017-11-16T03:32:13.590 | 20
2017-11-16T03:47:13.590 | 21
2017-11-16T04:02:13.590 | 22
2017-11-16T04:17:13.590 | 23
2017-11-16T04:32:13.590 | 24
2017-11-16T04:47:13.590 | 25
2017-11-16T05:02:13.590 | 26
2017-11-16T05:17:13.590 | 27
2017-11-16T05:32:13.590 | 28
2017-11-16T05:47:13.590 | 29
</code>```

And the values ArrayList contains:

```<code>[0, 4, 8, 12, 16, 20, 24, 28]
</code>```

If you don't have Strings or whatnot you can also make conversions from TimeStamp to LocalDateTime.

Body:
I'm working on a java program that reads from a database that is keeping various measurements of a lake minute by minute.  I need to write a query that will list each variables by most recent time then skip 1 full hour and display the record at that new time, and repeat that process so I can retrieve the values hourly for the last 48 hours and store them as an array on the java side. The biggest thing is it needs to be real time.  (The DB records 3120 records each hour)

StreamID is that of the sensor, MeasurementID is given to a single measurement, MeasurementValue is the what the sensor returns, and MeasurementTime is using the datetime data type YYYY-MM-DD HH:MM:SS of the measurement

my current select statement is below, I will mostly likely have to do separate statements for each variable but if I can avoid that I would like to.

SELECT StreamID,MeasurementID,MeasurementValue,MeasurementTime

  FROM measurements

  WHERE StreamID IN (26,27,28,29,30,31,32,33,34,35,14,36,37,38,39,40,
   41,42,43,44,45,46,47,48,49,50,18,13,11,12)

  ORDER BY MeasurementTime DESC, StreamID;

Here I have my reading of the db using result set, I'm not sure how to do multiple queries in a row to ignore "&&result2.next()"

 while(result.next())//&&result2.next()

 System.out.println(result.getString(1)+"\t"+result.getString(2)
 +"\t"+result.getString(3)+"\t"+result.getString(4)
 +"/t"+result.getString(5)+"\n";

con.close();

Body:
I'm not sure I understand exactly what you need to get from the db, but to execute a query hourly you can use a ScheduledExecutorService.

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    Runnable task = () -> {
        // Run query
    };
    executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.HOURS);

This will create a new thread that runs the run() method at a fixed rate. The rate is specified by scheduleAtFixedRate(task to run, initial delay (before the first time you run it), delay (between every time you run it), unit).

For the query you can try using a PreparedStatement so that you can just update the parameters instead of making a new query, thought I'm not completely sure what you want to do on that part, how do you know what IDs to look for?

EDIT:
As I understand it, you're trying to get records hourly instead of every minute? The new Date and Time API has some pretty nifty tricks that can help you.

Here's a quick mockup I ran earlier:

String sql = "SELECT * FROM measurements ORDER BY Time";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet result = ps.executeQuery();
ArrayList<Integer> values = new ArrayList<>(); // This is where I store the values I want to keep, you can do it w/e way you want
LocalDateTime ldt1;
LocalDateTime ldt2;
// Take the earliest time
result.next(); // You might want to put that in an if() or catch Exceptions
ldt1 = LocalDateTime.parse(result.getString("Date"));
values.add(result.getInt("Value"));
// Increment throught the values until you find one with more than an hour difference with the first one, keep it and change that first one to this new one to continue
while (result.next()) {
    ldt2 = LocalDateTime.parse(result.getString("Date"));
    if (Duration.between(ldt1, ldt2).getSeconds() >= 60*60) {
        values.add(result.getInt("Value"));
        ldt1 = ldt2;
    }
}
System.out.println("values:\n");
System.out.println(values);

My simplified db has theses values:

Date                    | Value
2017-11-15T22:32:13.590 | 0
2017-11-15T22:47:13.590 | 1
2017-11-15T23:02:13.590 | 2
2017-11-15T23:17:13.590 | 3
2017-11-15T23:32:13.590 | 4
2017-11-15T23:47:13.590 | 5
2017-11-16T00:02:13.590 | 6
2017-11-16T00:17:13.590 | 7
2017-11-16T00:32:13.590 | 8
2017-11-16T00:47:13.590 | 9
2017-11-16T01:02:13.590 | 10
2017-11-16T01:17:13.590 | 11
2017-11-16T01:32:13.590 | 12
2017-11-16T01:47:13.590 | 13
2017-11-16T02:02:13.590 | 14
2017-11-16T02:17:13.590 | 15
2017-11-16T02:32:13.590 | 16
2017-11-16T02:47:13.590 | 17
2017-11-16T03:02:13.590 | 18
2017-11-16T03:17:13.590 | 19
2017-11-16T03:32:13.590 | 20
2017-11-16T03:47:13.590 | 21
2017-11-16T04:02:13.590 | 22
2017-11-16T04:17:13.590 | 23
2017-11-16T04:32:13.590 | 24
2017-11-16T04:47:13.590 | 25
2017-11-16T05:02:13.590 | 26
2017-11-16T05:17:13.590 | 27
2017-11-16T05:32:13.590 | 28
2017-11-16T05:47:13.590 | 29

And the values ArrayList contains:

[0, 4, 8, 12, 16, 20, 24, 28]

If you don't have Strings or whatnot you can also make conversions from TimeStamp to LocalDateTime.


问:
Basic auth in rails
```<code>class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :authenticate_user!, :except => [:index]
  before_action :authenticate, :except => [:index]

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      basic_auth=User.find_by_email(username)
      if basic_auth.valid_password?(password)
        sign_in :user, basic_auth
        render :json => {:email => current_user.email, :id => current_user.id, :message => "hai ruby"}
      else
        render plain: "Unauthorized access"
      end
    end
  end
end
</code>```

I am trying to implement basic authorization in my sample application.When i give correct credentials values as in the user database. It gives json response.when the username and password goes wrong it throws error as "undefined method `valid_password?' for nil:NilClass"

答:
Just change if condition to this:

if basic_auth && basic_auth.valid_password?(password)

This will work because before checking for valid password, you must check whether a user even exists with given email id or not. Otherwise, basic_auth object will be nil and valid_password method on nil object will throw error.

Title: Basic auth in rails

Body:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :authenticate_user!, :except => [:index]
  before_action :authenticate, :except => [:index]

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      basic_auth=User.find_by_email(username)
      if basic_auth.valid_password?(password)
        sign_in :user, basic_auth
        render :json => {:email => current_user.email, :id => current_user.id, :message => "hai ruby"}
      else
        render plain: "Unauthorized access"
      end
    end
  end
end

I am trying to implement basic authorization in my sample application.When i give correct credentials values as in the user database. It gives json response.when the username and password goes wrong it throws error as "undefined method `valid_password?' for nil:NilClass"


问:
Upgrade to Spring Boot 1.3 causes java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableBeanFactory.getSingletonMutex()
Running the test, the stack trace is entirely in the Spring framework and jUnit:

```<code>java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableBeanFactory.getSingletonMutex()Ljava/lang/Object;
    at org.springframework.context.event.AbstractApplicationEventMulticaster.setBeanFactory(AbstractApplicationEventMulticaster.java:86)
    at org.springframework.boot.context.event.EventPublishingRunListener.registerApplicationEventMulticaster(EventPublishingRunListener.java:81)
    at org.springframework.boot.context.event.EventPublishingRunListener.contextPrepared(EventPublishingRunListener.java:71)
    at org.springframework.boot.SpringApplicationRunListeners.contextPrepared(SpringApplicationRunListeners.java:60)
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:329)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:295)
    at org.springframework.boot.test.SpringApplicationContextLoader.loadContext(SpringApplicationContextLoader.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
</code>```

The test class is pretty simple:

```<code>package com.uss.identity.dao;

import com.uss.identity.TestApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import static org.junit.Assert.assertNull;

@SuppressWarnings("SpringJavaAutowiredMembersInspection")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestApplication.class})
@EnableTransactionManagement
@ActiveProfiles("test-flyway")
public class ClientRepoTest2 {

    @Autowired
    ClientRepository dao;

    @Test
    public void testFindNone() throws Exception {
        assertNull(dao.findOne("nonesuch"));
    }

}
</code>```

And the referenced TestApplication class is just:

```<code>package com.uss.identity;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Profile;

@SpringBootApplication
@Profile({"test", "test-flyway"})
public class TestApplication {

}
</code>```

This worked fine when using Spring Boot 1.2.8.RELEASE.  But trying to upgrade to 1.3.0.RELEASE causes the above exception.

答:
In my case the culprit was activemq-all.jar which was bundling old spring classes.
Found that out with -verbose:class flag.

[Loaded org.springframework.beans.factory.access.BeanFactoryLocator from file:/C:/XXX/activemq-all-5.11.3.jar]
[Loaded org.springframework.beans.factory.access.SingletonBeanFactoryLocator from file:/C:/XXX/activemq-all-5.11.3.jar]
[Loaded org.springframework.context.access.ContextSingletonBeanFactoryLocator from file:/C:/XXX/activemq-all-5.11.3.jar]

Body:
Running the test, the stack trace is entirely in the Spring framework and jUnit:

java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableBeanFactory.getSingletonMutex()Ljava/lang/Object;
    at org.springframework.context.event.AbstractApplicationEventMulticaster.setBeanFactory(AbstractApplicationEventMulticaster.java:86)
    at org.springframework.boot.context.event.EventPublishingRunListener.registerApplicationEventMulticaster(EventPublishingRunListener.java:81)
    at org.springframework.boot.context.event.EventPublishingRunListener.contextPrepared(EventPublishingRunListener.java:71)
    at org.springframework.boot.SpringApplicationRunListeners.contextPrepared(SpringApplicationRunListeners.java:60)
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:329)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:295)
    at org.springframework.boot.test.SpringApplicationContextLoader.loadContext(SpringApplicationContextLoader.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

The test class is pretty simple:

package com.uss.identity.dao;

import com.uss.identity.TestApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import static org.junit.Assert.assertNull;

@SuppressWarnings("SpringJavaAutowiredMembersInspection")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestApplication.class})
@EnableTransactionManagement
@ActiveProfiles("test-flyway")
public class ClientRepoTest2 {

    @Autowired
    ClientRepository dao;

    @Test
    public void testFindNone() throws Exception {
        assertNull(dao.findOne("nonesuch"));
    }

}

And the referenced TestApplication class is just:

package com.uss.identity;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Profile;

@SpringBootApplication
@Profile({"test", "test-flyway"})
public class TestApplication {

}

This worked fine when using Spring Boot 1.2.8.RELEASE.  But trying to upgrade to 1.3.0.RELEASE causes the above exception.


问:
variables showing as undefined in firebug when they are defined
here is my site http://iadprint.com/products?product=Business%20Card

when i select a value for quantity a price is supposed to show in the pricing div on the top right.
this used to work but for some reason today in firebug under dom i can see that a few variables show undefined. when i do the ajax call  iadprint.com/ajax.php?id=1 the data shows correctly and the variables in the js are all defined. what can be wrong? here are the variables that i am seeing undefined.

```<code>woCoating_price
woColor_price
woDesign_price
woJob_Name_price
woPDF_Proof_price
woQuantity_price
woRound_Corners_price
woTurnaround_price
</code>```

答:
I replaced your $.get() call with a full $.ajax() call that includes an error: callback.

The result is that you're getting a parse error because your JSON response is invalid.

```<code>"parsererror" "Invalid JSON: {"price":"15.00"}<br/>"
</code>```

You need to get rid of that
 tag.

If this isn't it, then you'll need to provide specific detail on how to reproduce the problem, and in which part of your code you expect to see a defined value.

EDIT: Here's the change handler I used after removing yours:

```<code>$("#Quantity").change(function () {
    hash = $("#Quantity").val();
    console.log('hash',hash);

    $.ajax({
        url:"ajax.php",
        data: { id: hash },
        dataType:'json',
        success:function (out,b,c) {
            woQuantity_price = out.price;
            displayPrice();
            console.log(out,woQuantity_price,b,c);
        },
        error:function(a,b,c){
            console.log('error:',a,b,c);
        }
    });
});
</code>```

Body:
here is my site http://iadprint.com/products?product=Business%20Card

when i select a value for quantity a price is supposed to show in the pricing div on the top right.
this used to work but for some reason today in firebug under dom i can see that a few variables show undefined. when i do the ajax call  iadprint.com/ajax.php?id=1 the data shows correctly and the variables in the js are all defined. what can be wrong? here are the variables that i am seeing undefined.

woCoating_price
woColor_price
woDesign_price
woJob_Name_price
woPDF_Proof_price
woQuantity_price
woRound_Corners_price
woTurnaround_price

Body:
I replaced your $.get() call with a full $.ajax() call that includes an error: callback.

The result is that you're getting a parse error because your JSON response is invalid.

"parsererror" "Invalid JSON: {"price":"15.00"}<br/>"

You need to get rid of that <br/> tag.

If this isn't it, then you'll need to provide specific detail on how to reproduce the problem, and in which part of your code you expect to see a defined value.

EDIT: Here's the change handler I used after removing yours:

$("#Quantity").change(function () {
    hash = $("#Quantity").val();
    console.log('hash',hash);

    $.ajax({
        url:"ajax.php",
        data: { id: hash },
        dataType:'json',
        success:function (out,b,c) {
            woQuantity_price = out.price;
            displayPrice();
            console.log(out,woQuantity_price,b,c);
        },
        error:function(a,b,c){
            console.log('error:',a,b,c);
        }
    });
});