问:
Inline styles not preserved in wordpress table
Our company has developed some very simple table-based clickable html email signatures for clients to use, and we want to showcase them as being clickable on http://scottleroymarketing.com/email-signature but as you can tell...they're not showing up very well.

Setting aside using tables for layout and inline CSS versus a stylesheet (both of which are the easiest way we've found to work within email providers, especially Gmail/GSuite which is what most of our clients use), is there anything within wordpress that would override/mess up the inline styling of the tables? Inline styles trump global CSS from the theme, as far as I'm aware, but there might be exceptions that I don't know about. I'm pretty inexperienced with Wordpress, so I may have been googling the wrong thing (I've looked for "wordpress table styles" and "wordpress inline styles" but all I've found is tutorials for how to apply styles to tables, and fixes for the html/rich text editor not showing on the page). We can screenshot the template as it's supposed to display, and put that on the page, but we'd rather demonstrate how the elements are all clickable versus an image block signature, if possible.

I've previewed the page on Chrome and Firefox, and I figure it will look essentially the same on other browsers since all of the elements I used render about the same on each browser. I'm not sure what version of Wordpress we're using, or how to find it.

Here's the code for the second signature shown on that page, already having been tweaked so that at least the columns are somewhat the correct width:

```<code><!-- Begin Signature #2 !-->
<div class="slmsignature1">
<table style="width: 80%; max-width: 700px; min-width: 300px; border: none; border-collapse: collapse; background: url('http://i.imgur.com/SizXUrg.jpg'); background-color: black; color: #fff; font-family:sans-serif;">
    <tbody>
        <tr>
            <td style="width: 200px; font-family:'Gill Sans MT', Tahoma, sans-serif;">
                <img style="width: 100%; max-width: 195px; margin: 0px;" src="http://i.imgur.com/ectryVc.jpg" alt="Scott Le Roy's Head Shot" />
            </td>
            <td style="vertical-align: bottom; font-family:'Gill Sans MT', Tahoma, sans-serif;">
                <img style="max-width: 160px;" src="http://i.imgur.com/Uns6X52.png" alt="Keller Williams Logo" />
                <p style="font-size: 6pt; margin-bottom: 0px;">
                    Each Keller Williams Office
                    <br />
                    Is Independently Owned And Operated
                </p>
            </td>
            <td style="vertical-align: top; text-align: right; font-family:'Gill Sans MT', Tahoma, sans-serif;" colspan="2">
                <h1 style="font-family: sans-serif; margin: 0px 5px 0px 0px;">
                    Scott Le Roy
                </h1>
                <h2 style="font-family: sans-serif; font-size: 15px; margin: 0px 5px 5px 0px;">
                    CEO/Digital Marketer
                </h2>
                <p style="margin: 0px 5px 0px 0px;">
                    <a style="color: #fff; text-decoration: none;" href="tel:123-456-7890">
                         C: 123-456-7890
                    </a>
                </p>
                <p style="margin: 0px 5px 0px 0px;">
                    <a style="color: #fff; text-decoration: none;" href="tel:321-654-0987">
                         O: 321-654-0987
                    </a>
                </p>
                <p style="margin: 5px 5px 0px 0px;">
                    <a style="color: #fff; text-decoration: none;" href="mailto:scott@scottleroymarketing.com">
                         Scott@ScottLeRoyMarketing.com
                    </a>
                </p>
                <p style="margin: 0px 5px 0px 0px;">
                    <a style="color: #fff; text-decoration: none;" href="http://scottleroymarketing.com">
                         www.ScottLeRoyMarketing.com
                    </a>
                </p>
            </td>
        </tr>
        <tr style="height: 25px; text-decoration:none; font-size:8pt;">
            <td style="text-align: right; font-family:'Gill Sans MT', Tahoma, sans-serif;">
                <a href="https://www.facebook.com/groups/scottleroymarketing/">
                    <img style="height: 25px; margin: 0px 2px 0px 2px;" src="http://i.imgur.com/ES2mp6u.png" alt="Facebook Icon" />
                </a>
                <a href="https://www.twitter.com/">
                    <img style="height: 25px; margin: 0px 2px 0px 2px;" src="http://i.imgur.com/E2iChYF.png" alt="Twitter Icon" />
                </a>
                <a href="https://www.pinterest.com/">
                    <img style="height: 25px; margin: 0px 2px 0px 2px;" src="http://i.imgur.com/dJARSqo.png" alt="Pinterest Icon" />
                </a>
                <a href="https://www.linkedin.com/">
                    <img style="height: 25px; margin: 0px 2px 0px 2px;" src="http://i.imgur.com/Ucw1EDq.png" alt="Linkedin Icon" />
                </a>
                <a href="https://www.instagram.com/">
                    <img style="height: 25px; margin: 0px 2px 0px 2px;" src="http://i.imgur.com/lFx5fpA.png" alt="Instagram Icon" />
                </a>
            </td>
            <td style="text-align: center; width 40%; font-family:'Gill Sans MT', Tahoma, sans-serif;">
                123 E. Main St #201
                <span style="color: #b40101;">
                    |
                </span>
                 Anytown, VA 12345
            </td>
            <td>
                Another Placeholder
            </td>
        </tr>
    </tbody>
</table>
</code>```

Update: I played around some more and it looks like the Wordpress "Text"/code editor is treating line breaks in the code as line breaks in the content as well, and removing
 tags. I've updated the linked page to show that change, but the "Visual" editor is showing it differently than the live page. Ugh.

Screenshot of the "Visual" editor in Wordpress

Screenshot of the actual live page

Solved

Ho-lee hell that was something else. You have to be super duper specific with your markup in wordpress, for each individual  and everything, or else it will try to apply the default styles to that data, even if you told it not to in the actual table itself. Good thing email services aren't like this...

Anyway, the final verdict is to use a plugin that allows you to disable the "wpautop" plugin for the page so that it doesn't convert line breaks in the code to
 when it renders, then the "Don't Muck My Markup" plugin to have it not convert
 to those same line breaks.

Final code block for that signature that is displaying pretty much properly on http://scottleroymarketing.com/email-signature (second one):

```<code><!-- Begin Signature #2 !-->

<div class="slmsignature1">
    <table style="width: 80%; max-width: 700px; min-width: 300px; border: none; border-collapse: collapse; background: url('http://i.imgur.com/SizXUrg.jpg'); background-color: black; color: #fff; font-family:sans-serif;">
        <tbody>
            <tr>
                <td style="width: 200px; font-family:'Gill Sans MT', Tahoma, sans-serif; border:none;">
                    <img style="width: 100%; max-width: 195px; margin: 0px;" src="http://i.imgur.com/ectryVc.jpg" alt="Scott Le Roy's Head Shot" />
                </td>
                <td style="vertical-align: bottom; font-family:'Gill Sans MT', Tahoma, sans-serif; border:none;">
                    <img style="max-width: 160px;" src="http://i.imgur.com/Uns6X52.png" alt="Keller Williams Logo" />
                    <p style="font-size: 6pt; margin-bottom: 0px;">
                        Each Keller Williams Office
                        <br />
                        Is Independently Owned And Operated
                    </p>
                </td>
                <td style="vertical-align: top; text-align: right; font-family:'Gill Sans MT', Tahoma, sans-serif; border:none;" colspan="2">
                    <h1 style="font-family: sans-serif; margin: -5px 5px 0px 0px;">
                        Scott Le Roy
                    </h1>
                    <h2 style="font-family: sans-serif; font-size: 15px; margin: -5px 5px 5px 0px;">
                        CEO/Digital Marketer
                    </h2>
                    <p style="margin: -5px 5px 0px 0px;">
                        <a style="color: #fff; text-decoration: none;" href="tel:123-456-7890">
                             C: 123-456-7890
                        </a>
                    </p>
                    <p style="margin: -5px 5px 0px 0px;">
                        <a style="color: #fff; text-decoration: none;" href="tel:321-654-0987">
                             O: 321-654-0987
                        </a>
                    </p>
                    <p style="margin: -5px 5px 0px 0px;">
                        <a style="color: #fff; text-decoration: none;" href="mailto:scott@scottleroymarketing.com">
                             Scott@ScottLeRoyMarketing.com
                        </a>
                    </p>
                    <p style="margin: -5px 5px 0px 0px;">
                        <a style="color: #fff; text-decoration: none;" href="http://scottleroymarketing.com">
                             www.ScottLeRoyMarketing.com
                        </a>
                    </p>
                </td>
            </tr>
            <tr style="height: 25px; width: 200px;text-decoration:none; font-size:8pt;">
                <td style="text-align: right; font-family:'Gill Sans MT', Tahoma, sans-serif; border:none;">
<table style="border:none; border-collapse:collapse; padding:0px; margin:0px;">
<tr>
<td style="padding:0px;border:none;">
<a href="https://www.facebook.com/groups/scottleroymarketing/"><img style="height: 25px; margin: 0px 2px 0px 2px;" src="http://i.imgur.com/ES2mp6u.png" alt="Facebook Icon" /></a>
</td>
<td style="padding:0px;border:none;">
<a href="https://www.twitter.com/"><img style="height: 25px; margin: 0px 2px 0px 2px;" src="http://i.imgur.com/E2iChYF.png" alt="Twitter Icon" /></a>
</td>
<td style="padding:0px;border:none;">
<a href="https://www.pinterest.com/"><img style="height: 25px; margin: 0px 2px 0px 2px;" src="http://i.imgur.com/dJARSqo.png" alt="Pinterest Icon" /></a>
</td>
<td style="padding:0px;border:none;">
<a href="https://www.linkedin.com/"><img style="height: 25px; margin: 0px 2px 0px 2px;" src="http://i.imgur.com/Ucw1EDq.png" alt="Linkedin Icon" /></a>
</td>
<td style="padding:0px;border:none;">
<a href="https://www.instagram.com/"><img style="height: 25px; margin: 0px 2px 0px 2px;" src="http://i.imgur.com/lFx5fpA.png" alt="Instagram Icon" /></a>
</td>
</tr>
</table>
                </td>
                <td colspan="2" style="text-align: center; font-family:'Gill Sans MT', Tahoma, sans-serif; border:none;">
                    123 E. Main St #201 <span style="color: #b40101;">|</span> Anytown, VA 12345
                </td>

            </tr>
        </tbody>
    </table>
</div>

<!-- End Signature #2 !-->
</code>```

答:
The final verdict is to use a plugin (there are several) that allows you to disable the "wpautop" plugin for the page so that it doesn't convert line breaks in the code in the "Text" editor to
 when it renders, then the "Don't Muck My Markup" plugin to have it not convert
 to those same line breaks.

The other thing is that you have to go into each  element and tell it to not show borders, etc, because Wordpress (evidently) ignores

Body:
Our company has developed some very simple table-based clickable html email signatures for clients to use, and we want to showcase them as being clickable on http://scottleroymarketing.com/email-signature but as you can tell...they're not showing up very well.

Setting aside using tables for layout and inline CSS versus a stylesheet (both of which are the easiest way we've found to work within email providers, especially Gmail/GSuite which is what most of our clients use), is there anything within wordpress that would override/mess up the inline styling of the tables? Inline styles trump global CSS from the theme, as far as I'm aware, but there might be exceptions that I don't know about. I'm pretty inexperienced with Wordpress, so I may have been googling the wrong thing (I've looked for "wordpress table styles" and "wordpress inline styles" but all I've found is tutorials for how to apply styles to tables, and fixes for the html/rich text editor not showing on the page). We can screenshot the template as it's supposed to display, and put that on the page, but we'd rather demonstrate how the elements are all clickable versus an image block signature, if possible.

I've previewed the page on Chrome and Firefox, and I figure it will look essentially the same on other browsers since all of the elements I used render about the same on each browser. I'm not sure what version of Wordpress we're using, or how to find it.

Here's the code for the second signature shown on that page, already having been tweaked so that at least the columns are somewhat the correct width:

                    Each Keller Williams Office

                    Is Independently Owned And Operated

                    Scott Le Roy

                    CEO/Digital Marketer

                         C: 123-456-7890

                         O: 321-654-0987

                         Scott@ScottLeRoyMarketing.com

                         www.ScottLeRoyMarketing.com

                123 E. Main St #201

                    |

                 Anytown, VA 12345

                Another Placeholder

Update: I played around some more and it looks like the Wordpress "Text"/code editor is treating line breaks in the code as line breaks in the content as well, and removing
 tags. I've updated the linked page to show that change, but the "Visual" editor is showing it differently than the live page. Ugh.

Screenshot of the "Visual" editor in Wordpress

Screenshot of the actual live page

Solved

Ho-lee hell that was something else. You have to be super duper specific with your markup in wordpress, for each individual  and everything, or else it will try to apply the default styles to that data, even if you told it not to in the actual table itself. Good thing email services aren't like this...

Anyway, the final verdict is to use a plugin that allows you to disable the "wpautop" plugin for the page so that it doesn't convert line breaks in the code to
 when it renders, then the "Don't Muck My Markup" plugin to have it not convert
 to those same line breaks.

Final code block for that signature that is displaying pretty much properly on http://scottleroymarketing.com/email-signature (second one):

                        Each Keller Williams Office

                        Is Independently Owned And Operated

                        Scott Le Roy

                        CEO/Digital Marketer

                             C: 123-456-7890

                             O: 321-654-0987

                             Scott@ScottLeRoyMarketing.com

                             www.ScottLeRoyMarketing.com

                    123 E. Main St #201 | Anytown, VA 12345

Body:
The final verdict is to use a plugin (there are several) that allows you to disable the "wpautop" plugin for the page so that it doesn't convert line breaks in the code in the "Text" editor to <br /> when it renders, then the "Don't Muck My Markup" plugin to have it not convert <br /> to those same line breaks.

The other thing is that you have to go into each <td> element and tell it to not show borders, etc, because Wordpress (evidently) ignores <style> elements added to the "Text" editor so you can't apply a style to all <td>s, you have to do them each individually :-/

And in the social media icons shown in the bottom left (of the particular signature noted in this post), just adding them to that table cell with the <a> and <img> tags won't show them inline like it's supposed to, you have to create another <table> within that cell, and make each icon its own <td> in the same <tr> with no padding, also remembering to do "border:none;" on each <td>.

Props to @ihazcode for pointing me in the direction of the "Don't Muck My Markup" plugin!


来源: stackexchange

问:
ngrok not working correctly to test HTTPs
I downloaded ngrok so i can test my site for http and https requests (if someone is trying to get in my site specific url and it will be a simple http request, i will deny it),

first, my localhost is working in 8080 port

I start ngrok, it gives me the following:

both at the same port, it's a problem i think, because if i do such simple route configuration in laravel:

```<code>Route::filter('force.ssl', function()
{
    if( ! Request::secure())
    {
        return 'unsecured';
    }

});
</code>```

and i have this route:

```<code>Route::get('survey/payment/secured', array('before' => 'force.ssl', function(){
   return 'secured!';
}));
</code>```

and i do the following request:

https://75fdaa96.ngrok.com/survey/payment/secured

it thinks it unsecured and returns 'unsecured', how can i fix this?

答:
Request::secure() relies on $_SERVER['HTTPS']. As the HTTPS is being provided by the proxy, not your webserver, Laravel doesn't know it's being served as HTTPS.

ngrok does pass the X-Forwarded-Proto header, but Laravel doesn't trust it by default.  You can use the trusted proxy middleware to trust it.

ContentLicense: CC BY-SA 3.0

Body:
I downloaded ngrok so i can test my site for http and https requests (if someone is trying to get in my site specific url and it will be a simple http request, i will deny it),

first, my localhost is working in 8080 port

I start ngrok, it gives me the following:

both at the same port, it's a problem i think, because if i do such simple route configuration in laravel:

Route::filter('force.ssl', function()
{
    if( ! Request::secure())
    {
        return 'unsecured';
    }

});

and i have this route:

Route::get('survey/payment/secured', array('before' => 'force.ssl', function(){
   return 'secured!';
}));

and i do the following request:

https://75fdaa96.ngrok.com/survey/payment/secured

it thinks it unsecured and returns 'unsecured', how can i fix this?


问:
How would I parse an XML file into a list
List:

```<code>List<string> list = new List<string>();
</code>```

XML File:

```<code><memberlist>
 <member>
  <name>Name</name>
  <status>Status</status>
 </member>
</memberlist>
</code>```

How would I go about parsing this file, lets say (file.xml) into the list?

I've tried many ways but none of them seem to be working.

I want to check to see if the status is 'gold', and if it is, I would like to put the name of that member into the list.

答:
Load the xml into an XDocument. You can do this from a file, I have demonstrated from a string.

Do a linq query for elements named "status" (within "member") that also have a value of "gold".

Of those, grab the value of the "name" element.

Use AddRange on your list of strings.

```<code>List<string> lstGolds = new List<string>();

string xml ="<memberlist><member><name>Name</name><status>gold</status></member></memberlist>";
XDocument doc = XDocument.Parse(xml);

var goldStatus = doc.Descendants("member")
    .Where(d => d.Element("status").Value == "gold")
    .Select(d => d.Element("name").Value);

lstGolds.AddRange(goldStatus);
</code>```

Body:
List:

List<string> list = new List<string>();

XML File:

<memberlist>
 <member>
  <name>Name</name>
  <status>Status</status>
 </member>
</memberlist>

How would I go about parsing this file, lets say (file.xml) into the list?

I've tried many ways but none of them seem to be working.

I want to check to see if the status is 'gold', and if it is, I would like to put the name of that member into the list.

Body:
Load the xml into an XDocument. You can do this from a file, I have demonstrated from a string.

Do a linq query for elements named "status" (within "member") that also have a value of "gold".

Of those, grab the value of the "name" element.

Use AddRange on your list of strings.

List<string> lstGolds = new List<string>();

string xml ="<memberlist><member><name>Name</name><status>gold</status></member></memberlist>";
XDocument doc = XDocument.Parse(xml);

var goldStatus = doc.Descendants("member")
    .Where(d => d.Element("status").Value == "gold")
    .Select(d => d.Element("name").Value);

lstGolds.AddRange(goldStatus);


问:
Clipboard SetText fails whereas SetDataObject does not
I was trying to copy a string to the clipboard via

```<code>System.Windows.Clipboard.SetText(someString);
</code>```

and it was failing (Clearing before setting before setting did not work because Clear also needs to open the clipboard). The call to GetOpenClipboardWindow() indicated that some window was keeping the clipboard open (in this case it was notepad++).

By changing the above line to:

```<code>System.Windows.Clipboard.SetDataObject(someString);
</code>```

the call succeeds every time and the contents of the clipboard are what I expect.

Does anybody have an explanation for this behaviour?

The documentation does not state much about what it does differently (except for clearing the clipboard when the program exits).

答:
From MSDN

Clipboard.SetDataObject() :
This method attempts to set the data ten times in 100-millisecond intervals, and throws an ExternalException if all attempts are unsuccessful.

Clipboard.SetText(): Clears the Clipboard and then adds text data to it.

Body:
I was trying to copy a string to the clipboard via

System.Windows.Clipboard.SetText(someString);

and it was failing (Clearing before setting before setting did not work because Clear also needs to open the clipboard). The call to GetOpenClipboardWindow() indicated that some window was keeping the clipboard open (in this case it was notepad++).

By changing the above line to:

System.Windows.Clipboard.SetDataObject(someString);

the call succeeds every time and the contents of the clipboard are what I expect.

Does anybody have an explanation for this behaviour?

The documentation does not state much about what it does differently (except for clearing the clipboard when the program exits).


问:
How do I get Groovy String.replace to remove a substring with unknown digits?
I have a Groovy String s that contains a String variable name and follows a pattern like this:

```<code>name = "{someInformation}"
s = "0/$name|2/{moreInformation}|3/$name"
</code>```

I'm trying to remove \d+/{someInformation}|* (both cases of it) from the string, but this doesn't work because \d+/{someInformation}|* is not the right pattern to match.

The following does not work:

```<code>s = s.replace ("\\d+/$name|", "")
</code>```

because s.contains("\\d+/$name|") returns false.  But I have been fiddling with the regular expression for a while now and I don't seem to be able to get it to match.

What do I need to put into my String.replace regex so that it can find and remove the parts, such that all I have left is

```<code>s == "2/{moreInformation}"
</code>```

答:
You may use the following regex based solution:

```<code>def name = "{someInformation}"
def s = "0/$name|2/{moreInformation}|3/$name"
println(s) // => 0/{someInformation}|2/{moreInformation}|3/{someInformation}
// => 0/{someInformation}|2/{moreInformation}|3/{someInformation}
def pat = "\\|*\\d+/${java.util.regex.Pattern.quote(name)}\\|*"
println(pat) // => \|*\d+/\Q{someInformation}\E\|*
println(s.replaceAll(pat, ""))
// => 2/{moreInformation}
</code>```

See the Groovy demo

Here is the generated regex demo. Note that ${java.util.regex.Pattern.quote(name)} is used to escape all special regex metacharacters inside the name variable so that they were treated as literal symbols by the regex engine.

Details

\|* - 0+ | chars

\d+ - 1+ digits

/ - a / char

\Q{someInformation}\E - a literal {someInformation} substring

\|* - 0+ | chars

Body:
I have a Groovy String s that contains a String variable name and follows a pattern like this:

name = "{someInformation}"
s = "0/$name|2/{moreInformation}|3/$name"

I'm trying to remove \d+/{someInformation}|* (both cases of it) from the string, but this doesn't work because \d+/{someInformation}|* is not the right pattern to match.

The following does not work:

s = s.replace ("\\d+/$name|", "")

because s.contains("\\d+/$name|") returns false.  But I have been fiddling with the regular expression for a while now and I don't seem to be able to get it to match.

What do I need to put into my String.replace regex so that it can find and remove the parts, such that all I have left is

s == "2/{moreInformation}"

Body:
You may use the following regex based solution:

def name = "{someInformation}"
def s = "0/$name|2/{moreInformation}|3/$name"
println(s) // => 0/{someInformation}|2/{moreInformation}|3/{someInformation}
// => 0/{someInformation}|2/{moreInformation}|3/{someInformation}
def pat = "\\|*\\d+/${java.util.regex.Pattern.quote(name)}\\|*"
println(pat) // => \|*\d+/\Q{someInformation}\E\|*
println(s.replaceAll(pat, ""))
// => 2/{moreInformation}

See the Groovy demo

Here is the generated regex demo. Note that ${java.util.regex.Pattern.quote(name)} is used to escape all special regex metacharacters inside the name variable so that they were treated as literal symbols by the regex engine.

Details

\|* - 0+ | chars

\d+ - 1+ digits

/ - a / char

\Q{someInformation}\E - a literal {someInformation} substring

\|* - 0+ | chars


问:
printing out data from ajax
So this is the first time ive used ajax with rails, Ive managed to get the "data" back from the controller... how do i now print this out on the page? Im finding information on ajax online but 9 cant find any code the same as mine to reference?

The code changes the order in which details are displayed ASC to DESC.

JS FILE

```<code>  $(".ord-dir-link").on("click", function(e){
    e.preventDefault();
      $.ajax({
        url: '/index_list',
        method: 'get',
        data: jQuery.param({
        option: this.href.split("=")[2],
        direction: $('.list-direction').val()
        }),
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        success: function(data){
          console.log(data)
        }
      })
  });
</code>```

CONTROLLER

```<code>    def index_list
      if params[:option]
        @products = @products.order("#{params[:option]} #{params[:direction]}")
        respond_to do |format|
        format.json { render json: @products.to_json }
        end
      end
    end
</code>```

AND THE VIEW

```<code>    <div class="right-content">
      <table class="index-list">
        <tr>
          <th>Id</th>
          <th><%= link_to "Name", index_list_path(option: "product_name"), class: "ord-dir-link"%></th>
          <th><%= link_to "Type", index_list_path(option: "type_of_product"), class: "ord-dir-link" %></th>
          <th><%= link_to "Section", index_list_path(option: "section"), class: "ord-dir-link" %></th>
          <th><%= link_to "Category", index_list_path(option: "category"), class: "ord-dir-link" %></th>
          <th><%= link_to "Price", index_list_path(option: "price"), class: "ord-dir-link" %></th>
          <th><%= link_to "Discount", index_list_path(option: "discount"), class: "ord-dir-link" %></th>
          <th><%= link_to "Views", index_list_path(option: "click_counter"), class: "ord-dir-link" %></th>
          <th><%= link_to "Upvotes", index_list_path(option: "upvotes"), class: "ord-dir-link" %></th>
          <th><%= select_tag(:direction, options_for_select([ ['ASC', "ASC"], ['DESC', "DESC"]] ), {:class => 'list-direction'})  %></th>
        </tr>
        <% n = 1 %>
        <% @products.each do |x| %>
        <tr>
          <td><%=n%>.</td>
          <td><%=x.product_name%></td>
          <td><%=x.type_of_product%></td>
          <td><%=x.section%></td>
          <td><%=x.category%></td>
          <td>£<%=x.price%></td>
          <td><%=x.discount if x.discount != nil%></td>
          <td><%=x.click_counter%></td>
          <td><%=x.upvotes%></td>
          <td><%=link_to "View", product_path(x.id)%></td>
          <% n += 1 %>
          <%end%>
        </tr>
      </table>
    </div>
</code>```

Do i need to append the whole thing written out in javascript? it seems kind of long and clunky way to do it.

答:
Just to expand on what Taplar said, you would do something like:</p>

```<code>$(".ord-dir-link").on("click", function(e){
  e.preventDefault();
    $.ajax({
      url: '/index_list',
      method: 'get',
      data: jQuery.param({
      option: this.href.split("=")[2],
      direction: $('.list-direction').val()
      }),
      contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
      success: function(data){
        $('#some-selector').html(data)
      }
    })
});
</code>```

Title: printing out data from ajax

Body:
So this is the first time ive used ajax with rails, Ive managed to get the "data" back from the controller... how do i now print this out on the page? Im finding information on ajax online but 9 cant find any code the same as mine to reference?

The code changes the order in which details are displayed ASC to DESC.

JS FILE

  $(".ord-dir-link").on("click", function(e){
    e.preventDefault();
      $.ajax({
        url: '/index_list',
        method: 'get',
        data: jQuery.param({
        option: this.href.split("=")[2],
        direction: $('.list-direction').val()
        }),
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        success: function(data){
          console.log(data)
        }
      })
  });

CONTROLLER

    def index_list
      if params[:option]
        @products = @products.order("#{params[:option]} #{params[:direction]}")
        respond_to do |format|
        format.json { render json: @products.to_json }
        end
      end
    end

AND THE VIEW

          Id
          <%= link_to "Name", index_list_path(option: "product_name"), class: "ord-dir-link"%>
          <%= link_to "Type", index_list_path(option: "type_of_product"), class: "ord-dir-link" %>
          <%= link_to "Section", index_list_path(option: "section"), class: "ord-dir-link" %>
          <%= link_to "Category", index_list_path(option: "category"), class: "ord-dir-link" %>
          <%= link_to "Price", index_list_path(option: "price"), class: "ord-dir-link" %>
          <%= link_to "Discount", index_list_path(option: "discount"), class: "ord-dir-link" %>
          <%= link_to "Views", index_list_path(option: "click_counter"), class: "ord-dir-link" %>
          <%= link_to "Upvotes", index_list_path(option: "upvotes"), class: "ord-dir-link" %>
          <%= select_tag(:direction, options_for_select([ ['ASC', "ASC"], ['DESC', "DESC"]] ), {:class => 'list-direction'})  %>

        <% n = 1 %>
        <% @products.each do |x| %>

          <%=n%>.
          <%=x.product_name%>
          <%=x.type_of_product%>
          <%=x.section%>
          <%=x.category%>
          £<%=x.price%>
          <%=x.discount if x.discount != nil%>
          <%=x.click_counter%>
          <%=x.upvotes%>
          <%=link_to "View", product_path(x.id)%>
          <% n += 1 %>
          <%end%>

Do i need to append the whole thing written out in javascript? it seems kind of long and clunky way to do it.

Body:
Just to expand on what Taplar said, you would do something like:

$(".ord-dir-link").on("click", function(e){
  e.preventDefault();
    $.ajax({
      url: '/index_list',
      method: 'get',
      data: jQuery.param({
      option: this.href.split("=")[2],
      direction: $('.list-direction').val()
      }),
      contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
      success: function(data){
        $('#some-selector').html(data)
      }
    })
});


问:
Angular Flex Directives Re Usability
I am having an angular 4 application which uses angular flex for layouts instead of Bootstrap.

But for alignments in each div tag I have to give:

```<code> fxLayout.xs="column"
 fxLayout="row"
 fxLayoutAlign="start center"
 fxLayoutGap="18px"
</code>```

Can anyone suggest how to reuse these directives instead of writing it for each tag?

答:
You can use the host property from the @Directive decorator.

Create a Directive and add those directives to the host property. Example:

```<code>@Directive({
  selector: '[reusable]',
  host: {
    '[hidden]': 'hidden'
  }
})
export class ReusableDirective {

  hidden = true;

}
</code>```

Title: Angular Flex Directives Re Usability

Body:
I am having an angular 4 application which uses angular flex for layouts instead of Bootstrap.

But for alignments in each div tag I have to give:

 fxLayout.xs="column"
 fxLayout="row"
 fxLayoutAlign="start center"
 fxLayoutGap="18px"

Can anyone suggest how to reuse these directives instead of writing it for each tag?

Body:
You can use the host property from the @Directive decorator.

Create a Directive and add those directives to the host property. Example:

@Directive({
  selector: '[reusable]',
  host: {
    '[hidden]': 'hidden'
  }
})
export class ReusableDirective {

  hidden = true;

}


问:
Spark missing column when write and read back
I am creating a dataset and writing it to s3 in a directory structure ${BasePath}/y=2107/m=11/d=16/ in parquet format. After I creates current day data and writes it to s3, I need to read back the data for last 10 days.

I can do this is 2 ways,

1st Approach :  Write current day data to s3, read rest of the 9 days data and do a union, like

```<code>dataset.write.mode(SaveMode.Overwrite)
              .format(sourceConfig.format).save(getWriteBasePath(sourceConfig.sourcePath
              , replaceDate))
newDf = spark.read.parquet("path1",...,"path9").union(dataset)
</code>```

2nd Approach:  Write current day data to s3, and read all 10 days data back again. Something like :

```<code>     dataset.write.mode(SaveMode.Overwrite)
          .format(sourceConfig.format).save(getWriteBasePath(sourceConfig.sourcePath
          , replaceDate))
    newDf = spark.read.parquet("path1",...,"path10")
</code>```

1st approach is working without any issues but very slow compared to 2nd approach. But with the second approach, some of the columns from current day's are getting null values after I read the complete data back to spark. I verified that the current day's data which is written is proper.

I am not able to figure out why this is happening. I am creating spark context with following properties :

```<code>sparkSession.sparkContext.hadoopConfiguration.set("mapreduce.fileoutputcommitter.algorithm.version", "2")
      sparkSession.sparkContext.getConf.set("spark.hadoop.parquet.enable.summary-metadata", "false")
      sparkSession.sparkContext.getConf.set("spark.sql.parquet.mergeSchema", "false")
      sparkSession.sparkContext.getConf.set("spark.sql.parquet.filterPushdown", "true")
      sparkSession.sparkContext.getConf.set("spark.sql.hive.metastorePartitionPruning", "true")
</code>```

答: I would prefer to cache the current data in one dataframe and read all past 9 days into another dataframe. Now that you have all data in memory.. your execution should be must faster. The moment we write to s3 (as its an action) the entire DAG created will be flushed and thats the reason your first approach is real slow. </p>

Body:
I am creating a dataset and writing it to s3 in a directory structure ${BasePath}/y=2107/m=11/d=16/ in parquet format. After I creates current day data and writes it to s3, I need to read back the data for last 10 days.

I can do this is 2 ways,

1st Approach :  Write current day data to s3, read rest of the 9 days data and do a union, like

dataset.write.mode(SaveMode.Overwrite)
              .format(sourceConfig.format).save(getWriteBasePath(sourceConfig.sourcePath
              , replaceDate))
newDf = spark.read.parquet("path1",...,"path9").union(dataset)

2nd Approach:  Write current day data to s3, and read all 10 days data back again. Something like :

     dataset.write.mode(SaveMode.Overwrite)
          .format(sourceConfig.format).save(getWriteBasePath(sourceConfig.sourcePath
          , replaceDate))
    newDf = spark.read.parquet("path1",...,"path10")

1st approach is working without any issues but very slow compared to 2nd approach. But with the second approach, some of the columns from current day's are getting null values after I read the complete data back to spark. I verified that the current day's data which is written is proper.

I am not able to figure out why this is happening. I am creating spark context with following properties :

sparkSession.sparkContext.hadoopConfiguration.set("mapreduce.fileoutputcommitter.algorithm.version", "2")
      sparkSession.sparkContext.getConf.set("spark.hadoop.parquet.enable.summary-metadata", "false")
      sparkSession.sparkContext.getConf.set("spark.sql.parquet.mergeSchema", "false")
      sparkSession.sparkContext.getConf.set("spark.sql.parquet.filterPushdown", "true")
      sparkSession.sparkContext.getConf.set("spark.sql.hive.metastorePartitionPruning", "true")


问:
Take the containing string array after split in Python
If I have some text like:

```<code> text= "  First sentence. Second sentence. Third sentence."
</code>```

And after this I split by '.':

```<code> new_split = text.split('.')
</code>```

I will receive: ['First sentence', Second sentence','Third sentence']

How could I print entire second sentence if I call it?

Like:

```<code>if 'second' in new_split : print (new_split[GET SECOND SENTENCE])
</code>```

I would like to know how to get entire 'second sentence' if I know in my split there exists a sentence that contains my keyword.

答:
You can try this:

```<code>text= "  First sentence. Second sentence. Third sentence."
new_text = [i for i in text.split('.') if "second" in i.lower()][0]
</code>```

Output:

```<code>' Second sentence'
</code>```

Body:
If I have some text like:

 text= "  First sentence. Second sentence. Third sentence."

And after this I split by '.':

 new_split = text.split('.')

I will receive: ['First sentence', Second sentence','Third sentence']

How could I print entire second sentence if I call it?

Like:

if 'second' in new_split : print (new_split[GET SECOND SENTENCE])

I would like to know how to get entire 'second sentence' if I know in my split there exists a sentence that contains my keyword.

Body:
You can try this:

text= "  First sentence. Second sentence. Third sentence."
new_text = [i for i in text.split('.') if "second" in i.lower()][0]

Output:

' Second sentence'


问:
Cannot read property 'getPayload' of undefined
I am implementing OAuth Google Sign in using backend  (written in node.js, express framework at Heroku). Front end is Android and it sends the token id to the server just fine. And server receives the token id correctly.

Here is the code (which is ripped off straight from Google Documents)

```<code>var auth = new GoogleAuth;
var client = new auth.OAuth2(CLIENT_ID, '', '');
    client.verifyIdToken(
        token,
        CLIENT_ID,
        // Or, if multiple clients access the backend:
        //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3],
        function(e, login) {
            var payload = login.getPayload();
            var userid = payload['sub'];
            // If request specified a G Suite domain:
            //var domain = payload['hd'];

        });
</code>```

But at times login in undefined. Its so strange that this problem occurs 1/10 rather than for every try so that I am not able to track the source of issue. For every other 9/10 it works just fine.

Any suggestions on how to solve this?

答:
The first parameter to the callback function is an error that needs to handled. </p>

```<code>    function(error, login) {
        if (error) return console.error(error)
        var payload = login.getPayload();
        var userid = payload['sub'];
        // If request specified a G Suite domain:
        //var domain = payload['hd'];

    });
</code>```

Body:
I am implementing OAuth Google Sign in using backend  (written in node.js, express framework at Heroku). Front end is Android and it sends the token id to the server just fine. And server receives the token id correctly.

Here is the code (which is ripped off straight from Google Documents)

var auth = new GoogleAuth;
var client = new auth.OAuth2(CLIENT_ID, '', '');
    client.verifyIdToken(
        token,
        CLIENT_ID,
        // Or, if multiple clients access the backend:
        //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3],
        function(e, login) {
            var payload = login.getPayload();
            var userid = payload['sub'];
            // If request specified a G Suite domain:
            //var domain = payload['hd'];

        });

But at times login in undefined. Its so strange that this problem occurs 1/10 rather than for every try so that I am not able to track the source of issue. For every other 9/10 it works just fine.

Any suggestions on how to solve this?

Body:
The first parameter to the callback function is an error that needs to handled.

    function(error, login) {
        if (error) return console.error(error)
        var payload = login.getPayload();
        var userid = payload['sub'];
        // If request specified a G Suite domain:
        //var domain = payload['hd'];

    });


问:
Fixed size div which sits to the right of a main div that fills up remainder of screen
I have seen lots of questions but none that seem to quite solve my problem.

I have two divs: mainbody and rightpanel. I would like the rightpanel to be a fixed size (210px), and to sit to the right of the mainbody div which fills up all the remaining space of the window.

So it would resize like this:

```<code>+----------------------------------------+
|                             |          |
|                             |          |
|                             |          |
|       mainbody              |rightpanel|
|                             |          |
|                             |          |
|                             |          |
+----------------------------------------+

+-------------------------------+
|                    |          |
|                    |          |
|                    |          |
|  mainbody          |rightpanel|
|                    |          |
|                    |          |
|                    |          |
+-------------------------------+
</code>```

My current solution below sort of works, but if the window is resized to below about 900px the right bar gets pushed to the bottom as the 25% remaining space gets too small for it to fit into, so I force the window to horizontally scroll at this width.

```<code>#wrap {
    width:97%;
    margin:0 auto;
}

#mainbody {
    float:left;
    width: 75%;
    margin-right: 10px;
    margin-left: 10px;
}

#rightpanel  {
    float:right;
    width: 22%;
    min-width: 210px;
    max-width: 210px;
}
</code>```

答:
```<code>#mainbody {
float: left;
}
#rightpanel {
width: 210px;
}
</code>```

Have you tried something like this?

ContentLicense: CC BY-SA 2.5

Body:
I have seen lots of questions but none that seem to quite solve my problem.

I have two divs: mainbody and rightpanel. I would like the rightpanel to be a fixed size (210px), and to sit to the right of the mainbody div which fills up all the remaining space of the window.

So it would resize like this:

+----------------------------------------+
|                             |          |
|                             |          |
|                             |          |
|       mainbody              |rightpanel|
|                             |          |
|                             |          |
|                             |          |
+----------------------------------------+

+-------------------------------+
|                    |          |
|                    |          |
|                    |          |
|  mainbody          |rightpanel|
|                    |          |
|                    |          |
|                    |          |
+-------------------------------+

My current solution below sort of works, but if the window is resized to below about 900px the right bar gets pushed to the bottom as the 25% remaining space gets too small for it to fit into, so I force the window to horizontally scroll at this width.

#wrap {
    width:97%;
    margin:0 auto;
}

#mainbody {
    float:left;
    width: 75%;
    margin-right: 10px;
    margin-left: 10px;
}

#rightpanel  {
    float:right;
    width: 22%;
    min-width: 210px;
    max-width: 210px;
}

