问:
Bootstrap 4 Modal Will Not Open on Click
I can not get my modal to open. I tried just the plain HTML found on the Bootstrap 4 site and then used some Javascript. I really can not figure out what I am doing wrong. Any help would be very much appreciated!

enter code here<

```<code><div class="col-sm-3 col-centered  boxes" id="box1">

  <button type="button" class="btn btn-primary" id="box1modal" data-toggle="modal" data-target="#exampleModal">

    See More

  </button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

    <div class="modal-dialog" role="document">

      <div class="modal-content">

        <div class="modal-header">

          <h5 class="modal-title" id="exampleModalLabel">Wedding Invites</h5>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">

            <span aria-hidden="true">×</span>

          </button>

        </div>

        <div class="modal-body">

          <img src="Wedding%20Invites.jpg">

        </div>

        <div class="modal-footer">

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

          <button type="button" class="btn btn-primary">Save changes</button>

        </div>

      </div>

    </div>

  </div>

</div>
 `enter code here`<script type="text/javascript">
</code>```

enter code here $("#box1modal").click(function(event){

 enter code here$('#myModal').modal('show');
    enter code here  )};

答:
i test your code , every things  fine just you have to make sure

1) add references
2) your code must be inside  $(document).ready(function(){ ---- }

```<code><html>
<head>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
<div class="col-sm-3 col-centered  boxes" id="box1">

  <button type="button" class="btn btn-primary" id="box1modal" data-toggle="modal" data-target="#exampleModal">

    See More

  </button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

    <div class="modal-dialog" role="document">

      <div class="modal-content">

        <div class="modal-header">

          <h5 class="modal-title" id="exampleModalLabel">Wedding Invites</h5>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">

            <span aria-hidden="true">×</span>

          </button>

        </div>

        <div class="modal-body">

          <img src="Wedding%20Invites.jpg">

        </div>

        <div class="modal-footer">

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

          <button type="button" class="btn btn-primary">Save changes</button>

        </div>

      </div>

    </div>

  </div>

</div>

</body>
</hmtl>

<script>

$(document).ready(function(){

$('#box1modal').click(function(){
alert("btn click")
$('#myModal').modal('show')
});

});

</script>
</code>```

Body:
I can not get my modal to open. I tried just the plain HTML found on the Bootstrap 4 site and then used some Javascript. I really can not figure out what I am doing wrong. Any help would be very much appreciated!

enter code here<

  <button type="button" class="btn btn-primary" id="box1modal" data-toggle="modal" data-target="#exampleModal">

    See More

  </button>

Wedding Invites

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">

            ×

          </button>

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

          <button type="button" class="btn btn-primary">Save changes</button>

 `enter code here`

Body:
i test your code , every things  fine just you have to make sure

1) add references
2) your code must be inside  $(document).ready(function(){ ---- }

<html>
<head>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
<div class="col-sm-3 col-centered  boxes" id="box1">

  <button type="button" class="btn btn-primary" id="box1modal" data-toggle="modal" data-target="#exampleModal">

    See More

  </button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

    <div class="modal-dialog" role="document">

      <div class="modal-content">

        <div class="modal-header">

          <h5 class="modal-title" id="exampleModalLabel">Wedding Invites</h5>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">

            <span aria-hidden="true">&times;</span>

          </button>

        </div>

        <div class="modal-body">

          <img src="Wedding%20Invites.jpg">

        </div>

        <div class="modal-footer">

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

          <button type="button" class="btn btn-primary">Save changes</button>

        </div>

      </div>

    </div>

  </div>

</div>

</body>
</hmtl>

<script>

$(document).ready(function(){

$('#box1modal').click(function(){
alert("btn click")
$('#myModal').modal('show')
});

});

</script>


来源: stackexchange

问:
iframe not disappearing
I have an iframe:

```<code>parent.document.getElementById("IFRAMENAME").style.display = "none";
</code>```

What would cause this code not to work?  If i set the width to 0px it hides it.  I debugged to make sure all the values of the frame are coming back.

I am using ie 7

答:
Is your stylesheet overriding this assignment?

If you have:

```<code> iframe#IFRAMENAME {display:block !important}
</code>```

or something similar, it could supercede that code.

Also, does the code work in, say, other browsers?

ContentLicense: CC BY-SA 2.5

Title: iframe not disappearing

Body:
I have an iframe:

parent.document.getElementById("IFRAMENAME").style.display = "none";

What would cause this code not to work?  If i set the width to 0px it hides it.  I debugged to make sure all the values of the frame are coming back.

I am using ie 7

Body:
Is your stylesheet overriding this assignment?

If you have:

 iframe#IFRAMENAME {display:block !important}

or something similar, it could supercede that code.

Also, does the code work in, say, other browsers?


问:
I can't get my drawed picture in browser
This is the HTML code:

```<code><body >
<canvas id ="my_canvas" width =500 height =500></canvas>
</body >
</code>```

This is my JavaScript code:

```<code>var canvas = document.getElememtById("my_canvas");
var c=canvas.getContext("2d");
c.beginPath();
c.moveTo(100,200);
c.lineTo(200,200);
c.fill();
c.stroke();
c.endPath();
</code>```

After all done,I can't see anything in browser.

答:
This is your syntactically right   code:

var canvas = document.getElementById("my_canvas");
var c = canvas.getContext("2d");
c.beginPath();
c.moveTo(100,200);
c.lineTo(200,200);
c.closePath();
c.stroke();
c.fill();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body >
  <canvas id="my_canvas" width=500 height=500></canvas>
</body ></code>```

You had multiple syntax errors in your code.
It is closePath instead of endPath and your element's  spellings were wrong.I might have missed some in hurry .Just have a look on the syntax.

ContentLicense: CC BY-SA 3.0

Body:
This is the HTML code:

<canvas id ="my_canvas" width =500 height =500></canvas>

This is my JavaScript code:

var canvas = document.getElememtById("my_canvas");
var c=canvas.getContext("2d");
c.beginPath();
c.moveTo(100,200);
c.lineTo(200,200);
c.fill();
c.stroke();
c.endPath();

After all done,I can't see anything in browser.

Body:
This is your syntactically right   code:

var canvas = document.getElementById("my_canvas");
var c = canvas.getContext("2d");
c.beginPath();
c.moveTo(100,200);
c.lineTo(200,200);
c.closePath();
c.stroke();
c.fill();

<body >
  <canvas id="my_canvas" width=500 height=500></canvas>
</body >

You had multiple syntax errors in your code.
It is closePath instead of endPath and your element's  spellings were wrong.I might have missed some in hurry .Just have a look on the syntax.


问:
Sequelize.js: findById() not found the data
I want to verify incoming token and I try to find user by Id:

```<code>module.exports = function (req) {
    var decodeToken = jwt.decode(req.cookies.token, JwtOptions.secretOrKey);
    db.users.findById(decodeToken.id).then(function (foundUser) {
        //It's example checking for self-learning
        if (foundUser.username == req.cookies.username) {
            return foundUser;
        }
        //Or more logic for token authentication
    }), function (error) {
        return error;
    }
</code>```

But I get "return false". I view foundUser variable for debuggindg, and it has message

'Reference Error: foundUser is nor defined'

In console I can see query:

Executing (default): SELECT "id", "username", "email", "password",
  "createdAt", "updatedAt" FROM "users" AS "users" WHERE "users"."id" =
  2;

And I have the user with id=2 in a db.
Why it doesn't work?

Addition:

I tried MWY's modified example:

```<code>module.exports = function (req) {
    var decodeToken = jwt.decode(req.cookies.token, JwtOptions.secretOrKey);
    findUserById().then(function(foundUser) {
        //It's example checking for self-learning
        if (foundUser.username == req.cookies.username) {
            return foundUser;
        }
        //Or more logic for token authentication
    }), function (error) {
        return error;
    }

    function findUserById() {
        return db.users.findById(decodeToken.id).then(function (foundUser) {
            return foundUser;
        }), function (error) {
            return error;
        }
    }
}
</code>```

And get error:

TypeError: findUserById(...).then is not a function

答:
Be sure to remember asynchronously

Because asynchronously! you will get false first, then get the result!

So you can write like this, In ty.js file

```<code>      module.exports = function (req) {
      var decodeToken = jwt.decode(req.cookies.token,   JwtOptions.secretOrKey);
      return db.users.findById(decodeToken.id).then(function (foundUser) {
    //It's example checking for self-learning
    if (foundUser.username == req.cookies.username) {
        return foundUser;
    }
    //Or more logic for token authentication
    }).catch(function (err) {
    return err;
     })
   };
</code>```

In tu.js file:

```<code>   var user = require('./ty');

   user().then(function (result) {
   //search findById result
   console.log(result)

   });
</code>```

Body:
I want to verify incoming token and I try to find user by Id:

module.exports = function (req) {
    var decodeToken = jwt.decode(req.cookies.token, JwtOptions.secretOrKey);
    db.users.findById(decodeToken.id).then(function (foundUser) {
        //It's example checking for self-learning
        if (foundUser.username == req.cookies.username) {
            return foundUser;
        }
        //Or more logic for token authentication
    }), function (error) {
        return error;
    }

But I get "return false". I view foundUser variable for debuggindg, and it has message

'Reference Error: foundUser is nor defined'

In console I can see query:

Executing (default): SELECT "id", "username", "email", "password",
  "createdAt", "updatedAt" FROM "users" AS "users" WHERE "users"."id" =
  2;

And I have the user with id=2 in a db.
Why it doesn't work?

Addition:

I tried MWY's modified example:

module.exports = function (req) {
    var decodeToken = jwt.decode(req.cookies.token, JwtOptions.secretOrKey);
    findUserById().then(function(foundUser) {
        //It's example checking for self-learning
        if (foundUser.username == req.cookies.username) {
            return foundUser;
        }
        //Or more logic for token authentication
    }), function (error) {
        return error;
    }

    function findUserById() {
        return db.users.findById(decodeToken.id).then(function (foundUser) {
            return foundUser;
        }), function (error) {
            return error;
        }
    }
}

And get error:

TypeError: findUserById(...).then is not a function

Body:
Be sure to remember asynchronously

Because asynchronously! you will get false first, then get the result!

So you can write like this, In ty.js file

      module.exports = function (req) {
      var decodeToken = jwt.decode(req.cookies.token,   JwtOptions.secretOrKey);
      return db.users.findById(decodeToken.id).then(function (foundUser) {
    //It's example checking for self-learning
    if (foundUser.username == req.cookies.username) {
        return foundUser;
    }
    //Or more logic for token authentication
    }).catch(function (err) {
    return err;
     })
   };

In tu.js file:

   var user = require('./ty');

   user().then(function (result) {
   //search findById result
   console.log(result)

   });


问:
UWP MVVM binding to TextBox and passing back value
I am trying to get the content of a TextBox updated using Binding in a MVVM environment. When a Button receive focus, it passes a value, and that value should be reflected in the TextBox. I seem to have the first part right, however seems to be struggling at passing the value..
I know the question about MVVM has been asked before (including by myself), but I really cannot get it, for some reasons..

So I start with my model:

```<code>public class iText : INotifyPropertyChanged

{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _text;
    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Text)));
        }
    }
