问:
When to use async vs defer when loading scripts?
So I've recently learned that putting your js at the bottom of the DOM is antiquated, and that I should be once again putting them in the  with the “async” and “defer” attributes.

Great. But I'm a bit confused as to which I should use, based on priority.

So I have:

jquery

jquery plugins that don't have immediate effects on the look of the
page

jquery plugins that do have immediate effects on the look of the page

my own personal scripts, which have immediate effects on the look of
the page, and is also reliant on jquery

Which should get async, and which should get defer?

If I understand all this correctly, the ones that don't have an immediate effect on the look of the site should get defer, while everything else gets async. Correct? Or am I getting these mixed up.

答:
It's quite simple. You should use [async] for scripts which can be executed in any order, and [defer] for scripts which have to be executed after HTML is parsed.

For example, if you have a script that add social sharing icons next to your posts, and this script doesn't rely on any other script, you can use both [async] and [defer]. But if your scripts requires jQuery, you can't use [async], because if you do, it might turn out that it gets executed before jQuery is loaded and it breaks.

If all your scripts require jQuery, then you shouldn't use [async] at all. As for [defer], it depends on whether your scripts access DOM. For plugins it probably doesn't matter, but you'll probably need it for your own code.

If you wrap your scripts in $(document).ready();, you can use [defer] for scripts which don't have immediate effect (e.g. require user interaction).


来源: stackexchange

问:
How to remove element from list that is being iterated in another method?
I have a class member list I am iterating over in following method:

```<code>public void deselectAll() {
    Iterator<GraphicalObject> iterator = selectedObjects.iterator();
    while(iterator.hasNext())
    {
        iterator.next().setSelected(false);
    }
}
</code>```

Method setSelected() will cause current element to be removed in subsequent calls that setSelected() triggers.
Is there a way I can remove current element somewhere out of this method and continue iterating normally?

EDIT: I see question is ambiguous a bit. Here's example showing problem in context ( I left out irrelevant code):
```
public class Model {</p>

```     private List<GraphicalObject> selectedObjects;

     private final GraphicalObjectListener listener = new GraphicalObjectListener() {
           @Override
           public void graphicalObjectSelectionChanged(GraphicalObject go) {
                int index = selectedObjects.indexOf(go);
                if(go.isSelected()) {
                     if(index == -1) {
                          selectedObjects.add(go);
                      } else {
                          return;
                      }
                } else {
                      if(index != -1) {
                          selectedObjects.remove(index);
                      } else {
                          return;
                      }
                }
                notifyListeners();
          }
    };

    public void deselectAll() {
        Iterator<GraphicalObject> iterator = selectedObjects.iterator();
        while(iterator.hasNext()){
                iterator.next().setSelected(false);
        }
    }
```

<p>}</p>

<p>public abstract class AbstractGraphicalObject implements GraphicalObject {</p>

<code>    @Override
    public void setSelected(boolean selected) {
        this.selected = selected;
        notifySelectionListeners();
    }

    public void notifySelectionListeners() {
        for (GraphicalObjectListener listener : listeners) {
            listener.graphicalObjectSelectionChanged(this);
        }
    }
</code>```

}

答:
If you want to both remove the element from the list and call setSelected(false) on the removed element, you could do it as follows:

```<code>public void deselectAll() {
    Iterator<GraphicalObject> iterator = selectedObjects.iterator();
    while(iterator.hasNext()) {
        GraphicalObject g = iterator.next();
        iterator.remove();    // removes g from selectedObjects
        g.setSelected(false); // deselects g
    }
}
</code>```

Of course, in your setSelected method you shouldn't remove the element from the list.

Note: invoking remove on the iterator works as long as the collection selectedObjects supports removal through an iterator, but this is the case with most common collections, such as ArrayList.

ContentLicense: CC BY-SA 3.0

Body:
I have a class member list I am iterating over in following method:

public void deselectAll() {
    Iterator<GraphicalObject> iterator = selectedObjects.iterator();
    while(iterator.hasNext())
    {
        iterator.next().setSelected(false);
    }
}

Method setSelected() will cause current element to be removed in subsequent calls that setSelected() triggers.
Is there a way I can remove current element somewhere out of this method and continue iterating normally?

EDIT: I see question is ambiguous a bit. Here's example showing problem in context ( I left out irrelevant code):

public class Model {

     private List<GraphicalObject> selectedObjects;

     private final GraphicalObjectListener listener = new GraphicalObjectListener() {
           @Override
           public void graphicalObjectSelectionChanged(GraphicalObject go) {
                int index = selectedObjects.indexOf(go);
                if(go.isSelected()) {
                     if(index == -1) {
                          selectedObjects.add(go);
                      } else {
                          return;
                      }
                } else {
                      if(index != -1) {
                          selectedObjects.remove(index);
                      } else {
                          return;
                      }
                }
                notifyListeners();
          }
    };

    public void deselectAll() {
        Iterator<GraphicalObject> iterator = selectedObjects.iterator();
        while(iterator.hasNext()){
                iterator.next().setSelected(false);
        }
    }

}

public abstract class AbstractGraphicalObject implements GraphicalObject {

    @Override
    public void setSelected(boolean selected) {
        this.selected = selected;
        notifySelectionListeners();
    }

    public void notifySelectionListeners() {
        for (GraphicalObjectListener listener : listeners) {
            listener.graphicalObjectSelectionChanged(this);
        }
    }

}

Body:
If you want to both remove the element from the list and call setSelected(false) on the removed element, you could do it as follows:

public void deselectAll() {
    Iterator<GraphicalObject> iterator = selectedObjects.iterator();
    while(iterator.hasNext()) {
        GraphicalObject g = iterator.next();
        iterator.remove();    // removes g from selectedObjects
        g.setSelected(false); // deselects g
    }
}

Of course, in your setSelected method you shouldn't remove the element from the list.

Note: invoking remove on the iterator works as long as the collection selectedObjects supports removal through an iterator, but this is the case with most common collections, such as ArrayList.


问:
Make link from text inside brackets using preg_replace
I would like to use PHP to transform a text from this format:

foo [[http://www.google.com|This Link points to google]] foo

to this

foo This Link points to google foo

I've made this code:

```<code>function linkLine($line) {
    if (preg_match('#\[\[(.*?)\]\]#', $line, $match)) {
        $arr = explode("|", $match[1], 2);
        $link = "<a href=\"$arr[0]\">$arr[1]</a>";
        return str_replace($match[0], $link, $line);
    } else {
        return $line;
   }
}
</code>```

But i know that's is not elegant, not robust and doesn't work if there is more than one occurrences in the same line.

How can I improve it using preg_replace?

答:
Personally, I think 'style' is low on the list of priorities when it comes to text manipulation with regex. Higher on that list, in my opinion, is first and foremost functionality: does it work? Great. Second is readability: can others understand what it's doing, and if there's an error/mistake, can they easily fix it?

That said, your motivation to improve it is valid as it fails one of your functional requirements, that is, if there are multiple occurrences in the same line.

So why not approach this problem step by step:

1) Replace the first occurrence of ' [[' with '

2) Replace the first occurrence of '|' that follows after '[[' with '">'.

(this is a tricky one, since it requires a decision on your part. For the following example, which of the two outcomes would you prefer?:

3) foo [[http://www.google.com|This Link points to]] google]] foo

I'm going to go with the first instance of ']] '. If you want to capture outer brackets, then you'll need to use lookaheads to check to make sure there are no more ']] ' before '[[ '.

Following the above steps, I came up with (in javascript, so I can show an example):

let regex = /(.*)(\s\[\[)(http:\/\/[^|]+)(\|)((.*)(?=\b)(\]\]\s))(.*)/;

let result = "foo [[http://www.google.com|This Link points to google]] foo".replace(regex,'$1 $6 $8');

let pathologicalDataResult = "foo [[http://ww[[w.google.co|m|This Link poi]]nts to google]] foo".replace(regex,'$1 $6 $8');

console.log(result);
console.log(pathologicalDataResult);```

Body:
I would like to use PHP to transform a text from this format:

foo [[http://www.google.com|This Link points to google]] foo

to this

foo This Link points to google foo

I've made this code:

function linkLine($line) {
    if (preg_match('#\[\[(.*?)\]\]#', $line, $match)) {
        $arr = explode("|", $match[1], 2);
        $link = "$arr[1]";
        return str_replace($match[0], $link, $line);
    } else {
        return $line;
   }
}

But i know that's is not elegant, not robust and doesn't work if there is more than one occurrences in the same line.

How can I improve it using preg_replace?

Body:
Personally, I think 'style' is low on the list of priorities when it comes to text manipulation with regex. Higher on that list, in my opinion, is first and foremost functionality: does it work? Great. Second is readability: can others understand what it's doing, and if there's an error/mistake, can they easily fix it?

That said, your motivation to improve it is valid as it fails one of your functional requirements, that is, if there are multiple occurrences in the same line.

So why not approach this problem step by step:

1) Replace the first occurrence of ' [[' with '

2) Replace the first occurrence of '|' that follows after '[[' with '">'.

(this is a tricky one, since it requires a decision on your part. For the following example, which of the two outcomes would you prefer?:

3) foo [[http://www.google.com|This Link points to]] google]] foo

I'm going to go with the first instance of ']] '. If you want to capture outer brackets, then you'll need to use lookaheads to check to make sure there are no more ']] ' before '[[ '.

Following the above steps, I came up with (in javascript, so I can show an example):

let regex = /(.*)(\s\[\[)(http:\/\/[^|]+)(\|)((.*)(?=\b)(\]\]\s))(.*)/;

let result = "foo [[http://www.google.com|This Link points to google]] foo".replace(regex,'$1 <a href="$3"/>$6</a> $8');

let pathologicalDataResult = "foo [[http://ww[[w.google.co|m|This Link poi]]nts to google]] foo".replace(regex,'$1 <a href="$3"/>$6</a> $8');

console.log(result);
console.log(pathologicalDataResult);


问:
c# messenger, send commands over network, protocol?
I'm making a c# messenger application just for fun, but I wanna do it good.
I want the possibility to send commands like a chat message, kick comand etc, but i dont know a good way to control it.

I could send an object over the networkstream, or I could send a string like: stream.write("command##");

maybe you know another way to fix this things, but I'm in stackoverflow atm.
Thanks.

答:
It seems like you already have a handle on building your sockets from the use of Stream.Write() in your question.

You might want to try something that builds a byte array with a message type, and some sort of checksum. For example:

```<code>        string message = "this is your message";
        byte packetType = 1;
        byte checksum = 0;

        // calculate a simple checksum
        foreach (char c in message)
        {
            checksum ^= (byte)c;
        }

        // type, message, checksum into buffer
        // (uses list instead of playing with arrays for expeditious example code)
        List<byte> buffer = new List<byte>();
        buffer.Add(packetType);
        buffer.AddRange(ASCIIEncoding.UTF8.GetBytes(message));
        buffer.Add(checksum);

        // write out to the socket
        CommStream.Write(buffer.ToArray(), 0, buffer.Count);