Body:
#mainbody {
float: left;
}
#rightpanel {
width: 210px;
}

Have you tried something like this?


问:
Decoding Windows-1252 characters in imap subject line to UTF-8
I have a website that will allow people to post things to it using the subject line of an email in Outlook. Using PHP and imap, I get the subject line of the text and store it in a mysql db. But every once in a while, someone will copy text from a website into the subject line of that email and I will get garbled text. Similar to this:

=?Windows-1252?Q?_Every_day_in_our_offices_we_recycle_cardboard,aluminum?=
=?Windows-1252?Q?=96_won=92t_you_join_us=3F?=

What I've done is try to decode this text so it will appear normal on the page using the following code:

```<code>$subject = strip_tags($mailHeader->subject);
$header = imap_mime_header_decode($subject);
$subject = "";
for($i=0;$i<count($header);$i++)
{
    $subject .= $header[$i]->text;
}
</code>```

When finished I get rid of most of the garbled text, but am left behind with replacement characters for an em dash and a curly quote that was in the original subject line text. See the result below:

Every day in our offices we recycle cardboard, aluminum, � won�t you join us?

The charset for the website is set to UTF-8. When I set the website charset to ISO-8859-1, the replacement characters are replaced with the curly quote and em dash, which is great but I want to leave the website's charset at UTF-8.

