问:
jQuery functions not firing with Stripe Elements
I have a form that let's users select payment method. If the method is Credit Card, an initiated Stripe Elements form is displayed and they can enter CC/EXP/ZIP data. Once they click submit, the form should first pass validation (jQuery Validate), then go through the process of getting the token from Stripe to pass to the server in the next page. The problem is that even though the functions are declared, and even though I am calling them, they don't seem to be running and I cannot figure out why.

```<code>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'
  }
};

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('keyup', function(event) {
  var displayError = document.getElementById('card-errors');
  if (event.error) {
    displayError.textContent = event.error.message;
  } else {
    displayError.textContent = '';
  }
});

var stripe = Stripe('');

// Create an instance of Elements
var elements = stripe.elements();
jQuery( document ).ready(function() {
    function stripeTokenHandler(token) {
                // Insert the token ID into the form so it gets submitted to the server
                document.createElement('input');
                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);
                alert('token id is' + token.id);
                var token_field = jQuery("input[name='stripeToken']").val();
                alert(token_field);
                // Submit the form

                setTimeout(form.submit(), 3000);

        };
    function createToken() {
        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;
            alert(result.error.message);
            } else {
            // Send the token to your server
            alert('we got the token, sending it off')
            stripeTokenHandler(result.token);
            }
        });
    };

    function stripeCreateToken(event){

        var selectVal = jQuery("#payment_type option:selected").val();
        if( selectVal !== "Credit Card" ){
            // Not CC, skip Stripe and submit the form
            alert('it failed or no credit card');
            var form = document.getElementById('payment-form');
            form.submit();
        }
        createToken();
    };

    jQuery('#payment_type').on('change', function () {
            var selectVal = jQuery("#payment_type option:selected").val();
            //var form = document.getElementById('payment-form');
            if( selectVal == "Credit Card" ){
                jQuery('.check').hide();
                jQuery('.cc').show();

                jQuery("#payment-form").submit(function(e){
                    stripeCreateToken(e);
                });
            }else{
                jQuery('.cc').hide();
                jQuery('.check').show();
            }
        });
});
</code>```

Weird thing is that if I paste all of the above in the console it works, but I want to understand what I am doing wrong, or at least some direction of where to look.

答: Issue was jQuery validation was firing the form submit before Stripe could finish it's thing. I removed the form.submit(); from jQuery validation and had it initiate my stripe functions and its working great.

Body:
I have a form that let's users select payment method. If the method is Credit Card, an initiated Stripe Elements form is displayed and they can enter CC/EXP/ZIP data. Once they click submit, the form should first pass validation (jQuery Validate), then go through the process of getting the token from Stripe to pass to the server in the next page. The problem is that even though the functions are declared, and even though I am calling them, they don't seem to be running and I cannot figure out why.

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'
  }
};

var card = elements.create('card', {style: style});

// Add an instance of the card Element into the `card-element`

card.mount('#card-element');

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

var stripe = Stripe('');

// Create an instance of Elements
var elements = stripe.elements();
jQuery( document ).ready(function() {
    function stripeTokenHandler(token) {
                // Insert the token ID into the form so it gets submitted to the server
                document.createElement('input');
                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);
                alert('token id is' + token.id);
                var token_field = jQuery("input[name='stripeToken']").val();
                alert(token_field);
                // Submit the form

                setTimeout(form.submit(), 3000);

        };
    function createToken() {
        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;
            alert(result.error.message);
            } else {
            // Send the token to your server
            alert('we got the token, sending it off')
            stripeTokenHandler(result.token);
            }
        });
    };

    function stripeCreateToken(event){

        var selectVal = jQuery("#payment_type option:selected").val();
        if( selectVal !== "Credit Card" ){
            // Not CC, skip Stripe and submit the form
            alert('it failed or no credit card');
            var form = document.getElementById('payment-form');
            form.submit();
        }
        createToken();
    };

    jQuery('#payment_type').on('change', function () {
            var selectVal = jQuery("#payment_type option:selected").val();
            //var form = document.getElementById('payment-form');
            if( selectVal == "Credit Card" ){
                jQuery('.check').hide();
                jQuery('.cc').show();

                jQuery("#payment-form").submit(function(e){
                    stripeCreateToken(e);
                });
            }else{
                jQuery('.cc').hide();
                jQuery('.check').show();
            }
        });
});

Weird thing is that if I paste all of the above in the console it works, but I want to understand what I am doing wrong, or at least some direction of where to look.


来源: stackexchange

问:
confused addition operator logic
Why does the variable counter keep increasing when it re-initializes itself back to 0 in the self-invoking function?

```<code> var add = (function () {
     var counter = 0;
     return function () {
        return counter += 1;
     }
 })();

 add();
 add();
 add();

 // the counter is still 3 when this line of code exists
 // var counter = 0;
</code>```

So when add() function gets invoked, a function runs first with initializing counter = 0 and returning another function that returns the incremental value of counter. Why is this the case when there's var counter = 0; ?

source: https://www.w3schools.com/js/js_function_closures.asp

edit: November 16th, 2017

Okay so it makes a lot more sense now from both of the answers given on this page. For extra clarification, I will add my own reasoning to give it a better visualization of why this happens.

```<code> //first call of add()
 (function(){ // a self-invoking function
    var counter = 0; // executes once with the self-invoking function
    return function() { return counter += 1; } //explained below
 });

 //since the self-invoke function ran already, add() will begin to run the returned function:
 add = function() { return counter += 1; };
 add(); ----> counter += 1; -----> add.counter = 1;
 //counter acts like this.counter, so it's a part of add()
 //counter is now at 1

 //second call of add();
 //add has now officially been **transformed** to the new function:
 add = function() {
    return counter += 1;
 };
 //while add.counter still **exists** and remains in the self-invoke
 //function. Do we call this **limbo variable** ? Don't know.
 //add.counter is at 2

 //third call of add();
 function() {
   return counter += 1;
 }
 //add.counter is at 3!
</code>```

答:
Please note that "var add" assigned a self invoking function that returns a function.
Whatever above the return statement is the self invoking function closure. Which means that it is available to the returned function.
So it is in fact only initialized once. And then the return function, which is what the variable "add" now contains, increments the counter whenever it is invoked.

ContentLicense: CC BY-SA 3.0

Title: confused addition operator logic

Body:
Why does the variable counter keep increasing when it re-initializes itself back to 0 in the self-invoking function?

 var add = (function () {
     var counter = 0;
     return function () {
        return counter += 1;
     }
 })();

 add();
 add();
 add();

 // the counter is still 3 when this line of code exists
 // var counter = 0;

So when add() function gets invoked, a function runs first with initializing counter = 0 and returning another function that returns the incremental value of counter. Why is this the case when there's var counter = 0; ?

source: https://www.w3schools.com/js/js_function_closures.asp

edit: November 16th, 2017

Okay so it makes a lot more sense now from both of the answers given on this page. For extra clarification, I will add my own reasoning to give it a better visualization of why this happens.

 //first call of add()
 (function(){ // a self-invoking function
    var counter = 0; // executes once with the self-invoking function
    return function() { return counter += 1; } //explained below
 });

 //since the self-invoke function ran already, add() will begin to run the returned function:
 add = function() { return counter += 1; };
 add(); ----> counter += 1; -----> add.counter = 1;
 //counter acts like this.counter, so it's a part of add()
 //counter is now at 1

 //second call of add();
 //add has now officially been **transformed** to the new function:
 add = function() {
    return counter += 1;
 };
 //while add.counter still **exists** and remains in the self-invoke
 //function. Do we call this **limbo variable** ? Don't know.
 //add.counter is at 2

 //third call of add();
 function() {
   return counter += 1;
 }
 //add.counter is at 3!


问:
R Subtracting columns within a list
I'd like to subtract specific columns within a list. I'm still learning how to properly use the apply functions. For example, given

```<code>> b <- list(data.frame(12:16, 3*2:6), data.frame(10:14, 2*1:5))
> b

[[1]]
  X12.16 X3...2.6
1     12        6
2     13        9
3     14       12
4     15       15
5     16       18

[[2]]
  X10.14 X2...1.5
1     10        2
2     11        4
3     12        6
4     13        8
5     14       10
</code>```

I'd like some function x so that I get

```<code>> x(b)

[[1]]
  X12.16 X3...2.6  <newcol>
1     12        6         6
2     13        9         4
3     14       12         2
4     15       15         0
5     16       18        -2

[[2]]
  X10.14 X2...1.5  <newcol>
1     10        2         8
2     11        4         7
3     12        6         6
4     13        8         5
5     14       10         4
</code>```

Thanks in advance.

答:
If your data.frames had nice and consistent names, you could use transform with lapply

```<code>b <- list(data.frame(a=12:16, b=3*2:6), data.frame(a=10:14, b=2*1:5))
lapply(b, transform, c=a-b)
</code>```

Title: R Subtracting columns within a list

Body:
I'd like to subtract specific columns within a list. I'm still learning how to properly use the apply functions. For example, given

> b <- list(data.frame(12:16, 3*2:6), data.frame(10:14, 2*1:5))
> b

[[1]]
  X12.16 X3...2.6
1     12        6
2     13        9
3     14       12
4     15       15
5     16       18

[[2]]
  X10.14 X2...1.5
1     10        2
2     11        4
3     12        6
4     13        8
5     14       10

I'd like some function x so that I get

> x(b)

[[1]]
  X12.16 X3...2.6  <newcol>
1     12        6         6
2     13        9         4
3     14       12         2
4     15       15         0
5     16       18        -2

[[2]]
  X10.14 X2...1.5  <newcol>
1     10        2         8
2     11        4         7
3     12        6         6
4     13        8         5
5     14       10         4

Thanks in advance.

Body:
If your data.frames had nice and consistent names, you could use transform with lapply

b <- list(data.frame(a=12:16, b=3*2:6), data.frame(a=10:14, b=2*1:5))
lapply(b, transform, c=a-b)


问:
Observable - make queue of dynamic requests (angular 4)
I have a question about observable.
For example, we have api, and send a reguest there:

```<code>this.http.get('https://swapi.co/api/people/').subscribe(peoplesData => {
   let peoples = peoplesData.json();
   let nextPage = peoples.next; // https://swapi.co/api/people/?page=2
   this.peoples = peoples.results;
});
</code>```

When I send first request, I will get url for next request (in this example, url contains in 'nextPage').
I need to create method, which will make all request, and after every requests will add all 'results' to 'this.peoples'.
I think, .mergeMap and switchMap don't fit for it.
Maybe are you have more expirience with Observable? Please help me with this method.

Update
I solved this problem with .expand:

```<code>return this.http.get('https://swapi.co/api/people/')
      .expand(peoplesData => {
        let peoples = peoplesData.json();
        if (peoples.next) {
          return this.http.get(peoples.next);
        } else {
          return Observable.empty();
        }
      })
      .map(peoples => peoples.json());
</code>```

答:
My solution using rxjs Rx flatMap :</p>

