问:
Implementing infinite scroll in Bootstrap modal?
I'm trying to implement infinite scroll in a Bootstrap modal. I've tried several infinite scroll libraries but none of them have worked within a modal.

Here's what my code looks like right now.

When the modal is opened, jQuery listens for the event and requests data from the server:

```<code>$(document).on('show.bs.modal', '#modal', function(event)
{
    var modal = $(this);
    var modalBody = modal.find('.modal-body');

    $.ajax({
        url: '/messages',
        type: 'post',
        dataType: 'json'
        success: function(data)
        {
            // Append the rendered view to the modal body
            modalBody.append(data.data.view);
        }
    });
});
</code>```

Here is the getData() method it retrieves the messages from:

```<code>public function getData()
{
    $messages = Message::paginate(10);

    return response()->json([
        'success' => true,
        'data' => [
            'view' => view('layouts.messages', ['messages' => $messages])->render()
        ]
    ], 200);
}
</code>```

Here is my layouts.messages blade file:

```<code><div class="messages-container">
    @foreach ($messages as $message)
        <div class="message">{{ $message->text }}</div>
    @endforeach
</div>

{{ $messages->links() }}
</code>```

In the end, the modal looks like this:

```<code><div class="modal fade" id="modal" tabindex="-1">
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="modal-body">
            <div class="messages-container">
                @foreach ($messages as $message)
                    <div class="message">{{ $message->text }}</div>
                @endforeach
            </div>

            {{ $messages->links() }}
         </div>
      </div>
   </div>
</div>
</code>```

As you can see, I need to append more data to the .content-container on each load.

From here, how can I implement infinite scrolling the modal so that if the user scrolls down to the bottom of the modal, it loads the next page from the server and appends it to the modal body?

答:
A quick google search resulted in: http://jscroll.com/

It specifically mentions the ability to load data via Ajax.

Body:
I'm trying to implement infinite scroll in a Bootstrap modal. I've tried several infinite scroll libraries but none of them have worked within a modal.

Here's what my code looks like right now.

When the modal is opened, jQuery listens for the event and requests data from the server:

$(document).on('show.bs.modal', '#modal', function(event)
{
    var modal = $(this);
    var modalBody = modal.find('.modal-body');

    $.ajax({
        url: '/messages',
        type: 'post',
        dataType: 'json'
        success: function(data)
        {
            // Append the rendered view to the modal body
            modalBody.append(data.data.view);
        }
    });
});

Here is the getData() method it retrieves the messages from:

public function getData()
{
    $messages = Message::paginate(10);

    return response()->json([
        'success' => true,
        'data' => [
            'view' => view('layouts.messages', ['messages' => $messages])->render()
        ]
    ], 200);
}

Here is my layouts.messages blade file:

    @foreach ($messages as $message)

{{ $message->text }}

    @endforeach

{{ $messages->links() }}

In the end, the modal looks like this:

                @foreach ($messages as $message)

{{ $message->text }}

                @endforeach

            {{ $messages->links() }}

As you can see, I need to append more data to the .content-container on each load.

From here, how can I implement infinite scrolling the modal so that if the user scrolls down to the bottom of the modal, it loads the next page from the server and appends it to the modal body?


来源: stackexchange

问:
I am trying to use jasonp using javascript to display the data in it
i've been trying to get data from the following url but without any success. The following is the html code that i have got so far. I'm not sure why it is not working, could someone explain to me please.
</p>

```<code><html>
    <button >
        <h1 id="head">`Top News #1`</h1>
    </button>
    <script>
        function processJSON(text)
        {
            document.getElementById("head").innerHTML = text[0].news_title;
        };
    </script>
    <script src='http://apps3.mcot.net/mcot_script/mcot_news_programs_all_in_cat.php?jsoncallback=processJSON'>
    </script>
</html>
</code>```

答:
I think you need to parse it to json, try this:</p>

```<code>var data= JSON.parse(text);
document.getElementById("head").innerHTML = data[0].news_title;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i've been trying to get data from the following url but without any success. The following is the html code that i have got so far. I'm not sure why it is not working, could someone explain to me please.

    <button >

`Top News #1`

    </button>

Body:
I think you need to parse it to json, try this:

var data= JSON.parse(text);
document.getElementById("head").innerHTML = data[0].news_title;


问:
Call javascript function through url on otherpage while Redirecting
I need to call a javascript function in index.php when I redirect to index.php from another page with some URL queries.

Here is my actual url: index.php?id=10&func=view. I need to wake up a javascript function which is in index.php with this URL.

答:
You can set a session variable in your php code

$_SESSION["jsload"] = "1";

And then check if the variable is set in the index.php

```<code><?php
        if ( isset($_SESSION['jsload'])=="1" ) { ?>
        //javascript here
        <?php
        }
?>
</code>```

Make sure you use session_start() function on both pages

And unset and destroy the session once used

Body:
You can set a session variable in your php code

$_SESSION["jsload"] = "1";

And then check if the variable is set in the index.php

<?php
        if ( isset($_SESSION['jsload'])=="1" ) { ?>
        //javascript here
        <?php
        }
?>

Make sure you use session_start() function on both pages

And unset and destroy the session once used


问:
Replace Object Fields
I have an object that looks like this:

PetForm

```<code>{
name:"Bobo",
type:"Golden Retriever",
food:null,
toys:null,
....
}
</code>```

I want to replace the fields with the values of null to an empty string like this:

Result:

```<code>{
name:"Bobo",
type:"Golden Retriever",
food:"",
toys:"",
....
}
</code>```

I did the following:

```<code>Object.keys(PetForm).forEach((key) => (PetForm[key] === null) && PetForm[key] == "");
</code>```

Am I missing something in this method?

答:
var obj = {
name:"Bobo",
type:"Golden Retriever",
food:null,
toys:null
};

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    (obj[key] === null) && (obj[key] = '');
  }
}

console.log(obj);```

Title: Replace Object Fields

Body:
I have an object that looks like this:

PetForm

{
name:"Bobo",
type:"Golden Retriever",
food:null,
toys:null,
....
}

I want to replace the fields with the values of null to an empty string like this:

Result:

{
name:"Bobo",
type:"Golden Retriever",
food:"",
toys:"",
....
}

I did the following:

Object.keys(PetForm).forEach((key) => (PetForm[key] === null) && PetForm[key] == "");

Am I missing something in this method?


问:
Post request with jQuery and Laravel framework
I need to receive data from jQuery post request, think there is some error with routs or controller, here is my post request javascript code:

```<code>$.post('http://localhost:8000/ajax',
                {

                    task: "comment_insert",
                    userID: _userID,
                    comment: _comment,
                    name: _name,
                    userName: _userName
                }

                ).error(
                    function(data)
                    {
                      alert("Error: "+ data);
                    }
                 )
                .success(
                    function( data )
                    {
                        comment_insert(jQuery.parseJSON( data ));
                      console.log("RESPOND TEXT:" + data);

                    }
                 );

     }