</code>```

once you feel adventerous to go beyond sending simple strings, you can attempt serializing objects to byte arrays using the runtime namespace:

```<code>    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;

    public class Message : ISerializable
    {
        DateTime timestamp;
        byte type;
        string message;
    }

    public byte[] BuildBuffer(Message input)
    {
        // Serialize the message
        Stream s = new MemoryStream();
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(s, input);
        buffer = s.ToArray();

        return buffer;
    }

    public Message BuildMessage(byte[] input)
    {
        Stream s = new MemoryStream(input);
        s.Position = 0;

        BinaryFormatter binaryFormatter = new BinaryFormatter();
        return (Message)binaryFormatter.Deserialize(s);
    }
</code>```

Body:
It seems like you already have a handle on building your sockets from the use of Stream.Write() in your question.

You might want to try something that builds a byte array with a message type, and some sort of checksum. For example:

        string message = "this is your message";
        byte packetType = 1;
        byte checksum = 0;

        // calculate a simple checksum
        foreach (char c in message)
        {
            checksum ^= (byte)c;
        }

        // type, message, checksum into buffer
        // (uses list instead of playing with arrays for expeditious example code)
        List<byte> buffer = new List<byte>();
        buffer.Add(packetType);
        buffer.AddRange(ASCIIEncoding.UTF8.GetBytes(message));
        buffer.Add(checksum);

        // write out to the socket
        CommStream.Write(buffer.ToArray(), 0, buffer.Count);

once you feel adventerous to go beyond sending simple strings, you can attempt serializing objects to byte arrays using the runtime namespace:

    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;

    public class Message : ISerializable
    {
        DateTime timestamp;
        byte type;
        string message;
    }

    public byte[] BuildBuffer(Message input)
    {
        // Serialize the message
        Stream s = new MemoryStream();
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(s, input);
        buffer = s.ToArray();

        return buffer;
    }

    public Message BuildMessage(byte[] input)
    {
        Stream s = new MemoryStream(input);
        s.Position = 0;

        BinaryFormatter binaryFormatter = new BinaryFormatter();
        return (Message)binaryFormatter.Deserialize(s);
    }

ContentLicense: CC BY-SA 2.5


问:
Retrieve retweeters id
I need to retrieve retweeters id using tweepy.</p>

```<code>import tweepy
import time,json

APP_KEY=""
APP_SECRET=""
OAUTH_TOKEN=""
OAUTH_TOKEN_SECRET=""

auth = tweepy.OAuthHandler(APP_KEY,APP_SECRET)
auth.set_access_token(OAUTH_TOKEN,OAUTH_TOKEN_SECRET)

api = tweepy.API(auth)
'''for status in api.user_timeline(screen_name='acmigdtuw',include_rts=1,count=200):
    print status.id'''
firstTweet = api.user_timeline(screen_name="acmigdtuw")[0]
print firstTweet.text
print firstTweet.id
#results = api.retweets(status.id,cursor=-1,stringify_ids=1)
pl = api.retweets.id(id=firstTweet.id)
print pl[0]['user']['screen_name']
</code>```

答:
```<code>firstTweet = api.user_timeline(screen_name="acmigdtuw")[0]

# get the original tweet
original_tweet = firstTweet.retweeted_status.id

# iterate over retweets to get user id
for status in api.retweets(original_tweet):
    print status.user.id
</code>```

output:

```<code>839110314012598272
390229046
</code>```

These are the IDs of the users who retweeted the original tweet.

We can confirm by comparing the number of retweets to our results:

```<code>print firstTweet.retweeted_status.retweet_count == len(api.retweets(original_tweet))
</code>```

True

Title: Retrieve retweeters id

Body:
I need to retrieve retweeters id using tweepy.

import tweepy
import time,json

APP_KEY=""
APP_SECRET=""
OAUTH_TOKEN=""
OAUTH_TOKEN_SECRET=""

auth = tweepy.OAuthHandler(APP_KEY,APP_SECRET)
auth.set_access_token(OAUTH_TOKEN,OAUTH_TOKEN_SECRET)

api = tweepy.API(auth)
'''for status in api.user_timeline(screen_name='acmigdtuw',include_rts=1,count=200):
    print status.id'''
firstTweet = api.user_timeline(screen_name="acmigdtuw")[0]
print firstTweet.text
print firstTweet.id
#results = api.retweets(status.id,cursor=-1,stringify_ids=1)
pl = api.retweets.id(id=firstTweet.id)
print pl[0]['user']['screen_name']

Body:
firstTweet = api.user_timeline(screen_name="acmigdtuw")[0]

# get the original tweet
original_tweet = firstTweet.retweeted_status.id

# iterate over retweets to get user id
for status in api.retweets(original_tweet):
    print status.user.id

output:

839110314012598272
390229046

These are the IDs of the users who retweeted the original tweet.

We can confirm by comparing the number of retweets to our results:

print firstTweet.retweeted_status.retweet_count == len(api.retweets(original_tweet))

True


问:
ones complement of 0 - 0
For background,  I'm trying to calculate a checksum for an IP packet which is stored in constant memory (can't modify it in place).   Before doing the checksum, I'm supposed to pretend the existing checksum in the packet is 0.   Rather than copy all the data to temporary buffer, and store 0, I'd like to do a checksum of the entire packet, and then subtract the existing checksum from the result.

To do this, I was looking for a one's complement version of subtraction which I found here.  Unfortunately, if I use this, and subtract 0 from 0, I get 0x1111 instead of the expected 0:

Convert 0 to one's complement:  [1111]

Next, we add 0:   [1111]

no overflow bit, so we're done...

I would have expected 0 - 0 to be 0 -- what am I missing?

答:
I suggest to Read this tutorial on One's Complement

https://courses.cs.vt.edu/csonline/NumberSystems/Lessons/SubtractionWithOnesComplement/index.html

I think this is easy:

```<code>0000 - 0000 = 0000 + 1111 = 1111
</code>```

As the last 1111 is in One's Complement form, we know that this is a Negative Number for having a Leading 1.
The Last Operation is One's Complement (1111).

Final Answer is - 0000.
As you know a Cons of One's Complement Calculation is that having two form for
presenting Zero 0.

Title: ones complement of 0 - 0

Body:
I suggest to Read this tutorial on One's Complement

https://courses.cs.vt.edu/csonline/NumberSystems/Lessons/SubtractionWithOnesComplement/index.html

I think this is easy:

0000 - 0000 = 0000 + 1111 = 1111

As the last 1111 is in One's Complement form, we know that this is a Negative Number for having a Leading 1.
The Last Operation is One's Complement (1111).

Final Answer is - 0000.
As you know a Cons of One's Complement Calculation is that having two form for
presenting Zero 0.


问:
SyntaxError when extending Number object
I am trying to extend the Number object with this code:

Number.prototype.isNumber = function(i){
  if(arguments.length === 1){
    return !isNaN(parseFloat(i)) && isFinite(i);
  } else {
    return !isNaN(parseFloat(this)) && isFinite(this);
  }
}

try {
  var x = 8.isNumber();
} catch(err) {
  console.log(err);
}```
</div>
</div>
</p>

<p>I get <code>SyntaxError: identifier starts immediately after numeric literal</code></p>

<p>also when I try the following:</p>

```Number.isNumber(8)
```

I get Number.isNumber is not a function!!

答:
The JavaScript parser reads 8.isNumber as a number literal.

To access a Number method on a numeric literal you'll have to surround the number with parenthesis so the JavaScript interpreter knows you're trying to use the number properties.

Number.prototype.isNumber = function(i) {
  if (arguments.length === 1) {
    return !isNaN(parseFloat(i)) && isFinite(i);
  }

  return !isNaN(parseFloat(this)) && isFinite(this);
}

