答:
Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

```<code>>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!
</code>```

Old style % format specifier:

```<code>>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!
</code>```

In Py 3.6 using the new f"" format strings:

```<code>>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!
</code>```

Or using print()s default separator:

```<code>>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!
</code>```

And least effectively, construct a new string by casting it to a str() and concatenating:

```<code>>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!
</code>```

Or join()ing it:

```<code>>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!
</code>```

Title: Python TypeError must be str not int

Body:
Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!


来源: stackexchange

问:
Linq with dot notation - which is better form or what's the difference between these two?
I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.

He has something similar to the following:

```<code>var item = someObject.Where(user => user.Id == Id).Single();
</code>```

Whereas I've been doing the following:

```<code>var item = someObject.Single(user => user.Id == Id);
</code>```

Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.

答: The queries should be equal when the tree is evaluated, however depending on the target the actual execution could differ (IE L2S optimization).</p>

ContentLicense: CC BY-SA 2.5

Body:
I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.

He has something similar to the following:

var item = someObject.Where(user => user.Id == Id).Single();

Whereas I've been doing the following:

var item = someObject.Single(user => user.Id == Id);

Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.


问:
code not working despite following exact instructions
I'm new to programming with Javascript, and I am building a simple ping-pong game with the help of a video. I have followed every instruction in the video yet it doesn't seem to be working. ballX is supposed to reset in the middle once it goes past the canvas width, but the X is supposed to reverse if it hits the right paddle.

```<code>if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  if (ballX > canvas.width) {
    if (ballY > paddle2Y &&
      ballY < paddleHeight + paddle2Y) {
      ballXSpeed = -ballXSpeed;
    } else {
      ballReset();
    }
  }
}; //ends movement();
</code>```

答:
Moved } - see if that helps

```<code>if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
} // added
if (ballX > canvas.width) { // this probably should be an else if but it really doesn't matter
  if (ballY > paddle2Y &&
    ballY < paddleHeight + paddle2Y) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  // a } removed from here
} //ends movement();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to programming with Javascript, and I am building a simple ping-pong game with the help of a video. I have followed every instruction in the video yet it doesn't seem to be working. ballX is supposed to reset in the middle once it goes past the canvas width, but the X is supposed to reverse if it hits the right paddle.

if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  if (ballX > canvas.width) {
    if (ballY > paddle2Y &&
      ballY < paddleHeight + paddle2Y) {
      ballXSpeed = -ballXSpeed;
    } else {
      ballReset();
    }
  }
}; //ends movement();

Body:
Moved } - see if that helps

if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
} // added
if (ballX > canvas.width) { // this probably should be an else if but it really doesn't matter
  if (ballY > paddle2Y &&
    ballY < paddleHeight + paddle2Y) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  // a } removed from here
} //ends movement();


问:
How to get route parameters from a url in angular2 app?
I have a constant ROUTES that is set up like this:

```<code>export const ROUTES: Routes = [
    { path: 'custom', component: MyCustomComponent }
]
</code>```

I want to make it so that if the user goes to:

```<code>http://my-angular-app/#/custom/something?mode=CRAZY
</code>```

That within "MyCustomComponent", I can see access the "mode=CRAZY" and do something with it.

How do I access the variable "mode" from my MyCustomComponent? Or do I have to define a new route to be able to pass the parameters?

答:
As said in other answer, you may use ActivatedRoute.snapshot.queryParam but if your queryParam change it's value while you are in the same route you'll have problems if you need to update the value that you got from the queryParam. As you are in the same route angular won't recreate the component for, so you won't get the new value from the snapshot in your constructor. If you need to get the updated value while in the same route, you should subscribe to que queryParam observable.

```<code>constructor(
  private route: ActivatedRoute
) {
  this.route.queryParams.subscribe((queryParams) => {
    console.log(queryParams); // get the values of your queryParams
  });
}
</code>```

Now, every new value on your queryParams will be updated in your Component. And as it is an Angular Observable you won't be bother to treat it's unsubscription manually, Angular'll take care of it for you.

Body:
I have a constant ROUTES that is set up like this:

export const ROUTES: Routes = [
    { path: 'custom', component: MyCustomComponent }
]

I want to make it so that if the user goes to:

http://my-angular-app/#/custom/something?mode=CRAZY

That within "MyCustomComponent", I can see access the "mode=CRAZY" and do something with it.

How do I access the variable "mode" from my MyCustomComponent? Or do I have to define a new route to be able to pass the parameters?

Body:
As said in other answer, you may use ActivatedRoute.snapshot.queryParam but if your queryParam change it's value while you are in the same route you'll have problems if you need to update the value that you got from the queryParam. As you are in the same route angular won't recreate the component for, so you won't get the new value from the snapshot in your constructor. If you need to get the updated value while in the same route, you should subscribe to que queryParam observable.

constructor(
  private route: ActivatedRoute
) {
  this.route.queryParams.subscribe((queryParams) => {
    console.log(queryParams); // get the values of your queryParams
  });
}

Now, every new value on your queryParams will be updated in your Component. And as it is an Angular Observable you won't be bother to treat it's unsubscription manually, Angular'll take care of it for you.


问:
Making UIView appear and disappear with swipe up and swipe down - Swift
I am trying to make a project in swift and am very new to the language.

I am trying to make a UIView appear and disappear with swipe up and swipe down on the screen. I am currently using a struct to store the instance of the view in order to be able to make changes with both the swipeUp() and swipeDown() methods.

When i try to access this.view.bounds.height it tells me "instance member view cannot be used on type SecondViewController"

Below is my code

```<code>import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit

class SecondViewController: UIViewController {

let label = UILabel()

override func viewDidLoad() {
    super.viewDidLoad()

    let swipeUp = UISwipeGestureRecognizer(target: self, action: "swipeUp")
    swipeUp.direction = UISwipeGestureRecognizerDirection.up
    self.view.addGestureRecognizer(swipeUp)

    let swipeDown = UISwipeGestureRecognizer(target: self, action: "swipeDown")
    swipeDown.direction = UISwipeGestureRecognizerDirection.down
    self.view.addGestureRecognizer(swipeDown)

}

struct myVars{

    let v = MyCustomView(frame: CGRect(x: 0, y: this.view.bounds.height / 2, width: this.view.bounds.width, height: self.view.bounds.height / 2))

}

func swipeUp(){

    if myVars.v.isDescendantOfView(self) {

        myVars.v.isHidden = false

    }

    else {
        self.view.addSubview(myVars.v)
    }

}

func swipeDown(){
    myVars.v.isHidden = true
}

}
</code>```

Can you please, either tell me what is wrong with my code or let me know if there is a better way to do this altogether?

答:
Just check Replace you code With below code it works.
On place of  #selector(ViewController.swipeUp) put name of your viewController     </p>

```<code>let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipeUp))
            swipeUp.direction = UISwipeGestureRecognizerDirection.up
            self.view.addGestureRecognizer(swipeUp)

let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipeDown))
                swipeDown.direction = UISwipeGestureRecognizerDirection.down
                self.view.addGestureRecognizer(swipeDown)
</code>```

Body:
I am trying to make a project in swift and am very new to the language.

I am trying to make a UIView appear and disappear with swipe up and swipe down on the screen. I am currently using a struct to store the instance of the view in order to be able to make changes with both the swipeUp() and swipeDown() methods.

When i try to access this.view.bounds.height it tells me "instance member view cannot be used on type SecondViewController"

Below is my code

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit

class SecondViewController: UIViewController {

let label = UILabel()

override func viewDidLoad() {
    super.viewDidLoad()

    let swipeUp = UISwipeGestureRecognizer(target: self, action: "swipeUp")
    swipeUp.direction = UISwipeGestureRecognizerDirection.up
    self.view.addGestureRecognizer(swipeUp)

    let swipeDown = UISwipeGestureRecognizer(target: self, action: "swipeDown")
    swipeDown.direction = UISwipeGestureRecognizerDirection.down
    self.view.addGestureRecognizer(swipeDown)

}

struct myVars{

    let v = MyCustomView(frame: CGRect(x: 0, y: this.view.bounds.height / 2, width: this.view.bounds.width, height: self.view.bounds.height / 2))

}

func swipeUp(){

    if myVars.v.isDescendantOfView(self) {

        myVars.v.isHidden = false

    }

    else {
        self.view.addSubview(myVars.v)
    }

}

func swipeDown(){
    myVars.v.isHidden = true
}

}

Can you please, either tell me what is wrong with my code or let me know if there is a better way to do this altogether?

Body:
Just check Replace you code With below code it works.
On place of  #selector(ViewController.swipeUp) put name of your viewController

let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipeUp))
            swipeUp.direction = UISwipeGestureRecognizerDirection.up
            self.view.addGestureRecognizer(swipeUp)

let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipeDown))
                swipeDown.direction = UISwipeGestureRecognizerDirection.down
                self.view.addGestureRecognizer(swipeDown)


问:
Spring Boot Application - what is default timeout for any rest API endpoint or a easy config to control all endpoint timeout
I am using current Spring boot version (1.4.x) and wondering if it has any default timeout for api calls. I have tested it by putting breakpoints but it was keep waiting and didn't time-out.
I was also trying to configure default timeout for all my spring-boot apps by using some annotation or yml settings.

I found couple of alternatives (one of them here) but using callable actually adding extra non-business logic code where setting something in xml bean is out of fashion in latest spring boot applications.

答:
I agree all above options and tried below option in my spring boot application.  It works perfectly fine now. Below is the code sample as a bean. Now just need to @Autowire RestTemplate wherever(java class) I need it.

```<code>   @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(15000);
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setReadTimeout(15000);

        return restTemplate;
    }