</code>```

Also here is my routes for Laravel framework:

```<code>Route::post('ajax', 'AjaxController@index');
</code>```

Controller:

```<code>class AjaxController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function index()
    {
             return view('ajax.ajax');

    }
}
</code>```

my ajax.php script is into /resource/views/ajax/ajax.php
Also if I put script into /public/ajax/ajax.php all works fine....I use Laravel 5... Please help

EDIT:

I found what is problem but don't know how to solve.

When I disable csrf protection from: kernel.php code work anyone know how to make code work with csrf protection enabled?

答:
Is a simple code with javascript to send methods GET,POST,PUT,DELETE

declare header:  <meta name="csrf-token" content="{{ Session::token() }}">

```<code>  function addCarrito(Urldir,paramt)
        {

        $(function(){
         $.post(Urldir,{ _token: $('meta[name=csrf-token]').attr('content'), _method : 'PUT', data :  }, function(response){

               if(response != '')
                {
                 console.log('good');
                }

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

Body:
I need to receive data from jQuery post request, think there is some error with routs or controller, here is my post request javascript code:

$.post('http://localhost:8000/ajax',
                {

                    task: "comment_insert",
                    userID: _userID,
                    comment: _comment,
                    name: _name,
                    userName: _userName
                }

                ).error(
                    function(data)
                    {
                      alert("Error: "+ data);
                    }
                 )
                .success(
                    function( data )
                    {
                        comment_insert(jQuery.parseJSON( data ));
                      console.log("RESPOND TEXT:" + data);

                    }
                 );

     }

Also here is my routes for Laravel framework:

Route::post('ajax', 'AjaxController@index');

Controller:

class AjaxController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function index()
    {
             return view('ajax.ajax');

    }
}

my ajax.php script is into /resource/views/ajax/ajax.php
Also if I put script into /public/ajax/ajax.php all works fine....I use Laravel 5... Please help

EDIT:

I found what is problem but don't know how to solve.

When I disable csrf protection from: kernel.php code work anyone know how to make code work with csrf protection enabled?

Body:
Is a simple code with javascript to send methods GET,POST,PUT,DELETE

declare header:  <meta name="csrf-token" content="{{ Session::token() }}">

  function addCarrito(Urldir,paramt)
        {

        $(function(){
         $.post(Urldir,{ _token: $('meta[name=csrf-token]').attr('content'), _method : 'PUT', data :  }, function(response){

               if(response != '')
                {
                 console.log('good');
                }

            });
        });
    }


问:
Iterate through a List of Strings starting from 'One' String until 'Another' String in Java
I'm trying to iterate through a List of Strings in Java.
My List consists of:

```<code>["DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux","DataFileDownload/FD/722066/71493/2016/12/31/untitled-2.aux","DataFileDownload/FD/722066/71493/2017/01/01/untitled-3.aux","DataFileDownload/FD/722066/71493/2016/01/02/untitled-4.aux"]
</code>```

And I am reading the dates from the user as:

```<code>SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date fromDate = fmt.parse("2016-12-30");
Date toDate = fmt.parse("2017-01-02");
Calendar fromCal = Calendar.getInstance();
fromCal.setTime(fromDate);
String fromYear = String.valueOf(fromCal.get(Calendar.YEAR));
String fromMonth = String.valueOf(fromCal.get(Calendar.MONTH)+1);
String fromDay = String.valueOf(fromCal.get(Calendar.DAY_OF_MONTH));
Calendar toCal = Calendar.getInstance();
toCal.setTime(toDate);
String toYear = String.valueOf(toCal.get(Calendar.YEAR));
String toMonth = String.valueOf(toCal.get(Calendar.MONTH)+1);
String toDay = String.valueOf(toCal.get(Calendar.DAY_OF_MONTH));
</code>```

If I wanted to extract the Strings from date: 30-dec-2016 to 01-Jan-2017, i.e.

```<code>"DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux","DataFileDownload/FD/722066/71493/2016/12/31/untitled-2.aux","DataFileDownload/FD/722066/71493/2017/01/01/untitled-3.aux"
</code>```

I'm using the below loop:-

```<code>for(String s : NameList){
    if((s.equals(fromYear) && s.equals(fromMonth) && s.equals(fromDay)) == true){
  while((s.equals(toYear) && s.equals(toMonth) && s.equals(toDay)) != true){
     System.out.println(s);
  }
  System.out.println(s);
}
</code>```

I get no result.

But when I try this:

```<code>       for(String s : objectNameList){
           if((s.contains(fromYear) && s.contains(fromMonth) && s.contains(fromDay))){
               System.out.println(s);
           }
       }
</code>```

I get only:

```<code>"DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux"
</code>```

Can anyone please let me know how can I improve my loop condition?

Thanks in advance!

答:
Go string by string in your list and extract the date using regular expression, something like this:

```<code>private static String getDate(String str) {
    Pattern regex = Pattern.compile("\\.*(?<date>([0-9]{4}\\/[0-9]{2}\\/[0-9]{2}))");
    Matcher matcher = regex.matcher(str);
    boolean success = matcher.find();
    return (success ? matcher.group("date") : null);
}

// Example:
String dateStr = getDate("DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux");
</code>```

Save it as a Date object:

```<code>SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd");
Date date = fmt.parse(dateStr);
</code>```

Then, read the input dates from the user and save them as Date objects.

Then, you can compare the user dates and the dates from the list using:

```<code>java.util.Date.before(Date when);
java.util.Date.after(Date when);
</code>```

Much easier than parsing all the dates and playing with strings.

Body:
I'm trying to iterate through a List of Strings in Java.
My List consists of:

["DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux","DataFileDownload/FD/722066/71493/2016/12/31/untitled-2.aux","DataFileDownload/FD/722066/71493/2017/01/01/untitled-3.aux","DataFileDownload/FD/722066/71493/2016/01/02/untitled-4.aux"]

And I am reading the dates from the user as:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date fromDate = fmt.parse("2016-12-30");
Date toDate = fmt.parse("2017-01-02");
Calendar fromCal = Calendar.getInstance();
fromCal.setTime(fromDate);
String fromYear = String.valueOf(fromCal.get(Calendar.YEAR));
String fromMonth = String.valueOf(fromCal.get(Calendar.MONTH)+1);
String fromDay = String.valueOf(fromCal.get(Calendar.DAY_OF_MONTH));
Calendar toCal = Calendar.getInstance();
toCal.setTime(toDate);
String toYear = String.valueOf(toCal.get(Calendar.YEAR));
String toMonth = String.valueOf(toCal.get(Calendar.MONTH)+1);
String toDay = String.valueOf(toCal.get(Calendar.DAY_OF_MONTH));

If I wanted to extract the Strings from date: 30-dec-2016 to 01-Jan-2017, i.e.

"DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux","DataFileDownload/FD/722066/71493/2016/12/31/untitled-2.aux","DataFileDownload/FD/722066/71493/2017/01/01/untitled-3.aux"

I'm using the below loop:-

for(String s : NameList){
    if((s.equals(fromYear) && s.equals(fromMonth) && s.equals(fromDay)) == true){
  while((s.equals(toYear) && s.equals(toMonth) && s.equals(toDay)) != true){
     System.out.println(s);
  }
  System.out.println(s);
}

I get no result.

But when I try this:

       for(String s : objectNameList){
           if((s.contains(fromYear) && s.contains(fromMonth) && s.contains(fromDay))){
               System.out.println(s);
           }
       }

I get only:

"DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux"

Can anyone please let me know how can I improve my loop condition?

Thanks in advance!

Body:
Go string by string in your list and extract the date using regular expression, something like this:

private static String getDate(String str) {
    Pattern regex = Pattern.compile("\\.*(?<date>([0-9]{4}\\/[0-9]{2}\\/[0-9]{2}))");
    Matcher matcher = regex.matcher(str);
    boolean success = matcher.find();
    return (success ? matcher.group("date") : null);
}

// Example:
String dateStr = getDate("DataFileDownload/FD/722066/71493/2016/12/30/untitled-1.aux");

Save it as a Date object:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd");
Date date = fmt.parse(dateStr);

Then, read the input dates from the user and save them as Date objects.

Then, you can compare the user dates and the dates from the list using:

java.util.Date.before(Date when);
java.util.Date.after(Date when);

Much easier than parsing all the dates and playing with strings.


问:
Split svmfile matrix into 4 parts
I have two files which I divided into training and testing sets.

```<code>traindata = load_svmlight_file("training")
testdata = load_svmlight_file("testing")
Xtrain = traindata[0].todense()
ytrain = traindata[1]
Xtest = testdata[0].todense()
ytest = testdata[1]
</code>```

I would like to split my Xtest and ytest into 4 parts:

Xtest1, ytest1
Xtest2, ytest2,
Xtest3, ytest3,
Xtest4, ytest4

My instinct is to use sklearn.train_test_split but I'm not sure. What is the best way to do this?

答:
You can do that using np.array_split:

```<code>import numpy as np
test=np.arange(21)
xtest1,xtest2,xtest3,xtest4 = np.array_split(np.random.permutation(test),4)
</code>```

I used np.random.permutation in case you want the data to split randomly. If you just want to split it into consecutive parts, you can remove the np.random.permutation.

Title: Split svmfile matrix into 4 parts

Body:
I have two files which I divided into training and testing sets.

traindata = load_svmlight_file("training")
testdata = load_svmlight_file("testing")
Xtrain = traindata[0].todense()
ytrain = traindata[1]
Xtest = testdata[0].todense()
ytest = testdata[1]

I would like to split my Xtest and ytest into 4 parts:

Xtest1, ytest1
Xtest2, ytest2,
Xtest3, ytest3,
Xtest4, ytest4

My instinct is to use sklearn.train_test_split but I'm not sure. What is the best way to do this?

Body:
You can do that using np.array_split:

import numpy as np
test=np.arange(21)
xtest1,xtest2,xtest3,xtest4 = np.array_split(np.random.permutation(test),4)

I used np.random.permutation in case you want the data to split randomly. If you just want to split it into consecutive parts, you can remove the np.random.permutation.


问:
How to set a timeout with AFNetworking
My project is using AFNetworking.

https://github.com/AFNetworking/AFNetworking

How do I dial down the timeout? Atm with no internet connection the fail block isn't triggered for what feels like about 2 mins. Waay to long....

答:
There are two different meanings on the "timeout" definition here.

Timeout as in timeoutInterval

You want to drop a request when it becomes idle (no more transfer) for longer than an arbitrary interval of time. Example: you set timeoutInterval to 10 seconds, you start your request at 12:00:00, it may transfer some data until 12:00:23, then connection will timeout at 12:00:33. This case is covered by almost all answers here (including JosephH, Mostafa Abdellateef, Cornelius and Gurpartap Singh).

Timeout as in timeoutDeadline

You want to drop a request when it reaches a deadline happening arbitrary later. Example: you set deadline to 10 seconds in the future, you start your request at 12:00:00, it may attempt to transfer some data until 12:00:23, but connection will timeout earlier at 12:00:10. This case is covered by borisdiakur.

I'd like to show how to implement this deadline in Swift (3 and 4) for AFNetworking 3.1.

```<code>let sessionManager = AFHTTPSessionManager(baseURL: baseURL)
let request = sessionManager.post(endPoint, parameters: parameters, progress: { ... }, success: { ... }, failure: { ... })
// timeout deadline at 10 seconds in the future
DispatchQueue.global().asyncAfter(deadline: .now() + 10.0) {
    request?.cancel()
}
</code>```

And to give a testable example, this code should print "failure" instead of "success" because of the immediate timeout at 0.0 seconds in the future:

```<code>let sessionManager = AFHTTPSessionManager(baseURL: URL(string: "https://example.com"))
sessionManager.responseSerializer = AFHTTPResponseSerializer()
let request = sessionManager.get("/", parameters: nil, progress: nil, success: { _ in
    print("success")
}, failure: { _ in
    print("failure")
})
// timeout deadline at 0 seconds in the future
DispatchQueue.global().asyncAfter(deadline: .now() + 0.0) {
    request?.cancel()
}
</code>```

Title: How to set a timeout with AFNetworking

Body:
There are two different meanings on the "timeout" definition here.

Timeout as in timeoutInterval

You want to drop a request when it becomes idle (no more transfer) for longer than an arbitrary interval of time. Example: you set timeoutInterval to 10 seconds, you start your request at 12:00:00, it may transfer some data until 12:00:23, then connection will timeout at 12:00:33. This case is covered by almost all answers here (including JosephH, Mostafa Abdellateef, Cornelius and Gurpartap Singh).

Timeout as in timeoutDeadline

You want to drop a request when it reaches a deadline happening arbitrary later. Example: you set deadline to 10 seconds in the future, you start your request at 12:00:00, it may attempt to transfer some data until 12:00:23, but connection will timeout earlier at 12:00:10. This case is covered by borisdiakur.

I'd like to show how to implement this deadline in Swift (3 and 4) for AFNetworking 3.1.

let sessionManager = AFHTTPSessionManager(baseURL: baseURL)
let request = sessionManager.post(endPoint, parameters: parameters, progress: { ... }, success: { ... }, failure: { ... })
// timeout deadline at 10 seconds in the future
DispatchQueue.global().asyncAfter(deadline: .now() + 10.0) {
    request?.cancel()
}

And to give a testable example, this code should print "failure" instead of "success" because of the immediate timeout at 0.0 seconds in the future:

let sessionManager = AFHTTPSessionManager(baseURL: URL(string: "https://example.com"))
sessionManager.responseSerializer = AFHTTPResponseSerializer()
let request = sessionManager.get("/", parameters: nil, progress: nil, success: { _ in
    print("success")
}, failure: { _ in
    print("failure")
})
// timeout deadline at 0 seconds in the future
DispatchQueue.global().asyncAfter(deadline: .now() + 0.0) {
    request?.cancel()
}


问:
Angular 4 shows time part wrong in datetime
I have an input on my Angular component html like this:

```<code><input id="orderdate" class="form-control" value="{{order.OrderDate | date: 'd.M.yyyy H:mm:ss'}}" disabled />
</code>```

order.OrderDate has value 2017-06-01T10:52:03.666723, and I expect to see value in format

1.6.2017 10:52:03.

However, what I actually get is

1.6.2017 10:00:6/1/2017 10:52:03 AM:6/1/2017 10:52:03 AM

If I use only date (d.M.yyyy), it works correctly (1.6.2017). Why is the time part showing wrong?

答:
Thanks to comment by Thiagz, I found solution to this problem here: Angular2 date pipe does not work in IE 11 and edge 13/14.

This seems to be bug in IE and Edge, so I had to create my own pipe for date.

DatexPipe.ts:

```<code>import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
    name: 'datex'
})

export class DatexPipe implements PipeTransform {
    transform(value: any, format: string = ""): string {
        var momentDate = moment(value);

        if (!momentDate.isValid()) return value;

        return momentDate.format(format);
    }
}
</code>```

Use it like this:

```<code><input id="orderdate" class="form-control" value="{{order.OrderDate | datex: 'd.M.YYYY H:mm:ss'}}" disabled />
</code>```

Body:
I have an input on my Angular component html like this:

<input id="orderdate" class="form-control" value="{{order.OrderDate | date: 'd.M.yyyy H:mm:ss'}}" disabled />

order.OrderDate has value 2017-06-01T10:52:03.666723, and I expect to see value in format

1.6.2017 10:52:03.

However, what I actually get is

1.6.2017 10:00:6/1/2017 10:52:03 AM:6/1/2017 10:52:03 AM

If I use only date (d.M.yyyy), it works correctly (1.6.2017). Why is the time part showing wrong?

Body:
Thanks to comment by Thiagz, I found solution to this problem here: Angular2 date pipe does not work in IE 11 and edge 13/14.

This seems to be bug in IE and Edge, so I had to create my own pipe for date.

DatexPipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
    name: 'datex'
})

export class DatexPipe implements PipeTransform {
    transform(value: any, format: string = ""): string {
        var momentDate = moment(value);

        if (!momentDate.isValid()) return value;

        return momentDate.format(format);
    }
}

Use it like this:

<input id="orderdate" class="form-control" value="{{order.OrderDate | datex: 'd.M.YYYY H:mm:ss'}}" disabled />


问:
Why can't I remove these divs with jQuery?
I have dynamically created elements within a parent element of .output which are created within my on('click') function.

```<code>$(document).on("click", '#search', function() {
//Loop crime data array from api request above...
for(var i = 0; i < mapData.length; i++) {

  //Fill in crime data
  var fill = '<div class="row resu"><div class="col-xs-2 number"><h5>'+[i+1]+'</h5></div><div class="col-xs-10"><p class="text-primary">Type of crime: <span class="text-strong">'+mapData[i][0]+'</span></p><p class="text-primary">Location specifics: <span class="text-strong">'+mapData[i][1]+'</span></p></div></div>';

  //add to div
  $('.output').append(fill);
}
...
.......
</code>```

But nowhere outside the function am I able to target the new .resu rows for which I can apply .empty() or .remove(). Every time I hit the search button I wish to empty the output container div first.

If you go to my pen and hit the button, you will see some information regarding crime in that postcode's area. If you keep pressing it then multiple duplications of the same information will fill it up. How can I get rid of those with jquery?

My pen:
https://codepen.io/anon/pen/xrwXYy

答:
If you try to invoke 'getCords' asynchronously, you will find that the #output is actually be cleared before being replenished. So there must be something wrong with your getCords or getPolApi.

```<code>setTimeout(function(){
    getCords(postcode);
    getPolApi(year,month,lat,lng,mapData);
},3000);
</code>```

Body:
I have dynamically created elements within a parent element of .output which are created within my on('click') function.

$(document).on("click", '#search', function() {
//Loop crime data array from api request above...
for(var i = 0; i < mapData.length; i++) {

  //Fill in crime data
  var fill = '

'+[i+1]+'

Type of crime: '+mapData[i][0]+'

Location specifics: '+mapData[i][1]+'

';

  //add to div
  $('.output').append(fill);
}
...
.......

But nowhere outside the function am I able to target the new .resu rows for which I can apply .empty() or .remove(). Every time I hit the search button I wish to empty the output container div first.

If you go to my pen and hit the button, you will see some information regarding crime in that postcode's area. If you keep pressing it then multiple duplications of the same information will fill it up. How can I get rid of those with jquery?

My pen:
https://codepen.io/anon/pen/xrwXYy

Body:
If you try to invoke 'getCords' asynchronously, you will find that the #output is actually be cleared before being replenished. So there must be something wrong with your getCords or getPolApi.

setTimeout(function(){
    getCords(postcode);
    getPolApi(year,month,lat,lng,mapData);
},3000);


问:
MySQL: Make a blog-style page with different data types at different points
I'm trying to develop something similar to this with PHP and MySQL: http://a-bittersweet-life.tumblr.com/

I'd like to make a page that is mostly made up of words, but can be interspersed with images or embedded videos or other data types. I'm not sure exactly how to do this, but I have an idea:

```<code>id | entry_date |  text | image_link | vid_embed | sound_embed
 0 |   June 1st |  data |    null    |   null    |  null
 1 |   June 1st |  null |    data    |   null    |  null
 2 |   June 1st |  null |    data    |   null    |  null
 3 |   June 1st |  data |    null    |   null    |  null
 4 |   June 2nd |  data |    null    |   null    |  null
 5 |   June 2nd |  null |    null    |   data    |  null
 6 |   June 2nd |  data |    null    |   null    |  null
 7 |   June 2nd |  null |    data    |   null    |  null
 8 |   June 2nd |  null |    data    |   null    |  null
 ....
 ....
 ....
</code>```

So, for each blog entry, the Date is displayed first, followed by the order in which data was put into the SQL table (ordered by id):

June 1st

Text

Image

Image

Text

June 2nd

Text

Video

Text

Image

Image

Is there another way to do this, or does this seem like a fairly practical way to do it?

答:
Seems like the easy way to do this is to get all the rows and then iterate through them and use an if statement to determine the type.

```<code>$sql = "SELECT * FROM Schema.Table WHERE CAST(entry_date AS DATE) BETWEEN '06/01/2017' AND '06/02/2017' ORDER BY id";
/* Query your database however you might do */

$lastDay = null;
while ($row in $sqlResult->fetch_row()) {
    if ($row->entry_date != $lastDay) {
        $lastDay = $row->entry_date;
        echo $row->entry_date;
    }
    if ($row->text != null) {
        echo $row->text;
    } else if ($row->vid_embed != null) {
        echo '<videoplayer src="' + $row->vid_embed + '">';
    } else if ($row->image_link != null) {
        echo '<img src="' + $row->image_link + '">';
    } else if ($row->sound_embed!= null) {
        echo '<soundplayer src="' + $row->sound_embed+ '">';
    }
}
</code>```

This is a bit psuedo-code-ish, but the methodology should work without issue.

Body:
I'm trying to develop something similar to this with PHP and MySQL: http://a-bittersweet-life.tumblr.com/

I'd like to make a page that is mostly made up of words, but can be interspersed with images or embedded videos or other data types. I'm not sure exactly how to do this, but I have an idea:

id | entry_date |  text | image_link | vid_embed | sound_embed
 0 |   June 1st |  data |    null    |   null    |  null
 1 |   June 1st |  null |    data    |   null    |  null
 2 |   June 1st |  null |    data    |   null    |  null
 3 |   June 1st |  data |    null    |   null    |  null
 4 |   June 2nd |  data |    null    |   null    |  null
 5 |   June 2nd |  null |    null    |   data    |  null
 6 |   June 2nd |  data |    null    |   null    |  null
 7 |   June 2nd |  null |    data    |   null    |  null
 8 |   June 2nd |  null |    data    |   null    |  null
 ....
 ....
 ....

So, for each blog entry, the Date is displayed first, followed by the order in which data was put into the SQL table (ordered by id):

June 1st

Text

Image

Image

Text

June 2nd

Text

Video

Text

Image

Image

Is there another way to do this, or does this seem like a fairly practical way to do it?

Body:
Seems like the easy way to do this is to get all the rows and then iterate through them and use an if statement to determine the type.

$sql = "SELECT * FROM Schema.Table WHERE CAST(entry_date AS DATE) BETWEEN '06/01/2017' AND '06/02/2017' ORDER BY id";
/* Query your database however you might do */

$lastDay = null;
while ($row in $sqlResult->fetch_row()) {
    if ($row->entry_date != $lastDay) {
        $lastDay = $row->entry_date;
        echo $row->entry_date;
    }
    if ($row->text != null) {
        echo $row->text;
    } else if ($row->vid_embed != null) {
        echo '<videoplayer src="' + $row->vid_embed + '">';
    } else if ($row->image_link != null) {
        echo '<img src="' + $row->image_link + '">';
    } else if ($row->sound_embed!= null) {
        echo '<soundplayer src="' + $row->sound_embed+ '">';
    }
}

This is a bit psuedo-code-ish, but the methodology should work without issue.


问:
Cancel file download from another thread at any time
I'm using HttpURLConnection to download a file. Can I cancel the download from another thread? If not, what method for file download should I use?</p>

答: You can read the data chunk by chunk (normally you should do that way) and check a boolean flag which is set to true (indicates stop) from another thread (consider using volatile). Here the problem may be if reading chunk takes too long and it will wait for the chunk to be read before checking the flag. I'm not sure that closing the connection from another thread is a good idea (no info sources though). But if you do this, you can use a flag to distinguish real connection failures from stopping.

ContentLicense: CC BY-SA 2.5


问:
static_cast vs GetBuffer(0) in casting CString to an LPCWSTR pointer
There are two ways to convert a CString to an LPCWSTR pointer. Usually, I use the static_cast method. But recently I have realized GetBuffer() can be used with the argument 0. So I think GetBuffer() is good for more clean code, because static_cast has an ugly syntax though it looks more C++.

What are the pros and cons of each way, and what should I use in C++?

```<code>#include <atlstr.h>

int main() {
    CString aCString = CString(_T("A string"));
    _tprintf(_T("%s"), aCString.GetBuffer(0)); //methond -1
    _tprintf(_T("%s"), static_cast<LPCWSTR>(aCString)); //methond -2
}
</code>```

答:
There is no essential difference between the 2 forms.
When running, the GetBuffer() method should return some internal buffer, while the static_cast should invoke the convert operator like below.

```<code>operator char* () {return _internalBuffer;}
</code>```

it's personal preference which one you like to use.

Body:
There are two ways to convert a CString to an LPCWSTR pointer. Usually, I use the static_cast method. But recently I have realized GetBuffer() can be used with the argument 0. So I think GetBuffer() is good for more clean code, because static_cast has an ugly syntax though it looks more C++.

What are the pros and cons of each way, and what should I use in C++?

#include <atlstr.h>

int main() {
    CString aCString = CString(_T("A string"));
    _tprintf(_T("%s"), aCString.GetBuffer(0)); //methond -1
    _tprintf(_T("%s"), static_cast<LPCWSTR>(aCString)); //methond -2
}

Body:
There is no essential difference between the 2 forms.
When running, the GetBuffer() method should return some internal buffer, while the static_cast should invoke the convert operator like below.

operator char* () {return _internalBuffer;}

it's personal preference which one you like to use.


问:
While speedily clicking on item of gridview, same method has been called twice a time
I have used grid view in my project. When I click on grid view item speedily, it calls the same method twice a time. But I slowly click, then it works perfectly.

In method below I call the dialog box. When I click the item it opens the dialog box but when I speedily click the item then dialog box open two times. What should I do to solve this?

```<code>grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
        showDialog(position);
    }
});
</code>```

答:
I have solution for opening twice time method. I can define the below condition through solved it:</p>
```<code>grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    private long mLastClickTime = 0;

    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) return;

        mLastClickTime = SystemClock.elapsedRealtime();
        grideProductAdd(position);
    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have used grid view in my project. When I click on grid view item speedily, it calls the same method twice a time. But I slowly click, then it works perfectly.

In method below I call the dialog box. When I click the item it opens the dialog box but when I speedily click the item then dialog box open two times. What should I do to solve this?

grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
        showDialog(position);
    }
});

Body:
I have solution for opening twice time method. I can define the below condition through solved it:

grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    private long mLastClickTime = 0;

    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) return;

        mLastClickTime = SystemClock.elapsedRealtime();
        grideProductAdd(position);
    }
});


问:
After successful login page not found 404 encountered, when setting 'pageNotFound_handling' TYPO3 7.6 version
If my successful login redirected url is like

domain.com/abc/xyz

where
abc = my page name

xyz = my action name of my custom extension

404 = 404 page name

When I set 404 page as below;

```<code>$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] =  404
</code>```

Then after successful login its redirected to 404 error page, it should redirect as earlier ie. domain.com/abc/xyz not 404 page

答:
It's redirects to 404 page, because may be your url domain.com/abc/xyz is not found on your domain.

You can select After Successful Login Redirect to Page option in login form plugin with page abc and your custom extension plugin is used on this page(abc).

Body:
If my successful login redirected url is like

domain.com/abc/xyz

where
abc = my page name

xyz = my action name of my custom extension

404 = 404 page name

When I set 404 page as below;

$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] =  404

Then after successful login its redirected to 404 error page, it should redirect as earlier ie. domain.com/abc/xyz not 404 page


问:
How to get C++-template-like behavior but only allow two specific types to be instantiated?
I'm trying to get a specific type of behavior from an inline C++ function, and I'm not sure if there's a way to do it or not.

I want my function to accept either a signed or an unsigned 16-bit value as an argument, perform an operation on that value, and then return a value of that same type.  If the argument's signed/unsigned-ness is ambiguous (e.g. because it's a constant), then it's okay for the compiler to just pick the signed version.  Here's a toy program showing my first attempt at getting that behavior:

```<code> #include <iostream>
 #include <cstdint>

  int16_t getValuePlusOne( int16_t x) {return x+1;}
 uint16_t getValuePlusOne(uint16_t x) {return x+1;}

 using namespace std;

 int main(int, char **)
 {
     int16_t   signedVal = -15;
    uint16_t unsignedVal = 23;

    cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
    cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
    cout << getValuePlusOne(1234)        << endl;  // COMPILE ERROR, ambiguous!  D'oh!
    return 0;
 }
</code>```

So that almost worked, but it errors out on the getValuePlusOne(1234) since 1234 is ambiguous (it could be signed or unsigned).  Fair enough, but I'd like it not to do that.

So here's my second attempt:

```<code>#include <iostream>
#include <cstdint>

template <typename T> T getValuePlusOne(T val) {return val+1;}

using namespace std;

int main(int, char **)
{
    int16_t   signedVal = 5;
   uint16_t unsignedVal = 5;

   cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
   cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
   cout << getValuePlusOne(1234)        << endl;  // works, yay!

   uint32_t inappropriateType32 = 54321;
   cout << getValuePlusOne(inappropriateType32) << endl;  // works, but I want this to be a compile-time error!  D'oh!

   float inappropriateTypeFloat = 666.0;
   cout << getValuePlusOne(inappropriateTypeFloat) << endl;  // works, but I want this to be a compile-time error!

   return 0;
}
</code>```

This version works just how I want it to work for the first three calls to getValuePlusOne() -- they compile without errors and the template mechanism makes sure that getValuePlusOne()'s return type matches its argument type, and chooses a default argument/return type in the ambiguous case.  Yay!

But -- this version also allows the user to pass in inappropriate values (e.g. 32-bit integers, or even -- gasp -- floating point types) which don't make sense in the context of my application, so I want the compiler to flag those calls as compile-time errors, and that doesn't happen with this implementation.

Is there any way for me to have my cake and eat it too?

答:
What about something like this?

```<code>template <typename T> T getValuePlusOne(T val)
{
    static_assert(std::is_same<T, int16_t>::value || std::is_same<T, uint16_t>::value, "Incorrect type");
    return val+1;
}
</code>```

Still, getValuePlusOne(1234) fails. But it's not because the type is ambiguous. It's because T is int.

Body:
I'm trying to get a specific type of behavior from an inline C++ function, and I'm not sure if there's a way to do it or not.

I want my function to accept either a signed or an unsigned 16-bit value as an argument, perform an operation on that value, and then return a value of that same type.  If the argument's signed/unsigned-ness is ambiguous (e.g. because it's a constant), then it's okay for the compiler to just pick the signed version.  Here's a toy program showing my first attempt at getting that behavior:

 #include <iostream>
 #include <cstdint>

  int16_t getValuePlusOne( int16_t x) {return x+1;}
 uint16_t getValuePlusOne(uint16_t x) {return x+1;}

 using namespace std;

 int main(int, char **)
 {
     int16_t   signedVal = -15;
    uint16_t unsignedVal = 23;

    cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
    cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
    cout << getValuePlusOne(1234)        << endl;  // COMPILE ERROR, ambiguous!  D'oh!
    return 0;
 }

So that almost worked, but it errors out on the getValuePlusOne(1234) since 1234 is ambiguous (it could be signed or unsigned).  Fair enough, but I'd like it not to do that.

So here's my second attempt:

#include <iostream>
#include <cstdint>

template <typename T> T getValuePlusOne(T val) {return val+1;}

using namespace std;

int main(int, char **)
{
    int16_t   signedVal = 5;
   uint16_t unsignedVal = 5;

   cout << getValuePlusOne(  signedVal) << endl;  // works, yay!
   cout << getValuePlusOne(unsignedVal) << endl;  // works, yay!
   cout << getValuePlusOne(1234)        << endl;  // works, yay!

   uint32_t inappropriateType32 = 54321;
   cout << getValuePlusOne(inappropriateType32) << endl;  // works, but I want this to be a compile-time error!  D'oh!

   float inappropriateTypeFloat = 666.0;
   cout << getValuePlusOne(inappropriateTypeFloat) << endl;  // works, but I want this to be a compile-time error!

   return 0;
}

This version works just how I want it to work for the first three calls to getValuePlusOne() -- they compile without errors and the template mechanism makes sure that getValuePlusOne()'s return type matches its argument type, and chooses a default argument/return type in the ambiguous case.  Yay!

But -- this version also allows the user to pass in inappropriate values (e.g. 32-bit integers, or even -- gasp -- floating point types) which don't make sense in the context of my application, so I want the compiler to flag those calls as compile-time errors, and that doesn't happen with this implementation.

Is there any way for me to have my cake and eat it too?

Body:
What about something like this?

template <typename T> T getValuePlusOne(T val)
{
    static_assert(std::is_same<T, int16_t>::value || std::is_same<T, uint16_t>::value, "Incorrect type");
    return val+1;
}

Still, getValuePlusOne(1234) fails. But it's not because the type is ambiguous. It's because T is int.


问:
Nest XML soap response PHP
Ok I am at a brick wall... SO I am making a request successfully to a webservice in php, I can capture the response and using php.net am able to output the result/response in readable form

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetLoanDetailResponse xmlns="http://vendorsite.com/">
<GetLoanDetailResult><WEB><LOANDETAIL><acctrefno>31415</acctrefno><master_acctrefno>0</master_acctrefno><loan_number>TEST100001</loan_number><name>HILL ALAN</name><shortname>ALAN HILL</shortname><current_payoff_balance>14,358.83</current_payoff_balance><curr_date>07/14/2015</curr_date><curr_maturity_date>07/14/2021</curr_maturity_date><interest_accrued_thru_date>06/06/2017</interest_accrued_thru_date><current_note_amount>10,000.00</current_note_amount><current_principal_balance>10,000.00</current_principal_balance><current_interest_balance>4,358.83</current_interest_balance><current_fees_balance>0.00</current_fees_balance><current_late_charge_balance>0.00</current_late_charge_balance><current_perdiem>6.30</current_perdiem><current_interest_rate>23.00000</current_interest_rate><total_past_due_balance>5,651.05</total_past_due_balance><total_current_due_balance>5,651.05</total_current_due_balance><next_billing_date>06/18/2017</next_billing_date><days_past_due>662</days_past_due><current_pending>0</current_pending><current_impound_balance>0</current_impound_balance><last_payment_date>05/18/2017</last_payment_date><last_payment_amount>5</last_payment_amount><status_code>ACTIVE</status_code><loan_type>Term</loan_type><open_date>07/14/2015</open_date><last_activity_date>05/18/2017</last_activity_date><current_udf1_balance>0.00</current_udf1_balance><current_udf2_balance>0.00</current_udf2_balance><current_udf3_balance>0.00</current_udf3_balance><current_udf4_balance>0.00</current_udf4_balance><current_udf5_balance>0.00</current_udf5_balance><current_udf6_balance>0.00</current_udf6_balance><current_udf7_balance>0.00</current_udf7_balance><current_udf8_balance>0.00</current_udf8_balance><current_udf9_balance>0.00</current_udf9_balance><current_udf10_balance>0.00</current_udf10_balance><current_suspense_balance>0.00</current_suspense_balance><interest_method>SI</interest_method><term_char>Payments</term_char><term>72</term><term_due>72</term_due></LOANDETAIL></WEB></GetLoanDetailResult>
</GetLoanDetailResponse>
</soap:Body>
</soap:Envelope>
</code>```

which is done using: echo "RESPONSE:\n" . htmlentities(str_ireplace('><', ">\n<", $soapClient->__getLastResponse())) . "\n";

I have tried simplexml_load_string() will not read soap response with "soap:" in the tags

and

How to drill into SOAP Namespaces with SimpleXML & PHP

trying How to convert SOAP response to PHP Array? again

And EVERY thing I can find in stack overflow and on php.net / google. I keep seeing references to a bug https://bugs.php.net/bug.php?id=48966 which I am now attempting to use to solve this... I really dont want to use dom seems like there should be a php only way to read this response... it is strange that when I call $soapClient->__getLastResponse()) I get

```<code><WEB><LOANDETAIL><acctrefno>31415</acctrefno><master_acctrefno>0</master_acctrefno><loan_number>TEST100001</loan_number><name>Last Name F Name</name><shortname>Name</shortname><current_payoff_balance>14,358.83</current_payoff_balance><curr_date>07/14/2015</curr_date><curr_maturity_date>07/14/2021</curr_maturity_date><interest_accrued_thru_date>06/06/2017</interest_accrued_thru_date><current_note_amount>10,000.00</current_note_amount><current_principal_balance>10,000.00</current_principal_balance><current_interest_balance>4,358.83</current_interest_balance><current_fees_balance>0.00</current_fees_balance><current_late_charge_balance>0.00</current_late_charge_balance><current_perdiem>6.30</current_perdiem><current_interest_rate>23.00000</current_interest_rate><total_past_due_balance>5,651.05</total_past_due_balance><total_current_due_balance>5,651.05</total_current_due_balance><next_billing_date>06/18/2017</next_billing_date><days_past_due>662</days_past_due><current_pending>0</current_pending><current_impound_balance>0</current_impound_balance><last_payment_date>05/18/2017</last_payment_date><last_payment_amount>5</last_payment_amount><status_code>ACTIVE</status_code><loan_type>Term</loan_type><open_date>07/14/2015</open_date><last_activity_date>05/18/2017</last_activity_date><current_udf1_balance>0.00</current_udf1_balance><current_udf2_balance>0.00</current_udf2_balance><current_udf3_balance>0.00</current_udf3_balance><current_udf4_balance>0.00</current_udf4_balance><current_udf5_balance>0.00</current_udf5_balance><current_udf6_balance>0.00</current_udf6_balance><current_udf7_balance>0.00</current_udf7_balance><current_udf8_balance>0.00</current_udf8_balance><current_udf9_balance>0.00</current_udf9_balance><current_udf10_balance>0.00</current_udf10_balance><current_suspense_balance>0.00</current_suspense_balance><interest_method>SI</interest_method><term_char>Payments</term_char><term>72</term><term_due>72</term_due></LOANDETAIL></WEB>
</code>```

Which I havent been able to explode to an array...

Notice the GetLoanDetailResult when I try anything with jsonencode/decode I get a key with this value and a sting with the rest of the data in a non delimited string...

The end GOAL is to put this in an array so I can pull the values and use them to populate parameters for new variables.

Using php7.0 on ubuntu server

Code to interact with response after How to convert SOAP response to PHP Array?

```<code>$loanDetail = var_dump($loanUpdate);
         $response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $soapClient->__getLastResponse());
         $xml = new SimpleXMLElement($response);
         $body = $xml->xpath('//SBody');

         var_export($xml);
        echo "======================<br />";
         var_export($body);
         echo "======================<br />";

         $array = json_decode(json_encode((array)$body), TRUE);
         print_r($array);
</code>```

Returns

```<code>    object(stdClass)#3 (1) {
  ["NLSGetLoanDetailResult"]=>
  string(24) "7"
}
SimpleXMLElement::__set_state(array(
   'soapBody' =>
  SimpleXMLElement::__set_state(array(
     'NLSGetLoanDetailResponse' =>
    SimpleXMLElement::__set_state(array(
       'NLSGetLoanDetailResult' => '7',
    )),
  )),
))======================
array (
)======================
Array
(
)
</code>```

Title: Nest XML soap response PHP

Body:
Ok I am at a brick wall... SO I am making a request successfully to a webservice in php, I can capture the response and using php.net am able to output the result/response in readable form

    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetLoanDetailResponse xmlns="http://vendorsite.com/">
<GetLoanDetailResult><WEB><LOANDETAIL><acctrefno>31415</acctrefno><master_acctrefno>0</master_acctrefno><loan_number>TEST100001</loan_number><name>HILL ALAN</name><shortname>ALAN HILL</shortname><current_payoff_balance>14,358.83</current_payoff_balance><curr_date>07/14/2015</curr_date><curr_maturity_date>07/14/2021</curr_maturity_date><interest_accrued_thru_date>06/06/2017</interest_accrued_thru_date><current_note_amount>10,000.00</current_note_amount><current_principal_balance>10,000.00</current_principal_balance><current_interest_balance>4,358.83</current_interest_balance><current_fees_balance>0.00</current_fees_balance><current_late_charge_balance>0.00</current_late_charge_balance><current_perdiem>6.30</current_perdiem><current_interest_rate>23.00000</current_interest_rate><total_past_due_balance>5,651.05</total_past_due_balance><total_current_due_balance>5,651.05</total_current_due_balance><next_billing_date>06/18/2017</next_billing_date><days_past_due>662</days_past_due><current_pending>0</current_pending><current_impound_balance>0</current_impound_balance><last_payment_date>05/18/2017</last_payment_date><last_payment_amount>5</last_payment_amount><status_code>ACTIVE</status_code><loan_type>Term</loan_type><open_date>07/14/2015</open_date><last_activity_date>05/18/2017</last_activity_date><current_udf1_balance>0.00</current_udf1_balance><current_udf2_balance>0.00</current_udf2_balance><current_udf3_balance>0.00</current_udf3_balance><current_udf4_balance>0.00</current_udf4_balance><current_udf5_balance>0.00</current_udf5_balance><current_udf6_balance>0.00</current_udf6_balance><current_udf7_balance>0.00</current_udf7_balance><current_udf8_balance>0.00</current_udf8_balance><current_udf9_balance>0.00</current_udf9_balance><current_udf10_balance>0.00</current_udf10_balance><current_suspense_balance>0.00</current_suspense_balance><interest_method>SI</interest_method><term_char>Payments</term_char><term>72</term><term_due>72</term_due></LOANDETAIL></WEB></GetLoanDetailResult>
</GetLoanDetailResponse>
</soap:Body>
</soap:Envelope>

which is done using: echo "RESPONSE:\n" . htmlentities(str_ireplace('><', ">\n<", $soapClient->__getLastResponse())) . "\n";

I have tried simplexml_load_string() will not read soap response with "soap:" in the tags

and

How to drill into SOAP Namespaces with SimpleXML & PHP

trying How to convert SOAP response to PHP Array? again

And EVERY thing I can find in stack overflow and on php.net / google. I keep seeing references to a bug https://bugs.php.net/bug.php?id=48966 which I am now attempting to use to solve this... I really dont want to use dom seems like there should be a php only way to read this response... it is strange that when I call $soapClient->__getLastResponse()) I get

<WEB><LOANDETAIL><acctrefno>31415</acctrefno><master_acctrefno>0</master_acctrefno><loan_number>TEST100001</loan_number><name>Last Name F Name</name><shortname>Name</shortname><current_payoff_balance>14,358.83</current_payoff_balance><curr_date>07/14/2015</curr_date><curr_maturity_date>07/14/2021</curr_maturity_date><interest_accrued_thru_date>06/06/2017</interest_accrued_thru_date><current_note_amount>10,000.00</current_note_amount><current_principal_balance>10,000.00</current_principal_balance><current_interest_balance>4,358.83</current_interest_balance><current_fees_balance>0.00</current_fees_balance><current_late_charge_balance>0.00</current_late_charge_balance><current_perdiem>6.30</current_perdiem><current_interest_rate>23.00000</current_interest_rate><total_past_due_balance>5,651.05</total_past_due_balance><total_current_due_balance>5,651.05</total_current_due_balance><next_billing_date>06/18/2017</next_billing_date><days_past_due>662</days_past_due><current_pending>0</current_pending><current_impound_balance>0</current_impound_balance><last_payment_date>05/18/2017</last_payment_date><last_payment_amount>5</last_payment_amount><status_code>ACTIVE</status_code><loan_type>Term</loan_type><open_date>07/14/2015</open_date><last_activity_date>05/18/2017</last_activity_date><current_udf1_balance>0.00</current_udf1_balance><current_udf2_balance>0.00</current_udf2_balance><current_udf3_balance>0.00</current_udf3_balance><current_udf4_balance>0.00</current_udf4_balance><current_udf5_balance>0.00</current_udf5_balance><current_udf6_balance>0.00</current_udf6_balance><current_udf7_balance>0.00</current_udf7_balance><current_udf8_balance>0.00</current_udf8_balance><current_udf9_balance>0.00</current_udf9_balance><current_udf10_balance>0.00</current_udf10_balance><current_suspense_balance>0.00</current_suspense_balance><interest_method>SI</interest_method><term_char>Payments</term_char><term>72</term><term_due>72</term_due></LOANDETAIL></WEB>

Which I havent been able to explode to an array...

Notice the GetLoanDetailResult when I try anything with jsonencode/decode I get a key with this value and a sting with the rest of the data in a non delimited string...

The end GOAL is to put this in an array so I can pull the values and use them to populate parameters for new variables.

Using php7.0 on ubuntu server

Code to interact with response after How to convert SOAP response to PHP Array?

$loanDetail = var_dump($loanUpdate);
         $response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $soapClient->__getLastResponse());
         $xml = new SimpleXMLElement($response);
         $body = $xml->xpath('//SBody');

         var_export($xml);
        echo "======================
";
         var_export($body);
         echo "======================
";

         $array = json_decode(json_encode((array)$body), TRUE);
         print_r($array);

Returns

    object(stdClass)#3 (1) {
  ["NLSGetLoanDetailResult"]=>
  string(24) "7"
}
SimpleXMLElement::__set_state(array(
   'soapBody' =>
  SimpleXMLElement::__set_state(array(
     'NLSGetLoanDetailResponse' =>
    SimpleXMLElement::__set_state(array(
       'NLSGetLoanDetailResult' => '7',
    )),
  )),
))======================
array (
)======================
Array
(
)


问:
How to configure ssl certificate on play framework?
I have generated X.509 Certificates according to the description in https://www.playframework.com/documentation/2.5.x/ConfiguringHttps . But, i cannot configure play to use this as ssl certicate.
Can anybody provide me the actual procedure to point ssl certifate and use this certificate in play to make https.

Note:
I am using play only as a server and react page as client. So, please help me to figure out how i can configure ssl certificate in such scenario.

Thanks you!!!

答:
I found the solution to my problem.

After i created keyStore.jks from https://www.playframework.com/documentation/2.5.x/ConfiguringHttps . Then, all i needed to do was to put following things in application.conf file:

Application.conf

```<code>play.crypto.secret="changethissosomethingsecret"
play.server.https.keyStore.path = "Path to your .jks file"
play.server.https.keyStore.type = "JKS"
play.server.https.keyStore.password = "yourKeyStorePassword"
</code>```

Then to  start the application all i need to do in dev mode was sbt "start -Dhttps.port=9443".

Body:
I found the solution to my problem.

After i created keyStore.jks from https://www.playframework.com/documentation/2.5.x/ConfiguringHttps . Then, all i needed to do was to put following things in application.conf file:

Application.conf

play.crypto.secret="changethissosomethingsecret"
play.server.https.keyStore.path = "Path to your .jks file"
play.server.https.keyStore.type = "JKS"
play.server.https.keyStore.password = "yourKeyStorePassword"

Then to  start the application all i need to do in dev mode was sbt "start -Dhttps.port=9443".


问:
Getting certificate-related error when downloading Kotlin into Android Studio
What I'm trying to accomplish:

So I'm trying to install Kotlin into Android Studio. I believe it is installed, but I get an error when Gradle tries to build the project. This is where my error comes in.

The problem:

When Gradle tries to build the project, it gives me this error:

Error: Cause: unable to find valid certification path to requested target

This is my build.gradle project file:

```<code>buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

I'm not sure what the problem is here.

答:
You need to declare google maven central repository.

```<code>buildscript {
  ext.kotlin_version = '1.1.2-4'
  repositories {
    maven { url 'https://maven.google.com' } // This one
    jcenter()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

  }
}

allprojects {
  repositories {
    maven { url 'https://maven.google.com' } // And this one
    jcenter()
    mavenCentral()
  }
}

task clean(type: Delete) {
  delete rootProject.buildDir
}
</code>```

Body:
What I'm trying to accomplish:

So I'm trying to install Kotlin into Android Studio. I believe it is installed, but I get an error when Gradle tries to build the project. This is where my error comes in.

The problem:

When Gradle tries to build the project, it gives me this error:

Error: Cause: unable to find valid certification path to requested target

This is my build.gradle project file:

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I'm not sure what the problem is here.

Body:
You need to declare google maven central repository.

buildscript {
  ext.kotlin_version = '1.1.2-4'
  repositories {
    maven { url 'https://maven.google.com' } // This one
    jcenter()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

  }
}

allprojects {
  repositories {
    maven { url 'https://maven.google.com' } // And this one
    jcenter()
    mavenCentral()
  }
}

task clean(type: Delete) {
  delete rootProject.buildDir
}


问:
c++ parse int from string

Possible Duplicate:

  How to parse a string to an int in C++?

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

So I just want to ask flat out, whats the right way to convert a string to a int.

```<code>string s = "10";
int i = s....?
</code>```

Thanks!

答:
You can use istringstream.

```<code>string s = "10";

// create an input stream with your string.
istringstream is(str);

int i;
// use is like an input stream
is >> i;
</code>```

Title: c++ parse int from string

Body:
Possible Duplicate:

  How to parse a string to an int in C++?

I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.

So I just want to ask flat out, whats the right way to convert a string to a int.

string s = "10";
int i = s....?

Thanks!

Body:
You can use istringstream.

string s = "10";

// create an input stream with your string.
istringstream is(str);

int i;
// use is like an input stream
is >> i;


问:
Get error when I run Hbase shell
My local environment: OS X 10.9.2, Hbase 0.98.0, Java1.6

conf/hbase-site.xml

```<code> <property>
     <name>hbase.rootdir</name>
     <!--<value>hdfs://127.0.0.1:9000/hbase</value> need to run dfs -->
     <value>file:///Users/apple/Documents/tools/hbase-rootdir/hbase</value>
 </property>

 <property>
        <name>hbase.zookeeper.property.dataDir</name>
        <value>/Users/apple/Documents/tools/hbase-zookeeper/zookeeper</value>
 </property>
</code>```

conf/hbase-env.sh

```<code>export JAVA_HOME=$(/usr/libexec/java_home -d 64 -v 1.6)
export HBASE_OPTS="-XX:+UseConcMarkSweepGC"
</code>```

And when I ran

```<code>> list
</code>```

in Hbase shell, I got following errors:

```<code>2014-03-29 10:25:53.412 java[2434:1003] Unable to load realm info from SCDynamicStore
2014-03-29 10:25:53,416 WARN  [main] util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
2014-03-29 10:26:14,470 ERROR [main] zookeeper.RecoverableZooKeeper: ZooKeeper exists failed after 4 attempts
2014-03-29 10:26:14,471 WARN  [main] zookeeper.ZKUtil: hconnection-0x5e15e68d, quorum=localhost:2181, baseZNode=/hbase Unable to set watcher on znode (/hbase/hbaseid)
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /hbase/hbaseid
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:99)
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
    at org.apache.zookeeper.ZooKeeper.exists(ZooKeeper.java:1041)
    at org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper.exists(RecoverableZooKeeper.java:199)
    at org.apache.hadoop.hbase.zookeeper.ZKUtil.checkExists(ZKUtil.java:479)
    at org.apache.hadoop.hbase.zookeeper.ZKClusterId.readClusterIdZNode(ZKClusterId.java:65)
    at org.apache.hadoop.hbase.client.ZooKeeperRegistry.getClusterId(ZooKeeperRegistry.java:83)
    at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.retrieveClusterId(HConnectionManager.java:857)
    at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.<init>(HConnectionManager.java:662)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.apache.hadoop.hbase.client.HConnectionManager.createConnection(HConnectionManager.java:414)
    at org.apache.hadoop.hbase.client.HConnectionManager.createConnection(HConnectionManager.java:393)
    at org.apache.hadoop.hbase.client.HConnectionManager.getConnection(HConnectionManager.java:274)
    at org.apache.hadoop.hbase.client.HBaseAdmin.<init>(HBaseAdmin.java:183)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.jruby.javasupport.JavaConstructor.newInstanceDirect(JavaConstructor.java:275)
    at org.jruby.java.invokers.ConstructorInvoker.call(ConstructorInvoker.java:91)
    at org.jruby.java.invokers.ConstructorInvoker.call(ConstructorInvoker.java:178)
    at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:322)
    at org.jruby.runtime.callsite.CachingCallSite.callBlock(CachingCallSite.java:178)
    at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:182)
    at org.jruby.java.proxies.ConcreteJavaProxy$2.call(ConcreteJavaProxy.java:48)
    at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:322)
    at org.jruby.runtime.callsite.CachingCallSite.callBlock(CachingCallSite.java:178)
    at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:182)
    at org.jruby.RubyClass.newInstance(RubyClass.java:829)
        ...
