问:
Initialization of a Static Map: null value returned
Following the answers of this question: How can I initialise a static Map? I'm trying to create a static Map in my project.
 Below a code snippet:

```<code>public class MyClass {

    public static final Map<String, String> dataMap;

    static {
        Map<String, String> tempMap = new HashMap<String, String>();
        try {
           // Getting a string value from a file, e.g. String data
           String data = "data";
           tempMap.put("firstData", data);
        }
        catch(Exception e) {}

        dataMap = Collections.unmodifiableMap(tempMap);

        //DEBUG (I test it and it correctly prints "data")
        System.out.println(dataMap.get("firstData"));
     }
}
</code>```

Then I call the map in another class, like this:

```<code>public class AnotherClass {

   @Before
   public void MyMethod() {
      System.out.println(MyClass.dataMap.get("firstData"));
   }

   @Test
   public void testMethod() {}
}
</code>```

Now it prints null, instead of the value "data".

Why?

答:
When I executing the same code on my machine it's work and print data twice as you excpected , This code is not your problem.

UPDATE:
maybe MyClass refer to another MyClass in your package?
check your imports..
try to compile in and run it from the command line and check if you get the same results , there is something you missing here

Body:
Following the answers of this question: How can I initialise a static Map? I'm trying to create a static Map in my project.
 Below a code snippet:

public class MyClass {

    public static final Map<String, String> dataMap;

    static {
        Map<String, String> tempMap = new HashMap<String, String>();
        try {
           // Getting a string value from a file, e.g. String data
           String data = "data";
           tempMap.put("firstData", data);
        }
        catch(Exception e) {}

        dataMap = Collections.unmodifiableMap(tempMap);

        //DEBUG (I test it and it correctly prints "data")
        System.out.println(dataMap.get("firstData"));
     }
}

Then I call the map in another class, like this:

public class AnotherClass {

   @Before
   public void MyMethod() {
      System.out.println(MyClass.dataMap.get("firstData"));
   }

   @Test
   public void testMethod() {}
}

Now it prints null, instead of the value "data".

Why?


来源: stackexchange

问:
How to link collection view scroll to mapkit annotation
I'm building an app in swift that has a collection view and a map view on the same page. The user can scroll through the collection view to see offers (this is the purpose of the app) and the map view is populated with annotation pins displaying the physical location of the offers on the map.

My issue is that i'm finding it hard to link the collection view cell to the correct annotation. I use:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

    let row = indexPath.row

    self.mapView.selectAnnotation(self.mapView.annotations[row], animated: true)
}
</code>```

in order to link to the annotation. But the index path does not often link to the relevant annotation. I've read elsewhere on this site that the annotation indexes are not ordered and the users location data also messes up this order.

I'd like to be able to link the cell to the annotation but am at a loss on how to do this. Any help would be most appreciated.

答:
How about maintaining your own annotation objects and collectionView dataSources by yourself instead of reading it from MKMapView's annotations property?

I'm guessing that the main problem is:

The order of annotation object's of MKMapView is not same with the collectionView dataSource you use, so you will pick the wrong annotation object.

Sorry I'm not quite familiar in Swift yet, I'll express my thought in Obj-C

I assume you have a bunch of instances of Order class stored in an array called orders

Declare an array to store annotation objects

@property (nonatomic, strong) NSMutableArray *annotations;

Create annotations from your Order objects

```<code>for (Order *order in self.orders) {
    MKAnnotation *annotation = [[MKAnnotation alloc] init];
    [self.annotations addObject:annotation];
}
[self.mapView addAnnotations:self.annotations];
</code>```

Remember to read your order objects from orders array for collectionView,

```<code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    Order *order = [self.orders objectAtIndex:indexPath.row];
    [self.mapView selectAnnotation:self.annotations[indexPath.row] animated:YES];
}
</code>```

When you want to select your annotations, pick it from the annotations array.

This way, we can guarantee that when cellForItemAtIndexPath is called, the order of annotation objects and Order objects were same, because they were added in the same order.

ContentLicense: CC BY-SA 3.0

Body:
I'm building an app in swift that has a collection view and a map view on the same page. The user can scroll through the collection view to see offers (this is the purpose of the app) and the map view is populated with annotation pins displaying the physical location of the offers on the map.

My issue is that i'm finding it hard to link the collection view cell to the correct annotation. I use:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

    let row = indexPath.row

    self.mapView.selectAnnotation(self.mapView.annotations[row], animated: true)
}

in order to link to the annotation. But the index path does not often link to the relevant annotation. I've read elsewhere on this site that the annotation indexes are not ordered and the users location data also messes up this order.

I'd like to be able to link the cell to the annotation but am at a loss on how to do this. Any help would be most appreciated.

Body:
How about maintaining your own annotation objects and collectionView dataSources by yourself instead of reading it from MKMapView's annotations property?

I'm guessing that the main problem is:

The order of annotation object's of MKMapView is not same with the collectionView dataSource you use, so you will pick the wrong annotation object.

Sorry I'm not quite familiar in Swift yet, I'll express my thought in Obj-C

I assume you have a bunch of instances of Order class stored in an array called orders

Declare an array to store annotation objects

@property (nonatomic, strong) NSMutableArray *annotations;

Create annotations from your Order objects

for (Order *order in self.orders) {
    MKAnnotation *annotation = [[MKAnnotation alloc] init];
    [self.annotations addObject:annotation];
}
[self.mapView addAnnotations:self.annotations];

Remember to read your order objects from orders array for collectionView,

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    Order *order = [self.orders objectAtIndex:indexPath.row];
    [self.mapView selectAnnotation:self.annotations[indexPath.row] animated:YES];
}

When you want to select your annotations, pick it from the annotations array.

This way, we can guarantee that when cellForItemAtIndexPath is called, the order of annotation objects and Order objects were same, because they were added in the same order.


问:
Rails + Vue: Accessing instance variable
I have a simple view, but Purchase belongs to :client.  Therefore to access the purchases I need to provide a client_id.  :

```<code>$(document).ready(function() {
  var purchases = new Vue({
    el: '#purchases',
    data: {
      purchases: []
    },
    ready: function() {
      var that;
      that = this;
      $.ajax({
        url: 'clients/' + CLIENT_ID + '/purchases.json', // problem
        success: function(res) {
          console.log(res)
          that.purchases = res;
        }
      });
    }
  });
});
</code>```

How do I access the client_id in the ajax request?  I tried <%= @client.id %> but it get the error undefined methodid' for nil:NilClass`.

How do I pass that variable?

答:
The answer to the question is you cant access an instance variable directly in a js function. This is because js is a client side language which only runs in your browser and ruby/rails is a server side language.

The only way you can access the variable in js is by passing it as an html data. For eg as a hidden field in your corresponding html.erb file.

```<code><%= hidden_field_tag('client_id', @client_id) %>
</code>```

and accessing it as

```<code>client_id: $('#client_id').val()
</code>```

in the js file.

Body:
I have a simple view, but Purchase belongs to :client.  Therefore to access the purchases I need to provide a client_id.  :

$(document).ready(function() {
  var purchases = new Vue({
    el: '#purchases',
    data: {
      purchases: []
    },
    ready: function() {
      var that;
      that = this;
      $.ajax({
        url: 'clients/' + CLIENT_ID + '/purchases.json', // problem
        success: function(res) {
          console.log(res)
          that.purchases = res;
        }
      });
    }
  });
});

How do I access the client_id in the ajax request?  I tried <%= @client.id %> but it get the error undefined methodid' for nil:NilClass`.

How do I pass that variable?

Body:
The answer to the question is you cant access an instance variable directly in a js function. This is because js is a client side language which only runs in your browser and ruby/rails is a server side language.

The only way you can access the variable in js is by passing it as an html data. For eg as a hidden field in your corresponding html.erb file.

<%= hidden_field_tag('client_id', @client_id) %>

and accessing it as

client_id: $('#client_id').val()

in the js file.


问:
Find all posts with more than a defined number of comments
I have a simple rails 3 blog app where posts have many comments and comments belong to a post.

I want to create a scope that will fetch all posts that have more than 5 comments.
What's the best way of doing this without a counter cache column.

答:
Great answer from noodl... thanks for that!

I needed to find - to stick with the example classes of the original question - the 4 posts that were most recently commented on... a slight variant of noodl's answer does the trick:

```<code>Post.select('posts.*, max(comments.created_at) as last_commented_at').
  joins(:comments).
  group('posts.id').
  order('last_commented_at DESC').
  limit(4)
</code>```