```<code>import {Observable} from 'rxjs/Rx';

ngOnInit() {
  const arrayIds = [2456, 12456, 456, 7899];
  this.doUsersRequest(arrayIds);
}

doUsersRequest(queryArr, previousObservable = null) {
        if (queryArr.length) {
            const url = 'api/users/id/' + queryArr.shift();
            let observable = null;
            if (previousObservable) {
                observable = previousObservable.flatMap(() => {
                    return this.http.get(url);
                });
            } else {
                observable = this.http.get(url);
            }
            return this.doUsersRequest(queryArr, observable);
        } else {
            return previousObservable;
        }
    }
</code>```

Body:
I have a question about observable.
For example, we have api, and send a reguest there:

this.http.get('https://swapi.co/api/people/').subscribe(peoplesData => {
   let peoples = peoplesData.json();
   let nextPage = peoples.next; // https://swapi.co/api/people/?page=2
   this.peoples = peoples.results;
});

When I send first request, I will get url for next request (in this example, url contains in 'nextPage').
I need to create method, which will make all request, and after every requests will add all 'results' to 'this.peoples'.
I think, .mergeMap and switchMap don't fit for it.
Maybe are you have more expirience with Observable? Please help me with this method.

Update
I solved this problem with .expand:

return this.http.get('https://swapi.co/api/people/')
      .expand(peoplesData => {
        let peoples = peoplesData.json();
        if (peoples.next) {
          return this.http.get(peoples.next);
        } else {
          return Observable.empty();
        }
      })
      .map(peoples => peoples.json());

Body:
My solution using rxjs Rx flatMap :

import {Observable} from 'rxjs/Rx';

ngOnInit() {
  const arrayIds = [2456, 12456, 456, 7899];
  this.doUsersRequest(arrayIds);
}

doUsersRequest(queryArr, previousObservable = null) {
        if (queryArr.length) {
            const url = 'api/users/id/' + queryArr.shift();
            let observable = null;
            if (previousObservable) {
                observable = previousObservable.flatMap(() => {
                    return this.http.get(url);
                });
            } else {
                observable = this.http.get(url);
            }
            return this.doUsersRequest(queryArr, observable);
        } else {
            return previousObservable;
        }
    }


问:
CSS min-height not working in firefox
I'm working on a ReactJS app and I want my body to take up the entire screen at least - using min-height: 100%, with height: auto to account for the screen being more than 100%. This is not working in firefox specifically but is working in other browsers.

Left is chrome, right is firefox.

Everything is being held by a div with the body class as such;

```<code><div className={styles.body}>
   {this.props.children}
</div>
</code>```

My scss:

```<code>.body{
display: block;
font-family: "Ubuntu", sans-serif;
margin: auto;
height: auto;
min-height: 100%;
width: 100%;
background:
    linear-gradient(135deg, #696D7D 22px, #FAF5E3 22px, #FAF5E3 24px, transparent 24px, transparent 67px, #FAF5E3 67px, #FAF5E3 69px, transparent 69px),
    linear-gradient(225deg, #696D7D 22px, #FAF5E3 22px, #FAF5E3 24px, transparent 24px, transparent 67px, #FAF5E3 67px, #FAF5E3 69px, transparent 69px)0 64px;
background-color:#696D7D;
background-size: 64px 128px;
}
</code>```

答:
You should use this:</p>

```<code>min-height: 100vh;
</code>```

Title: CSS min-height not working in firefox

Body:
I'm working on a ReactJS app and I want my body to take up the entire screen at least - using min-height: 100%, with height: auto to account for the screen being more than 100%. This is not working in firefox specifically but is working in other browsers.

Left is chrome, right is firefox.

Everything is being held by a div with the body class as such;

   {this.props.children}

My scss:

.body{
display: block;
font-family: "Ubuntu", sans-serif;
margin: auto;
height: auto;
min-height: 100%;
width: 100%;
background:
    linear-gradient(135deg, #696D7D 22px, #FAF5E3 22px, #FAF5E3 24px, transparent 24px, transparent 67px, #FAF5E3 67px, #FAF5E3 69px, transparent 69px),
    linear-gradient(225deg, #696D7D 22px, #FAF5E3 22px, #FAF5E3 24px, transparent 24px, transparent 67px, #FAF5E3 67px, #FAF5E3 69px, transparent 69px)0 64px;
background-color:#696D7D;
background-size: 64px 128px;
}

Body:
You should use this:

min-height: 100vh;


问:
ArangoDb: Time from save() to availability through AQL - waitForSync?
In my NodeJS backed REST API, using the ArangoJS library, I'm calling the await save(...) on a document in a collection. Note I'm not using using the waitForSync option.

Right after the await on the save, I'll send a SSE event to the client, which then immediately calls another REST API method, which uses AQL to query the very same collection. Unfortunately I get the previous (old/unchanged) data back. Waiting a sec then AQL-querying gives me the fresh data though.

Is waitForSync the solution? Most documentation states that this option waits for data to sync to the disk, but as I understand ArangoDB keep most data in memory, so it shouldn't affect the following query, which should query against memory?

Anyone care to explain?

Update

see my own answer

答:
Just to mark this as answered:

As expected, there is nothing wrong with ArangoDb. Thanks to the comment/confirmation that await should be enough, I investigated further around my setup. Found that the problem was with caching, and adding a Cache-Control header with 'no-cache' resolved the issue.

Funny thing is that when developer console was open in Chrome, I never had problems. Found that the checkbox 'disable cache' in development mode had hidden the issue during development. Issue being a lot of 304 Not Changed responses.


问:
Error: Immutable value passed on reduce function
I'm trying to do the following code that transforms an array of tuples into a dictionary but I'm receiving a compile error saying:

Immutable value of type '[String : String]' only has mutating members named 'updateValue'

```<code>var array = [("key0", "value0"), ("key1", "value1")]
var initial = [String: String]()
var final = array.reduce(initial) { (dictionary, tuple) in
    dictionary.updateValue(tuple.0, forKey: tuple.1)
    return dictionary
}
</code>```

Why is that if initial was declared as var? Does it have to do with @noescape on reduce's signature?

```<code>func reduce<U>(initial: U, combine: @noescape (U, T) -> U) -> U
</code>```

答:
Swift 4 has a new variant:

```<code>var array = [("key0", "value0"), ("key1", "value1")]
var initial = [String: String]()
var final = array.reduce(into: initial) { dictionary, tuple in
    dictionary[tuple.0] = tuple.1
}
</code>```

Which could be expressed:

```<code>var array = [("key0", "value0"), ("key1", "value1")]
let final: [String: String] = array.reduce(into: [:]){ $0[$1.0] = $1.1 }
</code>```

Body:
I'm trying to do the following code that transforms an array of tuples into a dictionary but I'm receiving a compile error saying:

Immutable value of type '[String : String]' only has mutating members named 'updateValue'

var array = [("key0", "value0"), ("key1", "value1")]
var initial = [String: String]()
var final = array.reduce(initial) { (dictionary, tuple) in
    dictionary.updateValue(tuple.0, forKey: tuple.1)
    return dictionary
}

Why is that if initial was declared as var? Does it have to do with @noescape on reduce's signature?

func reduce(initial: U, combine: @noescape (U, T) -> U) -> U

Body:
Swift 4 has a new variant:

var array = [("key0", "value0"), ("key1", "value1")]
var initial = [String: String]()
var final = array.reduce(into: initial) { dictionary, tuple in
    dictionary[tuple.0] = tuple.1
}

Which could be expressed:

var array = [("key0", "value0"), ("key1", "value1")]
let final: [String: String] = array.reduce(into: [:]){ $0[$1.0] = $1.1 }


问:
Generic class with array
I want to create a custom generic class for my Java project and this is how far I got - I found the code as an example on how to create generic arrays.

```<code>public class RegisterSet<T> {
   private T[] register;
   public <T> RegisterSet(int size) {
      register = (T[])Array.newInstance(T, size);
   }
}
</code>```

Now, I get the error Incompatible types - found: T[], required: T[] which makes absolutely no sense to me - how can I fix this?

答:
You need a variable containing a Class object for T.  The easiest way to populate this is probably a static factory method:

```<code>public class RegisterSet<T> {
   public static <T>RegisterSet<T> create(Class<T> clazz, int size) {
       return new RegisterSet<T>(clazz, size);
   }

   private T[] register;

   @SuppressWarnings("unchecked")
   private RegisterSet(Class<T> clazz, int size) {
      if (clazz.isPrimitive()) throw new IllegalArgumentException("Cannot create a RegisterSet of primitives");
      register = (T[])Array.newInstance(clazz, size);
   }
}
</code>```

The static method allows you to say

```<code>RegisterSet<String> x = RegisterSet.create(String.class, 42);
</code>```

which is slightly shorter and less repetitive than

```<code>RegisterSet<String> x = new RegisterSet<String>(String.class, 42);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Generic class with array

Body:
I want to create a custom generic class for my Java project and this is how far I got - I found the code as an example on how to create generic arrays.

public class RegisterSet<T> {
   private T[] register;
   public <T> RegisterSet(int size) {
      register = (T[])Array.newInstance(T, size);
   }
}

Now, I get the error Incompatible types - found: T[], required: T[] which makes absolutely no sense to me - how can I fix this?

Body:
You need a variable containing a Class object for T.  The easiest way to populate this is probably a static factory method:

public class RegisterSet<T> {
   public static <T>RegisterSet<T> create(Class<T> clazz, int size) {
       return new RegisterSet<T>(clazz, size);
   }

   private T[] register;

   @SuppressWarnings("unchecked")
   private RegisterSet(Class<T> clazz, int size) {
      if (clazz.isPrimitive()) throw new IllegalArgumentException("Cannot create a RegisterSet of primitives");
      register = (T[])Array.newInstance(clazz, size);
   }
}

The static method allows you to say

RegisterSet<String> x = RegisterSet.create(String.class, 42);

which is slightly shorter and less repetitive than

RegisterSet<String> x = new RegisterSet<String>(String.class, 42);


问:
Looping through csv file to create smaller file for action, loop not activating
The following code is meant to loop through a large csv file, take a block of 20 observations at a time, and load them into a smaller file, which will than be used for geocoding.  Loop does not seem to be running, and have run out of ideas why (nothing past the first row_count gets printed, except end)  </p>

```<code>SalesLoad = open('C:\Users\DillonSaxe\Real Estate\Chi address 2000-2015.csv')
Sales = csv.reader(SalesLoad)
Storage = []
row_count = sum(1 for row in Sales)
print row_count
for row in Sales:
    if Sales.line_num == 1:
        Header = row
        print header
    elif Sales.line_num%20 != 0 and Sales.line_num != row_count:
        Storage.append(row)
    else:
        Storage.append(row)
        print row
        TempLoad = open('C:\Users\DillonSaxe\Real Estate\Temp Geocode File.csv', 'wb')
        TempGeocode = csv.writer(TempLoad)
        TempGeocode.writerow(Header)
        for item in Storage:
            TempGeocode.writerow(item)
        TempLoad.close()
SalesLoad.close()
print 'Done'
</code>```

答:
you can use enumerate to test line number and iterate file once </p>

```<code>  with open('C:\Users\DillonSaxe\Real Estate\Chi address 2000-2015.csv', 'rb') as f
    reader = csv.reader(f)
    storage = [line for idx, line in enumerate(reader) if idx%20]

  with open('C:\Users\DillonSaxe\Real Estate\Temp Geocode File.csv', 'wb') as f
    writer = csv.writer(f)
    writer.writerows(storage )

  print 'Done'
</code>```

Body:
The following code is meant to loop through a large csv file, take a block of 20 observations at a time, and load them into a smaller file, which will than be used for geocoding.  Loop does not seem to be running, and have run out of ideas why (nothing past the first row_count gets printed, except end)

SalesLoad = open('C:\Users\DillonSaxe\Real Estate\Chi address 2000-2015.csv')
Sales = csv.reader(SalesLoad)
Storage = []
row_count = sum(1 for row in Sales)
print row_count
for row in Sales:
    if Sales.line_num == 1:
        Header = row
        print header
    elif Sales.line_num%20 != 0 and Sales.line_num != row_count:
        Storage.append(row)
    else:
        Storage.append(row)
        print row
        TempLoad = open('C:\Users\DillonSaxe\Real Estate\Temp Geocode File.csv', 'wb')
        TempGeocode = csv.writer(TempLoad)
        TempGeocode.writerow(Header)
        for item in Storage:
            TempGeocode.writerow(item)
        TempLoad.close()
SalesLoad.close()
print 'Done'

Body:
you can use enumerate to test line number and iterate file once

  with open('C:\Users\DillonSaxe\Real Estate\Chi address 2000-2015.csv', 'rb') as f
    reader = csv.reader(f)
    storage = [line for idx, line in enumerate(reader) if idx%20]

  with open('C:\Users\DillonSaxe\Real Estate\Temp Geocode File.csv', 'wb') as f
    writer = csv.writer(f)
    writer.writerows(storage )

  print 'Done'


问:
Emulator not starting after updating to Android Studio
I have updated android studio to 3.0 through standard update channel. After update am not able to start the emulator.

I have tried the following. But nothing worked.

Restart and reinstall HAXM installer.

Restart and reinstall AVD manager.

Start emulator from terminal.

Change the size of RAM to 2GB.

Graphics to Software GLES 2.0

PFB the logs.

At 4:Run

```<code>Error while waiting for device: The emulator process for AVD Nexus_5X_API_25 was killed.
</code>```

AT Gradle Console:

```<code>27/10/17
8:42 PM Gradle sync started

8:42 PM Project setup started

8:42 PM Gradle sync finished in 3s 25ms (from cached state)

8:42 PM adb E 10-27 20:42:34   953 34293 usb_osx.cpp:152] Unable to create an interface plug-in (e00002be)

8:43 PM Executing tasks: [:app:assembleDebug]

8:43 PM Emulator: Failed to open vm 7

8:43 PM Emulator: Failed to create HAX VM

8:43 PM Emulator: No accelerator found.

8:43 PM Emulator: failed to initialize HAX: Invalid argument

8:43 PM Emulator: Process finished with exit code 0

8:43 PM Gradle build finished in 19s 741ms
</code>```

System Config :

Macbook Pro 2016

OS: High Sierra

Build: 3.0, AI-171.4408382, 201710201707,

AI-171.4408382, JRE 1.8.0_152-release-915-b08x64 JetBrains s.r.o, OS Mac OS X(x86_64) v10.13 unknown, screens 1680x1050; Retina

答: I had the same problem. All I did to solve it was updating Android Emulator and Intel x86 Emulator Accelerator under Android SDK Manager > SDK Tools. It started to work again.

ContentLicense: CC BY-SA 4.0

Body:
I have updated android studio to 3.0 through standard update channel. After update am not able to start the emulator.

I have tried the following. But nothing worked.

Restart and reinstall HAXM installer.

Restart and reinstall AVD manager.

Start emulator from terminal.

Change the size of RAM to 2GB.

Graphics to Software GLES 2.0

PFB the logs.

At 4:Run

Error while waiting for device: The emulator process for AVD Nexus_5X_API_25 was killed.

AT Gradle Console:

27/10/17
8:42 PM Gradle sync started

8:42 PM Project setup started

8:42 PM Gradle sync finished in 3s 25ms (from cached state)

8:42 PM adb E 10-27 20:42:34   953 34293 usb_osx.cpp:152] Unable to create an interface plug-in (e00002be)

8:43 PM Executing tasks: [:app:assembleDebug]

8:43 PM Emulator: Failed to open vm 7

8:43 PM Emulator: Failed to create HAX VM

8:43 PM Emulator: No accelerator found.

8:43 PM Emulator: failed to initialize HAX: Invalid argument

8:43 PM Emulator: Process finished with exit code 0

8:43 PM Gradle build finished in 19s 741ms

System Config :

Macbook Pro 2016

OS: High Sierra

Build: 3.0, AI-171.4408382, 201710201707,

AI-171.4408382, JRE 1.8.0_152-release-915-b08x64 JetBrains s.r.o, OS Mac OS X(x86_64) v10.13 unknown, screens 1680x1050; Retina


Title: R Subtracting columns within a list

Body:
Here is a solution:

lapply(b, function(x) {
  x[, 3] <- x[, 1] - x[, 2]
  x
})

[[1]]
  X12.16 X3...2.6 V3
1     12        6  6
2     13        9  4
3     14       12  2
4     15       15  0
5     16       18 -2

[[2]]
  X10.14 X2...1.5 V3
1     10        2  8
2     11        4  7
3     12        6  6
4     13        8  5
5     14       10  4


问:
Extract Bom Vocabulary IBM ODM in rule designer
Hi all i am new to IBM ODM Rule designer i need to export all the vocabulary tab to be exported to a document is there smart to do it instead of copying manually.

Please find the attachment of screenshot highlighted with red color.

答:
I think the best approach for extracting this vocabulary is to search for your *.voc files in your project.  Inside these text files, you will find lines like:

com.model.BillingItemExtender.addChargeToTotalCharge(com.model.BillingItem,java.math.BigDecimal)#phrase.action = add a charge of  {1} to the total charge of {0}

The vocabulary is everything after the equal sign.  Use your tool of choice to parse these lines with a regex and output the vocabulary.


问:
Spring Boot microservice response issue with Angular 2 http call
I am trying to call a GET request from my Angular 2 front-end app to a Spring Boot REST microservice, But when I calling, I am getting error like:

No Access-Control-Allow-Origin header is present on the requested resource

Here is my controller actions:

```<code>@RequestMapping(value = "/checkUsers", method = RequestMethod.POST)
public String checkLogin(@RequestBody Users user) throws Exception{

    ObjectMapper mapper = new ObjectMapper();
    List<Users> useObj = (List<Users>) userRepo.findAll();
    return(mapper.writeValueAsString(useObj));
}
</code>```

And when I am running my Angular, I am getting the above error. I added its screenshot

Is this from an Angular problem or from a Spring Boot microservice response problem?

答:
In you Application.java add a bean

```<code> @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    return bean;
  }