at Users.apple.Documents.tools.hbase_minus_0_dot_98_dot_0_minus_hadoop2.bin.hirb.block_2$RUBY$start(/Users/apple/Documents/tools/hbase-0.98.0-hadoop2/bin/hirb.rb:185)
    at Users$apple$Documents$tools$hbase_minus_0_dot_98_dot_0_minus_hadoop2$bin$hirb$block_2$RUBY$start.call(Users$apple$Documents$tools$hbase_minus_0_dot_98_dot_0_minus_hadoop2$bin$hirb$block_2$RUBY$start:65535)
    at org.jruby.runtime.CompiledBlock.yield(CompiledBlock.java:112)
    at org.jruby.runtime.CompiledBlock.yield(CompiledBlock.java:95)
    at org.jruby.runtime.Block.yield(Block.java:130)
    at org.jruby.RubyContinuation.enter(RubyContinuation.java:106)
    at org.jruby.RubyKernel.rbCatch(RubyKernel.java:1212)
    at org.jruby.RubyKernel$s$1$0$rbCatch.call(RubyKernel$s$1$0$rbCatch.gen:65535)
    at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:322)
    at org.jruby.runtime.callsite.CachingCallSite.callBlock(CachingCallSite.java:178)
    at org.jruby.runtime.callsite.CachingCallSite.callIter(CachingCallSite.java:187)
    at Users.apple.Documents.tools.hbase_minus_0_dot_98_dot_0_minus_hadoop2.bin.hirb.method__5$RUBY$start(/Users/apple/Documents/tools/hbase-0.98.0-hadoop2/bin/hirb.rb:184)
    at Users$apple$Documents$tools$hbase_minus_0_dot_98_dot_0_minus_hadoop2$bin$hirb$method__5$RUBY$start.call(Users$apple$Documents$tools$hbase_minus_0_dot_98_dot_0_minus_hadoop2$bin$hirb$method__5$RUBY$start:65535)
    at org.jruby.internal.runtime.methods.DynamicMethod.call(DynamicMethod.java:203)
    at org.jruby.internal.runtime.methods.CompiledMethod.call(CompiledMethod.java:255)
    at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:292)
    at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:135)
    at Users.apple.Documents.tools.hbase_minus_0_dot_98_dot_0_minus_hadoop2.bin.hirb.__file__(/Users/apple/Documents/tools/hbase-0.98.0-hadoop2/bin/hirb.rb:190)
    at Users.apple.Documents.tools.hbase_minus_0_dot_98_dot_0_minus_hadoop2.bin.hirb.load(/Users/apple/Documents/tools/hbase-0.98.0-hadoop2/bin/hirb.rb)
    at org.jruby.Ruby.runScript(Ruby.java:697)
    at org.jruby.Ruby.runScript(Ruby.java:690)
    at org.jruby.Ruby.runNormally(Ruby.java:597)
    at org.jruby.Ruby.runFromMain(Ruby.java:446)
    at org.jruby.Main.doRunFromMain(Main.java:369)
    at org.jruby.Main.internalRun(Main.java:258)
    at org.jruby.Main.run(Main.java:224)
    at org.jruby.Main.run(Main.java:208)
    at org.jruby.Main.main(Main.java:188)
