问:
Moving a custom overlay in Google Maps javascript API v3
I'm developing a small app using Google Maps javascript API v3 where I need to display 2 markers and update their positions using ajax. I found no problem in doing it using Google Maps Markers, but I need a more customized marker so I'm using Google Maps custom overlays and I can't find the way to make the movements smooth.

This is the design of the markers (that also uses css animations, so I need custom html):
Markers design
The problem I have is that I can't find a way to actually move the custom overlay on the map. What I'm doing now is removing the overlay and creating a new one every time I have to move it, what makes a little blink and don't allow me to make a smooth transition from one position to the other.

So here are my questions:

1- Is using custom overlays the best way to build the markers according to the design? Is there any way to make Google Maps Markers look like the design?

2- If using custom overlays (https://developers.google.com/maps/documentation/javascript/customoverlays) is the best option, is there another way for moving them that is not removing and creating a new one?

Thanks in advance!

答:
After struggling with this some time (it really took me several hours) I have manage to do it getting inspired by this fiddle:

https://jsfiddle.net/doktormolle/QRuW8/

The functionality is not the same, but I could get some ideas.

Since there is not a lot of documentation I have created my own fiddle with a working (and simplified) example, just in case is useful for anyone:

https://jsfiddle.net/javigbas/3zx5xa2u/

```<code>:)
</code>```

Body:
After struggling with this some time (it really took me several hours) I have manage to do it getting inspired by this fiddle:

https://jsfiddle.net/doktormolle/QRuW8/

The functionality is not the same, but I could get some ideas.

Since there is not a lot of documentation I have created my own fiddle with a working (and simplified) example, just in case is useful for anyone:

https://jsfiddle.net/javigbas/3zx5xa2u/

:)


来源: stackexchange

问:
GET Web API Method returns method not allowed
I am developing web api project that will be mediator between our website and third party service and my website need to call my api where my api will adapt the request in the way third party service is expecting it, however I am getting method not allowed on my get method and I am kinda stuck. I've tried enabling CORS, but it still doesn't help , I've checked if our website is really calling with GET verb and it does, but my Web API is still returning:

The remote server returned an error: (405) Method Not Allowed.

This is the code of the method that our website is calling:

```<code>public IHttpActionResult CommitReserve()
{
    var request = this.Request;
    this.Logger.InfoFormat("CommitReserve: {0}", request.RequestUri);

    try
    {
        var customerID = request.GetRequestParameter<string>("cust_id");
        var reserveID = request.GetRequestParameter<int>("reserve_id");
        this.Logger.InfoFormat("CommitReserve: ReserveId: {0}, CustID: {1}", reserveID, customerID);

        HttpResponseMessage response = new HttpResponseMessage();
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("error_code=" + 0);
        sb.AppendLine("error_message=");
        sb.AppendLine("trx_id=" + reserveID);
        sb.Append("balance=" + 0);

        response.Content = new StringContent(sb.ToString());
        response.StatusCode = HttpStatusCode.OK;
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");

        return this.ResponseMessage(response);
   }
   catch (Exception ex)
   {
        this.Logger.ErrorFormat("CommitReserve: {0}" + ex);
        return this.BadRequest(ex.Message);
   }
}
</code>```

and this is how I enabled CORS:

```<code>config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
</code>```

I know its bad the way I did it but it is just for test t osee if this is really the problem , turns out it is not.

This is the request that I am sending with postman and it fails:

```<code>GET http://localhost:60747/api/Reserve/CommitReserve?cust_id=32569_5001&reserve_id=62150259&SportTypeID=sport HTTP/1.1
Host: localhost:60747
Proxy-Connection: keep-alive
Postman-Token: 8f26fb31-d59d-78c8-2399-3b46c4beeff5
Cache-Control: no-cache
cust_id: 32569_5001
reserve_id: 62148599
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/56.0.2924.87 Safari/537.36
amount: 2
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,pt;q=0.6
</code>```

So I ran out of options here..

**EDITS **

WebApiConfig.cs as requested:

```<code>public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();
    config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}
</code>```

答:
I think you are getting this error in your GetRequestParameter. So you need to access your query string like this,

```<code>var _req = Request.GetQueryNameValuePairs();
string customerID = _req.FirstOrDefault(ma => string.Compare(ma.Key, "cust_id") == 0).Value;
string reserveID = _req.FirstOrDefault(ma => string.Compare(ma.Key, "reserve_id") == 0).Value;
</code>```

Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
I am developing web api project that will be mediator between our website and third party service and my website need to call my api where my api will adapt the request in the way third party service is expecting it, however I am getting method not allowed on my get method and I am kinda stuck. I've tried enabling CORS, but it still doesn't help , I've checked if our website is really calling with GET verb and it does, but my Web API is still returning:

The remote server returned an error: (405) Method Not Allowed.

This is the code of the method that our website is calling:

public IHttpActionResult CommitReserve()
{
    var request = this.Request;
    this.Logger.InfoFormat("CommitReserve: {0}", request.RequestUri);

    try
    {
        var customerID = request.GetRequestParameter<string>("cust_id");
        var reserveID = request.GetRequestParameter<int>("reserve_id");
        this.Logger.InfoFormat("CommitReserve: ReserveId: {0}, CustID: {1}", reserveID, customerID);

        HttpResponseMessage response = new HttpResponseMessage();
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("error_code=" + 0);
        sb.AppendLine("error_message=");
        sb.AppendLine("trx_id=" + reserveID);
        sb.Append("balance=" + 0);

        response.Content = new StringContent(sb.ToString());
        response.StatusCode = HttpStatusCode.OK;
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");

        return this.ResponseMessage(response);
   }
   catch (Exception ex)
   {
        this.Logger.ErrorFormat("CommitReserve: {0}" + ex);
        return this.BadRequest(ex.Message);
   }
}

and this is how I enabled CORS:

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

I know its bad the way I did it but it is just for test t osee if this is really the problem , turns out it is not.

This is the request that I am sending with postman and it fails:

GET http://localhost:60747/api/Reserve/CommitReserve?cust_id=32569_5001&reserve_id=62150259&SportTypeID=sport HTTP/1.1
Host: localhost:60747
Proxy-Connection: keep-alive
Postman-Token: 8f26fb31-d59d-78c8-2399-3b46c4beeff5
Cache-Control: no-cache
cust_id: 32569_5001
reserve_id: 62148599
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/56.0.2924.87 Safari/537.36
amount: 2
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,pt;q=0.6

So I ran out of options here..

**EDITS **

WebApiConfig.cs as requested:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();
    config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

Body:
I think you are getting this error in your GetRequestParameter. So you need to access your query string like this,

var _req = Request.GetQueryNameValuePairs();
string customerID = _req.FirstOrDefault(ma => string.Compare(ma.Key, "cust_id") == 0).Value;
string reserveID = _req.FirstOrDefault(ma => string.Compare(ma.Key, "reserve_id") == 0).Value;

Hope it helps.


问:
How to add
 with  link into a textarea as simple text?
I would like to be able to add links with an  tag based on user input.

HTML

```<code><div id="linkRef">
  <button type="button" class="btn btn-default link-list">Aggiungi un link</button>
  <ul class="main_ul">
  </ul>
</div>

<div id="linkData">
  <textarea></textarea>
</div>
</code>```

JS

```<code>$('body').on('click', 'button.link-list', function() {
  $("#linkRef").on("DOMSubtreeModified", updateTree);
  $('.main_ul').append(
    $('<li><div class="form-group"><input  placeholder="Dai un nome al link...." class="link_name form-control" type="text"></div><div class="form-group"><input placeholder="inserisci il link..." class="form-control" type="text"></div></li>')
  );
});

function updateTree() {
   var myLinks = $("#linkRef ul");
   $("#linkData textarea").val(myLinks.html() + "\n");
 }

$("#linkRef").on("DOMSubtreeModified", updateTree);
$("#linkRef").on('keyup', '.form-group input', updateTree);
</code>```

The above inserts the added list but it inserts the inputs and buttons and all the html in it too, yet not the actual values, i didn't insert the  code as i was trying to work out the basic first.

The output within the textarea that I am expecting would be:

```<code><ul>
   <li>
     <a href="www.example.com">Example</a>
   </li>
   <li>
     <a href="www.example2.com">Example2</a>
   </li>
</ul>
</code>```

I made a JsFiddle playground

And this is another JsFiddle for another case I had and I was trying to work this new question out based on that but i didn't manage it