</code>```

Body:
I agree all above options and tried below option in my spring boot application.  It works perfectly fine now. Below is the code sample as a bean. Now just need to @Autowire RestTemplate wherever(java class) I need it.

   @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(15000);
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setReadTimeout(15000);

        return restTemplate;
    }


问:
Xamarin.Forms ListView size to content?
I have a pretty large form (adapted mainly for tablets), that has a TabbedPage nesting a ScrollView and a vertical StackPanel containing many controls.

I have few occurrences where I have a ListView that contains a few single-line items, and I need it to size to content.

I'd like to get rid of its scroll-bars, but anyway I don't want it to take up more space than what's required for its items.

Is there a way (even an ugly one) to achieve that without have to write a renderer x3 platforms?

Here's a pseudo describing my tree:

```<code><ContentPage>
  <MasterDetailPage>
    <MasterDetailPage.Detail>
      <TabbedPage>
        <ContentPage>
          <ScrollView>
            <StackPanel>
              <!-- many controls-->
              <ListView>
</code>```

When rendered, there is a huge gap coming after the ListView. How can I avoid that?

I tried messing around with the VerticalOptions and HeightRequest, non of which worked.

I'm looking for a dynamic way (preferably without inheritance) to achieve that without involving custom renderers.

答:
Based on Lutaaya's answer, I made a behavior that automates this, determining and setting the row-height (Gist).

Behavior:

```<code>namespace Xamarin.Forms
{
  using System;
  using System.Linq;
  public class AutoSizeBehavior : Behavior<ListView>
  {
    ListView _ListView;
    ITemplatedItemsView<Cell> Cells => _ListView;

    protected override void OnAttachedTo(ListView bindable)
    {
      bindable.ItemAppearing += AppearanceChanged;
      bindable.ItemDisappearing += AppearanceChanged;
      _ListView = bindable;
    }

    protected override void OnDetachingFrom(ListView bindable)
    {
      bindable.ItemAppearing -= AppearanceChanged;
      bindable.ItemDisappearing -= AppearanceChanged;
      _ListView = null;
    }

    void AppearanceChanged(object sender, ItemVisibilityEventArgs e) =>
      UpdateHeight(e.Item);

    void UpdateHeight(object item)
    {
      if (_ListView.HasUnevenRows)
      {
        double height;
        if ((height = _ListView.HeightRequest) ==
            (double)VisualElement.HeightRequestProperty.DefaultValue)
          height = 0;

        height += MeasureRowHeight(item);
        SetHeight(height);
      }
      else if (_ListView.RowHeight == (int)ListView.RowHeightProperty.DefaultValue)
      {
        var height = MeasureRowHeight(item);
        _ListView.RowHeight = height;
        SetHeight(height);
      }
    }

    int MeasureRowHeight(object item)
    {
      var template = _ListView.ItemTemplate;
      var cell = (Cell)template.CreateContent();
      cell.BindingContext = item;
      var height = cell.RenderHeight;
      var mod = height % 1;
      if (mod > 0)
        height = height - mod + 1;
      return (int)height;
    }

    void SetHeight(double height)
    {
      //TODO if header or footer is string etc.
      if (_ListView.Header is VisualElement header)
        height += header.Height;
      if (_ListView.Footer is VisualElement footer)
        height += footer.Height;
      _ListView.HeightRequest = height;
    }
  }
}
</code>```

Usage:

```<code><ContentPage xmlns:xf="clr-namespace:Xamarin.Forms">
  <ListView>
    <ListView.Behaviors>
      <xf:AutoSizeBehavior />
</code>```

Title: Xamarin.Forms ListView size to content?

Body:
I have a pretty large form (adapted mainly for tablets), that has a TabbedPage nesting a ScrollView and a vertical StackPanel containing many controls.

I have few occurrences where I have a ListView that contains a few single-line items, and I need it to size to content.

I'd like to get rid of its scroll-bars, but anyway I don't want it to take up more space than what's required for its items.

Is there a way (even an ugly one) to achieve that without have to write a renderer x3 platforms?

Here's a pseudo describing my tree:

<ContentPage>
  <MasterDetailPage>
    <MasterDetailPage.Detail>
      <TabbedPage>
        <ContentPage>
          <ScrollView>
            <StackPanel>

              <ListView>

When rendered, there is a huge gap coming after the ListView. How can I avoid that?

I tried messing around with the VerticalOptions and HeightRequest, non of which worked.

I'm looking for a dynamic way (preferably without inheritance) to achieve that without involving custom renderers.

Body:
Based on Lutaaya's answer, I made a behavior that automates this, determining and setting the row-height (Gist).

Behavior:

namespace Xamarin.Forms
{
  using System;
  using System.Linq;
  public class AutoSizeBehavior : Behavior<ListView>
  {
    ListView _ListView;
    ITemplatedItemsView<Cell> Cells => _ListView;

    protected override void OnAttachedTo(ListView bindable)
    {
      bindable.ItemAppearing += AppearanceChanged;
      bindable.ItemDisappearing += AppearanceChanged;
      _ListView = bindable;
    }

    protected override void OnDetachingFrom(ListView bindable)
    {
      bindable.ItemAppearing -= AppearanceChanged;
      bindable.ItemDisappearing -= AppearanceChanged;
      _ListView = null;
    }

    void AppearanceChanged(object sender, ItemVisibilityEventArgs e) =>
      UpdateHeight(e.Item);

    void UpdateHeight(object item)
    {
      if (_ListView.HasUnevenRows)
      {
        double height;
        if ((height = _ListView.HeightRequest) ==
            (double)VisualElement.HeightRequestProperty.DefaultValue)
          height = 0;

        height += MeasureRowHeight(item);
        SetHeight(height);
      }
      else if (_ListView.RowHeight == (int)ListView.RowHeightProperty.DefaultValue)
      {
        var height = MeasureRowHeight(item);
        _ListView.RowHeight = height;
        SetHeight(height);
      }
    }

    int MeasureRowHeight(object item)
    {
      var template = _ListView.ItemTemplate;
      var cell = (Cell)template.CreateContent();
      cell.BindingContext = item;
      var height = cell.RenderHeight;
      var mod = height % 1;
      if (mod > 0)
        height = height - mod + 1;
      return (int)height;
    }

    void SetHeight(double height)
    {
      //TODO if header or footer is string etc.
      if (_ListView.Header is VisualElement header)
        height += header.Height;
      if (_ListView.Footer is VisualElement footer)
        height += footer.Height;
      _ListView.HeightRequest = height;
    }
  }
}

Usage:

<ContentPage xmlns:xf="clr-namespace:Xamarin.Forms">
  <ListView>
    <ListView.Behaviors>
      <xf:AutoSizeBehavior />


问:
How to retrieve stripe token value from ASP.NET after Form.Submit
Needed help here, this is my code

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        /**
 * The CSS shown here will not be introduced in the Quickstart guide, but shows
 * how you can use CSS to style your Element's container.
 */
        .StripeElement {
            background-color: white;
            padding: 8px 12px;
            border-radius: 4px;
            border: 1px solid transparent;
            box-shadow: 0 1px 3px 0 #e6ebf1;
            -webkit-transition: box-shadow 150ms ease;
            transition: box-shadow 150ms ease;
        }

        .StripeElement--focus {
            box-shadow: 0 1px 3px 0 #cfd7df;
        }

        .StripeElement--invalid {
            border-color: #fa755a;
        }

        .StripeElement--webkit-autofill {
            background-color: #fefde5 !important;
        }
    </style>

    <script src="https://js.stripe.com/v3/"></script>
    <script type="text/javascript">
    </script>
</head>
<body>

        <div>

            <script src="https://js.stripe.com/v3/"></script>

            <form id="payment-form">
                <div class="form-row">
                    <label for="card-element">
                        Credit or debit card
                    </label>
                    <div id="card-element">
                        <!-- a Stripe Element will be inserted here. -->
                    </div>

                    <!-- Used to display form errors -->
                    <div id="card-errors" role="alert"></div>
                </div>

                <button>Submit Payment</button>
                <br />
                <br />
            </form>
                <form runat="server">
                    <asp:Button ID="Button1" runat="server" OnClientClick="abc()" OnClick="Button1_Click" Text="Button" />

                            </form>

        </div>
    <script>

        // Create a Stripe client
        var stripe = Stripe('pk_test_2O7D78OBubjUApxMMbvbHLVr');
        var test = "Whatsup";
        // Create an instance of Elements
        var elements = stripe.elements();

        // Custom styling can be passed to options when creating an Element.
        // (Note that this demo uses a wider set of styles than the guide below.)
        var style = {
            base: {
                color: '#32325d',
                lineHeight: '24px',
                fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                fontSmoothing: 'antialiased',
                fontSize: '16px',
                '::placeholder': {
                    color: '#aab7c4'
                }
            },
            invalid: {
                color: '#fa755a',
                iconColor: '#fa755a'
            }
        };

        // Create an instance of the card Element
        var card = elements.create('card', { style: style });

        // Add an instance of the card Element into the `card-element` <div>
        card.mount('#card-element');

        // Handle real-time validation errors from the card Element.
        card.addEventListener('change', function (event) {
            var displayError = document.getElementById('card-errors');
            if (event.error) {
                displayError.textContent = event.error.message;
            } else {
                displayError.textContent = '';
            }
        });

        // Handle form submission
        var form = document.getElementById('payment-form');
        form.addEventListener('submit', function (event) {
            event.preventDefault();

            stripe.createToken(card).then(function (result) {
                if (result.error) {
                    // Inform the user if there was an error
                    var errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error.message;
                } else {
                    // Send the token to your server
                    stripeTokenHandler(result.token);
                }
            });
        });

        function stripeTokenHandler(token) {
            // Insert the token ID into the form so it gets submitted to the server
            var form = document.getElementById('payment-form');
            var hiddenInput = document.createElement('input');
            hiddenInput.setAttribute('type', 'hidden');
            hiddenInput.setAttribute('name', 'stripeToken');
            hiddenInput.setAttribute('value', token.id);
            form.appendChild(hiddenInput);

            // Submit the form
            form.submit();
        };

    </script>

    <script type="text/javascript">
        function abc() {
            var str = "value";
            document.getElementById("Hidden1").value = str;
        }
</body>
</html>
</code>```

