问:
Type Hints Convention for Instance Variables Python
I'm unsure of the Python convention for type hinting instance variables - I've been doing them within the __init__ constructor arguments like seen here:

```<code>class LoggedVar(Generic[T]):
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value`
</code>```

But I also see the PEP conventions of annotating instance variables as such (snippet below) and then also doing type hinting within the __init__ arguments:

```<code>class BasicStarship:
    captain: str = 'Picard'               # instance variable with default
    damage: int                           # instance variable without default
    stats: ClassVar[Dict[str, int]] = {}  # class variable`

    def __init__(self, damage: int, captain: str = None):
        self.damage = damage
        if captain:
            self.captain = captain  # Else keep the default
</code>```

Lastly, later on in the PEP 526 article they say one can do the following for convenience and convention:

```<code>class Box(Generic[T]):
    def __init__(self, content):
        self.content: T = content
</code>```

(Both of the above code snippets are from here.)

So — is one of these conventions better/more widely accepted than the others that I should try to stick to (better readability etc..)?

答:
I'd stick with what you're doing in LoggedVar, it follows the same rules as everywhere else in Python, so there's less confusion all round.

The BasicStarShip class changes the scope of the variables by moving them out of the __init__ function. With captain declared there, BasicStarShip.captain, will return 'Picard'.

The PEP 526 annotations are nice to read, but it's a new rule for one specific case, the __init__ function. From the Zen of Python:

"Special cases aren't special enough to break the rules."

Body:
I'm unsure of the Python convention for type hinting instance variables - I've been doing them within the __init__ constructor arguments like seen here:

class LoggedVar(Generic[T]):
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value`

But I also see the PEP conventions of annotating instance variables as such (snippet below) and then also doing type hinting within the __init__ arguments:

class BasicStarship:
    captain: str = 'Picard'               # instance variable with default
    damage: int                           # instance variable without default
    stats: ClassVar[Dict[str, int]] = {}  # class variable`

    def __init__(self, damage: int, captain: str = None):
        self.damage = damage
        if captain:
            self.captain = captain  # Else keep the default

Lastly, later on in the PEP 526 article they say one can do the following for convenience and convention:

class Box(Generic[T]):
    def __init__(self, content):
        self.content: T = content

(Both of the above code snippets are from here.)

So — is one of these conventions better/more widely accepted than the others that I should try to stick to (better readability etc..)?


来源: stackexchange

问:
C++: Array with custom size in class
I want to do this:

```<code>class Graphic
{
    int *array;
    Graphic( int size )
    {
        int temp_array[size];
        array = temp_array;
        glGenTextures( size, array );
    }
}
</code>```

Will this work? And even if it will, is there a better way to do this?

Thanks.

答:
Using new means you have to remember to delete [] it; using compiler-dependent variable-size arrays means you lose portability.

It's much better to use a vector.

```<code>#include <vector>

class Graphic
{
    std::vector<int> array;
    Graphic( int size )
    {
        array.resize(size);
        glGenTextures( size, &array[0] );
    }
}
</code>```

The language guarantees that vector elements will be contiguous in memory so it's safe to do &array[0] here.

ContentLicense: CC BY-SA 2.5

Title: C++: Array with custom size in class

Body:
I want to do this:

class Graphic
{
    int *array;
    Graphic( int size )
    {
        int temp_array[size];
        array = temp_array;
        glGenTextures( size, array );
    }
}

Will this work? And even if it will, is there a better way to do this?

Thanks.

Body:
Using new means you have to remember to delete [] it; using compiler-dependent variable-size arrays means you lose portability.

It's much better to use a vector.

#include <vector>

class Graphic
{
    std::vector<int> array;
    Graphic( int size )
    {
        array.resize(size);
        glGenTextures( size, &array[0] );
    }
}

The language guarantees that vector elements will be contiguous in memory so it's safe to do &array[0] here.


问:
VBA scrape website to get all artist names and albums?
Ok, I`m totally clueless about what I need to do regarding this topic...

Here is code. I took first some links from website, and then I should follow link by link and take some data from that website...

```<code>Sheets("LINKS TEMP").Activate

Dim httpObject As Object
Set httpObject = CreateObject("MSXML2.XMLHTTP")
Dim doc As Object
Set doc = CreateObject("htmlfile")
Dim links As Variant
Dim l As Variant

With httpObject
    .Open "GET", "http://www.smoothjazz.com/charts/", False
    .Send
    Do Until httpObject.ReadyState = 4
    Loop
    doc.body.innerhtml = .responseText
    Set links = doc.getElementsByTagName("a")
    I = 1
    For Each l In links
        Sheets("LINKS TEMP").Cells(I, 2).Value = l.href
        I = I + 1
    Next l
End With

Sheets("LINKS TEMP").Activate
lrLINKS = Cells(Rows.Count, "B").End(xlUp).Row
copyLINKS = 1
For deleteLINKS = 1 To lrLINKS
If Cells(deleteLINKS, 2).Value Like "*votesbytrack*" Then GoTo copyLOOP
GoTo nextLOOP
copyLOOP:
Cells(deleteLINKS, 2).Copy
Cells(copyLINKS, 1).PasteSpecial xlPasteValues
copyLINKS = copyLINKS + 1
nextLOOP:
Next deleteLINKS
LRlinks2 = Cells(Rows.Count, "A").End(xlUp).Row

For formatLINKS = 1 To LRlinks2
Cells(formatLINKS, 1).Value = "http://smoothjazz.com/charts/" &
Right(Cells(formatLINKS, 1), Len(Cells(formatLINKS, 1)) - 6)
nextLINK = Sheets("LINKS TEMP").Cells(formatLINKS, 1).Text
Range("B:B").ClearContents

With httpObject
    .Open "GET", Sheets("LINKS TEMP").Cells(formatLINKS, 1).Text, False
    .Send
    Do Until httpObject.ReadyState = 4
    Loop
    doc.body.innerhtml = .responseText
    Set elem = doc.getElementsByClassName("trackingalbumname")
    x = 1
    For Each l In elem
        Sheets("HEADER TEMP").Cells(x, 1).Value = l.span
        x = x + 1
    Next l
End With

Next formatLINKS
</code>```

Why is it breaking in part with GetElementsByClassName?

Here is HTML:

     NATHAN EAST

     Reverence
```

It is just one artist/album, but it needs to run trough entire HTML and find them all!

What do I need to do...Except to start learning hard?!

答:
I normally use the InternetExplorer.Application instead of MSXML2.XMLHTTP. And I hear that the htmlfile was deprecated from IE 11 and will no longer work. As for the getelementsbyclassname. It should be .document.getelementsbyclassname. Also, not sure if you wanted "span" or the attributes. I used tagname as a demo. To get the value of the artist, swap tagname for innertext or innerhtml. You can observe the object attributes in the locals windows and step through the code. Look for the attribute's value that matches the data that you are trying to scrape.

```<code>Sheets("LINKS TEMP").Activate
 Dim httpObject As Object
 Set httpObject = CreateObject("InternetExplorer.Application")
 Dim doc As Object
 ' Set doc = CreateObject("Shell.Application")
 Dim links As Variant
 Dim l As Variant

 With httpObject
   .navigate "http://www.smoothjazz.com/charts/"
   Do Until httpObject.ReadyState = 4
     DoEvents
   Loop
   .Visible = True
End With

Set doc = httpObject
  Set elem = doc.document.getElementsByClassName("first")
  x = 1
 For Each l In elem
    Sheets("HEADER TEMP").Cells(x, 1).Value = l.tagname
    x = x + 1
 Next l
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Ok, I`m totally clueless about what I need to do regarding this topic...

Here is code. I took first some links from website, and then I should follow link by link and take some data from that website...

Sheets("LINKS TEMP").Activate

Dim httpObject As Object
Set httpObject = CreateObject("MSXML2.XMLHTTP")
Dim doc As Object
Set doc = CreateObject("htmlfile")
Dim links As Variant
Dim l As Variant

With httpObject
    .Open "GET", "http://www.smoothjazz.com/charts/", False
    .Send
    Do Until httpObject.ReadyState = 4
    Loop
    doc.body.innerhtml = .responseText
    Set links = doc.getElementsByTagName("a")
    I = 1
    For Each l In links
        Sheets("LINKS TEMP").Cells(I, 2).Value = l.href
        I = I + 1
    Next l
End With

Sheets("LINKS TEMP").Activate
lrLINKS = Cells(Rows.Count, "B").End(xlUp).Row
copyLINKS = 1
For deleteLINKS = 1 To lrLINKS
If Cells(deleteLINKS, 2).Value Like "*votesbytrack*" Then GoTo copyLOOP
GoTo nextLOOP
copyLOOP:
Cells(deleteLINKS, 2).Copy
Cells(copyLINKS, 1).PasteSpecial xlPasteValues
copyLINKS = copyLINKS + 1
nextLOOP:
Next deleteLINKS
LRlinks2 = Cells(Rows.Count, "A").End(xlUp).Row

For formatLINKS = 1 To LRlinks2
Cells(formatLINKS, 1).Value = "http://smoothjazz.com/charts/" &
Right(Cells(formatLINKS, 1), Len(Cells(formatLINKS, 1)) - 6)
nextLINK = Sheets("LINKS TEMP").Cells(formatLINKS, 1).Text
Range("B:B").ClearContents

With httpObject
    .Open "GET", Sheets("LINKS TEMP").Cells(formatLINKS, 1).Text, False
    .Send
    Do Until httpObject.ReadyState = 4
    Loop
    doc.body.innerhtml = .responseText
    Set elem = doc.getElementsByClassName("trackingalbumname")
    x = 1
    For Each l In elem
        Sheets("HEADER TEMP").Cells(x, 1).Value = l.span
        x = x + 1
    Next l
End With

Next formatLINKS

Why is it breaking in part with GetElementsByClassName?

Here is HTML:

     NATHAN EAST

     Reverence

It is just one artist/album, but it needs to run trough entire HTML and find them all!

What do I need to do...Except to start learning hard?!

Body:
I normally use the InternetExplorer.Application instead of MSXML2.XMLHTTP. And I hear that the htmlfile was deprecated from IE 11 and will no longer work. As for the getelementsbyclassname. It should be .document.getelementsbyclassname. Also, not sure if you wanted "span" or the attributes. I used tagname as a demo. To get the value of the artist, swap tagname for innertext or innerhtml. You can observe the object attributes in the locals windows and step through the code. Look for the attribute's value that matches the data that you are trying to scrape.