答:
$('body').on('click', 'button.link-list', function() {
 $("#linkRef").on("DOMSubtreeModified", updateTree);
  $('.main_ul').append(
    $('

<input  placeholder="Dai un nome al link...." class="link_name form-control" type="text">

<input placeholder="inserisci il link..." class="inser_link form-control" type="text">

')
    );
});

function updateTree() {
  var myLinks = $("#linkRef ul li .link_name");
  var myinserLinks = $("#linkRef ul li .inser_link");
   $("#linkData textarea").val(myLinks.val() + "\n" + myinserLinks.val());
 }

$("#linkRef").on("DOMSubtreeModified", updateTree);
$("#linkRef").on('keyup', '.form-group input', updateTree);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea {
  width: 500px;
  height: 300px;
}

input {
  width: 400px;
  height: 40px;
  margin-bottom: 10px;
}

.margin-top-20 {
  margin-top: 20px;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  <button type="button" class="btn btn-default link-list">Aggiungi un link</button>

  <textarea></textarea>

```

Title: How to add <ul> with <a> link into a textarea as simple text?

Body:
I would like to be able to add links with an  tag based on user input.

HTML

  <button type="button" class="btn btn-default link-list">Aggiungi un link</button>

  <textarea></textarea>

JS

$('body').on('click', 'button.link-list', function() {
  $("#linkRef").on("DOMSubtreeModified", updateTree);
  $('.main_ul').append(
    $('

<input  placeholder="Dai un nome al link...." class="link_name form-control" type="text">

<input placeholder="inserisci il link..." class="form-control" type="text">

')
  );
});

function updateTree() {
   var myLinks = $("#linkRef ul");
   $("#linkData textarea").val(myLinks.html() + "\n");
 }

$("#linkRef").on("DOMSubtreeModified", updateTree);
$("#linkRef").on('keyup', '.form-group input', updateTree);

The above inserts the added list but it inserts the inputs and buttons and all the html in it too, yet not the actual values, i didn't insert the  code as i was trying to work out the basic first.

The output within the textarea that I am expecting would be:

     Example

     Example2

I made a JsFiddle playground

And this is another JsFiddle for another case I had and I was trying to work this new question out based on that but i didn't manage it

Body:
$('body').on('click', 'button.link-list', function() {
 $("#linkRef").on("DOMSubtreeModified", updateTree);
  $('.main_ul').append(
    $('<li><div class="form-group"><input  placeholder="Dai un nome al link...." class="link_name form-control" type="text"></div><div class="form-group"><input placeholder="inserisci il link..." class="inser_link form-control" type="text"></div></li>')
    );
});

function updateTree() {
  var myLinks = $("#linkRef ul li .link_name");
  var myinserLinks = $("#linkRef ul li .inser_link");
   $("#linkData textarea").val(myLinks.val() + "\n" + myinserLinks.val());
 }

$("#linkRef").on("DOMSubtreeModified", updateTree);
$("#linkRef").on('keyup', '.form-group input', updateTree);

textarea {
  width: 500px;
  height: 300px;
}

input {
  width: 400px;
  height: 40px;
  margin-bottom: 10px;
}

.margin-top-20 {
  margin-top: 20px;
}

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div id="linkRef">
  <button type="button" class="btn btn-default link-list">Aggiungi un link</button>
  <ul class="main_ul">
  </ul>
</div>

<div id="linkData">
  <textarea></textarea>
</div>


问:
Retain same array key value rest other delete in php array
I have below PHP array

```<code>Array
(
    [attendees] => Array
        (
            [322] => Array
                (
                    [0] => Array
                        (
                            [attendee_name] => Amy Rainwater
                            [attendee_email] => arainwater@azdps.gov
                            [attendee_phone] => 345676575
                        )

                    [1] => Array
                        (
                            [attendee_name] => Lisa Hernandez
                            [attendee_email] => lhernandez@azdps.gov
                            [attendee_phone] => 34565
                        )

                )

        )

    [registration] => Array
        (
            [user_name] => Amy Rainwater
            [user_email] => arainwater@azdps.gov
            [dbem_name] => Lisa Hernandez
            [dbem_email] => lhernandez@azdps.gov
            [dbem_address] => PO Box 6638
            [dbem_phone] => 343545546
            [dbem_city] => Ph
            [dbem_state] => Arz
            [dbem_zip] => 85334
            [dbem_company] => Arizona Department of Public Safety
        )

    [gateway] => authorize_aim
)
</code>```

I want to retain [attendees] [322] [0] this key value rest other [1] remove from the attendees array. Currently you can see there is three arrays. So in first array (attendees) we have value "amy rainwater" so I want to retain this key value and other key value i.e [0]->Lisa Hernandez this sholud be removed from there. So please confrim how can I filter this array.

Thanks

答:
You can use reset:</p>

```<code>reset($res_booking_meta['attendees'][322]);
</code>```

Body:
I have below PHP array

Array
(
    [attendees] => Array
        (
            [322] => Array
                (
                    [0] => Array
                        (
                            [attendee_name] => Amy Rainwater
                            [attendee_email] => arainwater@azdps.gov
                            [attendee_phone] => 345676575
                        )

                    [1] => Array
                        (
                            [attendee_name] => Lisa Hernandez
                            [attendee_email] => lhernandez@azdps.gov
                            [attendee_phone] => 34565
                        )

                )

        )

    [registration] => Array
        (
            [user_name] => Amy Rainwater
            [user_email] => arainwater@azdps.gov
            [dbem_name] => Lisa Hernandez
            [dbem_email] => lhernandez@azdps.gov
            [dbem_address] => PO Box 6638
            [dbem_phone] => 343545546
            [dbem_city] => Ph
            [dbem_state] => Arz
            [dbem_zip] => 85334
            [dbem_company] => Arizona Department of Public Safety
        )

    [gateway] => authorize_aim
)

I want to retain [attendees] [322] [0] this key value rest other [1] remove from the attendees array. Currently you can see there is three arrays. So in first array (attendees) we have value "amy rainwater" so I want to retain this key value and other key value i.e [0]->Lisa Hernandez this sholud be removed from there. So please confrim how can I filter this array.

Thanks

Body:
You can use reset:

reset($res_booking_meta['attendees'][322]);


问:
How can I find words in matrix of letters
This is another question I was asked in the telephonic interview:

Given a dictionary and a crossword(2d matrix of characters) find all the dictionary words which can be found in the crossword.

All I could think of was hash the dictionary, find every possible word in the crossword and search the hash. I could not optimize it all.

Must admit Microsoft interview questions are tough :(

Please give me the lines to think on.

答:
The most appropriate solution depends a lot on the constraints you expect to be dealing with. How large is your dictionary? How large is your crossword.

I'd suggest taking a look at Suffix trees. You can insert all the dictionary words into one. Then search the suffix tree for the rows, columns and diagonals. For the rows, start a search from the root of the tree for the first letter in each row and iterate through the tree as you pass through the row. Do the same from right to left if necessary. Similar story for columns and diagonals.

Tree construction is O(N) and consumes O(N) space, where N is the size of your dictionary in characters. Searching will then take O(PQ) time, where your crossword is of size PxQ. Giving an overall runtime of O(N+PQ) and space of O(N).

The thing is, though, suffix trees are a pain to implement. They really are. So you might prefer settling for a simple Trie, which will give you a total runtime of O(N+PQ(max(P,Q)).

ContentLicense: CC BY-SA 2.5


问:
Prolog answers Argument = Argument, instead of answer No
How can I make prolog answer No , if search_answer didn't find an answer , and
Yes with L = [Answer]

search_answer : predicate that returns a list or let's A as a free variable.

```<code> found_list(L) :-
   search_answer(L).
</code>```

For example , when asked found_list(L) , although search_answer didn't find an answer , Prolog still answers Yes. I print L , and it is equal to _496 , a free variable.

Given the above piece of code, found_list answers L = [...] if search_answer found a list , else returns L = L, while I want to answer no

I tried the following , but doesn't work

```<code>found_list(L) :-
   search_answer(L) , is_list(L).
</code>```

liar_detector is my search_answer predicate , with L = answer
and liars is my found_answer

答:
In found_list(L) :- search_answer(A). both L and A are singleton. I assume you saw the warning. You need to fix that for this predicate to make sense. Do you really want L = [Answer] or L = Answer?

You can achieve what you're after this way:

```<code>found_list(A) :-
    search_answer(A).
</code>```

This will fail (result in "no") if search_answer(A) doesn't succeed, and your result will be A if it does succeed.

If you want the result as an answer within a list, you can do this:

```<code>found_list([A]) :-
    search_answer(A).
</code>```

I'm not sure what the value is of either of these. The first found_list/1 is just a simple wrapper on search_answer/1 without any additional logic. The second simply makes a single-element list out of the search_answer/1 result. If A is already a list, you don't need to put it inside of brackets ([...]), otherwise you just get a list within a list. I suspect you are really trying to do something else but haven't explained.

In response to the updated question, the following code should work if A is a simple unbound term:

```<code>found_list(A) :-
    search_answer(A),
    is_list(A).
</code>```

However, is_list/1 will succeed if its argument has a list structure even though it's elements may be unbound:

```<code>| ?- X = [_], is_list(X).

X = [_]

yes
| ?-
</code>```

So, for example, if search_answer(A) succeeds with A = [_], then found_list(A) will suceed with A = [_].

ground/1 can be useful here since:

```<code>| ?- ground(X).

no
| ?- ground([_|_]).

no
| ?- ground([a,b]).

yes
| ?-
</code>```

Thus, the following solution should work:

```<code>found_list(A) :-
    search_answer(A),
    ground(A).
</code>```

If your intention is not to backtrack to search_answer(A) if A is not ground, but just fail, you could implement found_list/1 as:

```<code>found_list(A) :-
    search_answer(A),
    ( ground(A) -> true ; !, false ).
</code>```

I think, though, there may be a more fundamental issue with the code, as it shouldn't have a behavior that you feel compelled to work around like this.

Body:
How can I make prolog answer No , if search_answer didn't find an answer , and
Yes with L = [Answer]

search_answer : predicate that returns a list or let's A as a free variable.

 found_list(L) :-
   search_answer(L).

For example , when asked found_list(L) , although search_answer didn't find an answer , Prolog still answers Yes. I print L , and it is equal to _496 , a free variable.

Given the above piece of code, found_list answers L = [...] if search_answer found a list , else returns L = L, while I want to answer no

I tried the following , but doesn't work

found_list(L) :-
   search_answer(L) , is_list(L).

liar_detector is my search_answer predicate , with L = answer
and liars is my found_answer

Body:
In found_list(L) :- search_answer(A). both L and A are singleton. I assume you saw the warning. You need to fix that for this predicate to make sense. Do you really want L = [Answer] or L = Answer?

You can achieve what you're after this way:

found_list(A) :-
    search_answer(A).

This will fail (result in "no") if search_answer(A) doesn't succeed, and your result will be A if it does succeed.

If you want the result as an answer within a list, you can do this:

found_list([A]) :-
    search_answer(A).

I'm not sure what the value is of either of these. The first found_list/1 is just a simple wrapper on search_answer/1 without any additional logic. The second simply makes a single-element list out of the search_answer/1 result. If A is already a list, you don't need to put it inside of brackets ([...]), otherwise you just get a list within a list. I suspect you are really trying to do something else but haven't explained.

In response to the updated question, the following code should work if A is a simple unbound term:

found_list(A) :-
    search_answer(A),
    is_list(A).

However, is_list/1 will succeed if its argument has a list structure even though it's elements may be unbound:

| ?- X = [_], is_list(X).

X = [_]

yes
| ?-

So, for example, if search_answer(A) succeeds with A = [_], then found_list(A) will suceed with A = [_].

ground/1 can be useful here since:

| ?- ground(X).

no
| ?- ground([_|_]).

no
| ?- ground([a,b]).

yes
| ?-

Thus, the following solution should work:

found_list(A) :-
    search_answer(A),
    ground(A).

If your intention is not to backtrack to search_answer(A) if A is not ground, but just fail, you could implement found_list/1 as:

found_list(A) :-
    search_answer(A),
    ( ground(A) -> true ; !, false ).

I think, though, there may be a more fundamental issue with the code, as it shouldn't have a behavior that you feel compelled to work around like this.


问:
MySQL - How to search for exact word match in a column of sentence?
I have a MySQL table with a list of sentences such as:

```<code>id | Sentence
---+---------------------------------------------------------------
 1 | Come On Boys, You Can do it my boy.
 2 | Everything is possible, impossible itself says I am possible.
 3 | Boys I know possible solutions are good!
 4 | Possible solutions are all failed its also possible
</code>```

I have to search on Sentence column exact word like possible.

There are some condition :

Searching word can't be prefix or suffix of any word.

Searching word possible , impossible is incorrect.

Punctuation mark can be before or after the word.Ex: !boy or boy,

No case sensitive means for possible Possible is correct.

I try a query but it is not working

```<code>mysql_query("SELECT * FROM products WHERE Sentence LIKE '%".$search."%'");
</code>```

Possible punctuation mark are ,.!?;-

I need a working solution. Thanks in advance !

答:
You could use REGEXP:

```<code>SELECT *
FROM products
WHERE Sentence REGEXP '[[:<:]]possible[[:>:]]'
--                       ^^^            ^^^ word boundaries
</code>```

This would correspond to matching possible surrounded by a word boundary.  Note in the demo that punctuation counts as a word boundary.

Also note that MySQL's REGEXP is case insensitive, so the above should match possible or Possible.

Demo here:

Rextester

Body:
I have a MySQL table with a list of sentences such as:

id | Sentence
---+---------------------------------------------------------------
 1 | Come On Boys, You Can do it my boy.
 2 | Everything is possible, impossible itself says I am possible.
 3 | Boys I know possible solutions are good!
 4 | Possible solutions are all failed its also possible

I have to search on Sentence column exact word like possible.

There are some condition :

Searching word can't be prefix or suffix of any word.

Searching word possible , impossible is incorrect.

Punctuation mark can be before or after the word.Ex: !boy or boy,

No case sensitive means for possible Possible is correct.

I try a query but it is not working

mysql_query("SELECT * FROM products WHERE Sentence LIKE '%".$search."%'");

Possible punctuation mark are ,.!?;-

I need a working solution. Thanks in advance !

Body:
You could use REGEXP:

SELECT *
FROM products
WHERE Sentence REGEXP '[[:<:]]possible[[:>:]]'
--                       ^^^            ^^^ word boundaries

This would correspond to matching possible surrounded by a word boundary.  Note in the demo that punctuation counts as a word boundary.

Also note that MySQL's REGEXP is case insensitive, so the above should match possible or Possible.

Demo here:

Rextester


问:
Find in one cell, replace in different cell - Only works for one phase
I'm creating a tool that will help with translations for a user interface.

I have a list of English phrases in Sheet "Translate" Col A which I want to compare with English Phrases from a library of translations on sheet "2052 Simplified Chinese" in Col A. When a match is found I want the cosponsoring Chinese phrase from Col B of the library sheet to be copied to Col B of "Translate" Sheet.

Searching different forums for similar problems I found the following sub which I adapted to my needs:

```<code>Sub Replace_From_List()

Dim cell As Range, rngFind As Range, counter As Long
Dim RefSheet As String
Dim ReplaceSheet As String

RefSheet = "2052 Simplified Chinese"
ReplaceSheet = "Translate"

'List of items to search for from Translated phases sheet column A
With Sheets(RefSheet)
    Set rngFind = .Range("A1", .Range("A" & Rows.Count).End(xlUp))
End With

For Each cell In rngFind
    'Search in Sheet containing phases to translate Column A
    Set Found = Sheets(ReplaceSheet).Range("A:A").Find(What:=cell.Value, _
                                                   LookIn:=xlValues, _
                                                   LookAt:=xlWhole, _
                                                   SearchOrder:=xlByRows, _
                                                   MatchCase:=False)

    If Not Found Is Nothing Then
        'When a match is found, replace Sheet "Translate" column B with Sheet "2052 Simplified Chinese" Column B
        'Overwrites formulas
        Found.Offset(, 1).Value = cell.Offset(, 1).Value
        counter = counter + 1
    End If
Next cell

MsgBox "Replacements made: " & counter, , "Replacements Complete"

End Sub
</code>```

However, this seems to only replace each matched phrase only once then move on to the next phrases. I need it to keep searching the whole sheet and replace each match it finds before it moves on to the next phrase.

You can see in the pic below that the value in B3 should also be in B4, the same with B18:B21

Results from Replace_From_List() Sub

I think that I need to add another loop or change my loop parameters to do this but I'm not entirely sure what's happening.

I'm familiar with programming in C but I'm pretty much a novice with VBA.

答:
You can use the FindNext method which will search for values until it returns to the original found item (though I must say I don't see why you couldnt just use VLOOKUP).</p>

```<code>Sub Replace_From_List()

Dim cell As Range, rngFind As Range, counter As Long
Dim RefSheet As String
Dim ReplaceSheet As String
Dim s As String

RefSheet = "2052 Simplified Chinese"
ReplaceSheet = "Translate"

'List of items to search for from Translated phases sheet column A
With Sheets(RefSheet)
    Set rngFind = .Range("A1", .Range("A" & Rows.Count).End(xlUp))
End With

For Each cell In rngFind
    'Search in Sheet containing phases to translate Column A
    Set found = Sheets(ReplaceSheet).Range("A:A").Find(What:=cell.Value, _
                                                   LookIn:=xlValues, _
                                                   LookAt:=xlWhole, _
                                                   SearchOrder:=xlByRows, _
                                                   MatchCase:=False)

    If Not found Is Nothing Then
        'When a match is found, replace Sheet "Translate" column B with Sheet "2052 Simplified Chinese" Column B
        'Overwrites formulas
        s = found.Address
        Do
            found.Offset(, 1).Value = cell.Offset(, 1).Value
            counter = counter + 1
            Set found = Sheets(ReplaceSheet).Range("A:A").FindNext(found)
        Loop While found.Address <> s
    End If
Next cell

MsgBox "Replacements made: " & counter, , "Replacements Complete"

End Sub
</code>```

Body:
I'm creating a tool that will help with translations for a user interface.

I have a list of English phrases in Sheet "Translate" Col A which I want to compare with English Phrases from a library of translations on sheet "2052 Simplified Chinese" in Col A. When a match is found I want the cosponsoring Chinese phrase from Col B of the library sheet to be copied to Col B of "Translate" Sheet.

Searching different forums for similar problems I found the following sub which I adapted to my needs:

Sub Replace_From_List()

Dim cell As Range, rngFind As Range, counter As Long
Dim RefSheet As String
Dim ReplaceSheet As String

RefSheet = "2052 Simplified Chinese"
ReplaceSheet = "Translate"

'List of items to search for from Translated phases sheet column A
With Sheets(RefSheet)
    Set rngFind = .Range("A1", .Range("A" & Rows.Count).End(xlUp))
End With

For Each cell In rngFind
    'Search in Sheet containing phases to translate Column A
    Set Found = Sheets(ReplaceSheet).Range("A:A").Find(What:=cell.Value, _
                                                   LookIn:=xlValues, _
                                                   LookAt:=xlWhole, _
                                                   SearchOrder:=xlByRows, _
                                                   MatchCase:=False)

    If Not Found Is Nothing Then
        'When a match is found, replace Sheet "Translate" column B with Sheet "2052 Simplified Chinese" Column B
        'Overwrites formulas
        Found.Offset(, 1).Value = cell.Offset(, 1).Value
        counter = counter + 1
    End If
Next cell

MsgBox "Replacements made: " & counter, , "Replacements Complete"

End Sub

However, this seems to only replace each matched phrase only once then move on to the next phrases. I need it to keep searching the whole sheet and replace each match it finds before it moves on to the next phrase.

You can see in the pic below that the value in B3 should also be in B4, the same with B18:B21

Results from Replace_From_List() Sub

I think that I need to add another loop or change my loop parameters to do this but I'm not entirely sure what's happening.

I'm familiar with programming in C but I'm pretty much a novice with VBA.

Body:
You can use the FindNext method which will search for values until it returns to the original found item (though I must say I don't see why you couldnt just use VLOOKUP).

Sub Replace_From_List()

Dim cell As Range, rngFind As Range, counter As Long
Dim RefSheet As String
Dim ReplaceSheet As String
Dim s As String

RefSheet = "2052 Simplified Chinese"
ReplaceSheet = "Translate"

'List of items to search for from Translated phases sheet column A
With Sheets(RefSheet)
    Set rngFind = .Range("A1", .Range("A" & Rows.Count).End(xlUp))
End With

For Each cell In rngFind
    'Search in Sheet containing phases to translate Column A
    Set found = Sheets(ReplaceSheet).Range("A:A").Find(What:=cell.Value, _
                                                   LookIn:=xlValues, _
                                                   LookAt:=xlWhole, _
                                                   SearchOrder:=xlByRows, _
                                                   MatchCase:=False)

    If Not found Is Nothing Then
        'When a match is found, replace Sheet "Translate" column B with Sheet "2052 Simplified Chinese" Column B
        'Overwrites formulas
        s = found.Address
        Do
            found.Offset(, 1).Value = cell.Offset(, 1).Value
            counter = counter + 1
            Set found = Sheets(ReplaceSheet).Range("A:A").FindNext(found)
        Loop While found.Address <> s
    End If
Next cell

MsgBox "Replacements made: " & counter, , "Replacements Complete"

End Sub


问:
Kafka with Spark 2.1 Structured Streaming - cannot deserialize
With Apache Spark version 2.1, I would like to use Kafka (0.10.0.2.5) as source for Structured Streaming with pyspark.

In the Kafka topic, I have json messages (pushed with Streamsets Data Collector).
However, I am not able to read it with following code:

```<code>kafka=spark.readStream.format("kafka") \
.option("kafka.bootstrap.servers","localhost:6667") \
.option("subscribe","mytopic").load()
msg=kafka.selectExpr("CAST(value AS STRING)")
disp=msg.writeStream.outputMode("append").format("console").start()
</code>```

It generates this error :

```<code> java.lang.NoClassDefFoundError: org/apache/kafka/common/serialization/ByteArrayDeserializer
</code>```

I tried to add at the readStream line:

```<code>.option("value.serializer","org.common.serialization.StringSerializer")
.option("key.serializer","org.common.serialization.StringSerializer")
</code>```

But it does not solve the problem.

Any idea ? Thank you in advance.

答:
Actually I found the solution: I added the following jar in dependency:

spark-streaming-kafka-0-10-assembly_2.10-2.1.0.jar

(after having downloaded it from https://mvnrepository.com/artifact/org.apache.spark/spark-streaming-kafka-0-10-assembly_2.10/2.1.0)

Body:
With Apache Spark version 2.1, I would like to use Kafka (0.10.0.2.5) as source for Structured Streaming with pyspark.

In the Kafka topic, I have json messages (pushed with Streamsets Data Collector).
However, I am not able to read it with following code:

kafka=spark.readStream.format("kafka") \
.option("kafka.bootstrap.servers","localhost:6667") \
.option("subscribe","mytopic").load()
msg=kafka.selectExpr("CAST(value AS STRING)")
disp=msg.writeStream.outputMode("append").format("console").start()

It generates this error :

 java.lang.NoClassDefFoundError: org/apache/kafka/common/serialization/ByteArrayDeserializer

I tried to add at the readStream line:

.option("value.serializer","org.common.serialization.StringSerializer")
.option("key.serializer","org.common.serialization.StringSerializer")

But it does not solve the problem.

Any idea ? Thank you in advance.


问:
Android - NullPointerException hashCode() on a null object Reference
Help Me, I have Error when i want to POST JSON from my register (frmDaftar) class to WebService, error code is : java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
                                                                              at com.android.volley.Request.(Request.java:136)

```<code>public class frmDaftar extends AppCompatActivity {
Button btnDaftar, btnKembali;
EditText email, pass, nama;
AlertDialog alertDialog;
private static final String TAG = frmDaftar.class.getSimpleName();
SessionManager session;

private String EmailView;
private ProgressDialog pDialog;

private static final String Key_nama = "nama";
private static final String Key_email = "email";
private static final String Key_password = "password";
private static  final String url = "Webservice_Controller.URL_DAFTAR";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_frm_daftar);
    btnDaftar = (Button) findViewById(R.id.btnDaftar1);
    btnKembali = (Button) findViewById(R.id.btnKembali);
    email = (EditText) findViewById(R.id.txtEmailDaftar);
    pass = (EditText) findViewById(R.id.txtPasswordDaftar);
    nama = (EditText) findViewById(R.id.txtNamaDaftar);

    session = new SessionManager(getApplicationContext());
    btnDaftar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            btnDaftar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String emails = email.getText().toString().trim();
                    String passwords = pass.getText().toString().trim();
                    String namas = nama.getText().toString().trim();

                    registerUser(emails, passwords,namas);
                    //alertDialog.show();

                }
            });
        }
    });
    btnKembali.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(frmDaftar.this, frmLogin.class));
        }
    });

}

    private void initCustomAlertDialog(String EmailView) {
        View v = getLayoutInflater().inflate(R.layout.dialogverivikasi, null);
        TextView txtEmail = (TextView) findViewById(R.id.lblemailDaftar);
        //txtEmail.setText(EmailView);
        alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setView(v);
        alertDialog.setTitle("Verifikasi Email");
    }