</code>```

It is global and it will work for every controller of your project.

Body:
I am trying to call a GET request from my Angular 2 front-end app to a Spring Boot REST microservice, But when I calling, I am getting error like:

No Access-Control-Allow-Origin header is present on the requested resource

Here is my controller actions:

@RequestMapping(value = "/checkUsers", method = RequestMethod.POST)
public String checkLogin(@RequestBody Users user) throws Exception{

    ObjectMapper mapper = new ObjectMapper();
    List<Users> useObj = (List<Users>) userRepo.findAll();
    return(mapper.writeValueAsString(useObj));
}

And when I am running my Angular, I am getting the above error. I added its screenshot

Is this from an Angular problem or from a Spring Boot microservice response problem?

Body:
In you Application.java add a bean

 @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    return bean;
  }

It is global and it will work for every controller of your project.


问:
Calling Sql procedure from Spring DAO
```<code>CREATE OR REPLACE TYPE NEW_ADDRS_OBJ
AS OBJECT (newAddress1 varchar2(20),
newAddress2 varchar2(20),
city varchar2(20),
state varchar2(20),
zip number(20))

create or replace type NEW_ADDRS_OBJ_ARRAY as table of NEW_ADDRS_OBJ

CREATE OR REPLACE TYPE ACCOUNT_OBJ
AS OBJECT (fname varchar2(20),
newAddress NEW_ADDRS_OBJ_ARRAY)

create or replace type ACCOUNT_OBJ_ARRAY as table of ACCOUNT_OBJ
</code>```

Now when calling the procedure

```<code>    CREATE OR REPLACE PROCEDURE INSERT_NEW_ADDRESS ( account_array in ACCOUNT_OBJ_ARRAY ) AS
tempaddres NEW_ADDRS_OBJ_ARRAY;
begin
  for i in 1..account_array.count loop
   tempaddres := NEW_ADDRS_OBJ_ARRAY();
   tempaddres := account_array(i).newAddress;
  for j in 1..tempaddres.count loop
    insert into TEST_ACCOUNT (ACCOUNT,NEWADDRESS1 ,NEWADDRESS2 ,CITY ,STATE ,ZIP )
       values(account_array(i).fname,
        tempaddres(j).newAddress1,
       tempaddres(j).newAddress2,
       tempaddres(j).city,
        tempaddres(j).state,
         tempaddres(j).zip);
  end loop;
  end loop;
end;
</code>```

i can make use of arraydescriptor to pass parent array ACCOUNT_OBJ_ARRAY ,but how to pass array inside it (the array of new address objects) from Spring procedure call?

答:
See the SO question "How to call oracle stored procedure which include user-defined type in java?" for an example of how to bind a SQL nested table of SQL object in java. Here the SQL object also itself contains a nested table of object. The method is similar (SQL arrays are bound by ARRAY Object in java, SQL objects are bound by STRUCT).

```<code>SQL> CREATE OR REPLACE PROCEDURE insert_new_address (
  2     account_array IN ACCOUNT_OBJ_ARRAY
  3     ) AS
  4     tempaddres NEW_ADDRS_OBJ_ARRAY;
  5  BEGIN
  6     FOR i IN 1 .. account_array.COUNT LOOP
  7        FOR j IN 1 .. account_array(i).newAddress.COUNT LOOP
  8           dbms_output.put_line(
  9              account_array(i).fname || ', ' ||
 10              account_array(i).newAddress(j).newAddress1 || ', ' ||
 11              account_array(i).newAddress(j).newAddress2 || ', ' ||
 12              account_array(i).newAddress(j).city || ', ' ||
 13              account_array(i).newAddress(j).state || ', ' ||
 14              account_array(i).newAddress(j).zip);
 15        END LOOP;
 16     END LOOP;
 17  END;
 18  /