</code>```

I then continue with my ViewModel:

```<code>private iText _helper = new iText();
public iText Helper
{
    get { return _helper; }
    set
    {
        _helper = value;
    }
}
</code>```

The XAML page:

```<code><Page.Resources>
    <scan:ModelDataContext x:Key="ModelDataContext" x:Name="ModelDataContext"/>
</Page.Resources>

<TextBox Text="{Binding Helper.Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</code>```

I then try to update the Text from MainPage.cs

```<code>public sealed partial class MainPage : Page
{
    public MainPageViewModel iText { get; set; }

    public MainPage()
    {
        InitializeComponent();
        iText = new MainPageViewModel();
    }

    private void btn_GotFocus(object sender, RoutedEventArgs e)
    {
        var str = "test"
        iText.Helper.Text = str;
    }
</code>```

I could really appreciate if someone could tell me what I do wrong, and where. Thanks so much in advance.

答:
In your MainPage constructor, try setting the datacontext to your ViewModel.
Something like...</p>

```<code>public MainPage()
{
    InitializeComponent();
    iText = new MainPageViewModel();
    this.dataContext = iText;
}
</code>```

Body:
I am trying to get the content of a TextBox updated using Binding in a MVVM environment. When a Button receive focus, it passes a value, and that value should be reflected in the TextBox. I seem to have the first part right, however seems to be struggling at passing the value..
I know the question about MVVM has been asked before (including by myself), but I really cannot get it, for some reasons..

So I start with my model:

public class iText : INotifyPropertyChanged

{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _text;
    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Text)));
        }
    }

I then continue with my ViewModel:

private iText _helper = new iText();
public iText Helper
{
    get { return _helper; }
    set
    {
        _helper = value;
    }
}

The XAML page:

<Page.Resources>
    <scan:ModelDataContext x:Key="ModelDataContext" x:Name="ModelDataContext"/>
</Page.Resources>

<TextBox Text="{Binding Helper.Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

I then try to update the Text from MainPage.cs

public sealed partial class MainPage : Page
{
    public MainPageViewModel iText { get; set; }

    public MainPage()
    {
        InitializeComponent();
        iText = new MainPageViewModel();
    }

    private void btn_GotFocus(object sender, RoutedEventArgs e)
    {
        var str = "test"
        iText.Helper.Text = str;
    }

I could really appreciate if someone could tell me what I do wrong, and where. Thanks so much in advance.

Body:
In your MainPage constructor, try setting the datacontext to your ViewModel.
Something like...

public MainPage()
{
    InitializeComponent();
    iText = new MainPageViewModel();
    this.dataContext = iText;
}


问:
Don't display remote notification?
I'm performing some logic to determine whether to display a notification in my didReceiveRemoteNotification function. In the case where I want to show no notification how do I show no alert?

If I don't include a completion handler I get the error Application delegate received call to -application:didReceiveRemoteNotification:fetchCompletionHandler: but the completion handler was never called.

Adding completionHandler([]) or completionHandler(nil) says I need to pass in a UIBackgroundFetchResult to the completion handler. How do I not display the received remote notification?

答:
It seems that you're looking for a Silent Notification. They can be used to inform the application of new content without having the user informed. Instead of displaying a notification alert, the application will be awakened in background and application:didReceiveRemoteNotification:fetchCompletionHandler: will be called. You then have the opportunity to process any information transparently for the user :

Download some content
Synchronize some elements,
Inform the user directly within the application when he opens it back
Note that your time is limited to 30s.

To configure silent notifications

To support silent remote notifications, add the remote-notification
  value to the UIBackgroundModes array in your Info.plist file.

```<code><key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>
</code>```

Configuring a Silent Notification

The aps dictionary can also contain the content-available property.
  The content- available property with a value of 1 lets the remote
  notification act as a silent notification. When a silent notification
  arrives, iOS wakes up your app in the background so that you can get
  new data from your server or do background information processing.
  Users aren’t told about the new or changed information that results
  from a silent notification, but they can find out about it the next
  time they open your app.

For a silent notification, take care to ensure there is no alert, sound, or badge payload in the aps dictionary. If you don’t follow this guidance, the incorrectly-configured notification might be throttled and not delivered to the app in the background, and instead of being silent is displayed to the user

Title: Don't display remote notification?

Body:
It seems that you're looking for a Silent Notification. They can be used to inform the application of new content without having the user informed. Instead of displaying a notification alert, the application will be awakened in background and application:didReceiveRemoteNotification:fetchCompletionHandler: will be called. You then have the opportunity to process any information transparently for the user :

Download some content
Synchronize some elements,
Inform the user directly within the application when he opens it back
Note that your time is limited to 30s.

To configure silent notifications

To support silent remote notifications, add the remote-notification
  value to the UIBackgroundModes array in your Info.plist file.

<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

Configuring a Silent Notification

The aps dictionary can also contain the content-available property.
  The content- available property with a value of 1 lets the remote
  notification act as a silent notification. When a silent notification
  arrives, iOS wakes up your app in the background so that you can get
  new data from your server or do background information processing.
  Users aren’t told about the new or changed information that results
  from a silent notification, but they can find out about it the next
  time they open your app.

For a silent notification, take care to ensure there is no alert, sound, or badge payload in the aps dictionary. If you don’t follow this guidance, the incorrectly-configured notification might be throttled and not delivered to the app in the background, and instead of being silent is displayed to the user


问:
How to modify dependent: :destroy in rails
If I have two models, Model1 and Model2 as follows

```<code>class Model1 < ActiveRecord::Base
  has_many :model2s, dependent: :destroy
end
</code>```

and

```<code>class Model2 < ActiveRecord::Base
  belongs :model1
end
</code>```

I want to increase the destroy capability when I destroy a record in Model1. As well as the dependent records, I want to destroy Model2 records that meet an attribute test as well. How can this be done?

答:
You can use Active Record Callbacks to solve your problem. after_destroy may help you.

```<code>class Model1 < ActiveRecord::Base
  has_many :model2s, dependent: :destroy

  after_destroy :increase_the_destroy_capability

  private

  def increase_the_destroy_capability
    # do some thing
  end
end
</code>```

Body:
If I have two models, Model1 and Model2 as follows

class Model1 < ActiveRecord::Base
  has_many :model2s, dependent: :destroy
end

and

class Model2 < ActiveRecord::Base
  belongs :model1
end

I want to increase the destroy capability when I destroy a record in Model1. As well as the dependent records, I want to destroy Model2 records that meet an attribute test as well. How can this be done?

Body:
You can use Active Record Callbacks to solve your problem. after_destroy may help you.

class Model1 < ActiveRecord::Base
  has_many :model2s, dependent: :destroy

  after_destroy :increase_the_destroy_capability

  private

  def increase_the_destroy_capability
    # do some thing
  end
end


问:
Getting access to a hash - Ruby
I'm trying to get to data that I found in a binding.pry --- Here is is

```<code>[#<Stripe::Card:0x3fc1da530e18 id=card_1A4KjTLcGwfBVD0DjTHzDqsO> JSON: {
  "id": "card_1A4KjTLcGwfBVD0DjTHzDqsO",
  "object": "card",
  "address_city": null,
  "address_country": null,
  "address_line1": null,
  "address_line1_check": null,
  "address_line2": null,
  "address_state": null,
  "address_zip": "42424",
  "address_zip_check": "pass",
  "brand": "Visa",
  "country": "US",
  "customer": "cus_AP91mImLV1GIrS",
  "cvc_check": "pass",
  "dynamic_last4": null,
  "exp_month": 4,
  "exp_year": 2024,
  "fingerprint": "U2Lh3jtN9G5jgtxm",
  "funding": "credit",
  "last4": "4242",
  "metadata": {},
  "name": null,
  "tokenization_method": null
}]
</code>```

I get all that data when I type this in the console: context.customer.sources.data

I've tried getting the object like this: context.customer.sources.data[:object] but that gives me this error => TypeError: no implicit conversion of Symbol into Integer

How do I get to that data?

答: Because it's an array. so you should visit like context.customer.sources.data[0][:object] or context.customer.sources.data[0].object

Title: Getting access to a hash - Ruby

Body:
I'm trying to get to data that I found in a binding.pry --- Here is is

[#<Stripe::Card:0x3fc1da530e18 id=card_1A4KjTLcGwfBVD0DjTHzDqsO> JSON: {
  "id": "card_1A4KjTLcGwfBVD0DjTHzDqsO",
  "object": "card",
  "address_city": null,
  "address_country": null,
  "address_line1": null,
  "address_line1_check": null,
  "address_line2": null,
  "address_state": null,
  "address_zip": "42424",
  "address_zip_check": "pass",
  "brand": "Visa",
  "country": "US",
  "customer": "cus_AP91mImLV1GIrS",
  "cvc_check": "pass",
  "dynamic_last4": null,
  "exp_month": 4,
  "exp_year": 2024,
  "fingerprint": "U2Lh3jtN9G5jgtxm",
  "funding": "credit",
  "last4": "4242",
  "metadata": {},
  "name": null,
  "tokenization_method": null
}]

I get all that data when I type this in the console: context.customer.sources.data

I've tried getting the object like this: context.customer.sources.data[:object] but that gives me this error => TypeError: no implicit conversion of Symbol into Integer

How do I get to that data?


问:
Python: straight line, Slope k is known, one point P1 is known, length P1P2 is known, how to get P2?
For a straight line, Slope k is known, one point(x1,y1) is know, how to get the other point (x2,y2) using python?
I know the way to do calculation, but have no idea to code using python.

(y2-y1)/(x2-x1)=k

sqrt((x2-x1)^2+(y2-y1)^2)= length

if two unknown equations, both two variables with power 1, linalg-solve should work, but now the power of 2rd function is 2, how to deal with that?

I tried to simplify as following, but seems I cannot apply linalg-solve

kx2-y2-kx1+y1 = 0

(y2-y1)^2 + (x2-x1)^2 = length^2