private void registerUser(final String nama, final String email, final String pass){
    String tag_string_req = "req_register";
    pDialog.setMessage("Registering ...");
    showDialog();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, Webservice_Controller.URL_DAFTAR,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try{
                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("error");
                        Log.d(TAG, "Register Response: " + response.toString());
                        hideDialog();

                    }catch (JSONException e) {
                        e.printStackTrace();
                    } {

                    }
                    //Toast.makeText(DataSent.this, response, Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //Toast.makeText(DataSent.this,error.toString(),Toast.LENGTH_LONG).show();
                    Log.e(TAG, "Registration Error: " + error.getMessage());
                    Toast.makeText(getApplicationContext(),
                            error.getMessage(), Toast.LENGTH_LONG).show();
                    hideDialog();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", nama);
            params.put("email", email);
            params.put("password", pass);;

            return params;
        }
    };

    AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
</code>```

Here is my AppController

```<code>public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}
</code>```

}

Help Me Please, This is my first android project :)

答:
Double check that you added your app controller in your applicaiton tag. Hope it'll fix your crash. </p>

```<code>   <application
    android:name="AppController"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
</code>```

Body:
Help Me, I have Error when i want to POST JSON from my register (frmDaftar) class to WebService, error code is : java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
                                                                              at com.android.volley.Request.(Request.java:136)

public class frmDaftar extends AppCompatActivity {
Button btnDaftar, btnKembali;
EditText email, pass, nama;
AlertDialog alertDialog;
private static final String TAG = frmDaftar.class.getSimpleName();
SessionManager session;

private String EmailView;
private ProgressDialog pDialog;

private static final String Key_nama = "nama";
private static final String Key_email = "email";
private static final String Key_password = "password";
private static  final String url = "Webservice_Controller.URL_DAFTAR";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_frm_daftar);
    btnDaftar = (Button) findViewById(R.id.btnDaftar1);
    btnKembali = (Button) findViewById(R.id.btnKembali);
    email = (EditText) findViewById(R.id.txtEmailDaftar);
    pass = (EditText) findViewById(R.id.txtPasswordDaftar);
    nama = (EditText) findViewById(R.id.txtNamaDaftar);

    session = new SessionManager(getApplicationContext());
    btnDaftar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            btnDaftar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String emails = email.getText().toString().trim();
                    String passwords = pass.getText().toString().trim();
                    String namas = nama.getText().toString().trim();

                    registerUser(emails, passwords,namas);
                    //alertDialog.show();

                }
            });
        }
    });
    btnKembali.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(frmDaftar.this, frmLogin.class));
        }
    });

}

    private void initCustomAlertDialog(String EmailView) {
        View v = getLayoutInflater().inflate(R.layout.dialogverivikasi, null);
        TextView txtEmail = (TextView) findViewById(R.id.lblemailDaftar);
        //txtEmail.setText(EmailView);
        alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setView(v);
        alertDialog.setTitle("Verifikasi Email");
    }
private void registerUser(final String nama, final String email, final String pass){
    String tag_string_req = "req_register";
    pDialog.setMessage("Registering ...");
    showDialog();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, Webservice_Controller.URL_DAFTAR,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try{
                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("error");
                        Log.d(TAG, "Register Response: " + response.toString());
                        hideDialog();

                    }catch (JSONException e) {
                        e.printStackTrace();
                    } {

                    }
                    //Toast.makeText(DataSent.this, response, Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //Toast.makeText(DataSent.this,error.toString(),Toast.LENGTH_LONG).show();
                    Log.e(TAG, "Registration Error: " + error.getMessage());
                    Toast.makeText(getApplicationContext(),
                            error.getMessage(), Toast.LENGTH_LONG).show();
                    hideDialog();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", nama);
            params.put("email", email);
            params.put("password", pass);;

            return params;
        }
    };

    AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}

Here is my AppController

public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}

}

Help Me Please, This is my first android project :)

Body:
Double check that you added your app controller in your applicaiton tag. Hope it'll fix your crash.

   <application
    android:name="AppController"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">


问:
DataFrameGroupBy diff() on condition
Suppose i have a DataFrame:

```<code>df = pd.DataFrame({'CATEGORY':['a','b','c','b','b','a','b'],
                   'VALUE':[pd.np.NaN,1,0,0,5,0,4]})