Procedure created
</code>```

I will show a demo using the Oracle java jvm:

```<code>SQL> CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "ArrayDemo"
  2  as
  3
  4  import java.io.*;
  5  import java.sql.*;
  6  import oracle.sql.*;
  7  import oracle.jdbc.driver.*;
  8
  9  public class ArrayDemo {
 10
 11     public static void passArray() throws SQLException {
 12
 13        Connection conn = new OracleDriver().defaultConnection();
 14
 15        /*creation of NEW_ADDRS_OBJ*/
 16        StructDescriptor addrObjDescriptor =
 17           StructDescriptor.createDescriptor("NEW_ADDRS_OBJ",conn);
 18        Object[] addrAtributes = new Object[] {new String("address1"),
 19                                               new String("address2"),
 20                                               new String("city"),
 21                                               new String("state"),
 22                                               new Integer(12345)};
 23
 24        /*creation of NEW_ADDRS_OBJ_ARRAY*/
 25        ArrayDescriptor addrTabDescriptor =
 26           ArrayDescriptor.createDescriptor( "NEW_ADDRS_OBJ_ARRAY", conn );
 27        STRUCT addr1 = new STRUCT(addrObjDescriptor,conn,addrAtributes);
 28        STRUCT[] adrStructArray = {addr1};
 29        ARRAY arrayAddr = new ARRAY(addrTabDescriptor,conn,adrStructArray);
 30
 31        /*creation of ACCOUNT_OBJ*/
 32        StructDescriptor acctObjDescriptor =
 33           StructDescriptor.createDescriptor("ACCOUNT_OBJ",conn);
 34        Object[] acctAttributes = new Object[] {new String("AcctName"),
 35                                                arrayAddr};
 36
 37        /*creation of ACCOUNT_OBJ_ARRAY*/
 38        ArrayDescriptor acctTabDescriptor =
 39           ArrayDescriptor.createDescriptor( "ACCOUNT_OBJ_ARRAY", conn );
 40        STRUCT acct1 = new STRUCT(acctObjDescriptor,conn,acctAttributes);
 41        STRUCT[] acctStructArray = {acct1};
 42        ARRAY acctArray = new ARRAY(acctTabDescriptor,conn,acctStructArray);
 43
 44        /* statement */
 45        OraclePreparedStatement ps =
 46           (OraclePreparedStatement)conn.prepareStatement
 47              ("begin insert_new_address(:x); end;" );
 48
 49        ps.setARRAY( 1, acctArray );
 50        ps.execute();
 51
 52     }
 53  }
 54  /

Java created
</code>```

Now we call the java procedure:

```<code>SQL> CREATE OR REPLACE
  2  PROCEDURE show_java_calling_plsql
  3  AS LANGUAGE JAVA
  4  NAME 'ArrayDemo.passArray()';
  5  /

Procedure created

SQL> exec show_java_calling_plsql

AcctName, address1, address2, city, state, 12345

PL/SQL procedure successfully completed
</code>```

Title: Calling Sql procedure from Spring DAO

Body:
CREATE OR REPLACE TYPE NEW_ADDRS_OBJ
AS OBJECT (newAddress1 varchar2(20),
newAddress2 varchar2(20),
city varchar2(20),
state varchar2(20),
zip number(20))

create or replace type NEW_ADDRS_OBJ_ARRAY as table of NEW_ADDRS_OBJ

CREATE OR REPLACE TYPE ACCOUNT_OBJ
AS OBJECT (fname varchar2(20),
newAddress NEW_ADDRS_OBJ_ARRAY)

create or replace type ACCOUNT_OBJ_ARRAY as table of ACCOUNT_OBJ

Now when calling the procedure

    CREATE OR REPLACE PROCEDURE INSERT_NEW_ADDRESS ( account_array in ACCOUNT_OBJ_ARRAY ) AS
tempaddres NEW_ADDRS_OBJ_ARRAY;
begin
  for i in 1..account_array.count loop
   tempaddres := NEW_ADDRS_OBJ_ARRAY();
   tempaddres := account_array(i).newAddress;
  for j in 1..tempaddres.count loop
    insert into TEST_ACCOUNT (ACCOUNT,NEWADDRESS1 ,NEWADDRESS2 ,CITY ,STATE ,ZIP )
       values(account_array(i).fname,
        tempaddres(j).newAddress1,
       tempaddres(j).newAddress2,
       tempaddres(j).city,
        tempaddres(j).state,
         tempaddres(j).zip);
  end loop;
  end loop;
end;

i can make use of arraydescriptor to pass parent array ACCOUNT_OBJ_ARRAY ,but how to pass array inside it (the array of new address objects) from Spring procedure call?

Body:
See the SO question "How to call oracle stored procedure which include user-defined type in java?" for an example of how to bind a SQL nested table of SQL object in java. Here the SQL object also itself contains a nested table of object. The method is similar (SQL arrays are bound by ARRAY Object in java, SQL objects are bound by STRUCT).

SQL> CREATE OR REPLACE PROCEDURE insert_new_address (
  2     account_array IN ACCOUNT_OBJ_ARRAY
  3     ) AS
  4     tempaddres NEW_ADDRS_OBJ_ARRAY;
  5  BEGIN
  6     FOR i IN 1 .. account_array.COUNT LOOP
  7        FOR j IN 1 .. account_array(i).newAddress.COUNT LOOP
  8           dbms_output.put_line(
  9              account_array(i).fname || ', ' ||
 10              account_array(i).newAddress(j).newAddress1 || ', ' ||
 11              account_array(i).newAddress(j).newAddress2 || ', ' ||
 12              account_array(i).newAddress(j).city || ', ' ||
 13              account_array(i).newAddress(j).state || ', ' ||
 14              account_array(i).newAddress(j).zip);
 15        END LOOP;
 16     END LOOP;
 17  END;
 18  /

Procedure created

I will show a demo using the Oracle java jvm:

SQL> CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "ArrayDemo"
  2  as
  3
  4  import java.io.*;
  5  import java.sql.*;
  6  import oracle.sql.*;
  7  import oracle.jdbc.driver.*;
  8
  9  public class ArrayDemo {
 10
 11     public static void passArray() throws SQLException {
 12
 13        Connection conn = new OracleDriver().defaultConnection();
 14
 15        /*creation of NEW_ADDRS_OBJ*/
 16        StructDescriptor addrObjDescriptor =
 17           StructDescriptor.createDescriptor("NEW_ADDRS_OBJ",conn);
 18        Object[] addrAtributes = new Object[] {new String("address1"),
 19                                               new String("address2"),
 20                                               new String("city"),
 21                                               new String("state"),
 22                                               new Integer(12345)};
 23
 24        /*creation of NEW_ADDRS_OBJ_ARRAY*/
 25        ArrayDescriptor addrTabDescriptor =
 26           ArrayDescriptor.createDescriptor( "NEW_ADDRS_OBJ_ARRAY", conn );
 27        STRUCT addr1 = new STRUCT(addrObjDescriptor,conn,addrAtributes);
 28        STRUCT[] adrStructArray = {addr1};
 29        ARRAY arrayAddr = new ARRAY(addrTabDescriptor,conn,adrStructArray);
 30
 31        /*creation of ACCOUNT_OBJ*/
 32        StructDescriptor acctObjDescriptor =
 33           StructDescriptor.createDescriptor("ACCOUNT_OBJ",conn);
 34        Object[] acctAttributes = new Object[] {new String("AcctName"),
 35                                                arrayAddr};
 36
 37        /*creation of ACCOUNT_OBJ_ARRAY*/
 38        ArrayDescriptor acctTabDescriptor =
 39           ArrayDescriptor.createDescriptor( "ACCOUNT_OBJ_ARRAY", conn );
 40        STRUCT acct1 = new STRUCT(acctObjDescriptor,conn,acctAttributes);
 41        STRUCT[] acctStructArray = {acct1};
 42        ARRAY acctArray = new ARRAY(acctTabDescriptor,conn,acctStructArray);
 43
 44        /* statement */
 45        OraclePreparedStatement ps =
 46           (OraclePreparedStatement)conn.prepareStatement
 47              ("begin insert_new_address(:x); end;" );
 48
 49        ps.setARRAY( 1, acctArray );
 50        ps.execute();
 51
 52     }
 53  }
 54  /

Java created

Now we call the java procedure:

SQL> CREATE OR REPLACE
  2  PROCEDURE show_java_calling_plsql
  3  AS LANGUAGE JAVA
  4  NAME 'ArrayDemo.passArray()';
  5  /

Procedure created

SQL> exec show_java_calling_plsql

AcctName, address1, address2, city, state, 12345

PL/SQL procedure successfully completed


问:
How do I capitalize first character of sentence?
I need to capitalize first character of a sentence where sentence ends with a period. ( it could be multiple periods too) OR !  </p>

```<code> String result = "";
 Scanner scanner = new Scanner(content);
 scanner.useDelimiter("(?<=(\\.+))|(?<=!)");
 while (scanner.hasNext()) {
     String line = scanner.next();
     String line1 = line.substring(0, 1).toUpperCase() + line.substring(1);
     result = result + line1;
 }