Supplement：
thanks to all of your answer...Posh_Pumpkin's code is exactly what I want, previously I thought I need to apply linalg-solve which I usually use.

here is a test code based on his answer:suppose P1 = (1,1) p2=(x,y), p1p2= sqrt(2), k=1,then p2 must be = (2,2)

```<code>import numpy as np
import math
k = 1
d = math.sqrt(2)
p1 = (1,1)
r_sq = d**2 / (1 + k**2)
r = math.sqrt(r_sq)
p2 = (p1[0] + r, p1[1] + k*r)
print(p2)
</code>```

答:
Why use a complicated solution at all? I would approach it under the assumption that P1 = (0, 0).

Assuming P1 is at the origin, and knowing that the slope = k, you know that P2 = (r, k*r) for a constant r. The r can be computed by calculating the distance P1P2. Since you said you already know the distance, we can then simply do:

```<code>r^2 + (k*r)^2 = d^2
</code>```

To find r. Once you find r, you can get the coordinates of P2 when P1 = (0, 0). So to find the actual coordinates, you'd just do P2 = P1 + P2. Check below:

```<code>import math

# Obviously assume k and d are known constants, and P1 is a known point
k = # given k
d = # given d
p1 = # (given x coord, given y coord)

r_sq = d**2 / (1 + k**2)
r = math.sqrt(r_sq)
p2 = (p1[0] + r, p1[1] + k*r)
print(p2)
</code>```

If you have to use numpy, you should show us your code and what exactly is troubling you. What is preventing you from using the module, whether it's an error or an unexpected behavior?

Body:
For a straight line, Slope k is known, one point(x1,y1) is know, how to get the other point (x2,y2) using python?
I know the way to do calculation, but have no idea to code using python.

(y2-y1)/(x2-x1)=k

sqrt((x2-x1)^2+(y2-y1)^2)= length

if two unknown equations, both two variables with power 1, linalg-solve should work, but now the power of 2rd function is 2, how to deal with that?

I tried to simplify as following, but seems I cannot apply linalg-solve

kx2-y2-kx1+y1 = 0

(y2-y1)^2 + (x2-x1)^2 = length^2

Supplement：
thanks to all of your answer...Posh_Pumpkin's code is exactly what I want, previously I thought I need to apply linalg-solve which I usually use.

here is a test code based on his answer:suppose P1 = (1,1) p2=(x,y), p1p2= sqrt(2), k=1,then p2 must be = (2,2)

import numpy as np
import math
k = 1
d = math.sqrt(2)
p1 = (1,1)
r_sq = d**2 / (1 + k**2)
r = math.sqrt(r_sq)
p2 = (p1[0] + r, p1[1] + k*r)
print(p2)

Body:
Why use a complicated solution at all? I would approach it under the assumption that P1 = (0, 0).

Assuming P1 is at the origin, and knowing that the slope = k, you know that P2 = (r, k*r) for a constant r. The r can be computed by calculating the distance P1P2. Since you said you already know the distance, we can then simply do:

r^2 + (k*r)^2 = d^2

To find r. Once you find r, you can get the coordinates of P2 when P1 = (0, 0). So to find the actual coordinates, you'd just do P2 = P1 + P2. Check below:

import math

# Obviously assume k and d are known constants, and P1 is a known point
k = # given k
d = # given d
p1 = # (given x coord, given y coord)

r_sq = d**2 / (1 + k**2)
r = math.sqrt(r_sq)
p2 = (p1[0] + r, p1[1] + k*r)
print(p2)

If you have to use numpy, you should show us your code and what exactly is troubling you. What is preventing you from using the module, whether it's an error or an unexpected behavior?


问:
Elm Json Decoder Pipeline error
I'm trying to decode some json coming in from an http request but I keep running into syntax issues. This is the error I get from the compiler:

```<code>-- TYPE MISMATCH ------------------------------------------------------ [7/1811$

The 2nd argument to function `send` is causing a mismatch.

65|     Http.send CardFetch (Http.get url modelDecoder)
                             ^^^^^^^^^^^^^^^^^^^^^^^^^
Function `send` is expecting the 2nd argument to be:

    Http.Request String

But it is:

    Http.Request Model
</code>```

Here is my code:

```<code>module Main exposing (..)

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode as Decode exposing (string, Decoder, at, index)
import Json.Decode.Pipeline exposing (..)

main : Program Never Model Msg
main =
    program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }

type alias Model =
    { boardName : String
    , cardName : String
    }

init =
    ( Model "Default Board" "Default Card"
    , Cmd.none
    )

-- UPDATE

type Msg
    = CardFetch (Result Http.Error String)
    | DataFetch

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        DataFetch ->
            ( model, getData )

        CardFetch (Ok incomingName) ->
            ( Model model.cardName incomingName, Cmd.none )

        CardFetch (Err errorMessage) ->
            ( model, Debug.log "Errors" Cmd.none )

-- HTTP

url : String
url =
    "https://api.trello.com/1/members/user/actions?limit=3&key=..."

getData =
    Http.send CardFetch (Http.get url modelDecoder)

{--decodeCard =
    Decode.index 0
        modelDecoder
        (Decode.at
            [ "data", "card", "name" ]
            string
        )
        --}

modelDecoder : Decoder Model
modelDecoder =
    decode Model
        |> custom (index 0 (at [ "data", "card", "name" ] string))
        |> custom (index 0 (at [ "data", "board", "name" ] string))

--UPDATE
-- VIEW

view : Model -> Html Msg
view model =
    div []
        [ div []
            [ button [ onClick DataFetch ] [ text "Get Card" ] ]
        , div [ class "card" ]
            [ h3 [] [ text model.boardName ]
            , div [ class "board" ] [ h4 [] [ text model.cardName ] ]
            ]
        ]

-- SUBSCRIPTIONS

subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.none
</code>```

I'm am fairly new to Elm and I'm trying to figure out how API calls work. Elm documentation is excellent but the bit about API calls is kind of vague. I would appreciate any help I can get. Thanks a lot!

答:
You declared in your messages:

```<code>CardFetch (Result Http.Error String)
</code>```

which means that successful response will produce String. However, your modelDecoder is returning Model: modelDecoder : Decoder Model.

Changing your message declaration to:

```<code>CardFetch (Result Http.Error Model)
</code>```

and in update function:

```<code>CardFetch (Ok incomingName) ->
    ( incomingName, Cmd.none )
</code>```

should help.

Title: Elm Json Decoder Pipeline error

Body:
I'm trying to decode some json coming in from an http request but I keep running into syntax issues. This is the error I get from the compiler:

-- TYPE MISMATCH ------------------------------------------------------ [7/1811$

The 2nd argument to function `send` is causing a mismatch.

65|     Http.send CardFetch (Http.get url modelDecoder)
                             ^^^^^^^^^^^^^^^^^^^^^^^^^
Function `send` is expecting the 2nd argument to be:

    Http.Request String

But it is:

    Http.Request Model

Here is my code:

module Main exposing (..)

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode as Decode exposing (string, Decoder, at, index)
import Json.Decode.Pipeline exposing (..)

main : Program Never Model Msg
main =
    program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }

type alias Model =
    { boardName : String
    , cardName : String
    }

init =
    ( Model "Default Board" "Default Card"
    , Cmd.none
    )

-- UPDATE

type Msg
    = CardFetch (Result Http.Error String)
    | DataFetch

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        DataFetch ->
            ( model, getData )

        CardFetch (Ok incomingName) ->
            ( Model model.cardName incomingName, Cmd.none )

        CardFetch (Err errorMessage) ->
            ( model, Debug.log "Errors" Cmd.none )

-- HTTP

url : String
url =
    "https://api.trello.com/1/members/user/actions?limit=3&key=..."

getData =
    Http.send CardFetch (Http.get url modelDecoder)

{--decodeCard =
    Decode.index 0
        modelDecoder
        (Decode.at
            [ "data", "card", "name" ]
            string
        )
        --}

modelDecoder : Decoder Model
modelDecoder =
    decode Model
        |> custom (index 0 (at [ "data", "card", "name" ] string))
        |> custom (index 0 (at [ "data", "board", "name" ] string))

--UPDATE
-- VIEW

view : Model -> Html Msg
view model =
    div []
        [ div []
            [ button [ onClick DataFetch ] [ text "Get Card" ] ]
        , div [ class "card" ]
            [ h3 [] [ text model.boardName ]
            , div [ class "board" ] [ h4 [] [ text model.cardName ] ]
            ]
        ]

-- SUBSCRIPTIONS

subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.none

I'm am fairly new to Elm and I'm trying to figure out how API calls work. Elm documentation is excellent but the bit about API calls is kind of vague. I would appreciate any help I can get. Thanks a lot!

Body:
You declared in your messages:

CardFetch (Result Http.Error String)

which means that successful response will produce String. However, your modelDecoder is returning Model: modelDecoder : Decoder Model.

Changing your message declaration to:

CardFetch (Result Http.Error Model)

and in update function:

CardFetch (Ok incomingName) ->
    ( incomingName, Cmd.none )

should help.


问:
using only one button to play and pause a Mediaplayer in Android
I am new to Android, my requirement is to use only one button for playing and pause using media player class?</p>

答:
I would use 2 buttons and hide one of them:</p>

```<code>public class MyActivity extends Activity implements View.OnClickListener {
    Button playBtn;
    Button pauseBtn;

    public void onCreate() {
        playBtn = (Button) findViewById(R.id.playButton);
        pauseBtn = (Button) findViewById(R.id.pauseButton);
        playBtn.setOnClickListener(this);
        pauseBtn.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.playButton:
            // play music here
            playBtn.setVisibility(Button.GONE);
            pauseBtn.setVisibility(Button.VISIBLE);
            break;
        case R.id.pauseButton:
            // pause music here
            pauseBtn.setVisibility(Button.GONE);
            playBtn.setVisibility(Button.VISIBLE);
            break;
        }
    }
}
</code>```

Body:
I would use 2 buttons and hide one of them:

public class MyActivity extends Activity implements View.OnClickListener {
    Button playBtn;
    Button pauseBtn;

    public void onCreate() {
        playBtn = (Button) findViewById(R.id.playButton);
        pauseBtn = (Button) findViewById(R.id.pauseButton);
        playBtn.setOnClickListener(this);
        pauseBtn.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.playButton:
            // play music here
            playBtn.setVisibility(Button.GONE);
            pauseBtn.setVisibility(Button.VISIBLE);
            break;
        case R.id.pauseButton:
            // pause music here
            pauseBtn.setVisibility(Button.GONE);
            playBtn.setVisibility(Button.VISIBLE);
            break;
        }
    }
}