Any help on how to get rid of the replacement characters without changing the charset to ISO-8859-1 would be great. Thanks.

答:
Each of the objects returned by imap_mime_header_decode includes a charset property, which you are ignoring. You would need to convert each one to UTF-8 in your loop, using something like:

```<code>$subject .= mb_convert_encoding($header[$i]->text, "UTF-8", $header[$i]->charset);
</code>```

As an alternative, consider using the mb_decode_mimeheader or iconv_mime_decode_headers functions. Both of these functions do the entire job of decoding a MIME header for you, returning a string in PHP's internal encoding (which is usually UTF-8).

Body:
I have a website that will allow people to post things to it using the subject line of an email in Outlook. Using PHP and imap, I get the subject line of the text and store it in a mysql db. But every once in a while, someone will copy text from a website into the subject line of that email and I will get garbled text. Similar to this:

=?Windows-1252?Q?_Every_day_in_our_offices_we_recycle_cardboard,aluminum?=
=?Windows-1252?Q?=96_won=92t_you_join_us=3F?=

What I've done is try to decode this text so it will appear normal on the page using the following code:

$subject = strip_tags($mailHeader->subject);
$header = imap_mime_header_decode($subject);
$subject = "";
for($i=0;$i<count($header);$i++)
{
    $subject .= $header[$i]->text;
}