2014-03-29 10:28:21,137 ERROR [main] client.HConnectionManager$HConnectionImplementation: Can't get connection to ZooKeeper: KeeperErrorCode = ConnectionLoss for /hbase

ERROR: KeeperErrorCode = ConnectionLoss for /hbase
</code>```

And my /etc/hosts looks right:

```<code>127.0.0.1   localhost
255.255.255.255 broadcasthost
::1             localhost
fe80::1%lo0 localhost
127.0.0.1 activate.adobe.com
127.0.0.1 practivate.adobe.com
127.0.0.1 ereg.adobe.com
127.0.0.1 activate.wip3.adobe.com
127.0.0.1 wip3.adobe.com
127.0.0.1 3dns-3.adobe.com
127.0.0.1 3dns-2.adobe.com
127.0.0.1 adobe-dns.adobe.com
127.0.0.1 adobe-dns-2.adobe.com
127.0.0.1 adobe-dns-3.adobe.com
127.0.0.1 ereg.wip3.adobe.com
127.0.0.1 activate-sea.adobe.com
127.0.0.1 wwis-dubc1-vip60.adobe.com
127.0.0.1 activate-sjc0.adobe.com
127.0.0.1 adobe.activate.com
127.0.0.1 209.34.83.73:443
127.0.0.1 209.34.83.73:43
127.0.0.1 209.34.83.73
127.0.0.1 209.34.83.67:443
127.0.0.1 209.34.83.67:43
127.0.0.1 209.34.83.67
127.0.0.1 ood.opsource.net
127.0.0.1 CRL.VERISIGN.NET
127.0.0.1 199.7.52.190:80
127.0.0.1 199.7.52.190
127.0.0.1 adobeereg.com
127.0.0.1 OCSP.SPO1.VERISIGN.COM
127.0.0.1 199.7.54.72:80
127.0.0.1 199.7.54.72
</code>```

答:
I faced this problem when i didn't add my hostname in /etc/hosts file.

for example, my hostname is node1.

```<code>add 127.0.0.1 node1 in /etc/hosts
</code>```

Title: Get error when I run Hbase shell

Body:
My local environment: OS X 10.9.2, Hbase 0.98.0, Java1.6

conf/hbase-site.xml

 <property>
     <name>hbase.rootdir</name>

     <value>file:///Users/apple/Documents/tools/hbase-rootdir/hbase</value>
 </property>

 <property>
        <name>hbase.zookeeper.property.dataDir</name>
        <value>/Users/apple/Documents/tools/hbase-zookeeper/zookeeper</value>
 </property>

conf/hbase-env.sh

export JAVA_HOME=$(/usr/libexec/java_home -d 64 -v 1.6)
export HBASE_OPTS="-XX:+UseConcMarkSweepGC"

And when I ran

> list

in Hbase shell, I got following errors:

2014-03-29 10:25:53.412 java[2434:1003] Unable to load realm info from SCDynamicStore
2014-03-29 10:25:53,416 WARN  [main] util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
2014-03-29 10:26:14,470 ERROR [main] zookeeper.RecoverableZooKeeper: ZooKeeper exists failed after 4 attempts
2014-03-29 10:26:14,471 WARN  [main] zookeeper.ZKUtil: hconnection-0x5e15e68d, quorum=localhost:2181, baseZNode=/hbase Unable to set watcher on znode (/hbase/hbaseid)
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /hbase/hbaseid
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:99)
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
    at org.apache.zookeeper.ZooKeeper.exists(ZooKeeper.java:1041)
    at org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper.exists(RecoverableZooKeeper.java:199)
    at org.apache.hadoop.hbase.zookeeper.ZKUtil.checkExists(ZKUtil.java:479)
    at org.apache.hadoop.hbase.zookeeper.ZKClusterId.readClusterIdZNode(ZKClusterId.java:65)
    at org.apache.hadoop.hbase.client.ZooKeeperRegistry.getClusterId(ZooKeeperRegistry.java:83)
    at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.retrieveClusterId(HConnectionManager.java:857)
    at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.<init>(HConnectionManager.java:662)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.apache.hadoop.hbase.client.HConnectionManager.createConnection(HConnectionManager.java:414)
    at org.apache.hadoop.hbase.client.HConnectionManager.createConnection(HConnectionManager.java:393)
    at org.apache.hadoop.hbase.client.HConnectionManager.getConnection(HConnectionManager.java:274)
    at org.apache.hadoop.hbase.client.HBaseAdmin.<init>(HBaseAdmin.java:183)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.jruby.javasupport.JavaConstructor.newInstanceDirect(JavaConstructor.java:275)
    at org.jruby.java.invokers.ConstructorInvoker.call(ConstructorInvoker.java:91)
    at org.jruby.java.invokers.ConstructorInvoker.call(ConstructorInvoker.java:178)
    at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:322)
    at org.jruby.runtime.callsite.CachingCallSite.callBlock(CachingCallSite.java:178)
    at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:182)
    at org.jruby.java.proxies.ConcreteJavaProxy$2.call(ConcreteJavaProxy.java:48)
    at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:322)
    at org.jruby.runtime.callsite.CachingCallSite.callBlock(CachingCallSite.java:178)
    at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:182)
    at org.jruby.RubyClass.newInstance(RubyClass.java:829)
        ...
at Users.apple.Documents.tools.hbase_minus_0_dot_98_dot_0_minus_hadoop2.bin.hirb.block_2$RUBY$start(/Users/apple/Documents/tools/hbase-0.98.0-hadoop2/bin/hirb.rb:185)
    at Users$apple$Documents$tools$hbase_minus_0_dot_98_dot_0_minus_hadoop2$bin$hirb$block_2$RUBY$start.call(Users$apple$Documents$tools$hbase_minus_0_dot_98_dot_0_minus_hadoop2$bin$hirb$block_2$RUBY$start:65535)
    at org.jruby.runtime.CompiledBlock.yield(CompiledBlock.java:112)
    at org.jruby.runtime.CompiledBlock.yield(CompiledBlock.java:95)
    at org.jruby.runtime.Block.yield(Block.java:130)
    at org.jruby.RubyContinuation.enter(RubyContinuation.java:106)
    at org.jruby.RubyKernel.rbCatch(RubyKernel.java:1212)
    at org.jruby.RubyKernel$s$1$0$rbCatch.call(RubyKernel$s$1$0$rbCatch.gen:65535)
    at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:322)
    at org.jruby.runtime.callsite.CachingCallSite.callBlock(CachingCallSite.java:178)
    at org.jruby.runtime.callsite.CachingCallSite.callIter(CachingCallSite.java:187)
    at Users.apple.Documents.tools.hbase_minus_0_dot_98_dot_0_minus_hadoop2.bin.hirb.method__5$RUBY$start(/Users/apple/Documents/tools/hbase-0.98.0-hadoop2/bin/hirb.rb:184)
    at Users$apple$Documents$tools$hbase_minus_0_dot_98_dot_0_minus_hadoop2$bin$hirb$method__5$RUBY$start.call(Users$apple$Documents$tools$hbase_minus_0_dot_98_dot_0_minus_hadoop2$bin$hirb$method__5$RUBY$start:65535)
    at org.jruby.internal.runtime.methods.DynamicMethod.call(DynamicMethod.java:203)
    at org.jruby.internal.runtime.methods.CompiledMethod.call(CompiledMethod.java:255)
    at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:292)
    at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:135)
    at Users.apple.Documents.tools.hbase_minus_0_dot_98_dot_0_minus_hadoop2.bin.hirb.__file__(/Users/apple/Documents/tools/hbase-0.98.0-hadoop2/bin/hirb.rb:190)
    at Users.apple.Documents.tools.hbase_minus_0_dot_98_dot_0_minus_hadoop2.bin.hirb.load(/Users/apple/Documents/tools/hbase-0.98.0-hadoop2/bin/hirb.rb)
    at org.jruby.Ruby.runScript(Ruby.java:697)
    at org.jruby.Ruby.runScript(Ruby.java:690)
    at org.jruby.Ruby.runNormally(Ruby.java:597)
    at org.jruby.Ruby.runFromMain(Ruby.java:446)
    at org.jruby.Main.doRunFromMain(Main.java:369)
    at org.jruby.Main.internalRun(Main.java:258)
    at org.jruby.Main.run(Main.java:224)
    at org.jruby.Main.run(Main.java:208)
    at org.jruby.Main.main(Main.java:188)
2014-03-29 10:28:21,137 ERROR [main] client.HConnectionManager$HConnectionImplementation: Can't get connection to ZooKeeper: KeeperErrorCode = ConnectionLoss for /hbase

ERROR: KeeperErrorCode = ConnectionLoss for /hbase

And my /etc/hosts looks right:

127.0.0.1   localhost
255.255.255.255 broadcasthost
::1             localhost
fe80::1%lo0 localhost
127.0.0.1 activate.adobe.com
127.0.0.1 practivate.adobe.com
127.0.0.1 ereg.adobe.com
127.0.0.1 activate.wip3.adobe.com
127.0.0.1 wip3.adobe.com
127.0.0.1 3dns-3.adobe.com
127.0.0.1 3dns-2.adobe.com
127.0.0.1 adobe-dns.adobe.com
127.0.0.1 adobe-dns-2.adobe.com
127.0.0.1 adobe-dns-3.adobe.com
127.0.0.1 ereg.wip3.adobe.com
127.0.0.1 activate-sea.adobe.com
127.0.0.1 wwis-dubc1-vip60.adobe.com
127.0.0.1 activate-sjc0.adobe.com
127.0.0.1 adobe.activate.com
127.0.0.1 209.34.83.73:443
127.0.0.1 209.34.83.73:43
127.0.0.1 209.34.83.73
127.0.0.1 209.34.83.67:443
127.0.0.1 209.34.83.67:43
127.0.0.1 209.34.83.67
127.0.0.1 ood.opsource.net
127.0.0.1 CRL.VERISIGN.NET
127.0.0.1 199.7.52.190:80
127.0.0.1 199.7.52.190
127.0.0.1 adobeereg.com
127.0.0.1 OCSP.SPO1.VERISIGN.COM
127.0.0.1 199.7.54.72:80
127.0.0.1 199.7.54.72

Body:
I faced this problem when i didn't add my hostname in /etc/hosts file.

for example, my hostname is node1.

add 127.0.0.1 node1 in /etc/hosts


问:
I get an error for inserting data into SQL Server via VB.Net
I need to put some data into my SQL Server database using VB.net forms and vb language.

I already have a similar SQL request who is working but this time I get crazy errors.

This is the code who is inserting the data into the database:

```<code>Dim strIns As String = "INSERT INTO Entreprise (adresseClient, villeClient, cpClient, telClient, identClient, nomEntreprise, secteurEntreprise, dateCreationEntreprise) VALUES ('"
      strIns &= txtAdresse.Text & ", " & txtVille.Text & ", " & txtCp.Text & ", " & txtNumero.Text & ", " & txtID.Text & ", " & txtNom.Text & ", " & txtSecteur.Text & ", " & txtDateCreation.Text & "')"