Thanks!

ContentLicense: CC BY-SA 2.5

Body:
Great answer from noodl... thanks for that!

I needed to find - to stick with the example classes of the original question - the 4 posts that were most recently commented on... a slight variant of noodl's answer does the trick:

Post.select('posts.*, max(comments.created_at) as last_commented_at').
  joins(:comments).
  group('posts.id').
  order('last_commented_at DESC').
  limit(4)

Thanks!


问:
Can't vertically center text in a table cell
I'm creating a website for a school project using HTML and CSS. In the header there is a table and I need a text (which is inside a cell) to be aligned on the vertical center and on the horizontal right.

This is the HTML code

```<code><table id="intestazione">
........
    <tr>
        <td class="centerV"><h1>Text</h1></td>
        <td><img src="Logo.jpg"></td>
    </tr>
</table>
</code>```

and this is the CSS code

```<code>h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;
    text-align:right;
}
.centerV
{
    display:table-cell;
    vertical-align:middle;
}
</code>```

but it doesn't work as I want, so I changed the CSS code into

```<code>h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;

    display:table-cell;
    vertical-align:middle;
    text-align:right;
}
</code>```

and the text is vertically centered, but not on the right (it is on the left). I've read that I can use line-height or a padding on the top, but in my opinion it is more clean and elegant to use vertical-align (tell me if I am wrong).

I tried also other code from suggestions on the web but I don't write it otherwise the question will be too long.

答:
Take out display:table-cell from your h1 headings and simply apply a text-align:right to your td elements.

h1 {
  font-family: Arial;
  font-size: 50px;
  color: #009ED9;
  text-align: right;
}

.centerV {
  vertical-align: middle;
}

tr {
  border: solid red;
}

td {
  border: solid green;
  width: 100%;
}

h1 {
  font-family: Arial;
  font-size: 50px;
  color: #009ED9;
  vertical-align: middle;
  text-align: right;
}

h1 {
  border: solid red;
}

table {
  text-align: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="intestazione">
  ........
  <tr>
    <td class="centerV">
      <h1>Text</h1>
    </td>
    <td><img src="Logo.jpg"></td>
  </tr>
</table></code>```

Body:
I'm creating a website for a school project using HTML and CSS. In the header there is a table and I need a text (which is inside a cell) to be aligned on the vertical center and on the horizontal right.

This is the HTML code

........

Text

and this is the CSS code

h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;
    text-align:right;
}
.centerV
{
    display:table-cell;
    vertical-align:middle;
}

but it doesn't work as I want, so I changed the CSS code into

h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;

    display:table-cell;
    vertical-align:middle;
    text-align:right;
}

and the text is vertically centered, but not on the right (it is on the left). I've read that I can use line-height or a padding on the top, but in my opinion it is more clean and elegant to use vertical-align (tell me if I am wrong).

I tried also other code from suggestions on the web but I don't write it otherwise the question will be too long.

Body:
Take out display:table-cell from your h1 headings and simply apply a text-align:right to your td elements.

h1 {
  font-family: Arial;
  font-size: 50px;
  color: #009ED9;
  text-align: right;
}

.centerV {
  vertical-align: middle;
}

tr {
  border: solid red;
}

td {
  border: solid green;
  width: 100%;
}

h1 {
  font-family: Arial;
  font-size: 50px;
  color: #009ED9;
  vertical-align: middle;
  text-align: right;
}

h1 {
  border: solid red;
}

table {
  text-align: right;
}

<table id="intestazione">
  ........
  <tr>
    <td class="centerV">
      <h1>Text</h1>
    </td>
    <td><img src="Logo.jpg"></td>
  </tr>
</table>


问:
A weird error when passing a struct pointer to a function in C
I've written a simple C test program to practice using structs. However I can't understand what's wrong with the code; it seems that the first printout of either the integer or the double field clears both fields. What's my mistake here?

the code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Dummy {
    int i;
    double d;
    char s[8];
};

void print(struct Dummy *dummy) {
    printf("%lf ", dummy->d);
    printf("%lf ", dummy->d);
    printf("%d ", dummy->i);
    printf("%s\n", dummy->s);
}

void set(struct Dummy **dummy) {
    struct Dummy duh;
    duh.i = 1;
    duh.d = 3.14;
    strcpy(duh.s, "Hello!");
    *dummy = &duh;
}

int main(int argc, char **argv) {
    struct Dummy *dummy;
    set(&dummy);
    print(dummy);
    return 0;
}
</code>```

its output:

```<code>3.140000 0.000000 0 Hello!
</code>```

Thanks a lot!

答:
In set you assign **dummy to variable duh which is defined in the scope of the function. This means that duh will be lost at the end of the function, even if you keep a pointer to it.
To correct assign directly to the function's parameter</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Dummy {
    int i;
    double d;
    char s[8];
};

void print(struct Dummy *dummy) {
    printf("%lf ", dummy->d);
    printf("%lf ", dummy->d);
    printf("%d ", dummy->i);
    printf("%s\n", dummy->s);
}

void set(struct Dummy *dummy) {
    dummy->i = 1;
    dummy->d = 3.14;
    strcpy(dummy->s, "Hello!");
}