问:
Using NDK and opengl
I want to use NDK to implement Opengl in c++ but I have no idea how to use the ndk or set it up. Can someone give me a easy step by step instruction?</p>

答:
https://developer.android.com/studio/projects/add-native-code.html?hl=en

you should know a concept and basic steps about it.

Title: Using NDK and opengl


问:
Force update to matplotlib toolbar/status bar information
I've got a matplotlib plot in which I've modified the toolbar/status bar information much as in this question. This works just fine and the necessary information is displayed as I need it.

However, I often need to update the plot (which is done by calling draw() on the canvas object) with new data. What happens though is that the toolbar/status bar information won't update until the mouse is moved again. I'd like this information to update as soon as the canvas is redrawn because some of this information is pertinent to the new plot.

My attempt at making this happen was to force a mouse motion event to trigger. I've tried to trigger the event from the canvas via self.canvas.motion_notify_event(0,0) but that doesn't seem to work well. I can see that the toolbar itself has a mouse_move method, but I don't know how to trigger it (or even if it's what I want to trigger).

How can I force the toolbar/status bar information to update during a plot redraw without requiring the user to move their mouse slightly?

答:
Did a lot of digging and figured it out. The motion_notify_event method was what I was looking for, I was just using it wrong. You can fake matplotlib out and trigger a MouseEvent by using this function, which will then make matplotlib call all functions that respond to MouseEvents, including updating the toolbar/status bar information.

The key here is that I needed to trigger the MouseEvent as if it happened within the axes object, not the entire figure. The input to the function is the (x,y) pixel position of the event with respect to the lower left corner of the figure window. By using (0,0) as I did in my question, I was saying the mouse event happened at the lower left corner of the figure window, not on the axes itself. Matplotlib does not show toolbar/status bar information unless the cursor is on the axes.

What you can do then is pick some random pixel position on the axes and use that as the position. A simple way to pick such a pixel position is using matplotlib transformations.

The following now works for me:

```<code>canvas.motion_notify_event(*ax.transAxes.transform([0,0]))
</code>```

Of course in my case I'm not displaying the data coordinates of the mouse, so your use cases may vary.

Body:
Did a lot of digging and figured it out. The motion_notify_event method was what I was looking for, I was just using it wrong. You can fake matplotlib out and trigger a MouseEvent by using this function, which will then make matplotlib call all functions that respond to MouseEvents, including updating the toolbar/status bar information.

The key here is that I needed to trigger the MouseEvent as if it happened within the axes object, not the entire figure. The input to the function is the (x,y) pixel position of the event with respect to the lower left corner of the figure window. By using (0,0) as I did in my question, I was saying the mouse event happened at the lower left corner of the figure window, not on the axes itself. Matplotlib does not show toolbar/status bar information unless the cursor is on the axes.

What you can do then is pick some random pixel position on the axes and use that as the position. A simple way to pick such a pixel position is using matplotlib transformations.

The following now works for me:

canvas.motion_notify_event(*ax.transAxes.transform([0,0]))

Of course in my case I'm not displaying the data coordinates of the mouse, so your use cases may vary.


问:
Best options for translating a rails app
Since there are so many options there available for internationalization of a rails app, which gems or plugins are the best (today) for adding i18n support to a rails app.

Im using I18n bundled with rails for the application messages, button labels, and model attribue names.

But I also need to let the users to input content and the translated version of the content, but there are so many options for this right now that I don't really know which one to use.

答:
I like this one:
https://www.github.com/mynewsdesk/translate

because it has a nice webGUI for translating new/changed strings


问:
Azure Mobile Service getting error - Sequence contains no matching element
I have simple Azure Mobile Service which is connected to MySql Database

Web.Config

```<code>  <connectionStrings>
    <add name="MS_TableConnectionString" connectionString="Server=11.11.111.111;User Id=test;Password=test;Database=testDB" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
</code>```

App_Start\WebApiConfig.cs

```<code> public static class WebApiConfig
    {
        public static void Register()
        {
            ConfigOptions options = new ConfigOptions();

            HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));

             config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

        }
    }
</code>```

Controllers\CommentController.cs

```<code> public class CommentController : TableController<wp_comments>
    {
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();
            DomainManager = new EntityDomainManager<wp_comments>(context, Request, Services);
        }

        // GET tables/Comment
        public IQueryable<wp_comments> GetAllComment()
        {
            return Query(); // Getting Exception Here
        }
</code>```

DataObjects\wp_comments.cs

```<code>public class wp_comments : EntityData
    {
        public int comment_ID { get; set; }
        public int comment_post_ID { get; set; }

        [Column("comment_author", TypeName = "NVARCHAR(MAX)")]
        public string comment_author { get; set; }

        [Column("comment_author_email", TypeName = "NVARCHAR(MAX)")]
        public string comment_author_email { get; set; }

        [Column("comment_author_url", TypeName = "NVARCHAR(MAX)")]
        public string comment_author_url { get; set; }

        [Column("comment_author_IP", TypeName = "NVARCHAR(MAX)")]
        public string comment_author_IP { get; set; }
        public DateTime comment_date { get; set; }
        public DateTime comment_date_gmt { get; set; }

        [Column("comment_author_IP", TypeName = "NVARCHAR(MAX)")]
        public string comment_content { get; set; }
        public int comment_karma { get; set; }

        [Column("comment_approved", TypeName = "NVARCHAR(MAX)")]
        public string comment_approved { get; set; }

        [Column("comment_agent", TypeName = "NVARCHAR(MAX)")]
        public string comment_agent { get; set; }

        [Column("comment_type", TypeName = "NVARCHAR(MAX)")]
        public string comment_type { get; set; }
        public int comment_parent { get; set; }
        public int user_id { get; set; }
    }
</code>```

Models\MobileServiceContext.cs

```<code>public class MobileServiceContext : DbContext
    {

        private const string connectionStringName = "Name=MS_TableConnectionString";

        public MobileServiceContext() : base(connectionStringName)
        {
        }

        public DbSet<wp_comments> Comments { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            string schema = ServiceSettingsDictionary.GetSchemaName();
            if (!string.IsNullOrEmpty(schema))
            {
                modelBuilder.HasDefaultSchema(schema);
            }

            //modelBuilder.Conventions.Add(
            //    new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
            //        "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
        }
    }
</code>```

答:
Please check with your model, you have defined the same property "comment_author_IP". Please modify it then to see whether your code works.</p>

```<code>    [Column("comment_author_IP", TypeName = "NVARCHAR(MAX)")]
    public string comment_author_IP { get; set; }
    public DateTime comment_date { get; set; }
    public DateTime comment_date_gmt { get; set; }

    [Column("comment_author_IP", TypeName = "NVARCHAR(MAX)")]
    public string comment_content { get; set; }
</code>```

Body:
I have simple Azure Mobile Service which is connected to MySql Database

Web.Config

  <connectionStrings>
    <add name="MS_TableConnectionString" connectionString="Server=11.11.111.111;User Id=test;Password=test;Database=testDB" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>

App_Start\WebApiConfig.cs

 public static class WebApiConfig
    {
        public static void Register()
        {
            ConfigOptions options = new ConfigOptions();

            HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));

             config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

        }
    }

Controllers\CommentController.cs

 public class CommentController : TableController<wp_comments>
    {
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            MobileServiceContext context = new MobileServiceContext();
            DomainManager = new EntityDomainManager<wp_comments>(context, Request, Services);
        }

        // GET tables/Comment
        public IQueryable<wp_comments> GetAllComment()
        {
            return Query(); // Getting Exception Here
        }

DataObjects\wp_comments.cs

public class wp_comments : EntityData
    {
        public int comment_ID { get; set; }
        public int comment_post_ID { get; set; }

        [Column("comment_author", TypeName = "NVARCHAR(MAX)")]
        public string comment_author { get; set; }

        [Column("comment_author_email", TypeName = "NVARCHAR(MAX)")]
        public string comment_author_email { get; set; }

        [Column("comment_author_url", TypeName = "NVARCHAR(MAX)")]
        public string comment_author_url { get; set; }

        [Column("comment_author_IP", TypeName = "NVARCHAR(MAX)")]
        public string comment_author_IP { get; set; }
        public DateTime comment_date { get; set; }
        public DateTime comment_date_gmt { get; set; }

        [Column("comment_author_IP", TypeName = "NVARCHAR(MAX)")]
        public string comment_content { get; set; }
        public int comment_karma { get; set; }

        [Column("comment_approved", TypeName = "NVARCHAR(MAX)")]
        public string comment_approved { get; set; }

        [Column("comment_agent", TypeName = "NVARCHAR(MAX)")]
        public string comment_agent { get; set; }

        [Column("comment_type", TypeName = "NVARCHAR(MAX)")]
        public string comment_type { get; set; }
        public int comment_parent { get; set; }
        public int user_id { get; set; }
    }

Models\MobileServiceContext.cs

public class MobileServiceContext : DbContext
    {

        private const string connectionStringName = "Name=MS_TableConnectionString";

        public MobileServiceContext() : base(connectionStringName)
        {
        }

        public DbSet<wp_comments> Comments { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            string schema = ServiceSettingsDictionary.GetSchemaName();
            if (!string.IsNullOrEmpty(schema))
            {
                modelBuilder.HasDefaultSchema(schema);
            }

            //modelBuilder.Conventions.Add(
            //    new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
            //        "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
        }
    }

Body:
Please check with your model, you have defined the same property "comment_author_IP". Please modify it then to see whether your code works.

    [Column("comment_author_IP", TypeName = "NVARCHAR(MAX)")]
    public string comment_author_IP { get; set; }
    public DateTime comment_date { get; set; }
    public DateTime comment_date_gmt { get; set; }

    [Column("comment_author_IP", TypeName = "NVARCHAR(MAX)")]
    public string comment_content { get; set; }


问:
Schema formatting in Apache Pig
I am new at this language, and I am trying to create a schema for data that was in a excel spreadsheet and downloaded to a Text file.

(Text file is attached)

Please note I have no java knowledge so this is all Pig.
Can someone assist helping me format this properly to  match the  schema and remove the
 commas in the numeric values ?

My attempted code:

```<code>sales2000 = LOAD '2000rssales1.txt'  USING PigStorage()
AS (field1:chararray,field2:chararray,field3:int,field4:int,field5:int,
field6:chararray,field7:chararray,field8:chararray,field9:chararray,field10:chararray,
field12:chararray,field13:chararray,field14:chararray,field15:int)
</code>```