Dim con As New SqlConnection
Dim cmd As New SqlCommand

Try
   con.ConnectionString = "Data Source= DESKTOP - KBTD2C1 \ MYDATABASE;Initial Catalog=MyDatabse; Integrated Security=SSPI;"
   con.Open()

   cmd.Connection = con
   cmd.CommandText = strIns

   cmd.ExecuteNonQuery()

Catch ex As Exception
    MessageBox.Show("Error While inserting record On table..." & ex.Message, "Insert Records")
Finally
    con.Close()
End Try
</code>```

I get this error:

Error while inserting record on table: Syntax error near 'Infinite'

This is the SQL command I generate in strIns:

I don't find out where is the syntax error ?

Here is my SQL Server database table:

答:
It looks like you are not applying single quote " ' " around each of the values you are passing. You are simply concatenating the textbox's value with the query string.

With current code your SQL query will become something like this:

```<code>INSERT INTO Entreprise (adresseClient, villeClient) Values ('ABC, XYZ')
</code>```

But after applying " ' " around values it will become :

```<code>INSERT INTO Entreprise (adresseClient, villeClient) Values ('ABC', 'XYZ')
</code>```

which is the correct version.

Also I would say not to concatenate the SQL Query as string as wit will cause SQL injection, please use Query parameters instead.

You can also share the error details here, which will help us to analyze the bug

Body:
I need to put some data into my SQL Server database using VB.net forms and vb language.

I already have a similar SQL request who is working but this time I get crazy errors.

This is the code who is inserting the data into the database:

Dim strIns As String = "INSERT INTO Entreprise (adresseClient, villeClient, cpClient, telClient, identClient, nomEntreprise, secteurEntreprise, dateCreationEntreprise) VALUES ('"
      strIns &= txtAdresse.Text & ", " & txtVille.Text & ", " & txtCp.Text & ", " & txtNumero.Text & ", " & txtID.Text & ", " & txtNom.Text & ", " & txtSecteur.Text & ", " & txtDateCreation.Text & "')"

Dim con As New SqlConnection
Dim cmd As New SqlCommand

Try
   con.ConnectionString = "Data Source= DESKTOP - KBTD2C1 \ MYDATABASE;Initial Catalog=MyDatabse; Integrated Security=SSPI;"
   con.Open()

   cmd.Connection = con
   cmd.CommandText = strIns

   cmd.ExecuteNonQuery()

Catch ex As Exception
    MessageBox.Show("Error While inserting record On table..." & ex.Message, "Insert Records")
Finally
    con.Close()
End Try

I get this error:

Error while inserting record on table: Syntax error near 'Infinite'

This is the SQL command I generate in strIns:

I don't find out where is the syntax error ?

Here is my SQL Server database table:

Body:
It looks like you are not applying single quote " ' " around each of the values you are passing. You are simply concatenating the textbox's value with the query string.

With current code your SQL query will become something like this:

INSERT INTO Entreprise (adresseClient, villeClient) Values ('ABC, XYZ')

But after applying " ' " around values it will become :

INSERT INTO Entreprise (adresseClient, villeClient) Values ('ABC', 'XYZ')

which is the correct version.

Also I would say not to concatenate the SQL Query as string as wit will cause SQL injection, please use Query parameters instead.

You can also share the error details here, which will help us to analyze the bug


问:
Parsing JSON response in Angular2
```<code>Id  FirstName LastName  Action
1.  Foo       Bar       Edit
2.  Happy     Kid       Edit
</code>```

The json which I get from my backend is [{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}].

Below is my HTML file -

```<code><table datatable class="row-border hover">
  <thead>
    <tr>
      <th>ID</th>
      <th>First name</th>
      <th>Last name</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>

    <tr *ngIf="userList" >
      <td *ngFor="let user of userList">{{user.firstName}}</td>

      <td>
        <button>Edit</button>
      </td>
    </tr>
    </tbody>