int main(int argc, char **argv) {
    struct Dummy dummy;
    set(&dummy);
    print(dummy);
    return 0;
}
</code>```

Body:
I've written a simple C test program to practice using structs. However I can't understand what's wrong with the code; it seems that the first printout of either the integer or the double field clears both fields. What's my mistake here?

the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Dummy {
    int i;
    double d;
    char s[8];
};

void print(struct Dummy *dummy) {
    printf("%lf ", dummy->d);
    printf("%lf ", dummy->d);
    printf("%d ", dummy->i);
    printf("%s\n", dummy->s);
}

void set(struct Dummy **dummy) {
    struct Dummy duh;
    duh.i = 1;
    duh.d = 3.14;
    strcpy(duh.s, "Hello!");
    *dummy = &duh;
}

int main(int argc, char **argv) {
    struct Dummy *dummy;
    set(&dummy);
    print(dummy);
    return 0;
}

its output:

3.140000 0.000000 0 Hello!

Thanks a lot!

Body:
In set you assign **dummy to variable duh which is defined in the scope of the function. This means that duh will be lost at the end of the function, even if you keep a pointer to it.
To correct assign directly to the function's parameter

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Dummy {
    int i;
    double d;
    char s[8];
};

void print(struct Dummy *dummy) {
    printf("%lf ", dummy->d);
    printf("%lf ", dummy->d);
    printf("%d ", dummy->i);
    printf("%s\n", dummy->s);
}

void set(struct Dummy *dummy) {
    dummy->i = 1;
    dummy->d = 3.14;
    strcpy(dummy->s, "Hello!");
}

int main(int argc, char **argv) {
    struct Dummy dummy;
    set(&dummy);
    print(dummy);
    return 0;
}


问:
How do you programmatically change the alpha of a UIVisualEffectView in a NavigationBar?
I have a scroll view that I'm using to control the alpha of other elements depending on how far down the view the user scrolls.

First, I set up the blur view. Alpha here doesn't seem to take, firstly

```<code>var effect: UIBlurEffectStyle = .light
if #available(iOS 10.0, *) {
    effect = .prominent
}
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: effect))
blurView.alpha = 0
if let navigationBar = navigationController?.navigationBar {
    blurView.frame = navigationBar.bounds
}
self.blurView = blurView
</code>```

Then in my UIScrollViewDelegate:

```<code>func scrollViewDidScroll(_ scrollView: UIScrollView) {
        var alpha = (scrollView.contentOffset.y / 200)
        alpha = alpha > 1.0 ? 1.0 : alpha

        blurView?.alpha = alpha
}
</code>```

This doesn't seem to be working either.

Any advice on how to achieve this effect? Thanks!

答:
When you read the Apple documentation you can find:

When using the UIVisualEffectView class, avoid alpha values that are
  less than 1.

In fact you should obtain also a warning:

```<code>[Warning] <UIVisualEffectView 0x7af7a3b0> is being asked to animate its opacity. This will cause the effect to appear broken until opacity returns to 1.
</code>```

P.S.: Pay attention, what I mean is that you can change the alpha of the visual effects but the view could appear as simply partially transparent rather than blurred.

If you don't believe in this documentation, you can test my little example below to a blank project and you can see that, if you change alpha value, your effect stop to work correctly:

(You can find all the project below to my GitHUB repository here)

Prepare in a blank project a navigationController connected to a viewController like this:

Put a generic image with an UIImageView to the view of your viewController, like this image:

```<code>class ViewController: UIViewController {
    var blurView: UIVisualEffectView!
    var effect: UIBlurEffectStyle = .light
    var blurEffect : UIBlurEffect!
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // This code make more transparent our navigation
        if let navigationBar = navigationController?.navigationBar {
            navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
            navigationBar.tintColor = .white
            let textAttributes = [NSForegroundColorAttributeName:UIColor.white]
            navigationBar.titleTextAttributes = textAttributes
            navigationBar.shadowImage = UIImage()
            navigationBar.backgroundColor = UIColor(red: 0.0, green: 0.3, blue: 0.5, alpha: 0.3)
            navigationBar.isTranslucent = true
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 10.0, *) {
            effect = .prominent
        } else {
            // Fallback on earlier versions
        }
        if let navigationBar = navigationController?.navigationBar {
            let noEffectView = UIVisualEffectView.init(frame: navigationBar.bounds)
            self.blurEffect = UIBlurEffect(style: effect)
            self.blurView = noEffectView
            navigationBar.addSubview(self.blurView)
            // This line below to don't blur buttons and title
            navigationBar.sendSubview(toBack: self.blurView)
            // Apply the effect:
            Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.applyBlur), userInfo: nil, repeats: false)
        }
    }
    func applyBlur() {
        print("Apply the blur effect..")
        UIView.animate(withDuration: 10.2, animations: {
            self.blurView.effect = self.blurEffect
        }, completion:{ (finished: Bool) in
            // Make test with a simple timer:
            Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(self.changeAlpha), userInfo: nil, repeats: true)
        })
    }
    func changeAlpha() {
        let startNum:CGFloat = 0.0; let stopNum:CGFloat = 200.0
        let randomNum = CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(startNum - stopNum) + min(startNum, stopNum)
        var alpha = (randomNum / 200)
        alpha = alpha > 1.0 ? 1.0 : alpha
        print("we change alpha to : \(alpha)")
        self.blurView.alpha = alpha
    }
}
</code>```

Output with the blur effect:

Output during alpha changes:

A solution:

Probably you don't want to change the alpha value but the amount of blur effect during the scrolling so the solution could be to use the new fractionComplete of UIViewPropertyAnimator property available only from iOS 10.0 (as suggested in this other SO answer)

```<code>import UIKit
@available(iOS 10.0, *)
class ViewController: UIViewController {
    var blurView: UIVisualEffectView!
    var effect: UIBlurEffectStyle = .light
    var blurEffect : UIBlurEffect!
    var animator: UIViewPropertyAnimator!
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // This code make more transparent our navigation
        if let navigationBar = navigationController?.navigationBar {
            navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
            navigationBar.tintColor = .white
            let textAttributes = [NSForegroundColorAttributeName:UIColor.white]
            navigationBar.titleTextAttributes = textAttributes
            navigationBar.shadowImage = UIImage()
            navigationBar.backgroundColor = UIColor(red: 0.0, green: 0.3, blue: 0.5, alpha: 0.3)
            navigationBar.isTranslucent = true
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
            effect = .prominent
            if let navigationBar = navigationController?.navigationBar {
                let noEffectView = UIVisualEffectView.init(frame: navigationBar.bounds)
                self.blurEffect = UIBlurEffect(style: effect)
                self.blurView = noEffectView
                navigationBar.addSubview(self.blurView)
                // This line below to don't blur buttons and title
                navigationBar.sendSubview(toBack: self.blurView)
                // Apply the effect:
                Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.applyBlur), userInfo: nil, repeats: false)
            }
    }
    func applyBlur() {
        print("Apply the blur effect..")
        animator = UIViewPropertyAnimator(duration: 0.5, curve: .linear)
        self.blurView.effect = self.blurEffect
        animator.addAnimations {
            self.blurView.effect = nil
        }
        Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(self.changeBlurFraction), userInfo: nil, repeats: true)

    }
    func changeBlurFraction() {
        let startNum:CGFloat = 0.0; let stopNum:CGFloat = 200.0
        let randomNum = CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(startNum - stopNum) + min(startNum, stopNum)
        var blurFraction = (randomNum / 200)
        blurFraction = blurFraction > 1.0 ? 1.0 : blurFraction
        print("we change the blur fraction to : \(blurFraction)")
        animator.fractionComplete = blurFraction
    }
}
</code>```

As you can see this change the blur effect not the alpha and every time the timer is fired you can see a different value of blur to your navigationBar.

The trick is to apply the blur effect and add a new animation to report the effect to nil but everytime with a new "fraction" to change the animation to that exact value of blur.

Output:

Body:
I have a scroll view that I'm using to control the alpha of other elements depending on how far down the view the user scrolls.

First, I set up the blur view. Alpha here doesn't seem to take, firstly

var effect: UIBlurEffectStyle = .light
if #available(iOS 10.0, *) {
    effect = .prominent
}
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: effect))
blurView.alpha = 0
if let navigationBar = navigationController?.navigationBar {
    blurView.frame = navigationBar.bounds
}
self.blurView = blurView

Then in my UIScrollViewDelegate:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
        var alpha = (scrollView.contentOffset.y / 200)
        alpha = alpha > 1.0 ? 1.0 : alpha

        blurView?.alpha = alpha
}

This doesn't seem to be working either.

Any advice on how to achieve this effect? Thanks!

Body:
When you read the Apple documentation you can find:

When using the UIVisualEffectView class, avoid alpha values that are
  less than 1.

In fact you should obtain also a warning:

[Warning] <UIVisualEffectView 0x7af7a3b0> is being asked to animate its opacity. This will cause the effect to appear broken until opacity returns to 1.

P.S.: Pay attention, what I mean is that you can change the alpha of the visual effects but the view could appear as simply partially transparent rather than blurred.

If you don't believe in this documentation, you can test my little example below to a blank project and you can see that, if you change alpha value, your effect stop to work correctly:

(You can find all the project below to my GitHUB repository here)

Prepare in a blank project a navigationController connected to a viewController like this:

Put a generic image with an UIImageView to the view of your viewController, like this image:

class ViewController: UIViewController {
    var blurView: UIVisualEffectView!
    var effect: UIBlurEffectStyle = .light
    var blurEffect : UIBlurEffect!
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // This code make more transparent our navigation
        if let navigationBar = navigationController?.navigationBar {
            navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
            navigationBar.tintColor = .white
            let textAttributes = [NSForegroundColorAttributeName:UIColor.white]
            navigationBar.titleTextAttributes = textAttributes
            navigationBar.shadowImage = UIImage()
            navigationBar.backgroundColor = UIColor(red: 0.0, green: 0.3, blue: 0.5, alpha: 0.3)
            navigationBar.isTranslucent = true
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 10.0, *) {
            effect = .prominent
        } else {
            // Fallback on earlier versions
        }
        if let navigationBar = navigationController?.navigationBar {
            let noEffectView = UIVisualEffectView.init(frame: navigationBar.bounds)
            self.blurEffect = UIBlurEffect(style: effect)
            self.blurView = noEffectView
            navigationBar.addSubview(self.blurView)
            // This line below to don't blur buttons and title
            navigationBar.sendSubview(toBack: self.blurView)
            // Apply the effect:
            Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.applyBlur), userInfo: nil, repeats: false)
        }
    }
    func applyBlur() {
        print("Apply the blur effect..")
        UIView.animate(withDuration: 10.2, animations: {
            self.blurView.effect = self.blurEffect
        }, completion:{ (finished: Bool) in
            // Make test with a simple timer:
            Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(self.changeAlpha), userInfo: nil, repeats: true)
        })
    }
    func changeAlpha() {
        let startNum:CGFloat = 0.0; let stopNum:CGFloat = 200.0
        let randomNum = CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(startNum - stopNum) + min(startNum, stopNum)
        var alpha = (randomNum / 200)
        alpha = alpha > 1.0 ? 1.0 : alpha
        print("we change alpha to : \(alpha)")
        self.blurView.alpha = alpha
    }
}

Output with the blur effect:

Output during alpha changes:

A solution:

Probably you don't want to change the alpha value but the amount of blur effect during the scrolling so the solution could be to use the new fractionComplete of UIViewPropertyAnimator property available only from iOS 10.0 (as suggested in this other SO answer)

import UIKit
@available(iOS 10.0, *)
class ViewController: UIViewController {
    var blurView: UIVisualEffectView!
    var effect: UIBlurEffectStyle = .light
    var blurEffect : UIBlurEffect!
    var animator: UIViewPropertyAnimator!
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // This code make more transparent our navigation
        if let navigationBar = navigationController?.navigationBar {
            navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
            navigationBar.tintColor = .white
            let textAttributes = [NSForegroundColorAttributeName:UIColor.white]
            navigationBar.titleTextAttributes = textAttributes
            navigationBar.shadowImage = UIImage()
            navigationBar.backgroundColor = UIColor(red: 0.0, green: 0.3, blue: 0.5, alpha: 0.3)
            navigationBar.isTranslucent = true
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
            effect = .prominent
            if let navigationBar = navigationController?.navigationBar {
                let noEffectView = UIVisualEffectView.init(frame: navigationBar.bounds)
                self.blurEffect = UIBlurEffect(style: effect)
                self.blurView = noEffectView
                navigationBar.addSubview(self.blurView)
                // This line below to don't blur buttons and title
                navigationBar.sendSubview(toBack: self.blurView)
                // Apply the effect:
                Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.applyBlur), userInfo: nil, repeats: false)
            }
    }
    func applyBlur() {
        print("Apply the blur effect..")
        animator = UIViewPropertyAnimator(duration: 0.5, curve: .linear)
        self.blurView.effect = self.blurEffect
        animator.addAnimations {
            self.blurView.effect = nil
        }
        Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(self.changeBlurFraction), userInfo: nil, repeats: true)

    }
    func changeBlurFraction() {
        let startNum:CGFloat = 0.0; let stopNum:CGFloat = 200.0
        let randomNum = CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(startNum - stopNum) + min(startNum, stopNum)
        var blurFraction = (randomNum / 200)
        blurFraction = blurFraction > 1.0 ? 1.0 : blurFraction
        print("we change the blur fraction to : \(blurFraction)")
        animator.fractionComplete = blurFraction
    }
}

As you can see this change the blur effect not the alpha and every time the timer is fired you can see a different value of blur to your navigationBar.

The trick is to apply the blur effect and add a new animation to report the effect to nil but everytime with a new "fraction" to change the animation to that exact value of blur.

Output:


问:
Dynamically generate multiple elements
I am trying to use JavaScript to generate a set amount of input box's dependent on the users input. However, when I do so with a for loop it just generates one input box and appends said input box a set amount of time.

```<code>function generateAttributes(){
    var y = 1;
    var mAttributes = document.getElementById('numAttributes').value;
    var parent = document.getElementsByTagName('div')[17];
    var inputBox = document.createElement('input');
    inputBox.setAttribute('class', 'form-control');
    for(var i = 0; i < mAttributes; i++){
        inputBox.setAttribute('id', y);
        inputBox.setAttribute('placeholder', 'Attribute ' + y);
        parent.appendChild(inputBox);
        y++;
    }
</code>```

}

答:
You need to create a new element for each iteration of the loop.

Move the following inside the loop:

```<code>var inputBox = document.createElement('input');
    inputBox.setAttribute('class', 'form-control');
</code>```

Result:

```<code>for(var i = 0; i < mAttributes; i++){

    var inputBox = document.createElement('input');
    inputBox.setAttribute('class', 'form-control');
    inputBox.setAttribute('id', y);
    inputBox.setAttribute('placeholder', 'Attribute ' + y);
    parent.appendChild(inputBox);
    y++;
}
</code>```

You are currently creating only one element and modifying and appending that same element over and over

Title: Dynamically generate multiple elements

Body:
I am trying to use JavaScript to generate a set amount of input box's dependent on the users input. However, when I do so with a for loop it just generates one input box and appends said input box a set amount of time.

function generateAttributes(){
    var y = 1;
    var mAttributes = document.getElementById('numAttributes').value;
    var parent = document.getElementsByTagName('div')[17];
    var inputBox = document.createElement('input');
    inputBox.setAttribute('class', 'form-control');
    for(var i = 0; i < mAttributes; i++){
        inputBox.setAttribute('id', y);
        inputBox.setAttribute('placeholder', 'Attribute ' + y);
        parent.appendChild(inputBox);
        y++;
    }

}

Body:
You need to create a new element for each iteration of the loop.

Move the following inside the loop:

var inputBox = document.createElement('input');
    inputBox.setAttribute('class', 'form-control');

Result:

for(var i = 0; i < mAttributes; i++){

    var inputBox = document.createElement('input');
    inputBox.setAttribute('class', 'form-control');
    inputBox.setAttribute('id', y);
    inputBox.setAttribute('placeholder', 'Attribute ' + y);
    parent.appendChild(inputBox);
    y++;
}

You are currently creating only one element and modifying and appending that same element over and over


问:
Image Button to open phone galllery and display picture on Android
I tried looking for code that would help me with selecting a picture from my phone's gallery to the image button in my application, however, most of it is with an Image View.

I was wondering if somebody could help me by showing me how to do this please?

答:
First in your xml create ImageButton:

```<code><ImageButton
    android:id="@+id/image_button"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="fitCenter"/>
</code>```

Then in your activity:

Create class variable:

```<code>ImageButton imageButton;
</code>```

In OnCreate method find this button and set OnClickListener:

```<code>imageButton = (ImageButton) findViewById(R.id.image_button);
imageButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, 500);
    }
});
</code>```

Override onActivityResult:

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

switch(requestCode) {
    case 500:
        if(resultCode == RESULT_OK){
            try {
                final Uri imageUri = data.getData();
                final InputStream imageStream = getActivity().getContentResolver().openInputStream(imageUri);
                final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                imageButton.setImageBitmap(selectedImage);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }
}
</code>```