```<code> `The field I would like to do calculations on is field15  [![text.sales.data][1]][1]`
</code>```

答:
Load it into one field say line:charrarray and replace the ',' and """.Then you can split the fields using ' ' and use the 15th field for your calculations.

```<code>A = LOAD '2000rssales1.txt' AS (line:chararray);
B = FOREACH A GENERATE REPLACE(REPLACE(line,"\"",''),',','');
C = FOREACH B GENERATE STRSPLIT($0,' ',15); -- If your columns are tab separated use '\\t' instead of ' ' in strsplit.
</code>```

Alternatively you can use CSVExcelStorage() as well to load the records.Download piggybank.jar and register it using the path where you download it.

```<code>REGISTER /downloaded_path/piggybank.jar;
A = LOAD '2000rssales1.txt' USING org.apache.pig.piggybank.storage.CSVExcelStorage('\t')
B = FOREACH A GENERATE $0..$13,REPLACE($14,',',''); -- Replace the ',' with space for the 15th field;
DUMP B;
</code>```

Title: Schema formatting in Apache Pig

Body:
I am new at this language, and I am trying to create a schema for data that was in a excel spreadsheet and downloaded to a Text file.

(Text file is attached)

Please note I have no java knowledge so this is all Pig.
Can someone assist helping me format this properly to  match the  schema and remove the
 commas in the numeric values ?

My attempted code:

sales2000 = LOAD '2000rssales1.txt'  USING PigStorage()
AS (field1:chararray,field2:chararray,field3:int,field4:int,field5:int,
field6:chararray,field7:chararray,field8:chararray,field9:chararray,field10:chararray,
field12:chararray,field13:chararray,field14:chararray,field15:int)

 `The field I would like to do calculations on is field15  [![text.sales.data][1]][1]`

Body:
Load it into one field say line:charrarray and replace the ',' and """.Then you can split the fields using ' ' and use the 15th field for your calculations.

A = LOAD '2000rssales1.txt' AS (line:chararray);
B = FOREACH A GENERATE REPLACE(REPLACE(line,"\"",''),',','');
C = FOREACH B GENERATE STRSPLIT($0,' ',15); -- If your columns are tab separated use '\\t' instead of ' ' in strsplit.

Alternatively you can use CSVExcelStorage() as well to load the records.Download piggybank.jar and register it using the path where you download it.

REGISTER /downloaded_path/piggybank.jar;
A = LOAD '2000rssales1.txt' USING org.apache.pig.piggybank.storage.CSVExcelStorage('\t')
B = FOREACH A GENERATE $0..$13,REPLACE($14,',',''); -- Replace the ',' with space for the 15th field;
DUMP B;


问:
Why isn't the option list showing in HTML using JQuery?
The select tag which is a child of the input text element simply does not display options that are added to the select element.

The HTML output and corresponding DOM are shown below:

答: input type="text" cannot have children. You will have to place your select element outside.


问:
"If strMyString.Contains, Then strMyString.Contains, Else Boolean" Procedure
I need help with a-
"If strMyString.Contains, Then strMyString.Contains, Else Boolean" Procedure

I am trying to find the name "lordgun" within a very big data Log.  For all the times it's listed, I want to list it to the right of my data.

Here is the my whole attempt thus far-

```<code>Option Explicit

Public Function linecontains()lordgun As Boolean

Dim strMyString As String
Dim TargetString1 As String
Dim TargetString2 As String

'Returns True if cell contains substring, False otherwise
If strMyString.Contains("lordgun.org")

Else strMyString.Contains("") Then

End If

End Function
</code>```

答:
One way is to use the instr function.

This function returns an int. If it returns a value > 0 then the string was found.
e.g:

```<code>If Instr(1, MyString, SearchFor, 0) >0  Then

Else

End if
</code>```

Body:
I need help with a-
"If strMyString.Contains, Then strMyString.Contains, Else Boolean" Procedure

I am trying to find the name "lordgun" within a very big data Log.  For all the times it's listed, I want to list it to the right of my data.

Here is the my whole attempt thus far-

Option Explicit

Public Function linecontains()lordgun As Boolean

Dim strMyString As String
Dim TargetString1 As String
Dim TargetString2 As String

'Returns True if cell contains substring, False otherwise
If strMyString.Contains("lordgun.org")

Else strMyString.Contains("") Then

End If

End Function

Body:
One way is to use the instr function.

This function returns an int. If it returns a value > 0 then the string was found.
e.g:

If Instr(1, MyString, SearchFor, 0) >0  Then

Else

End if


问:
convert an encoded string to jpg and display it
I need to convert a base64 encoded string from a server (being sent via amf) to an image. on the server the raw image data (gif / jpeg / png) is being encoded to base64 (which already works fine), and I need to decode this string and display the image in my flash movie. How can this be done?</p>

答:
After you've converted your string to a ByteArray, you can create a Loader object and use LoadBytes to turn your binary object into a display object. Then add the loader to stage.</p>

```<code>var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.loadBytes(yourBytesHere)

function completeHandler(e:Event):void {
addChild(loader);
}
</code>```

Body:
After you've converted your string to a ByteArray, you can create a Loader object and use LoadBytes to turn your binary object into a display object. Then add the loader to stage.

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.loadBytes(yourBytesHere)

function completeHandler(e:Event):void {
addChild(loader);
}


问:
Is there any way to reuse Visual Studio 2015 SDKs while installing Visual Studio 2017?
I've been recently upgrading to VS2017 and was wondering if there was any way I can use the SDKs I've already had downloaded for VS2015 ?

UPDATE: I think it should be possible for standalone SKDs like UWP, Xamarin.... !

答: SDKs are bind to VS versions strictly. Don't attempt to do so and make sure you have enough disk space to install Visual Studio 2017.</p>


问:
C++ - Proper method to use delete while creating a vector of class objects
I saw a few examples of creating a vector of class objects and many of them uses a pointer and new keyword. However, in many cases the delete is not used to free up memory allocated by new. I would like to know if the following piece of code uses delete properly.

I have a class Marker:

```<code>class Marker{

    public:
        Marker(int, float, float);
        int marker_id();

    private:
        int id;
        float mx;
        float my;
};
</code>```

It's constructor is:

```<code>Marker::Marker(int idno, float x, float y){

    //ctor
    id = idno;
    mx = x;
    my = y;
}
</code>```

I need a vector marker_vec with objects or instances of Marker class. Hence, I wrote the following piece of code:

```<code>vector <Marker> marker_vec;

Marker *m = new Marker(last_id, m_x, m_y);
marker_vec.push_back(*m);
delete m;
</code>```

If I use the above code in a loop to create marker_vec[0] and marker_vec[1], I believe that the delete wouldn't delete them and will only free up the pointer m. Is there any disadvantages for the above method?

答:
This piece of code is alright, since when you push_back, the contents referenced by the m pointer will be copied and added as the last element of the vector. You're doing good by deallocating the memory you set properly (for every new there is a corresponding delete).

```<code>vector <Marker> marker_vec;

Marker *m = new Marker(last_id, m_x, m_y);
marker_vec.push_back(*m);
delete m;
</code>```

I just think it's unnecessary for you to use pointers in this case having one type of Marker class and your std::vector of type <Marker>.

I would personally improve the implementation of this code to being statically instantiated. It's simple and cleaner in this case:

```<code>vector <Marker> marker_vec;

Marker m(last_id, m_x, m_y);
marker_vec.push_back*m);
</code>```

However, if you maybe had inheritance like different type of markers:

```<code>class HighlighterMarker : public Marker { };
</code>```

and

```<code>class PenMarker: public Marker { };
</code>```

Only then, it'd make sense for you to use dynamic memory and your vector to be declared as:

std::vector <Marker*> marker_vec. This one can store all your references to any type of derived class Marker,

Body:
I saw a few examples of creating a vector of class objects and many of them uses a pointer and new keyword. However, in many cases the delete is not used to free up memory allocated by new. I would like to know if the following piece of code uses delete properly.

I have a class Marker:

class Marker{

    public:
        Marker(int, float, float);
        int marker_id();

    private:
        int id;
        float mx;
        float my;
};

It's constructor is:

Marker::Marker(int idno, float x, float y){

    //ctor
    id = idno;
    mx = x;
    my = y;
}

I need a vector marker_vec with objects or instances of Marker class. Hence, I wrote the following piece of code:

vector <Marker> marker_vec;

Marker *m = new Marker(last_id, m_x, m_y);
marker_vec.push_back(*m);
delete m;

If I use the above code in a loop to create marker_vec[0] and marker_vec[1], I believe that the delete wouldn't delete them and will only free up the pointer m. Is there any disadvantages for the above method?

Body:
This piece of code is alright, since when you push_back, the contents referenced by the m pointer will be copied and added as the last element of the vector. You're doing good by deallocating the memory you set properly (for every new there is a corresponding delete).

vector <Marker> marker_vec;

Marker *m = new Marker(last_id, m_x, m_y);
marker_vec.push_back(*m);
delete m;

I just think it's unnecessary for you to use pointers in this case having one type of Marker class and your std::vector of type <Marker>.

I would personally improve the implementation of this code to being statically instantiated. It's simple and cleaner in this case:

vector <Marker> marker_vec;

Marker m(last_id, m_x, m_y);
marker_vec.push_back*m);

However, if you maybe had inheritance like different type of markers:

class HighlighterMarker : public Marker { };

and

class PenMarker: public Marker { };

Only then, it'd make sense for you to use dynamic memory and your vector to be declared as:

std::vector <Marker*> marker_vec. This one can store all your references to any type of derived class Marker,


问:
Overriding default umask for docker daemon
I'm trying to mount a folder on host machine inside a container. In cases when the host folder does not exist, Docker daemon automatically creates the folder on host machine and assigns permissions based on default umask(which is that of root). As a result of this, it is not possible to write to the folder from within the container due to permission issues(script inside container runs as an unprivileged user). I tried overriding the permissions assigned by setting the umask in the startup script for Docker but I believe those are being ignored. Is there any way I can override the umask Docker uses to achieve this?</p>

答:
I created a script to help with this problem. Here it is:

https://github.com/coppit/docker-inotify-command/blob/master/runas.sh

You call it like:

runas.sh 99 100 0000 /mycommand.sh

99 would be the user ID number, and 100 the group ID number in the host that you want to emulate. 0000 is the umask.


问:
Account confirmation email sent as SPAM
I am using PHPMailer to send a confirmation email for newly registered users in my social network. But I found out most of them have ended up in user's spam list. (Hotmail and Yahoo). How to avoid this?