</table>
</code>```

The "userList" holds my json response.

Problem :- I get the error "Error trying to diff '[{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}]'. Only arrays and iterables are allowed".

How do I parse my json into my required ui ?

答:
ngFor expects array or object on which it can iterate the result, but as per your problem neither of them is present.

Try using this code -

For GET Request -

```<code>return this.http.get(API_URL)
        .map(res => res.json()
        .subscribe(
            data => this.YOUR_VARIABLE = JSON.stringify(data),
            error => alert(error),
            () => TO_DO_AFTER_REQUEST_COMPLETION
         ));
</code>```

For POST Request -

```<code>return this.http.post(API_URL,POST_PARAMETERS,{
            headers:HEADERS
        })
        .map(res => res.json()
        .subscribe(
            data => this.YOUR_VARIABLE = JSON.stringify(data),
            error => alert(error),
            () => TO_DO_AFTER_REQUEST_COMPLETION
         ));
</code>```

This will return Json response for iteration.

NOTE -

This is a pseudo code, make amendments as per your requirement.

Title: Parsing JSON response in Angular2

Body:
Id  FirstName LastName  Action
1.  Foo       Bar       Edit
2.  Happy     Kid       Edit

The json which I get from my backend is [{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}].

Below is my HTML file -

      ID
      First name
      Last name
      Action

      {{user.firstName}}

        <button>Edit</button>

The "userList" holds my json response.

Problem :- I get the error "Error trying to diff '[{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}]'. Only arrays and iterables are allowed".

How do I parse my json into my required ui ?

Body:
ngFor expects array or object on which it can iterate the result, but as per your problem neither of them is present.

Try using this code -

For GET Request -

return this.http.get(API_URL)
        .map(res => res.json()
        .subscribe(
            data => this.YOUR_VARIABLE = JSON.stringify(data),
            error => alert(error),
            () => TO_DO_AFTER_REQUEST_COMPLETION
         ));

For POST Request -

return this.http.post(API_URL,POST_PARAMETERS,{
            headers:HEADERS
        })
        .map(res => res.json()
        .subscribe(
            data => this.YOUR_VARIABLE = JSON.stringify(data),
            error => alert(error),
            () => TO_DO_AFTER_REQUEST_COMPLETION
         ));

This will return Json response for iteration.

NOTE -

This is a pseudo code, make amendments as per your requirement.


问:
Pandas Profiling - NameError: name 'pandas_profiling' is not defined
Experts,

Here is my block of code and I am getting the below error.

```<code>import pandas
import os
trainFile = r'C:\PythonProjects\sample.csv'
pwd = os.getcwd()
os.chdir(os.path.dirname(trainFile))
trainData = pandas.read_csv(os.path.basename(trainFile))
p=pandas_profiling.ProfileReport(trainData)
os.chdir(pwd)
</code>```

--------------------------------------------------------------------------- NameError                                 Traceback (most recent call
  last)  in ()
        6 trainData = pandas.read_csv(os.path.basename(trainFile))
  ----> 7 p=pandas_profiling.ProfileReport(trainData)
        8 os.chdir(pwd)

Can you provide your inputs/suggestions to resolve this error pls.
NameError: name 'pandas_profiling' is not defined

答:
"pandas_profiling" comes as a pip packages.
Have you installed the package..?

```<code>pip install pandas-profiling
</code>```

or maybe you have installed the package in some virtual environment, not in your complete path.

See the link pandas-profiling

Body:
Experts,

Here is my block of code and I am getting the below error.

import pandas
import os
trainFile = r'C:\PythonProjects\sample.csv'
pwd = os.getcwd()
os.chdir(os.path.dirname(trainFile))
trainData = pandas.read_csv(os.path.basename(trainFile))
p=pandas_profiling.ProfileReport(trainData)
os.chdir(pwd)

--------------------------------------------------------------------------- NameError                                 Traceback (most recent call
  last)  in ()
        6 trainData = pandas.read_csv(os.path.basename(trainFile))
  ----> 7 p=pandas_profiling.ProfileReport(trainData)
        8 os.chdir(pwd)

Can you provide your inputs/suggestions to resolve this error pls.
NameError: name 'pandas_profiling' is not defined

Body:
"pandas_profiling" comes as a pip packages.
Have you installed the package..?

pip install pandas-profiling

or maybe you have installed the package in some virtual environment, not in your complete path.

See the link pandas-profiling


问:
Order fields in UNION query
I am trying to make an union query in MySQL between two queries.  But, each query is ordered by a different field, and I need both queries in only one query.  Is that possible?

For example, I have this table:

```<code>table