Body:
First in your xml create ImageButton:

<ImageButton
    android:id="@+id/image_button"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="fitCenter"/>

Then in your activity:

Create class variable:

ImageButton imageButton;

In OnCreate method find this button and set OnClickListener:

imageButton = (ImageButton) findViewById(R.id.image_button);
imageButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, 500);
    }
});

Override onActivityResult:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

switch(requestCode) {
    case 500:
        if(resultCode == RESULT_OK){
            try {
                final Uri imageUri = data.getData();
                final InputStream imageStream = getActivity().getContentResolver().openInputStream(imageUri);
                final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                imageButton.setImageBitmap(selectedImage);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }
}


问:
MySQL select equals condition work as like condition
I got today strange results, when I use query

```<code> SELECT id, zip FROM `Locations` WHERE zip = '4000XXXXX'
</code>```

Which simply fetchs id and zip code where zip code should be equals to condition.
Schema:

```<code>zip int(11)
</code>```

I have in table rows with zip values 4000 and expected result of this query is no result.

Simply - equals condition works as like condition where there is string and type of column is int. Whats going on ?

答:
What do you expect would be the result of a string and an int?

In order to make a sensable comparison, MySql tries to cast the string to an int by taking the left most digits.

In this case the casting gives 4000, hence you'll get all the rows with zip=4000

Body:
I got today strange results, when I use query

 SELECT id, zip FROM `Locations` WHERE zip = '4000XXXXX'

Which simply fetchs id and zip code where zip code should be equals to condition.
Schema:

zip int(11)

I have in table rows with zip values 4000 and expected result of this query is no result.

Simply - equals condition works as like condition where there is string and type of column is int. Whats going on ?


问:
C++ not showing cout in Xcode console but runs perfectly in Terminal
Basically i am running a simple program in Xcode Version 8.3 (8E162)

```<code>#include <iostream>
using namespace std;
int main() {
    int a;
    cout << "What is your age: ";
    cin >> a;
    cout << "My age is " << a << endl;
    return 0;
}
</code>```

I have seen different questions about cout need to be flushed and all std::cout won't print and Xcode debugger not showing C++ cout output. The Xcode debugger does not print cout until i put \n or endl. But, it works perfectly fine on terminal.

What if i had to use What is your age: and the user input age in the single line rather than the next line putting \n and endl?

This is what the Xcode debugger shows after build and run

This is when user inputs and it displays the result

This is on the terminal and this is what exactly what i need the output on the Xcode debugger.

答:
You already solved your problem yourself: std::cout uses buffered output and should always be flushed. You can achieve this by either using std::cout << "What is your age? << std::flush, by using std::cout.flush() or by adding a line break like std::endl which flushes implicitly.

A complete solution could look like this:

```<code>#include <iostream>

using namespace std;

int main() {
    int a;
    cout << "What is your age: " << flush;
    cin >> a;
    cout << "My age is " << a << endl;
    return 0;
}
</code>```

Body:
Basically i am running a simple program in Xcode Version 8.3 (8E162)

#include <iostream>
using namespace std;
int main() {
    int a;
    cout << "What is your age: ";
    cin >> a;
    cout << "My age is " << a << endl;
    return 0;
}

I have seen different questions about cout need to be flushed and all std::cout won't print and Xcode debugger not showing C++ cout output. The Xcode debugger does not print cout until i put \n or endl. But, it works perfectly fine on terminal.

What if i had to use What is your age: and the user input age in the single line rather than the next line putting \n and endl?

This is what the Xcode debugger shows after build and run

This is when user inputs and it displays the result

This is on the terminal and this is what exactly what i need the output on the Xcode debugger.

Body:
You already solved your problem yourself: std::cout uses buffered output and should always be flushed. You can achieve this by either using std::cout << "What is your age? << std::flush, by using std::cout.flush() or by adding a line break like std::endl which flushes implicitly.

A complete solution could look like this:

#include <iostream>

using namespace std;

int main() {
    int a;
    cout << "What is your age: " << flush;
    cin >> a;
    cout << "My age is " << a << endl;
    return 0;
}


问:
Shell script to get difference between two dates
If there are dates as 2010-06-01 and another as 2010-05-15

Using shell script or date command how to get the number of days between the two dates

Thanks..

答:
OSX date is different than GNU date. Got it working like this in OSX. This is not portable solution.

```<code>start_date=$(date -j -f "%Y-%m-%d" "2010-05-15" "+%s")
end_date=$(date -j -f "%Y-%m-%d" "2010-06-01" "+%s")

echo $(( ($end_date - $start_date) / (60 * 60 * 24) ))
</code>```

Idea is still same as in the other answers. Convert dates to epoch time, subtract and convert result to days.

ContentLicense: CC BY-SA 4.0

Body:
OSX date is different than GNU date. Got it working like this in OSX. This is not portable solution.

start_date=$(date -j -f "%Y-%m-%d" "2010-05-15" "+%s")
end_date=$(date -j -f "%Y-%m-%d" "2010-06-01" "+%s")

echo $(( ($end_date - $start_date) / (60 * 60 * 24) ))

Idea is still same as in the other answers. Convert dates to epoch time, subtract and convert result to days.


问:
Printing Values In Excel
Sample Template

Please Refer the above Screenshot attached here.As i have find max Value of two numbers ,I also want to print Value whose number is max ie Hello,how do i achieve this?

答:
So you want to also print Hello or World? Am I right? Try this:

```<code>=index(a1:a3, match(d2, b1:b3, 0))
</code>```

Title: Printing Values In Excel

Body:
So you want to also print Hello or World? Am I right? Try this:

=index(a1:a3, match(d2, b1:b3, 0))


问:
request-promise causing too many sockets to be open
I am currently trying to write a function that takes in user input and returns the top subreddit that the user's comment might have belonged to based on how many times the word occurred in training data. I have a database containing frequencies of words in different subreddits, which I am making GET requests to for each subreddit and for every word in the user's input.

This adds up to many get requests, as I have over 7000 subreddits in my database. I am currently making a request-promise (shallow) request to get the list of all subreddits. Then, for each subreddit, I loop over each word in the user's input, make another request-promise object and add that to an array of promises.

Once all the request-promise objects are added, I wait until they are all resolved using Promise.all, where I then try to print out the array of word frequencies for the given subreddit, but I get an 'Error: connect EMFILE' message.

According to another post on stack overflow, this means that I have too many sockets open, but I'm confused as to how that could happen. From my understanding, wouldn't it only ever have up to user_words.length possible connections open at a time, since those are the requests that are being done while the Promise.all waits to resolve? I don't see how the connections are not being closed.

Thanks in advance for any help!

```<code>function getBestSubreddit(messageText) {
  var user_words = parse_message(messageText);
  var top_subreddit = "";
  var top_score = Number.MIN_SAFE_INTEGER;
  rp(dbUrl + '/.json?shallow=true').then(function(res) {
    res = JSON.parse(res);
    for (var subreddit in res) {
      if (res.hasOwnProperty(subreddit)) {
        var score = 0.0;
        var promises = []
        for (var i = 0; i < user_words.length; i++) {
          promises.push(rp(dbUrl + '/' + subreddit + '/word_freqs/' + user_words[i] + '.json'));
        }
        Promise.all(promises).then(function(values) {
          console.log(values);
        }, function(err) {
          console.log(err);
        });
      }
    }
  }).catch(function(err) {
    console.log(err);
  })
  return top_subreddit;
}
</code>```

答:
From my understanding, wouldn't it only ever have up to user_words.length possible connections open at a time, since those are the requests that are being done while the Promise.all waits to resolve? I don't see how the connections are not being closed.

No, this is not correct.  You have two nested for loops so you can have as many as user_words.length * how many subreddits there are all open at the same time.  Remember, rp() and Promise.all() do not block so you run the nested for loops to completion launching every single connection before any of the responses are processed.

It also looks like you're expecting to somehow synchronously return a result with the line of code return top_subreddit.  You can't do that either.  You should return a promise that will eventually resolve to the desired result.

From my understanding, wouldn't it only ever have up to user_words.length possible connections open at a time, since those are the requests that are being done while the Promise.all waits to resolve? I don't see how the connections are not being closed.

This is not the right understanding of Promise.all().  Promise.all() is not blocking.  It doesn't "wait" until all the promises are resolved before your code continues to exit.  It behaves asynchronously.  Your code continues to execute other iterations of your for loop and Promise.all() calls it's .then() handler sometime in the future when all the promises you passed it have finished.  The other iterations of your for loop continue to run and pile up more sockets.

I think the easiest way to approach this is the make an array of URLs that you want to process and then use one of the asynchronous libraries that already has a function built-in to allow you to run a max of N async operations in-flight at the same time.  Since your code is promise-based, I would choose Bluebird's Promise.map() to process the list of URLs.

```<code>var Promise = require('bluebird');

function getBestSubreddit(messageText) {
  var user_words = parse_message(messageText);
  var top_subreddit = "";
  var top_score = Number.MIN_SAFE_INTEGER;
  return rp(dbUrl + '/.json?shallow=true').then(function(res) {
    res = JSON.parse(res);
    // build a list of URLs to process
    var urls = [];
    for (var subreddit in res) {
      if (res.hasOwnProperty(subreddit)) {
        for (var i = 0; i < user_words.length; i++) {
          urls.push(dbUrl + '/' + subreddit + '/word_freqs/' + user_words[i] + '.json');
        }
      }
    }
    //
    return Promise.map(urls, function(url) {
        return rp(url);
    }, {concurrency: 20}).then(function(allResults) {
        // do any final processing of allResults here and return that value
        // to become the resolved result of the returned promise
    });
  }
}

getBestSubreddit(someText).then(function(result) {
    // process result here
}).catch(function(err) {
    // handle error here
});
</code>```

I set the number of concurrent requests to 20 in this example.  You can experiment whether changing that to a higher or lower number improves your throughput.  The ideal number is dependent upon a number of things including your local execution environment, the amount of data you are requesting and the bandwidth you have and on the target host you are making requests from and how it handles simultaneous requests.  You may also need to be concerned about rate limiting by the target if you make too many requests too quickly.

Some other related answers:

How to make millions of parallel http requests from nodejs app?

In Node js. How many simultaneous requests can I send with the "request" package

Making a million requests

It still is not clear to me from your question exactly what result you're trying to get, but here's a version that collects all the data possible.  You end up with an array of objects of this form {result: result, subreddit: subreddit, word: word} where result is the result of your rp() for a given subreddit and a given word.  You can then collate that set of results however you want:

```<code>var Promise = require('bluebird');

function getBestSubreddit(messageText) {
  var user_words = parse_message(messageText);
  var top_subreddit = "";
  var top_score = Number.MIN_SAFE_INTEGER;
  return rp(dbUrl + '/.json?shallow=true').then(function(res) {
    res = JSON.parse(res);
    // build a list of URLs to process
    var requestData = [];
    for (var subreddit in res) {
      if (res.hasOwnProperty(subreddit)) {
        for (var i = 0; i < user_words.length; i++) {
          requestData.push({url:dbUrl + '/' + subreddit + '/word_freqs/' + user_words[i] + '.json', subreddit: subreddit, word: user_words[i]});
        }
      }
    }
    //
    return Promise.map(requestData, function(url) {
        return rp(requestData.url).then(function(result) {
            return {result: result, subreddit: requestData.subreddit, word: requestData.word};
        });
    }, {concurrency: 20}).then(function(allResults) {
        // now filter through all the data with appropriate subreddit
        // allResults is an array of objects of this form {result: result, subreddit: subreddit, word: word}
        // return whatever you want the final result to be after processing the allResults array
    });
  }
}

getBestSubreddit(someText).then(function(result) {
    // process result here
}).catch(function(err) {
    // handle error here
});
</code>```

Body:
I am currently trying to write a function that takes in user input and returns the top subreddit that the user's comment might have belonged to based on how many times the word occurred in training data. I have a database containing frequencies of words in different subreddits, which I am making GET requests to for each subreddit and for every word in the user's input.

This adds up to many get requests, as I have over 7000 subreddits in my database. I am currently making a request-promise (shallow) request to get the list of all subreddits. Then, for each subreddit, I loop over each word in the user's input, make another request-promise object and add that to an array of promises.

Once all the request-promise objects are added, I wait until they are all resolved using Promise.all, where I then try to print out the array of word frequencies for the given subreddit, but I get an 'Error: connect EMFILE' message.

According to another post on stack overflow, this means that I have too many sockets open, but I'm confused as to how that could happen. From my understanding, wouldn't it only ever have up to user_words.length possible connections open at a time, since those are the requests that are being done while the Promise.all waits to resolve? I don't see how the connections are not being closed.

Thanks in advance for any help!

function getBestSubreddit(messageText) {
  var user_words = parse_message(messageText);
  var top_subreddit = "";
  var top_score = Number.MIN_SAFE_INTEGER;
  rp(dbUrl + '/.json?shallow=true').then(function(res) {
    res = JSON.parse(res);
    for (var subreddit in res) {
      if (res.hasOwnProperty(subreddit)) {
        var score = 0.0;
        var promises = []
        for (var i = 0; i < user_words.length; i++) {
          promises.push(rp(dbUrl + '/' + subreddit + '/word_freqs/' + user_words[i] + '.json'));
        }
        Promise.all(promises).then(function(values) {
          console.log(values);
        }, function(err) {
          console.log(err);
        });
      }
    }
  }).catch(function(err) {
    console.log(err);
  })
  return top_subreddit;
}

Body:
From my understanding, wouldn't it only ever have up to user_words.length possible connections open at a time, since those are the requests that are being done while the Promise.all waits to resolve? I don't see how the connections are not being closed.

No, this is not correct.  You have two nested for loops so you can have as many as user_words.length * how many subreddits there are all open at the same time.  Remember, rp() and Promise.all() do not block so you run the nested for loops to completion launching every single connection before any of the responses are processed.

It also looks like you're expecting to somehow synchronously return a result with the line of code return top_subreddit.  You can't do that either.  You should return a promise that will eventually resolve to the desired result.

From my understanding, wouldn't it only ever have up to user_words.length possible connections open at a time, since those are the requests that are being done while the Promise.all waits to resolve? I don't see how the connections are not being closed.

This is not the right understanding of Promise.all().  Promise.all() is not blocking.  It doesn't "wait" until all the promises are resolved before your code continues to exit.  It behaves asynchronously.  Your code continues to execute other iterations of your for loop and Promise.all() calls it's .then() handler sometime in the future when all the promises you passed it have finished.  The other iterations of your for loop continue to run and pile up more sockets.

I think the easiest way to approach this is the make an array of URLs that you want to process and then use one of the asynchronous libraries that already has a function built-in to allow you to run a max of N async operations in-flight at the same time.  Since your code is promise-based, I would choose Bluebird's Promise.map() to process the list of URLs.

var Promise = require('bluebird');

function getBestSubreddit(messageText) {
  var user_words = parse_message(messageText);
  var top_subreddit = "";
  var top_score = Number.MIN_SAFE_INTEGER;
  return rp(dbUrl + '/.json?shallow=true').then(function(res) {
    res = JSON.parse(res);
    // build a list of URLs to process
    var urls = [];
    for (var subreddit in res) {
      if (res.hasOwnProperty(subreddit)) {
        for (var i = 0; i < user_words.length; i++) {
          urls.push(dbUrl + '/' + subreddit + '/word_freqs/' + user_words[i] + '.json');
        }
      }
    }
    //
    return Promise.map(urls, function(url) {
        return rp(url);
    }, {concurrency: 20}).then(function(allResults) {
        // do any final processing of allResults here and return that value
        // to become the resolved result of the returned promise
    });
  }
}

getBestSubreddit(someText).then(function(result) {
    // process result here
}).catch(function(err) {
    // handle error here
});

I set the number of concurrent requests to 20 in this example.  You can experiment whether changing that to a higher or lower number improves your throughput.  The ideal number is dependent upon a number of things including your local execution environment, the amount of data you are requesting and the bandwidth you have and on the target host you are making requests from and how it handles simultaneous requests.  You may also need to be concerned about rate limiting by the target if you make too many requests too quickly.

Some other related answers:

How to make millions of parallel http requests from nodejs app?

In Node js. How many simultaneous requests can I send with the "request" package

Making a million requests

It still is not clear to me from your question exactly what result you're trying to get, but here's a version that collects all the data possible.  You end up with an array of objects of this form {result: result, subreddit: subreddit, word: word} where result is the result of your rp() for a given subreddit and a given word.  You can then collate that set of results however you want:

var Promise = require('bluebird');

function getBestSubreddit(messageText) {
  var user_words = parse_message(messageText);
  var top_subreddit = "";
  var top_score = Number.MIN_SAFE_INTEGER;
  return rp(dbUrl + '/.json?shallow=true').then(function(res) {
    res = JSON.parse(res);
    // build a list of URLs to process
    var requestData = [];
    for (var subreddit in res) {
      if (res.hasOwnProperty(subreddit)) {
        for (var i = 0; i < user_words.length; i++) {
          requestData.push({url:dbUrl + '/' + subreddit + '/word_freqs/' + user_words[i] + '.json', subreddit: subreddit, word: user_words[i]});
        }
      }
    }
    //
    return Promise.map(requestData, function(url) {
        return rp(requestData.url).then(function(result) {
            return {result: result, subreddit: requestData.subreddit, word: requestData.word};
        });
    }, {concurrency: 20}).then(function(allResults) {
        // now filter through all the data with appropriate subreddit
        // allResults is an array of objects of this form {result: result, subreddit: subreddit, word: word}
        // return whatever you want the final result to be after processing the allResults array
    });
  }
}

getBestSubreddit(someText).then(function(result) {
    // process result here
}).catch(function(err) {
    // handle error here
});


问:
Find the smallest area rectangle covering a query point
I'm working on a personal project to do with computational geometry. The question in the title is an abstraction of one of the small subproblems that I am trying, but struggling, to solve efficiently. Hopefully it's general enough to maybe be of use of more than just me!

The problem

Imagine we have a set S of rectangles in the plane, all of which have edges parallel to the coordinate axes (no rotations). For my problem we'll assume that rectangle intersections are very common. But they are also very nice: If two rectangles intersect, we can assume one of them always completely contains the other. So there's no "partial" overlaps.

I want to store these rectangles in a way that:

We can efficiently add new rectangles.

Given a query point (x,y) we can efficiently report back the
rectangle of smallest area that contains the point.

The illustration provides the motivation for the latter. We always want to find the most deeply nested rectangle that contains the query point, so that's always the one of smallest area.

My thoughts

So I know that both R-Trees and Quad-Trees are often used for spatial indexing problems, and indeed both can work well in some cases. The problem with R-Trees is that they can degrade to linear performance in the worst case.

I thought about building a set of balanced binary trees based on nestedness. The left subtree of node r contains all the rectangles that are inside rectangle r. The right subtree contains all the rectangles that r is inside of. The illustrated example would have three trees.

But what if none of the rectangles are nested? Then you need O(n) trees of 1 element and again we have something that performs just as poorly as a linear scan through the boxes.

How could I solve this in  a way that we have asymptotically sub linear time in the worst case? Even if that means sacrificing some performance in the best cases or storage requirements. (I assume for a problem like this, there may be a need to maintain two data structures and that's cool)

I am certain that the very specific way in which rectangles are allowed to intersect should help make this problem possible. In fact, it looks like a candidate for logarithmic performance to me but I'm just not getting anywhere.

Thanks in advance for any ideas you have!

答:
How about a PH-Tree? The PH-Tree is a essentially quadtree shaped like a quadtree, but with some unique properties that may be ideal for your case, such as very efficient updates and a high likelihood of locality of small rectangles.

Basics:

The PH-Tree is a bit-level try, that means it splits in all dimensions at every bit position. This means, for 64bit floating point data, the maximum depth of the tree is 64.

The tree is implicitly z-ordered

Query speed is usually comparable to R*Tree or STR-Tree, for your case it may be considerably faster, see below.

Insertion/deletion speed is equal to or better that STR-Trees and better than any other R-Tree type that I am aware of.

Tree shape is determined only by the data, not by insertion order. That means there will never be any costly rebalancing. In fact, the tree guarantees that any insertion or deletion will never affect more than two nodes (with child/parent relationship).

Storing rectangles: The PH-Tree can only store vectors of data, ie. points. In order to store (axis aligned) rectangles, it takes by default the 'lower left' and 'upper right' corner and but these into single vector. For example, a 2D rectangle (2,2)-(4,5) is stored as a 4-dim vector (2,2,4,5). It may not be obvious, but this representation still allows for efficient queries, such as window queries and nearest neighbor queries, see some results here and some more explanation here.

The tree cannot directly store the same rectangle twice. Instead you would have associate a counter with each 'key'. For the special case with 'n' identical rectangles, this actually has the advantage that the resulting tree would contain only one key, so overlap with the smallest rectangle could be determined in almost constant time.

Query performance: As can be seen from the performance results, the PH-Tree is (depending on the dataset) fastest with small query windows that return few results (here, Figure 16). I'm not sure whether the performance benefit is connected to the small query window size or the small result size. But if it is connected to the first, then your queries should be very fast, because essentially your query window is a point.

Optimising for small rectangle size: Due to the encoding of rectangles into a single vector, the smallest rectangle is likely (guaranteed??) to be in the same leaf node that would also contain your search point.
Usually, queries are traversed in z-order, so to exploit locality of small rectangles, you would need to write a special query. This should not be hard, I think I could simply use the PH-Tree k-nearest-neighbor implementation and provide a custom distance function. The current kNN starts with locating the node with the search point and then extends the search area until it found all nearest neighbors. I do believe that using a custom distance function should be sufficient, but you may have to do some research to prove it.

The complete code (Java) of the PH-Tree is available in the link above. For comparison, you may want to check out my other index implementations here (R*Tree, quadtrees, STR-Tree).


问:
dependencies of current namespace
*ns* returns a namespace, not a namespace declaration. clojure.tools.namespace.parse.deps-from-ns-decl requires a declaration. There are many ways to read declarations from files. How do I get the declaration from the current namespace (*ns*). If this helps, here's what the REPL coughs up:

```<code>(deps-from-ns-decl *ns*)
IllegalArgumentException Don't know how to create ISeq from: clojure.lang.Namespace  clojure.lang.RT.seqFrom (RT.java:542)
</code>```

答: It turns out that asking questions like this one arises out of "meta" namespace work. In conjunction with Tawny OWL ontology definitions, my app rides on top of Clojure's namespace thinking. To answer my question, I had to create a sense of namespace in the app with it's own dependency declarations. Substrate namespace constructs are just that.</p>

Title: dependencies of current namespace

Body:
*ns* returns a namespace, not a namespace declaration. clojure.tools.namespace.parse.deps-from-ns-decl requires a declaration. There are many ways to read declarations from files. How do I get the declaration from the current namespace (*ns*). If this helps, here's what the REPL coughs up:

(deps-from-ns-decl *ns*)
IllegalArgumentException Don't know how to create ISeq from: clojure.lang.Namespace  clojure.lang.RT.seqFrom (RT.java:542)


问:
Get internal byte array from ByteArrayInputStream
I want to get the internal byte array from ByteArrayInputStream. I don't want to extends that class or write it into another byte array. Is there a utility class that help me do that?

Thanks,

答: No. Extending the class is the only way (well, that and using reflection to bypass the field visibility, which absolutely NOT recommended).</p>


问:
What is perl's equivalent one liner of grep -o
My question is simple as my title says "What is perl's equivalent one liner of grep -o?". That is print the matched regex only instead of whole line?</p>

```<code>perl -pe some_option?? 'm/regex/' file
</code>```

答:
You could just change the code:</p>

```<code>perl -ne 'if(/(regex)/) {print "$1\n"}' file
</code>```

Body:
My question is simple as my title says "What is perl's equivalent one liner of grep -o?". That is print the matched regex only instead of whole line?

perl -pe some_option?? 'm/regex/' file

Body:
You could just change the code:

perl -ne 'if(/(regex)/) {print "$1\n"}' file


问:
Companion objects - does Android want to register them as activities (?)
I have an Activity

```<code>class DummyActivity : Activity() {

    companion object {
        @JvmStatic fun onNewIntent(context: Context): Intent {
            val intent = Intent(context, DummyActivity.javaClass)
            return intent
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
</code>```

It is declared in the Manifest as follows:

```<code>    <activity android:name=".DummyActivity"/>
</application>
</code>```

When I try to launch it, I get:

Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class > {com.example.andrzejzuzak.visiondummyapp/com.example.andrzejzuzak.visiondummyapp.DummyActivity$Companion}; have you declared this activity in your AndroidManifest.xml?
                                                                                at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794)
                                                                                at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:3930)
                                                                                at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:3890)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                                                at android.app.Activity.startActivity(Activity.java:4213)
                                                                                at android.app.Activity.startActivity(Activity.java:4181)
                                                                                at com.example.andrzejzuzak.visiondummyapp.MainActivity.onActivityResult(MainActivity.kt:85)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:6456)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
                                                                                at android.app.ActivityThread.-wrap16(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)