</code>```

<p>When i do this , the whitespace new line character is present at the 0 index and the program doesn't capitalize the letter. </p>

答:
Trim the line:

String line = scanner.next().trim();

Body:
I need to capitalize first character of a sentence where sentence ends with a period. ( it could be multiple periods too) OR !

 String result = "";
 Scanner scanner = new Scanner(content);
 scanner.useDelimiter("(?<=(\\.+))|(?<=!)");
 while (scanner.hasNext()) {
     String line = scanner.next();
     String line1 = line.substring(0, 1).toUpperCase() + line.substring(1);
     result = result + line1;
 }

When i do this , the whitespace new line character is present at the 0 index and the program doesn't capitalize the letter.


问:
Checking Spelling of Word using HashTable
I have an array of words being inserted into a HashTable.
Then a function that will check if the word that the user typed in is spelled correctly.
My problem is that the spellchecker function only works if i initiate the word, but not if the user inputs the word(even though is spelled correctly).
Program is set up in a way that collisions do not occur, but if you have a suggestion on how to handle them please let me know.</p>

```<code>public class hashExample {

    String[] myArray = new String[31];

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String[] words = { "Achieve", "Across", "Apparently", "Admin",
                "Amazing", "Argument", "Assasination", "Accommodate" };

        hashExample theFunc = new hashExample();

        theFunc.hashFunction(words, theFunc.myArray);

        System.out.println("Enter a word to check for spelling...");

        String Word = input.nextLine();
        //Works only if I initiate Word.
        //String Word = "Accommodate";

        theFunc.findKey(Word);
    }

    public void hashFunction(String[] stringsForArray, String[] myArray) {

        for (int n = 0; n < stringsForArray.length; n++) {

            String newElementVal = stringsForArray[n];

            // Using ASCII values of the first four letters of each word.
            int arrayIndex = ((int)newElementVal.charAt(0) + (int)newElementVal.charAt(1)
            + (int)newElementVal.charAt(2)+ (int)newElementVal.charAt(3)) % 31;

            myArray[arrayIndex] = newElementVal;
        }
    }

    public void findKey(String key) {

        int indexHash = ((int)key.charAt(0) + (int)key.charAt(1) + (int)key.charAt(2)
        + (int)key.charAt(3)) % 31;

        String wordSearch = myArray[indexHash];

        if (key == wordSearch){
                System.out.println("Word is spelled correctly!");
            } else{
                System.out.println("Sorry word is not spelled correctly");
            }
    }
}
</code>```

答:
Change key == wordSearch to key.equals(wordSearch) then it will start working with inputs.

Because Strings are objects and if you want to compare two strings, use the .equals method to compare them instead of ==.

```<code>if (key.equals(wordSearch)) {
    System.out.println("Word is spelled correctly!");
} else {
    System.out.println("Sorry word is not spelled correctly");
}
</code>```

Body:
I have an array of words being inserted into a HashTable.
Then a function that will check if the word that the user typed in is spelled correctly.
My problem is that the spellchecker function only works if i initiate the word, but not if the user inputs the word(even though is spelled correctly).
Program is set up in a way that collisions do not occur, but if you have a suggestion on how to handle them please let me know.

public class hashExample {

    String[] myArray = new String[31];

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String[] words = { "Achieve", "Across", "Apparently", "Admin",
                "Amazing", "Argument", "Assasination", "Accommodate" };

        hashExample theFunc = new hashExample();

        theFunc.hashFunction(words, theFunc.myArray);

        System.out.println("Enter a word to check for spelling...");

        String Word = input.nextLine();
        //Works only if I initiate Word.
        //String Word = "Accommodate";

        theFunc.findKey(Word);
    }

    public void hashFunction(String[] stringsForArray, String[] myArray) {

        for (int n = 0; n < stringsForArray.length; n++) {

            String newElementVal = stringsForArray[n];

            // Using ASCII values of the first four letters of each word.
            int arrayIndex = ((int)newElementVal.charAt(0) + (int)newElementVal.charAt(1)
            + (int)newElementVal.charAt(2)+ (int)newElementVal.charAt(3)) % 31;

            myArray[arrayIndex] = newElementVal;
        }
    }

    public void findKey(String key) {

        int indexHash = ((int)key.charAt(0) + (int)key.charAt(1) + (int)key.charAt(2)
        + (int)key.charAt(3)) % 31;

        String wordSearch = myArray[indexHash];

        if (key == wordSearch){
                System.out.println("Word is spelled correctly!");
            } else{
                System.out.println("Sorry word is not spelled correctly");
            }
    }
}

Body:
Change key == wordSearch to key.equals(wordSearch) then it will start working with inputs.

Because Strings are objects and if you want to compare two strings, use the .equals method to compare them instead of ==.

if (key.equals(wordSearch)) {
    System.out.println("Word is spelled correctly!");
} else {
    System.out.println("Sorry word is not spelled correctly");
}


问:
MongoDB aggregate, how to addToSet each element of array in group pipeline
I have documents that contains a tags fields. It's a simple array with tag names inside, no object nor _id inside.
Just plain tags like this ["Protocol", "Access", "Leverage", "Capability"].

And in my group pipeline I tried something like 'selectedTags': { $addToSet: '$tags' } but then I end up with an array containing arrays of tags. And I get the same with $push.

I tried to use $each or $pushAll but they are not supported as grouping operator as my shell tell me.

Can someone help me on this one please ?

Thank you

Edit:

Sample docs:

```<code>{
    "_id" : "HWEdDGsq86x4ikDSQ",
    "teamId" : "AdLizGnPuqbWNsFHe",
    "ownerId" : "Qb5EigWjqn2t3bfxD",
    "type" : "meeting",
    "topic" : "Grass-roots hybrid knowledge user",
    "fullname" : "Guidouil",
    "startDate" : ISODate("2017-07-30T09:00:05.513Z"),
    "shareResults" : true,
    "open" : true,
    "language" : "fr",
    "tags" : [
        "Protocol",
        "Challenge",
        "Artificial Intelligence",
        "Capability"
    ],
    "isDemo" : true,
    "createdAt" : ISODate("2017-11-15T19:24:05.513Z"),
    "participantsCount" : 10,
    "ratersCount" : 10,
    "averageRating" : 3.4,
    "hasAnswers" : true,
    "updatedAt" : ISODate("2017-11-15T19:24:05.562Z")
}
{
    "_id" : "rXvkFndpXwJ6KAvNo",
    "teamId" : "AdLizGnPuqbWNsFHe",
    "ownerId" : "Qb5EigWjqn2t3bfxD",
    "type" : "meeting",
    "topic" : "Profit-focused modular system engine",
    "fullname" : "Guidouil",
    "startDate" : ISODate("2017-07-24T12:00:05.564Z"),
    "shareResults" : true,
    "open" : true,
    "language" : "fr",
    "tags" : [
        "Initiative",
        "Artificial Intelligence",
        "Protocol",
        "Utilisation"
    ],
    "isDemo" : true,
    "createdAt" : ISODate("2017-11-15T19:24:05.564Z"),
    "participantsCount" : 33,
    "ratersCount" : 33,
    "averageRating" : 2.9393939393939394,
    "hasAnswers" : true,
    "updatedAt" : ISODate("2017-11-15T19:24:05.753Z")
}
</code>```

Aggregation:

```<code>db.surveys.aggregate(
  { $match: query },
  {
    $group: {
      '_id': {
        'year': { $year: '$startDate' },
        'day': { $dayOfYear: '$startDate' },
      },
      'participants': { $sum: '$ratersCount' },
      'rating': { $avg: '$averageRating' },
      'surveys': { $push: '$_id' },
      'selectedTags': { $addToSet: '$tags' },
      'peoples': { $addToSet: '$fullname' },
    }
  },
  { $sort: { _id: 1 } }
);
</code>```

then I tried to change the selectedTags to { $push: { $each: '$tags' } } or { $pushAll: '$tags' } but this does not execute :(

Edit 2:

In javascript I do it like that:

```<code>return Surveys.aggregate(
  { $match: query },
  { $group: {
    _id: dateGroup,
    participants: { $sum: '$ratersCount' },
    rating: { $avg: '$averageRating' },
    surveys: { $push: '$_id' },
    selectedTags: { $push: '$tags' },
    peoples: { $addToSet: '$fullname' },
  } },
  { $project: {
    _id: null,
    selectedTags: {
      $reduce: {
        input: "$selectedTags",
        initialValue: [],
        in: { $setUnion: ["$$value", "$$this"] }
      }
    },
  } }
);
</code>```

答:
To mimic functionality of $addToSet update operator with $each modifier in aggregation pipeline you can use a combination of $push on grouping stage and $reduce + $setUnion on projection stage. E.g.:

```<code>db.collection.aggregate([
    {$group:{
       _id: null,
       selectedTags: { $push: '$tags' }
    }},
    {$project: {
        selectedTags: { $reduce: {
            input: "$selectedTags",
            initialValue: [],
            in: {$setUnion : ["$$value", "$$this"]}
        }}
    }}
])
</code>```

results with a single document which contains a distinct list of tags from all documents in selectedTags array.

Body:
I have documents that contains a tags fields. It's a simple array with tag names inside, no object nor _id inside.
Just plain tags like this ["Protocol", "Access", "Leverage", "Capability"].

And in my group pipeline I tried something like 'selectedTags': { $addToSet: '$tags' } but then I end up with an array containing arrays of tags. And I get the same with $push.

I tried to use $each or $pushAll but they are not supported as grouping operator as my shell tell me.

Can someone help me on this one please ?

Thank you

Edit:

Sample docs:

{
    "_id" : "HWEdDGsq86x4ikDSQ",
    "teamId" : "AdLizGnPuqbWNsFHe",
    "ownerId" : "Qb5EigWjqn2t3bfxD",
    "type" : "meeting",
    "topic" : "Grass-roots hybrid knowledge user",
    "fullname" : "Guidouil",
    "startDate" : ISODate("2017-07-30T09:00:05.513Z"),
    "shareResults" : true,
    "open" : true,
    "language" : "fr",
    "tags" : [
        "Protocol",
        "Challenge",
        "Artificial Intelligence",
        "Capability"
    ],
    "isDemo" : true,
    "createdAt" : ISODate("2017-11-15T19:24:05.513Z"),
    "participantsCount" : 10,
    "ratersCount" : 10,
    "averageRating" : 3.4,
    "hasAnswers" : true,
    "updatedAt" : ISODate("2017-11-15T19:24:05.562Z")
}
{
    "_id" : "rXvkFndpXwJ6KAvNo",
    "teamId" : "AdLizGnPuqbWNsFHe",
    "ownerId" : "Qb5EigWjqn2t3bfxD",
    "type" : "meeting",
    "topic" : "Profit-focused modular system engine",
    "fullname" : "Guidouil",
    "startDate" : ISODate("2017-07-24T12:00:05.564Z"),
    "shareResults" : true,
    "open" : true,
    "language" : "fr",
    "tags" : [
        "Initiative",
        "Artificial Intelligence",
        "Protocol",
        "Utilisation"
    ],
    "isDemo" : true,
    "createdAt" : ISODate("2017-11-15T19:24:05.564Z"),
    "participantsCount" : 33,
    "ratersCount" : 33,
    "averageRating" : 2.9393939393939394,
    "hasAnswers" : true,
    "updatedAt" : ISODate("2017-11-15T19:24:05.753Z")
}

Aggregation:

db.surveys.aggregate(
  { $match: query },
  {
    $group: {
      '_id': {
        'year': { $year: '$startDate' },
        'day': { $dayOfYear: '$startDate' },
      },
      'participants': { $sum: '$ratersCount' },
      'rating': { $avg: '$averageRating' },
      'surveys': { $push: '$_id' },
      'selectedTags': { $addToSet: '$tags' },
      'peoples': { $addToSet: '$fullname' },
    }
  },
  { $sort: { _id: 1 } }
);

then I tried to change the selectedTags to { $push: { $each: '$tags' } } or { $pushAll: '$tags' } but this does not execute :(

Edit 2:

In javascript I do it like that:

return Surveys.aggregate(
  { $match: query },
  { $group: {
    _id: dateGroup,
    participants: { $sum: '$ratersCount' },
    rating: { $avg: '$averageRating' },
    surveys: { $push: '$_id' },
    selectedTags: { $push: '$tags' },
    peoples: { $addToSet: '$fullname' },
  } },
  { $project: {
    _id: null,
    selectedTags: {
      $reduce: {
        input: "$selectedTags",
        initialValue: [],
        in: { $setUnion: ["$$value", "$$this"] }
      }
    },
  } }
);

Body:
To mimic functionality of $addToSet update operator with $each modifier in aggregation pipeline you can use a combination of $push on grouping stage and $reduce + $setUnion on projection stage. E.g.:

db.collection.aggregate([
    {$group:{
       _id: null,
       selectedTags: { $push: '$tags' }
    }},
    {$project: {
        selectedTags: { $reduce: {
            input: "$selectedTags",
            initialValue: [],
            in: {$setUnion : ["$$value", "$$this"]}
        }}
    }}
])

results with a single document which contains a distinct list of tags from all documents in selectedTags array.


问:
onSelect function in antd calendar component
How to get the selected date inside the onSelect function, after update the selected date in the state and

```<code>onSelect = (cal) => {
      this.setState({  selectedValue: cal   });
      alert(this.state.selectedValue);
</code>```

I got the previous date in the alert but i need the current selected date, how to achieve this...?

答:
From the antd docs, DatePicker uses an onChange event, not onSelect.

This should log the correct value.

```<code><DatePicker
    format="MM/DD/YYYY"
    placeholder="Banana"
    locale="en_US"
    onChange={console.log}
/>
</code>```

Body:
How to get the selected date inside the onSelect function, after update the selected date in the state and

onSelect = (cal) => {
      this.setState({  selectedValue: cal   });
      alert(this.state.selectedValue);

I got the previous date in the alert but i need the current selected date, how to achieve this...?

Body:
From the antd docs, DatePicker uses an onChange event, not onSelect.

This should log the correct value.

<DatePicker
    format="MM/DD/YYYY"
    placeholder="Banana"
    locale="en_US"
    onChange={console.log}
/>


问:
Count the number of elements in a Json file
All type of json elements like objects in json files arrays and simple key value pairs.</p>

答:
When you call JSONParser parser = new JSONParser(); obj = parser.parse(path);

parser.parse() expects an actual JSON string, not the path to the JSON file.

It wants to see something like this:

```<code>json.parse("{ "name":"John", "age":31, "city":"New York" }");
</code>```

To fix your code, you can do this:

```<code>List < String > list = new ArrayList < >();

try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {

    //br returns as stream and convert it into a List
    list = br.lines().collect(Collectors.toList());

} catch(IOException e) {
    e.printStackTrace();
}

StringBuilder sb = new StringBuilder();
for (String s: list) {
    sb.append(s);
}

String json = sb.toString()
JSONParser parser = new JSONParser();
obj = parser.parse(json);
</code>```

Body:
When you call JSONParser parser = new JSONParser(); obj = parser.parse(path);

parser.parse() expects an actual JSON string, not the path to the JSON file.

It wants to see something like this:

json.parse("{ "name":"John", "age":31, "city":"New York" }");

To fix your code, you can do this:

List < String > list = new ArrayList < >();

try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {

    //br returns as stream and convert it into a List
    list = br.lines().collect(Collectors.toList());

} catch(IOException e) {
    e.printStackTrace();
}

StringBuilder sb = new StringBuilder();
for (String s: list) {
    sb.append(s);
}

String json = sb.toString()
JSONParser parser = new JSONParser();
obj = parser.parse(json);


问:
android generate randomly unique color code
I want to generate random,unique color code. Is there any algorithm ?</p>

答:
```<code>Random color = new Random();

Color randomColor = new Color(color.nextInt(256),color.nextInt(256),color.nextInt(256));
</code>```

Ofcouse pedantically speaking, not assured to be random ;)

Body:
Random color = new Random();

Color randomColor = new Color(color.nextInt(256),color.nextInt(256),color.nextInt(256));

Ofcouse pedantically speaking, not assured to be random ;)


问:
How to import/consume ES6 modules which are in .js extension with --experimental-module?
My mjs files can import other mjs file but cannot import js file in the chain of imports. In the following example imagine that kale.js is a 3rd party library e.g. lodash-es/isObject.js
e.g.

```<code>// apple.mjs
import {banana} from './banana.mjs';
</code>```

..and

```<code>// banana.mjs
import {kale} from './kale.js';
export function banana() {};
</code>```

and kale.js is

```<code>// kale.js
export function kale() {};
export function kite() {}
</code>```

I get following error:-

$ node --experimental-modules ./test/apple.mjs (node:389272)
  ExperimentalWarning: The ESM module loader is experimental.
  SyntaxError: The requested module does not provide an export named
  'kale'
      at checkComplete (internal/loader/ModuleJob.js:75:27)
      at moduleJob.linked.then (internal/loader/ModuleJob.js:58:11)
      at

Tried custom resolve function but still no luck:

```<code>import url from 'url';
import path from 'path';

const JS_EXTENSIONS = new Set(['.js', '.mjs']);

export default function resolve(specifier, parentModuleURL, defaultResolve ) {
  console.log('resolving '+specifier);
  if (/^\.{0,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) {
    return defaultResolve(specifier, parentModuleURL);
  }
  const resolved = new url.URL(specifier, parentModuleURL);
  const ext = path.extname(resolved.pathname);
  if (!JS_EXTENSIONS.has(ext)) {
    throw new Error(
      `Cannot load file with non-JavaScript file extension ${ext}.`);
  }
  return {
    url: resolved.href,
    format: 'esm'
  };
}
</code>```

and I am running it like this:

```<code>node --experimental-modules --loader ./custom-loader.mjs apple.mjs
</code>```

node version v8.9.1

I get following error:

```<code>SyntaxError: Unexpected token export
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:599:28)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at createDynamicModule (internal/loader/ModuleRequest.js:43:15)
    at setExecutor (internal/loader/ModuleWrap.js:40:23)
    at file:///C:/Users/user/projs/dev/my-project-js/test/es2015/test/kale.js:8:36
</code>```

UPDATE --- using @std/esm approach as per the answer

All code is here https://github.com/yogeshgadge/mjs-mixed-loaders.git

This is what worked:

```<code>//index.js
require = require("@std/esm")(module,{"esm":"js"});
module.exports = require("./apple.mjs").default;
</code>```

Then I run it as below (and now I am eating kale:)):-

```<code>$ node index.js
eating kale with some lodash
</code>```

package.json approach did not work.

```<code>$ node -r @std/esm apple.mjs
C:\Users\myuser\projs\github\mjs-in-harmony\node_modules\lodash-es\isObject.js:31
export default isObject;
^^^^^^

SyntaxError: Unexpected token export
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:537:28)
    at Object.Module._extensions..js (module.js:584:10)