When finished I get rid of most of the garbled text, but am left behind with replacement characters for an em dash and a curly quote that was in the original subject line text. See the result below:

Every day in our offices we recycle cardboard, aluminum, � won�t you join us?

The charset for the website is set to UTF-8. When I set the website charset to ISO-8859-1, the replacement characters are replaced with the curly quote and em dash, which is great but I want to leave the website's charset at UTF-8.

Any help on how to get rid of the replacement characters without changing the charset to ISO-8859-1 would be great. Thanks.

Body:
Each of the objects returned by imap_mime_header_decode includes a charset property, which you are ignoring. You would need to convert each one to UTF-8 in your loop, using something like:

$subject .= mb_convert_encoding($header[$i]->text, "UTF-8", $header[$i]->charset);

As an alternative, consider using the mb_decode_mimeheader or iconv_mime_decode_headers functions. Both of these functions do the entire job of decoding a MIME header for you, returning a string in PHP's internal encoding (which is usually UTF-8).


问:
Load python source code into function object
I need to create a unit-test like framework for light-weight auto grading of single-function python assignments. I'd love to do something like the following:

```<code>test = """
def foo(x):
    return x * x
"""

compiled_module = magic_compile(test)
result = compiled_module.foo(3)
assert result == 9
</code>```

Is there such a magic_compile function? The best I have so far is