What bothers me is this line:

Unable to find explicit activity class {com.example.andrzejzuzak.visiondummyapp/com.example.andrzejzuzak.visiondummyapp.DummyActivity$Companion

Does it actually mean that I have to register the Companion object somewhere?

答:
DummyActivity.javaClass refers to DummyActivity.Companion and not to DummyActivity. In fact, it is even a warning:

The resulting type of this javaClass call is
  Class<Dummy.Companion> and not Class<Dummy>. Please use more clear
  ::class.java syntax to avoid confusion.

Instead, you should use DummyActivity::class.java,

Body:
I have an Activity

class DummyActivity : Activity() {

    companion object {
        @JvmStatic fun onNewIntent(context: Context): Intent {
            val intent = Intent(context, DummyActivity.javaClass)
            return intent
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

It is declared in the Manifest as follows:

    <activity android:name=".DummyActivity"/>
</application>

When I try to launch it, I get:

Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class > {com.example.andrzejzuzak.visiondummyapp/com.example.andrzejzuzak.visiondummyapp.DummyActivity$Companion}; have you declared this activity in your AndroidManifest.xml?
                                                                                at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794)
                                                                                at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:3930)
                                                                                at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:3890)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                                                at android.app.Activity.startActivity(Activity.java:4213)
                                                                                at android.app.Activity.startActivity(Activity.java:4181)
                                                                                at com.example.andrzejzuzak.visiondummyapp.MainActivity.onActivityResult(MainActivity.kt:85)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:6456)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
                                                                                at android.app.ActivityThread.-wrap16(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)