try {
  var x = (8).isNumber();
  console.log(x);
} catch(err) {
  console.log(err);
}```

Body:
I am trying to extend the Number object with this code:

Number.prototype.isNumber = function(i){
  if(arguments.length === 1){
    return !isNaN(parseFloat(i)) && isFinite(i);
  } else {
    return !isNaN(parseFloat(this)) && isFinite(this);
  }
}

try {
  var x = 8.isNumber();
} catch(err) {
  console.log(err);
}

I get SyntaxError: identifier starts immediately after numeric literal

also when I try the following:

Number.isNumber(8)

I get Number.isNumber is not a function!!


问:
Selenium c# , Xpath is not recognizing
i have element but the xpath is not working
receiving unable to find element with xpath ....

var newnumber = driver.FindElement(By.XPath("//div[@id='1496943330773-0-uiGrid-0006-cell']/div"));

please help me with this?

答:
To handle a dynamic ID, they easiest thing is to remove it.

How to do so in Chrome:

Right-click the element and select "Inspect"

Double-click the element's id="..." attribute to edit it

Delete the attribute and save the changes (by clicking on another element)

Right-click the element and select "Copy" -> "Copy Xpath"

Title: Selenium c# , Xpath is not recognizing


问:
Bootstrap Dropdown and Bootstrap Tagsinput not working when integrating with angular 2
Bootstrap dropdown code works fine (without angular 2) but same code is integrated with angular 2, it fails to work as expected.

HTML and CSS Code: [Dropdown is working.]

```<code><div class="collapse navbar-collapse">
     <ul class="nav navbar-nav navbar-right">
         <li class="dropdown">
               <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                     <i class="ti-user"></i>
                     <p>You can</p>
                     <b class="caret"></b>
               </a>
               <ul class="dropdown-menu">
                 <li><a href="login.html">Login</a></li>
                 <li><a href="signup.html">Signup</a></li>
               </ul>
         </li>
      </ul>
 </div>
</code>```

HTML and CSS with Angular 2 [Dropdown is not working.]

```<code><div class="collapse navbar-collapse">
     <ul class="nav navbar-nav navbar-right">
         <li class="dropdown">
               <a class="dropdown-toggle" data-toggle="dropdown">
                     <i class="ti-user"></i>
                     <p>You can</p>
                     <b class="caret"></b>
               </a>
               <ul class="dropdown-menu">
                 <li><a [routerLink]="['/login']">Login</a></li>
                 <li><a [routerLink]="['/signup']">Signup</a></li>
               </ul>
         </li>
     </ul>
 </div>
</code>```

答:
Certain Bootstrap Elements do not work in Angular2/4. Luckily the Angular UI team has built out Bootstrap 4 Elements in Angular components.

Follow these instructions to install

Documentation for dropdown

Note: this is tested with angular 4.0.3 so you may have to find the version that works with angular 2.

Body:
Bootstrap dropdown code works fine (without angular 2) but same code is integrated with angular 2, it fails to work as expected.

HTML and CSS Code: [Dropdown is working.]

You can

Login

Signup

HTML and CSS with Angular 2 [Dropdown is not working.]

You can

Login

Signup


问:
Show echo in previous php file
I'm Probably searching with the wrong keywords, but I can not find the correct answer.

I have a php file(overview.php) which contains a button, this button executes another php script(mailinfo.php) which sends a email and shows a echo line when successful .

```<code><input onclick="location.href = 'mailinfo.php';" type="button" value="Nee" class="btn btn-danger btn-md">
</code>```

When I click the button, mail.php is loaded and i only see the echo. I would like to see this echo on overview.php without showing the mail.php page.

答:
Do it in javascript :

  function mailinfo() {
        var p = document.createElement('p');
        var text = document.createTextNode('Your text go here');
        p.appendChild(text);
        document.body.appendChild(p);
        // If you want to give a class or id
        p.className = "text-center";
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input onclick='mailinfo()' type="button" value="Nee" class="btn btn-danger btn-md"></code>```

Title: Show echo in previous php file

Body:
I'm Probably searching with the wrong keywords, but I can not find the correct answer.

I have a php file(overview.php) which contains a button, this button executes another php script(mailinfo.php) which sends a email and shows a echo line when successful .

<input onclick="location.href = 'mailinfo.php';" type="button" value="Nee" class="btn btn-danger btn-md">

When I click the button, mail.php is loaded and i only see the echo. I would like to see this echo on overview.php without showing the mail.php page.

Body:
Do it in javascript :

  function mailinfo() {
        var p = document.createElement('p');
        var text = document.createTextNode('Your text go here');
        p.appendChild(text);
        document.body.appendChild(p);
        // If you want to give a class or id
        p.className = "text-center";
    }

<input onclick='mailinfo()' type="button" value="Nee" class="btn btn-danger btn-md">


问:
Xml card layout
i trying to get a layout just like the image below for a game in android studio

currently my xml is

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dreacot.testmymemory.Game">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="53dp"
    tools:layout_editor_absoluteY="136dp" />

<ImageView
    android:id="@+id/imageView4"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="156dp"
    tools:layout_editor_absoluteY="136dp" />

<ImageView
    android:id="@+id/imageView3"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="266dp"
    tools:layout_editor_absoluteY="136dp" />

<ImageView
    android:id="@+id/imageView6"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="53dp"
    tools:layout_editor_absoluteY="285dp" />

<ImageView
    android:id="@+id/imageView5"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="156dp"
    tools:layout_editor_absoluteY="285dp" />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="266dp"
    tools:layout_editor_absoluteY="285dp" />
</code>```

i want more cards to be added on the next level eg lvl 2
do i need to make several layouts for each level?

also i want each card to show its face when it is clicked

and finally i feel i am not doing the right thing as i feel xml files cannot be called into the gameplay is there a better way to do this layout(maybe programmatically)?

could anyone help?

答:
You have to do it programmatically.

1. Use RecyclerView with GridLayoutManager to show your card as grid style.

2. Create a layout with just a CardView with single ImageView for your single card item.

3. Create an custom RecyclerView.Adapter<> and use it with RecyclerView to populate your card data on CardView.

4. Add onItemClick listener to Adapter to flip to the specific Card item and do something as per your needs.

Here are some useful links about RecyclerView:

Android RecyclerView with GridLayoutManager Example

Android GridLayoutManager with RecyclerView in Material Design

Simple Android grid example using RecyclerView with GridLayoutManager

Here is a good library for CardView animation.

Hope this will help~

Title: Xml card layout

Body:
i trying to get a layout just like the image below for a game in android studio

currently my xml is

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dreacot.testmymemory.Game">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="53dp"
    tools:layout_editor_absoluteY="136dp" />

<ImageView
    android:id="@+id/imageView4"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="156dp"
    tools:layout_editor_absoluteY="136dp" />

<ImageView
    android:id="@+id/imageView3"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="266dp"
    tools:layout_editor_absoluteY="136dp" />

<ImageView
    android:id="@+id/imageView6"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="53dp"
    tools:layout_editor_absoluteY="285dp" />

<ImageView
    android:id="@+id/imageView5"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="156dp"
    tools:layout_editor_absoluteY="285dp" />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="72dp"
    android:layout_height="115dp"
    app:srcCompat="@drawable/backside"
    tools:layout_editor_absoluteX="266dp"
    tools:layout_editor_absoluteY="285dp" />

i want more cards to be added on the next level eg lvl 2
do i need to make several layouts for each level?

also i want each card to show its face when it is clicked

and finally i feel i am not doing the right thing as i feel xml files cannot be called into the gameplay is there a better way to do this layout(maybe programmatically)?

could anyone help?


问:
Python Embeddable Zip File Doesn't Include lib/site-packages in sys.path
I am attempting to update our Python version from 3.4 to 3.6.  We are embedding Python into a C++ application, so it seemed logical to utilize the new (since Python 3.5) Windows x86 embeddable zip file.  However, our application is failing to execute because "lib/site-packages" isn't being added to the sys.path variable.  I have confirmed that after installing Python 3.6 on my machine, and running from the installed location, the sys.path variable contains (relative to the python directory):

```<code>'...\\python36.zip'
'...\\DLLs'
'...\\lib'
'...'
'...\\lib\\site-packages'
</code>```

However, when I run from the embeddable zip file on the same machine, the sys.path variable contains (relative to the python directory):

```<code>'...\\python36.zip'
'...'
'...\\\n'
</code>```

In both cases, the "lib/site-packages" directory exists within the Python directory.  I also don't have a PYTHONPATH environment variable defined.  Does anyone know how to get the embeddable zip file to act the same as the installed version, with respect to how it determines sys.path?

答:
After extracting the Python embeddable zip file, there is a file called
python36._pth in the root directory.  That file contains the following text:

```<code># Uncomment to run site.main() automatically
#import site
</code>```

As the comment indicates, simply uncomment the import site statement by
removing the '#' character.  After doing so, the sys.path variable contains:

```<code>'...\\python36.zip'
'...'
'...\\\n'
'...\\lib\\site-packages'
</code>```

This is still different than the installed version, but is exactly what I
needed in my particular case.

BEGIN EDIT

I also discovered that you can remove the python36._pth file entirely, which
reverts Python to behavior of the non-embeddable version.

Body:
I am attempting to update our Python version from 3.4 to 3.6.  We are embedding Python into a C++ application, so it seemed logical to utilize the new (since Python 3.5) Windows x86 embeddable zip file.  However, our application is failing to execute because "lib/site-packages" isn't being added to the sys.path variable.  I have confirmed that after installing Python 3.6 on my machine, and running from the installed location, the sys.path variable contains (relative to the python directory):

'...\\python36.zip'
'...\\DLLs'
'...\\lib'
'...'
'...\\lib\\site-packages'

However, when I run from the embeddable zip file on the same machine, the sys.path variable contains (relative to the python directory):

'...\\python36.zip'
'...'
'...\\\n'

In both cases, the "lib/site-packages" directory exists within the Python directory.  I also don't have a PYTHONPATH environment variable defined.  Does anyone know how to get the embeddable zip file to act the same as the installed version, with respect to how it determines sys.path?

Body:
After extracting the Python embeddable zip file, there is a file called
python36._pth in the root directory.  That file contains the following text:

# Uncomment to run site.main() automatically
#import site

As the comment indicates, simply uncomment the import site statement by
removing the '#' character.  After doing so, the sys.path variable contains:

'...\\python36.zip'
'...'
'...\\\n'
'...\\lib\\site-packages'

This is still different than the installed version, but is exactly what I
needed in my particular case.

BEGIN EDIT

I also discovered that you can remove the python36._pth file entirely, which
reverts Python to behavior of the non-embeddable version.

ContentLicense: CC BY-SA 4.0


问:
Map Filter and Fold in C++
I have a problem that normally would be well suited for Java streams, but I'm currently using c++11.

The way I would solve this problem in Java is:

```<code>int solution = myList.stream() //myList is an arraylist of MyClass
    .mapToInt(MyClass::GetInt)
    .sum();