</code>```

答:
You can try using the @std/esm loader with "@std/esm":"cjs" options:

Install @std/esm (npm i --save @std/esm)

Add "@std/esm":"cjs" to your package.json

Now node -r @std/esm apple.mjs will load successfully

Body:
My mjs files can import other mjs file but cannot import js file in the chain of imports. In the following example imagine that kale.js is a 3rd party library e.g. lodash-es/isObject.js
e.g.

// apple.mjs
import {banana} from './banana.mjs';

..and

// banana.mjs
import {kale} from './kale.js';
export function banana() {};

and kale.js is

// kale.js
export function kale() {};
export function kite() {}

I get following error:-

$ node --experimental-modules ./test/apple.mjs (node:389272)
  ExperimentalWarning: The ESM module loader is experimental.
  SyntaxError: The requested module does not provide an export named
  'kale'
      at checkComplete (internal/loader/ModuleJob.js:75:27)
      at moduleJob.linked.then (internal/loader/ModuleJob.js:58:11)
      at

Tried custom resolve function but still no luck:

import url from 'url';
import path from 'path';

const JS_EXTENSIONS = new Set(['.js', '.mjs']);

export default function resolve(specifier, parentModuleURL, defaultResolve ) {
  console.log('resolving '+specifier);
  if (/^\.{0,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) {
    return defaultResolve(specifier, parentModuleURL);
  }
  const resolved = new url.URL(specifier, parentModuleURL);
  const ext = path.extname(resolved.pathname);
  if (!JS_EXTENSIONS.has(ext)) {
    throw new Error(
      `Cannot load file with non-JavaScript file extension ${ext}.`);
  }
  return {
    url: resolved.href,
    format: 'esm'
  };
}

and I am running it like this:

node --experimental-modules --loader ./custom-loader.mjs apple.mjs

node version v8.9.1

I get following error:

SyntaxError: Unexpected token export
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:599:28)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at createDynamicModule (internal/loader/ModuleRequest.js:43:15)
    at setExecutor (internal/loader/ModuleWrap.js:40:23)
    at file:///C:/Users/user/projs/dev/my-project-js/test/es2015/test/kale.js:8:36

UPDATE --- using @std/esm approach as per the answer

All code is here https://github.com/yogeshgadge/mjs-mixed-loaders.git

This is what worked:

//index.js
require = require("@std/esm")(module,{"esm":"js"});
module.exports = require("./apple.mjs").default;

Then I run it as below (and now I am eating kale:)):-

$ node index.js
eating kale with some lodash

package.json approach did not work.

$ node -r @std/esm apple.mjs
C:\Users\myuser\projs\github\mjs-in-harmony\node_modules\lodash-es\isObject.js:31
export default isObject;
^^^^^^

SyntaxError: Unexpected token export
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:537:28)
    at Object.Module._extensions..js (module.js:584:10)


问:
Angular js ng-click not working
I am trying to add form validation using JavaScript. When I add

```<code> document.getElementById("one").setAttribute("ng-click", "insertData()");
</code>```

to validateForm function, it does not work after I press the button.

When I move that line out of validateForm function it works, but does not perform form validation.

Here is my code:

```<code><!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

</head>
<body>

<div class="container">
   <div ng-app="myapp" ng-controller = "controller">
        <div class="row">
            <div id="divID"> </div>
                <div class="col-sm-12 col-md-10  col-md-offset-1 ">
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                            <input class="form-control" id = "k" placeholder="Name" ng-model = "username" name="user_name" type="text" autofocus>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                                <i class="glyphicon glyphicon-user"></i></span>
                            <input class="form-control" placeholder="NIC" ng-model = "nic" name="NIC" type="text" value="">
                        </div>
                    </div>

             <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"> @</span>
                            <input class="form-control" placeholder="Email" ng-model = "Email" name="email" type="email" value="">
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                                <i class="glyphicon glyphicon-lock"></i></span>
                            <input class="form-control" placeholder="Password" ng-model = "password" name="Password" type="password" value="">
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                                <i class="glyphicon glyphicon-lock"></i></span>
                            <input class="form-control" placeholder="Confierm Password" ng-model = "Conf_password" name="Conf_password" type="password" value="">
                        </div>
                    </div>

                    <div class="form-group">
                        <input type="submit" id = 'one' onclick="validateForm()"  class="btn btn-lg btn-primary btn-block" value="Sign Up">
                    </div>
                </div>
            </div>
       </div>
   </div>
  </body>
</html>
  <Script>
     function validateForm()
       {
       var x = document.getElementById("k").value;
       if (x == "")
         {
         document.getElementById("k").setAttribute("placeholder", "Insert Name");
         }
         else
         {
           //document.getElementById("one").removeAttribute("onclick");
           document.getElementById("one").setAttribute("ng-click", "insertData()");
          }
       }
      // when add this part here code working fine ---- document.getElementById("one").setAttribute("ng-click", "insertData()");

     var app = angular.module("myapp", []);
     app.controller("controller",function($scope,$http){
     $scope.insertData = function()
        {
         $http.post(
        "Signup.php",
        {'username':$scope.username,'nic':$scope.nic,'email':$scope.Email,'password':$scope.password,'Conf_password':$scope.Conf_password }

    ).then(function(data){

     var result = angular.toJson(data.data);
     var myEl = angular.element( document.querySelector( '#divID' ) );
     if(result.replace(/^"|"$/g, '') == 1)
       {
       myEl.replaceWith("<div class='alert alert-success alert-dismissable fade in'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Success!</strong>You have sucessfully registerd. Please login</div>");
       }
     else
        {
         myEl.replaceWith(result.replace(/^"|"$/g, ''));
         }
      $scope.username = null;
    });
  }
});