What I am trying to do is to retrieve the stripeToken after the user click "submit", the code-behind that I did is

```<code>public partial class Payment2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string token = Request.Form["stripeToken"];
    }

}
</code>```

But I tried to debug to check the value and it appears to be "null"

How do I retrieve it from the code-behind side?

Thanks!

答:
Your form has never been submitted to server, that is the reason why you got null.
When you click on your Button1, it just fires Button1_Click() event on server.

You can press F12, place a debugger on below function and will see it will never reach there.

```<code>function stripeTokenHandler(token) {
        // Insert the token ID into the form so it gets submitted to the server
        var form = document.getElementById('payment-form');
        var hiddenInput = document.createElement('input');
        hiddenInput.setAttribute('type', 'hidden');
        hiddenInput.setAttribute('name', 'stripeToken');
        hiddenInput.setAttribute('value', token.id);
        form.appendChild(hiddenInput);

        // Submit the form
        form.submit();
    };
</code>```

My suggestions are:

To configure the form, to request to a controller, API when it's submitted.

To add your form onsubmit handler to the below block:

```<code><script type="text/javascript">
function abc() {
    var str = "value";
    document.getElementById("Hidden1").value = str;
}
</code>```

Can you try the above then let me know the result?

Body:
Needed help here, this is my code

<!DOCTYPE html>

    <title></title>

            <form id="payment-form">

                        Credit or debit card

                <button>Submit Payment</button>

            </form>
                <form runat="server">
                    <asp:Button ID="Button1" runat="server" OnClientClick="abc()" OnClick="Button1_Click" Text="Button" />

                            </form>

Body:
Your form has never been submitted to server, that is the reason why you got null.
When you click on your Button1, it just fires Button1_Click() event on server.

You can press F12, place a debugger on below function and will see it will never reach there.

function stripeTokenHandler(token) {
        // Insert the token ID into the form so it gets submitted to the server
        var form = document.getElementById('payment-form');
        var hiddenInput = document.createElement('input');
        hiddenInput.setAttribute('type', 'hidden');
        hiddenInput.setAttribute('name', 'stripeToken');
        hiddenInput.setAttribute('value', token.id);
        form.appendChild(hiddenInput);

        // Submit the form
        form.submit();
    };

My suggestions are:

To configure the form, to request to a controller, API when it's submitted.

To add your form onsubmit handler to the below block:

<script type="text/javascript">
function abc() {
    var str = "value";
    document.getElementById("Hidden1").value = str;
}

Can you try the above then let me know the result?


问:
Regular expression search or LIKE type feature in cassandra
I am using datastax cassandra ver 2.0.
How do we search in cassandra column a value using regular expression.Is there way to achieve 'LIKE' ( as in sQL) functionality ?

I have created table with below schema.

```<code>CREATE TABLE Mapping (
id timeuuid,
userid text,
createdDate timestamp,
createdBy text,
lastUpdateDate timestamp,
lastUpdateBy text,
PRIMARY KEY (id,userid)
);
</code>```

I inserted few test records as below.

```<code>       id                                  | userid   | createdby
     -------------------------------------+----------+-----------
      30c78710-c00c-11e3-bb06-1553ee5e40dd |      Jon |     admin
      3e673aa0-c00c-11e3-bb06-1553ee5e40dd |     Jony |     admin
      441c4210-c00c-11e3-bb06-1553ee5e40dd | Jonathan |     admin
</code>```

I need to search records, where userid contains the word 'jon'.So that in results, i get all records, containing jon,jony,jonathan.

I know,there is no sql LIKE functionality in cassandra.
But is there any way to achieve it in cassandra ?
(NOTE: I am using datastax-java driver as client api).

答: There is a lucene index for cassandra. You can use this on the community edition too and perform Regex searches </p>

Body:
I am using datastax cassandra ver 2.0.
How do we search in cassandra column a value using regular expression.Is there way to achieve 'LIKE' ( as in sQL) functionality ?

I have created table with below schema.

CREATE TABLE Mapping (
id timeuuid,
userid text,
createdDate timestamp,
createdBy text,
lastUpdateDate timestamp,
lastUpdateBy text,
PRIMARY KEY (id,userid)
);

I inserted few test records as below.

       id                                  | userid   | createdby
     -------------------------------------+----------+-----------
      30c78710-c00c-11e3-bb06-1553ee5e40dd |      Jon |     admin
      3e673aa0-c00c-11e3-bb06-1553ee5e40dd |     Jony |     admin
      441c4210-c00c-11e3-bb06-1553ee5e40dd | Jonathan |     admin

I need to search records, where userid contains the word 'jon'.So that in results, i get all records, containing jon,jony,jonathan.

I know,there is no sql LIKE functionality in cassandra.
But is there any way to achieve it in cassandra ?
(NOTE: I am using datastax-java driver as client api).


答: If ballX is smaller than 0 then it will never be larger than the canvas width, quite simply making that portion of code useless. The logic simply doesn't make sense.

Title: code not working despite following exact instructions


问:
Creating a fancy search bar with Swing components
I'm trying to come up with an elegant recreation of the search bar component in Thunderbird. The clear button doesn't appear until there is text in the box, so that screen-shot is a bit inaccurate.

Should I use a layered pane and get some buttons to float above the box? (but then getting the text to not appear below the buttons would be hacky)

Maybe just put buttons at the ends of the search bar and have it somehow blend in?

Any ideas or maybe a style reconsideration is welcome, thank you.

答: For building a very similar component I've used JXLayer (for drawing the buttons) in conjunction with IntelliHints from JIDE OSS project (for implementing a drop down list of values).</p>


问:
Dismiss keyboard on the Textfield - Custom TableCell
I have a custom cell and in the custom cell, I have a textfield where user can able to change the value. No matter, what I tried, I cannot able to dismiss the keyboard when user enters some values. It does not hit any of the delegate methods shown below.

CheckOutTableViewCell.m

```<code>#import "CheckOutTableViewCell.h"

@implementation CheckOutTableViewCell
@synthesize productName;
@synthesize productPrice;
@synthesize productOrderNumberTF;

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

-(id) init;
{
    self = [super init];
    if (!self) return nil;
    productOrderNumberTF.delegate = (id)self;
    return self;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // enter closes the keyboard
    if ([string isEqualToString:@"\n"])
    {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void) textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"%@", textField.text);
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

// dismiss keyboard when user clicks on anywhere on the UI
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.productOrderNumberTF resignFirstResponder];
}
</code>```