This is my script

```<code>$mail=new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = mSMTPAuth();
$mail->SMTPSecure = mSMTPSecure();
$mail->Host = mHost();
$mail->Port = mPort();
$mail->Username = mUsername();
$mail->Password = mPassword();
$mail->From = mFrom();
$mail->FromName = "SiteName";
$mail->Subject = "SiteName New Account Activation";
$mail->IsHTML(true);
$mail->WordWrap = 50;

$mail->Body = "<h2>Welcome to " .$sitename. " " .$username. "! </h2><br><br>";
$mail->Body .= "Please click on the link below to verify your email address:<br><br>";
$mail->Body .= "<a href='".$base. "verify.php?a=" .$gen_key."'>".$base. "verify.php?a=" .$gen_key."</a>";
$mail->Body .= "<br><br>Regards<br>";

$mail->AltBody = "Welcome to " .$sitename. " " .$username. "!\n\nTo verify your email address, please click on the link below:\n\n".$base. "verify.php?a=" .$gen_key;

$mail->AddAddress($email);
$mail->Send();
$mail->ClearAddresses();
</code>```

答:
I discovered that any variation of the word "confirm" in the title ends up in my spam bucket. I found other words that also do this: "purchase", "hurry", "order", "bargain", and "imminent".

This may not be true in all emails, but it happens in mine. It may be because those words appear in most of the emails I mark as span. It also may be that a local sysop made a filter and distributed it to all of us.

Title: Account confirmation email sent as SPAM

Body:
I am using PHPMailer to send a confirmation email for newly registered users in my social network. But I found out most of them have ended up in user's spam list. (Hotmail and Yahoo). How to avoid this?

This is my script

$mail=new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = mSMTPAuth();
$mail->SMTPSecure = mSMTPSecure();
$mail->Host = mHost();
$mail->Port = mPort();
$mail->Username = mUsername();
$mail->Password = mPassword();
$mail->From = mFrom();
$mail->FromName = "SiteName";
$mail->Subject = "SiteName New Account Activation";
$mail->IsHTML(true);
$mail->WordWrap = 50;

$mail->Body = "
Welcome to " .$sitename. " " .$username. "!

";
$mail->Body .= "Please click on the link below to verify your email address:

";
$mail->Body .= "".$base. "verify.php?a=" .$gen_key."";
$mail->Body .= "

Regards
";

$mail->AltBody = "Welcome to " .$sitename. " " .$username. "!\n\nTo verify your email address, please click on the link below:\n\n".$base. "verify.php?a=" .$gen_key;

$mail->AddAddress($email);
$mail->Send();
$mail->ClearAddresses();


问:
PHP explode specific text beetwen different elements
I have result

```<code>{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}
</code>```

I need to explode it on two arrays:

```<code>$id = 6583879;
</code>```

and

```<code>$listid = 11745/3470/OMS
</code>```

I'd like to avoid counting characters, this response may be another in future. I was thinking about taking:

everything between "id": and comma

everything between "listingId":" and "

答:
PHP code demo

```<code><?php
$json='{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}';
$array=  json_decode($json,true);
extract($array["data"]);
$first=array("id"=>$id);
$second=array("listingId"=>$listingId);
print_r($first);
print_r($second);
</code>```

Output:

```<code>Array
(
    [id] => 6583879
)
Array
(
    [listingId] => 11745/3470/OMS
)
</code>```

Body:
I have result

{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}

I need to explode it on two arrays:

$id = 6583879;

and

$listid = 11745/3470/OMS

I'd like to avoid counting characters, this response may be another in future. I was thinking about taking:

everything between "id": and comma

everything between "listingId":" and "

Body:
PHP code demo

<?php
$json='{"success":true,"data":{"id":6583879,"listingId":"11745/3470/OMS"}}';
$array=  json_decode($json,true);
extract($array["data"]);
$first=array("id"=>$id);
$second=array("listingId"=>$listingId);
print_r($first);
print_r($second);

Output:

Array
(
    [id] => 6583879
)
Array
(
    [listingId] => 11745/3470/OMS
)


问:
AngularJS ng-repeat directives is not working on my EventController.js
I was trying to add session details under address and date. But ng-repeat is working but its not displaying any details under sessions section. Its not giving me any error. Can anyone please check my codes and let me know what`s missing.

.....app.js.....

'use strict';

var eventsApp = angular.module('eventsApp', []);

'use strict';

eventsApp.controller('EventController',

    function EventController($scope){
   $scope.event = {
       name: 'Angular Event App',
       date: '04/02/2017',
       time: '3.09 am',
       location: {
           address: 'Google Headquaters',
           city: 'Mountain View',
           Province: 'CA'
       },
       imageUrl: '/img/angularjs-logo.png',
       sessions: [
           {
               name: 'Directive Masterclass'
           },
           {
               name: 'Scope for fun and profit'
           },
           {
               name: 'well Behaved Controllers'
           }
       ]
   };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html lang="en" ng-app="eventsApp">

    <head>
        <meta charset="utf-8">
        <title>Event Registration</title>
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/app.css">
        <script src="lib/jquery.min.js"></script>
        <script src="lib/underscore-1.4.4.min.js"></script>
        <script src="lib/bootstrap.min.js"></script>
        <script src="lib/angular/angular.js"></script>
        <script src="js/app.js"></script>
        <script src="js/controllers/EventController.js"></script>

    </head>

    <body>
        <div class="container">
            <div class="navbar-inner">
                <ul class="nav">

                </ul>

            </div>
            <div ng-controller="EventController" style="padding-left:20px; padding-right:20px">
                <img ng-src="{{event.imageUrl}}" alt="{{event.name}}" />
                <div class="row">
                    <div class="span1">
                        <h2> {{event.name}}</h2>
                    </div>

                </div>
                <div class="row">
                    <div class="span2">
                        <div><strong>Date: </strong> {{event.date}}</div>
                        <div><strong>Time: </strong> {{event.time}}</div>
                    </div>
                    <div class="span3">
                        <address>
                    <strong> Address: </strong><br>
                        {{event.location.address}}<br>
                        {{event.location.city}}, {{event.location.province}}
                    </address>
                    </div>
                </div>

                <h3>Sessions</h3>
                <ul class="thumbnails">
                    <li ng-repeat="session in event.sessions" ></li>
                    <div class="row session">
                    <div class="well span9">
                        <h4 class="well-title">{{session.name}}</h4>
                        </div>
                    </div>

                </ul>
            </div>

        </div>

    </body>

    </html></code>```

答:
you need to add the div content inside the li tag

change this

```<code><li ng-repeat="session in event.sessions" ></li>
        <div class="row session">
         <div class="well span9">
            <h4 class="well-title">{{session.name}}</h4>
        </div>
 </div>
</code>```

to this

```<code><li ng-repeat="session in event.sessions">
      <div class="row session">
            <div class="well span9">
         <h4 class="well-title">{{session.name}}</h4>
      </div>
   </div>
</li>
</code>```

Demo

Body:
I was trying to add session details under address and date. But ng-repeat is working but its not displaying any details under sessions section. Its not giving me any error. Can anyone please check my codes and let me know what`s missing.

.....app.js.....

'use strict';

var eventsApp = angular.module('eventsApp', []);

'use strict';

eventsApp.controller('EventController',

    function EventController($scope){
   $scope.event = {
       name: 'Angular Event App',
       date: '04/02/2017',
       time: '3.09 am',
       location: {
           address: 'Google Headquaters',
           city: 'Mountain View',
           Province: 'CA'
       },
       imageUrl: '/img/angularjs-logo.png',
       sessions: [
           {
               name: 'Directive Masterclass'
           },
           {
               name: 'Scope for fun and profit'
           },
           {
               name: 'well Behaved Controllers'
           }
       ]
   };
});

    <!DOCTYPE html>

        <meta charset="utf-8">
        <title>Event Registration</title>
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/app.css">

 {{event.name}}

Date:  {{event.date}}

Time:  {{event.time}}

                        <address>
                     Address:

                        {{event.location.address}}

                        {{event.location.city}}, {{event.location.province}}
                    </address>

Sessions

{{session.name}}

Body:
you need to add the div content inside the li tag

change this

<li ng-repeat="session in event.sessions" ></li>
        <div class="row session">
         <div class="well span9">
            <h4 class="well-title">{{session.name}}</h4>
        </div>
 </div>

to this

<li ng-repeat="session in event.sessions">
      <div class="row session">
            <div class="well span9">
         <h4 class="well-title">{{session.name}}</h4>
      </div>
   </div>
</li>

Demo


问:
Convert vb.net static method call on object
I am having more problems with my converting of vb.net to c#.net.

I have some files in vb.net that have "Option Strict Off" to allow for bad programming.  When I convert to c# I use "dynamic" until I come back and fix problems, and this works in all cases

But now I have this code:

```<code>Public Class ContractResults
   'Big class definition
   Public Shared Sub CleanCache()
       'Code here
   End Sub
End Class
</code>```

And in a file with Option Strict Off:

```<code>Public Sub VerifyResults(result as Object)
   'Here, result is normally ContractResults
   'first it check for that then call this:
   result.CleanCache()
End Sub
</code>```

In c# I use "dynamic", but a runtime error pops up when I call "static" method with dynamic reference.  In vb.net, I can called "shared" sub from instance, but in c# this is not allowed

Exception:
   "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"
   "Member 'ContractTypes.ContractResults.CleanCache()' cannot be accessed with an instance reference; qualify it with a type name instead"

It seems I must convert code to use actual type, but then this means much rewriting of more parts.  Is anyone able to show another way?

I want to make sure you do not think I can use

```<code>(result as ContractResults).CleanCache();
</code>```

Because all types that may be passed in have "CleanCache()" method, but do not inherits from anything the same other than "Object".  There are many types (30!) that have this "static" method and so that is why it uses Option Strict Off

答:
As the error suggests, you have to call a static method from the class, not an instance:

```<code>ContractResults.CleanCache();
</code>```

You could put your 30 types into a switch statement, but this would be ugly.

Body:
I am having more problems with my converting of vb.net to c#.net.

I have some files in vb.net that have "Option Strict Off" to allow for bad programming.  When I convert to c# I use "dynamic" until I come back and fix problems, and this works in all cases

But now I have this code:

Public Class ContractResults
   'Big class definition
   Public Shared Sub CleanCache()
       'Code here
   End Sub
End Class

And in a file with Option Strict Off:

Public Sub VerifyResults(result as Object)
   'Here, result is normally ContractResults
   'first it check for that then call this:
   result.CleanCache()
End Sub

In c# I use "dynamic", but a runtime error pops up when I call "static" method with dynamic reference.  In vb.net, I can called "shared" sub from instance, but in c# this is not allowed

Exception:
   "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"
   "Member 'ContractTypes.ContractResults.CleanCache()' cannot be accessed with an instance reference; qualify it with a type name instead"

It seems I must convert code to use actual type, but then this means much rewriting of more parts.  Is anyone able to show another way?

I want to make sure you do not think I can use

(result as ContractResults).CleanCache();

Because all types that may be passed in have "CleanCache()" method, but do not inherits from anything the same other than "Object".  There are many types (30!) that have this "static" method and so that is why it uses Option Strict Off

Body:
As the error suggests, you have to call a static method from the class, not an instance:

ContractResults.CleanCache();

You could put your 30 types into a switch statement, but this would be ugly.


问:
How can this while loop be broken?
```<code>counter = [2 3 3 4 5];
while counter(1:5)~=zeros(1,5)
    counter(1)=0;