</script>
</code>```

答:
You need to tell Angular that you've added an attribute, otherwise it doesn't work. When adding an attribute to your template file, Angular knows, but when adding it by setAttribute(), Angular has no idea.

In your controller, add the following two dependencies:

```<code>app.controller("controller", function($compile, $document, $scope, $http) {
    //
});
</code>```

Now, after adding the attribute to the element, you need to re-compile it:

```<code>$document.getElementById("one").setAttribute("ng-click", "insertData()");

// Try this:
$compile($document.getElementById("one"));

// If it doesn't work, or gives an error, try this:
$compile($document.getElementById("one"))($scope);
</code>```

Note: I use $document, not document

Documentation for $compile

Note: I cannot really test if this works for your code, but it should at least point you in the right direction. Your problem is that Angular doesn't know you added the attribute.

Title: Angular js ng-click not working

Body:
I am trying to add form validation using JavaScript. When I add

 document.getElementById("one").setAttribute("ng-click", "insertData()");

to validateForm function, it does not work after I press the button.

When I move that line out of validateForm function it works, but does not perform form validation.

Here is my code:

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                            <input class="form-control" id = "k" placeholder="Name" ng-model = "username" name="user_name" type="text" autofocus>

                            <input class="form-control" placeholder="NIC" ng-model = "nic" name="NIC" type="text" value="">

                             @
                            <input class="form-control" placeholder="Email" ng-model = "Email" name="email" type="email" value="">

                            <input class="form-control" placeholder="Password" ng-model = "password" name="Password" type="password" value="">

                            <input class="form-control" placeholder="Confierm Password" ng-model = "Conf_password" name="Conf_password" type="password" value="">

                        <input type="submit" id = 'one' onclick="validateForm()"  class="btn btn-lg btn-primary btn-block" value="Sign Up">

Body:
You need to tell Angular that you've added an attribute, otherwise it doesn't work. When adding an attribute to your template file, Angular knows, but when adding it by setAttribute(), Angular has no idea.

In your controller, add the following two dependencies:

app.controller("controller", function($compile, $document, $scope, $http) {
    //
});

Now, after adding the attribute to the element, you need to re-compile it:

$document.getElementById("one").setAttribute("ng-click", "insertData()");

// Try this:
$compile($document.getElementById("one"));

// If it doesn't work, or gives an error, try this:
$compile($document.getElementById("one"))($scope);

Note: I use $document, not document

Documentation for $compile

Note: I cannot really test if this works for your code, but it should at least point you in the right direction. Your problem is that Angular doesn't know you added the attribute.


问:
How to find the nearest common ancestors of two or more nodes?
Users selects two or more elements in a HTML page. What i want to accomplish is to find those elements' common ancestors (so body node would be the common ancestor if none found before) ?

P.S: It can be achieved with XPath but it is not a preferable option for me. Also it may be found with css selector parsing but i think it is a dirty method (?)

Thank you.

答:
PureJS</p>

```<code>function getFirstCommonAncestor(nodeA, nodeB) {
    const parentsOfA = this.getParents(nodeA);
    const parentsOfB = this.getParents(nodeB);
    return parentsOfA.find((item) => parentsOfB.indexOf(item) !== -1);
}

function getParents(node) {
    const result = [];
    while (node = node.parentElement) {
        result.push(node);
    }
    return result;
}
</code>```

Body:
PureJS

function getFirstCommonAncestor(nodeA, nodeB) {
    const parentsOfA = this.getParents(nodeA);
    const parentsOfB = this.getParents(nodeB);
    return parentsOfA.find((item) => parentsOfB.indexOf(item) !== -1);
}

function getParents(node) {
    const result = [];
    while (node = node.parentElement) {
        result.push(node);
    }
    return result;
}


问:
VBA - Apply same MouseMove code to all Labels (Event Handling Collections)
I have a few Labels on my worksheet, and each one has the following code to display on the Status Bar the Range they're currently at (as the mouse moves over them):

```<code>Private Sub Label1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

rng = ActiveSheet.Shapes("Label1").TopLeftCell.Address
Application.StatusBar = rng

End Sub
</code>```

Is there any way I can apply this same code to ALL the labels instead of rewriting it over and over again?

答:
I added a new class called LabelHandler:

```<code>Option Explicit

    Public WithEvents lbl As msforms.Label

Private Sub lbl_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    Dim rng As String
    rng = ActiveSheet.Shapes(lbl.Name).TopLeftCell.Address
    Application.StatusBar = rng
End Sub
</code>```

In a New Module I added the following:

```<code>Public myLabels As Collection 'Of LabelHandler

    Sub init()
    Dim ws As Worksheet
    Dim myLabel As LabelHandler
        Set myLabels = New Collection
       For Each l In ActiveSheet.OLEObjects
            Set myLabel = New LabelHandler
            Set myLabel.lbl = l.Object
            myLabels.Add myLabel
       Next
    End Sub
</code>```

Now when I run my cursor over the label, I get $F$11 in the status window

EDIT
You will want to edit your For Each loop to only add the label objects you want to the collection. Perhaps by their Name property

```<code>   For Each l In ActiveSheet.OLEObjects
        If Left(l.Name,5)="Label" Then
             Set myLabel = New LabelHandler
             Set myLabel.lbl = l.Object
             myLabels.Add myLabel
        End If
   Next
</code>```

Or for all Labels:

```<code>   For Each l In ActiveSheet.OLEObjects
        If l.progID = "Forms.Label.1" Then
             Set myLabel = New LabelHandler
             Set myLabel.lbl = l.Object
             myLabels.Add myLabel
        End If
   Next
</code>```

Body:
I have a few Labels on my worksheet, and each one has the following code to display on the Status Bar the Range they're currently at (as the mouse moves over them):

Private Sub Label1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

rng = ActiveSheet.Shapes("Label1").TopLeftCell.Address
Application.StatusBar = rng

End Sub

Is there any way I can apply this same code to ALL the labels instead of rewriting it over and over again?

Body:
I added a new class called LabelHandler:

Option Explicit

    Public WithEvents lbl As msforms.Label

Private Sub lbl_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    Dim rng As String
    rng = ActiveSheet.Shapes(lbl.Name).TopLeftCell.Address
    Application.StatusBar = rng
End Sub

In a New Module I added the following:

Public myLabels As Collection 'Of LabelHandler

    Sub init()
    Dim ws As Worksheet
    Dim myLabel As LabelHandler
        Set myLabels = New Collection
       For Each l In ActiveSheet.OLEObjects
            Set myLabel = New LabelHandler
            Set myLabel.lbl = l.Object
            myLabels.Add myLabel
       Next
    End Sub

Now when I run my cursor over the label, I get $F$11 in the status window

EDIT
You will want to edit your For Each loop to only add the label objects you want to the collection. Perhaps by their Name property

   For Each l In ActiveSheet.OLEObjects
        If Left(l.Name,5)="Label" Then
             Set myLabel = New LabelHandler
             Set myLabel.lbl = l.Object
             myLabels.Add myLabel
        End If
   Next

Or for all Labels:

   For Each l In ActiveSheet.OLEObjects
        If l.progID = "Forms.Label.1" Then
             Set myLabel = New LabelHandler
             Set myLabel.lbl = l.Object
             myLabels.Add myLabel
        End If
   Next


问:
ng-repeat not refreshing in select options
Currently working with AngularJS, I have a problem with a 'select-options'.

I'm doing a $http request to fetch data from a Cloud SQL database.

To do this, I call a function which is in my factory and that returns the data from my DB.

Here is my JS.

As you can see, I first initialize my 'controller.connections' variable with an array of 2 values (1 and 2).

After fetching my data (with my 'f_getData' function), I change the value of that array (I add 4 values and I don't use the data I fetch just to test, but the behaviour is the same).

Here is my HTML.

For your information, my ng-app is on the 'html' tag, and ng-controller is on the 'body' tag.
I'm using ng-repeat for my options because I had the same behaviour using ng-options.
Right underneath my select I have a ng-repeat with the exact same condition to test.

Here is the behaviour.

As you can see, my variable that is in my ng-repeat for my select doesn't seem to be updated.
Although, that same variable is updated on the ng-repeat on the 'p' tag.

So I tried :

$scope.$apply() in the callback ('then'), but console says $digest is being done. I also tried after the callback, it says that $apply() is being done, so I tried a $timeout of 2 seconds which didn't do anything.

$scope.connections instead of controller.connections, but I guess that generates a problem because ng-repeat creates its own scope.

Using a temporary variable for my big array in the callback, then changing the value of my 'connections' variable to this temporary variable out of the callback, and finaly calling $scope.$apply(). The ng-repeat on my options is not updated, but my ng-repeat on the 'p' tag is.

So basically my problem is : I can't use ng-repeat nor ng-options to create a dynamic select input.
Does anyone have a solution ?
Thanks in advance

答:
To all of you who tried to help me, thank you very much.
I resolved my problem (with a bit of change).
I started to use the old school awful way to fill a select with options by creating the options element in my JS while I would find a solution. While looking for a way to reset the value of my select, I found a plunker of someone who was using ng-options and it was working. I therefore took the code of this plunker and pasted it in my code.

And it worked !

Then I tried to adapt it to my code and it worked till a certain point.

That point was the div where my select was. I tried to put it in a few different places (working) till the div it was at the beginning (works a bit :sometimes when I refresh, options would not show, then refreshing again would solve the problem).

I'm still trying to figure out what was the problem.

Thanks everybody for your help.

I'm sorry for giving you screenshots of my code, I'm not familiar with posting questions here, I'm that kind of guy using the answers rather than finding them...

But I assure you that I take note of all of your critics for my future questions.

Thanks again !

P.S : How do we close a subject, please ? ^^


问:
Authentication on Server side routes in Meteor
What is the best way (most secure and easiest) to authenticate a user for a server side route?

Software/Versions

I'm using the latest Iron Router 1.* and Meteor 1.* and to begin, I'm just using accounts-password.

Reference code

I have a simple server side route that renders a pdf to the screen:

both/routes.js

```<code>Router.route('/pdf-server', function() {
  var filePath = process.env.PWD + "/server/.files/users/test.pdf";
  console.log(filePath);
  var fs = Npm.require('fs');
  var data = fs.readFileSync(filePath);
  this.response.write(data);
  this.response.end();
}, {where: 'server'});
</code>```

As an example, I'd like to do something close to what this SO answer suggested:

On the server:

```<code>var Secrets = new Meteor.Collection("secrets");