Sheets("LINKS TEMP").Activate
 Dim httpObject As Object
 Set httpObject = CreateObject("InternetExplorer.Application")
 Dim doc As Object
 ' Set doc = CreateObject("Shell.Application")
 Dim links As Variant
 Dim l As Variant

 With httpObject
   .navigate "http://www.smoothjazz.com/charts/"
   Do Until httpObject.ReadyState = 4
     DoEvents
   Loop
   .Visible = True
End With

Set doc = httpObject
  Set elem = doc.document.getElementsByClassName("first")
  x = 1
 For Each l In elem
    Sheets("HEADER TEMP").Cells(x, 1).Value = l.tagname
    x = x + 1
 Next l


问:
what is REQUEST_CHECK_SETTING?
I'm following this doc:  https://developer.android.com/training/location/change-location-settings.html

REQUEST_CHECK_SETTING isn't defined but used, and I can't find its value after doing several searchs, all I found is that : What is the value of REQUEST_CHECK_SETTINGS?

someone giving it a "random" value (provided link not working), can someone please tell me how to get the value? or am I supposed to define it myself?

Thank you.

答:
REQUEST_CHECK_SETTING isn't defined but used

The "training" at the Android developer site routinely skips stuff.

can someone please tell me how to get the value? or am I supposed to define it myself?

You are supposed to define it yourself. startResolutionForResult() works like startActivityForResult(), requestPermissions(), and similar methods:

You supply an int to the call

You get that int in the callback (e.g., onActivityResult() for startActivityForResult()), to help you identify what call triggered the callback

In this sample app, I used a value of 61124 (defined there as REQUEST_RESOLUTION) in my startResolutionForResult() call.

ContentLicense: CC BY-SA 3.0

Title: what is REQUEST_CHECK_SETTING?


问:
PHP - include a php file and also send query parameters
I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.

```<code>if(condition here){
  include "myFile.php?id='$someVar'";
}
</code>```

Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.

Can someone please tell me how to achieve this?
Thanks.

答:
I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)

In your myFile.php you'd have

```<code><?php

$MySomeVAR = $_SESSION['SomeVar'];

?>
</code>```

And in the calling file

```<code><?php

session_start();
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;

?>
</code>```

Would this circumvent the "suggested" need to Functionize the whole process?

Body:
I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.

if(condition here){
  include "myFile.php?id='$someVar'";
}

Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.

Can someone please tell me how to achieve this?
Thanks.

Body:
I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)

In your myFile.php you'd have

<?php

$MySomeVAR = $_SESSION['SomeVar'];

?>

And in the calling file

<?php

session_start();
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;

?>

Would this circumvent the "suggested" need to Functionize the whole process?


问:
Slack Slash commands - Not working in private channels or direct messages
I have programmed several slash commands that show a response in public channels without any problems, but they don't show any response in private channels or direct messages.

As shown below, I am using the in_channel response type. Is there any other response type I can use or a workaround so that it works everywhere?

```<code>$data = array(
    "username" => "My_user",
    "channel" => $channel_id,
    "response_type" => "in_channel",
    "text" => $text,
    "mrkdwn" => true,
    "icon_url" => $icon_url

);

$json_string = json_encode($data);
$slack_call = curl_init($slack_webhook_url);
curl_setopt($slack_call, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($slack_call, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($slack_call, CURLOPT_CRLF, true);
curl_setopt($slack_call, CURLOPT_RETURNTRANSFER, true);
curl_setopt($slack_call, CURLOPT_HTTPHEADER, array(
    "Content-Type: application/json",
    "Content-Length: " . strlen($json_string))
);
$result = curl_exec($slack_call);
curl_close($slack_call);
</code>```

Thanks in advance!

答:
That does not look like the right approach.

Responding to slash commands

For responding to a slash command you must not send a new message back (e.g. via webhook as in your code example). Instead just respond to the request from Slack with the content of your message.

Example

```<code>$message = array (
    'response_type' => 'in_channel',
    'text' => $text
    );

header ('content-type: application/json');
echo json_encode ($message);
</code>```

that is all you need.

response_type defines if the response can be seen by all members of a channel "in_channel" or only by the issuer of the slash command "ephemeral"

Please see the official documentation for more details and options.

Sending additional messages

You can of course also send a message from your script in response to the slash command. However, if you want to send a message to a private channel please note that the slash command request from Slack will not include the correct channel ID if it is used in a non-public channel. I don't think there is currently any solution or workaround for this.

You can however always send a direct message to the user by using the ID of the user as channel ID.

Body:
I have programmed several slash commands that show a response in public channels without any problems, but they don't show any response in private channels or direct messages.

As shown below, I am using the in_channel response type. Is there any other response type I can use or a workaround so that it works everywhere?

$data = array(
    "username" => "My_user",
    "channel" => $channel_id,
    "response_type" => "in_channel",
    "text" => $text,
    "mrkdwn" => true,
    "icon_url" => $icon_url

);