</code>```

which looks like

```<code>    CATEGORY    VALUE
0      a         NaN
1      b         1
2      c         0
3      b         0
4      b         5
5      a         0
6      b         4
</code>```

I group it:

```<code>df = df.groupby(by='CATEGORY')
</code>```

And now, let me show, what i want with the help of example on one group 'b':

```<code>df.get_group('b')
</code>```

group b:

```<code>    CATEGORY    VALUE
1      b          1
3      b          0
4      b          5
6      b          4
</code>```

I need: In the scope of each group, count diff() between VALUE values, skipping all NaNs and 0s. So the result should be:

```<code>    CATEGORY    VALUE  DIFF
1      b          1      -
3      b          0      -
4      b          5      4
6      b          4     -1
</code>```

答:
You can use diff to subtract values after dropping 0 and NaN values:

```<code>df = pd.DataFrame({'CATEGORY':['a','b','c','b','b','a','b'],
               'VALUE':[pd.np.NaN,1,0,0,5,0,4]})

grouped = df.groupby("CATEGORY")

# define diff func
diff = lambda x: x["VALUE"].replace(0, np.NaN).dropna().diff()
df["DIFF"] = grouped.apply(diff).reset_index(0, drop=True)

print(df)

  CATEGORY  VALUE  DIFF