Meteor.methods({
  getSecretKey: function () {
    if (!this.userId)
      // check if the user has privileges
      throw Meteor.Error(403);
    return Secrets.insert({_id: Random.id(), user: this.userId});
  },
});
</code>```

And then in client code:

```<code>testController.events({
  'click button[name=get-pdf]': function () {
      Meteor.call("getSecretKey", function (error, response) {
        if (error) throw error;

        if (response)
          Router.go('/pdf-server');
      });
  }
});
</code>```

But even if I somehow got this method working, I'd still be vulnerable to users just putting in a URL like '/pdf-server' unless the route itself somehow checked the Secrets collection right?

In the Route, I could get the request, and somehow get the header information?

```<code>Router.route('/pdf-server', function() {
  var req = this.request;
  var res = this.response;
}, {where: 'server'});
</code>```

And from the client pass a token over the HTTP header, and then in the route check if the token is good from the Collection?

答:
I truly believe using HTTP headers are the best solution to this problem because they're simple and don't require messing about with cookies or developing a new authentication scheme.

I loved @kahmali's answer, so I wrote it to work with WebApp and a simple XMLHttpRequest.  This has been tested on Meteor 1.6.

Client

```<code>import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';

// Skipping ahead to the upload logic
const xhr = new XMLHttpRequest();
const form = new FormData();

// Add files
files.forEach((file) => {
  form.append(file.name,
    // So BusBoy sees as file instead of field, use Blob
    new Blob([file.data], { type: 'text/plain' })); // w/e your mime type is
});

// XHR progress, load, error, and readystatechange event listeners here

// Open Connection
xhr.open('POST', '/path/to/upload', true);

// Meteor authentication details (must happen *after* xhr.open)
xhr.setRequestHeader('X-Auth-Token', Accounts._storedLoginToken());
xhr.setRequestHeader('X-User-Id', Meteor.userId());

// Send
xhr.send(form);
</code>```

Server

```<code>import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import { Roles } from 'meteor/alanning:roles'; // optional
const BusBoy = require('connect-busboy');
const crypto = require('crypto'); // built-in Node library

WebApp.connectHandlers
  .use(BusBoy())
  .use('/path/to/upload', (req, res) => {
    const user = req.headers['x-user-id'];
    // We have to get a base64 digest of the sha256 hashed login token
    // I'm not sure when Meteor changed to hashed tokens, but this is
    // one of the major differences from @kahmali's answer
    const hash = crypto.createHash('sha256');
    hash.update(req.headers['x-auth-token']);

    // Authentication (is user logged-in)
    if (!Meteor.users.findOne({
      _id: user,
      'services.resume.loginTokens.hashedToken': hash.digest('base64'),
    })) {
      // User not logged in; 401 Unauthorized
      res.writeHead(401);
      res.end();
      return;
    }

    // Authorization
    if (!Roles.userIsInRole(user, 'whatever')) {
      // User is not authorized; 403 Forbidden
      res.writeHead(403);
      res.end();
      return;
    }

    if (req.busboy) {
      // Handle file upload
      res.writeHead(201); // eventually
      res.end();
    } else {
      // Something went wrong
      res.writeHead(500); // server error
      res.end();
    }
  });
</code>```

I hope this helps someone!

Body:
What is the best way (most secure and easiest) to authenticate a user for a server side route?

Software/Versions

I'm using the latest Iron Router 1.* and Meteor 1.* and to begin, I'm just using accounts-password.

Reference code

I have a simple server side route that renders a pdf to the screen:

both/routes.js

Router.route('/pdf-server', function() {
  var filePath = process.env.PWD + "/server/.files/users/test.pdf";
  console.log(filePath);
  var fs = Npm.require('fs');
  var data = fs.readFileSync(filePath);
  this.response.write(data);
  this.response.end();
}, {where: 'server'});

As an example, I'd like to do something close to what this SO answer suggested:

On the server:

var Secrets = new Meteor.Collection("secrets");

Meteor.methods({
  getSecretKey: function () {
    if (!this.userId)
      // check if the user has privileges
      throw Meteor.Error(403);
    return Secrets.insert({_id: Random.id(), user: this.userId});
  },
});

And then in client code:

testController.events({
  'click button[name=get-pdf]': function () {
      Meteor.call("getSecretKey", function (error, response) {
        if (error) throw error;

        if (response)
          Router.go('/pdf-server');
      });
  }
});

But even if I somehow got this method working, I'd still be vulnerable to users just putting in a URL like '/pdf-server' unless the route itself somehow checked the Secrets collection right?

In the Route, I could get the request, and somehow get the header information?

Router.route('/pdf-server', function() {
  var req = this.request;
  var res = this.response;
}, {where: 'server'});

And from the client pass a token over the HTTP header, and then in the route check if the token is good from the Collection?

Body:
I truly believe using HTTP headers are the best solution to this problem because they're simple and don't require messing about with cookies or developing a new authentication scheme.

I loved @kahmali's answer, so I wrote it to work with WebApp and a simple XMLHttpRequest.  This has been tested on Meteor 1.6.

Client

import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';

// Skipping ahead to the upload logic
const xhr = new XMLHttpRequest();
const form = new FormData();

// Add files
files.forEach((file) => {
  form.append(file.name,
    // So BusBoy sees as file instead of field, use Blob
    new Blob([file.data], { type: 'text/plain' })); // w/e your mime type is
});

// XHR progress, load, error, and readystatechange event listeners here

// Open Connection
xhr.open('POST', '/path/to/upload', true);

// Meteor authentication details (must happen *after* xhr.open)
xhr.setRequestHeader('X-Auth-Token', Accounts._storedLoginToken());
xhr.setRequestHeader('X-User-Id', Meteor.userId());

// Send
xhr.send(form);

Server

import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import { Roles } from 'meteor/alanning:roles'; // optional
const BusBoy = require('connect-busboy');
const crypto = require('crypto'); // built-in Node library

WebApp.connectHandlers
  .use(BusBoy())
  .use('/path/to/upload', (req, res) => {
    const user = req.headers['x-user-id'];
    // We have to get a base64 digest of the sha256 hashed login token
    // I'm not sure when Meteor changed to hashed tokens, but this is
    // one of the major differences from @kahmali's answer
    const hash = crypto.createHash('sha256');
    hash.update(req.headers['x-auth-token']);

    // Authentication (is user logged-in)
    if (!Meteor.users.findOne({
      _id: user,
      'services.resume.loginTokens.hashedToken': hash.digest('base64'),
    })) {
      // User not logged in; 401 Unauthorized
      res.writeHead(401);
      res.end();
      return;
    }

    // Authorization
    if (!Roles.userIsInRole(user, 'whatever')) {
      // User is not authorized; 403 Forbidden
      res.writeHead(403);
      res.end();
      return;
    }

    if (req.busboy) {
      // Handle file upload
      res.writeHead(201); // eventually
      res.end();
    } else {
      // Something went wrong
      res.writeHead(500); // server error
      res.end();
    }
  });

I hope this helps someone!


问:
file.exist for online available files in R
I want to test whether one file exist on gitub, file.exists() is not working:

```<code>t= "https://raw.githubusercontent.com/jcolomb/HCS_data_1/master/Project_exampledata1/Routputs/Min_permutated_1.csv"
file.exists(t)
#FALSE
read.csv2(t) #that does work
</code>```

I tried also:

```<code> data = try(read.csv2(paste0(onlinemin,'/Min_',Name_project,'.csv'),dec = ".")
 ,T)
</code>```

but then exists("data") is true even when try() is not successful.

any idea?

答:
Since I did not want to use another package, I finally used

```<code>data = try(read.csv2(paste0(onlinemin,'/Min_',Name_project,'.csv'),dec = ".")
,T)
if (class(data)=="try-error") ...
</code>```

not very elegant, but works.

Body:
I want to test whether one file exist on gitub, file.exists() is not working:

t= "https://raw.githubusercontent.com/jcolomb/HCS_data_1/master/Project_exampledata1/Routputs/Min_permutated_1.csv"
file.exists(t)
#FALSE
read.csv2(t) #that does work

I tried also:

 data = try(read.csv2(paste0(onlinemin,'/Min_',Name_project,'.csv'),dec = ".")
 ,T)

but then exists("data") is true even when try() is not successful.

any idea?

Body:
Since I did not want to use another package, I finally used

data = try(read.csv2(paste0(onlinemin,'/Min_',Name_project,'.csv'),dec = ".")
,T)
if (class(data)=="try-error") ...

not very elegant, but works.


问:
select single item from a collection : Python
I created a utility function to return the expected single item from an generator expression

```<code>print one(name for name in ('bob','fred') if name=='bob')
</code>```

Is this a good way to go about it?

```<code>def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')
</code>```

答:
A simpler solution is to use tuple unpacking.  This will already do everything you want, including checking that it contains exactly one item.

Single item:

```<code> >>> name, = (name for name in ('bob','fred') if name=='bob')
 >>> name
 'bob'
</code>```

Too many items:

```<code>>>> name, = (name for name in ('bob','bob') if name=='bob')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
</code>```

No items:

```<code>>>> name, = (name for name in ('fred','joe') if name=='bob')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack
</code>```

OwnerDisplayName: GHZ

Body:
I created a utility function to return the expected single item from an generator expression

print one(name for name in ('bob','fred') if name=='bob')

Is this a good way to go about it?

def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')

LastEditorDisplayName: nosklo

Body:
A simpler solution is to use tuple unpacking.  This will already do everything you want, including checking that it contains exactly one item.

Single item:

 >>> name, = (name for name in ('bob','fred') if name=='bob')
 >>> name
 'bob'

Too many items:

>>> name, = (name for name in ('bob','bob') if name=='bob')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

No items:

>>> name, = (name for name in ('fred','joe') if name=='bob')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack

OwnerDisplayName: Brian


问:
How to play .aac file in Cocos2d?
How can play an .aac file in Cocos2d?

答:
Use CocosDenshion. However, you may want to convert your audio files to AAC encoded *.caf format, as that is the preferred format.

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

//preloading is important. do it in the scene init function
[[SimpleAudioEngine sharedEngine] preloadBackgroundMusic:@"MyBgMusic.caf"];
[[SimpleAudioEngine sharedEngine] preloadEffect:@"MyEffect.caf"];

//later on
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"MyBgMusic.caf"];
[[SimpleAudioEngine sharedEngine] playEffect:@"MyEffect.caf"];
</code>```

Full documentation is here: http://www.cocos2d-iphone.org/api-ref/0.99.5/interface_simple_audio_engine.html

Title: How to play .aac file in Cocos2d?

Body: How can play an .aac file in Cocos2d?

Body:
Use CocosDenshion. However, you may want to convert your audio files to AAC encoded *.caf format, as that is the preferred format.

#import "SimpleAudioEngine.h"

//preloading is important. do it in the scene init function
[[SimpleAudioEngine sharedEngine] preloadBackgroundMusic:@"MyBgMusic.caf"];
[[SimpleAudioEngine sharedEngine] preloadEffect:@"MyEffect.caf"];

//later on
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"MyBgMusic.caf"];
[[SimpleAudioEngine sharedEngine] playEffect:@"MyEffect.caf"];

Full documentation is here: http://www.cocos2d-iphone.org/api-ref/0.99.5/interface_simple_audio_engine.html