end
counter
</code>```

I know this is a stupid code but I don't understand as to how this while loop gets broken. I want a loop to exist until all the counters become 0 i.e.)counter=[0 0 0 0 0] not just one of them.

Can someone tell why this loop gets broken and write while loop that has my original intention?

答:
This line

```<code>counter(1) = 0;
</code>```

is one problem. You only ever change that one element of counter. You need to add some sort of code to your loop that is capable of setting any/all of the elements of counter to zero or you can end up with an infinite loop.

In addition, you need to change counter(1:5)~=zeros(1,5) to any(counter(1:5)~=zeros(1,5)) as TroyHaskin already commented, so that it will keep running until all elements of counter are zero.

Title: How can this while loop be broken?

Body:
counter = [2 3 3 4 5];
while counter(1:5)~=zeros(1,5)
    counter(1)=0;
end
counter

I know this is a stupid code but I don't understand as to how this while loop gets broken. I want a loop to exist until all the counters become 0 i.e.)counter=[0 0 0 0 0] not just one of them.

Can someone tell why this loop gets broken and write while loop that has my original intention?

Body:
This line

counter(1) = 0;

is one problem. You only ever change that one element of counter. You need to add some sort of code to your loop that is capable of setting any/all of the elements of counter to zero or you can end up with an infinite loop.

In addition, you need to change counter(1:5)~=zeros(1,5) to any(counter(1:5)~=zeros(1,5)) as TroyHaskin already commented, so that it will keep running until all elements of counter are zero.


问:
How to get JSON from URL in JavaScript?
This URL returns JSON:

```<code>{
  query: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  }
}
</code>```

I tried this, and it didn't work:

```<code>responseObj = readJsonFromUrl('http://query.yahooapis.com/v1/publ...');
var count = responseObj.query.count;

console.log(count) // should be 1
</code>```

How can I get a JavaScript object from this URL's JSON response?

答:
With Chrome, Firefox, Safari, Edge, and Webview you can natively use the fetch API which makes this a lot easier, and much more terse.

If you need support for IE or older browsers, you can also use the fetch polyfill.

```<code>let url = 'https://example.com';

fetch(url)
.then(res => res.json())
.then(out =>
  console.log('Checkout this JSON! ', out))
.catch(err => { throw err });
</code>```

MDN: Fetch API

Even though Node.js does not have this method built-in, you can use node-fetch which allows for the exact same implementation.

ContentLicense: CC BY-SA 4.0

Title: How to get JSON from URL in JavaScript?

Body:
This URL returns JSON:

{
  query: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  }
}

I tried this, and it didn't work:

responseObj = readJsonFromUrl('http://query.yahooapis.com/v1/publ...');
var count = responseObj.query.count;

console.log(count) // should be 1

How can I get a JavaScript object from this URL's JSON response?

Body:
With Chrome, Firefox, Safari, Edge, and Webview you can natively use the fetch API which makes this a lot easier, and much more terse.

If you need support for IE or older browsers, you can also use the fetch polyfill.

let url = 'https://example.com';

fetch(url)
.then(res => res.json())
.then(out =>
  console.log('Checkout this JSON! ', out))
.catch(err => { throw err });

MDN: Fetch API

Even though Node.js does not have this method built-in, you can use node-fetch which allows for the exact same implementation.


问:
SQL Query DBMS Actually Executes When View Query Uses an Aliased Aggregate Function
I'm working on a 3-step homework problem and I'm stumped on the last step. For the last step to make sense, I'll post the entire problem including my solutions for the first two steps:

The Problem and My Solutions for the First Two Steps

Create a view named TRIP_INVENTORY. It consists of the state and the total number of trips for each state. Use UNITS as the column name for the total number of trips for each state. Group and order the rows by state.

a. Write and execute the CREATE VIEW command to create the TRIP_INVENTORY view.

```<code>CREATE VIEW TRIP_INVENTORY AS
SELECT STATE, COUNT(TRIP_ID) AS UNITS
FROM TOURS_TRIP
GROUP BY STATE
</code>```

b. Write and execute the command to retreive the state and units for each state having more than 10 trips.

```<code>SELECT STATE, UNITS
FROM TRIP_INVENTORY
WHERE UNITS > 10
</code>```

The Step that has Me Stumped

c. Write and execute the query that the DBMS actually executes.

This was the unsuccessful query I came up with:

```<code>SELECT STATE, COUNT(TRIP_ID) AS UNITS
FROM TOURS_TRIP
WHERE UNITS > 10
GROUP BY STATE
</code>```

The problem is that the UNITS column alias can't be referenced in the WHERE clause. I can't use an aggregate function in the WHERE clause either. I'm pretty sure I need to use a subquery, but I can't figure out how to structure the constraints so that they will remove the unnecessary states using the results of the nested query.

Can anyone offer any insight?

答:
should be</p>

```<code>  SELECT STATE, COUNT(TRIP_ID) AS UNITS
    FROM TOURS_TRIP
    GROUP BY STATE
    having COUNT(TRIP_ID) > 10