CheckOutTableViewController.m

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *cellIdentifier = @"cell";
        CheckOutTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil)
        {
            cell = [[CheckOutTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.productOrderNumberTF.delegate = (id)self;
        }
   return cell
}
</code>```

Screenshot of the ViewController

答:
Your delegate methods are not calling because of your textfield delegate value is not assigned.

Assign the delegate value inside the awakeFromNib

```<code>- (void)awakeFromNib {
    [super awakeFromNib];
    productOrderNumberTF.delegate = self;
}
</code>```

The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

Body:
I have a custom cell and in the custom cell, I have a textfield where user can able to change the value. No matter, what I tried, I cannot able to dismiss the keyboard when user enters some values. It does not hit any of the delegate methods shown below.

CheckOutTableViewCell.m

#import "CheckOutTableViewCell.h"

@implementation CheckOutTableViewCell
@synthesize productName;
@synthesize productPrice;
@synthesize productOrderNumberTF;

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

-(id) init;
{
    self = [super init];
    if (!self) return nil;
    productOrderNumberTF.delegate = (id)self;
    return self;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // enter closes the keyboard
    if ([string isEqualToString:@"\n"])
    {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void) textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"%@", textField.text);
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

// dismiss keyboard when user clicks on anywhere on the UI
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.productOrderNumberTF resignFirstResponder];
}

CheckOutTableViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *cellIdentifier = @"cell";
        CheckOutTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil)
        {
            cell = [[CheckOutTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.productOrderNumberTF.delegate = (id)self;
        }
   return cell
}

Screenshot of the ViewController

Body:
Your delegate methods are not calling because of your textfield delegate value is not assigned.

Assign the delegate value inside the awakeFromNib

- (void)awakeFromNib {
    [super awakeFromNib];
    productOrderNumberTF.delegate = self;
}

The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.


问:
Filter words in a sentence that begin with a certain range of letters
My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.

This is my code so far, however it still prints words which begin with "g" and does not print the last word.

```<code>famous_quote = input("Enter a one sentence quote: ").lower()
word = ""

for ltr in famous_quote:
    if ltr.isalpha() == True:
        word = word + ltr
    else:
        if word > "g":
            print(word)
            word = ""
        else:
            word = ""
</code>```

I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.

Sample input:

```<code>Wheresoever you go, go with all your heart
</code>```

Sample output:

```<code>WHERESOEVER
YOU
WITH
YOUR
HEART
</code>```

Algorithm I've come up with:

 - split the words by building a placeholder variable: word
 - Loop each character in the input string
 - check if character is a letter
 - add a letter to word each loop until a non-alpha char is encountered
 - if character is alpha
 - add character to word
 - non-alpha detected (space, punctuation, digit,...) defines the end of a     word and goes to else
 - else
 - check if word is greater than "g" alphabetically
 - print word
 - set word = empty string
 - or else
 - set word = empty string and build the next word
 - Hint: use .lower()
```

答:
You stated that you are not allowed to use the split() method.  I am not sure what you can use, so here's a solution (not the optimal one).

```<code>famous_quote = input("Enter a one sentence quote:") + ' '
current_word = None
for c in famous_quote:
  if ('a' <= c <= 'z') or ('A' <= c <= 'Z'):
    if current_word is None:
      current_word = c        # start a new word
    else:
      current_word += c       # append a new letter to current word
  else:
    if current_word is not None:
      f = current_word[0]     # first letter
      if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
        print(current_word)
    current_word = None
</code>```

Here is a sample run of the program. It preserves lowercase and uppercase.  It also splits words on any non-ASCII character.

```<code>Enter a one sentence quote: Whereever you go, there you are!!!
Whereever
you
there
you
</code>```

Note: Since printing is done when a non-ASCII character is encountered, a non-ASCII character is appended at the end of famous_quote.

ContentLicense: CC BY-SA 4.0

Body:
My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.

This is my code so far, however it still prints words which begin with "g" and does not print the last word.

famous_quote = input("Enter a one sentence quote: ").lower()
word = ""

for ltr in famous_quote:
    if ltr.isalpha() == True:
        word = word + ltr
    else:
        if word > "g":
            print(word)
            word = ""
        else:
            word = ""

I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.

Sample input:

Wheresoever you go, go with all your heart

Sample output:

WHERESOEVER
YOU
WITH
YOUR
HEART

Algorithm I've come up with:

 - split the words by building a placeholder variable: word
 - Loop each character in the input string
 - check if character is a letter
 - add a letter to word each loop until a non-alpha char is encountered
 - if character is alpha
 - add character to word
 - non-alpha detected (space, punctuation, digit,...) defines the end of a     word and goes to else
 - else
 - check if word is greater than "g" alphabetically
 - print word
 - set word = empty string
 - or else
 - set word = empty string and build the next word
 - Hint: use .lower()

Body:
You stated that you are not allowed to use the split() method.  I am not sure what you can use, so here's a solution (not the optimal one).

famous_quote = input("Enter a one sentence quote:") + ' '
current_word = None
for c in famous_quote:
  if ('a' <= c <= 'z') or ('A' <= c <= 'Z'):
    if current_word is None:
      current_word = c        # start a new word
    else:
      current_word += c       # append a new letter to current word
  else:
    if current_word is not None:
      f = current_word[0]     # first letter
      if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
        print(current_word)
    current_word = None

Here is a sample run of the program. It preserves lowercase and uppercase.  It also splits words on any non-ASCII character.

Enter a one sentence quote: Whereever you go, there you are!!!
Whereever
you
there
you

Note: Since printing is done when a non-ASCII character is encountered, a non-ASCII character is appended at the end of famous_quote.


问:
Can't access object variable starting with http
I have a JSON object called profile that I use in my application which I can access in my html as follows:

```{{ profile | json }}```

This gives me the following result on my screen (values omitted):

```<code>{
    "sub": "Test",
    "name": "Test",
    "nickname": "Test",
    "picture": "Test",
    "updated_at": "2017-07-05T03:34:49.038Z",
    "http://test.com/roles": [
        "admin",
        "guest"
    ]
}
</code>```

I can access all of the variables as follows:

{{ profile?.name }}

But where I have trouble is accessing the variable that begins with http. If I try:

{{ profile?.http://test.com/roles }}

I get unexpected token errors.

I am unable to change the name of this variable is there some other way I can access it.

Thank you,

答:
Similar to JavaScript, you need to use the bracket notation for object properties that do not have valid identifier names:

```<code><h3 class="name">{{ profile ? profile['http://test.com/roles'] : '' }}</h3>
</code>```

Unfortunately, the bracket notation does not support the safe navigation operator (?), so you'll have to use a ternary operator instead.

Body:
I have a JSON object called profile that I use in my application which I can access in my html as follows:

{{ profile | json }}

This gives me the following result on my screen (values omitted):

{
    "sub": "Test",
    "name": "Test",
    "nickname": "Test",
    "picture": "Test",
    "updated_at": "2017-07-05T03:34:49.038Z",
    "http://test.com/roles": [
        "admin",
        "guest"
    ]
}

I can access all of the variables as follows:

{{ profile?.name }}

But where I have trouble is accessing the variable that begins with http. If I try:

{{ profile?.http://test.com/roles }}

I get unexpected token errors.

I am unable to change the name of this variable is there some other way I can access it.

Thank you,

Body:
Similar to JavaScript, you need to use the bracket notation for object properties that do not have valid identifier names:

<h3 class="name">{{ profile ? profile['http://test.com/roles'] : '' }}</h3>

Unfortunately, the bracket notation does not support the safe navigation operator (?), so you'll have to use a ternary operator instead.


问:
How to have only unique options in select picker drop down?
I have a select picker dropdown. I'm appending option values dynamically from backend but when same values come, there are duplicate options in the drop down. I want to have only unique values in the drop down. How to check if a value already exists before appending it to the drop down?

I'm appending the value something like this:

```<code>$("#pid").append('<option value="'+strSplit[0]+'"selected="">'+strSplit[0]+'</option>');
$("#pid").selectpicker("refresh");
</code>```

答:
Use a selector to look for an existing option with the same value. If it doesn't exist, add it.</p>

```<code>if ($("#pid option[value=" + strSplit[0] + "]").length == 0){
    $("#pid").append('<option value="'+strSplit[0]+'"selected="">'+strSplit[0]+'</option>');
    $("#pid").selectpicker("refresh");
}
</code>```

Body:
I have a select picker dropdown. I'm appending option values dynamically from backend but when same values come, there are duplicate options in the drop down. I want to have only unique values in the drop down. How to check if a value already exists before appending it to the drop down?

I'm appending the value something like this:

$("#pid").append('<option value="'+strSplit[0]+'"selected="">'+strSplit[0]+'</option>');
$("#pid").selectpicker("refresh");

Body:
Use a selector to look for an existing option with the same value. If it doesn't exist, add it.

if ($("#pid option[value=" + strSplit[0] + "]").length == 0){
    $("#pid").append('<option value="'+strSplit[0]+'"selected="">'+strSplit[0]+'</option>');
    $("#pid").selectpicker("refresh");
}


问:
Insert large csv to MySQL, ignore lines with unknown characters
I have a large .csv that I'm trying to import into a MySQL database for a Django project. I'm using the django.db library to write raw sql statements such as:

```<code>LOAD DATA LOCAL INFILE 'file.csv'...
</code>```

However, I keep getting the following error:

```<code>django.db.utils.OperationalError: (1300, "Hey! Are you out tonight?")
</code>```

After grepping the .csv for the line, I realised that the error is being caused by this character: ; though I'm sure there will be other characters throwing that error after I fix this.

Running:

```<code>$ file --mime file.csv
</code>```

from a terminal, returns:

```<code>$ file.csv: text/html; charset=us-ascii
</code>```

Since the rest of my db is in UTF-8, I tried writing a python script to re-encode it, using .encode('utf-8', 'ignore') hoping that the 'ignore' would remove any symbols that gave it trouble, but it threw:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 825410: invalid continuation byte
</code>```

The thing is, I don't actually care about inserting 100% of the file into my db. I would rather just insert only the 'safe' lines that don't contain strange characters.

So ideally, I'm looking for a way to modify my LOAD DATA LOCAL INFILE sql statement so it just skips inserting any lines that give it trouble. This is optimal, since I don't want to spend time preprocessing the data.

If that isn't feasible, the next best thing is to remove any troublesome character/lines with a Python script that I could later run from my django app whenever I update my db.

If all else fails, information on how to grep out any characters that aren't UTF-8 friendly that I could write a shell script around would be useful.

答:
For , MySQL must use CHARACTER SET utf8mb4 on the column where you will be storing it, the LOAD DATA, and on the connection.

More Python notes: http://mysql.rjweb.org/doc.php/charcoll#python

E9 does not make sense.  The hex for the UTF-8 encoding for  is F09F989C.

The link on converting between character is irrelevant; only UTF-8 can be used for Emoji.

Body:
I have a large .csv that I'm trying to import into a MySQL database for a Django project. I'm using the django.db library to write raw sql statements such as:

LOAD DATA LOCAL INFILE 'file.csv'...

However, I keep getting the following error:

django.db.utils.OperationalError: (1300, "Hey! Are you out tonight?")

After grepping the .csv for the line, I realised that the error is being caused by this character: ; though I'm sure there will be other characters throwing that error after I fix this.

Running:

$ file --mime file.csv

from a terminal, returns:

$ file.csv: text/html; charset=us-ascii

Since the rest of my db is in UTF-8, I tried writing a python script to re-encode it, using .encode('utf-8', 'ignore') hoping that the 'ignore' would remove any symbols that gave it trouble, but it threw:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 825410: invalid continuation byte

The thing is, I don't actually care about inserting 100% of the file into my db. I would rather just insert only the 'safe' lines that don't contain strange characters.

So ideally, I'm looking for a way to modify my LOAD DATA LOCAL INFILE sql statement so it just skips inserting any lines that give it trouble. This is optimal, since I don't want to spend time preprocessing the data.

If that isn't feasible, the next best thing is to remove any troublesome character/lines with a Python script that I could later run from my django app whenever I update my db.

If all else fails, information on how to grep out any characters that aren't UTF-8 friendly that I could write a shell script around would be useful.


问:
How to do feature engineering for integer column?
I am working on a code assignment using Apache Spark. It's customer data analysis using Spark.

I need help to identify correct way to solve one of the query.

```<code>val bankText = sc.textFile("/tmp/resources/bank-full.csv")

case class Bank(age:Integer, job:String, marital : String, education : String, isdefault: String, balance : Integer, housing: String, loan:String, contact:String, month:String, day_of_week:String, duration: Integer, campaign:Integer, pdays:Integer, previous:Integer, poutcome:String, isSuccess:String)

val bankrdd = bankText.map(s=>s.split(";")).filter(s=>s(0)!="\"age\"").map(
s=>Bank(s(0).toInt,
 s(1).replaceAll("\"", ""),
  s(2).replaceAll("\"", ""),
   s(3).replaceAll("\"", ""),
   s(4).replaceAll("\"", ""),
  s(5).replaceAll("\"", "").toInt,
   s(6).replaceAll("\"", ""),
   s(7).replaceAll("\"", ""),
  s(8).replaceAll("\"", ""),
   s(9).replaceAll("\"", ""),
   s(10).replaceAll("\"", ""),
  s(11).replaceAll("\"", "").toInt,
   s(12).replaceAll("\"", "").toInt,
   s(13).replaceAll("\"", "").toInt,
  s(14).replaceAll("\"", "").toInt,
   s(15).replaceAll("\"", ""),
   s(16).replaceAll("\"", "")
)
)
val bankDF=bankrdd.toDF()
bankDF.printSchema()
</code>```

Dataframe looks like below.

How to do feature engineering for column age and find right age effect on campaign?

答:
I am working on a code assignment using Apache Spark.

Why don't you ask the mentor about the question then? It may help finding answers to this and future questions. Highly recommended.

How to do feature engineering for column age and find right age effect on campaign?

First of all, I'd use the latest and greatest APIs from Spark SQL and Spark MLlib. Your life would be so much easier.

With that said (and my limited understanding of practical use of Machine Learning) I think that you should use VectorAssembler transformer to assemble the feature column.

A feature transformer that merges multiple columns into a vector column.

From the official documentation about VectorAssembler:

VectorAssembler is a transformer that combines a given list of columns into a single vector column. It is useful for combining raw features and features generated by different feature transformers into a single feature vector, in order to train ML models like logistic regression and decision trees.

Body:
I am working on a code assignment using Apache Spark. It's customer data analysis using Spark.

I need help to identify correct way to solve one of the query.

val bankText = sc.textFile("/tmp/resources/bank-full.csv")

case class Bank(age:Integer, job:String, marital : String, education : String, isdefault: String, balance : Integer, housing: String, loan:String, contact:String, month:String, day_of_week:String, duration: Integer, campaign:Integer, pdays:Integer, previous:Integer, poutcome:String, isSuccess:String)

val bankrdd = bankText.map(s=>s.split(";")).filter(s=>s(0)!="\"age\"").map(
s=>Bank(s(0).toInt,
 s(1).replaceAll("\"", ""),
  s(2).replaceAll("\"", ""),
   s(3).replaceAll("\"", ""),
   s(4).replaceAll("\"", ""),
  s(5).replaceAll("\"", "").toInt,
   s(6).replaceAll("\"", ""),
   s(7).replaceAll("\"", ""),
  s(8).replaceAll("\"", ""),
   s(9).replaceAll("\"", ""),
   s(10).replaceAll("\"", ""),
  s(11).replaceAll("\"", "").toInt,
   s(12).replaceAll("\"", "").toInt,
   s(13).replaceAll("\"", "").toInt,
  s(14).replaceAll("\"", "").toInt,
   s(15).replaceAll("\"", ""),
   s(16).replaceAll("\"", "")
)
)
val bankDF=bankrdd.toDF()
bankDF.printSchema()

Dataframe looks like below.

How to do feature engineering for column age and find right age effect on campaign?


问:
Converting from an interface to an object that implements the interface?
I have an interface which is implemented by several different objects.  What I am trying to do is write a method in c# that will accept the interface object as a parameter and convert this parameter to an object that it implements so i don't have to write the same function for several different types.  Such as:

Class UnappliedCashDetails implements interface ITransactionDetail.

Constructor for ISSBatch:
```<code>public ISSBatch(List<code><ITransactionDetail></code> details)</p>

<p>public static ISSBatch GetNextReceiptBatch()
{
     List<code><UnappliedCashDetail></code> details = new List<code><UnappliedCashDetail></code>();</p>

```    /`*`some code here to populate my list`*`/

    return = new ISSBatch(details);
```

<p>}</p>

<p>```

C# does not like this.  Am i trying to use the interface wrong or just not casting correctly?

Thanks!

答:
You're passing a List<UnappliedCashDetail> to a constructor that accepts List<ITransactionDetail>. UnappliedCashDetail may very well implement ITransactionDetail, but this type of variance is not supported by C#. Consider that inside the constructor (or any other method) you could attempt to add an instance of SomeOtherTransactionDetail to your details list, except that the details list should really only accept UnappliedCashDetail, as per its declaration.

To make your code work, you need to change your declaration

```<code>List<ITransactionDetail> details = new List<ITransactionDetail>();
/* some code here to populate my list */
return new ISSBatch(details);
</code>```

Or you could simply change your constructor to accept IEnumerable<ITransactionDetail>, in which case your original List<UnappliedCashDetail> declaration would work. Variance is supported for IEnumerable<T> (note: C# 4), since it is just a sequence and cannot be added to, deleted from, etc., so there's no possibility of trying to add an AppliedCashDetail instance to a sequence of UnappliedCashDetail objects.

Body:
I have an interface which is implemented by several different objects.  What I am trying to do is write a method in c# that will accept the interface object as a parameter and convert this parameter to an object that it implements so i don't have to write the same function for several different types.  Such as:

Class UnappliedCashDetails implements interface ITransactionDetail.

Constructor for ISSBatch:

public ISSBatch(List<ITransactionDetail> details)

public static ISSBatch GetNextReceiptBatch()
{
     List<UnappliedCashDetail> details = new List<UnappliedCashDetail>();

    /`*`some code here to populate my list`*`/

    return = new ISSBatch(details);

}

C# does not like this.  Am i trying to use the interface wrong or just not casting correctly?

Thanks!

Body:
You're passing a List<UnappliedCashDetail> to a constructor that accepts List<ITransactionDetail>. UnappliedCashDetail may very well implement ITransactionDetail, but this type of variance is not supported by C#. Consider that inside the constructor (or any other method) you could attempt to add an instance of SomeOtherTransactionDetail to your details list, except that the details list should really only accept UnappliedCashDetail, as per its declaration.

To make your code work, you need to change your declaration

List<ITransactionDetail> details = new List<ITransactionDetail>();
/* some code here to populate my list */
return new ISSBatch(details);

Or you could simply change your constructor to accept IEnumerable<ITransactionDetail>, in which case your original List<UnappliedCashDetail> declaration would work. Variance is supported for IEnumerable<T> (note: C# 4), since it is just a sequence and cannot be added to, deleted from, etc., so there's no possibility of trying to add an AppliedCashDetail instance to a sequence of UnappliedCashDetail objects.


问:
Can't find BPM Composer endpoint on weblogic 11g
I have a weblogic server with 3 managed servers and an admin server

I am trying to access the bpm composer (which is shown as deployed and active)

I have looked under the Deployments > Bpm Composer > Testing (Tab) which clearly states it is running at

```<code>localhost:8103/bpm/composer
</code>```

However when I attempt to access this I am greeted with a 404.

Annoyingly I am able to access the Console & Enterprise manager, I am thinking the composer might have been hidden or obfuscated somehow as this is our production environment.

Has anyone any idea how to access, or unhide the composer?

Many thanks
Alex

答:
Let's assume that you did not find any exception in the current server log. In fact, getting a 404 indicates that the server is up, but that URL can't be resolved by the server. With this I can think of two possibilities:

Try to access with the URI 'BPM/Composer' instead of 'bpm/composer', It might not seem logical but i seem to remember in the past that the URI was case-sensitive.

If the above test URL suggests otherwise, it might be that the composer is not targeted to the server you seem to deploy. Please do review the targeting.

If the above suggest otherwise,

login to console page, navigate under Home > Summary of Deployments >BPMComposer, and go to the testing tab. Expand the /bpm/composer/ node. Under 'default' row click on the link under Test Point column.

See if the page opens.

Body:
I have a weblogic server with 3 managed servers and an admin server

I am trying to access the bpm composer (which is shown as deployed and active)

I have looked under the Deployments > Bpm Composer > Testing (Tab) which clearly states it is running at

localhost:8103/bpm/composer

However when I attempt to access this I am greeted with a 404.

Annoyingly I am able to access the Console & Enterprise manager, I am thinking the composer might have been hidden or obfuscated somehow as this is our production environment.

Has anyone any idea how to access, or unhide the composer?

Many thanks
Alex


问:
Undesired space between two different divs?
Alright, so I think I know why this is happening. As you'll see, I have placed my text boxes with background images on top of those other images via bottom. Is that bad practice? Is there a more efficient way to do it? The problem is that I need a transparent image so that you can still kind of see the picture when you hover over it and I couldn't figure out how to do that via two background images.

It works to some extent, but I think the fact that it may be bad practice comes back to bite me in the butt when the second row of images you'll see are unable to inhabit the space that the text boxes inhabited before bottom moved them. I thought that by placing them all in one div (rowTwo) I would be able to move them all as a singular unit. But they seem to refuse to move at all and aren't even contained within the div in the layout which you can see from the dotted line box which is where I would like the row to be.

Maybe this was all more than one question... And I'm sorry for that. But if someone could help to educate me that would be fantastic! Thank you so much. Here is the JSFiddle (sorry for those weird placeholder images):

.rowOne {
    padding-top: 50px;
    display: block;
    margin: auto;
    height: 415px;
    width: 1050px;
}

.rowTwo {
    display: block;
    margin: auto;
    height: 415px;
    width: 1050px;
    border-style: dotted;
}

.episodeText {
    background-image: url("fadeBox.png");
    width: 350px;
    height: 415px;
    position: relative;
    bottom: 437px;
    opacity: 0;
    transition: opacity .3s ease-in-out;
    -moz-transition: opacity .3s ease-in-out;
    -webkit-transition: opacity .3s ease-in-out;
}

.episodeText:hover {
    background-image: url("fadeBox.png");
    width: 350px;
    height: 415px;
    position: relative;
    bottom: 437px;
    opacity: 1;
    transition: opacity .3s ease-in-out;
    -moz-transition: opacity .3s ease-in-out;
    -webkit-transition: opacity .3s ease-in-out;
}

.episodeImage {
    position: relative;
    display: block;
}

.episodeText a {
    text-decoration: none;
    display: inline;
}

.episode h1 {
    font-size: 28px;
    color: white;
    padding-left: 10px;
    padding-top: 20px;
    text-align: center;
}

.episode p1 {
    font-size: 18px;
    margin-bottom: 50px;
    width: 280px;
    height:200px;
    background: none;
    color: white;
    line-height: 20px;
    text-align: inherit
}

.episode {
    display: inline;
    float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<head>
<link rel = "stylesheet" href = "dontgoogleit2.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>

<div class= logo>
<img src= "websitelogo.png">
</div>

<title>
pls dnt
</title>
    <div class="topnav" id="myTopnav">
 EPISODES
 SOURCES
 ABOUT
 CONTACT US
</div>
</head>
<body class=body>
<div class= "theEpisodes">
<div class="rowOne">
<div class="episode">
<div class= "episodeImage">
<img src="https://www.girlsgonestrong.com/wp-content/uploads/2016/07/longandlean-origin-and-insertion-example-350x415.png">
</div>
<div class= "episodeText">

<h1>
Episode 1: A Dental Disturbance
</h1>
<p1>
The first episode, and what better way to start than with a lovely little tool we use to start our day. Yes, that's right
the toothbrush. Where did it come from? Who invented it? Simple questions, unclear answers. There's a mystery afoot, and we're
going to point it out. Come one, come all and witness the birth of the most beloved and most hated of devices.
</p1>

</div>
</div>
<div class="episode">
<div class= "episodeImage">
<img src="https://www.girlsgonestrong.com/wp-content/uploads/2016/07/longandlean-origin-and-insertion-example-350x415.png">
</div>
<div class= "episodeText">

<h1>
Episode 2: A Dental Disturbance (Part II)
</h1>
<p1>
Ah yes, the exciting conclusion of our two-part series on toothbrushes. Are you on the edge of your seats?
Because a certain Saudi Arabian dentist has emailed a certain podcaster back. Yes, that's right. Hold on to
your miswaks. Plus, a dutiful dive into the murky depths of unclean mouths and minds, further investigations
into the first patented toothbrush, as well as other designs of the future and past.
</p1>

</div>
</div>
<div class="episode">
<div class= "episodeImage">
<img src="https://www.girlsgonestrong.com/wp-content/uploads/2016/07/longandlean-origin-and-insertion-example-350x415.png">
</div>
<div class= "episodeText">

<h1>
Episode 3: Nice to Meet Screw
</h1>
<p1>
Screws. So many screws. Who invented the screw? Why all of these beautiful shapes and where did they
come from? Which one's the best? All of these questions will be answered, kind of. Join us as we embark
on a journey through time. From the time of Ancient Greek mathematicians, Babylonian kings to a poor man
ahead of his time, a happy-go-lucky Canadian and crafty manufacturers.
</p1>

</div>
</div>
</div>
<div class="rowTwo">
<div class="episode">
<div class= "episodeImage">
<img src="https://www.girlsgonestrong.com/wp-content/uploads/2016/07/longandlean-origin-and-insertion-example-350x415.png">
</div>
<div class= "episodeText">

<h1>
Episode 4: Gothip Guys
</h1>
<p1>
Two normies discuss the roots and implications of goth culture. From the ancient tribes of Europe to the Bat Cave, we delve shallowly into a deeply misunderstood subculture. Who are the goths? What do they want? Where did they come from? Music. Literature. Art. Architecture. Don't Google It.
</p1>

</div>
</div>
<div class="episode">
<div class= "episodeImage">
<img src="https://www.girlsgonestrong.com/wp-content/uploads/2016/07/longandlean-origin-and-insertion-example-350x415.png">
</div>
<div class= "episodeText">

<h1>
Episode 5: IP-YAY
</h1>
<p1>
Things get a little out of hand as two very refined gentleman discuss the ins and outs of the beer industry--specifically craft beers and IPAs. Hear the confusing (and somewhat false) tale about where the IPA comes from. We also muse upon the definitions of the terms "craft beers" and "IPA"s. What does it all mean? What is it all pointing to? One thing is for sure, you shouldn't google it.
</p1>

</div>
</div>
<div class="episode">
<div class= "episodeImage">
<img src="https://www.girlsgonestrong.com/wp-content/uploads/2016/07/longandlean-origin-and-insertion-example-350x415.png">
</div>
<div class= "episodeText">

<h1>
Episode 6: Real Men Talk Pink
</h1>
<p1>
Pink. It's not just for girls anymore. But why was it ever a color "for girls"? How long had it been that way? Well, we'll do our best to answer all of your questions and also bloviate endlessly about our fragile male egos. From the early conception of pink, to the feminist movements, to the "Real Men Wear Pink" movement, we'll try our best to conquer the ever-shifting pink landscape.
</p1>

</div>
</div>
</div>
</div>
</body>
</html></code>```

答:
If you add height to the episode style to match the episodeText height, that blank space collapses, which I think is what you want:</p>

```<code>episode {
    display: inline;
    float: left;
    height: 415px;
}
</code>```

Body:
Alright, so I think I know why this is happening. As you'll see, I have placed my text boxes with background images on top of those other images via bottom. Is that bad practice? Is there a more efficient way to do it? The problem is that I need a transparent image so that you can still kind of see the picture when you hover over it and I couldn't figure out how to do that via two background images.

It works to some extent, but I think the fact that it may be bad practice comes back to bite me in the butt when the second row of images you'll see are unable to inhabit the space that the text boxes inhabited before bottom moved them. I thought that by placing them all in one div (rowTwo) I would be able to move them all as a singular unit. But they seem to refuse to move at all and aren't even contained within the div in the layout which you can see from the dotted line box which is where I would like the row to be.

Maybe this was all more than one question... And I'm sorry for that. But if someone could help to educate me that would be fantastic! Thank you so much. Here is the JSFiddle (sorry for those weird placeholder images):

.rowOne {
    padding-top: 50px;
    display: block;
    margin: auto;
    height: 415px;
    width: 1050px;
}

.rowTwo {
    display: block;
    margin: auto;
    height: 415px;
    width: 1050px;
    border-style: dotted;
}

.episodeText {
    background-image: url("fadeBox.png");
    width: 350px;
    height: 415px;
    position: relative;
    bottom: 437px;
    opacity: 0;
    transition: opacity .3s ease-in-out;
    -moz-transition: opacity .3s ease-in-out;
    -webkit-transition: opacity .3s ease-in-out;
}

.episodeText:hover {
    background-image: url("fadeBox.png");
    width: 350px;
    height: 415px;
    position: relative;
    bottom: 437px;
    opacity: 1;
    transition: opacity .3s ease-in-out;
    -moz-transition: opacity .3s ease-in-out;
    -webkit-transition: opacity .3s ease-in-out;
}

.episodeImage {
    position: relative;
    display: block;
}

.episodeText a {
    text-decoration: none;
    display: inline;
}

.episode h1 {
    font-size: 28px;
    color: white;
    padding-left: 10px;
    padding-top: 20px;
    text-align: center;
}

.episode p1 {
    font-size: 18px;
    margin-bottom: 50px;
    width: 280px;
    height:200px;
    background: none;
    color: white;
    line-height: 20px;
    text-align: inherit
}

.episode {
    display: inline;
    float: left;
}

<!DOCTYPE html>

<link rel = "stylesheet" href = "dontgoogleit2.css">

<title>
pls dnt
</title>

 EPISODES
 SOURCES
 ABOUT
 CONTACT US

Episode 1: A Dental Disturbance

<p1>
The first episode, and what better way to start than with a lovely little tool we use to start our day. Yes, that's right
the toothbrush. Where did it come from? Who invented it? Simple questions, unclear answers. There's a mystery afoot, and we're
going to point it out. Come one, come all and witness the birth of the most beloved and most hated of devices.
</p1>

Episode 2: A Dental Disturbance (Part II)

<p1>
Ah yes, the exciting conclusion of our two-part series on toothbrushes. Are you on the edge of your seats?
Because a certain Saudi Arabian dentist has emailed a certain podcaster back. Yes, that's right. Hold on to
your miswaks. Plus, a dutiful dive into the murky depths of unclean mouths and minds, further investigations
into the first patented toothbrush, as well as other designs of the future and past.
</p1>

Episode 3: Nice to Meet Screw

<p1>
Screws. So many screws. Who invented the screw? Why all of these beautiful shapes and where did they
come from? Which one's the best? All of these questions will be answered, kind of. Join us as we embark
on a journey through time. From the time of Ancient Greek mathematicians, Babylonian kings to a poor man
ahead of his time, a happy-go-lucky Canadian and crafty manufacturers.
</p1>

Episode 4: Gothip Guys

<p1>
Two normies discuss the roots and implications of goth culture. From the ancient tribes of Europe to the Bat Cave, we delve shallowly into a deeply misunderstood subculture. Who are the goths? What do they want? Where did they come from? Music. Literature. Art. Architecture. Don't Google It.
</p1>

Episode 5: IP-YAY

<p1>
Things get a little out of hand as two very refined gentleman discuss the ins and outs of the beer industry--specifically craft beers and IPAs. Hear the confusing (and somewhat false) tale about where the IPA comes from. We also muse upon the definitions of the terms "craft beers" and "IPA"s. What does it all mean? What is it all pointing to? One thing is for sure, you shouldn't google it.
</p1>

Episode 6: Real Men Talk Pink

<p1>
Pink. It's not just for girls anymore. But why was it ever a color "for girls"? How long had it been that way? Well, we'll do our best to answer all of your questions and also bloviate endlessly about our fragile male egos. From the early conception of pink, to the feminist movements, to the "Real Men Wear Pink" movement, we'll try our best to conquer the ever-shifting pink landscape.
</p1>

Body:
If you add height to the episode style to match the episodeText height, that blank space collapses, which I think is what you want:

episode {
    display: inline;
    float: left;
    height: 415px;
}


问:
How to concatenate unrelated queries in SqlAlchemy
How can I concatenate sqlalchemy queries with no relation and sort by date?

e.g.
These are the models:

```<code>Human
Car
Tree
</code>```

And they all have the column created. Here are the queries:

```<code>q1 = session.query(Human.created.label('created'), Human).filter(...)
q2 = session.query(Car.created.label('created'), Car).filter(...)
q3 = session.query(Tree.created.label('created'), Tree).filter(...)
</code>```

Now I want to concatenate these 3 queries and order_by date. The expected result would be something like:

```<code>date      | instance
----------------------------
<created> | Human<instance>
<created> | Car<instance>
<created> | Car<instance>
<created> | Tree<instance>
<created> | Human<instance>
...
</code>```

答:
Based on the information provided I'm geussing you want to perform a union (https://www.w3schools.com/sql/sql_union.asp) on the different tables.

In the example below the different tables are created, a union of these different tables is made.

```<code>from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from datetime import datetime

Base = declarative_base()

class Human(Base):
    __tablename__ = 'human'
    id = Column('id', Integer, primary_key=True)
    created = Column('created', DateTime)
    name = Column('name', String(250))

    def __init__(self, created, name):
        self.created = created
        self.name = name

    def __repr__(self):
        return '<{created} - {name}>'.format(created=self.created, name=self.name)

class Car(Base):
    __tablename__ = 'car'
    id = Column('id', Integer, primary_key=True)
    created = Column('created', DateTime)
    brand = Column(String(250))

    def __init__(self, created, brand):
        self.created = created
        self.brand = brand

    def __repr__(self):
        return '<{created} - {brand}>'.format(created=self.created, brand=self.brand)

class Tree(Base):
    __tablename__ = 'tree'
    id = Column('id', Integer, primary_key=True)
    created = Column('created', DateTime)
    type = Column(String(250))

    def __init__(self, created, type):
        self.created = created
        self.type = type

    def __repr__(self):
        return '<{created} - {type}>'.format(created=self.created, type=self.type)

engine = create_engine('sqlite:///')
session = sessionmaker()
session.configure(bind=engine)
ex_ses = session()
Base.metadata.create_all(engine)

human = Human(datetime.now(), 'Human a')
human2 = Human(datetime.now(), 'Human b')
car = Car(datetime.now(), 'Car a')
car2 = Car(datetime.now(), 'Car b')
tree = Tree(datetime.now(), 'Tree a')
tree2 = Tree(datetime.now(), 'Tree b')

ex_ses.add(human)
ex_ses.add(human2)
ex_ses.add(car)
ex_ses.add(car2)
ex_ses.add(tree)
ex_ses.add(tree2)
ex_ses.commit()

# Query
h = ex_ses.query(Human.created, 'name')
c = ex_ses.query(Car.created, 'brand')
t = ex_ses.query(Tree.created, 'type')

print(h.union_all(c).union_all(t).all())
</code>```

The final query (in the print statement) returns:

```<code>[(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Human a'),
(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Human b'),
(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Car a'),
(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Car b'),
(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Tree a'),
(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Tree b')]
</code>```

This answer is based on: How to union across multiple tables in SQLAlchemy?

Body:
How can I concatenate sqlalchemy queries with no relation and sort by date?

e.g.
These are the models:

Human
Car
Tree

And they all have the column created. Here are the queries:

q1 = session.query(Human.created.label('created'), Human).filter(...)
q2 = session.query(Car.created.label('created'), Car).filter(...)
q3 = session.query(Tree.created.label('created'), Tree).filter(...)

Now I want to concatenate these 3 queries and order_by date. The expected result would be something like:

date      | instance
----------------------------
<created> | Human<instance>
<created> | Car<instance>
<created> | Car<instance>
<created> | Tree<instance>
<created> | Human<instance>
...

Body:
Based on the information provided I'm geussing you want to perform a union (https://www.w3schools.com/sql/sql_union.asp) on the different tables.

In the example below the different tables are created, a union of these different tables is made.

from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from datetime import datetime

Base = declarative_base()

class Human(Base):
    __tablename__ = 'human'
    id = Column('id', Integer, primary_key=True)
    created = Column('created', DateTime)
    name = Column('name', String(250))

    def __init__(self, created, name):
        self.created = created
        self.name = name

    def __repr__(self):
        return '<{created} - {name}>'.format(created=self.created, name=self.name)

class Car(Base):
    __tablename__ = 'car'
    id = Column('id', Integer, primary_key=True)
    created = Column('created', DateTime)
    brand = Column(String(250))

    def __init__(self, created, brand):
        self.created = created
        self.brand = brand

    def __repr__(self):
        return '<{created} - {brand}>'.format(created=self.created, brand=self.brand)

class Tree(Base):
    __tablename__ = 'tree'
    id = Column('id', Integer, primary_key=True)
    created = Column('created', DateTime)
    type = Column(String(250))

    def __init__(self, created, type):
        self.created = created
        self.type = type

    def __repr__(self):
        return '<{created} - {type}>'.format(created=self.created, type=self.type)

engine = create_engine('sqlite:///')
session = sessionmaker()
session.configure(bind=engine)
ex_ses = session()
Base.metadata.create_all(engine)

human = Human(datetime.now(), 'Human a')
human2 = Human(datetime.now(), 'Human b')
car = Car(datetime.now(), 'Car a')
car2 = Car(datetime.now(), 'Car b')
tree = Tree(datetime.now(), 'Tree a')
tree2 = Tree(datetime.now(), 'Tree b')

ex_ses.add(human)
ex_ses.add(human2)
ex_ses.add(car)
ex_ses.add(car2)
ex_ses.add(tree)
ex_ses.add(tree2)
ex_ses.commit()

# Query
h = ex_ses.query(Human.created, 'name')
c = ex_ses.query(Car.created, 'brand')
t = ex_ses.query(Tree.created, 'type')

print(h.union_all(c).union_all(t).all())

The final query (in the print statement) returns:

[(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Human a'),
(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Human b'),
(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Car a'),
(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Car b'),
(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Tree a'),
(datetime.datetime(2017, 7, 5, 5, 55, 54, 633863), 'Tree b')]

This answer is based on: How to union across multiple tables in SQLAlchemy?


问:
code not working despite following exact instructions
I'm new to programming with Javascript, and I am building a simple ping-pong game with the help of a video. I have followed every instruction in the video yet it doesn't seem to be working. ballX is supposed to reset in the middle once it goes past the canvas width, but the X is supposed to reverse if it hits the right paddle.

```<code>if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  if (ballX > canvas.width) {
    if (ballY > paddle2Y &&
      ballY < paddleHeight + paddle2Y) {
      ballXSpeed = -ballXSpeed;
    } else {
      ballReset();
    }
  }
}; //ends movement();
</code>```

答:
I suspect it could be some parenthesis issues.</p>

```<code>if (ballX < 0) {
  if ((ballY > paddle1Y) &&
    ((ballY < paddle1Y) + paddleHeight))) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
} // added
if (ballX > canvas.width) { // this probably should be an else if but it really doesn't matter
  if ((ballY > paddle2Y) &&
    ((ballY < paddleHeight) + paddle2Y))) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  // a } removed from here
} //ends movement();
</code>```

Body:
I'm new to programming with Javascript, and I am building a simple ping-pong game with the help of a video. I have followed every instruction in the video yet it doesn't seem to be working. ballX is supposed to reset in the middle once it goes past the canvas width, but the X is supposed to reverse if it hits the right paddle.

if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  if (ballX > canvas.width) {
    if (ballY > paddle2Y &&
      ballY < paddleHeight + paddle2Y) {
      ballXSpeed = -ballXSpeed;
    } else {
      ballReset();
    }
  }
}; //ends movement();

Body:
I suspect it could be some parenthesis issues.

if (ballX < 0) {
  if ((ballY > paddle1Y) &&
    ((ballY < paddle1Y) + paddleHeight))) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
} // added
if (ballX > canvas.width) { // this probably should be an else if but it really doesn't matter
  if ((ballY > paddle2Y) &&
    ((ballY < paddleHeight) + paddle2Y))) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  // a } removed from here
} //ends movement();


问:
SetTimout not properly functioning
I am working on project where I am currently trying to execute for loop statements with five seconds interval. Here is what I came up so far ...

$(document).ready(function(){
    $("#start").click(function(){
        for(var i = 0; i < 5; i++){
            setTimeout(function(){
                console.log("hello world")
            },5000)
        }
    })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="start">
start
</button></code>```

The issue here is that alert shows up five times in a row instead of every five seconds.
My goal here is to alert hello world every five seconds for five times.
Could you help me figure out what I am missing?

答:
I've updated the answer using setInterval and instead of for loop you can pass data runTimer method

function runTimer(callback, delay, repeat) {
    var i = 0;
    var timer = setInterval(function () {
       callback();
       i++;
       if (i == repeat) clearInterval(timer);
    }, delay);
}

$(document).ready(function(){
 $("#start").click(function(){
          runTimer(function(){
           alert('hello')
          }, 5000, 5);
       })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="start">
start
</button></code>```

Title: SetTimout not properly functioning

Body:
I am working on project where I am currently trying to execute for loop statements with five seconds interval. Here is what I came up so far ...

$(document).ready(function(){
    $("#start").click(function(){
        for(var i = 0; i < 5; i++){
            setTimeout(function(){
                console.log("hello world")
            },5000)
        }
    })
})

<button id="start">
start
</button>

The issue here is that alert shows up five times in a row instead of every five seconds.
My goal here is to alert hello world every five seconds for five times.
Could you help me figure out what I am missing?

Body:
I've updated the answer using setInterval and instead of for loop you can pass data runTimer method

function runTimer(callback, delay, repeat) {
    var i = 0;
    var timer = setInterval(function () {
       callback();
       i++;
       if (i == repeat) clearInterval(timer);
    }, delay);
}

$(document).ready(function(){
 $("#start").click(function(){
          runTimer(function(){
           alert('hello')
          }, 5000, 5);
       })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="start">
start
</button>


问:
Two DIVS keep distance when overlaps each other
I have two DIVS which html code is given

function collision($div1, $div2) {
 var x1 = $div1.offset().left;
 var y1 = $div1.offset().top;
 var h1 = $div1.outerHeight(true);
 var w1 = $div1.outerWidth(true);
 var b1 = y1 + h1;
 var r1 = x1 + w1;
 var x2 = $div2.offset().left;
 var y2 = $div2.offset().top;
 var h2 = $div2.outerHeight(true);
 var w2 = $div2.outerWidth(true);
 var b2 = y2 + h2;
 var r2 = x2 + w2;

 if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
 return true;
}

window.setInterval(function () {
 $('#result').text(collision($('#div1'), $('#div2')));
 if (collision($('#div1'), $('#div2')) == true) {
  $('#div1').addClass('touch');
  $('#div2').addClass('touch');
  $('#div1,#div2').css();
 }
 if (collision($('#div1'), $('#div2')) == false) {
  $('#div2').addClass("remTouch");
  $('#div1').addClass('remTouch');
 }
}, 200);

$('#div1').draggable();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.touch{
    margin:20px;
    transition: margin 1s;
}
.remTouch{
    margin:-20x;
    transition: margin 1s;
}
#div1 {
    width: 100px; height: 100px; background-color: pink;
    border-radius: 50%;
    opacity: 0.7;
}
#div2 {
    width: 200px; height: 200px; background-color: green;
    border-radius: 50%;
    opacity: 0.7;
}</code>```

<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />

Colliding? false

```

Now the problem is that when i move the small div towards the bigger one, after overlapping it moves but while during false condition nothing happens, I mean when condition is false i want to move the bigger div back to its position. More specifically i want the bigger div to run away smoothly from the smaller div and keep a little distance. I want to do it just like UC browser has done it. Thank you so much in advance.

答:
I have updated the fiddle.
https://jsfiddle.net/uv4uurzn/3/
JS change:

```<code>  var newTop =  $('#div1').offset().top + 150;
  var newLeft =  $('#div1').offset().left + 10;
  console.log(newTop);
  $('#div2').css('top', newTop);
  $('#div2').css('left', newLeft);
</code>```

CSS update:#div2 {
      width: 200px; height: 200px; background-color: green;
      position: fixed;
      top: 150px;
      left: 10px;
      border-radius: 50%;
      opacity: 0.7;
      -moz-transition: all 250ms ease-out;
      -webkit-transition: all 250ms ease-out;
    }

you can set div to fixed position and set top left as per your desire.

Body:
I have two DIVS which html code is given

function collision($div1, $div2) {
 var x1 = $div1.offset().left;
 var y1 = $div1.offset().top;
 var h1 = $div1.outerHeight(true);
 var w1 = $div1.outerWidth(true);
 var b1 = y1 + h1;
 var r1 = x1 + w1;
 var x2 = $div2.offset().left;
 var y2 = $div2.offset().top;
 var h2 = $div2.outerHeight(true);
 var w2 = $div2.outerWidth(true);
 var b2 = y2 + h2;
 var r2 = x2 + w2;

 if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
 return true;
}

window.setInterval(function () {
 $('#result').text(collision($('#div1'), $('#div2')));
 if (collision($('#div1'), $('#div2')) == true) {
  $('#div1').addClass('touch');
  $('#div2').addClass('touch');
  $('#div1,#div2').css();
 }
 if (collision($('#div1'), $('#div2')) == false) {
  $('#div2').addClass("remTouch");
  $('#div1').addClass('remTouch');
 }
}, 200);

$('#div1').draggable();

.touch{
    margin:20px;
    transition: margin 1s;
}
.remTouch{
    margin:-20x;
    transition: margin 1s;
}
#div1 {
    width: 100px; height: 100px; background-color: pink;
    border-radius: 50%;
    opacity: 0.7;
}
#div2 {
    width: 200px; height: 200px; background-color: green;
    border-radius: 50%;
    opacity: 0.7;
}

<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />

Colliding? false

Now the problem is that when i move the small div towards the bigger one, after overlapping it moves but while during false condition nothing happens, I mean when condition is false i want to move the bigger div back to its position. More specifically i want the bigger div to run away smoothly from the smaller div and keep a little distance. I want to do it just like UC browser has done it. Thank you so much in advance.

Body:
I have updated the fiddle.
https://jsfiddle.net/uv4uurzn/3/
JS change:

  var newTop =  $('#div1').offset().top + 150;
  var newLeft =  $('#div1').offset().left + 10;
  console.log(newTop);
  $('#div2').css('top', newTop);
  $('#div2').css('left', newLeft);

CSS update:#div2 {
      width: 200px; height: 200px; background-color: green;
      position: fixed;
      top: 150px;
      left: 10px;
      border-radius: 50%;
      opacity: 0.7;
      -moz-transition: all 250ms ease-out;
      -webkit-transition: all 250ms ease-out;
    }

you can set div to fixed position and set top left as per your desire.


问:
Meteor cross platform: different output on web and iOS
I am trying to run the code for website and mobile app(iOS). I am using meteor with react and redux as well.

When I run on web, condition 1 becomes true and it runs. When I run on mobile (simulator iOS), the condition 1 becomes false and it prints running here.
I am very confused in this problem. What I think is that as website loads slowly as compared to mobile app, the list is prepared by call to method.js and thus, condition 1 becomes true. But for mobile, it is not happening.

```<code>const mapStateToProps = (state) => {
   return {
      List: state.State.List
   }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getList(Id){
      dispatch(getList(Id))
    },
  }
}
componentWillReceiveProps(nextProps) {

    let Id = nextProps.chapter[0].listOf;
    this.props.getList(Id)
  }
}
             {this.props.list && !_.isEmpty(this.props.list) //condition 1
              ?

              this.props.list.map((title) => (
                <Tile
                  key={title._id}
                  onClick={()=>{
                    this.openPlay(title)
                  }}
                >
                </Tile>
              ))
              :
              <div>
                {this.props.list && lodash.get(this.props.list, 'length') === 0?
                  <span>nothing available</span>
                  :
                  <span> running here </span>

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

答: Try putting this function as a callback when your list gets ready</p>

Body:
I am trying to run the code for website and mobile app(iOS). I am using meteor with react and redux as well.

When I run on web, condition 1 becomes true and it runs. When I run on mobile (simulator iOS), the condition 1 becomes false and it prints running here.
I am very confused in this problem. What I think is that as website loads slowly as compared to mobile app, the list is prepared by call to method.js and thus, condition 1 becomes true. But for mobile, it is not happening.

const mapStateToProps = (state) => {
   return {
      List: state.State.List
   }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getList(Id){
      dispatch(getList(Id))
    },
  }
}
componentWillReceiveProps(nextProps) {

    let Id = nextProps.chapter[0].listOf;
    this.props.getList(Id)
  }
}
             {this.props.list && !_.isEmpty(this.props.list) //condition 1
              ?

              this.props.list.map((title) => (
                <Tile
                  key={title._id}
                  onClick={()=>{
                    this.openPlay(title)
                  }}
                >
                </Tile>
              ))
              :

                {this.props.list && lodash.get(this.props.list, 'length') === 0?
                  nothing available
                  :
                   running here

                }

            }