</code>```

After exploring the c++ standard library a little, I have learned that
std::transform and std::accumulate exist.

My only problem is that std::transform seems like it can only map from type T to type T, where I need to map from type T to type V (integer), before I can accumulate.

Ideally I'd like to be able to chain this logic together instead of having temporary arrays storing the intermediate results of each step.

Is there an idiomatic c++11 way to accomplish this?

答:
std::transform can transform to a different type, but you don't even need that here. You can just use std::accumulate with a custom operation, like this:

```<code>int solution = std::accumulate(
  begin(myList), end(myList), 0,
  [](int v, const MyClass &c) { return v + c.GetInt(); }
);
</code>```

An alternative way, pretty close to the Java example you've posted, would be to use the Boost.Range library:

```<code>int solution = boost::accumulate(
  myList | boost::adaptors::transformed(boost::mem_fn(&MyClass::GetInt)),
  0
);
</code>```

Title: Map Filter and Fold in C++

Body:
I have a problem that normally would be well suited for Java streams, but I'm currently using c++11.

The way I would solve this problem in Java is:

int solution = myList.stream() //myList is an arraylist of MyClass
    .mapToInt(MyClass::GetInt)
    .sum();

After exploring the c++ standard library a little, I have learned that
std::transform and std::accumulate exist.

My only problem is that std::transform seems like it can only map from type T to type T, where I need to map from type T to type V (integer), before I can accumulate.

Ideally I'd like to be able to chain this logic together instead of having temporary arrays storing the intermediate results of each step.

Is there an idiomatic c++11 way to accomplish this?

Body:
std::transform can transform to a different type, but you don't even need that here. You can just use std::accumulate with a custom operation, like this:

int solution = std::accumulate(
  begin(myList), end(myList), 0,
  [](int v, const MyClass &c) { return v + c.GetInt(); }
);

An alternative way, pretty close to the Java example you've posted, would be to use the Boost.Range library:

int solution = boost::accumulate(
  myList | boost::adaptors::transformed(boost::mem_fn(&MyClass::GetInt)),
  0
);


问:
example of using multiple iterations for SHA512
I need a code example for C#, of how to generate a hash using SHA512 using a random salt and for n number of iterations?  Also, a code example of how to verify hash created by the above method.</p>

答: Don't know what you mean by "verify", but System.Security.Cryptography.SHA512 does what you're looking for. Note that .NET's implementation is not FIPS validated, so if your customers have FIPS compilant mode turned on your program will not function.


问:
Modal segue not working from code
I've already spent the whole day in an issue and did not find a solution yet. I have a UITabBarViewController and I am trying to fire off a modal segue from one of its tabs. I've already created the view I want to segue to, created the segue itself (from the tab's view controller to the target's view controller) and the identifier. In order to test my segue I created a UIButton in my tab and wrote the following code on its action:

```<code>    [self performSegueWithIdentifier:@"showProductInfo" sender:self];
</code>```

The modal segue worked fine. But if I try to write the same code to be performed somewhere else (inside a specific method that is called after I receive a web service response) the segue simply does not work. I get the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver () has no segue with identifier 'showProductInfo''

This is driving me crazy! Any help is more then welcome.

Editting:

Some additional findings:

If I take off the performSegue from the method I am currently using (which by the way is called by DidFinishLoading) and put it on ViewDidLoad the segue is performed successfully.

Thinking that it could be a thread related issue I included the performSegue inside a dispatch_async(dispatch_get_main_queue()... But the error is the same !

答:
The current view controller must have been loaded from a storyboard. If its storyboard property is nil, perhaps because you allocated and initialized the view controller yourself, this method throws an exception.

Make sure you have Storyboard ID for your destination VC (in this example myViewController).

```<code>UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"myStoryboard" bundle:[NSBundle mainBundle]];
UIViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyController"];
[self.navigationController pushViewController:myViewController animated:YES];
</code>```

Title: Modal segue not working from code

Body:
I've already spent the whole day in an issue and did not find a solution yet. I have a UITabBarViewController and I am trying to fire off a modal segue from one of its tabs. I've already created the view I want to segue to, created the segue itself (from the tab's view controller to the target's view controller) and the identifier. In order to test my segue I created a UIButton in my tab and wrote the following code on its action:

    [self performSegueWithIdentifier:@"showProductInfo" sender:self];

The modal segue worked fine. But if I try to write the same code to be performed somewhere else (inside a specific method that is called after I receive a web service response) the segue simply does not work. I get the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver () has no segue with identifier 'showProductInfo''

This is driving me crazy! Any help is more then welcome.

Editting:

Some additional findings:

If I take off the performSegue from the method I am currently using (which by the way is called by DidFinishLoading) and put it on ViewDidLoad the segue is performed successfully.

Thinking that it could be a thread related issue I included the performSegue inside a dispatch_async(dispatch_get_main_queue()... But the error is the same !

Body:
The current view controller must have been loaded from a storyboard. If its storyboard property is nil, perhaps because you allocated and initialized the view controller yourself, this method throws an exception.

Make sure you have Storyboard ID for your destination VC (in this example myViewController).

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"myStoryboard" bundle:[NSBundle mainBundle]];
UIViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyController"];
[self.navigationController pushViewController:myViewController animated:YES];


问:
How to split a string by "," except between certain characters in python?
How to split a string by "," except between certain characters in python?
My data is like:

```<code>('00012+1357','LSC   2','Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,'M0.5',+019,+135,NULL,NULL,NULL,NULL,'000113.19+135830.3')
</code>```

I need to split them by "," except for 'Aa,Ab'.

The result should be:

```<code>("00012+1357" "LSC   2" "Aa,Ab" "2014" "2014" "2" "185" "185" "0.2"  "0.2" "10.7" "13.1" "M0.5" "+019" "+135" "NULL" "NULL" "NULL" "NULL" "000113.19+135830.3")
</code>```

Do you know how to do that?

答: It appears you're trying to parse CSV data. The csv module should be more than sufficient and be able to handle all these edge cases.</p>

Body:
How to split a string by "," except between certain characters in python?
My data is like:

('00012+1357','LSC   2','Aa,Ab',2014,2014,   2,185,185,  0.2,  0.2,10.7,13.1,'M0.5',+019,+135,NULL,NULL,NULL,NULL,'000113.19+135830.3')

I need to split them by "," except for 'Aa,Ab'.

The result should be:

("00012+1357" "LSC   2" "Aa,Ab" "2014" "2014" "2" "185" "185" "0.2"  "0.2" "10.7" "13.1" "M0.5" "+019" "+135" "NULL" "NULL" "NULL" "NULL" "000113.19+135830.3")

Do you know how to do that?


问:
Split a string into a String[] of a specific size
Assuming my delimiter is ',' (comma), I'm looking for a function split that will guarantee that the returned String[] array is a certain size (no more, no less):

```<code>String[] split(String str, int limit);

split("hello", 2);               => ["hello", ""]
split("hello,", 2);              => ["hello", ""]
split(",hello", 2);              => ["", "hello"]
split("hello,world", 2);         => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]
</code>```

See how the array size is always 2? I can get some of this behavior with Pattern.split, but not for every case... How can I do this?

答:
StringUtils.split(string, separator, max) is very close to what you need.

Then you can use ArrayUtils.addAll(result, emptyArray), where emptyArray is an array of size max - result.length.

The functionality you want is too specific, so I doubt there will be anything ready-to-use.

Body:
Assuming my delimiter is ',' (comma), I'm looking for a function split that will guarantee that the returned String[] array is a certain size (no more, no less):

String[] split(String str, int limit);

split("hello", 2);               => ["hello", ""]
split("hello,", 2);              => ["hello", ""]
split(",hello", 2);              => ["", "hello"]
split("hello,world", 2);         => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]

See how the array size is always 2? I can get some of this behavior with Pattern.split, but not for every case... How can I do this?


问:
Render component with concat helper
Is there a way to render component in HTMLBars as argument passed in concat helper?
I have fa-icon ember component and my custom component that displays label. I need to display it like:

```<code>{{my-simple-button label=(concat (fa-icon "pencil") " " (t "myAwesomeTranslate"))}}
</code>```

but, obviously, fa-icon is a component not a helper.

Update.
Thanks! In fact I use ember-async-button with custom messages, and therefore I have to write something like

```<code>{{#async-button as |component state|}}
  {{#if state.isPending}}
    {{if pendingLabel pendingLabel (t 'site.actions.pending')}}
  {{else if state.isDefault}}
    {{label}}
  {{else if state.isRejected}}
    {{label}}
  {{else if state.isFulfilled}}
    {{label}}
  {{/if}}
{{/async-button}}
</code>```

So I want a wrapper like my-simple-button which takes label and pendingLabel and hides those ifs. So I can't use block because I need to set up icons in 4 places. The only option I see is using ifs for icon and pendingIcon properties, but that makes code ugly. So basicly I want to know if there is a way to simplify this...

答:
As far as I know, that's not really possible. Even if it is in some obscure way, passing a pre-rendered component just seems hacky.

The proper approach for this is to have a {{yield}} as part of your label which is a built-in mechanism in Ember to render components from external scope.

```<code>// inside templates/components/my-simple-button.hbs
{{yield}} {{label}}
</code>```

Then you can just pass fa-icon as a child of my-simple-button:

```<code>{{#my-simple-button label="myAwesomeTranslate"}}
  {{fa-icon "pencil"}}
{{/my-simple-button}}
</code>```

And it would render {{fa-icon "pencil"}} instead of {{yield}}.

If you want my-simple-button to specifically support icons, you could include an icon property and use fa-icon instead of yield:

```<code>// inside templates/components/my-simple-button.hbs
{{#if icon}}{{fa-icon icon}}{{/if}} {{label}}
</code>```

And pass it like:

```<code>{{my-simple-button label="myAwesomeTranslate" icon="pencil"}}
</code>```

Title: Render component with concat helper

Body:
Is there a way to render component in HTMLBars as argument passed in concat helper?
I have fa-icon ember component and my custom component that displays label. I need to display it like:

{{my-simple-button label=(concat (fa-icon "pencil") " " (t "myAwesomeTranslate"))}}

but, obviously, fa-icon is a component not a helper.

Update.
Thanks! In fact I use ember-async-button with custom messages, and therefore I have to write something like

{{#async-button as |component state|}}
  {{#if state.isPending}}
    {{if pendingLabel pendingLabel (t 'site.actions.pending')}}
  {{else if state.isDefault}}
    {{label}}
  {{else if state.isRejected}}
    {{label}}
  {{else if state.isFulfilled}}
    {{label}}
  {{/if}}
{{/async-button}}

So I want a wrapper like my-simple-button which takes label and pendingLabel and hides those ifs. So I can't use block because I need to set up icons in 4 places. The only option I see is using ifs for icon and pendingIcon properties, but that makes code ugly. So basicly I want to know if there is a way to simplify this...

Body:
As far as I know, that's not really possible. Even if it is in some obscure way, passing a pre-rendered component just seems hacky.

The proper approach for this is to have a {{yield}} as part of your label which is a built-in mechanism in Ember to render components from external scope.

// inside templates/components/my-simple-button.hbs
{{yield}} {{label}}

Then you can just pass fa-icon as a child of my-simple-button:

{{#my-simple-button label="myAwesomeTranslate"}}
  {{fa-icon "pencil"}}
{{/my-simple-button}}

And it would render {{fa-icon "pencil"}} instead of {{yield}}.

If you want my-simple-button to specifically support icons, you could include an icon property and use fa-icon instead of yield:

// inside templates/components/my-simple-button.hbs
{{#if icon}}{{fa-icon icon}}{{/if}} {{label}}

And pass it like:

{{my-simple-button label="myAwesomeTranslate" icon="pencil"}}


问:
Angular multi step form routing
I am fairly new to angular and I'm building a multi step form using angular 4. Currently the component structure is as follows:

```<code>-apply.component
--step-one.component
--step-two.component
--step-three.component
</code>```

Router is set up like this:

```<code>{
 path: '',
 redirectTo: '/apply',
 pathMatch: 'full'
},
{
 path: 'apply',
 component: ApplyComponent,
 children: [
   {
     path: 'personalInfo',
     component: StepOneComponent,
     outlet: 'step1'
   },
   {
      path: 'employmentInfo',
      component: StepTwoComponent,
      outlet: 'step2'
   }
</code>```

Router outlets in ApplyComponent:

```<code> <router-outlet name="step1">Child 1 in apply comp</router-outlet>
 <router-outlet name="step2">Child 2 in apply comp</router-outlet>
</code>```

As the use completes one section, it should hide as the next sections shows. Each section is a router outlet on the parent component.

I am trying to figure out the best way to orchestrate the show/hide of each section. I have figured out how to activate each route from the previous route but how should I hide or destroy the previous route (section)? Should each section actually be generated in a ? How can I orchestrate interactions (go back/edit/next) for all of the different sections?

Edit: Another idea, should all the components be defined in the parent and then just show/hide as the move to next step and then update route? I might be thinking of this backwards in my current implementation of router updates components instead of components update route.

答:
I would recommend using a single router-outlet to display the steps.  Remove the named router outlet from your routes configuration and remove the name from the router outlet mark up.  I assume you already have next and previous buttons to move between the steps.  Now you don't have to worry about show/hide logic, the router takes care of that for you.  You may need to add Route Guards to prevent the user from tampering with the url.

Your router config would look like this:

```<code>{
 path: 'apply',
 component: ApplyComponent,
 children: [
   {
     path: 'personalInfo',
     component: StepOneComponent
   },
   {
      path: 'employmentInfo',
      component: StepTwoComponent,
   }
}
</code>```

Your single router outlet would look like this:

```<code><router-outlet>Steps will be loaded here</router-outlet>
</code>```

Title: Angular multi step form routing

Body:
I am fairly new to angular and I'm building a multi step form using angular 4. Currently the component structure is as follows:

-apply.component
--step-one.component
--step-two.component
--step-three.component

Router is set up like this:

{
 path: '',
 redirectTo: '/apply',
 pathMatch: 'full'
},
{
 path: 'apply',
 component: ApplyComponent,
 children: [
   {
     path: 'personalInfo',
     component: StepOneComponent,
     outlet: 'step1'
   },
   {
      path: 'employmentInfo',
      component: StepTwoComponent,
      outlet: 'step2'
   }

Router outlets in ApplyComponent:

 <router-outlet name="step1">Child 1 in apply comp</router-outlet>
 <router-outlet name="step2">Child 2 in apply comp</router-outlet>

As the use completes one section, it should hide as the next sections shows. Each section is a router outlet on the parent component.

I am trying to figure out the best way to orchestrate the show/hide of each section. I have figured out how to activate each route from the previous route but how should I hide or destroy the previous route (section)? Should each section actually be generated in a ? How can I orchestrate interactions (go back/edit/next) for all of the different sections?

Edit: Another idea, should all the components be defined in the parent and then just show/hide as the move to next step and then update route? I might be thinking of this backwards in my current implementation of router updates components instead of components update route.

Body:
I would recommend using a single router-outlet to display the steps.  Remove the named router outlet from your routes configuration and remove the name from the router outlet mark up.  I assume you already have next and previous buttons to move between the steps.  Now you don't have to worry about show/hide logic, the router takes care of that for you.  You may need to add Route Guards to prevent the user from tampering with the url.

Your router config would look like this:

{
 path: 'apply',
 component: ApplyComponent,
 children: [
   {
     path: 'personalInfo',
     component: StepOneComponent
   },
   {
      path: 'employmentInfo',
      component: StepTwoComponent,
   }
}

Your single router outlet would look like this:

<router-outlet>Steps will be loaded here</router-outlet>


问:
Nativescript Angular + Webpack + Onesignal plugin
I'm currently working on a project which uses the OneSignal NS plugin for push notifications.

It works fine, and it used to build / run correctly with Webpack enabled until I started using the OneSignal plugin.

I'm not exactly shure on how to configure my project to get a Webpack build.

This is the plugin I'm referring to: https://github.com/roblav96/nativescript-onesignal

It asks to add this line on the source code to use it (and this is which I'm currently doing), so I did, for example, in a file named main.module.ts:

let TnsOneSignal = require("nativescript-onesignal").TnsOneSignal;

I've found I should register the modules I'm using with Webpack, and I've tried a few things, but it didn't work.

Something like this:

global.registerModule("nativescript-onesignal", ()=> require('../nodemodules/nativescript-onesignal'));

The error(s) I get are like this:

```<code>ERROR in ./modules/main/main.module.ts
Module not found: Error: Can't resolve 'nativescript-onesignal' in
'EDITED-APP-PATH/my-app/app/modules/main'
@ ./modules/main/main.module.ts 8:19-52
@ ./app.module.ngfactory.ts
@ ./main.aot.ts
</code>```

I've found some topics on this forum: https://discourse.nativescript.org, but I couldn't get any working solution from them.

Any help or hints will be appreciated.

This is my current package.json:

```<code>{
  "description": "App",
  "license": "LicenseRef-LICENSE",
  "readme": "README",
  "nativescript": {
    "id": "com.app.name"
  },
  "dependencies": {
    "@angular/animations": "~4.1.0",
    "@angular/common": "~4.1.0",
    "@angular/compiler": "~4.1.0",
    "@angular/core": "~4.1.0",
    "@angular/forms": "~4.1.0",
    "@angular/http": "~4.1.0",
    "@angular/platform-browser": "~4.1.0",
    "@angular/router": "~4.1.0",
    "nativescript-angular": "~3.0.0",
    "nativescript-iqkeyboardmanager": "^1.0.1",
    "nativescript-localize": "^2.0.1",
    "nativescript-onesignal": "^1.0.6",
    "nativescript-telerik-ui": "^2.0.1",
    "nativescript-theme-core": "~1.0.2",
    "reflect-metadata": "~0.1.8",
    "rxjs": "~5.3.0",
    "tns-core-modules": "^3.0.1",
    "zone.js": "~0.8.2"
  },
  "devDependencies": {
    "@angular/compiler-cli": "~4.1.0",
    "@ngtools/webpack": "1.3.1",
    "babel-traverse": "6.24.1",
    "babel-types": "6.24.1",
    "babylon": "6.17.1",
    "copy-webpack-plugin": "~4.0.1",
    "extract-text-webpack-plugin": "~2.1.0",
    "lazy": "1.0.11",
    "nativescript-css-loader": "~0.26.0",
    "nativescript-custom-entitlements": "^0.2.0",
    "nativescript-dev-sass": "^1.1.1",
    "nativescript-dev-typescript": "~0.4.0",
    "nativescript-dev-webpack": "^0.6.0",
    "raw-loader": "~0.5.1",
    "resolve-url-loader": "~2.0.2",
    "tns-platform-declarations": "^3.0.0-rc.2",
    "typescript": "~2.2.1",
    "webpack": "~2.5.1",
    "webpack-sources": "~0.2.3"
  },
  "scripts": {
    "ns-bundle": "ns-bundle",
    "start-android-bundle": "npm run ns-bundle --android --start-app",
    "start-ios-bundle": "npm run ns-bundle --ios --start-app",
    "build-android-bundle": "npm run ns-bundle --android --build-app",
    "build-ios-bundle": "npm run ns-bundle --ios --build-app",
    "publish-ios-bundle": "npm run ns-bundle --ios --publish-app"
  }
}
</code>```

答:
I'll mark this comment from Nick Illiev as the right answer to my problem.

Nativescript Angular + Webpack + Onesignal plugin

Thank you!

Body:
I'm currently working on a project which uses the OneSignal NS plugin for push notifications.

It works fine, and it used to build / run correctly with Webpack enabled until I started using the OneSignal plugin.

I'm not exactly shure on how to configure my project to get a Webpack build.

This is the plugin I'm referring to: https://github.com/roblav96/nativescript-onesignal

It asks to add this line on the source code to use it (and this is which I'm currently doing), so I did, for example, in a file named main.module.ts:

let TnsOneSignal = require("nativescript-onesignal").TnsOneSignal;

I've found I should register the modules I'm using with Webpack, and I've tried a few things, but it didn't work.

Something like this:

global.registerModule("nativescript-onesignal", ()=> require('../nodemodules/nativescript-onesignal'));

The error(s) I get are like this:

ERROR in ./modules/main/main.module.ts
Module not found: Error: Can't resolve 'nativescript-onesignal' in
'EDITED-APP-PATH/my-app/app/modules/main'
@ ./modules/main/main.module.ts 8:19-52
@ ./app.module.ngfactory.ts
@ ./main.aot.ts

I've found some topics on this forum: https://discourse.nativescript.org, but I couldn't get any working solution from them.

Any help or hints will be appreciated.

This is my current package.json:

{
  "description": "App",
  "license": "LicenseRef-LICENSE",
  "readme": "README",
  "nativescript": {
    "id": "com.app.name"
  },
  "dependencies": {
    "@angular/animations": "~4.1.0",
    "@angular/common": "~4.1.0",
    "@angular/compiler": "~4.1.0",
    "@angular/core": "~4.1.0",
    "@angular/forms": "~4.1.0",
    "@angular/http": "~4.1.0",
    "@angular/platform-browser": "~4.1.0",
    "@angular/router": "~4.1.0",
    "nativescript-angular": "~3.0.0",
    "nativescript-iqkeyboardmanager": "^1.0.1",
    "nativescript-localize": "^2.0.1",
    "nativescript-onesignal": "^1.0.6",
    "nativescript-telerik-ui": "^2.0.1",
    "nativescript-theme-core": "~1.0.2",
    "reflect-metadata": "~0.1.8",
    "rxjs": "~5.3.0",
    "tns-core-modules": "^3.0.1",
    "zone.js": "~0.8.2"
  },
  "devDependencies": {
    "@angular/compiler-cli": "~4.1.0",
    "@ngtools/webpack": "1.3.1",
    "babel-traverse": "6.24.1",
    "babel-types": "6.24.1",
    "babylon": "6.17.1",
    "copy-webpack-plugin": "~4.0.1",
    "extract-text-webpack-plugin": "~2.1.0",
    "lazy": "1.0.11",
    "nativescript-css-loader": "~0.26.0",
    "nativescript-custom-entitlements": "^0.2.0",
    "nativescript-dev-sass": "^1.1.1",
    "nativescript-dev-typescript": "~0.4.0",
    "nativescript-dev-webpack": "^0.6.0",
    "raw-loader": "~0.5.1",
    "resolve-url-loader": "~2.0.2",
    "tns-platform-declarations": "^3.0.0-rc.2",
    "typescript": "~2.2.1",
    "webpack": "~2.5.1",
    "webpack-sources": "~0.2.3"
  },
  "scripts": {
    "ns-bundle": "ns-bundle",
    "start-android-bundle": "npm run ns-bundle --android --start-app",
    "start-ios-bundle": "npm run ns-bundle --ios --start-app",
    "build-android-bundle": "npm run ns-bundle --android --build-app",
    "build-ios-bundle": "npm run ns-bundle --ios --build-app",
    "publish-ios-bundle": "npm run ns-bundle --ios --publish-app"
  }
}


问:
Prevent div collapsing if child min-with set
I have the following markup:

```<code><html>
<head>
    <style>
        html,
        body {
            margin: 0;
            width: 100%;
            background: #000;
        }

        .wrapper {
            min-width: 1000px;
            background: #f00;
            height: 300px;
        }
    </style>
</head>
<body>
    <div class="problem-div">
        <div class="wrapper"></div>
    </div>
</body>
</html>
</code>```

When I resize the browser window DIV.problem-div takes the body, html or viewport with (I dont know exactly). What i need is to make that div to take width of its child (.wrapper) without setting its min-width or making it positioned absolute. Is it possible?

答:
Divs are block level elements that will always have a width of 100%.  Set the display property to inline-block and that should get you the desired result.</p>

```<code>.problem-div {
    display: inline-block;
}
</code>```

Body:
I have the following markup:

When I resize the browser window DIV.problem-div takes the body, html or viewport with (I dont know exactly). What i need is to make that div to take width of its child (.wrapper) without setting its min-width or making it positioned absolute. Is it possible?

Body:
Divs are block level elements that will always have a width of 100%.  Set the display property to inline-block and that should get you the desired result.

.problem-div {
    display: inline-block;
}


问:
How do I get sourcemap files to output to my build folder?
I have a minimal webpack1 config that I've whittled a massive project down to just to reproduce this.

When I run my config with webpack-dev-server it works just fine, except the file is only accessible at localhost:port/bundle.js.map not in my local projects dist folder.

link to repo with instructions: https://github.com/rublev/webpack-nosourcemaps

webpack.config.base.js

```<code>module.exports = {
    output: {
        path: path.join(process.cwd(), '/dist'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    resolve: {
        root: path.join(__dirname, ''),
        modulesDirectories: [
            'node_modules',
            'app'
        ],
        extensions: ['', '.html', '.js'] // removing '' makes everything explode
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'webpack-sourcemap',
            template: 'app/index.html'
        })
    ],
    module: {
        loaders: [],
    }
}
</code>```

webpack.config.production.js

```<code>var config = require('./webpack.config.base.js')

config.devtool = 'source-map'

if (process.env.NODE_ENV !== 'test') {
    config.entry = {
        main: path.join(process.cwd(), '/app/') + 'app.js',
        vendor: [
            'react',
            'react-dom'
        ]
    }
}

config.output = {
    path: path.join(process.cwd(), '/dist'),
    pathInfo: true,
    publicPath: '/',
    filename: 'bundle.js'
}

config.module.loaders = config.module.loaders.concat([
    {
        test: /\.js$/,
        loaders: ['babel'],
        exclude: /node_modules/
    }
])

config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        filename: 'vendor.js'
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
            warnings: false
        }
    }),
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('production')
        }
    })
])

module.exports = config
</code>```

答:
Add to your production config config.devtool = 'source-map'; for the highest quality production source-map.

Other production options are cheap-source-map, cheap-module-source-map, and nosources-source-map.

And it's good that you already have sourceMap: true set within your UglifyJsPlugin, or else the source-map files wouldn't be generated.

Resource:
https://webpack.js.org/configuration/devtool/

Body:
I have a minimal webpack1 config that I've whittled a massive project down to just to reproduce this.

When I run my config with webpack-dev-server it works just fine, except the file is only accessible at localhost:port/bundle.js.map not in my local projects dist folder.

link to repo with instructions: https://github.com/rublev/webpack-nosourcemaps

webpack.config.base.js

module.exports = {
    output: {
        path: path.join(process.cwd(), '/dist'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    resolve: {
        root: path.join(__dirname, ''),
        modulesDirectories: [
            'node_modules',
            'app'
        ],
        extensions: ['', '.html', '.js'] // removing '' makes everything explode
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'webpack-sourcemap',
            template: 'app/index.html'
        })
    ],
    module: {
        loaders: [],
    }
}

webpack.config.production.js

var config = require('./webpack.config.base.js')

config.devtool = 'source-map'

if (process.env.NODE_ENV !== 'test') {
    config.entry = {
        main: path.join(process.cwd(), '/app/') + 'app.js',
        vendor: [
            'react',
            'react-dom'
        ]
    }
}

config.output = {
    path: path.join(process.cwd(), '/dist'),
    pathInfo: true,
    publicPath: '/',
    filename: 'bundle.js'
}

config.module.loaders = config.module.loaders.concat([
    {
        test: /\.js$/,
        loaders: ['babel'],
        exclude: /node_modules/
    }
])

config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        filename: 'vendor.js'
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
            warnings: false
        }
    }),
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('production')
        }
    })
])

module.exports = config


答:
Checkout this link, it has code for salting and using other hashes other than sha512 and is liberally commented.

To rehash the hash all you would have to do is first compute the hash string and then use Byte to get a hex-encoded string that you could then hash again.

Title: example of using multiple iterations for SHA512

Body: I need a code example for C#, of how to generate a hash using SHA512 using a random salt and for n number of iterations?  Also, a code example of how to verify hash created by the above method.


问:
Partition linked list around a value x : Cracking the coding Interview book
I am trying to solve an interview question such that the given linked list needs to be partition around a value say 'x'. I gave an attempt to it but not getting the desired result.

```<code>class Node(object):
    def __init__(self, val):
        self.val = val
        self.next = None

def Partition(head, x):
    x_node = Node(x)
    x_node.next = head
    current = head
    last = x_node
    while current:
        if current.val < x_node.val:
            last = last.next
            temp_val = current.val
            current.val = last.val
            last.val = temp_val
        current = current.next
    temp_val = last.val
    last.val = x_node.val
    x_node.val = temp_val

Partition(head,3)

Input:           1->4->3->2->5->2
Actual Output:   1->2->3->4->5->3
Expected Output: 1->2->2->3->4->5
</code>```

Thanks in advance.

答:
For [9,2,9,3,5,8,5,10,2,1] (which I magically convert to a ll behind the scenes), I'm getting 1,2,3,2,9,9,5,8,5,10 for value 5.

The question is to have all items less than the value to the left of all items greater than or equal to the value, where the value itself can appear anywhere in the right partition. Notice 9 is appearing before 5, which is as expected.

```<code>class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

def partition(node, val):
b_n = node
head = node
right = False
while node:
    if node.data < val:
        if node == head:
            node = node.next
        else:
            head = Node(node.data, head)
            b_n.next = node.next
    else:
        right = True
        if right:
            r_e = node
    b_n = node
    node = node.next
r_e.next = None
return head

ll5 = Linked_List()
ll5.build_from_list([9,2,9,3,5,8,5,10,2,1])
ll6.head = partition(ll5.head, 5)
ll6.iterate()
</code>```

.build_from_list(), and .iterate() are methods that I built into my Linked_List() class.

Body:
I am trying to solve an interview question such that the given linked list needs to be partition around a value say 'x'. I gave an attempt to it but not getting the desired result.

class Node(object):
    def __init__(self, val):
        self.val = val
        self.next = None

def Partition(head, x):
    x_node = Node(x)
    x_node.next = head
    current = head
    last = x_node
    while current:
        if current.val < x_node.val:
            last = last.next
            temp_val = current.val
            current.val = last.val
            last.val = temp_val
        current = current.next
    temp_val = last.val
    last.val = x_node.val
    x_node.val = temp_val

Partition(head,3)

Input:           1->4->3->2->5->2
Actual Output:   1->2->3->4->5->3
Expected Output: 1->2->2->3->4->5

Thanks in advance.

Body:
For [9,2,9,3,5,8,5,10,2,1] (which I magically convert to a ll behind the scenes), I'm getting 1,2,3,2,9,9,5,8,5,10 for value 5.

The question is to have all items less than the value to the left of all items greater than or equal to the value, where the value itself can appear anywhere in the right partition. Notice 9 is appearing before 5, which is as expected.

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

def partition(node, val):
b_n = node
head = node
right = False
while node:
    if node.data < val:
        if node == head:
            node = node.next
        else:
            head = Node(node.data, head)
            b_n.next = node.next
    else:
        right = True
        if right:
            r_e = node
    b_n = node
    node = node.next
r_e.next = None
return head

ll5 = Linked_List()
ll5.build_from_list([9,2,9,3,5,8,5,10,2,1])
ll6.head = partition(ll5.head, 5)
ll6.iterate()

.build_from_list(), and .iterate() are methods that I built into my Linked_List() class.


问:
Why does Django think my query string is empty?
I've been having trouble with a query string in one of my views in Django. I've successfully handled query strings in other views, so I'm not sure what I did wrong here. I stripped things down to a really basic view, and I'm still not getting anything.

My URL:

localhost/query_view/?foo=foo
```

<p>My template:</p>

<pre class="lang-html prettyprint-override"><code><html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <p>{{ query_string }}</p>
    </body>
</html>
</code>```

My view:

def query_view(request):
    query_string = request.META['QUERY_STRING']
    return render(request, 'query_view.html', {'query_string': query_string})
```

I should expect foo=foo to be displayed on the page, right? Currently, I'm getting nothing.

Edit: Django version 1.9.4, Python version 3.4.3

答:
try

```<code> def query_view(request):
     query_string = request.GET.get('foo',None)
     print(query_string)
     return render(request, 'query_view.html', {'query_string': query_string})
</code>```

and check if query_string value is None or not .

Let me know, if it didn't work out!

Inaddition  mention your django and python version also.

Body:
I've been having trouble with a query string in one of my views in Django. I've successfully handled query strings in other views, so I'm not sure what I did wrong here. I stripped things down to a really basic view, and I'm still not getting anything.

My URL:

localhost/query_view/?foo=foo

My template:

        <title>Title</title>

{{ query_string }}

My view:

def query_view(request):
    query_string = request.META['QUERY_STRING']
    return render(request, 'query_view.html', {'query_string': query_string})

I should expect foo=foo to be displayed on the page, right? Currently, I'm getting nothing.

Edit: Django version 1.9.4, Python version 3.4.3

Body:
try

 def query_view(request):
     query_string = request.GET.get('foo',None)
     print(query_string)
     return render(request, 'query_view.html', {'query_string': query_string})

and check if query_string value is None or not .

Let me know, if it didn't work out!

Inaddition  mention your django and python version also.


问:
jwt_auth_no_auth_header error on validating WordPress REST API JWT token
I have two AWS instances, one for WordPress website and another for React application. To connect them together I am using "WP REST API - OAuth 1.0a Server" and "JWT Authentication for WP-API" for accessing WP REST API.

I am able to generate token by /wp-json/jwt-auth/v1/token but when I am trying to access any other endpoint or if trying to validate the token by /wp-json/jwt-auth/v1/token/validate I am getting following error :

```<code>{
  "code": "jwt_auth_no_auth_header",
  "message": "Authorization header not found.",
  "data": {
    "status": 403
  }
}
</code>```

I looked up and found few things to add to .htaccess. I added everything I could find but had no success.

```<code>RewriteEngine On
RewriteBase /

# Enable HTTP Auth
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

# WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# For SetEnvIf Authorization
#RewriteRule (.*) - [env=myenv:1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
#SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
</code>```

I added following code to see if any Authorization Header is present in the request but there isn't any

```<code>add_filter( 'rest_pre_dispatch', 'prefix_show_request_headers', 10, 3 );
function prefix_show_request_headers( $result, $server, $request ) {
    $result = $request->get_headers();
    return $result;
}
</code>```

Here (https://github.com/Tmeister/wp-api-jwt-auth/issues/6) I read that WordPress is maybe trying to authenticate via cookie method by default and is throwing error and not reaching JWT authentication so I added this piece of code but still no success

```<code>add_filter( 'rest_authentication_errors', '__return_true' );
</code>```

At last I added "JSON Basic Authentication" plugin which also sends username:password in the Headers and it works. So I am not sure if it's an issue with Headers being stripped. As it is not recommended for production server so I need JWT authentication to work.

Any help is appreciated.

答:
In case someone else faces this issue, this code that I added to .htaccess is probably not working

```<code># Enable HTTP Auth
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
</code>```

So in the plugin file jwt-authentication-for-wp-rest-api/class-jwt-auth-public.php, look in the function named validate_token, after the $auth check fails I added this piece of code :

```<code>if (!$auth) {
    $allHeaders = getallheaders();
    $auth = isset($allHeaders['Authorization']) ? $allHeaders['Authorization'] : false;
}
</code>```

This will get that Authorization header and JWT will work as expected

Body:
I have two AWS instances, one for WordPress website and another for React application. To connect them together I am using "WP REST API - OAuth 1.0a Server" and "JWT Authentication for WP-API" for accessing WP REST API.

I am able to generate token by /wp-json/jwt-auth/v1/token but when I am trying to access any other endpoint or if trying to validate the token by /wp-json/jwt-auth/v1/token/validate I am getting following error :

{
  "code": "jwt_auth_no_auth_header",
  "message": "Authorization header not found.",
  "data": {
    "status": 403
  }
}

I looked up and found few things to add to .htaccess. I added everything I could find but had no success.

RewriteEngine On
RewriteBase /

# Enable HTTP Auth
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

# WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# For SetEnvIf Authorization
#RewriteRule (.*) - [env=myenv:1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
#SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0

I added following code to see if any Authorization Header is present in the request but there isn't any

add_filter( 'rest_pre_dispatch', 'prefix_show_request_headers', 10, 3 );
function prefix_show_request_headers( $result, $server, $request ) {
    $result = $request->get_headers();
    return $result;
}

Here (https://github.com/Tmeister/wp-api-jwt-auth/issues/6) I read that WordPress is maybe trying to authenticate via cookie method by default and is throwing error and not reaching JWT authentication so I added this piece of code but still no success

add_filter( 'rest_authentication_errors', '__return_true' );

At last I added "JSON Basic Authentication" plugin which also sends username:password in the Headers and it works. So I am not sure if it's an issue with Headers being stripped. As it is not recommended for production server so I need JWT authentication to work.

Any help is appreciated.

Body:
In case someone else faces this issue, this code that I added to .htaccess is probably not working

# Enable HTTP Auth
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

So in the plugin file jwt-authentication-for-wp-rest-api/class-jwt-auth-public.php, look in the function named validate_token, after the $auth check fails I added this piece of code :

if (!$auth) {
    $allHeaders = getallheaders();
    $auth = isset($allHeaders['Authorization']) ? $allHeaders['Authorization'] : false;
}

This will get that Authorization header and JWT will work as expected


问:
Issue sending mail message from ASP.NET MVC application hosted on GoDaddy
I have a form on a MVC Web Application that is hosted over at GoDaddy that users can fill out and send to our office. I am currently testing it using both a Gmail account and a GoDaddy email account (linked to my hosting space).  With the Gmail code in place, the email will send fine from my localhost, but when I publish it to the web I get the following error:

Request for the permission of type 'System.Net.Mail.SmtpPermission,
  System, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089' failed.

Here is the code (borrowed from this post) I am using, credentials have been changed and password removed:

```<code>var fromAddress = new MailAddress("iihs.eval@gmail.com", "FEA Drone");
var toAddress = new MailAddress("improveithomeservices@gmail.com", "ImproveIt Home Services");
const string fromPassword = "<removed>";
var subject = string.Format("Energy Evaluation Request for {0} {1}", model.FirstName, model.LastName);
var body = MailBody(results);

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}
</code>```

I then tried to use my GoDaddy email that I set up for this particular form, and again locally it sends. However, when this one is uploaded it just times out rather than give me any sort of useful information. Here is that code:

```<code>var fromAddress = new MailAddress("fea@goimproveit.com", "FEA Drone");
var toAddress = new MailAddress("improveithomeservices@gmail.com", "ImproveIt! Home Services");
const string fromPassword = "<removed>";
var client = new SmtpClient
{
    Host = "relay-hosting.secureserver.net",
    Port = 25,
    EnableSsl = false,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Timeout = 20000,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};

using (var msg = new MailMessage(fromAddress, toAddress)
{
    Subject = string.Format("Energy Evaluation Request for {0} {1}", model.FirstName, model.LastName),
    IsBodyHtml = false,
    Body = MailBody(results)
})
{
    client.Send(msg);
}
</code>```

Originally I had smtpout.secureserver.net for my GoDaddy Host, but I found out from this article that I needed to change it to relay-hosting.secureserver.net. With the updated host information, the script runs but the mail message does not make it to the destination email inbox (or spam box).

Edit

Using Maxim's code, it seems I have gotten a "functioning" version in place. The email does not immediately appear in the destination inbox, but does so after about 15 minutes. Too bad it seems that GoDaddy is a giant PITA when it comes to programmatic emailing.

Here is what I got:

```<code>var emailmessage = new System.Web.Mail.MailMessage()
{
    Subject = subject,
    Body = body,
    From = fromAddress.Address,
    To = toAddress.Address,
    BodyFormat = MailFormat.Text,
    Priority = System.Web.Mail.MailPriority.High
};

SmtpMail.SmtpServer = "relay-hosting.secureserver.net";
SmtpMail.Send(emailmessage);
</code>```

Thanks again for the assistance, I hope that I can figure out how to get GoDaddy to cooperate better. If I can, I will post back with updates.

答:
Don't recall where I found this code, but it works for me on my GoDaddy server for sending email via a google account:

```<code>public class GmailService : IEmailService
{
    private static int _port = 465;
    private readonly string _accountName;
    private readonly string _password;

    public GmailService(string accountName, string password)
    {
        _accountName = accountName;
        _password = password;
    }
    public void Send(string from, string to, string subject, string body, bool isHtml)
    {
        Send(from, to, subject, body, isHtml, null);
    }

    public void Send(string from, string to, string subject, string body, bool isHtml, string[] attachments)
    {
        System.Web.Mail.MailMessage mailMessage = new System.Web.Mail.MailMessage
                                                      {
                                                          From = from,
                                                          To = to,
                                                          Subject = subject,
                                                          Body = body,
                                                          BodyFormat = isHtml ? MailFormat.Html : MailFormat.Text
                                                      };

        // Add attachments
        if (attachments != null)
        {
            for (int i = 0; i < attachments.Length; i++)
            {
                mailMessage.Attachments.Add(new Attachment(attachments[i]));
            }
        }

        //  Authenticate
        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
        // Username for gmail - email@domain.com for email for Google Apps
        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _accountName);
        // Password for gmail account
        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _password);
        // Google says to use 465 or 587.  I don't get an answer on 587 and 465 works - YMMV
        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _port.ToString());
        // STARTTLS
        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);

        // assign outgoing gmail server
        SmtpMail.SmtpServer = "smtp.gmail.com";
        SmtpMail.Send(mailMessage);
    }
}
</code>```

Update: Here is how I am using this code:

```<code>GmailService gmail = new GmailService("do_not_reply@bobcravens.com", "the_password");
const string from = "Email Service <do_not_reply@bobcravens.com>";
const string to = "my_email_address";
const string subject = "Contact Form";
string body = "your message";
gmail.Send(from, to, subject, body, false);
</code>```

This may make a difference...I have a Google Apps account (free). Therefore, I am able to have the from address the same domain as my server.

Body:
I have a form on a MVC Web Application that is hosted over at GoDaddy that users can fill out and send to our office. I am currently testing it using both a Gmail account and a GoDaddy email account (linked to my hosting space).  With the Gmail code in place, the email will send fine from my localhost, but when I publish it to the web I get the following error:

Request for the permission of type 'System.Net.Mail.SmtpPermission,
  System, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089' failed.

Here is the code (borrowed from this post) I am using, credentials have been changed and password removed:

var fromAddress = new MailAddress("iihs.eval@gmail.com", "FEA Drone");
var toAddress = new MailAddress("improveithomeservices@gmail.com", "ImproveIt Home Services");
const string fromPassword = "<removed>";
var subject = string.Format("Energy Evaluation Request for {0} {1}", model.FirstName, model.LastName);
var body = MailBody(results);

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

I then tried to use my GoDaddy email that I set up for this particular form, and again locally it sends. However, when this one is uploaded it just times out rather than give me any sort of useful information. Here is that code:

var fromAddress = new MailAddress("fea@goimproveit.com", "FEA Drone");
var toAddress = new MailAddress("improveithomeservices@gmail.com", "ImproveIt! Home Services");
const string fromPassword = "<removed>";
var client = new SmtpClient
{
    Host = "relay-hosting.secureserver.net",
    Port = 25,
    EnableSsl = false,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Timeout = 20000,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};

using (var msg = new MailMessage(fromAddress, toAddress)
{
    Subject = string.Format("Energy Evaluation Request for {0} {1}", model.FirstName, model.LastName),
    IsBodyHtml = false,
    Body = MailBody(results)
})
{
    client.Send(msg);
}

Originally I had smtpout.secureserver.net for my GoDaddy Host, but I found out from this article that I needed to change it to relay-hosting.secureserver.net. With the updated host information, the script runs but the mail message does not make it to the destination email inbox (or spam box).

Edit

Using Maxim's code, it seems I have gotten a "functioning" version in place. The email does not immediately appear in the destination inbox, but does so after about 15 minutes. Too bad it seems that GoDaddy is a giant PITA when it comes to programmatic emailing.

Here is what I got:

var emailmessage = new System.Web.Mail.MailMessage()
{
    Subject = subject,
    Body = body,
    From = fromAddress.Address,
    To = toAddress.Address,
    BodyFormat = MailFormat.Text,
    Priority = System.Web.Mail.MailPriority.High
};

SmtpMail.SmtpServer = "relay-hosting.secureserver.net";
SmtpMail.Send(emailmessage);

Thanks again for the assistance, I hope that I can figure out how to get GoDaddy to cooperate better. If I can, I will post back with updates.

Body:
Don't recall where I found this code, but it works for me on my GoDaddy server for sending email via a google account:

public class GmailService : IEmailService
{
    private static int _port = 465;
    private readonly string _accountName;
    private readonly string _password;

    public GmailService(string accountName, string password)
    {
        _accountName = accountName;
        _password = password;
    }
    public void Send(string from, string to, string subject, string body, bool isHtml)
    {
        Send(from, to, subject, body, isHtml, null);
    }

    public void Send(string from, string to, string subject, string body, bool isHtml, string[] attachments)
    {
        System.Web.Mail.MailMessage mailMessage = new System.Web.Mail.MailMessage
                                                      {
                                                          From = from,
                                                          To = to,
                                                          Subject = subject,
                                                          Body = body,
                                                          BodyFormat = isHtml ? MailFormat.Html : MailFormat.Text
                                                      };

        // Add attachments
        if (attachments != null)
        {
            for (int i = 0; i < attachments.Length; i++)
            {
                mailMessage.Attachments.Add(new Attachment(attachments[i]));
            }
        }

        //  Authenticate
        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
        // Username for gmail - email@domain.com for email for Google Apps
        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _accountName);
        // Password for gmail account
        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _password);
        // Google says to use 465 or 587.  I don't get an answer on 587 and 465 works - YMMV
        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _port.ToString());
        // STARTTLS
        mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);

        // assign outgoing gmail server
        SmtpMail.SmtpServer = "smtp.gmail.com";
        SmtpMail.Send(mailMessage);
    }
}

Update: Here is how I am using this code:

GmailService gmail = new GmailService("do_not_reply@bobcravens.com", "the_password");
const string from = "Email Service <do_not_reply@bobcravens.com>";
const string to = "my_email_address";
const string subject = "Contact Form";
string body = "your message";
gmail.Send(from, to, subject, body, false);

This may make a difference...I have a Google Apps account (free). Therefore, I am able to have the from address the same domain as my server.