```<code>exec(test)
result = getattr(sys.modules[__name__], 'foo')(3)
</code>```

But this seems dangerous and unstable. This won't be run in production, so I'm not super-concerned about sandboxing and safety. Just wanted to make sure there wasn't a better solution I'm missing.

答:
In Python 3.x:

```<code>module = {}
exec(test, module)
assert module['foo'](3) == 9
</code>```

module isn't a real Python module, it's just a namespace to hold the code's globals to avoid polluting your module's namespace.

Body:
I need to create a unit-test like framework for light-weight auto grading of single-function python assignments. I'd love to do something like the following:

test = """
def foo(x):
    return x * x
"""

compiled_module = magic_compile(test)
result = compiled_module.foo(3)
assert result == 9

Is there such a magic_compile function? The best I have so far is

exec(test)
result = getattr(sys.modules[__name__], 'foo')(3)

But this seems dangerous and unstable. This won't be run in production, so I'm not super-concerned about sandboxing and safety. Just wanted to make sure there wasn't a better solution I'm missing.

Body:
In Python 3.x:

module = {}
exec(test, module)
assert module['foo'](3) == 9

module isn't a real Python module, it's just a namespace to hold the code's globals to avoid polluting your module's namespace.


问:
Keras reinforcement training with softmax
A project i am working on has a reinforcement learning stage using the REINFORCE algorithm. The used model has a final softmax activation layer and because of that a negative learning rate is used as a replacement for negative rewards. I have some doubts about this process and can't find much literature on using a negative learning rate.

Does reinforement learning work with switching learning rate between positive and negative? and if not what would be a better approach, get rid of softmax or has keras a nice option for this?

Loss function:

def log_loss(y_true, y_pred):
    '''
    Keras 'loss' function for the REINFORCE algorithm,
    where y_true is the action that was taken, and updates
    with the negative gradient will make that action more likely.
    We use the negative gradient because keras expects training data
    to minimize a loss function.
    '''
    return -y_true * K.log(K.clip(y_pred, K.epsilon(), 1.0 - K.epsilon()))
```

<p>Switching learning rate:</p>

<pre class="lang-py prettyprint-override"><code>K.set_value(optimizer.lr, lr * (+1 if won else -1))
learner_net.train_on_batch(np.concatenate(st_tensor, axis=0),
                           np.concatenate(mv_tensor, axis=0))
</code>```

Update, test results

I ran a test with only positive reinforcement samples, omitting all negative examples and thus the negative learning rate. Winning rate is rising, it is improving and i can safely assume using a negative learning rate is not correct.

anybody any thoughts on how we should implement it?

Update, model explanation

We are trying to recreate AlphaGo as described by DeepMind, the slow policy net:

For the first stage of the training pipeline, we build on prior work
  on predicting expert moves in the game of Go using supervised
  learning13,21–24. The SL policy network pσ(a| s) alternates between convolutional
  layers with weights σ, and rectifier nonlinearities. A final softmax
  layer outputs a probability distribution over all legal moves a.

答:
Not sure if it the best way but at least i found a way that works.

for all negative training samples i reuse the network prediction, set the action i want to unlearn to zero and adjust all values to sum up to one again

i tried several ways to adjust them afterwards but haven't run enough tests to be sure what works best:

apply softmax ( action that has to be unlearned gets a nonzero value.. )

redistribute old action value over all other actions

set all illigal action values to zero and distribute the total removed value

distribute value proportional to value of other values

probably there are several other ways to do so, it might depend on use case what works best and there might be a better way to do so but this one works at least.

Body:
A project i am working on has a reinforcement learning stage using the REINFORCE algorithm. The used model has a final softmax activation layer and because of that a negative learning rate is used as a replacement for negative rewards. I have some doubts about this process and can't find much literature on using a negative learning rate.

Does reinforement learning work with switching learning rate between positive and negative? and if not what would be a better approach, get rid of softmax or has keras a nice option for this?

Loss function:

def log_loss(y_true, y_pred):
    '''
    Keras 'loss' function for the REINFORCE algorithm,
    where y_true is the action that was taken, and updates
    with the negative gradient will make that action more likely.
    We use the negative gradient because keras expects training data
    to minimize a loss function.
    '''
    return -y_true * K.log(K.clip(y_pred, K.epsilon(), 1.0 - K.epsilon()))

Switching learning rate:

K.set_value(optimizer.lr, lr * (+1 if won else -1))
learner_net.train_on_batch(np.concatenate(st_tensor, axis=0),
                           np.concatenate(mv_tensor, axis=0))

Update, test results

I ran a test with only positive reinforcement samples, omitting all negative examples and thus the negative learning rate. Winning rate is rising, it is improving and i can safely assume using a negative learning rate is not correct.

anybody any thoughts on how we should implement it?

Update, model explanation

We are trying to recreate AlphaGo as described by DeepMind, the slow policy net:

For the first stage of the training pipeline, we build on prior work
  on predicting expert moves in the game of Go using supervised
  learning13,21–24. The SL policy network pσ(a| s) alternates between convolutional
  layers with weights σ, and rectifier nonlinearities. A final softmax
  layer outputs a probability distribution over all legal moves a.


问:
How to dynamically change a Model attribute in a controller?
I have two tables users and users_metadata, where a single user hasMany metadata.

When I'm fetching all of the users, I want to be able to select certain fields, some of which exist in the metadata table.

```<code>users - id:1
users_metadata - user_id:1, key:username, value: MyUsername
users_metadata - user_id:1, key:birthday, value: 2017-11-16
</code>```

Through the url, I can add on a fields attribute which lists what fields I want to select rather than all of them.

```<code>/api/v1/users?fields=username
</code>```

What I'd like to be able to do is, instead of fetching all the metadata is to just fetch the metadata which is listed in the fields.

```<code>// Are we selecting all the fields?
if(!is_array($fields))
{
    // We are not, so lets build an array
    $fields = explode(',', $fields);

    // Loop through the users
    foreach($users as $user)
    {
        // Loop through the fields
        foreach($fields as $field)
        {
            // Try to fetch it as metadata
            if(array_key_exists($field, $user->metadata->toArray()))
            {
                $metadata[] = $field;
            }
        }

        // Adjust the user metadata
        $user->metadata = $user->metadata->filter(function($value, $key) use($metadata)
        {
            return in_array($key, $metadata);
        });
    }
}
</code>```

However this isn't updating my data with the new metadata, and when I dump the user data I'm still getting all my original metadata rather than just the username.

```<code>/**
 * Fetch all the metadata for a user.
 *
 * @return objects
 */
public function metadata()
{
    return $this->hasMany(UserMetadata::class);
}

    /**
     * Fetch the metadata as an attribute.
     *
     * @return array
     */
    public function getMetadataAttribute()
    {
        return $this->metadata()->get()->flatMap(function($values)
        {
            return [$values['key'] => $values['value']];
        });
    }

    /**
     * Update the metadata attribute.
     *
     * @param varied $value     The new metadata attribute.
     * @return void
     */
    public function setMetadataAttribute($value)
    {
        $this->attributes['metadata'] = $value;
    }
</code>```

答:
Could you use the only() method at the collection level?

For example, you have your fields array from the URL.  In this case it is only the one metadata field.

```<code>$fields = ['username'];
</code>```

Then get all the users:

$users_all = User::all(); or however you wish to get the collection of users.

Then use the only() method to filter the results to just the fields you need:

```<code>$filtered = $users_all->only($fields);
</code>```

Then return the filtered collection:

```<code>$filtered->all();
</code>```

From:  https://laravel.com/docs/5.5/collections#method-only

Body:
I have two tables users and users_metadata, where a single user hasMany metadata.

When I'm fetching all of the users, I want to be able to select certain fields, some of which exist in the metadata table.

users - id:1
users_metadata - user_id:1, key:username, value: MyUsername
users_metadata - user_id:1, key:birthday, value: 2017-11-16

Through the url, I can add on a fields attribute which lists what fields I want to select rather than all of them.

/api/v1/users?fields=username

What I'd like to be able to do is, instead of fetching all the metadata is to just fetch the metadata which is listed in the fields.

// Are we selecting all the fields?
if(!is_array($fields))
{
    // We are not, so lets build an array
    $fields = explode(',', $fields);

    // Loop through the users
    foreach($users as $user)
    {
        // Loop through the fields
        foreach($fields as $field)
        {
            // Try to fetch it as metadata
            if(array_key_exists($field, $user->metadata->toArray()))
            {
                $metadata[] = $field;
            }
        }

        // Adjust the user metadata
        $user->metadata = $user->metadata->filter(function($value, $key) use($metadata)
        {
            return in_array($key, $metadata);
        });
    }
}

However this isn't updating my data with the new metadata, and when I dump the user data I'm still getting all my original metadata rather than just the username.

/**
 * Fetch all the metadata for a user.
 *
 * @return objects
 */
public function metadata()
{
    return $this->hasMany(UserMetadata::class);
}

    /**
     * Fetch the metadata as an attribute.
     *
     * @return array
     */
    public function getMetadataAttribute()
    {
        return $this->metadata()->get()->flatMap(function($values)
        {
            return [$values['key'] => $values['value']];
        });
    }

    /**
     * Update the metadata attribute.
     *
     * @param varied $value     The new metadata attribute.
     * @return void
     */
    public function setMetadataAttribute($value)
    {
        $this->attributes['metadata'] = $value;
    }

Body:
Could you use the only() method at the collection level?

For example, you have your fields array from the URL.  In this case it is only the one metadata field.

$fields = ['username'];

Then get all the users:

$users_all = User::all(); or however you wish to get the collection of users.

Then use the only() method to filter the results to just the fields you need:

$filtered = $users_all->only($fields);

Then return the filtered collection:

$filtered->all();

From:  https://laravel.com/docs/5.5/collections#method-only


问:
Accessing "neighbor" classes created from 1 class possible?
Here's my problem:

I have 1 class that creates two new instances of a two other classes, and now I would need to either have a direct availability from one of the instances to the other, is this possible and if so, how?

so:

in Class A:

```<code>b = new B(5); // where 5 is an int data member of B
c = new C();
</code>```

and let B::bee() be a function I would need to access from C() BUT, I would need to access members of B (not a new instance of B) created by A.

```<code>So C::getIntfromB(){
  b->getInt();
}
</code>```

Or something.

I've tried going for:

```<code>b = new B(5);
c = new C(*b);
</code>```

having a B b; private member for C

However for some reason I simply cannot get it to work properly, what is the obvious error I am making?

答:
Your C member should be a pointer or a reference (B *b or B &b). If it's a B it will copy your B object, so it will refer to a different instance (which has been created by copying the one you're interested into).

Also, you'll need to pass your b object as a pointer or a reference, otherwise a new instance will be created while passing the parameter, and your pointer/reference in C class will refer to that one. (This would also lead to other problems, since such copy would be a temporary getting destroyed as soon as C's constructor returns)

Body:
Here's my problem:

I have 1 class that creates two new instances of a two other classes, and now I would need to either have a direct availability from one of the instances to the other, is this possible and if so, how?

so:

in Class A:

b = new B(5); // where 5 is an int data member of B
c = new C();

and let B::bee() be a function I would need to access from C() BUT, I would need to access members of B (not a new instance of B) created by A.

So C::getIntfromB(){
  b->getInt();
}

Or something.

I've tried going for:

b = new B(5);
c = new C(*b);

having a B b; private member for C

However for some reason I simply cannot get it to work properly, what is the obvious error I am making?


问:
Traversing polymorphic structures and performing a transformation only in few cases
Suppose we represent a company hierarchy in the following way:

```<code>{-# LANGUAGE DeriveDataTypeable #-}

import           Data.Data
import           Data.Generics.Aliases
import           Data.Generics.Schemes

data CompanyAsset = Employee Name Salary
                  | Plant Name
                  | Boss Name Performance Salary [CompanyAsset]
                  | Pet Name
                  | Car Id
                  | Guild [CompanyAsset]
                  | Fork CompanyAsset CompanyAsset
                  -- ... and imagine 100 more options that recursively use `CompanyAsset`.
                  deriving (Show, Data)

-- Performance of the department.
data Performance = Good | Bad deriving (Show, Data)

type Name = String

type Id = Int

newtype Salary = Salary Double deriving (Show, Data, Typeable)

raise :: Salary -> Salary
</code>```