------
A | B
------
1 | 3
------
2 | 2
------
3 | 1
</code>```

I have tried with this query:

```<code>(SELECT A, B)
    FROM table
    ORDER BY A)
UNION
(SELECT A, B)
    FROM table
    ORDER BY B)
</code>```

And I want to get something like this:

```<code>A | B
------
1 | 3
------
2 | 2
------
3 | 1
------
3 | 1
------
2 | 2
------
1 | 3
</code>```

But, instead of that, I get the union of both queries without ordering, like this:

```<code>A | B
------
1 | 3
------
2 | 2
------
3 | 1
------
1 | 3
------
2 | 2
------
3 | 1
</code>```

How must I do it?  Of course, if I do both queries separately, it works, but I need them in the same query.

答:
You can introduce an extra column which tracks each side of the union, and then use it order as you want.

```<code>SELECT t.A, t.B
FROM
(
    SELECT A, B, 'A' AS source
    FROM yourTable
    UNION ALL
    SELECT A, B, 'B'
    FROM yourTable
) t
ORDER BY
    t.source,
    CASE WHEN t.source = 'A' THEN A ELSE B END
</code>```

Output:

Demo here:

Rextester

Title: Order fields in UNION query

Body:
I am trying to make an union query in MySQL between two queries.  But, each query is ordered by a different field, and I need both queries in only one query.  Is that possible?

For example, I have this table:

table

------
A | B
------
1 | 3
------
2 | 2
------
3 | 1

I have tried with this query:

(SELECT A, B)
    FROM table
    ORDER BY A)
UNION
(SELECT A, B)
    FROM table
    ORDER BY B)

And I want to get something like this:

A | B
------
1 | 3
------
2 | 2
------
3 | 1
------
3 | 1
------
2 | 2
------
1 | 3

But, instead of that, I get the union of both queries without ordering, like this:

A | B
------
1 | 3
------
2 | 2
------
3 | 1
------
1 | 3
------
2 | 2
------
3 | 1

How must I do it?  Of course, if I do both queries separately, it works, but I need them in the same query.

Body:
You can introduce an extra column which tracks each side of the union, and then use it order as you want.

SELECT t.A, t.B
FROM
(
    SELECT A, B, 'A' AS source
    FROM yourTable
    UNION ALL
    SELECT A, B, 'B'
    FROM yourTable
) t
ORDER BY
    t.source,
    CASE WHEN t.source = 'A' THEN A ELSE B END

Output:

Demo here:

Rextester


问:
How can I make a random choice according to probabilities stored in a list (weighted random distribution)?
Given a list of probabilities like:

```<code>P = [0.10, 0.25, 0.60, 0.05]
</code>```

(I can ensure that the sum of all the variables in P is always 1)

How can I write a function that randomly returns a valid index, according to the values in the list? In other words, for this specific input, I want it to return 0 10% of the time, 1 25% of the time, 2 60% of the time and 3 the remainind 5% of the time.

答:
Basically, make a cumulative probability distribution (CDF) array. Basically, the value of the CDF for a given index is equal to the sum of all values in P equal to or less than that index. Then you generate a random number between 0 and 1 and do a binary search (or linear search if you want). Here's some simple code for it.

```<code>from bisect import bisect
from random import random