0        a    NaN   NaN
1        b    1.0   NaN
2        c    0.0   NaN
3        b    0.0   NaN
4        b    5.0   4.0
5        a    0.0   NaN
6        b    4.0  -1.0
</code>```

Title: DataFrameGroupBy diff() on condition

Body:
Suppose i have a DataFrame:

df = pd.DataFrame({'CATEGORY':['a','b','c','b','b','a','b'],
                   'VALUE':[pd.np.NaN,1,0,0,5,0,4]})

which looks like

    CATEGORY    VALUE
0      a         NaN
1      b         1
2      c         0
3      b         0
4      b         5
5      a         0
6      b         4

I group it:

df = df.groupby(by='CATEGORY')

And now, let me show, what i want with the help of example on one group 'b':

df.get_group('b')

group b:

    CATEGORY    VALUE
1      b          1
3      b          0
4      b          5
6      b          4

I need: In the scope of each group, count diff() between VALUE values, skipping all NaNs and 0s. So the result should be:

    CATEGORY    VALUE  DIFF
1      b          1      -
3      b          0      -
4      b          5      4
6      b          4     -1

Body:
You can use diff to subtract values after dropping 0 and NaN values:

df = pd.DataFrame({'CATEGORY':['a','b','c','b','b','a','b'],
               'VALUE':[pd.np.NaN,1,0,0,5,0,4]})

grouped = df.groupby("CATEGORY")

# define diff func
diff = lambda x: x["VALUE"].replace(0, np.NaN).dropna().diff()
df["DIFF"] = grouped.apply(diff).reset_index(0, drop=True)

print(df)

  CATEGORY  VALUE  DIFF
0        a    NaN   NaN
1        b    1.0   NaN
2        c    0.0   NaN
3        b    0.0   NaN
4        b    5.0   4.0
5        a    0.0   NaN
6        b    4.0  -1.0


问:
ClickListner is not working on SearchView
```<code><android.support.v7.widget.SearchView
                 android:layout_width="match_parent"
                android:layout_height="36dp"
                android:id="@+id/search"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="15dp"
                android:layout_marginBottom="15dp"
                android:background="@drawable/edit_text"
                app:queryBackground="@color/white"
                app:iconifiedByDefault="false"
                app:showAsAction="always"
                 app:queryHint="Search Medicines">
            </android.support.v7.widget.SearchView>
</code>```

This is my xml of searchView,SetOnclicklistner is not working,when i type any character its working fine but when i click nothing happens.

setOnQueryTextListener is working,
onQueryTextChange is working,
setOnCloseListener is working,but SetOnclicklistner  is not working.

```<code> search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             Log.e("my_OnSearchClick","OnSearchClick");
             //not working

        }
    });
</code>```

答:
```<code>search.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //use this action
        }
    });
</code>```

or

```<code>search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                 //use this action

                search.clearFocus();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

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

Body:
<android.support.v7.widget.SearchView
                 android:layout_width="match_parent"
                android:layout_height="36dp"
                android:id="@+id/search"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="15dp"
                android:layout_marginBottom="15dp"
                android:background="@drawable/edit_text"
                app:queryBackground="@color/white"
                app:iconifiedByDefault="false"
                app:showAsAction="always"
                 app:queryHint="Search Medicines">
            </android.support.v7.widget.SearchView>

This is my xml of searchView,SetOnclicklistner is not working,when i type any character its working fine but when i click nothing happens.

setOnQueryTextListener is working,
onQueryTextChange is working,
setOnCloseListener is working,but SetOnclicklistner  is not working.

 search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             Log.e("my_OnSearchClick","OnSearchClick");
             //not working

        }
    });

Body:
search.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //use this action
        }
    });

or

search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                 //use this action

                search.clearFocus();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                return false;
            }
        });


问:
IList.Cast<typeof(T)>() returns error, syntax looks ok
```<code>public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}
</code>```

<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>

答:
T is not a type nor a System.Type.  T is a type parameter.  typeof(T) returns the type of T.  The typeof operator does not act on an object, it returns the Type object of a type. http://msdn.microsoft.com/en-us/library/58918ffs.aspx

@John is correct in answering your direct question.  But the NHibernate code there is a little off. You shouldn't be configuring the ISessionFactory after getting the ISession, for example.

```<code>public static T[] LoadObjectListAll()
{
    var session = GetNewSession();
    var criteria = session.CreateCriteria(typeof(T));
    var results = criteria.List<T>();
    return results.ToArray();
}
</code>```

OwnerDisplayName: Sara Chipps

Body:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?

Body:
T is not a type nor a System.Type.  T is a type parameter.  typeof(T) returns the type of T.  The typeof operator does not act on an object, it returns the Type object of a type. http://msdn.microsoft.com/en-us/library/58918ffs.aspx

@John is correct in answering your direct question.  But the NHibernate code there is a little off. You shouldn't be configuring the ISessionFactory after getting the ISession, for example.

public static T[] LoadObjectListAll()
{
    var session = GetNewSession();
    var criteria = session.CreateCriteria(typeof(T));
    var results = criteria.List<T>();
    return results.ToArray();
}

OwnerDisplayName: Matt Hinze

LastEditorDisplayName: Matt Hinze


问:
What is the significance of trailing slashes in a namespace URI?
I have been studying SOAP and WSDL in preparation for implementing a web service.  One thing that I have encountered that puzzles me is that some of the URIs that I have seen use a trailing slash such as:

```<code>http://www.w3.org/some-namespace/
</code>```

while other examples that I have studied omit this trailing slash.  I really have several questions regarding this:

What is the significance of the trailing slash?

Is the URI, http://www.w3.org/some-namespace the same as http://www.w3.org/some-namespace/?

If they are not the same, how do I decide when one form is warranted versus another?

I have read the guidelines given by w3c regarding URI's and these appear to indicate that that URI should be considered equal only if the case-sensitive comparison of the URI strings are considered equal.  Is this interpretation correct?

答:
Namespace URIs are simply meant as unique identifiers (here's a link to the rules for comparison). Use of a URI (versus, say "foo") can be traced back (I believe) to the use of URIs in an XML DOCTYPE.

Which is also, I think where the confusion comes regarding the "retrievability" of such URIs. The XML Spec requires that the SYSTEM identifier in a DOCTYPE may be used to retrieve the document's DTD (I link to the Annotated XML Spec, rather than the W3C version, because I believe that Tim Bray's commentary is very useful).