And I would like to defne a function that raises the salaries of company assets that do not have a Boss ancestor whose department had a Bad performance. Such a function can be easily defined as follows:

```<code>raiseSalaries :: CompanyAsset -> CompanyAsset
raiseSalaries (Boss n Good s as) = Boss n Good (raise s) (raiseSalaries <$> as)
raiseSalaries a@(Boss _ Bad _ _) = a -- The salaries of everything below are not raised if the performance is 'Bad'
raiseSalaries ... -- and from here onwards we have **boilerplate**!
</code>```

The problem is that this requires a lot of boilerplate (for the sake of the discussion, please assume that the CompanyAsset is given and cannot be changed).

So my question is whether there is a way of traversing data structures in such a way that the boilerplate above can be avoided.

This question is related to a similar one I posted, but in this case the use of everywhere' won't help, since there are cases in which salaries should not be raised.

答:
This can be accomplished with a Traversal for CompanyAsset. You can write it yourself, or use uniplate or plate from lens.

For illustration, I'm going to write a traversal for CompanyAsset explicitly. It applies an operation (which I call p as in pure) to each direct descendant of a company asset. Note that traverse_ca pure == pure.

```<code>traverse_ca :: Applicative f => (CompanyAsset -> f CompanyAsset) -> CompanyAsset -> f CompanyAsset
traverse_ca p ca =
  case ca of
    Fork ca1 ca2      -> Fork <$> p ca1 <*> p ca2
    Boss n perf s cas -> Boss n perf s <$> traverse p cas
    Guild cas         -> Guild <$> traverse p cas
    otherwise         -> pure ca
</code>```

By itself this is enough to define raiseSalaries without any additional boilerplate.

```<code>import Data.Functor.Identity

raiseSalaries :: CompanyAsset -> CompanyAsset
raiseSalaries (Boss n Good s as) = Boss n Good (raise s) (raiseSalaries <$> as)
raiseSalaries a@(Boss _ Bad _ _) = a -- The salaries of everything below are not raised if the performance is 'Bad'
raiseSalaries a = runIdentity $ traverse_ca (pure . raiseSalaries) a
</code>```

Body:
Suppose we represent a company hierarchy in the following way:

{-# LANGUAGE DeriveDataTypeable #-}

import           Data.Data
import           Data.Generics.Aliases
import           Data.Generics.Schemes

data CompanyAsset = Employee Name Salary
                  | Plant Name
                  | Boss Name Performance Salary [CompanyAsset]
                  | Pet Name
                  | Car Id
                  | Guild [CompanyAsset]
                  | Fork CompanyAsset CompanyAsset
                  -- ... and imagine 100 more options that recursively use `CompanyAsset`.
                  deriving (Show, Data)

-- Performance of the department.
data Performance = Good | Bad deriving (Show, Data)

type Name = String

type Id = Int

newtype Salary = Salary Double deriving (Show, Data, Typeable)

raise :: Salary -> Salary

And I would like to defne a function that raises the salaries of company assets that do not have a Boss ancestor whose department had a Bad performance. Such a function can be easily defined as follows:

raiseSalaries :: CompanyAsset -> CompanyAsset
raiseSalaries (Boss n Good s as) = Boss n Good (raise s) (raiseSalaries <$> as)
raiseSalaries a@(Boss _ Bad _ _) = a -- The salaries of everything below are not raised if the performance is 'Bad'
raiseSalaries ... -- and from here onwards we have **boilerplate**!

The problem is that this requires a lot of boilerplate (for the sake of the discussion, please assume that the CompanyAsset is given and cannot be changed).

So my question is whether there is a way of traversing data structures in such a way that the boilerplate above can be avoided.

This question is related to a similar one I posted, but in this case the use of everywhere' won't help, since there are cases in which salaries should not be raised.

Body:
This can be accomplished with a Traversal for CompanyAsset. You can write it yourself, or use uniplate or plate from lens.

For illustration, I'm going to write a traversal for CompanyAsset explicitly. It applies an operation (which I call p as in pure) to each direct descendant of a company asset. Note that traverse_ca pure == pure.

traverse_ca :: Applicative f => (CompanyAsset -> f CompanyAsset) -> CompanyAsset -> f CompanyAsset
traverse_ca p ca =
  case ca of
    Fork ca1 ca2      -> Fork <$> p ca1 <*> p ca2
    Boss n perf s cas -> Boss n perf s <$> traverse p cas
    Guild cas         -> Guild <$> traverse p cas
    otherwise         -> pure ca

By itself this is enough to define raiseSalaries without any additional boilerplate.

import Data.Functor.Identity

raiseSalaries :: CompanyAsset -> CompanyAsset
raiseSalaries (Boss n Good s as) = Boss n Good (raise s) (raiseSalaries <$> as)
raiseSalaries a@(Boss _ Bad _ _) = a -- The salaries of everything below are not raised if the performance is 'Bad'
raiseSalaries a = runIdentity $ traverse_ca (pure . raiseSalaries) a


问:
Activate certain functions based on percent
```<code>            if chance == 1:
                function1()

            elif chance == 4:
                function2()

            elif chance == 20:
                function3()

            elif chance == 10:
                functiongettingoutofideas()

            elif chance == 40:
               function_minecraft_club_was_not_on_today_insertcryingemoji()

            elif chance == 10:
               function8()

            elif chance == 4:
                functionthesearealotoffunctions()

            elif chance == 5:
                function_above_when_i_mean_5_i_mean_5_percent_chance()

            elif chance == 6:
                function_thank_you_for_your_help()
</code>```

In the if and the elifs when i put for example, chance == 10, that means there is a 10% chance of that function being activated.

Any help will be much appreciated

答:
An example with three functions:

```<code>from numpy.random import choice
func_list = [function1, function2, function2]
weights = [10,40, 50]
choice(func_list, 1, p=weights)()
</code>```

Note that for this to work, weights has to add up to 100.

Body:
            if chance == 1:
                function1()

            elif chance == 4:
                function2()

            elif chance == 20:
                function3()

            elif chance == 10:
                functiongettingoutofideas()

            elif chance == 40:
               function_minecraft_club_was_not_on_today_insertcryingemoji()

            elif chance == 10:
               function8()

            elif chance == 4:
                functionthesearealotoffunctions()

            elif chance == 5:
                function_above_when_i_mean_5_i_mean_5_percent_chance()

            elif chance == 6:
                function_thank_you_for_your_help()

In the if and the elifs when i put for example, chance == 10, that means there is a 10% chance of that function being activated.

Any help will be much appreciated

Body:
An example with three functions:

from numpy.random import choice
func_list = [function1, function2, function2]
weights = [10,40, 50]
choice(func_list, 1, p=weights)()

Note that for this to work, weights has to add up to 100.


问:
How can I post to the wall of a Facebook Fan Page using PHP and Open Graph API
Sample code is appreciated, I can't seem to find any simple examples of this online.</p>

答:
Using the new Facebook PHP-SDK, it's very easy to accomplish this.

Requirements:

Extended Permissions, depending on your needs

Page ID

Now as I said, depending on your requirements you may need offline_access, manage_pages, but for now this is the simplest straight forward way of doing this:

After downloading the PHP SDK, and in the example.php file:

Acquire the publish_stream permission:

```<code><fb:login-button perms="publish_stream"></fb:login-button>
</code>```

After successful authentication, you post to the page wall the same way you do it for normal user profile (and with the same options too, message, picture, link, name, caption, description, source):

```<code>$page_id = '123456789';
$feed_array = array(
    'message' => "Hello world!"
);
$page_post = $facebook->api("/$page_id/feed","post",$feed_array);
</code>```

Result:

Please note that this approach requires you being an administrator of the page.

Body:
Using the new Facebook PHP-SDK, it's very easy to accomplish this.

Requirements:

Extended Permissions, depending on your needs

Page ID

Now as I said, depending on your requirements you may need offline_access, manage_pages, but for now this is the simplest straight forward way of doing this:

After downloading the PHP SDK, and in the example.php file:

Acquire the publish_stream permission:

<fb:login-button perms="publish_stream"></fb:login-button>

After successful authentication, you post to the page wall the same way you do it for normal user profile (and with the same options too, message, picture, link, name, caption, description, source):

$page_id = '123456789';
$feed_array = array(
    'message' => "Hello world!"
);
$page_post = $facebook->api("/$page_id/feed","post",$feed_array);

Result:

Please note that this approach requires you being an administrator of the page.


问:
Issue with ExoPlayer
when i push the button to comeback to previous activity, exoplayer continue to playing sound. Why?

This is my code:

```<code>public class MainActivity extends AppCompatActivity {

    SimpleExoPlayerView exoPlayerView;
    SimpleExoPlayer exoPlayer;
    String videoURL = "myurl";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        exoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exo_player_view);
     try {

         BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
         TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
         exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);

         Uri videoURI = Uri.parse(videoURL);

         DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video");
         ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
         MediaSource mediaSource = new ExtractorMediaSource(videoURI, dataSourceFactory, extractorsFactory, null, null);

         exoPlayerView.setPlayer(exoPlayer);
         exoPlayer.prepare(mediaSource);
         exoPlayer.setPlayWhenReady(true);
     }catch (Exception e){
         Log.e("MainAcvtivity"," exoplayer error "+ e.toString());
     }

    }
}
</code>```

Any suggestion?

答:
it is because you didn't release the resource. just use this code

```<code>@Override
public void onPause() {
super.onPause();
if (Util.SDK_INT <= 23) {
 exoPlayer.release();
}

}

@Override
public void onStop() {
super.onStop();
if (Util.SDK_INT > 23) {
   exoPlayer.release();
 }
}
</code>```

Title: Issue with ExoPlayer

Body:
when i push the button to comeback to previous activity, exoplayer continue to playing sound. Why?

This is my code:

public class MainActivity extends AppCompatActivity {

    SimpleExoPlayerView exoPlayerView;
    SimpleExoPlayer exoPlayer;
    String videoURL = "myurl";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        exoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exo_player_view);
     try {

         BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
         TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
         exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);

         Uri videoURI = Uri.parse(videoURL);

         DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video");
         ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
         MediaSource mediaSource = new ExtractorMediaSource(videoURI, dataSourceFactory, extractorsFactory, null, null);

         exoPlayerView.setPlayer(exoPlayer);
         exoPlayer.prepare(mediaSource);
         exoPlayer.setPlayWhenReady(true);
     }catch (Exception e){
         Log.e("MainAcvtivity"," exoplayer error "+ e.toString());
     }

    }
}