What bothers me is this line:

Unable to find explicit activity class {com.example.andrzejzuzak.visiondummyapp/com.example.andrzejzuzak.visiondummyapp.DummyActivity$Companion

Does it actually mean that I have to register the Companion object somewhere?


答:
```<code>perl -nE 'say $& while /regex/g' file
</code>```

Title: What is perl's equivalent one liner of grep -o

Body: perl -nE 'say $& while /regex/g' file


问:
ng-cloak not working in Angular
I am trying to remove {{ }} from my website. Basically it came if angular didn't load. So, I checked SO and found some answer to use ng-cloak. I tried that but I can still see {{ }}. I added the CSS code below in a CSS file as well as locally on the page.

CSS

```<code>.ng-cloak {
      display: none !important;
}
</code>```

Here is the form.

```<code><form name="register" method="post" id="register" role="form" ng-submit="registerForm()">
<div class="form-group" ng-class="{ 'has-error' : erroractype }">
        <select id="actype" name="actype" class=" selector form-control" ng-model="formData.actype" required="required">
           <option value="" selected="selected" >I am</option>
          <option value="1"> Student</option>
          <option value="2"> Teacher</option>
          <option value="3"> School</option>
          </select>
<span class="help-block" ng-show="errorName" class="ng-cloak">{{ erroractype }}</span>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorFname }">

<input type="text" id="fname" name="fname" placeholder="First Name" title="Please Enter Your First Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Fname">
<div class = "alert alert-danger" ng-show="errorFname" class="ng-cloak">{{errorFname}}</div>

</div>

<div class="form-group" ng-class="{ 'has-error' : errorLname }">
<input type="text" id="lname" name="lname" placeholder="Last Name" title="Please Enter Your Last Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Lname">
<div class = "alert alert-danger" ng-show="errorLname" class="ng-cloak">{{ errorLname }}</div>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorEmail1 }">
<input type="email" id="email1" name="email1" placeholder="Email" class="form-control input-sm textbox1" title="Please Enter Your Valid Email" required="required" ng-model="formData.Email1">
<div class = "alert alert-danger" ng-show="errorEmail1" class="ng-cloak">{{ errorEmail1 }}</div>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorPassword1 }">
<input type="password" name="password1" id="password1" placeholder="Password" title="Please enter AlphaNumeric value" class="form-control input-sm textbox1" required="required" ng-model="formData.Password1">
<div class = "alert alert-danger" ng-show="errorPassword1" class="ng-cloak">{{ errorPassword1 }}</div>
{{ errorPassword1 }}
</div>

<div class="form-group" ng-class="{ 'has-error' : errormobile }">
    <input type="text" id="mobile" name="mobile" placeholder="Mobile Number (+1)" title="Please Enter Your Contact Number without Coutry Code." class="form-control input-sm textbox1" required="required" ng-model="formData.mobile">
    <div class = "alert alert-danger" ng-show="errormobile" class="ng-cloak">{{ errormobile }}</div>
 </div>

<div class="form-group">
<button type="submit" class="btn btn-home" name="btn-register" id="btn-register" required="required">Register</button>
</div>
</form>
</code>```

Any advice as to what am I doing wrong?

答: Apply ng-cloak at the root level, where you mentioned your ng-app directive. (html tag probably), further I would suggest to completely avoid ng-cloak , and start using ng-bind. It will solve your problem of flickering of {{}} interpolation operator

Title: ng-cloak not working in Angular

Body:
I am trying to remove {{ }} from my website. Basically it came if angular didn't load. So, I checked SO and found some answer to use ng-cloak. I tried that but I can still see {{ }}. I added the CSS code below in a CSS file as well as locally on the page.

CSS

.ng-cloak {
      display: none !important;
}

Here is the form.

<form name="register" method="post" id="register" role="form" ng-submit="registerForm()">

        <select id="actype" name="actype" class=" selector form-control" ng-model="formData.actype" required="required">
           <option value="" selected="selected" >I am</option>
          <option value="1"> Student</option>
          <option value="2"> Teacher</option>
          <option value="3"> School</option>
          </select>
{{ erroractype }}

<input type="text" id="fname" name="fname" placeholder="First Name" title="Please Enter Your First Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Fname">

{{errorFname}}

<input type="text" id="lname" name="lname" placeholder="Last Name" title="Please Enter Your Last Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Lname">

{{ errorLname }}

<input type="email" id="email1" name="email1" placeholder="Email" class="form-control input-sm textbox1" title="Please Enter Your Valid Email" required="required" ng-model="formData.Email1">

{{ errorEmail1 }}

<input type="password" name="password1" id="password1" placeholder="Password" title="Please enter AlphaNumeric value" class="form-control input-sm textbox1" required="required" ng-model="formData.Password1">

{{ errorPassword1 }}

{{ errorPassword1 }}

    <input type="text" id="mobile" name="mobile" placeholder="Mobile Number (+1)" title="Please Enter Your Contact Number without Coutry Code." class="form-control input-sm textbox1" required="required" ng-model="formData.mobile">

{{ errormobile }}

<button type="submit" class="btn btn-home" name="btn-register" id="btn-register" required="required">Register</button>

</form>

Any advice as to what am I doing wrong?


答:
try this</p>

```<code>h1 {
    font-family:Arial;
    font-size:50px;
    color:#085ED9;
    display:table-cell;
    vertical-align:middle;
    float: right;
}
</code>```

Title: Can't vertically center text in a table cell

Body:
I'm creating a website for a school project using HTML and CSS. In the header there is a table and I need a text (which is inside a cell) to be aligned on the vertical center and on the horizontal right.

This is the HTML code

........

Text

and this is the CSS code

h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;
    text-align:right;
}
.centerV
{
    display:table-cell;
    vertical-align:middle;
}