</code>```

Body:
I'm working on a 3-step homework problem and I'm stumped on the last step. For the last step to make sense, I'll post the entire problem including my solutions for the first two steps:

The Problem and My Solutions for the First Two Steps

Create a view named TRIP_INVENTORY. It consists of the state and the total number of trips for each state. Use UNITS as the column name for the total number of trips for each state. Group and order the rows by state.

a. Write and execute the CREATE VIEW command to create the TRIP_INVENTORY view.

CREATE VIEW TRIP_INVENTORY AS
SELECT STATE, COUNT(TRIP_ID) AS UNITS
FROM TOURS_TRIP
GROUP BY STATE

b. Write and execute the command to retreive the state and units for each state having more than 10 trips.

SELECT STATE, UNITS
FROM TRIP_INVENTORY
WHERE UNITS > 10

The Step that has Me Stumped

c. Write and execute the query that the DBMS actually executes.

This was the unsuccessful query I came up with:

SELECT STATE, COUNT(TRIP_ID) AS UNITS
FROM TOURS_TRIP
WHERE UNITS > 10
GROUP BY STATE

The problem is that the UNITS column alias can't be referenced in the WHERE clause. I can't use an aggregate function in the WHERE clause either. I'm pretty sure I need to use a subquery, but I can't figure out how to structure the constraints so that they will remove the unnecessary states using the results of the nested query.

Can anyone offer any insight?

Body:
should be

  SELECT STATE, COUNT(TRIP_ID) AS UNITS
    FROM TOURS_TRIP
    GROUP BY STATE
    having COUNT(TRIP_ID) > 10


问:
How to get the absolute path for JUnit tests
I have a file within my project called x.txt in the same directory as a file that takes x and reads it. However, when using JUnit testing, if I test on a different PC, it will have a different absolute path to the file x.txt

How do I do this so that I dont need to enter the absolute file path, but can hardcode the relative file path for use?

答:
You should be using Class#getResource or Class#getResourceAsStream

Examples:

How to get resources directory path programmatically

https://docs.oracle.com/javase/8/docs/technotes/guides/lang/resources.html


问:
how to divide a vector by 4 in scheme
I have a vector list (3 6 8 2 ) and want to divide each element of the vector by 4 and return the vector </p>

```<code>ex:- (div4 #(3 6 8 2))
     '#(3/4 6/4 8/4 2/4)
</code>```

答:
You can use vector-map to apply a procedure to every element of a vector, as:

```<code>(define (div4 vec)
  (vector-map (lambda (x) (/ x 4)) vec))
</code>```

For example,

```<code>> (div4 #(4 8 12 16))
'#(1 2 3 4)
</code>```

Title: how to divide a vector by 4 in scheme

Body:
I have a vector list (3 6 8 2 ) and want to divide each element of the vector by 4 and return the vector

ex:- (div4 #(3 6 8 2))
     '#(3/4 6/4 8/4 2/4)

Body:
You can use vector-map to apply a procedure to every element of a vector, as:

(define (div4 vec)
  (vector-map (lambda (x) (/ x 4)) vec))

For example,

> (div4 #(4 8 12 16))
'#(1 2 3 4)


问:
Send massage to group devices in Firebase Cloud Messaging
I am building a chat and I want to send message in FCM to 1000 clients in a group. The message would sent from client to group of 1000 clients (the message not pass through server). I can use the topic method, but if I want to remove a client by the group admin it's not possible. Anyone can propose a solution?

Help me please.

答:
If you simply want to remove (unsubscribe) some specific members, you can make use of the InstanceID API, specifically batchRemove.

Manage relationship maps for multiple app instances

Using the Instance ID service's batch methods, you can perform batch management of app instances. For example, you can perform bulk addition or removal of app instances to an FCM or GCM topic. To manage app instances, call the Instance ID service at this endpoint, providing the app instance tokens in the JSON body:

```<code>https://iid.googleapis.com/iid/v1:batchAdd

https://iid.googleapis.com/iid/v1:batchRemove
</code>```

Parameters

Authorization: key=YOUR_API_KEY. Set this parameter in the header.

to : The topic name.

registration_tokens : The array of IID tokens for the app instances you want to add or remove.

Results

On success the call returns HTTP status 200. Empty results indicate successful subscription for the token. For failed subscriptions, the result contains one of these error codes:

NOT_FOUND — The registration token has been deleted or the app has been uninstalled.

INVALID_ARGUMENT — The registration token provided is not valid for the Sender ID.

INTERNAL — The backend server failed for unknown reasons. Retry the request.

TOO_MANY_TOPICS — Excessive number of topics per app instance.

Example POST request

```<code>https://iid.googleapis.com/iid/v1:batchAdd
Content-Type:application/json
Authorization:key=API_KEY
{
   "to": "/topics/movies",
   "registration_tokens": ["nKctODamlM4:CKrh_PC8kIb7O...", "1uoasi24:9jsjwuw...", "798aywu:cba420..."],
}
</code>```

Example result

```<code>HTTP 200 OK
{
  "results":[
    {},
    {"error":"NOT_FOUND"},
    {},
  ]
}
</code>```

Body:
If you simply want to remove (unsubscribe) some specific members, you can make use of the InstanceID API, specifically batchRemove.

Manage relationship maps for multiple app instances

Using the Instance ID service's batch methods, you can perform batch management of app instances. For example, you can perform bulk addition or removal of app instances to an FCM or GCM topic. To manage app instances, call the Instance ID service at this endpoint, providing the app instance tokens in the JSON body:

https://iid.googleapis.com/iid/v1:batchAdd

https://iid.googleapis.com/iid/v1:batchRemove

Parameters

Authorization: key=YOUR_API_KEY. Set this parameter in the header.

to : The topic name.

registration_tokens : The array of IID tokens for the app instances you want to add or remove.

Results

On success the call returns HTTP status 200. Empty results indicate successful subscription for the token. For failed subscriptions, the result contains one of these error codes:

NOT_FOUND — The registration token has been deleted or the app has been uninstalled.

INVALID_ARGUMENT — The registration token provided is not valid for the Sender ID.

INTERNAL — The backend server failed for unknown reasons. Retry the request.

TOO_MANY_TOPICS — Excessive number of topics per app instance.

Example POST request

https://iid.googleapis.com/iid/v1:batchAdd
Content-Type:application/json
Authorization:key=API_KEY
{
   "to": "/topics/movies",
   "registration_tokens": ["nKctODamlM4:CKrh_PC8kIb7O...", "1uoasi24:9jsjwuw...", "798aywu:cba420..."],
}

Example result

HTTP 200 OK
{
  "results":[
    {},
    {"error":"NOT_FOUND"},
    {},
  ]
}


问:
symfony fields relating to each entity
I am displaying a list of purchase orders and each "line item" corresponding to it so its basically nested in a table.

ie:

```<code>PO#  |  Item  |  Qty Ordered  |    Qty Received  |
 1
        123         20            [form Field]
        345         10            [form field]
 5
        232         5             [form field]
</code>```

What I am trying to do is provide a single (unmapped) field for each line item called "quantity received" which the user will type a number in there and save the form. I currently setup my code to have a few collection types nested. For example, my initial FormType starts with my user. Then users have "PurchaseOrders" so I add a collection type of "PurchaseOrders" (PurchaseOrderType), then inside that PurchaseOrderType I have a collectiontype of PurchaseOrderItems (PurchaseOrderItemType) (these are the line items). In that form type I have a single unmapped field called "quantityReceived" (NumberType).

Everything seems to work fine with the form except I dont have a way to place the correct field in the correct row in the table. In my template I have a nested loop to loop through my PurchaseOrders and their corresponding PurchaseOrderItems for the purpose of displaying data in the table shown below. How can I render the correct form field in line with the data I am already displaying? The problem is that collections create field names using sequential index numbers starting with [0], so that does not correspond to the ID of the "PurchaseOrderItem" so as I am looping through each PurchaseOrderItem i feel like I dont have a reliable way to select the correct form field to place into that row.

答: So it seems that I have resolved this issue by instead of looping through my entities, I loop through my form instead and access the necessary variables for display purposes by using form.fieldName.vars.value.[propertyName]</p>

Title: symfony fields relating to each entity

Body:
I am displaying a list of purchase orders and each "line item" corresponding to it so its basically nested in a table.

ie:

PO#  |  Item  |  Qty Ordered  |    Qty Received  |
 1
        123         20            [form Field]
        345         10            [form field]
 5
        232         5             [form field]

What I am trying to do is provide a single (unmapped) field for each line item called "quantity received" which the user will type a number in there and save the form. I currently setup my code to have a few collection types nested. For example, my initial FormType starts with my user. Then users have "PurchaseOrders" so I add a collection type of "PurchaseOrders" (PurchaseOrderType), then inside that PurchaseOrderType I have a collectiontype of PurchaseOrderItems (PurchaseOrderItemType) (these are the line items). In that form type I have a single unmapped field called "quantityReceived" (NumberType).

Everything seems to work fine with the form except I dont have a way to place the correct field in the correct row in the table. In my template I have a nested loop to loop through my PurchaseOrders and their corresponding PurchaseOrderItems for the purpose of displaying data in the table shown below. How can I render the correct form field in line with the data I am already displaying? The problem is that collections create field names using sequential index numbers starting with [0], so that does not correspond to the ID of the "PurchaseOrderItem" so as I am looping through each PurchaseOrderItem i feel like I dont have a reliable way to select the correct form field to place into that row.


问:
Displaying only user specific items from MongoDB collection in Meteor
I am new to Meteor, and creating a meteor web application for teachers in order for them to keep track of the classes they teach and the students within each class. After logging in, the teacher sees a running list of all of the classes that they personally teach, and will be able to select each individual class in order to view a list of students in that particular class, with options to remove, edit, or add. The teacher will then be able to select an individual student's name, which will take them to a page where the teacher can upload documents (pdfs, word documents, etc) corresponding to the specific student they have chosen. The problem I am running into is how exactly I can display, add, and edit only information that applies to each teacher, since there will be many teachers using the app, each with different classes and students. I have a single collection for both classes and students, but can not seem to wrap my mind around how to only display items that correspond to the presently logged in teacher. What is the best way to go about this? </p>

答:
you said:

I have a single collection for both classes and students

that sounds like you mean 1 collection total (so far), and not one each for classes and students.

this problem is non-trivial, because you might also want to handle:

a teacher teaches a class of a certain subject more than 1x/day

more than 1 teacher may teach a subject

a semester ends, and there are a whole new group of teacher/class/student relationships

if i were modeling this, i would start with these collections:

teachers

subjects

students

notice i listed "subjects" instead of "classes". classes will come next. a subject might be "History 4", which comes with a textbook and maybe some existing tests and homework assignments, and is offered year after year. or maybe 2 teachers teach History 4 each semester.

each of those collections above represent concepts that are more "durable" than a semester. a teacher has (hopefully) a long career at the school. students may be there 4 years. subjects, though they may evolve over time, stay relatively constant.

the next step is to start making associations among all those collections. here's where "classes" comes into play. to avoid reserved words, let's call it a "schoolClass".

a schoolClass is when the school offers a subject to students w/ a fixed schedule. e.g. School Year 2017, Semester 1. it is taught by a teacher and attended by students. since each item in the durable collections has an _id, now you can do the association in one go:

```<code>{
    subjectId: 'abc123',
    teacherId: 'def456',
    students: ['ghi789', 'xxx123', ... ],
    year: 2017,
    semester: 1,
    schedule: [
        {
            day: 'M',
            time: '1030'
        },
        {
            day: 'Th',
            time: '1500'
        }
    ]
}
</code>```

does that make sense? this solves all the issues i mentioned above. it provides good flexibility and keeps an important distinction between a subject and that subject being offered to students at a scheduled time.

there's also the schedule there (handy), showing that the class meets 2x/week for that semester.

and now you can do your queries:

start with a teacher

grab their _id

search through the schoolClass collection with teacherId=_id, and also filtering by the school year and semester

you'll get back an array. each item in the array will give you the association to the subject (so you can show History 4 or Math 1 or whatever), and the list of students.

you can iterative over the students and, with their _id's, query the students collection to show their names. and with the schoolClass and student ids, now you can create an association for that student, in that class, for the uploaded documents.

you'll probably want another collection for those upload documents. each item might look like this:

```<code>{
    schoolClassId: 'zzz789',
    studentId: 'ghi789',
    documents: [] // however you want to handle that...
}
</code>```

to borrow a term from relational databases, those id's (schoolClassId, studentId) are called foreign keys. they simply set up a reference back to an item in another collection.

it will be a fair amount of work to get everything correct and working, but i think it will provide you a lot of flexibility and solve your requirements.

Body:
you said:

I have a single collection for both classes and students

that sounds like you mean 1 collection total (so far), and not one each for classes and students.

this problem is non-trivial, because you might also want to handle:

a teacher teaches a class of a certain subject more than 1x/day

more than 1 teacher may teach a subject

a semester ends, and there are a whole new group of teacher/class/student relationships

if i were modeling this, i would start with these collections:

teachers

subjects

students

notice i listed "subjects" instead of "classes". classes will come next. a subject might be "History 4", which comes with a textbook and maybe some existing tests and homework assignments, and is offered year after year. or maybe 2 teachers teach History 4 each semester.

each of those collections above represent concepts that are more "durable" than a semester. a teacher has (hopefully) a long career at the school. students may be there 4 years. subjects, though they may evolve over time, stay relatively constant.

the next step is to start making associations among all those collections. here's where "classes" comes into play. to avoid reserved words, let's call it a "schoolClass".

a schoolClass is when the school offers a subject to students w/ a fixed schedule. e.g. School Year 2017, Semester 1. it is taught by a teacher and attended by students. since each item in the durable collections has an _id, now you can do the association in one go:

{
    subjectId: 'abc123',
    teacherId: 'def456',
    students: ['ghi789', 'xxx123', ... ],
    year: 2017,
    semester: 1,
    schedule: [
        {
            day: 'M',
            time: '1030'
        },
        {
            day: 'Th',
            time: '1500'
        }
    ]
}

does that make sense? this solves all the issues i mentioned above. it provides good flexibility and keeps an important distinction between a subject and that subject being offered to students at a scheduled time.

there's also the schedule there (handy), showing that the class meets 2x/week for that semester.

and now you can do your queries:

start with a teacher

grab their _id

search through the schoolClass collection with teacherId=_id, and also filtering by the school year and semester

you'll get back an array. each item in the array will give you the association to the subject (so you can show History 4 or Math 1 or whatever), and the list of students.

you can iterative over the students and, with their _id's, query the students collection to show their names. and with the schoolClass and student ids, now you can create an association for that student, in that class, for the uploaded documents.

you'll probably want another collection for those upload documents. each item might look like this:

{
    schoolClassId: 'zzz789',
    studentId: 'ghi789',
    documents: [] // however you want to handle that...
}

to borrow a term from relational databases, those id's (schoolClassId, studentId) are called foreign keys. they simply set up a reference back to an item in another collection.

it will be a fair amount of work to get everything correct and working, but i think it will provide you a lot of flexibility and solve your requirements.