$json_string = json_encode($data);
$slack_call = curl_init($slack_webhook_url);
curl_setopt($slack_call, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($slack_call, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($slack_call, CURLOPT_CRLF, true);
curl_setopt($slack_call, CURLOPT_RETURNTRANSFER, true);
curl_setopt($slack_call, CURLOPT_HTTPHEADER, array(
    "Content-Type: application/json",
    "Content-Length: " . strlen($json_string))
);
$result = curl_exec($slack_call);
curl_close($slack_call);

Thanks in advance!

Body:
That does not look like the right approach.

Responding to slash commands

For responding to a slash command you must not send a new message back (e.g. via webhook as in your code example). Instead just respond to the request from Slack with the content of your message.

Example

$message = array (
    'response_type' => 'in_channel',
    'text' => $text
    );

header ('content-type: application/json');
echo json_encode ($message);

that is all you need.

response_type defines if the response can be seen by all members of a channel "in_channel" or only by the issuer of the slash command "ephemeral"

Please see the official documentation for more details and options.

Sending additional messages

You can of course also send a message from your script in response to the slash command. However, if you want to send a message to a private channel please note that the slash command request from Slack will not include the correct channel ID if it is used in a non-public channel. I don't think there is currently any solution or workaround for this.

You can however always send a direct message to the user by using the ID of the user as channel ID.


问:
How to filter a multidimentional JSON Object
I have a Json string which contains many json objects, each json has a key, I use JSON.parse to place the string into an object.

I then extract what I need in the following format

```<code>json['product1'][0].name
</code>```

However, I want to get an array of element from each of the json objects based on the value of another elements. Currently I am using:

```<code>for each (var row:Object in json) {

    if (row[0][filterElement] == filterValue) {
        arr.push(row[0][element]);
    }

}
</code>```

Is this a good approach? I ask because it seems that I am going through the entire json object every time.

答:
If I've understood your question correctly, it sounds like you want to use .map and .filter.

So if we have an object such as...

```<code>var obj = {
    people: [
       {name: 'person1'},
       {name: 'person2'},
       {name: 'person3'},
       {name: 'person4'},
    ]
};
</code>```

You can then use .map to create a new array of names...

```<code>var names = obj.people.map(function(person){
     return person.name;
}); // ['person1', 'person2', 'person3', 'person4']
</code>```

on this array you can then use .filter...

```<code>var filter = 'person2';
var filteredNames = obj.people.map(function(person){
         return person.name;
    }).filter(function(name){
        return name == filter; // if true, will push name into a name into our new array
    }); // 'person2'
</code>```

This is obviously a rudimentary example, but the same concepts will apply for the precise properties which apply in your question. Hope this helps.

Body:
I have a Json string which contains many json objects, each json has a key, I use JSON.parse to place the string into an object.

I then extract what I need in the following format

json['product1'][0].name

However, I want to get an array of element from each of the json objects based on the value of another elements. Currently I am using:

for each (var row:Object in json) {

    if (row[0][filterElement] == filterValue) {
        arr.push(row[0][element]);
    }

}

Is this a good approach? I ask because it seems that I am going through the entire json object every time.

Body:
If I've understood your question correctly, it sounds like you want to use .map and .filter.

So if we have an object such as...

var obj = {
    people: [
       {name: 'person1'},
       {name: 'person2'},
       {name: 'person3'},
       {name: 'person4'},
    ]
};

You can then use .map to create a new array of names...

var names = obj.people.map(function(person){
     return person.name;
}); // ['person1', 'person2', 'person3', 'person4']

on this array you can then use .filter...

var filter = 'person2';
var filteredNames = obj.people.map(function(person){
         return person.name;
    }).filter(function(name){
        return name == filter; // if true, will push name into a name into our new array
    }); // 'person2'

This is obviously a rudimentary example, but the same concepts will apply for the precise properties which apply in your question. Hope this helps.


问:
how to add uipickerview in uialertview swift 3
Swift 3 iOS 10: I want to add UIPickerView in UIAlertView so that i can choose item and set it's value to the textField. I could do it with UIView but I want to improve it in a better and natural way. Is it possible to do this or any way out?

Thank in advance!

This is what I have done,

Pix1: my textfield: https://z-p3-scontent.fpnh5-1.fna.fbcdn.net/v/t1.0-9/19702221_1969127863363332_1282515913735651533_n.jpg?oh=ece774626e6691c531dc69b168104fcc&oe=59D72E14

Pix2: my alert: https://z-p3-scontent.fpnh5-1.fna.fbcdn.net/v/t1.0-9/19665630_1969127860029999_9139151345242136168_n.jpg?oh=d56be1efc3bd772ff68e7e45fa7ebfae&oe=5A0F290F

答:
Although Apple suggests us not to do so, you can indeed add a picker view to your alert view controller. UIAlertViewController has nothing magic other than a normal view controller. All you need to do is to show title text with lots of new lines (namely "Select\n\n\n\n\n\n\n\n\n\n\n\n") in order to increase the alert height, and then call alertViewController.addSubview(datePicker)

However the questions is why you need to write extra code to manipulate an alert view controller and handle which text field to set value? Here is another approach that is way easier to maintain and implement.

First create your picker view and configure it.

```<code>let picker = UIPickerView()
picker.delegate = self
picker.dateSource = self
// configure
</code>```

Then for each of your text field, simply call this

```<code>tf1.tag = 1
tf2.tag = 2
tf3.tag = 3

tf1.delegate = self
tf2.delegate = self
tf3.delegate = self

tf1.inputView = picker
tf2.inputView = picker
tf3.inputView = picker
</code>```

Not in your text field delegate method, store which text field user clicked on and reload picker view data

```<code>var tfTag = 0

func textFieldDidBeginEditing(_ textField: UITextField) {
    tfTag = textField.tag
    picker.reloadAllComponents()
}
</code>```

Finally in all your picker view data source or delegate method, load different set of data base on the unique tag number from each of the text field

```<code>func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if tfTag == 0 {
        if component == 0 {
            return "1"
        }else if component == 1 {
            return "2"
        }else if component == 2 {
            return "3"
        }else{
            return "4"
        }
    }else if tfTag == 1 {
        //...
    }else{
        //...
    }
}
</code>```

Body:
Although Apple suggests us not to do so, you can indeed add a picker view to your alert view controller. UIAlertViewController has nothing magic other than a normal view controller. All you need to do is to show title text with lots of new lines (namely "Select\n\n\n\n\n\n\n\n\n\n\n\n") in order to increase the alert height, and then call alertViewController.addSubview(datePicker)

However the questions is why you need to write extra code to manipulate an alert view controller and handle which text field to set value? Here is another approach that is way easier to maintain and implement.

First create your picker view and configure it.

let picker = UIPickerView()
picker.delegate = self
picker.dateSource = self
// configure

Then for each of your text field, simply call this

tf1.tag = 1
tf2.tag = 2
tf3.tag = 3

tf1.delegate = self
tf2.delegate = self
tf3.delegate = self

tf1.inputView = picker
tf2.inputView = picker
tf3.inputView = picker

Not in your text field delegate method, store which text field user clicked on and reload picker view data

var tfTag = 0

func textFieldDidBeginEditing(_ textField: UITextField) {
    tfTag = textField.tag
    picker.reloadAllComponents()
}

Finally in all your picker view data source or delegate method, load different set of data base on the unique tag number from each of the text field

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if tfTag == 0 {
        if component == 0 {
            return "1"
        }else if component == 1 {
            return "2"
        }else if component == 2 {
            return "3"
        }else{
            return "4"
        }
    }else if tfTag == 1 {
        //...
    }else{
        //...
    }
}


问:
Can Math.Round in C# be used for whole integer values?
I have integer 363 for example.

Any method to make it 360 or 365?

答:
There's nothing built-in, you're just going to have to code the logic yourself. Here's one such method. (Going down is clearer, but going up is manageable.)

```<code>int number = 363;
int roundedDown = number - number % 5;
int roundedUp = number + (number % 5 > 0 ? (5 - number % 5) : 0);
</code>```

Edit for negative numbers, the logic almost gets reversed.

```<code>static int RoundUpToFive(int number)
{
    if (number >= 0)
        return number + (number % 5 > 0 ? (5 - number % 5) : 0);
    else
        return number - (number % 5);
}

static int RoundDownToFive(int number)
{
    if (number >= 0)
        return number - number % 5;
    else
        return number + (number % 5 < 0 ? (-5 - number % 5) : 0);
}
</code>```

Body:
There's nothing built-in, you're just going to have to code the logic yourself. Here's one such method. (Going down is clearer, but going up is manageable.)

int number = 363;
int roundedDown = number - number % 5;
int roundedUp = number + (number % 5 > 0 ? (5 - number % 5) : 0);

Edit for negative numbers, the logic almost gets reversed.

static int RoundUpToFive(int number)
{
    if (number >= 0)
        return number + (number % 5 > 0 ? (5 - number % 5) : 0);
    else
        return number - (number % 5);
}

static int RoundDownToFive(int number)
{
    if (number >= 0)
        return number - number % 5;
    else
        return number + (number % 5 < 0 ? (-5 - number % 5) : 0);
}


问:
How can I modify this SQL SELECT statement to change non-numeric values?
The dataset I am using can be found here.

I am using SSIS to upload the dataset into MS SQL Server.

I uploaded everything as text, and am trying to create a working table with proper data types by inserting values from the raw table.

```<code>CREATE TABLE [WRK_demographics]
(
        [RowNumber]         INT IDENTITY(1,1)
        ,[DBN]              VARCHAR(10)
        ,[Name]             VARCHAR(1000)
        ,[schoolyear]       VARCHAR(100)
        ,[fl_percent]       FLOAT
        ,[frl_percent]      FLOAT
        ,[total_enrollment] INT
        ,[grade9]           INT
        ,[grade10]          INT
        ,[grade11]          INT
        ,[grade12]          INT
        ,[ell_num]          INT
        ,[ell_percent]      FLOAT
        ,[sped_num]         INT
        ,[sped_percent]     FLOAT
        ,[ctt_num]          INT
        ,[selfcontained_num] INT
        ,[asian_num]        INT
        ,[asian_per]        FLOAT
        ,[black_num]        INT
        ,[black_per]        FLOAT
        ,[hispanic_num]     INT
        ,[hispanic_per]     FLOAT
        ,[white_num]        INT
        ,[white_per]        FLOAT
        ,[male_num]         INT
        ,[male_per]         FLOAT
        ,[female_num]       INT
        ,[female_per]       FLOAT
)

INSERT INTO [WRK_demographics]
(
        [DBN]
        ,[Name]
        ,[schoolyear]
        ,[fl_percent]
        ,[frl_percent]
        ,[total_enrollment]
        ,[grade9]
        ,[grade10]
        ,[grade11]
        ,[grade12]
        ,[ell_num]
        ,[ell_percent]
        ,[sped_num]
        ,[sped_percent]
        ,[ctt_num]
        ,[selfcontained_num]
        ,[asian_num]
        ,[asian_per]
        ,[black_num]
        ,[black_per]
        ,[hispanic_num]
        ,[hispanic_per]
        ,[white_num]
        ,[white_per]
        ,[male_num]
        ,[male_per]
        ,[female_num]
        ,[female_per]
)
SELECT
        [DBN]
        ,[Name]
        ,[schoolyear]
        ,[fl_percent]
        ,[frl_percent]
        ,[total_enrollment]
        ,[grade9]
        ,[grade10]
        ,[grade11]
        ,[grade12]
        ,[ell_num]
        ,[ell_percent]
        ,[sped_num]
        ,[sped_percent]
        ,[ctt_num]
        ,[selfcontained_num]
        ,[asian_num]
        ,[asian_per]
        ,[black_num]
        ,[black_per]
        ,[hispanic_num]
        ,[hispanic_per]
        ,[white_num]
        ,[white_per]
        ,[male_num]
        ,[male_per]
        ,[female_num]
        ,[female_per]
FROM [RAW_demographics_20170706]
</code>```

However, the issue I am having is that for cells where there is no value, there is text instead of a null cell. So, implicit conversion cannot convert the data to int/float. Is there a way I can modify the SELECT statement to update the values of non-numeric cells to NULL? If I didn't have so many columns I would update each one in the raw table like this before inserting into the working table:

```<code>UPDATE [RAW_demographics_20170706]
SET [fl_percent] = NULL
WHERE ISNUMERIC([fl_percent]) <> 1
</code>```

I'm wondering if there is a more efficient path to take.

答:
You'd want to use a case statement since your error should be coming from empty strings not an actual NULL

```<code>SELECT
        [DBN]
        ,[Name]
        ,[schoolyear]
        ,case when [fl_percent] = '' then 0.0 else fl_percent end
        ,case when [frl_percent] = '' then 0.0 else flr_percent end
        ...
        ...
        ,case when [grade12] = '' then 0 else grade12 end
        ...
FROM [RAW_demographics_20170706]
</code>```

I also wouldn't use ISNUMERIC for this situation. It will cause problems as it returns true for an array of cases other than an int or float.

These return true, but would fail for conversions:

```<code>select isnumeric('$')
select isnumeric('1e4')
etc...
</code>```

Body:
The dataset I am using can be found here.

I am using SSIS to upload the dataset into MS SQL Server.

I uploaded everything as text, and am trying to create a working table with proper data types by inserting values from the raw table.

CREATE TABLE [WRK_demographics]
(
        [RowNumber]         INT IDENTITY(1,1)
        ,[DBN]              VARCHAR(10)
        ,[Name]             VARCHAR(1000)
        ,[schoolyear]       VARCHAR(100)
        ,[fl_percent]       FLOAT
        ,[frl_percent]      FLOAT
        ,[total_enrollment] INT
        ,[grade9]           INT
        ,[grade10]          INT
        ,[grade11]          INT
        ,[grade12]          INT
        ,[ell_num]          INT
        ,[ell_percent]      FLOAT
        ,[sped_num]         INT
        ,[sped_percent]     FLOAT
        ,[ctt_num]          INT
        ,[selfcontained_num] INT
        ,[asian_num]        INT
        ,[asian_per]        FLOAT
        ,[black_num]        INT
        ,[black_per]        FLOAT
        ,[hispanic_num]     INT
        ,[hispanic_per]     FLOAT
        ,[white_num]        INT
        ,[white_per]        FLOAT
        ,[male_num]         INT
        ,[male_per]         FLOAT
        ,[female_num]       INT
        ,[female_per]       FLOAT
)

INSERT INTO [WRK_demographics]
(
        [DBN]
        ,[Name]
        ,[schoolyear]
        ,[fl_percent]
        ,[frl_percent]
        ,[total_enrollment]
        ,[grade9]
        ,[grade10]
        ,[grade11]
        ,[grade12]
        ,[ell_num]
        ,[ell_percent]
        ,[sped_num]
        ,[sped_percent]
        ,[ctt_num]
        ,[selfcontained_num]
        ,[asian_num]
        ,[asian_per]
        ,[black_num]
        ,[black_per]
        ,[hispanic_num]
        ,[hispanic_per]
        ,[white_num]
        ,[white_per]
        ,[male_num]
        ,[male_per]
        ,[female_num]
        ,[female_per]
)
SELECT
        [DBN]
        ,[Name]
        ,[schoolyear]
        ,[fl_percent]
        ,[frl_percent]
        ,[total_enrollment]
        ,[grade9]
        ,[grade10]
        ,[grade11]
        ,[grade12]
        ,[ell_num]
        ,[ell_percent]
        ,[sped_num]
        ,[sped_percent]
        ,[ctt_num]
        ,[selfcontained_num]
        ,[asian_num]
        ,[asian_per]
        ,[black_num]
        ,[black_per]
        ,[hispanic_num]
        ,[hispanic_per]
        ,[white_num]
        ,[white_per]
        ,[male_num]
        ,[male_per]
        ,[female_num]
        ,[female_per]
FROM [RAW_demographics_20170706]

However, the issue I am having is that for cells where there is no value, there is text instead of a null cell. So, implicit conversion cannot convert the data to int/float. Is there a way I can modify the SELECT statement to update the values of non-numeric cells to NULL? If I didn't have so many columns I would update each one in the raw table like this before inserting into the working table:

UPDATE [RAW_demographics_20170706]
SET [fl_percent] = NULL
WHERE ISNUMERIC([fl_percent]) <> 1

I'm wondering if there is a more efficient path to take.

Body:
You'd want to use a case statement since your error should be coming from empty strings not an actual NULL

SELECT
        [DBN]
        ,[Name]
        ,[schoolyear]
        ,case when [fl_percent] = '' then 0.0 else fl_percent end
        ,case when [frl_percent] = '' then 0.0 else flr_percent end
        ...
        ...
        ,case when [grade12] = '' then 0 else grade12 end
        ...
FROM [RAW_demographics_20170706]

I also wouldn't use ISNUMERIC for this situation. It will cause problems as it returns true for an array of cases other than an int or float.

These return true, but would fail for conversions:

select isnumeric('$')
select isnumeric('1e4')
etc...


问:
Terraform target aws_volume_attachment with only its corresponding aws_instance resource from a list
I am not able to target a single aws_volume_attachment with its corresponding aws_instance via -target.
The problem is that the aws_instance is taken from a list by using count.index, which forces terraform to refresh all aws_instance resources from that list.

In my concrete case I am trying to manage a consul cluster with terraform.
The goal is to be able to reinit a single aws_instance resource via the -target flag, so I can upgrade/change the whole cluster node by node without downtime.

I have the following tf code:

```<code>### IP suffixes
variable "subnet_cidr" { "10.10.0.0/16" }

// I want nodes with addresses 10.10.1.100, 10.10.1.101, 10.10.1.102
variable "consul_private_ips_suffix" {
  default = {
    "0" = "100"
    "1" = "101"
    "2" = "102"
  }
}

###########
# EBS
#
// Get existing data EBS via Name Tag
data "aws_ebs_volume" "consul-data" {
  count = "${length(keys(var.consul_private_ips_suffix))}"

  filter {
    name   = "volume-type"
    values = ["gp2"]
  }

  filter {
    name   = "tag:Name"
    values = ["${var.platform_type}.${var.platform_id}.consul.data.${count.index}"]
  }
}

#########
# EC2
#
resource "aws_instance" "consul" {
  count      = "${length(keys(var.consul_private_ips_suffix))}"

  ...

  private_ip = "${cidrhost(aws_subnet.private-b.cidr_block, lookup(var.consul_private_ips_suffix, count.index))}"
}

resource "aws_volume_attachment" "consul-data" {
  count       = "${length(keys(var.consul_private_ips_suffix))}"

  device_name = "/dev/sdh"
  volume_id   = "${element(data.aws_ebs_volume.consul-data.*.id, count.index)}"
  instance_id = "${element(aws_instance.consul.*.id, count.index)}"
}
</code>```

This works perfectly fine for initializing the cluster.
Now I make a change in my user_data init script of the consul nodes and want to rollout node by node.
I run terraform plan -target=aws_volume_attachment.consul_data[0] to reinit node 0.
This is when I run into the above mentioned problem, that terraform renders all aws_instance resources because of instance_id = "${element(aws_instance.consul.*.id, count.index)}".

Is there a way to "force" tf to target a single aws_volume_attachment with only its corresponding aws_instance resource?

答:
At the time of writing this sort of usage is not possible due to the fact that, as you've seen, an expression like aws_instance.consul.*.id creates a dependency on all the instances, before the element function is applied.

The -target option is not intended for routine use and is instead provided only for exceptional circumstances such as recovering carefully from an unintended change.

For this specific situation it may work better to use the ignore_changes lifecycle setting to prevent automatic replacement of the instances when user_data changes, like this:

```<code>resource "aws_instance" "consul" {
  count      = "${length(keys(var.consul_private_ips_suffix))}"

  ...

  private_ip = "${cidrhost(aws_subnet.private-b.cidr_block, lookup(var.consul_private_ips_suffix, count.index))}"

  lifecycle {
    ignore_changes = ["user_data"]
  }
}
</code>```

With this set, Terraform will detect but ignore changes to the user_data attribute. You can then get the gradual replacement behavior you want by manually tainting the resources one at a time:

```<code>$ terraform taint aws_instance.consul[0]
</code>```

On the next plan, Terraform will then see that this resource instance is tainted and produce a plan to replace it. This gives you direct control over when the resources are replaced, so you can therefore ensure that e.g. the consul leave step gets a chance to run first, or whatever other cleanup you need to do.

This workflow is recommended over -target because it makes the replacement step explicit. -target can be confusing in a collaborative environment because there is no evidence of its use, and thus no clear explanation of how the current state was reached. taint, on the other hand, explicitly marks your intention in the state where other team members can see it, and then replaces the resource via the normal plan/apply steps.

Body:
I am not able to target a single aws_volume_attachment with its corresponding aws_instance via -target.
The problem is that the aws_instance is taken from a list by using count.index, which forces terraform to refresh all aws_instance resources from that list.

In my concrete case I am trying to manage a consul cluster with terraform.
The goal is to be able to reinit a single aws_instance resource via the -target flag, so I can upgrade/change the whole cluster node by node without downtime.

I have the following tf code:

### IP suffixes
variable "subnet_cidr" { "10.10.0.0/16" }

// I want nodes with addresses 10.10.1.100, 10.10.1.101, 10.10.1.102
variable "consul_private_ips_suffix" {
  default = {
    "0" = "100"
    "1" = "101"
    "2" = "102"
  }
}

###########
# EBS
#
// Get existing data EBS via Name Tag
data "aws_ebs_volume" "consul-data" {
  count = "${length(keys(var.consul_private_ips_suffix))}"

  filter {
    name   = "volume-type"
    values = ["gp2"]
  }

  filter {
    name   = "tag:Name"
    values = ["${var.platform_type}.${var.platform_id}.consul.data.${count.index}"]
  }
}

#########
# EC2
#
resource "aws_instance" "consul" {
  count      = "${length(keys(var.consul_private_ips_suffix))}"

  ...

  private_ip = "${cidrhost(aws_subnet.private-b.cidr_block, lookup(var.consul_private_ips_suffix, count.index))}"
}

resource "aws_volume_attachment" "consul-data" {
  count       = "${length(keys(var.consul_private_ips_suffix))}"

  device_name = "/dev/sdh"
  volume_id   = "${element(data.aws_ebs_volume.consul-data.*.id, count.index)}"
  instance_id = "${element(aws_instance.consul.*.id, count.index)}"
}

This works perfectly fine for initializing the cluster.
Now I make a change in my user_data init script of the consul nodes and want to rollout node by node.
I run terraform plan -target=aws_volume_attachment.consul_data[0] to reinit node 0.
This is when I run into the above mentioned problem, that terraform renders all aws_instance resources because of instance_id = "${element(aws_instance.consul.*.id, count.index)}".

Is there a way to "force" tf to target a single aws_volume_attachment with only its corresponding aws_instance resource?

Body:
At the time of writing this sort of usage is not possible due to the fact that, as you've seen, an expression like aws_instance.consul.*.id creates a dependency on all the instances, before the element function is applied.

The -target option is not intended for routine use and is instead provided only for exceptional circumstances such as recovering carefully from an unintended change.

For this specific situation it may work better to use the ignore_changes lifecycle setting to prevent automatic replacement of the instances when user_data changes, like this:

resource "aws_instance" "consul" {
  count      = "${length(keys(var.consul_private_ips_suffix))}"

  ...

  private_ip = "${cidrhost(aws_subnet.private-b.cidr_block, lookup(var.consul_private_ips_suffix, count.index))}"

  lifecycle {
    ignore_changes = ["user_data"]
  }
}

With this set, Terraform will detect but ignore changes to the user_data attribute. You can then get the gradual replacement behavior you want by manually tainting the resources one at a time:

$ terraform taint aws_instance.consul[0]

On the next plan, Terraform will then see that this resource instance is tainted and produce a plan to replace it. This gives you direct control over when the resources are replaced, so you can therefore ensure that e.g. the consul leave step gets a chance to run first, or whatever other cleanup you need to do.

This workflow is recommended over -target because it makes the replacement step explicit. -target can be confusing in a collaborative environment because there is no evidence of its use, and thus no clear explanation of how the current state was reached. taint, on the other hand, explicitly marks your intention in the state where other team members can see it, and then replaces the resource via the normal plan/apply steps.


问:
Newline characters are not preserved on server side from h:inputTextarea
I have a form which uses a JSF h:inputTextarea like so:

index.xhtml:

<!DOCTYPE html>

    <h:head></h:head>
    <h:body>

            <h:form enctype="multipart/form-data">

                <h:inputTextarea
                    id="termineesText"
                    value="#{controller.text}"/>

                <h:commandButton
                    value="Upload and Continue"
                    type = "submit"
                    action="#{controller.respond}"/>

            </h:form>

    </h:body>

```

<p>result.xhtml:</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head></h:head>
    <h:body>
        <div id="ContentFrame">

            <h:form enctype="multipart/form-data">

                <h:inputTextarea
                    id="termineesText"
                    value="#{controller.text}"/>

                <h:outputText value="#{controller.containsNewline}"/>

            </h:form>
        </div>
    </h:body>
</html>
</code>```

With this backing bean:

controller.java:

package main;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named("controller")
@SessionScoped
public class Controller implements Serializable {
    private static final long serialVersionUID = 1L;
    private String text;
    private boolean containsNewline = false;

    public String respond() {
        return "result.xhtml";
    }

    public void setText(String value) {
        if (value.contains("\n") || value.contains("\r")) {
            containsNewline = true;
        }
        text = value;
    }
    public String getText() {return text;}
    public String getContainsNewline()
    {
        return String.valueOf(containsNewline);
    }
}
```

<p>When the user inputs text over many lines (by pressing enter) and submits the form the newline characters disappear in the text area in <code>result.xhtml</code>. For example if the user enters:</p>

<blockquote>
  <p>abc<br>
  abc</p>
</blockquote>

<p>The <code>result.xhtml</code>'s text area has it as "abcabc", And the output text evaluates to <code>false</code>. The newline characters seem to get lost when the form is submitted to the server, which can be seen using the <code>containsNewLine</code> boolean in the controller.</p>

<p>I have read many posts about why newlines aren't shown on a web browser when the text comes from the server side, but my case is the other way around, for some reason new lines are not getting transferred from the Textarea to the backing bean.</p>

<h3>What I have tried</h3>

<p>I have tried:</p>

<pre class="lang-html prettyprint-override"><code>```<h:inputTextarea id="termineesText" styleClass="termineesTextInput" onchange="enableDisableSubmitBtn()" value="#{controller.termineesText}"/>```
</code>```

And in CSS:

.termineesTextInput { white-space: pre; }
```

Technology I am using

JSF 2.2 with CDI 1.2 running on Websphere Application Server, and I have done most of my testing using a Chrome incognito window.

How do I get newlines to transfer to the backing property?

答:
The issue here as @Kukeltje pointed out was my use of enctype="multipart/form-data". For some reason this is causing the newlines to be lost when the form is submitted to the server. If you are able to remove that encoding and use the normal enctype="application/x-www-form-urlencoded" then that will fix the issue for you. Hope this helps someone.

For me removing this is not an option as I'm using a file upload control on my form which requires the use of multipart/form-data. To address this I've opened a new question:
Newline characters lost when using enctype="multipart/form-data" in html form

Body:
I have a form which uses a JSF h:inputTextarea like so:

index.xhtml:

<!DOCTYPE html>

    <h:head></h:head>
    <h:body>

            <h:form enctype="multipart/form-data">

                <h:inputTextarea
                    id="termineesText"
                    value="#{controller.text}"/>

                <h:commandButton
                    value="Upload and Continue"
                    type = "submit"
                    action="#{controller.respond}"/>

            </h:form>

    </h:body>

result.xhtml:

<!DOCTYPE html>

    <h:head></h:head>
    <h:body>

            <h:form enctype="multipart/form-data">

                <h:inputTextarea
                    id="termineesText"
                    value="#{controller.text}"/>

                <h:outputText value="#{controller.containsNewline}"/>

            </h:form>

    </h:body>

With this backing bean:

controller.java:

package main;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named("controller")
@SessionScoped
public class Controller implements Serializable {
    private static final long serialVersionUID = 1L;
    private String text;
    private boolean containsNewline = false;

    public String respond() {
        return "result.xhtml";
    }

    public void setText(String value) {
        if (value.contains("\n") || value.contains("\r")) {
            containsNewline = true;
        }
        text = value;
    }
    public String getText() {return text;}
    public String getContainsNewline()
    {
        return String.valueOf(containsNewline);
    }
}

When the user inputs text over many lines (by pressing enter) and submits the form the newline characters disappear in the text area in result.xhtml. For example if the user enters:

abc

  abc

The result.xhtml's text area has it as "abcabc", And the output text evaluates to false. The newline characters seem to get lost when the form is submitted to the server, which can be seen using the containsNewLine boolean in the controller.

I have read many posts about why newlines aren't shown on a web browser when the text comes from the server side, but my case is the other way around, for some reason new lines are not getting transferred from the Textarea to the backing bean.

What I have tried

I have tried:

<h:inputTextarea id="termineesText" styleClass="termineesTextInput" onchange="enableDisableSubmitBtn()" value="#{controller.termineesText}"/>

And in CSS:

.termineesTextInput { white-space: pre; }

Technology I am using

JSF 2.2 with CDI 1.2 running on Websphere Application Server, and I have done most of my testing using a Chrome incognito window.

How do I get newlines to transfer to the backing property?


问:
ASP.NET 5 MVC: unable to connect to web server 'IIS Express'
What I'm doing:

Opening Visual Studio Community 2015

File -> New -> Project

Under Visual C#: Web -> ASP.NET Web Application

Web Application

And press f5 for the popup error "unable to connect to web server 'IIS Express'."

Deleting applicationhost.config, located in Documents\IISExpress\config, doesn't change the error message. (There's also an IISExpress folder in program files and program files (x86).)

Something I noticed, and I don't know if it's a problem:

Referenced file 'lib/jquery-validation/jquery.validate.js' not found.

I got a dump with rawcap but I don't notice much in there. Some of what was there:

"Framework":{"FrameworkName":"DNXCore,Version=v5.0","FriendlyName":"DNX Core 5.0","ShortName":"dnxcore50","RedistListPath":null}

I don't notice a problem, but I have the network data if that can help figure out why I cannot connect to the web server. I get a RST,ACK immediately so I'm guessing the port is closed and whatever this web server is, isn't being setup.

More on this problem: 800700c1 error from /trace:error

I've tried:

deleting applicationhost.config (and changing port number)

running visual studio as administrator

deleting IISExpress folder in Documents (changes error message until the folder is reinstalled)

toggling ssl off and on, copying url to launch box. (note: I'm not using ssl)

clearing all sfc /scannow errors

starting iisexpress with x86 version and 64-bit version

答: Mine happens as soon as I add a new binding inside the applicationhost.config, running as administrator fixed the problem.</p>


问:
O(n) algorithm to find out the element appearing more than n/2 times
I was asked in an interview to give an O(n) algorithm to print an element that appears more than n/2 times in an array, if there is such an element. n is the size of the array.
I don't have any clue on how to do this. Can anyone help?</p>

答:
In psuedocode:</p>

```<code>int n = array.length
Hash<elementType,int> hash
foreach element in array
    hash[element] += 1
foreach entry in hash
    if entry.value > n/2
        print entry.key
        break
</code>```

Body:
In psuedocode:

int n = array.length
Hash<elementType,int> hash
foreach element in array
    hash[element] += 1
foreach entry in hash
    if entry.value > n/2
        print entry.key
        break


问:
tensorflow giving nans when calculating gradient with sparse tensors
The following snippet is from a fairly large piece of code but hopefully I can give all the information necessary:

y2 = tf.matmul(y1,ymask)

dist = tf.norm(ystar-y2,axis=0)

y1 and y2 are 128x30 and ymask is 30x30. ystar is 128x30. dist is 1x30. When ymask is the identity matrix, everything works fine. But when I set it to be all zeros, apart from a single 1 along the diagonal (so as to set all columns but one in y2 to be zero), I get nans for the gradient of dist with respect to y2, using tf.gradients(dist, [y2]). The specific value of dist is [0,0,7.9,0,...], with all the ystar-y2 values being around the range (-1,1) in the third column and zero elsewhere.

I'm pretty confused as to why a numerical issue would occur here, given there are no logs or divisions, is this underflow? Am I missing something in the maths?

For context, I'm doing this to try to train individual dimensions of y, one at a time, using the whole network.

longer version to reproduce:

```<code>import tensorflow as tf
import numpy as np
import pandas as pd

batchSize = 128
eta = 0.8
tasks = 30
imageSize = 32**2
groups = 3
tasksPerGroup = 10
trainDatapoints = 10000

w = np.zeros([imageSize, groups * tasksPerGroup])
toyIndex = 0
for toyLoop in range(groups):
    m = np.ones([imageSize]) * np.random.randn(imageSize)
    for taskLoop in range(tasksPerGroup):
        w[:, toyIndex] = m * 0.1 * np.random.randn(1)
        toyIndex += 1

xRand = np.random.normal(0, 0.5, (trainDatapoints, imageSize))
taskLabels = np.matmul(xRand, w) + np.random.normal(0,0.5,(trainDatapoints, groups * tasksPerGroup))
DF = np.concatenate((xRand, taskLabels), axis=1)
trainDF = pd.DataFrame(DF[:trainDatapoints, ])

# define graph variables
x = tf.placeholder(tf.float32, [None, imageSize])
W = tf.Variable(tf.zeros([imageSize, tasks]))
b = tf.Variable(tf.zeros([tasks]))
ystar = tf.placeholder(tf.float32, [None, tasks])
ymask = tf.placeholder(tf.float32, [tasks, tasks])
dataLength = tf.cast(tf.shape(ystar)[0],dtype=tf.float32)

y1 = tf.matmul(x, W) + b
y2 = tf.matmul(y1,ymask)
dist = tf.norm(ystar-y2,axis=0)
mse = tf.reciprocal(dataLength) * tf.reduce_mean(tf.square(dist))
grads = tf.gradients(dist, [y2])

trainStep = tf.train.GradientDescentOptimizer(eta).minimize(mse)

# build graph
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

randTask = np.random.randint(0, 9)
ymaskIn = np.zeros([tasks, tasks])
ymaskIn[randTask, randTask] = 1
batch = trainDF.sample(batchSize)
batch_xs = batch.iloc[:, :imageSize]
batch_ys = np.zeros([batchSize, tasks])
batch_ys[:, randTask] = batch.iloc[:, imageSize + randTask]

gradOut = sess.run(grads, feed_dict={x: batch_xs, ystar: batch_ys, ymask: ymaskIn})

sess.run(trainStep, feed_dict={x: batch_xs, ystar: batch_ys, ymask:ymaskIn})
</code>```

答:
Here's a very simple reproduction:

```<code>import tensorflow as tf

with tf.Graph().as_default():
  y = tf.zeros(shape=[1], dtype=tf.float32)
  dist = tf.norm(y,axis=0)
  (grad,) = tf.gradients(dist, [y])
  with tf.Session():
    print(grad.eval())
</code>```

Prints:

```<code>[ nan]
</code>```

The issue is that tf.norm computes sum(x**2)**0.5. The gradient is x / sum(x**2) ** 0.5 (see e.g. https://math.stackexchange.com/a/84333), so when sum(x**2) is zero we're dividing by zero.

There's not much to be done in terms of a special case: the gradient as x approaches all zeros depends on which direction it's approaching from. For example if x is a single-element vector, the limit as x approaches 0 could either be 1 or -1 depending on which side of zero it's approaching from.

So in terms of solutions, you could just add a small epsilon:

```<code>import tensorflow as tf

def safe_norm(x, epsilon=1e-12, axis=None):
  return tf.sqrt(tf.reduce_sum(x ** 2, axis=axis) + epsilon)

with tf.Graph().as_default():
  y = tf.constant([0.])
  dist = safe_norm(y,axis=0)
  (grad,) = tf.gradients(dist, [y])
  with tf.Session():
    print(grad.eval())
</code>```

Prints:

```<code>[ 0.]
</code>```

Note that this is not actually the Euclidean norm. It's a good approximation as long as the input is much larger than epsilon.

Body:
The following snippet is from a fairly large piece of code but hopefully I can give all the information necessary:

y2 = tf.matmul(y1,ymask)

dist = tf.norm(ystar-y2,axis=0)

y1 and y2 are 128x30 and ymask is 30x30. ystar is 128x30. dist is 1x30. When ymask is the identity matrix, everything works fine. But when I set it to be all zeros, apart from a single 1 along the diagonal (so as to set all columns but one in y2 to be zero), I get nans for the gradient of dist with respect to y2, using tf.gradients(dist, [y2]). The specific value of dist is [0,0,7.9,0,...], with all the ystar-y2 values being around the range (-1,1) in the third column and zero elsewhere.

I'm pretty confused as to why a numerical issue would occur here, given there are no logs or divisions, is this underflow? Am I missing something in the maths?

For context, I'm doing this to try to train individual dimensions of y, one at a time, using the whole network.

longer version to reproduce:

import tensorflow as tf
import numpy as np
import pandas as pd

batchSize = 128
eta = 0.8
tasks = 30
imageSize = 32**2
groups = 3
tasksPerGroup = 10
trainDatapoints = 10000

w = np.zeros([imageSize, groups * tasksPerGroup])
toyIndex = 0
for toyLoop in range(groups):
    m = np.ones([imageSize]) * np.random.randn(imageSize)
    for taskLoop in range(tasksPerGroup):
        w[:, toyIndex] = m * 0.1 * np.random.randn(1)
        toyIndex += 1

xRand = np.random.normal(0, 0.5, (trainDatapoints, imageSize))
taskLabels = np.matmul(xRand, w) + np.random.normal(0,0.5,(trainDatapoints, groups * tasksPerGroup))
DF = np.concatenate((xRand, taskLabels), axis=1)
trainDF = pd.DataFrame(DF[:trainDatapoints, ])

# define graph variables
x = tf.placeholder(tf.float32, [None, imageSize])
W = tf.Variable(tf.zeros([imageSize, tasks]))
b = tf.Variable(tf.zeros([tasks]))
ystar = tf.placeholder(tf.float32, [None, tasks])
ymask = tf.placeholder(tf.float32, [tasks, tasks])
dataLength = tf.cast(tf.shape(ystar)[0],dtype=tf.float32)

y1 = tf.matmul(x, W) + b
y2 = tf.matmul(y1,ymask)
dist = tf.norm(ystar-y2,axis=0)
mse = tf.reciprocal(dataLength) * tf.reduce_mean(tf.square(dist))
grads = tf.gradients(dist, [y2])

trainStep = tf.train.GradientDescentOptimizer(eta).minimize(mse)

# build graph
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

randTask = np.random.randint(0, 9)
ymaskIn = np.zeros([tasks, tasks])
ymaskIn[randTask, randTask] = 1
batch = trainDF.sample(batchSize)
batch_xs = batch.iloc[:, :imageSize]
batch_ys = np.zeros([batchSize, tasks])
batch_ys[:, randTask] = batch.iloc[:, imageSize + randTask]

gradOut = sess.run(grads, feed_dict={x: batch_xs, ystar: batch_ys, ymask: ymaskIn})

sess.run(trainStep, feed_dict={x: batch_xs, ystar: batch_ys, ymask:ymaskIn})

Body:
Here's a very simple reproduction:

import tensorflow as tf

with tf.Graph().as_default():
  y = tf.zeros(shape=[1], dtype=tf.float32)
  dist = tf.norm(y,axis=0)
  (grad,) = tf.gradients(dist, [y])
  with tf.Session():
    print(grad.eval())

Prints:

[ nan]

The issue is that tf.norm computes sum(x**2)**0.5. The gradient is x / sum(x**2) ** 0.5 (see e.g. https://math.stackexchange.com/a/84333), so when sum(x**2) is zero we're dividing by zero.

There's not much to be done in terms of a special case: the gradient as x approaches all zeros depends on which direction it's approaching from. For example if x is a single-element vector, the limit as x approaches 0 could either be 1 or -1 depending on which side of zero it's approaching from.

So in terms of solutions, you could just add a small epsilon:

import tensorflow as tf

def safe_norm(x, epsilon=1e-12, axis=None):
  return tf.sqrt(tf.reduce_sum(x ** 2, axis=axis) + epsilon)

with tf.Graph().as_default():
  y = tf.constant([0.])
  dist = safe_norm(y,axis=0)
  (grad,) = tf.gradients(dist, [y])
  with tf.Session():
    print(grad.eval())

Prints:

[ 0.]

Note that this is not actually the Euclidean norm. It's a good approximation as long as the input is much larger than epsilon.


问:
Limit Amazon AWS Access of Specific EC2/RDS Instances
I have an Amazon EC2 instance and a corresponding RDS instance that I want to keep private. I'd like to keep it so that only myself and the sysadmin can access these instances. I don't want to provide access to other developers.

However, one of my developers is working on a project right now where he needs to create/configure his own EC2/RDS instance. I could have my sysadmin perform this work, but I'd rather have the developer do it for the sake of expediency.

Is there any way to configure a group/role/policy in a way that allows me to keep my current instances private from the new developer, but would allow him to create his own EC2 and RDS instances?

答:
Your question appears to be mixing several security concepts, such as 'private', 'group/role/policy' and 'firewalls'.

An Amazon EC2 instance has several layers of security:

First, there is the ability to login to the EC2 instance. This is managed by you, typically by creating users on the instance (in either Linux or Windows) and associating a password or Public/Private. Only people who have login credentials will be able to access the instance.

Second, there is the ability to reach the instance. Security Groups control which ports are open from which IP address range. Therefore, you could configure a security group to only make the instance accessible from your own IP address or your own private network. Your instance might also be in a private subnet that has no Internet connectivity. This again restricts access to the instance.

A person can therefore only login to an instance if they have login credentials, if the security group(s) permit access on the protocol being used (RDP or SSH) and if the instance is reachable by the user from the Internet or private network.

Similarly, an Amazon Relational Database Service (RDS) instance is protected by:

Login credentials: A master user login is created when the database is launched, but additional users can be added via normal CREATE USER database commands

Security Groups: As with EC2 instances, security groups control what ports are open to a particular range of IP addresses

Network security: As with EC2 instances, an RDS instance can be placed in a private subnet, which is not accessible from the Internet.

Please note that none of the above controls involve Identity and Access Management (IAM) users/groups/roles/policies, which are used to grant access to AWS services, such as the ability to launch an Amazon EC2 instance or an Amazon RDS instance.

So, the fact that you have existing Amazon EC2 and Amazon RDS instances has no impact on the security of any other instances that you choose to launch. If a user cannot access your existing services, then launching more services will not change that situation.

If you wish to give another person the ability to launch new EC2/RDS instances, you can do this by applying an appropriate policy on their IAM User entity. However, you might want to be careful about how much permission you give them, because you might also be granting them the ability to delete your existing instances, change the master password, create and restore snapshots (thereby potentially accessing your data) and change network configurations (potentially exposing your instances to the Internet).

When granting IAM permissions to somebody, it is recommend that you grant least privilege, which means you should only give them the permissions they need and nothing more. If you are unsure about how much permission to give them or how to configure these permissions, you would be wise to have your System Administrator create the instances on their behalf. That way, you are fully aware of what has been done and you have not potentially exposed your systems.


问:
How to iterate over multiline variable in bash?
Given

```<code># this is programmatically generated... hard-coded here for this example
commands="\nthing1@this is thing 1!\nthing2@this is thing 2!"

while read -r line; do
  cmd=$(printf "$line" | cut -d'@' -f1 | tr -d '\n')
  desc=$(printf "$line" | cut -d'@' -f2 | tr -d '\n')

  printf '  %-20s %s\n' "$cmd" "$desc"
done <<< "$commands"
</code>```

I'd expect that to output

```<code>  thing1        this is thing1!
  thing2        this is thing2!
</code>```

Instead I get

```<code>  thing1thing2        this is thing1!this is thing2!
</code>```

What am I doing wrong?

I want to read over the newlines, so I can then cut on @ and printf accordingly.

答:
according to your question, it seems like bash does not interpret any of \n \t \f e.t.c when used with here strings.This might be what you want, it might be bad practice. And an exclamation mark wrapped around double quote will result in an error, because bash will try to evaluate it as an event ( command executed on the shell at some point ) , so you have to escape that ( when used from the terminal )

```<code>commands="\nthing1@this is thing 1\!\nthing2@this is thing 2!"

while read line;do
   // do your stuff here
line <<< $( echo -e "${commands}" )  # -e switch tells the echo command to honour all back slashes . The same behaviour can be achieved with `shopt -s xpg_echo` ( you have to remove -e switch whenever you do that )
</code>```

noise: Note: When used from the terminal: if you look closely at the command variable i did not backslash the "!" this is because it is not proceeded by any value, so bash will not try to locate the preceded value as an event.

check the history expansion section of bash man page for more information on that if you wish

Body:
Given

# this is programmatically generated... hard-coded here for this example
commands="\nthing1@this is thing 1!\nthing2@this is thing 2!"

while read -r line; do
  cmd=$(printf "$line" | cut -d'@' -f1 | tr -d '\n')
  desc=$(printf "$line" | cut -d'@' -f2 | tr -d '\n')

  printf '  %-20s %s\n' "$cmd" "$desc"
done <<< "$commands"

I'd expect that to output

  thing1        this is thing1!
  thing2        this is thing2!

Instead I get

  thing1thing2        this is thing1!this is thing2!

What am I doing wrong?

I want to read over the newlines, so I can then cut on @ and printf accordingly.

Body:
according to your question, it seems like bash does not interpret any of \n \t \f e.t.c when used with here strings.This might be what you want, it might be bad practice. And an exclamation mark wrapped around double quote will result in an error, because bash will try to evaluate it as an event ( command executed on the shell at some point ) , so you have to escape that ( when used from the terminal )

commands="\nthing1@this is thing 1\!\nthing2@this is thing 2!"

while read line;do
   // do your stuff here
line <<< $( echo -e "${commands}" )  # -e switch tells the echo command to honour all back slashes . The same behaviour can be achieved with `shopt -s xpg_echo` ( you have to remove -e switch whenever you do that )

noise: Note: When used from the terminal: if you look closely at the command variable i did not backslash the "!" this is because it is not proceeded by any value, so bash will not try to locate the preceded value as an event.

check the history expansion section of bash man page for more information on that if you wish


问:
Collapsing divs depending on resolution
I've got 6 divs floating rights. I have used percentages for responsiveness, sharing out 33.3% with 3 divs for a row. Worked fine for my laptop resolution - but as I resize the screen both smaller and larger, the divs begin to collapse. Can't seem to find a fix, if anyone can care to explain why this is the case, despite the percentage being a reference to I presume the individual viewport?

.routine-content {
  text-align: center;
}

.routine-content ul li {
  display: block;
  line-height: 1.1em;
  font-family: 'amiri';
  margin-top: 10px;
}

.routine {
  max-width: 30.3333333333%;
  float: left;
  margin-top: 20px;
  margin-left: 3%;
  word-wrap: break-word;
  vertical-align: top;
}

.routine-content h1 {
  font-family: 'Pacifico', sans-serif;
  font-size: 30px;
  text-decoration: underline;
}

.routine-content h2 {
  font-family: 'Amaranth';
  margin-bottom: 10px;
  font-size: 18px;
}

.routine span {
  font-weight: bolder;
}

.routine-content p {
  font-family: 'amiri';
  width: 50%;
  text-align: center;
  margin: 0 auto;
  margin-top: 20px;
  font-size: 18px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="routine-content">
  <div class="inner-wrapper">

    <!-- Monday Routine -->
    <div class="routine monday">
      <h2>Monday</h2>
      <ul>
        <li>
          <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.
        </li>

        <li>
          <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so your head..
        </li>

        <li>
          <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
        </li>

        <li>
          <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground for.
        </li>
      </ul>
    </div>

    <!-- Tuesday Routine -->
    <div class="routine tuesday">
      <h2>Tuesday</h2>

      <ul>
        <li>
          <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.
        </li>

        <li>
          <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so. loor.
        </li>

        <li>
          <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't available, try a bent-over row.
        </li>

        <li>
          <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground.
        </li>
      </ul>
    </div>

    <!-- Wednsday Routine -->
    <div class="routine wednesday">
      <h2>Wednesday</h2>
      <ul>
        <li>
          <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees..
        </li>

        <li>
          <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so.
        </li>

        <li>
          <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
        </li>

        <li>
          <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground for this one if that feels more comfortable.
        </li>
      </ul>
    </div>

    <!-- Thursday Routine-->
    <div class="routine thursday">
      <h2>Thursday</h2>
      <ul>
        <li>
          <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.
        </li>

        <li>
          <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so your head, back.
        </li>

        <li>
          <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
        </li>

        <li>
          <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: one if that feels more comfortable.
        </li>
      </ul>
    </div>

    <!-- Friday Routine -->
    <div class="routine friday">
      <h2>Friday</h2>
      <ul>
        <li>
          <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your. and don't let your knees go over your toes during this lower-body move.
        </li>

        <li>
          <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so your the bench, your feet flat on the floor.
        </li>

        <li>
          <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
        </li>

        <li>
          <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You .
        </li>
      </ul>
    </div>

    <!-- Saturday Routine -->
    <div class="routine saturday">
      <h2>Saturday</h2>

      <ul>
        <li>
          <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your.
        </li>

        <li>
          <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so. loor.
        </li>

        <li>
          <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you, try a bent-over row.
        </li>

        <li>
          <span>Lying Isometric Y</span>,—Hold for 30 seconds. You can keep your legs on the ground.
        </li>
      </ul>
    </div>

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

答:
I'm not super sure what you mean by collapse, but I think this should solve it. You can have different CSS be activated based on the device width (see here).  I did this below.  So, when the width is below 500px, the workouts will be displayed with only one per row.  Otherwise, there will be three per row as there is currently.  Feel free to toy around with the max-width parameter to see what works best.

.routine-content{
    text-align:center;
}
.routine-content ul li{
    display:block;
    line-height:1.1em;
    font-family:'amiri';
    margin-top:10px;

}

.routine{
    max-width:30.3333333333%;
    float:left;
    white-space: normal;
    margin-top:20px;
    margin-left:3%;
    word-wrap:break-word;
    vertical-align:top;

}

.routine-content h1{
    font-family:'Pacifico',sans-serif;
    font-size:30px;
    text-decoration: underline;
}

.routine-content h2{
    font-family:'Amaranth';
    margin-bottom:10px;
    font-size:18px;
}

.routine span{
    font-weight: bolder;
}
.routine-content p{
    font-family:'amiri';
    width:50%;
    text-align:center;
    margin: 0 auto;
    margin-top:20px;
    font-size: 18px;
}

@media screen and (max-width: 500px) {
    .routine {
      text-align: center;
      max-width:100%;
      display: block;
      float: center;
      clear: both;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "routine-content">
 <div class = "inner-wrapper">

    <div style="width:100%;">
  <!-- Monday Routine -->
  <div align="center" class = "routine monday">
   <h2 class="workoutheader">Monday</h2>
   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so your head..
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground for.
    </li>
   </ul>
  </div>

  <!-- Tuesday Routine -->
  <div align="center" class = "routine tuesday">
   <h2>Tuesday</h2>

   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so. loor.
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't available, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground.
    </li>
   </ul>
  </div>

  <!-- Wednsday Routine -->
  <div align="center" class = "routine wednesday">
   <h2>Wednesday</h2>
   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees..
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so.
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground for this one if that feels more comfortable.
    </li>
   </ul>
  </div>
</div>
<div align="center" style="width:100%">
  <!-- Thursday Routine-->
  <div class = "routine thursday">
   <h2>Thursday</h2>
   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so your head, back.
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: one if that feels more comfortable.
    </li>
   </ul>
  </div>

  <!-- Friday Routine -->
  <div align="center" class = "routine friday">
   <h2>Friday</h2>
   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your. and don't let your knees go over your toes during this lower-body move.
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so your the bench, your feet flat on the floor.
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You .
    </li>
   </ul>
  </div>

  <!-- Saturday Routine -->
  <div align="center" class = "routine saturday">
   <h2>Saturday</h2>

   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your.
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so. loor.
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. You can keep your legs on the ground.
    </li>
   </ul>
  </div>
<div>
 </div>
</div></code>```

Title: Collapsing divs depending on resolution

Body:
I've got 6 divs floating rights. I have used percentages for responsiveness, sharing out 33.3% with 3 divs for a row. Worked fine for my laptop resolution - but as I resize the screen both smaller and larger, the divs begin to collapse. Can't seem to find a fix, if anyone can care to explain why this is the case, despite the percentage being a reference to I presume the individual viewport?

.routine-content {
  text-align: center;
}

.routine-content ul li {
  display: block;
  line-height: 1.1em;
  font-family: 'amiri';
  margin-top: 10px;
}

.routine {
  max-width: 30.3333333333%;
  float: left;
  margin-top: 20px;
  margin-left: 3%;
  word-wrap: break-word;
  vertical-align: top;
}

.routine-content h1 {
  font-family: 'Pacifico', sans-serif;
  font-size: 30px;
  text-decoration: underline;
}

.routine-content h2 {
  font-family: 'Amaranth';
  margin-bottom: 10px;
  font-size: 18px;
}

.routine span {
  font-weight: bolder;
}

.routine-content p {
  font-family: 'amiri';
  width: 50%;
  text-align: center;
  margin: 0 auto;
  margin-top: 20px;
  font-size: 18px;
}

Monday

          Bodyweight Squats—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.

          Dumbbell Bench Press—12 reps. Quick tip: Position yourself so your head..

          Dumbbell Row—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.

          Lying Isometric Y,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground for.

Tuesday

          Bodyweight Squats—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.

          Dumbbell Bench Press—12 reps. Quick tip: Position yourself so. loor.

          Dumbbell Row—12 reps each side. Quick tip: If you don't available, try a bent-over row.

          Lying Isometric Y,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground.

Wednesday

          Bodyweight Squats—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees..

          Dumbbell Bench Press—12 reps. Quick tip: Position yourself so.

          Dumbbell Row—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.

          Lying Isometric Y,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground for this one if that feels more comfortable.

Thursday

          Bodyweight Squats—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.

          Dumbbell Bench Press—12 reps. Quick tip: Position yourself so your head, back.

          Dumbbell Row—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.

          Lying Isometric Y,—Hold for 30 seconds. Quick tip: one if that feels more comfortable.

Friday

          Bodyweight Squats—15 reps.Quick tip: Get low, keep your. and don't let your knees go over your toes during this lower-body move.

          Dumbbell Bench Press—12 reps. Quick tip: Position yourself so your the bench, your feet flat on the floor.

          Dumbbell Row—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.

          Lying Isometric Y,—Hold for 30 seconds. Quick tip: You .

Saturday

          Bodyweight Squats—15 reps.Quick tip: Get low, keep your chest up, and don't let your.

          Dumbbell Bench Press—12 reps. Quick tip: Position yourself so. loor.

          Dumbbell Row—12 reps each side. Quick tip: If you, try a bent-over row.

          Lying Isometric Y,—Hold for 30 seconds. You can keep your legs on the ground.

Body:
I'm not super sure what you mean by collapse, but I think this should solve it. You can have different CSS be activated based on the device width (see here).  I did this below.  So, when the width is below 500px, the workouts will be displayed with only one per row.  Otherwise, there will be three per row as there is currently.  Feel free to toy around with the max-width parameter to see what works best.

.routine-content{
    text-align:center;
}
.routine-content ul li{
    display:block;
    line-height:1.1em;
    font-family:'amiri';
    margin-top:10px;

}

.routine{
    max-width:30.3333333333%;
    float:left;
    white-space: normal;
    margin-top:20px;
    margin-left:3%;
    word-wrap:break-word;
    vertical-align:top;

}

.routine-content h1{
    font-family:'Pacifico',sans-serif;
    font-size:30px;
    text-decoration: underline;
}

.routine-content h2{
    font-family:'Amaranth';
    margin-bottom:10px;
    font-size:18px;
}

.routine span{
    font-weight: bolder;
}
.routine-content p{
    font-family:'amiri';
    width:50%;
    text-align:center;
    margin: 0 auto;
    margin-top:20px;
    font-size: 18px;
}

@media screen and (max-width: 500px) {
    .routine {
      text-align: center;
      max-width:100%;
      display: block;
      float: center;
      clear: both;
    }
}

<div class = "routine-content">
 <div class = "inner-wrapper">

    <div style="width:100%;">
  <!-- Monday Routine -->
  <div align="center" class = "routine monday">
   <h2 class="workoutheader">Monday</h2>
   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so your head..
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground for.
    </li>
   </ul>
  </div>

  <!-- Tuesday Routine -->
  <div align="center" class = "routine tuesday">
   <h2>Tuesday</h2>

   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so. loor.
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't available, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground.
    </li>
   </ul>
  </div>

  <!-- Wednsday Routine -->
  <div align="center" class = "routine wednesday">
   <h2>Wednesday</h2>
   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees..
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so.
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You can keep your legs on the ground for this one if that feels more comfortable.
    </li>
   </ul>
  </div>
</div>
<div align="center" style="width:100%">
  <!-- Thursday Routine-->
  <div class = "routine thursday">
   <h2>Thursday</h2>
   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your knees go over your toes during this lower-body move.
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so your head, back.
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: one if that feels more comfortable.
    </li>
   </ul>
  </div>

  <!-- Friday Routine -->
  <div align="center" class = "routine friday">
   <h2>Friday</h2>
   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your. and don't let your knees go over your toes during this lower-body move.
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so your the bench, your feet flat on the floor.
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you don't have a bench available, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. Quick tip: You .
    </li>
   </ul>
  </div>

  <!-- Saturday Routine -->
  <div align="center" class = "routine saturday">
   <h2>Saturday</h2>

   <ul>
    <li>
    <span>Bodyweight Squats</span>—15 reps.Quick tip: Get low, keep your chest up, and don't let your.
    </li>

    <li>
    <span>Dumbbell Bench Press</span>—12 reps. Quick tip: Position yourself so. loor.
    </li>

    <li>
    <span>Dumbbell Row</span>—12 reps each side. Quick tip: If you, try a bent-over row.
    </li>

    <li>
    <span>Lying Isometric Y</span>,—Hold for 30 seconds. You can keep your legs on the ground.
    </li>
   </ul>
  </div>
<div>
 </div>
</div>


问:
Doubles are contaminating my BigDecimal math
I'm writing a Mandelbrot Set explorer. I need as much precision as possible so I can zoom in as far as possible.

I noticed an unfortunate side-effect of mixing doubles and BigDecimals: they "contaminate" the type returned:

```<code>(type (* 1M 2))
=> java.math.BigDecimal

(type (* 1M 2.0))
=> java.lang.Double
</code>```

I expected the opposite. BigDecimals, being potentially more precise, should contaminate the doubles.

Besides manually calling bigdec on every number that may come in contact with a BigDecimal, is there a way of preventing the auto-downgrade to double when doing math on doubles and BigDecimals?

答:
Once you introduce a double into the equation, you limit the amount of precision you can possibly have. A BigDecimal accurate to within a million decimal places is no use to you, if the way you got it involved multiplying by something with just 15 or so significant digits. You could promote the result to a BigDecimal, but you've lost a ton of precision whether you like it or not. Therefore, Clojure's promotion rules make that obvious for you, by giving back a double instead of a high-precision BigDecimal.

See, for example, BigDecimal's JavaDoc for an explanation of why it is a bad idea to convert doubles to BigDecimals, implicitly or explicitly.

Body:
I'm writing a Mandelbrot Set explorer. I need as much precision as possible so I can zoom in as far as possible.

I noticed an unfortunate side-effect of mixing doubles and BigDecimals: they "contaminate" the type returned:

(type (* 1M 2))
=> java.math.BigDecimal

(type (* 1M 2.0))
=> java.lang.Double

I expected the opposite. BigDecimals, being potentially more precise, should contaminate the doubles.

Besides manually calling bigdec on every number that may come in contact with a BigDecimal, is there a way of preventing the auto-downgrade to double when doing math on doubles and BigDecimals?


问:
Pass data depends on the button in tableView cell
I have a TableView where I display all my data and each cell might have 1-2 buttons. I read many topics and understand how to add target for each button through my ViewController. Since these buttons will be forwarded to the same VC and display images, I have the following code. In my TableViewCell subclass I have 2 buttons

```<code>class CODetailsTicketCell: UITableViewCel {

      var onButtonTapped: (() -> Void)? = nil

      @IBAction func firstBtnTapped(_ sender: UIButton) {
          if let onButtonTapped = self.onButtonTapped {
              onButtonTapped()
          }
         print("First button was pressed")

     }

      @IBAction func secondBtnTapped(_ sender: UIButton) {
          if let onButtonTapped = self.onButtonTapped {
             onButtonTapped()
          }
          print("Second button was pressed")
     }
}
</code>```

In my ViewController in cellForRowAt indexPath I have the following code

```<code>let message = messages[indexPath.row]

if let cell = tableView.dequeueReusableCell(withIdentifier: "COTicketsCell", for: indexPath) as? CODetailsTicketCell {
    cell.configureCell(openTickets: message)
    cell.onButtonTapped = {
         self.performSegue(withIdentifier: "toImageVC", sender: message)
     }

     return cell
</code>```

In order to pass the data through segue I use the following code in prepareForSegue

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toImageVC" {
        let navigationController = segue.destination as? UINavigationController
        if let targetController = navigationController?.topViewController as? ImageVC {
            if let data = sender as? OpenTicketsData {
                targetController.loadImageURL = URL(string: data.firstImageUrl)
            }

        }
    }
}
</code>```

Everything is working FINE but I can't check for button tag in prepareForSegue. Basically, currently both buttons send the same data

```<code>targetController.loadImageURL = URL(string: data.firstImageUrl)
</code>```

How can I pass data based on the button pressed? I tried to do something like this but seems it's wrong and not working.

```<code>let button = sender as? UIButton
if let data = sender as? OpenTicketsData {
   if button?.tag == 1 {
      targetController.loadImageURL = URL(string: data.firstImageUrl)
   } else if button?.tag == 2 {
      targetController.loadImageURL = URL(string: data.secondImageUrl)
   }
}
</code>```

答:
You can either separate it into 2 different events or

```<code>class CODetailsTicketCell: UITableViewCell {

      var onButtonTapped: ((_ sender: UIButton) -> Void)? = nil

      @IBAction func firstBtnTapped(_ sender: UIButton) {
          if let onButtonTapped = self.onButtonTapped {
              onButtonTapped?(sender)
          }
         print("First button was pressed")

     }

      @IBAction func secondBtnTapped(_ sender: UIButton) {
          if let onButtonTapped = self.onButtonTapped {
              onButtonTapped(sender)
          }
          print("Second button was pressed")
     }
}
</code>```

In your assignment of the onButtonTapped, remember to add [weak self] if you ever use self to avoid the retain cycle.

```<code>cell.onButtonTapped = { [weak self] sender in
    if sender.tag == 1 {
        // Do something
    } else {
        // Do other thing
    }
}
</code>```

Body:
I have a TableView where I display all my data and each cell might have 1-2 buttons. I read many topics and understand how to add target for each button through my ViewController. Since these buttons will be forwarded to the same VC and display images, I have the following code. In my TableViewCell subclass I have 2 buttons

class CODetailsTicketCell: UITableViewCel {

      var onButtonTapped: (() -> Void)? = nil

      @IBAction func firstBtnTapped(_ sender: UIButton) {
          if let onButtonTapped = self.onButtonTapped {
              onButtonTapped()
          }
         print("First button was pressed")

     }

      @IBAction func secondBtnTapped(_ sender: UIButton) {
          if let onButtonTapped = self.onButtonTapped {
             onButtonTapped()
          }
          print("Second button was pressed")
     }
}

In my ViewController in cellForRowAt indexPath I have the following code

let message = messages[indexPath.row]

if let cell = tableView.dequeueReusableCell(withIdentifier: "COTicketsCell", for: indexPath) as? CODetailsTicketCell {
    cell.configureCell(openTickets: message)
    cell.onButtonTapped = {
         self.performSegue(withIdentifier: "toImageVC", sender: message)
     }

     return cell

In order to pass the data through segue I use the following code in prepareForSegue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toImageVC" {
        let navigationController = segue.destination as? UINavigationController
        if let targetController = navigationController?.topViewController as? ImageVC {
            if let data = sender as? OpenTicketsData {
                targetController.loadImageURL = URL(string: data.firstImageUrl)
            }

        }
    }
}

Everything is working FINE but I can't check for button tag in prepareForSegue. Basically, currently both buttons send the same data

targetController.loadImageURL = URL(string: data.firstImageUrl)

How can I pass data based on the button pressed? I tried to do something like this but seems it's wrong and not working.

let button = sender as? UIButton
if let data = sender as? OpenTicketsData {
   if button?.tag == 1 {
      targetController.loadImageURL = URL(string: data.firstImageUrl)
   } else if button?.tag == 2 {
      targetController.loadImageURL = URL(string: data.secondImageUrl)
   }
}

Body:
You can either separate it into 2 different events or

class CODetailsTicketCell: UITableViewCell {

      var onButtonTapped: ((_ sender: UIButton) -> Void)? = nil

      @IBAction func firstBtnTapped(_ sender: UIButton) {
          if let onButtonTapped = self.onButtonTapped {
              onButtonTapped?(sender)
          }
         print("First button was pressed")

     }

      @IBAction func secondBtnTapped(_ sender: UIButton) {
          if let onButtonTapped = self.onButtonTapped {
              onButtonTapped(sender)
          }
          print("Second button was pressed")
     }
}

In your assignment of the onButtonTapped, remember to add [weak self] if you ever use self to avoid the retain cycle.

cell.onButtonTapped = { [weak self] sender in
    if sender.tag == 1 {
        // Do something
    } else {
        // Do other thing
    }
}


问:
Creating Noncontinuous Scroll Boxes and Measuring Time in Each Section
I have a two-part question on creating scroll boxes to be used in a Qualtrics survey and measuring the amount of time people spend looking at the different sections of text within a scroll box.

I'm looking to create a scroll box that contains two paragraphs, where only one paragraph is visible at a time (not continuous scrolling), that can be used in a Qualtrics survey. I've found some html guides for creating scroll boxes (https://www.quackit.com/html/codes/html_scroll_box.cfm) but they all seem to only show continuous scrolling.

I also need a way to measure the total amount of time that each paragraph was visible on the screen (If the reader flips back and forth between the two paragraphs, I need to capture the full amount of time that each paragraph was onscreen). Again, I've found resources on how to measure the amount of scrolling (http://www.javascriptkit.com/javatutors/detect-user-scroll-amount.shtml), but not the amount of time within the different sections within the scroll box.

Any help would be greatly appreciated!

答:
I do not know how you will determine when a user enters or exits a scroll box, but one way to measure the time in each scroll box is to use something like the method below:

```<code>var scrollBox1Time = 0;
var scrollBox2Time = 0;
//When user enters scroll box 1
var startTime = new Date().getTime();

//When user exits scroll box 1
var endTime = new Date().getTime();
scrollBox1Time += (endTime-startTime);

//When user enters scroll box 2
var startTime = new Date().getTime();

//When user exits scroll box 2
var endTime = new Date().getTime();
scrollBox2Time += (endTime-startTime);  //Add time for scroll box 2
</code>```

The time is measured in milliseconds.

Body:
I do not know how you will determine when a user enters or exits a scroll box, but one way to measure the time in each scroll box is to use something like the method below:

var scrollBox1Time = 0;
var scrollBox2Time = 0;
//When user enters scroll box 1
var startTime = new Date().getTime();

//When user exits scroll box 1
var endTime = new Date().getTime();
scrollBox1Time += (endTime-startTime);

//When user enters scroll box 2
var startTime = new Date().getTime();

//When user exits scroll box 2
var endTime = new Date().getTime();
scrollBox2Time += (endTime-startTime);  //Add time for scroll box 2

The time is measured in milliseconds.