Although other specifications (eg, XML schema) do not require this behavior, I believe that it's a useful habit to follow -- particularly in the case of Schema target namespaces. For one thing, it makes it easy for consumers of your schema to always find the correct definition. For another, if you have the power to put the document at a public URL, then you can also ensure that the URI is unique.

Finally: Uniform Resource Identifiers (URIs) are a superset of Uniform Resource Locators (URLs). You can also have a Uniform Resource Name (URN), and I believe (but don't have the spec handy) that there is a third form of identifier.

OwnerDisplayName: Jon Trauntvein

Body:
I have been studying SOAP and WSDL in preparation for implementing a web service.  One thing that I have encountered that puzzles me is that some of the URIs that I have seen use a trailing slash such as:

http://www.w3.org/some-namespace/

while other examples that I have studied omit this trailing slash.  I really have several questions regarding this:

What is the significance of the trailing slash?

Is the URI, http://www.w3.org/some-namespace the same as http://www.w3.org/some-namespace/?

If they are not the same, how do I decide when one form is warranted versus another?

I have read the guidelines given by w3c regarding URI's and these appear to indicate that that URI should be considered equal only if the case-sensitive comparison of the URI strings are considered equal.  Is this interpretation correct?

OwnerDisplayName: kdgregory

LastEditorDisplayName: Sam Hasler


问:
How do I Find Categories within in Contained Model in CakePHP
I had a recent question here regarding Finding records via conditions in habtm. Now, I could search for posts within a category I searched for.

Now, my questions is how to I retrieve the categories of each post. Sometimes a post has one or more categories in this query:

```<code>$this->set('posts', $this->Category->find(
    'first',
    array(
        'conditions' => array(
            'Category.uri' => $uri
        ),
        'contain' => array('Post')
    )
));
</code>```

I'd imagine something like this:

```<code>$this->set('posts', $this->Category->find(
    'first',
    array(
        'conditions' => array(
            'Category.uri' => $uri
        ),
        'contain' => array('Post' => array(
            'contain' => 'Category'
        ))
    )
));
</code>```

Here's what my models look like.

```<code>// Category Model
class Category extends AppModel {
    var $name = 'Category';
    var $hasAndBelongsToMany = array(
        'Post' => array(
            'className' => 'Post'
        )
    );
    var $actsAs = array('Containable');
}

// Post Model
    class Post extends AppModel {
        var $name = 'Post';
        var $hasAndBelongsToMany = array(
            'Category' => array(
                'className' => 'Category'
            )
        );
        var $actsAs = array('Containable');
        var $virtualFields = array(
            'date_posted' => 'DATE_SUB(Post.created, INTERVAL 7 DAY)'
        );
    }
</code>```

A sample data would be like this:

```<code>categories
id name
1  holidays
2  destinations

posts
id title
1  I am a post
2  I am another post

categories_posts
post_id category_id
1       1
2       2
2       1
</code>```

I am retrieving posts from holidays.

```<code>Array
(
    [Category] => Array
        (
            [id] => 3
            [name] => holidays
            [uri] => holidays
            [created] => 2010-11-25 20:43:03
            [modified] => 2010-11-25 20:43:03
        )

    [Post] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [title] => I am a post
                ),
            [1] => Array
                (
                    [id] => 2
                    [title] => I am a another post
                )
        )
)
</code>```

The problem is that 1 of the posts are in two categories. I'd like to have that information also available.

答:
I'm leaving my other answer as-is because it contains a lot of good info for those who may stumble upon it.  As far as solving your problem more elegantly?  You'll need to flip the find on it's head and search from the Post model with an ad-hoc join, like this:

```<code>// From the CategoriesController
$this->Category->Post->find('all', array(
    'joins' => array(
        array(
            'table' => 'categories_posts',
            'alias' => 'CategoryFilter',
            'type' => 'inner',
            'conditions' => array(
                'CategoryFilter.post_id = Post.id'
            )
        ),
        array(
            'table' => 'categories',
            'alias' => 'CategoryUriFilter',
            'type' => 'inner',
            'conditions' => array(
                'CategoryUriFilter.id = CategoryFilter.category_id'
            )
        )
    ),
    'conditions' => array(
        'CategoryUriFilter.uri' => $uri
    ),
    'contain' => array('Category')
));
</code>```

The array returned will be formatted a bit differently, but it should contain all of the data you were looking for.

Body:
I had a recent question here regarding Finding records via conditions in habtm. Now, I could search for posts within a category I searched for.

Now, my questions is how to I retrieve the categories of each post. Sometimes a post has one or more categories in this query:

$this->set('posts', $this->Category->find(
    'first',
    array(
        'conditions' => array(
            'Category.uri' => $uri
        ),
        'contain' => array('Post')
    )
));

I'd imagine something like this:

$this->set('posts', $this->Category->find(
    'first',
    array(
        'conditions' => array(
            'Category.uri' => $uri
        ),
        'contain' => array('Post' => array(
            'contain' => 'Category'
        ))
    )
));

Here's what my models look like.

// Category Model
class Category extends AppModel {
    var $name = 'Category';
    var $hasAndBelongsToMany = array(
        'Post' => array(
            'className' => 'Post'
        )
    );
    var $actsAs = array('Containable');
}

// Post Model
    class Post extends AppModel {
        var $name = 'Post';
        var $hasAndBelongsToMany = array(
            'Category' => array(
                'className' => 'Category'
            )
        );
        var $actsAs = array('Containable');
        var $virtualFields = array(
            'date_posted' => 'DATE_SUB(Post.created, INTERVAL 7 DAY)'
        );
    }

A sample data would be like this:

categories
id name
1  holidays
2  destinations

posts
id title
1  I am a post
2  I am another post

categories_posts
post_id category_id
1       1
2       2
2       1

I am retrieving posts from holidays.

Array
(
    [Category] => Array
        (
            [id] => 3
            [name] => holidays
            [uri] => holidays
            [created] => 2010-11-25 20:43:03
            [modified] => 2010-11-25 20:43:03
        )

    [Post] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [title] => I am a post
                ),
            [1] => Array
                (
                    [id] => 2
                    [title] => I am a another post
                )
        )
)

The problem is that 1 of the posts are in two categories. I'd like to have that information also available.

Body:
I'm leaving my other answer as-is because it contains a lot of good info for those who may stumble upon it.  As far as solving your problem more elegantly?  You'll need to flip the find on it's head and search from the Post model with an ad-hoc join, like this:

// From the CategoriesController
$this->Category->Post->find('all', array(
    'joins' => array(
        array(
            'table' => 'categories_posts',
            'alias' => 'CategoryFilter',
            'type' => 'inner',
            'conditions' => array(
                'CategoryFilter.post_id = Post.id'
            )
        ),
        array(
            'table' => 'categories',
            'alias' => 'CategoryUriFilter',
            'type' => 'inner',
            'conditions' => array(
                'CategoryUriFilter.id = CategoryFilter.category_id'
            )
        )
    ),
    'conditions' => array(
        'CategoryUriFilter.uri' => $uri
    ),
    'contain' => array('Category')
));

The array returned will be formatted a bit differently, but it should contain all of the data you were looking for.


问:
Javascript GeoLocation is not working on Chrome
I'm trying to take the geolocation of the User and then do a query.
In Mozilla Firefox it works fine also in Safari.... but in Chrome it doesnt work at all.

```<code>window.onload = function(){
  if(navigator.geolocation){

    navigator.geolocation.getCurrentPosition(function(position){

        var latitude = position.coords.latitude,
            longitude = position.coords.longitude;
      console.log(latitude + " " + longitude);

    },handleError);

    function handleError(error){
      //Handle Errors
     switch(error.code) {
        case error.PERMISSION_DENIED:
            console.log("User denied the request for Geolocation.");
            break;
        case error.POSITION_UNAVAILABLE:
            console.log("Location information is unavailable.");
            break;
        case error.TIMEOUT:
           console.log("The request to get user location timed out.");
            break;
        case error.UNKNOWN_ERROR:
           console.log("An unknown error occurred.");
            break;
    }
    }
  }else{
    // container.innerHTML = "Geolocation is not Supported for this browser/OS.";
    alert("Geolocation is not Supported for this browser/OS");
  }
};
</code>```

And i get the error 1

```<code>User denied the request for Geolocation.
</code>```

But i haven't denied any request, actually the popup window doesnt come up at all.

I've went to Chrome Settings > Show advanced > Privacy > Content Settings > Location allow for all.

Restarted chrome and nothing happened. I'm sure my code is 100% legit so does anyone know how to deal with it?
Thanks!

答: The easiest way is to click on the area left to the address bar and change location settings there. It allows to set location options even for file:/// and all other types

Body:
I'm trying to take the geolocation of the User and then do a query.
In Mozilla Firefox it works fine also in Safari.... but in Chrome it doesnt work at all.