but it doesn't work as I want, so I changed the CSS code into

h1
{
    font-family:Arial;
    font-size:50px;
    color:#009ED9;

    display:table-cell;
    vertical-align:middle;
    text-align:right;
}

and the text is vertically centered, but not on the right (it is on the left). I've read that I can use line-height or a padding on the top, but in my opinion it is more clean and elegant to use vertical-align (tell me if I am wrong).

I tried also other code from suggestions on the web but I don't write it otherwise the question will be too long.

Body:
try this

h1 {
    font-family:Arial;
    font-size:50px;
    color:#085ED9;
    display:table-cell;
    vertical-align:middle;
    float: right;
}


问:
Android:How can I access a value from a method of a class?
see, I have 2 class lets say Login class and Welcome class, within Login Class  I have Global Variable String Email; and an OnCreate() . and i set value for Email within that method, now my question is how do I get the value of that Variable that I initialized from a method?

```<code>public class LoginActivity extends AppCompatActivity {
private EditText email,password;

public String emailText;

protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        email = (EditText) findViewById(R.id.email);
        //I want to get this value
        emailText = email.getText().toString();
}
}
</code>```

and my another class is

```<code>public class Welcome extends Activity{
protected void onCreate(Bundle savedInstanceState) {
     TextView textView = (TextView) findViewById(R.id.email);
     //this is what I did which is the variable that was unInitialized
     LoginActivity loginActivity = new LoginActivity();
        textView.setText(loginActivity.getEmailText());
}
}
</code>```