Any suggestion?

Body:
it is because you didn't release the resource. just use this code

@Override
public void onPause() {
super.onPause();
if (Util.SDK_INT <= 23) {
 exoPlayer.release();
}

}

@Override
public void onStop() {
super.onStop();
if (Util.SDK_INT > 23) {
   exoPlayer.release();
 }
}


问:
HTML5 Canvas: Zooming
Is there any easy way how to zoom in and back out in canvas (JavaScript)? Basically I have a 400x400px canvas and I'd like to be able to zoom in with 'mousedown' (2x) and go back with 'mouseup'.

Spent last two days googling, but no luck so far.  :(

答:
One option is to use css zoom feature: </p>

```<code>$("#canvas_id").css("zoom","x%");
</code>```

ContentLicense: CC BY-SA 4.0

Title: HTML5 Canvas: Zooming

Body:
One option is to use css zoom feature:

$("#canvas_id").css("zoom","x%");


问:
Matplotlib 3D Plot does not work as expected
as a Python and Stackoverflow Newbie, please excuse my dumb question. I've been working on this quite some time without making progress. I'm trying to set up a 3D Plot with X Y Z vectors for the respective axes.

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
import pandas, io
data = np.array([[0 ,0 ,1918],
                [1000 ,0 ,2001],
                [2000 ,0 ,2031],
                [3000 ,0 ,2048],
                [0 ,1000 ,2001],
                [1000 ,1000 ,2084],
                [2000 ,1000 ,2114],
                [3000 ,1000 ,2131],
                [0 ,2000 ,2031],
                [1000 ,2000 ,2114],
                [2000 ,2000 ,2144],
                [3000 ,2000 ,2161],
                [0 ,3000 ,2048],
                [1000 ,3000 ,2131],
                [2000 ,3000 ,2161],
                [3000 ,3000 ,2178]])
df = pandas.DataFrame(data,columns=["X","Y","Z"])
print(df)
x, y = np.meshgrid(df['X'],df['Y'])
plt.clf()
fig = plt.figure()
ax = fig.gca(projection='3d')
myplot = ax.plot_surface(X=x,Y=y,Z=df['Z'])
plt.show(myplot)
</code>```

The sample data has 16 data points. I understand that I have to transform the X and Y vectors into a 4x4 grid which defines each Z value in the space. This is what I try to achieve with np.meshgrid. The result should be a uniform area that with a constant slope from (0,0) towards (3000,3000). However, this is not what I see:

Resulting Graph

I'd be grateful for everybody pushing me in the right direction.

答:
You may have misunderstood meshgrid. E.g.

```<code>p,q = np.meshgrid(["a","b"],["X","Y"])
print(p)
print (q)
# results in
[['a' 'b']
 ['a' 'b']]
[['X' 'X']
 ['Y' 'Y']]
</code>```

A meshgrid of two arrays with length n and m will result in two arrays with shape (m,n). If you put your complete coordinate list into meshgrid, it will result in a 16 by 16 matrix, not a 4 by 4 matrix as required.

Here you already have all the coordinates, they are just not in 2D shape. So the idea would be to simply reshape the coordinate lists, using numpy.reshape.

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

data = np.array([[0 ,0 ,1918],
                [1000 ,0 ,2001],
                [2000 ,0 ,2031],
                [3000 ,0 ,2048],
                [0 ,1000 ,2001],
                [1000 ,1000 ,2084],
                [2000 ,1000 ,2114],
                [3000 ,1000 ,2131],
                [0 ,2000 ,2031],
                [1000 ,2000 ,2114],
                [2000 ,2000 ,2144],
                [3000 ,2000 ,2161],
                [0 ,3000 ,2048],
                [1000 ,3000 ,2131],
                [2000 ,3000 ,2161],
                [3000 ,3000 ,2178]])

x = data[:,0].reshape(4,4)
y = data[:,1].reshape(4,4)
z = data[:,2].reshape(4,4)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X=x,Y=y,Z=z)
plt.show()
</code>```

Body:
as a Python and Stackoverflow Newbie, please excuse my dumb question. I've been working on this quite some time without making progress. I'm trying to set up a 3D Plot with X Y Z vectors for the respective axes.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
import pandas, io
data = np.array([[0 ,0 ,1918],
                [1000 ,0 ,2001],
                [2000 ,0 ,2031],
                [3000 ,0 ,2048],
                [0 ,1000 ,2001],
                [1000 ,1000 ,2084],
                [2000 ,1000 ,2114],
                [3000 ,1000 ,2131],
                [0 ,2000 ,2031],
                [1000 ,2000 ,2114],
                [2000 ,2000 ,2144],
                [3000 ,2000 ,2161],
                [0 ,3000 ,2048],
                [1000 ,3000 ,2131],
                [2000 ,3000 ,2161],
                [3000 ,3000 ,2178]])
df = pandas.DataFrame(data,columns=["X","Y","Z"])
print(df)
x, y = np.meshgrid(df['X'],df['Y'])
plt.clf()
fig = plt.figure()
ax = fig.gca(projection='3d')
myplot = ax.plot_surface(X=x,Y=y,Z=df['Z'])
plt.show(myplot)

The sample data has 16 data points. I understand that I have to transform the X and Y vectors into a 4x4 grid which defines each Z value in the space. This is what I try to achieve with np.meshgrid. The result should be a uniform area that with a constant slope from (0,0) towards (3000,3000). However, this is not what I see:

Resulting Graph

I'd be grateful for everybody pushing me in the right direction.

Body:
You may have misunderstood meshgrid. E.g.

p,q = np.meshgrid(["a","b"],["X","Y"])
print(p)
print (q)
# results in
[['a' 'b']
 ['a' 'b']]
[['X' 'X']
 ['Y' 'Y']]

A meshgrid of two arrays with length n and m will result in two arrays with shape (m,n). If you put your complete coordinate list into meshgrid, it will result in a 16 by 16 matrix, not a 4 by 4 matrix as required.

Here you already have all the coordinates, they are just not in 2D shape. So the idea would be to simply reshape the coordinate lists, using numpy.reshape.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

data = np.array([[0 ,0 ,1918],
                [1000 ,0 ,2001],
                [2000 ,0 ,2031],
                [3000 ,0 ,2048],
                [0 ,1000 ,2001],
                [1000 ,1000 ,2084],
                [2000 ,1000 ,2114],
                [3000 ,1000 ,2131],
                [0 ,2000 ,2031],
                [1000 ,2000 ,2114],
                [2000 ,2000 ,2144],
                [3000 ,2000 ,2161],
                [0 ,3000 ,2048],
                [1000 ,3000 ,2131],
                [2000 ,3000 ,2161],
                [3000 ,3000 ,2178]])

x = data[:,0].reshape(4,4)
y = data[:,1].reshape(4,4)
z = data[:,2].reshape(4,4)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X=x,Y=y,Z=z)
plt.show()


答:
```<code>if new_split[1] != '':
    print(new_split[1])
</code>```

Title: Take the containing string array after split in Python

Body:
If I have some text like:

 text= "  First sentence. Second sentence. Third sentence."

And after this I split by '.':

 new_split = text.split('.')

I will receive: ['First sentence', Second sentence','Third sentence']

How could I print entire second sentence if I call it?

Like:

if 'second' in new_split : print (new_split[GET SECOND SENTENCE])

I would like to know how to get entire 'second sentence' if I know in my split there exists a sentence that contains my keyword.


问:
Calculate GPS coordinates from a starting point
Is there a library (JS or .NET) or a set of formulas that would help me calculate set of gps coordinates based on starting location, direction and distance.

For example.

I have an exact lon/lat of a certain location. I'd like to calculate an exact lon/lot 5 miles NE from that location.

答: Perhaps this might or might not fit your needs but have you tried Entity Framework Spatial?</p>