window.onload = function(){
  if(navigator.geolocation){

    navigator.geolocation.getCurrentPosition(function(position){

        var latitude = position.coords.latitude,
            longitude = position.coords.longitude;
      console.log(latitude + " " + longitude);

    },handleError);

    function handleError(error){
      //Handle Errors
     switch(error.code) {
        case error.PERMISSION_DENIED:
            console.log("User denied the request for Geolocation.");
            break;
        case error.POSITION_UNAVAILABLE:
            console.log("Location information is unavailable.");
            break;
        case error.TIMEOUT:
           console.log("The request to get user location timed out.");
            break;
        case error.UNKNOWN_ERROR:
           console.log("An unknown error occurred.");
            break;
    }
    }
  }else{
    // container.innerHTML = "Geolocation is not Supported for this browser/OS.";
    alert("Geolocation is not Supported for this browser/OS");
  }
};

And i get the error 1

User denied the request for Geolocation.

But i haven't denied any request, actually the popup window doesnt come up at all.

I've went to Chrome Settings > Show advanced > Privacy > Content Settings > Location allow for all.

Restarted chrome and nothing happened. I'm sure my code is 100% legit so does anyone know how to deal with it?
Thanks!


问:
About Node.js Promise then and return?
I'm confused about Promise!

I use Promise then without return like this:

```<code>new Promise((resolve, reject) => {
    resolve("1");
}).then((v1) => {
    console.log("v1");
    new Promise((resolve, reject) => {
        //Time-consuming operation, for example: get data from database;
        setTimeout(() => {
            resolve(2)
        }, 3000);
    }).then((v11) => {
        console.log("v11");
    })
}).then((v2) => {
    console.log("v2")
});
</code>```

I get this result v1 v2 v11.
Then, I use another way of writing, Like below:

```<code> new Promise((resolve, reject) => {
    resolve("1");
}).then((v1) => {
    console.log("v1");
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(2)
        }, 3000)
    }).then((v11) => {
        console.log("v11");
    })
}).then((v2) => {
    console.log("v2")
});
</code>```

I get another result v1 v11 v2.

Maybe, There is another case:

```<code>new Promise((resolve, reject) => {
resolve("1");
}).then((v1) => {
console.log("v1");
return new Promise((resolve, reject) => {
    setTimeout(() => {resolve(2)}, 3000)
}).then((v11) => {
    console.log("v11");
    return new Promise((resolve, reject) => {
        setTimeout(() => {resolve(2)}, 4000)
    }).then(() => {
        console.log("v12")
    })
})
}).then((v2) => {
console.log("v2")
});
</code>```

I get this result v1 v11 v12 v2

I can't understand the second return  I want to know why I get this result?

答:
It will be easier to understand the control flow if you actually print the values of the resolved promises and not only the names of the variables:

Version 1

```<code>new Promise((resolve, reject) => {
    resolve("1");
}).then((v1) => {
    console.log("v1:", v1);
    new Promise((resolve, reject) => {
        //Time-consuming operation, for example: get data from database;
        setTimeout(() => {
            resolve(2)
        }, 3000);
    }).then((v11) => {
        console.log("v11:", v11);
    })
}).then((v2) => {
    console.log("v2:", v2)
});
</code>```

Version 2

```<code>new Promise((resolve, reject) => {
    resolve("1");
}).then((v1) => {
    console.log("v1:", v1);
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(2)
        }, 3000)
    }).then((v11) => {
        console.log("v11:", v11);
    })
}).then((v2) => {
    console.log("v2:", v2)
});
</code>```

Version 3

```<code>new Promise((resolve, reject) => {
        resolve("1");
}).then((v1) => {
       console.log("v1:", v1);
       return new Promise((resolve, reject) => {
           setTimeout(() => {resolve(2)}, 3000)
       }).then((v11) => {
           console.log("v11:", v11);
           return new Promise((resolve, reject) => {
               setTimeout(() => {resolve(2)}, 4000)
           }).then((v12) => {
              console.log("v12:", v12)
           })
       })
 }).then((v2) => {
      console.log("v2:", v2)
 });
</code>```

Now you can see what gets passed to the callbacks:

Result 1

```<code>v1: 1
v2: undefined
v11: 2
</code>```

Result 2

```<code>v1: 1
v11: 2
v2: undefined
</code>```

Result 3

```<code>v1: 1
v11: 2
v12: 2
v2: undefined
</code>```

Explanation

As you can see when in the .then() handlers you don't return a promise, it acts as if you returned an already resolved promise with value undefined - like if you did:

```<code>return Promise.resolve(undefined);
</code>```

and thus the next .then() handler can be called immediately.

If, on the other hand, you return a promise that is not resolved yet, then the next .then() handler will not be invoked immediately but only after that returned promise gets resolved.

And that explains the order of execution that is different when you don't return a promise - and what happens is as if an already resolved promise got returned implicitly for you.

Title: About Node.js Promise then and return?

Body:
I'm confused about Promise!

I use Promise then without return like this:

new Promise((resolve, reject) => {
    resolve("1");
}).then((v1) => {
    console.log("v1");
    new Promise((resolve, reject) => {
        //Time-consuming operation, for example: get data from database;
        setTimeout(() => {
            resolve(2)
        }, 3000);
    }).then((v11) => {
        console.log("v11");
    })
}).then((v2) => {
    console.log("v2")
});

I get this result v1 v2 v11.
Then, I use another way of writing, Like below:

 new Promise((resolve, reject) => {
    resolve("1");
}).then((v1) => {
    console.log("v1");
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(2)
        }, 3000)
    }).then((v11) => {
        console.log("v11");
    })
}).then((v2) => {
    console.log("v2")
});

I get another result v1 v11 v2.

Maybe, There is another case:

new Promise((resolve, reject) => {
resolve("1");
}).then((v1) => {
console.log("v1");
return new Promise((resolve, reject) => {
    setTimeout(() => {resolve(2)}, 3000)
}).then((v11) => {
    console.log("v11");
    return new Promise((resolve, reject) => {
        setTimeout(() => {resolve(2)}, 4000)
    }).then(() => {
        console.log("v12")
    })
})
}).then((v2) => {
console.log("v2")
});

I get this result v1 v11 v12 v2

I can't understand the second return  I want to know why I get this result?

Body:
It will be easier to understand the control flow if you actually print the values of the resolved promises and not only the names of the variables:

Version 1

new Promise((resolve, reject) => {
    resolve("1");
}).then((v1) => {
    console.log("v1:", v1);
    new Promise((resolve, reject) => {
        //Time-consuming operation, for example: get data from database;
        setTimeout(() => {
            resolve(2)
        }, 3000);
    }).then((v11) => {
        console.log("v11:", v11);
    })
}).then((v2) => {
    console.log("v2:", v2)
});

Version 2

new Promise((resolve, reject) => {
    resolve("1");
}).then((v1) => {
    console.log("v1:", v1);
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(2)
        }, 3000)
    }).then((v11) => {
        console.log("v11:", v11);
    })
}).then((v2) => {
    console.log("v2:", v2)
});

Version 3

new Promise((resolve, reject) => {
        resolve("1");
}).then((v1) => {
       console.log("v1:", v1);
       return new Promise((resolve, reject) => {
           setTimeout(() => {resolve(2)}, 3000)
       }).then((v11) => {
           console.log("v11:", v11);
           return new Promise((resolve, reject) => {
               setTimeout(() => {resolve(2)}, 4000)
           }).then((v12) => {
              console.log("v12:", v12)
           })
       })
 }).then((v2) => {
      console.log("v2:", v2)
 });

Now you can see what gets passed to the callbacks:

Result 1

v1: 1
v2: undefined
v11: 2

Result 2

v1: 1
v11: 2
v2: undefined

Result 3

v1: 1
v11: 2
v12: 2
v2: undefined

Explanation

As you can see when in the .then() handlers you don't return a promise, it acts as if you returned an already resolved promise with value undefined - like if you did:

return Promise.resolve(undefined);

and thus the next .then() handler can be called immediately.

If, on the other hand, you return a promise that is not resolved yet, then the next .then() handler will not be invoked immediately but only after that returned promise gets resolved.

And that explains the order of execution that is different when you don't return a promise - and what happens is as if an already resolved promise got returned implicitly for you.

ContentLicense: CC BY-SA 4.0


问:
I cannot use the Color.FromName(string s) method
I need to use the FromName Method, but for some reason it is not available.
I have been googling for a while but I cannot find a solution.

答:
I thinks you also have a reference to System.Windows.Media, hence the IDE is trying to refer to its Color class methods.

Try var c = System.Drawing.Color.FromName("colorname");


问:
Form too Large Exception
When I send a large file using a post request the system shows an exception:

```<code>java.lang.IllegalStateException: Form too large1105723>200000
at org.mortbay.jetty.Request.extractParameters(Request.java:1404)
at org.mortbay.jetty.Request.getParameter(Request.java:749)......
</code>```

When I search help for this in Google they give some help e.g.,
         webappcontext.setMaxFormContentSize(5000000);

I am using this code but the problem is not solved

Also I am using the code
    jettyServer.setAttribute("org.mortbay.jetty.Request.maxFormContentSize", 5000000);

But no result

Note:-I am using Jetty-6.1.0

Title: Form too Large Exception

Body:
When I send a large file using a post request the system shows an exception:

java.lang.IllegalStateException: Form too large1105723>200000
at org.mortbay.jetty.Request.extractParameters(Request.java:1404)
at org.mortbay.jetty.Request.getParameter(Request.java:749)......

When I search help for this in Google they give some help e.g.,
         webappcontext.setMaxFormContentSize(5000000);