答:
You have to start the Welcome activity with some extras:

```<code>    Intent startWelcomeActivityIntent = new Intent(context, Welcome.class);
    startWelcomeActivityIntent.putExtra("keyForUsername", userNameString);
    startWelcomeActivityIntent.putExtra("keyForPassword", passwordString);
    startActivity(startWelcomeActivityIntent);
</code>```

Then retrieve this extras from the Welcome activity onCreate method:

```<code>protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intentWithData = getIntent();
    String userNameFromLoginActivity = intentWithData.getStringExtra("keyForUsername");
    String passwordFromLoginActivity = intentWithData.getStringExtra("keyForPassword");
}
</code>```

Body:
see, I have 2 class lets say Login class and Welcome class, within Login Class  I have Global Variable String Email; and an OnCreate() . and i set value for Email within that method, now my question is how do I get the value of that Variable that I initialized from a method?

public class LoginActivity extends AppCompatActivity {
private EditText email,password;

public String emailText;

protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        email = (EditText) findViewById(R.id.email);
        //I want to get this value
        emailText = email.getText().toString();
}
}

and my another class is

public class Welcome extends Activity{
protected void onCreate(Bundle savedInstanceState) {
     TextView textView = (TextView) findViewById(R.id.email);
     //this is what I did which is the variable that was unInitialized
     LoginActivity loginActivity = new LoginActivity();
        textView.setText(loginActivity.getEmailText());
}
}

Body:
You have to start the Welcome activity with some extras:

    Intent startWelcomeActivityIntent = new Intent(context, Welcome.class);
    startWelcomeActivityIntent.putExtra("keyForUsername", userNameString);
    startWelcomeActivityIntent.putExtra("keyForPassword", passwordString);
    startActivity(startWelcomeActivityIntent);

Then retrieve this extras from the Welcome activity onCreate method:

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intentWithData = getIntent();
    String userNameFromLoginActivity = intentWithData.getStringExtra("keyForUsername");
    String passwordFromLoginActivity = intentWithData.getStringExtra("keyForPassword");
}


问:
How to set allow-access-origin in AJAX header?
How to set header for allow-access-origin for AJAX request using JSON, JQUERY?</p>

答:
Assuming the endpoint supports jsonp, remove Access-Control-Allow-Origin error by modifying the dataType parameter to dataType:'jsonp' and adding a crossDomain:true.

```<code>$.ajax({
    url: 'https://example.com?request='+key,
    data: myData,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader
});
</code>```

Body:
Assuming the endpoint supports jsonp, remove Access-Control-Allow-Origin error by modifying the dataType parameter to dataType:'jsonp' and adding a crossDomain:true.

$.ajax({
    url: 'https://example.com?request='+key,
    data: myData,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader
});