P = [0.10,0.25,0.60,0.05]

cdf = [P[0]]
for i in xrange(1, len(P)):
    cdf.append(cdf[-1] + P[i])

random_ind = bisect(cdf,random())
</code>```

of course you can generate a bunch of random indices with something like

```<code>rs = [bisect(cdf, random()) for i in xrange(20)]
</code>```

yielding

```<code>[2, 2, 3, 2, 2, 1, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2]
</code>```

(results will, and should vary). Of course, binary search is rather unnecessary for so few of possible indices, but definitely recommended for distributions with more possible indices.

Body:
Given a list of probabilities like:

P = [0.10, 0.25, 0.60, 0.05]

(I can ensure that the sum of all the variables in P is always 1)

How can I write a function that randomly returns a valid index, according to the values in the list? In other words, for this specific input, I want it to return 0 10% of the time, 1 25% of the time, 2 60% of the time and 3 the remainind 5% of the time.

Body:
Basically, make a cumulative probability distribution (CDF) array. Basically, the value of the CDF for a given index is equal to the sum of all values in P equal to or less than that index. Then you generate a random number between 0 and 1 and do a binary search (or linear search if you want). Here's some simple code for it.

from bisect import bisect
from random import random

P = [0.10,0.25,0.60,0.05]

cdf = [P[0]]
for i in xrange(1, len(P)):
    cdf.append(cdf[-1] + P[i])

random_ind = bisect(cdf,random())

of course you can generate a bunch of random indices with something like

rs = [bisect(cdf, random()) for i in xrange(20)]

yielding

[2, 2, 3, 2, 2, 1, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2]

(results will, and should vary). Of course, binary search is rather unnecessary for so few of possible indices, but definitely recommended for distributions with more possible indices.


问:
Get method in rest api
In this article
https://spring.io/understanding/REST
Was said that get method use for retrieving information, but when we use get in method attribute of form in html it is for sending data to the server
plz explain </p>

答:
If you put an url to your rest service into the browser it will use GET. The parameters should be put behind ? separated by & http://example.com?paramA=123&paramB=Hi.

Or with curl simply:
curl -X GET 'http://www.example.com?paramA=123&paramB=Hi'

if you want to use form you should use it like this:

```<code><form action="http://www.example.com">
  <input type="hidden" name="paramA" value="123" />
  <input type="hidden" name="paramB" value="Hi" />
  <input type="submit" />
</form>
</code>```

Title: Get method in rest api

Body:
If you put an url to your rest service into the browser it will use GET. The parameters should be put behind ? separated by & http://example.com?paramA=123&paramB=Hi.

Or with curl simply:
curl -X GET 'http://www.example.com?paramA=123&paramB=Hi'

if you want to use form you should use it like this:

<form action="http://www.example.com">
  <input type="hidden" name="paramA" value="123" />
  <input type="hidden" name="paramB" value="Hi" />
  <input type="submit" />
</form>


问:
How to identify notesView columns that have column totals defined for them?
I have several views that have 'column totals' defined in some columns of these views. The totals can be in different positions in each view. I'm looking a for a fast, reliable way of identifying which columns have totals before I scan these columns and views.

Ideally, I want a 'isTotal' property on the column defintion (NotesViewColumn), but that property is not defined/available.

I can see that totals in the ColumnValues array does return a 'double' datatype where a column exists, but I can only see this once I've started scanning the data in the view, and I want this detail before I start looking at the data. (For information, the ColumnValues for a category notesViewEntry is an array containing: strings for cat columns, 'empty' for untotalled fields, and doubles for totals).

I can (of course) hard-code this detail somewhere, but it seems archaic to have to do this. I can 'getFirstDoc' to work out the ColumnValues in a 'pre-loop' check, but this seems 'wasteful'.

PS: I have seen something called 'ColumnValuesIndex' but this appears to be an undocumented feature which I would prefer not to use. However, if there were an 'isTotal' undocumented feature - I'd be ok with it!

答:
The only solution I can think of to do this before you scan the data is to export the view design to DXL, then check the DXL for attributes or elements that specify whether each column shows totals.

I'm assuming view columns in DXL have an attribute or child element for this purpose. I haven't checked.

In case you've never done anything like this, using a NotesDXLExporter with either a NotesDOMParser or a NotesSAXParser, you can export selected design elements to in-memory DXL and programmatically analyse it.