I am using this code but the problem is not solved

Also I am using the code
    jettyServer.setAttribute("org.mortbay.jetty.Request.maxFormContentSize", 5000000);

But no result

Note:-I am using Jetty-6.1.0

Body: webappcontext.getServletContext().getContextHandler() .setMaxFormContentSize(10000000);


问:
Import a string value from first loop to second loop in template?
Is it able to import a string value from first loop to second loop in template?

In second loop, "mydata.data.room" should be mydata.A.room, mydata.B.room, mydata.C.room and mydata.D.room

In dictionary

```<code>{'mydata': {u'A': {'room': [u'1-1']},
            u'B': {'room': [u'1-1', u'1-2']},
            u'C': {'room': [u'1-1', u'1-2', u'1-3']},
            u'D': {'room': [u'1-1']}}
</code>```

In template

```<code>{% for data in mydata %}
    <div id="{{ data }}" class="tab-pane fade">
    {% for room in mydata.data.room  %}
            <h3>{{ room }}</h3>
            <p>Some content.</p>
    {% endfor %}
    </div>
{% endfor %}
</code>```

答:
Your code won't work. I'm guessing that what you want to do is:

In the python code:

```<code>mydict = {'mydata': {u'A': {'room': [u'1-1']},
        u'B': {'room': [u'1-1', u'1-2']},
        u'C': {'room': [u'1-1', u'1-2', u'1-3']},
        u'D': {'room': [u'1-1']}}
</code>```

In the template code:

```<code>{% for key, data in mydict.mydata.items %}
        <div id="{{ key }}" class="tab-pane fade">
        {% for room in data.room  %}
                <h3>{{ room }}</h3>
                <p>Some content.</p>
        {% endfor %}
        </div>
{% endfor %}
</code>```

Body:
Is it able to import a string value from first loop to second loop in template?

In second loop, "mydata.data.room" should be mydata.A.room, mydata.B.room, mydata.C.room and mydata.D.room

In dictionary

{'mydata': {u'A': {'room': [u'1-1']},
            u'B': {'room': [u'1-1', u'1-2']},
            u'C': {'room': [u'1-1', u'1-2', u'1-3']},
            u'D': {'room': [u'1-1']}}

In template

{% for data in mydata %}

    {% for room in mydata.data.room  %}

{{ room }}

Some content.

    {% endfor %}

{% endfor %}

Body:
Your code won't work. I'm guessing that what you want to do is:

In the python code:

mydict = {'mydata': {u'A': {'room': [u'1-1']},
        u'B': {'room': [u'1-1', u'1-2']},
        u'C': {'room': [u'1-1', u'1-2', u'1-3']},
        u'D': {'room': [u'1-1']}}

In the template code:

{% for key, data in mydict.mydata.items %}
        <div id="{{ key }}" class="tab-pane fade">
        {% for room in data.room  %}
                <h3>{{ room }}</h3>
                <p>Some content.</p>
        {% endfor %}
        </div>
{% endfor %}


问:
RStudio R Presentation Preview Error
I am trying to create an R Presentation in RStudio (File > New File > R Presentation). But when I try to create one with my working directory set to anything other than my default, I receive an error when it tries to preview.

The error displays in the preview panel just beneath the title where the author and date should be, and it says "Error in readLines(if (is.character(input2)) { : cannot open the connection". There are also no other slides that can be displayed even though there should be four from the default template.

I've searched all over but I haven't been able to find anyone with this issue. Anyone have an idea what might be causing this?

I'm running:

Windows 7 Professional

RStudio v0.99.903

答:
I guess, reinstalling is not necessary. I found that the error is most likely related to setting a working directory in .Rprofile or related files via setwd().

When I changed the critical line in my .Rprofile to

```<code>if(interactive()) setwd(<my preferred working directory>)
</code>```

it worked.

I think the .Rprofile file influences the R processes needed for creating the presentation in the background, too. If these processes are always set to your standard working directory, they cannot find the relevant files there. That also explains why it works when you put the presentation into your standard working directory.

EDIT: The line above works because interactive() is FALSE for these background processes I was talking about. So, for those, the setwd() is not called.

Title: RStudio R Presentation Preview Error

Body:
I guess, reinstalling is not necessary. I found that the error is most likely related to setting a working directory in .Rprofile or related files via setwd().

When I changed the critical line in my .Rprofile to

if(interactive()) setwd(<my preferred working directory>)

it worked.

I think the .Rprofile file influences the R processes needed for creating the presentation in the background, too. If these processes are always set to your standard working directory, they cannot find the relevant files there. That also explains why it works when you put the presentation into your standard working directory.

EDIT: The line above works because interactive() is FALSE for these background processes I was talking about. So, for those, the setwd() is not called.


问:
What are the differences between Talend openstudio and Enterprise edition..??
I really want the Differences between Talend open studio and Enterprise edition

What are the differences between Talend open studio and Enterprise edition..??
can you provide me in brief??

Thanks in Advance..

答:
Having used both products I can tell you there are two primary differences:

the paid version comes with the Talend Administration Center (TAC) which is a job scheduler.  It allows you to schedule jobs, setup dependencies, monitor and view logs.  It also allows you to centrally provision developer access and other roles (e.g. admin or operator to setup and monitor jobs).

The logging feature it is vital if you are seriously using the product for mission critical jobs.  You can setup recovery points in your job and if they fail re-run them in the TAC from the recovery point (a really cool feature).

It also allows you easily hook up to an SVN (or GIT) repository for version control, team collaboration, and code moves.  (I suspect you may be able to configure SVN access without enterprise version but it comes out of the box with enterprise).

There are some other more minor differences including a few components that are only available in the paid version.


问:
Loading data from a silent remote notification
I have an app that receives silent pushes when it's inactive via the -[AppDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:]. The push payload contains a url that I need to prefetch so that the data is ready on next app start.

The app needs to call the completionHandler when the downloads finishes:

The block to execute when the download operation is complete. When calling this block, pass in the fetch result value that best describes the results of your download operation. You must call this handler and should do so as soon as possible. For a list of possible values, see the UIBackgroundFetchResult type.

The question is whether I can do a simple NSURLSession request or if I'm supposed to do the fetch using one of the background fetch as described here

Option 1: Use a simple NSURLSession and call the callback

```<code>- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    NSURL *url = [NSURL URLWithString:userInfo[@"my-data-url"]];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        // save the result & call the
        completionHandler(data ? UIBackgroundFetchResultNewData : UIBackgroundFetchResultNoData);

    }];
    [task resume];
}
</code>```

Option 2: Use extra background handling for downloading the content

```<code>- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    NSURLSessionDataTask *task;

    __block UIBackgroundTaskIdentifier backgroundId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

        // time's up, cancel the download

        [application endBackgroundTask:backgroundId];
        backgroundId = UIBackgroundTaskInvalid;
        completionHandler(UIBackgroundFetchResultFailed);

        [task cancel];

    }];

    NSURL *url = [NSURL URLWithString:userInfo[@"my-data-url"]];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        // check if time was up
        if(backgroundId == UIBackgroundTaskInvalid) {
            return;
        }

        [application endBackgroundTask:backgroundId];
        backgroundId = UIBackgroundTaskInvalid;

        // save the result & call the
        completionHandler(data ? UIBackgroundFetchResultNewData : UIBackgroundFetchResultNoData);

    }];
    [task resume];
}
</code>```

答: So to answer my own question, after some testing, it appears the Option 2 works quite well. I can download whatever data I need using the UIBackgroundTaskIdentifier. If I don't use it, the download fails

Body:
I have an app that receives silent pushes when it's inactive via the -[AppDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:]. The push payload contains a url that I need to prefetch so that the data is ready on next app start.

The app needs to call the completionHandler when the downloads finishes:

The block to execute when the download operation is complete. When calling this block, pass in the fetch result value that best describes the results of your download operation. You must call this handler and should do so as soon as possible. For a list of possible values, see the UIBackgroundFetchResult type.

The question is whether I can do a simple NSURLSession request or if I'm supposed to do the fetch using one of the background fetch as described here

Option 1: Use a simple NSURLSession and call the callback

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    NSURL *url = [NSURL URLWithString:userInfo[@"my-data-url"]];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        // save the result & call the
        completionHandler(data ? UIBackgroundFetchResultNewData : UIBackgroundFetchResultNoData);

    }];
    [task resume];
}

Option 2: Use extra background handling for downloading the content

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    NSURLSessionDataTask *task;

    __block UIBackgroundTaskIdentifier backgroundId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

        // time's up, cancel the download

        [application endBackgroundTask:backgroundId];
        backgroundId = UIBackgroundTaskInvalid;
        completionHandler(UIBackgroundFetchResultFailed);

        [task cancel];

    }];

    NSURL *url = [NSURL URLWithString:userInfo[@"my-data-url"]];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        // check if time was up
        if(backgroundId == UIBackgroundTaskInvalid) {
            return;
        }

        [application endBackgroundTask:backgroundId];
        backgroundId = UIBackgroundTaskInvalid;

        // save the result & call the
        completionHandler(data ? UIBackgroundFetchResultNewData : UIBackgroundFetchResultNoData);

    }];
    [task resume];
}