问:
Add value of cards - C
Working on a simple C programming question and I'm a bit stuck.

Q: Write a function that takes the values of a two-card blackjack HAND as input, and returns the point total of the hand. The value
 of the cards '2' through '9' is equal to their face value, the cards 'T', 'K', 'Q', 'J' are worth 10 points and the ace ('A') is worth 11 points
 unless it comes with another ace, then that second ace is worth 1 point. The program should be able to catch incorrect input.

Example:
Enter cards: T 7
The score is 17

Enter cards: A 5
 The score is 16

Note: I've used a value of 'T' for the 10 card so you can simply pass in two characters,
 instead of strings, as parameters to this function.

```<code>#define CASE_VALUE(str,val,card) case str: card = val;break;
int point_total(char card1,char card2){
  int card1_v;
  int card2_v;
  switch(card1){
    CASE_VALUE('2',2,card1_v);
    CASE_VALUE('4',4,card1_v);
    CASE_VALUE('5',5,card1_v);
    CASE_VALUE('6',6,card1_v);
    CASE_VALUE('7',7,card1_v);
    CASE_VALUE('8',8,card1_v);
    CASE_VALUE('9',9,card1_v);
    CASE_VALUE('T',10,card1_v);
    CASE_VALUE('K',10,card1_v);
    CASE_VALUE('Q',10,card1_v);
    CASE_VALUE('J',10,card1_v);
    default:
    return -1;
    break;
  }
   switch(card2){
    CASE_VALUE('2',2,card2_v);
    CASE_VALUE('3',3,card2_v);
    CASE_VALUE('4',4,card2_v);
    CASE_VALUE('5',5,card2_v);
    CASE_VALUE('6',6,card2_v);
    CASE_VALUE('7',7,card2_v);
    CASE_VALUE('8',8,card2_v);
    CASE_VALUE('9',9,card2_v);
    CASE_VALUE('T',10,card2_v);
    CASE_VALUE('K',10,card2_v);
    CASE_VALUE('Q',10,card2_v);
    CASE_VALUE('J',10,card2_v);
    default:
    return -1;
    break;
  }
  int value=card1_v+card2_v;
  return value;
  return -1;
}

// to test if it works
int main(void) {
    char card1 = 10;
    char card2 = 2;
    printf("%i\n", point_total(card1, card2));
    return 0;

}
</code>```

Right now it is only returning -1, meaning the hand is invalid. I'm sure I'm overlooking something minor. I'm also unsure how to go about implementing the A (ace) card. Wondering if I'm on the right track and any help would be appreciated!

答:
The algorithm is incorrect.

Also, there are several issues in your code (listed in decreasing severity order):

You are not passing '10' and '2' in the example but the ASCII characters which correspond to 10 and 2 (check the ASCII table)

You are not considering the 'A' cases in your algorithm

return -1; after return value; is dead code

You are writing everything twice (WET) which is a bad practice. This practice is the opposite of don't repeat yourself (DRY)

The variables int card1_v, int card2_v are not necessary

The code can be improved by grouping the switch cases in different equivalence classes and using the decimal representation of the ASCII table values.

The following code is a correct implementation of the algorithm that you have described in your question, it also solves the problems that I previously pointed out. The comments explain the code.

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

int calculate_std_score(char card){
   /* use the ASCII decimal values to group ['2'...'9'] in the same equivalence class;
      shift the ASCII representation using '0' as "shifting value" to
      obtain the corresponding decimal representation.
      Example: '2' is 50 in ASCII, '0' is 48 in ASCII;
                      return (50 - 48)*/
   if(49 < (int) card && (int) card < 58)
      return (card - '0');
   /* check for all the figures whose value is 10 */
   if(card == 'T' || card == 'J' || card == 'Q' || card == 'K')
      return 10;
   /* we already checked the particular case of (A,A);
       Now the card A can only have 11 as value */
   if(card == 'A')
      return 11;
   /* error: unrecognized character; we ensure to obtain always a negative sum */
   return -22;
}

int calculate_total_score(char card1, char card2){
  /* check (A,A) case : the ASCII decimal value of char 'A' is  65 */
  if((int) card1 + (int) card2 == 130)
     return 11;/* (A,A) = 10 + 1 */
  /* calculate the standard sum of the 2 card values */
  int result= calculate_std_score(card1) + calculate_std_score(card2);
  /* check erroneous result */
  if(result < 0)
     return -1;
  /* return standard result : no error detected */
  return result;
}

// to test if it works
int main(void) {
    char card1 = 'T';
    char card2 = '2';
    printf("%i\n", calculate_total_score(card1, card2));
    return 0;
}
</code>```

Title: Add value of cards - C

Body:
Working on a simple C programming question and I'm a bit stuck.

Q: Write a function that takes the values of a two-card blackjack HAND as input, and returns the point total of the hand. The value
 of the cards '2' through '9' is equal to their face value, the cards 'T', 'K', 'Q', 'J' are worth 10 points and the ace ('A') is worth 11 points
 unless it comes with another ace, then that second ace is worth 1 point. The program should be able to catch incorrect input.

Example:
Enter cards: T 7
The score is 17

Enter cards: A 5
 The score is 16

Note: I've used a value of 'T' for the 10 card so you can simply pass in two characters,
 instead of strings, as parameters to this function.

#define CASE_VALUE(str,val,card) case str: card = val;break;
int point_total(char card1,char card2){
  int card1_v;
  int card2_v;
  switch(card1){
    CASE_VALUE('2',2,card1_v);
    CASE_VALUE('4',4,card1_v);
    CASE_VALUE('5',5,card1_v);
    CASE_VALUE('6',6,card1_v);
    CASE_VALUE('7',7,card1_v);
    CASE_VALUE('8',8,card1_v);
    CASE_VALUE('9',9,card1_v);
    CASE_VALUE('T',10,card1_v);
    CASE_VALUE('K',10,card1_v);
    CASE_VALUE('Q',10,card1_v);
    CASE_VALUE('J',10,card1_v);
    default:
    return -1;
    break;
  }
   switch(card2){
    CASE_VALUE('2',2,card2_v);
    CASE_VALUE('3',3,card2_v);
    CASE_VALUE('4',4,card2_v);
    CASE_VALUE('5',5,card2_v);
    CASE_VALUE('6',6,card2_v);
    CASE_VALUE('7',7,card2_v);
    CASE_VALUE('8',8,card2_v);
    CASE_VALUE('9',9,card2_v);
    CASE_VALUE('T',10,card2_v);
    CASE_VALUE('K',10,card2_v);
    CASE_VALUE('Q',10,card2_v);
    CASE_VALUE('J',10,card2_v);
    default:
    return -1;
    break;
  }
  int value=card1_v+card2_v;
  return value;
  return -1;
}

// to test if it works
int main(void) {
    char card1 = 10;
    char card2 = 2;
    printf("%i\n", point_total(card1, card2));
    return 0;

}

Right now it is only returning -1, meaning the hand is invalid. I'm sure I'm overlooking something minor. I'm also unsure how to go about implementing the A (ace) card. Wondering if I'm on the right track and any help would be appreciated!

Body:
The algorithm is incorrect.

Also, there are several issues in your code (listed in decreasing severity order):

You are not passing '10' and '2' in the example but the ASCII characters which correspond to 10 and 2 (check the ASCII table)

You are not considering the 'A' cases in your algorithm

return -1; after return value; is dead code

You are writing everything twice (WET) which is a bad practice. This practice is the opposite of don't repeat yourself (DRY)

The variables int card1_v, int card2_v are not necessary

The code can be improved by grouping the switch cases in different equivalence classes and using the decimal representation of the ASCII table values.

The following code is a correct implementation of the algorithm that you have described in your question, it also solves the problems that I previously pointed out. The comments explain the code.

#include <stdio.h>

int calculate_std_score(char card){
   /* use the ASCII decimal values to group ['2'...'9'] in the same equivalence class;
      shift the ASCII representation using '0' as "shifting value" to
      obtain the corresponding decimal representation.
      Example: '2' is 50 in ASCII, '0' is 48 in ASCII;
                      return (50 - 48)*/
   if(49 < (int) card && (int) card < 58)
      return (card - '0');
   /* check for all the figures whose value is 10 */
   if(card == 'T' || card == 'J' || card == 'Q' || card == 'K')
      return 10;
   /* we already checked the particular case of (A,A);
       Now the card A can only have 11 as value */
   if(card == 'A')
      return 11;
   /* error: unrecognized character; we ensure to obtain always a negative sum */
   return -22;
}

int calculate_total_score(char card1, char card2){
  /* check (A,A) case : the ASCII decimal value of char 'A' is  65 */
  if((int) card1 + (int) card2 == 130)
     return 11;/* (A,A) = 10 + 1 */
  /* calculate the standard sum of the 2 card values */
  int result= calculate_std_score(card1) + calculate_std_score(card2);
  /* check erroneous result */
  if(result < 0)
     return -1;
  /* return standard result : no error detected */
  return result;
}

// to test if it works
int main(void) {
    char card1 = 'T';
    char card2 = '2';
    printf("%i\n", calculate_total_score(card1, card2));
    return 0;
}


来源: stackexchange

问:
Randomizing numbers in C and storing them in an integer array
I am trying to write a code which randomizes numbers between 1 and 14 (symbolizing one suit of a deck of cards). The code should store the values in an array with a limit of 52. Each number can only be stored 4 times (as there are 4 suits in a deck of cards). So, in the end, I should be displaying two randomized decks for person_a and person_b.

My problem is that the randomized decks for person_a and person_b are the same. I have no idea why. I tried seeding using srand(), and using rand() for the random number. Can someone help?

Also, I know my code is really messy and terrible. I'm sorry - this is my first time taking a C course. Below is the code:

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

#define MAX_DECK 52
#define REPETITIONS 4
#define CARDS_HIGH 14
#define CARDS_LOW 1

int
randomize_check(int value_check, int limit, int cards[])
{
    int count = 0;
    int i = 0;
    for(i=0; i<limit; i++)
    {
        if(cards[i]==value_check)
        {
            count++;
        }
    }
    if(count>REPETITIONS)
    {
        return -1;
    }
    else if (count<=REPETITIONS)
    {
        return 1;
    }
}

int
get_random(void)
{
    int random_number = 0;
    random_number = (rand()%(CARDS_HIGH-CARDS_LOW))+CARDS_LOW;

    return(random_number);
}

int * randomize_deck(void)
{

    static int cards[MAX_DECK];
    int i = 0;
    int randomize = 0;
    int check = 0;

    for (i=0; i<MAX_DECK; i++)
    {
        randomize = get_random();
        cards[i] = randomize;
        check = randomize_check(cards[i], MAX_DECK, cards);
        while((check) == -1)
        {
            randomize = get_random();
            cards[i] = randomize;
            check = randomize_check(cards[i], MAX_DECK, cards);
        }

    }
    return(cards);
}

int
main(void)
{
    srand ( time(NULL) );
    int i = 0, j = 0;

    int *person_a = randomize_deck();
    int *person_b = randomize_deck();

    for (i = 0; i < MAX_DECK; i++) //print_a
    {
        printf( "Cards[a%d]: %d\n", i, *(person_a + i));
    }

    printf("\n");

    for (j = 0; j < MAX_DECK; j++) //print_b
    {
        printf( "Cards[b%d]: %d\n", j, *(person_b + j));
    }

    return(0);
}
</code>```

答:
"...randomized decks for person_a and person_b are the same. I have no idea why."

static int cards[MAX_DECK];

This happens because you declared your integer array as static

This means that every time the function randomize_deck is called the same int array will be operated upon and will be the same one  returned.**

```<code>int * randomize_deck(void) {
    int* cards = malloc(sizeof int) * MAX_DECK); // Instantiate a new and different deck of cards every time the function is called.

    int i = 0;
    int randomize = 0;
    int check = 0;

    /* next steps randomize_deck function */

    return cards; // Now you will return a different deck of cards every time you invoke the function

}
</code>```

There is one important step to take care of in your main() function. You need no deallocate the memory of the cards you allocated in randomize_deck(). So, you have to free person_a and person_b.

```<code>int main(void)
{
    srand ( time(NULL) );
    int i = 0, j = 0;

    int *person_a = randomize_deck();
    int *person_b = randomize_deck();

    /* ... */
    free(person_a); // You need to free these elements you returned,
    free(person_b);
    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a code which randomizes numbers between 1 and 14 (symbolizing one suit of a deck of cards). The code should store the values in an array with a limit of 52. Each number can only be stored 4 times (as there are 4 suits in a deck of cards). So, in the end, I should be displaying two randomized decks for person_a and person_b.

My problem is that the randomized decks for person_a and person_b are the same. I have no idea why. I tried seeding using srand(), and using rand() for the random number. Can someone help?

Also, I know my code is really messy and terrible. I'm sorry - this is my first time taking a C course. Below is the code:

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

#define MAX_DECK 52
#define REPETITIONS 4
#define CARDS_HIGH 14
#define CARDS_LOW 1

int
randomize_check(int value_check, int limit, int cards[])
{
    int count = 0;
    int i = 0;
    for(i=0; i<limit; i++)
    {
        if(cards[i]==value_check)
        {
            count++;
        }
    }
    if(count>REPETITIONS)
    {
        return -1;
    }
    else if (count<=REPETITIONS)
    {
        return 1;
    }
}

int
get_random(void)
{
    int random_number = 0;
    random_number = (rand()%(CARDS_HIGH-CARDS_LOW))+CARDS_LOW;

    return(random_number);
}

int * randomize_deck(void)
{

    static int cards[MAX_DECK];
    int i = 0;
    int randomize = 0;
    int check = 0;

    for (i=0; i<MAX_DECK; i++)
    {
        randomize = get_random();
        cards[i] = randomize;
        check = randomize_check(cards[i], MAX_DECK, cards);
        while((check) == -1)
        {
            randomize = get_random();
            cards[i] = randomize;
            check = randomize_check(cards[i], MAX_DECK, cards);
        }

    }
    return(cards);
}

int
main(void)
{
    srand ( time(NULL) );
    int i = 0, j = 0;

    int *person_a = randomize_deck();
    int *person_b = randomize_deck();

    for (i = 0; i < MAX_DECK; i++) //print_a
    {
        printf( "Cards[a%d]: %d\n", i, *(person_a + i));
    }

    printf("\n");

    for (j = 0; j < MAX_DECK; j++) //print_b
    {
        printf( "Cards[b%d]: %d\n", j, *(person_b + j));
    }

    return(0);
}

Body:
"...randomized decks for person_a and person_b are the same. I have no idea why."

static int cards[MAX_DECK];

This happens because you declared your integer array as static

This means that every time the function randomize_deck is called the same int array will be operated upon and will be the same one  returned.**

int * randomize_deck(void) {
    int* cards = malloc(sizeof int) * MAX_DECK); // Instantiate a new and different deck of cards every time the function is called.

    int i = 0;
    int randomize = 0;
    int check = 0;

    /* next steps randomize_deck function */

    return cards; // Now you will return a different deck of cards every time you invoke the function

}

There is one important step to take care of in your main() function. You need no deallocate the memory of the cards you allocated in randomize_deck(). So, you have to free person_a and person_b.

int main(void)
{
    srand ( time(NULL) );
    int i = 0, j = 0;

    int *person_a = randomize_deck();
    int *person_b = randomize_deck();

    /* ... */
    free(person_a); // You need to free these elements you returned,
    free(person_b);
    return 0;
}


问:
Log user ip address, date and time
Is there a simple script or piece of code I can add to my page to keep a log of every visitor, the date and time they hit the page and IP address?
And what would be the best way to do this... javascript, php, something else?

EDIT:

Ouch...

Here is what happened... When I went to my server with FileZilla there were all the domain names (about 20) I have being logged like my domain.com so I found the one I needed and checked the logs but it was mainly search engines.

But I just went back and happened to scroll down to stuff that was out of view and there were all the domain names again with www in front like www.mydomain.com and of course the logs in there are huge and have every single bit of info I need.

This happened because I found what I was looking for mydomain.com and of course I stopped looking. I didn't know or see there was a whole other set out of view... honest mistake.

I am still using that code because it is nice and small, the logs are freakin' huge and take hours to download and look at.

答:
here is my little script to log ip addresses
dont forget to add the below after the /HEAD tag
also note to make this work it must be a PHP not HTML

```<code><?php include ('log-ip.php') ?>
</code>```

where ever you want it called from

"log-ip.php"

```<code><?php
$iplogfile = 'logs/ip-address-mainsite.html';
$ipaddress = $_SERVER['REMOTE_ADDR'];
$webpage = $_SERVER['SCRIPT_NAME'];
$timestamp = date('d/m/Y h:i:s');
$browser = $_SERVER['HTTP_USER_AGENT'];
$fp = fopen($iplogfile, 'a+');
chmod($iplogfile, 0777);
fwrite($fp, '['.$timestamp.']: '.$ipaddress.' '.$webpage.' '.$browser. "\n<br><br>");
fclose($fp);
?>
</code>```

and the resault is a nice web HTML log file
logs/ip-address-mainsite.html

```<code><!DOCTYPE html><!-- HTML5 -->

<head>
<body bgcolor="#000000">
<title>NZ Quakes - Main Web Site Log</title>

</head>

<body>
<font color="#7FFF00">
<center>NZ Quakes - Main Web Site Log</center>
<font color="gold">
<br><center>
[01/04/2017 08:25:21]: 124.197.9.181 /index.php Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36
<br><br>
</code>```

below is a picture of what it looks like.

what do you think about this i think its clean and simple sort of.

Title: Log user ip address, date and time

Body:
here is my little script to log ip addresses
dont forget to add the below after the /HEAD tag
also note to make this work it must be a PHP not HTML

<?php include ('log-ip.php') ?>

where ever you want it called from

"log-ip.php"

<?php
$iplogfile = 'logs/ip-address-mainsite.html';
$ipaddress = $_SERVER['REMOTE_ADDR'];
$webpage = $_SERVER['SCRIPT_NAME'];
$timestamp = date('d/m/Y h:i:s');
$browser = $_SERVER['HTTP_USER_AGENT'];
$fp = fopen($iplogfile, 'a+');
chmod($iplogfile, 0777);
fwrite($fp, '['.$timestamp.']: '.$ipaddress.' '.$webpage.' '.$browser. "\n<br><br>");
fclose($fp);
?>

and the resault is a nice web HTML log file
logs/ip-address-mainsite.html

<!DOCTYPE html><!-- HTML5 -->

<head>
<body bgcolor="#000000">
<title>NZ Quakes - Main Web Site Log</title>

</head>

<body>
<font color="#7FFF00">
<center>NZ Quakes - Main Web Site Log</center>
<font color="gold">
<br><center>
[01/04/2017 08:25:21]: 124.197.9.181 /index.php Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36
<br><br>

below is a picture of what it looks like.

what do you think about this i think its clean and simple sort of.


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

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

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

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

Thanks in advance for any help!

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

答:
The problem arises from two nested loops and unthrottled rp() calls, leading to many simultaneous requests.

Throttling is typically achieved by :

serialising by building a then() chain, eg by reducing an array.

enforcing a "concurrency" limit, using eg Bluebird's Promise.map() with its concurrency option.

I guess there must be a number of approaches for this particular problem, but essentially :

pool all requests and throttle by concurrency (jFriend00's answer),

allow one loop to remain synchronous and throttle the other with serialisation or concurrency,

nest a serialisation in a serialisation,

nest a concurrency in a concurrency,

adopt a mixed approach of serialisation and concurrency.

Here's a mixed approach, in which :

the original outer loop is throttled by serialisation

the original inner loop is throttled by Bluebird's map with concurrency.

```<code>function getSubreddits(messageText) {
    var user_words = parse_message(messageText);
    return rp(dbUrl + '/.json?shallow=true').then(function(res) {
        var subreddits = Object.keys(JSON.parse(res));
        return subreddits.reduce(function(p, subreddit) {
            return p.then(function() {
                return Promise.map(user_words, function(word) {
                    return rp(dbUrl + '/' + subreddit + '/word_freqs/' + word + '.json');
                }, {concurrency: 10}).then(function(freqs) {
                    // return an object that associates each subreddit with its results
                    return {
                        'subreddit': subreddit, // or maybe the object for which `subreddit` is the key?
                        'word_freqs': freqs
                    };
                });
            });
        }, Promise.resolve());
    });
}
</code>```

A downside is that you end up with a deeply nested eyesore, which doesn't lend itself to flattening. That said, most if not all of the other approaches would be similar.

Whichever approach you adopt, getBestSubreddit() will now comprise a call to getSubreddits() plus some post-processing of the results.

```<code>function getBestSubreddit(messageText) {
    return getSubreddits(messageText).then(function(results) {
        // Here `results` is an array of `{'subreddit', 'word_freqs'}` objects.
        // Loop through and calculate a score for each subreddit,
        // then use that score to determine the top subreddit,
        // and return it.
    }).catch(function(error) {
        console.log(error);
    });
}
</code>```

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

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

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

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

Thanks in advance for any help!

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

Body:
The problem arises from two nested loops and unthrottled rp() calls, leading to many simultaneous requests.

Throttling is typically achieved by :

serialising by building a then() chain, eg by reducing an array.

enforcing a "concurrency" limit, using eg Bluebird's Promise.map() with its concurrency option.

I guess there must be a number of approaches for this particular problem, but essentially :

pool all requests and throttle by concurrency (jFriend00's answer),

allow one loop to remain synchronous and throttle the other with serialisation or concurrency,

nest a serialisation in a serialisation,

nest a concurrency in a concurrency,

adopt a mixed approach of serialisation and concurrency.

Here's a mixed approach, in which :

the original outer loop is throttled by serialisation

the original inner loop is throttled by Bluebird's map with concurrency.

function getSubreddits(messageText) {
    var user_words = parse_message(messageText);
    return rp(dbUrl + '/.json?shallow=true').then(function(res) {
        var subreddits = Object.keys(JSON.parse(res));
        return subreddits.reduce(function(p, subreddit) {
            return p.then(function() {
                return Promise.map(user_words, function(word) {
                    return rp(dbUrl + '/' + subreddit + '/word_freqs/' + word + '.json');
                }, {concurrency: 10}).then(function(freqs) {
                    // return an object that associates each subreddit with its results
                    return {
                        'subreddit': subreddit, // or maybe the object for which `subreddit` is the key?
                        'word_freqs': freqs
                    };
                });
            });
        }, Promise.resolve());
    });
}

A downside is that you end up with a deeply nested eyesore, which doesn't lend itself to flattening. That said, most if not all of the other approaches would be similar.

Whichever approach you adopt, getBestSubreddit() will now comprise a call to getSubreddits() plus some post-processing of the results.

function getBestSubreddit(messageText) {
    return getSubreddits(messageText).then(function(results) {
        // Here `results` is an array of `{'subreddit', 'word_freqs'}` objects.
        // Loop through and calculate a score for each subreddit,
        // then use that score to determine the top subreddit,
        // and return it.
    }).catch(function(error) {
        console.log(error);
    });
}


问:
advantage of tap method in ruby
I was just reading a blog article and noticed that the author used tap in a snippet something like:

user = User.new.tap do |u|
  u.username = "foobar"
  u.save!
end
```
<p>My question is what exactly is the benefit or advantage of using <code>tap</code>? Couldn't I just do:</p>
<pre class="lang-ruby prettyprint-override"><code>user = User.new
user.username = "foobar"
user.save!
</code>```

or better yet:

user = User.create! username: "foobar"
```

答:
If you wanted to return the user after setting the username you'd need to do

```<code>user = User.new
user.username = 'foobar'
user
</code>```

With tap you could save that awkward return

```<code>User.new.tap do |user|
  user.username = 'foobar'
end
</code>```

ContentLicense: CC BY-SA 4.0

Title: advantage of tap method in ruby

Body:
I was just reading a blog article and noticed that the author used tap in a snippet something like:

user = User.new.tap do |u|
  u.username = "foobar"
  u.save!
end

My question is what exactly is the benefit or advantage of using tap? Couldn't I just do:

user = User.new
user.username = "foobar"
user.save!

or better yet:

user = User.create! username: "foobar"

Body:
If you wanted to return the user after setting the username you'd need to do

user = User.new
user.username = 'foobar'
user

With tap you could save that awkward return

User.new.tap do |user|
  user.username = 'foobar'
end


问:
How can I efficiently run XSLT transformations for a large number of files in parallel?
I have to regularly transform large amount of XML files (min. 100K) within 1 folder each time (basically, from the unzipped input dataset), and I'd like to learn how to do that in the most efficient way as possible. My technological stack consists of XLTs and the Saxon XSLT Java libraries, called from Bash scripts. And it runs on an Ubuntu server with 8 cores and a Raid of SSD with 64Gb of Ram. Keep in mind I handle nicely XSLT but I'm still in the process of learning Bash and how to distribute the loads properly for such tasks (and Java is almost just a word at that point too).

I previously created a post regarding this issue, as my approach seemed very inefficient and was actually in need of help to properly run (See this SOF post). A lot of comments later, it makes sense to present the issue differently, therefore this post. I was proposed several solutions, one currently working much better than mine, but it could still be more elegant and efficient.

Now, I'm running this :

```<code>printf -- '-s:%s\0' input/*.xml | xargs -P 600 -n 1 -0 java -jar saxon9he.jar -xsl:some-xslt-sheet.xsl
</code>```

I set 600 processes based on some previous tests. Going higher would just throw memory errors from Java. But it is only using between 30 to 40Gb of Ram now (all 8 cores are at 100% though).

To put it in a nutshell, here is all the advices/approaches I have so far :

Splitting the whole XML files among subfolders (e.g. containing each
5K files), and use this as a way to run in parallel transformation scripts for each subfolder

Use specifically the Saxon-EE library    (allowing
multithreaded    execution) with the collection() function to parse the XML files

Set the Java environment with a lower number of tasks, or decrease
the memory per process

Specifying Saxon regarding if the XSLT sheets are compatible with
libxml/libxslt (isn't it only for XSLT1.0?)

Use a specialized shell such as xmlsh

I can handle the solution #2, and it should directly enable to control the loop and load JVM only once ; the #1 seems more clumsy and I still need to improve in Bash (load distribution & perf, tackling relative/absolute paths) ; the #3, #4 and #5 are totally new to me and I may need more explanations to see how to tackle that.

Any input would be greatly appreciated.

答:
Try using the xsltproc command line tool from libxslt. It can take multiple xml files as arguments. To call it like that, you'll need to create an output directory first. Try calling it like this:

```<code>mkdir output
xsltproc -o output/ some-xslt-sheet.xsl input/*.xml
</code>```

Body:
I have to regularly transform large amount of XML files (min. 100K) within 1 folder each time (basically, from the unzipped input dataset), and I'd like to learn how to do that in the most efficient way as possible. My technological stack consists of XLTs and the Saxon XSLT Java libraries, called from Bash scripts. And it runs on an Ubuntu server with 8 cores and a Raid of SSD with 64Gb of Ram. Keep in mind I handle nicely XSLT but I'm still in the process of learning Bash and how to distribute the loads properly for such tasks (and Java is almost just a word at that point too).

I previously created a post regarding this issue, as my approach seemed very inefficient and was actually in need of help to properly run (See this SOF post). A lot of comments later, it makes sense to present the issue differently, therefore this post. I was proposed several solutions, one currently working much better than mine, but it could still be more elegant and efficient.

Now, I'm running this :

printf -- '-s:%s\0' input/*.xml | xargs -P 600 -n 1 -0 java -jar saxon9he.jar -xsl:some-xslt-sheet.xsl

I set 600 processes based on some previous tests. Going higher would just throw memory errors from Java. But it is only using between 30 to 40Gb of Ram now (all 8 cores are at 100% though).

To put it in a nutshell, here is all the advices/approaches I have so far :

Splitting the whole XML files among subfolders (e.g. containing each
5K files), and use this as a way to run in parallel transformation scripts for each subfolder

Use specifically the Saxon-EE library    (allowing
multithreaded    execution) with the collection() function to parse the XML files

Set the Java environment with a lower number of tasks, or decrease
the memory per process

Specifying Saxon regarding if the XSLT sheets are compatible with
libxml/libxslt (isn't it only for XSLT1.0?)

Use a specialized shell such as xmlsh

I can handle the solution #2, and it should directly enable to control the loop and load JVM only once ; the #1 seems more clumsy and I still need to improve in Bash (load distribution & perf, tackling relative/absolute paths) ; the #3, #4 and #5 are totally new to me and I may need more explanations to see how to tackle that.

Any input would be greatly appreciated.

Body:
Try using the xsltproc command line tool from libxslt. It can take multiple xml files as arguments. To call it like that, you'll need to create an output directory first. Try calling it like this:

mkdir output
xsltproc -o output/ some-xslt-sheet.xsl input/*.xml


问:
nomethoderror in index for another method with collection routes on Rails
I want to create an excel file. When i try to going on professionals/628/medical_records displays the following message

```<code>undefined method `report_medical_records_path' for #<#<Class:0x0000000d0eb4f8>:0x0000000d0ea080>
</code>```

For the following lines on template, this line is the link that must going to the route that creates de excel file.

```<code>.clearfix
  div.excel-export
    = link_to report_medical_records_path(format: 'xlsx'), id: 'report_medical_records_link', data: { original_href: report_medical_records_path(format: 'xlsx') } do
      i.fa.fa-file-excel-o style="margin-right:5px"
      span exportar historias
</code>```

That's my index and report actions

```<code>def index
    @medical_records = MedicalRecord.for_organization(current_organization)

    medical_records_scope = @medical_records.joins(:owner,:target_user).preload(:owner,:target_user)
    medical_records_scope = medical_records_scope.like_with_target_user(params[:filter].strip) if params[:filter]
    @medical_records_list = smart_listing_create(:medical_records,
                                                 medical_records_scope,
                                                 sort_attributes: [[:name, "name"],[:profesional, "users.name"],[:target, "target_users_medical_records.name"]],
                                                 partial: 'medical_records/listing'
    )

    @medical_id = current_user.medical_id

    if params[:no_layout]=='true'
      render 'index', layout: false
    else
      render 'index'
    end
 end

def report
    medical_records_scope = begin_of_association_chain.order('active DESC')
    medical_records_scope = medical_records_scope.like(params[:filter].strip) if params[:filter]

    @medical_records_report = medical_records_scope

    respond_to do |format|
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="medical_records.xlsx"'
        render disposition: 'inline'
      }
    end
 end
</code>```

And the routes:

```<code>resources :medical_records, controller: 'medical_records' do
      collection do
        get :report
      end
    end
</code>```

UPDATED STATE

I'll keep before question upside, so remains outdated.

Current error message:

```<code>The action 'report' could not be found for MedicalRecordsController
</code>```

Now i have this in routes:

```<code>resources :professionals do
    #...
    resources :medical_records, controller: 'medical_records', only: [] do
      collection do
        get :report
      end
    end
  end
</code>```

and the action inside MedicalRecordsController is that:

```<code>def report
    medical_records_scope = begin_of_association_chain.order('active DESC')
    medical_records_scope = medical_records_scope.like(params[:filter].strip) if params[:filter]

    @medical_records_report = medical_records_scope

    respond_to do |format|
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="medical_records.xlsx"'
        render disposition: 'inline'
      }
    end
  end
</code>```

Why cannot find the action in controller?

答:
The route/action you want is not standard to rails.  You need to tell it a little more information in the routes.rb in order to get what you want, in particular, the action:

```<code>resources :medical_records, controller: 'medical_records' do
  collection do
    get :report, action: :report
  end
end
</code>```

That will get you the following route:

```<code>report_medical_records GET  /medical_records/report(.:format)   medical_records#report
</code>```

Body:
I want to create an excel file. When i try to going on professionals/628/medical_records displays the following message

undefined method `report_medical_records_path' for #<#<Class:0x0000000d0eb4f8>:0x0000000d0ea080>

For the following lines on template, this line is the link that must going to the route that creates de excel file.

.clearfix
  div.excel-export
    = link_to report_medical_records_path(format: 'xlsx'), id: 'report_medical_records_link', data: { original_href: report_medical_records_path(format: 'xlsx') } do
      i.fa.fa-file-excel-o style="margin-right:5px"
      span exportar historias

That's my index and report actions

def index
    @medical_records = MedicalRecord.for_organization(current_organization)

    medical_records_scope = @medical_records.joins(:owner,:target_user).preload(:owner,:target_user)
    medical_records_scope = medical_records_scope.like_with_target_user(params[:filter].strip) if params[:filter]
    @medical_records_list = smart_listing_create(:medical_records,
                                                 medical_records_scope,
                                                 sort_attributes: [[:name, "name"],[:profesional, "users.name"],[:target, "target_users_medical_records.name"]],
                                                 partial: 'medical_records/listing'
    )

    @medical_id = current_user.medical_id

    if params[:no_layout]=='true'
      render 'index', layout: false
    else
      render 'index'
    end
 end

def report
    medical_records_scope = begin_of_association_chain.order('active DESC')
    medical_records_scope = medical_records_scope.like(params[:filter].strip) if params[:filter]

    @medical_records_report = medical_records_scope

    respond_to do |format|
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="medical_records.xlsx"'
        render disposition: 'inline'
      }
    end
 end

And the routes:

resources :medical_records, controller: 'medical_records' do
      collection do
        get :report
      end
    end

UPDATED STATE

I'll keep before question upside, so remains outdated.

Current error message:

The action 'report' could not be found for MedicalRecordsController

Now i have this in routes:

resources :professionals do
    #...
    resources :medical_records, controller: 'medical_records', only: [] do
      collection do
        get :report
      end
    end
  end

and the action inside MedicalRecordsController is that:

def report
    medical_records_scope = begin_of_association_chain.order('active DESC')
    medical_records_scope = medical_records_scope.like(params[:filter].strip) if params[:filter]

    @medical_records_report = medical_records_scope

    respond_to do |format|
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="medical_records.xlsx"'
        render disposition: 'inline'
      }
    end
  end

Why cannot find the action in controller?

Body:
The route/action you want is not standard to rails.  You need to tell it a little more information in the routes.rb in order to get what you want, in particular, the action:

resources :medical_records, controller: 'medical_records' do
  collection do
    get :report, action: :report
  end
end

That will get you the following route:

report_medical_records GET  /medical_records/report(.:format)   medical_records#report


问:
I can't deploy an AngularJS app to heroku
When I do 'grunt build' I get the following message: Running "uglify:build" (uglify) task

Destination build/blog.min.js not written because src files were empty.

No files created.

Done.

I think something is wrong with my folder structure but I am not sure if that is the issue. Here is the layout of my folder structure with the package.json and displayed:

答:
It looks like your minification task is failing because it can't find the file you're trying to minify.

You should verify in your gruntfile.js that the src file for uglify:build  is a file that actually exists.


问:
SyntaxError: EOL while scanning string literal — Why are my quotation marks being ignored?
I am trying to follow 'How to Learn Python the Hard way' and am running into issues at a very early stage. When I try to run my first program 'hello world', I get a syntax error.

Error message:

```<code>File "ex1.py", line 1

print "Hello World!
                   ^
SyntaxError: EOL while scanning string literal
</code>```

The code is written in my text file:

```<code>print "Hello World!"
print "Hello Again"
</code>```

I've saved the file as a .py. I've rewritten the code about five times. I've even copy and pasted the authors code and I still get the same error. Judging from the error message, it seems as though I haven't put a quotation mark after 'World!'. However, there is a quotation there.

I also noticed that the error was printing the first quotation mark — just before the H of hello. I think these issues must be related. Somehow I think the parser is ignoring my quotation marks.

答: I'm not sure what fixed it, but I ended up deleting the file and host folder via the terminal with "rm -R", restarting my computer, and creating a new folder to work from through atom. I then followed the same steps, the same way, and it ran. Thanks for your patience guys. If you're stuck on this, just try deleting everything involved and restarting your computer. </p>

Body:
I am trying to follow 'How to Learn Python the Hard way' and am running into issues at a very early stage. When I try to run my first program 'hello world', I get a syntax error.

Error message:

File "ex1.py", line 1

print "Hello World!
                   ^
SyntaxError: EOL while scanning string literal

The code is written in my text file:

print "Hello World!"
print "Hello Again"

I've saved the file as a .py. I've rewritten the code about five times. I've even copy and pasted the authors code and I still get the same error. Judging from the error message, it seems as though I haven't put a quotation mark after 'World!'. However, there is a quotation there.

I also noticed that the error was printing the first quotation mark — just before the H of hello. I think these issues must be related. Somehow I think the parser is ignoring my quotation marks.


问:
Schedule cronjob to remove files modified before X days
I want to create and schedule cronjob to remove files modified before x days

I have taken following steps for that

Created Shell script (Named: Script.sh) as bellow

```<code>#!/bin/sh

15 2 * * 2-6  find  /usr/sch/cbm/files/newui/log -type f -mtime +2 exec rm {} \;
</code>```

I have put this file in "/var/spool/cron/crontabs" and usr/bin folder because i wasn't sure where to place exactly.

When i check with Crontab -e command get as in bellow image

But i didn't found any effect on my files. I am not sure is my job scheduled or i required to do anything else still

please guide me

答:
```<code>crontab <file>
</code>```

where file is what you have above will put the file in the right place and make sure everything is happy for cron to run it.

```<code>crontab -l
</code>```

will display the list of cron jobs for the currently logged in user.

Note that the file itself does not execute so no need for #!/bin/sh as the first line.  It is just a data file that cron interprets.

```<code>man 5 crontab
</code>```

and

```<code>man 1 crontab
</code>```

for more information.

Body:
I want to create and schedule cronjob to remove files modified before x days

I have taken following steps for that

Created Shell script (Named: Script.sh) as bellow

#!/bin/sh

15 2 * * 2-6  find  /usr/sch/cbm/files/newui/log -type f -mtime +2 exec rm {} \;

I have put this file in "/var/spool/cron/crontabs" and usr/bin folder because i wasn't sure where to place exactly.

When i check with Crontab -e command get as in bellow image

But i didn't found any effect on my files. I am not sure is my job scheduled or i required to do anything else still

please guide me

Body:
crontab <file>

where file is what you have above will put the file in the right place and make sure everything is happy for cron to run it.

crontab -l

will display the list of cron jobs for the currently logged in user.

Note that the file itself does not execute so no need for #!/bin/sh as the first line.  It is just a data file that cron interprets.

man 5 crontab

and

man 1 crontab

for more information.


问:
How do I access static member of a class?
I am trying to access static member of a class.

my class is:

```<code>class A
{
    public static $strName = 'A is my name'
    public function xyz()
    {
        ..
    }
    ..
}
//Since I have bunch of classes stored in an array
$x = array('A');
echo $x::$strName;
</code>```

I am getting error while printing. How can I print 'A is my name'

答:
From inside a class and want to access a static data member of its own you can also use
static::
instead of
self::

Body:
I am trying to access static member of a class.

my class is:

class A
{
    public static $strName = 'A is my name'
    public function xyz()
    {
        ..
    }
    ..
}
//Since I have bunch of classes stored in an array
$x = array('A');
echo $x::$strName;

I am getting error while printing. How can I print 'A is my name'


问:
Getting two div's side by side
Trying to get two div's to line up side by side but having some trouble getting them to connect with each other. This is the design of what im trying to make where it says "We're hiring today" and "Schedule Today".

HTML:

```<code><!DOCTYPE html>

<head>
<title>Merry Maids</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/stylesheet.css">
</head>

<body>

<div class="backgroundofdivgreen">
<header>
    <div class="logo"><a href="index.html"><img src="images/logo.jpg"></a></div>

    <nav>
    <a href="index.html">Home</a>
    <a href="services.html">Services</a>
    <a href="offers.html">Offers</a>
    <a href="people.html">People</a>
    <a href="franchises.html">Franchises</a>
    <a href="reviews.html">Reviews</a>

<div class ="phone">
Call Us Today:   <a href="tel:1233457890">(800) Merry Maids</a>
</div>

<div class="media">
        <a href="http://www.twitter.com" target=_blank"><img src="images/twitter.png"></a>
        <a href="http://www.facebook.com" target=_blank"><img src="images/facebook.png"></a>
</div>

<div class="clearboth"></div>
</header>
</nav>
</div>

<div class="banner"><img src="images/banner.jpg" alt="Merry Maids Banner Image"></div>

<div class="spacer1"></div>

<article>

<div class="wrapper">

<div class="yellow">
<h1>Schedule Appointments</h1>
<p>Our cleaning services are thorough, consistent and customized. If you would like to request a special service, change your cleaning schedule, or skip an area in your home, just let us know! We are happy to fulfill every request in order to exceed your expectations.Merry Maids home cleaning services are available weekly, every other week, monthly or one-time. On every visit, your Merry Maids team dusts, vacuums, washes and sanitizes each room.</p>
</div>
<div class="green">
<h1>We're Hiring Today</h1>
<p>For more than 30 years, our team members have provided reliable service for homeowners like you worldwide. We clean people's homes like they are our own and we treat our team members with the same concern, respect and care we expect them to show our customers. Merry Maids knows that our team members are our greatest asset and we recognize the power of our people.</p>
</div>
</code>```

CSS:

```<code>.clearboth {
    clear:both;
}

.backgroundofdivgreen {
    height: 96px;
    margin: 0px;
    background-color: #39b54a;
}

header {
    width: 980px;
    background-color: #39b54a;
    margin: 0px auto;
}

nav {
    float:right;
    width: 570px;
    text-align: right;
    padding-top:10px;
}

nav a {
    color:white;
    margin: 0px 25px 0px 0px;
    text-decoration:none;
}

nav a:hover {
    color: #fff799;
}

.logo {
    float:left;
}

.phone {
    margin: 40px 0px 0px 130px;
    color: white;
    float:left;
}

.media {
    float: right;
    margin: -23px 30px 0px 0px;
}

.banner {
    height:553px;
    width:1600px;
    margin: 0px auto;
}

.spacer1 {
    height:20px;
    background-color: #39b54a;
    margin: 0px auto;
}

.wrapper {
    margin: 0 auto;
    overflow: hidden;

}

.yellow {
    position:fixed;
    width:800px;
    height:313px;
    background-color: #fff799;
    float:left;
    text-align:right;
}
.green {
    position:fixed;
    width:800px;
    height:313px;
    background-color: #005e20;
    float:right;
}
</code>```

答:
Remove the position: fixed from the two divs. (position: fixed takes an element out of the document flow so the floats have no effect on them.)

You'll also need to make sure the wrapper has enough width to accommodate the full width of both divs.

Title: Getting two div's side by side

Body:
Trying to get two div's to line up side by side but having some trouble getting them to connect with each other. This is the design of what im trying to make where it says "We're hiring today" and "Schedule Today".

HTML:

<!DOCTYPE html>

<title>Merry Maids</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/stylesheet.css">

    Home
    Services
    Offers
    People
    Franchises
    Reviews

Call Us Today:   (800) Merry Maids

Schedule Appointments

Our cleaning services are thorough, consistent and customized. If you would like to request a special service, change your cleaning schedule, or skip an area in your home, just let us know! We are happy to fulfill every request in order to exceed your expectations.Merry Maids home cleaning services are available weekly, every other week, monthly or one-time. On every visit, your Merry Maids team dusts, vacuums, washes and sanitizes each room.

We're Hiring Today

For more than 30 years, our team members have provided reliable service for homeowners like you worldwide. We clean people's homes like they are our own and we treat our team members with the same concern, respect and care we expect them to show our customers. Merry Maids knows that our team members are our greatest asset and we recognize the power of our people.

CSS:

.clearboth {
    clear:both;
}

.backgroundofdivgreen {
    height: 96px;
    margin: 0px;
    background-color: #39b54a;
}

header {
    width: 980px;
    background-color: #39b54a;
    margin: 0px auto;
}

nav {
    float:right;
    width: 570px;
    text-align: right;
    padding-top:10px;
}

nav a {
    color:white;
    margin: 0px 25px 0px 0px;
    text-decoration:none;
}

nav a:hover {
    color: #fff799;
}

.logo {
    float:left;
}

.phone {
    margin: 40px 0px 0px 130px;
    color: white;
    float:left;
}

.media {
    float: right;
    margin: -23px 30px 0px 0px;
}

.banner {
    height:553px;
    width:1600px;
    margin: 0px auto;
}

.spacer1 {
    height:20px;
    background-color: #39b54a;
    margin: 0px auto;
}

.wrapper {
    margin: 0 auto;
    overflow: hidden;

}

.yellow {
    position:fixed;
    width:800px;
    height:313px;
    background-color: #fff799;
    float:left;
    text-align:right;
}
.green {
    position:fixed;
    width:800px;
    height:313px;
    background-color: #005e20;
    float:right;
}


问:
Google trends no longer showing GEO_CHART_o_o
I run a website and after having my tool successfully work for multiple months it's strange to me how it's just stopped working for the particular purpose.

I send Google visualisation requests to the URL:
https://www.google.com/trends/fetchComponent?hl=en-US&q=QUERYGOESHERE&cid=GEO_MAP_0_0&export=3&w=500&h=300&date=today%201-m

and now Google Trends seems to respond with:

```<code>google.visualization.Query.setResponse({"version":"0.6","status":"error","errors":[{"reason":"other","message":"Could not complete request","detailed_message":"Not enough search volume to show results."}]});
</code>```

This was working for practically any realistic search term you can think of. Now it's working for only very popular search terms. Is it possible Google Trends has changed/updated? Is there any reason my request is now outdated?

答:
check format of the search keywords

you can provide up to 5 keywords, separated with commas

this will result in error

```<code>q=QUERYGOESHERE
</code>```

this works...

```<code>q=QUERY,GOES,HERE
</code>```

test...

fetchComponent?hl=en-US&q=QUERY,GOES,HERE&cid=GEO_MAP_0_0&export=3&w=500&h=300&date=today%201-m

again

error...

```<code>q=tn%20vols
</code>```

success...

```<code>q=tn,vols
</code>```

Body:
I run a website and after having my tool successfully work for multiple months it's strange to me how it's just stopped working for the particular purpose.

I send Google visualisation requests to the URL:
https://www.google.com/trends/fetchComponent?hl=en-US&q=QUERYGOESHERE&cid=GEO_MAP_0_0&export=3&w=500&h=300&date=today%201-m

and now Google Trends seems to respond with:

google.visualization.Query.setResponse({"version":"0.6","status":"error","errors":[{"reason":"other","message":"Could not complete request","detailed_message":"Not enough search volume to show results."}]});

This was working for practically any realistic search term you can think of. Now it's working for only very popular search terms. Is it possible Google Trends has changed/updated? Is there any reason my request is now outdated?

Body:
check format of the search keywords

you can provide up to 5 keywords, separated with commas

this will result in error

q=QUERYGOESHERE

this works...

q=QUERY,GOES,HERE

test...

fetchComponent?hl=en-US&q=QUERY,GOES,HERE&cid=GEO_MAP_0_0&export=3&w=500&h=300&date=today%201-m

again

error...

q=tn%20vols

success...

q=tn,vols


问:
Is there any way to make these link inside another link work
I have the following markup:

```<code><a class="list-group-item hola" id="competition-card-<%= competition.id %>" href="a_url_to_a_site">
    <div class='row'>
          <div class='col-xs-11'>
            Some text
          </div>

        <div class='col-xs-1 shows-submenu'>
           Some text
        </div>
    </div>
</a>
</code>```

I'm trying to achieve:

If user clicks the 'a' tag he is directed to a site, except when...

user clicks the '.shows-submenu' div a hidden div is displayed.

My jQuery is as follows:

```<code>$('body').on('click', '.shows-submenu', function(e) {
   event.stopImmediatePropagation();
  if ($(this).closest('a.list-group-item').next('.hidden-group-item').hasClass('hide')) {
     $('.hidden-group-item').addClass('hide');
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
  else {
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
});
</code>```

Currently, if I click '.shows-submenu' div the 'a' tag is still called and I'm directed to the site.
As I'm using bootcards plugin I can't change the 'a' tag to a div, for example.

Is there any way to stop 'a' only when clicking the '.shows-submenu' div. I've tried using stopPropagation in both 'a' and the 'div' without success.

答:
What you are looking for is event.stopPropagation() that will prevent bubbling and event.preventDefault that will avoid the default behavior for links onClick.

Fortunately, in jQuery returning false inside the click handler function will fire both. More on the subject here: https://stackoverflow.com/a/1357151/670377

So you just need to modify your function as:

```<code>$('document').on('click', '.shows-submenu', function(e) {
  if ($(this).closest('a.list-group-item').next('.hidden-group-item').hasClass('hide')) {
     $('.hidden-group-item').addClass('hide');
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
  else {
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
  // This will be equivalent to
  // e.preventDefault; e.stopPropagation;
  return false;
});
</code>```

event.stopImmediatePropagation has another purpose than just stopping the default functionality, it will also prevent all the remaining listeners of the element from being called.

Body:
I have the following markup:

<a class="list-group-item hola" id="competition-card-<%= competition.id %>" href="a_url_to_a_site">

            Some text

           Some text

I'm trying to achieve:

If user clicks the 'a' tag he is directed to a site, except when...

user clicks the '.shows-submenu' div a hidden div is displayed.

My jQuery is as follows:

$('body').on('click', '.shows-submenu', function(e) {
   event.stopImmediatePropagation();
  if ($(this).closest('a.list-group-item').next('.hidden-group-item').hasClass('hide')) {
     $('.hidden-group-item').addClass('hide');
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
  else {
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
});

Currently, if I click '.shows-submenu' div the 'a' tag is still called and I'm directed to the site.
As I'm using bootcards plugin I can't change the 'a' tag to a div, for example.

Is there any way to stop 'a' only when clicking the '.shows-submenu' div. I've tried using stopPropagation in both 'a' and the 'div' without success.

Body:
What you are looking for is event.stopPropagation() that will prevent bubbling and event.preventDefault that will avoid the default behavior for links onClick.

Fortunately, in jQuery returning false inside the click handler function will fire both. More on the subject here: https://stackoverflow.com/a/1357151/670377

So you just need to modify your function as:

$('document').on('click', '.shows-submenu', function(e) {
  if ($(this).closest('a.list-group-item').next('.hidden-group-item').hasClass('hide')) {
     $('.hidden-group-item').addClass('hide');
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
  else {
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
  // This will be equivalent to
  // e.preventDefault; e.stopPropagation;
  return false;
});

event.stopImmediatePropagation has another purpose than just stopping the default functionality, it will also prevent all the remaining listeners of the element from being called.


问:
Map strings of letters and numbers based on if there's a valid date
I have 5 strings:

```<code>MO170915C00075000

GILD1514H117

9ZZZFD898

AHMIQ

894990415
</code>```

The first two have valid dates between between the first set of numbers and then then the next single letter (ex: C).

If I may ask, how would pick out the first two strings due to the date that's in them (need to identify that they contain a date after the first set of letters and before a single character) and then correctly format the dates?

For the first one, I can get the date using the GSub below:

```<code>("20" + @ticker.gsub(/(\w+?)(\d{6})([a-z])\d+/i,'\2')).to_date
</code>```

Body:
I have 5 strings:

MO170915C00075000

GILD1514H117

9ZZZFD898

AHMIQ

894990415

The first two have valid dates between between the first set of numbers and then then the next single letter (ex: C).

If I may ask, how would pick out the first two strings due to the date that's in them (need to identify that they contain a date after the first set of letters and before a single character) and then correctly format the dates?

For the first one, I can get the date using the GSub below:

("20" + @ticker.gsub(/(\w+?)(\d{6})([a-z])\d+/i,'\2')).to_date

Body:
Code

require 'date'

def extract_dates(arr)
  arr.each_with_object([]) do |str,a|
    s = str[/\d+/] || ''
    a <<
    case s.size
    when 8
      [convert_to_time(s, 4, 2, 2)]
    when 7
      [convert_to_time(s, 4, 2, 1), convert_to_time(s, 4, 1, 2)]
    when 6
      [convert_to_time(s, 4, 1, 1), convert_to_time(s, 2, 2, 2)]
    when 5
      [convert_to_time(s, 2, 2, 1), convert_to_time(s, 2, 1, 2)]
    when 4
      [convert_to_time(s, 2, 1, 1)]
    else
      []
    end.compact
  end
end

def convert_to_time(s, y, m, d)
  ss = s.dup
  ss.insert(0, "20") if y == 2
  ss.insert(4, "0") if m == 1
  ss.insert(6, "0") if d == 1
  DateTime.strptime(ss, "%Y%m%d") rescue nil
end

Examples

arr = <<-_.split
MA170915C00075000
MA20170915C00075000
MA20172115C00075000
GILD1514H117
GILD15111H117
9ZZZFD898
AHMIQ
894990415
_
  #=> ["MA170915C00075000", "MA20170915C00075000", "MA20172115C00075000",
  #    "GILD1514H117", "GILD15111H117", "9ZZZFD898", "AHMIQ", "894990415"]

arr.zip(extract_dates arr)
  #=> [["MA170915C00075000",
  #      [#<DateTime: 1709-01-05T00:00:00+00:00 ((2345264j,0s,0n),+0s,2299161j)>,
  #       #<DateTime: 2017-09-15T00:00:00+00:00 ((2458012j,0s,0n),+0s,2299161j)>]],
  #    ["MA20170915C00075000",
  #      [#<DateTime: 2017-09-15T00:00:00+00:00 ((2458012j,0s,0n),+0s,2299161j)>]],
  #    ["MA20172115C00075000", []],
  #    ["GILD1514H117",
  #      [#<DateTime: 2015-01-04T00:00:00+00:00 ((2457027j,0s,0n),+0s,2299161j)>]],
  #    ["GILD15111H117",
  #      [#<DateTime: 2015-11-01T00:00:00+00:00 ((2457328j,0s,0n),+0s,2299161j)>,
  #       #<DateTime: 2015-01-11T00:00:00+00:00 ((2457034j,0s,0n),+0s,2299161j)>]],
  #    ["9ZZZFD898", []],
  #    ["AHMIQ", []],
  #    ["894990415", []]]

This shows that:

the first string of digits in "MA170915C00075000", "170915", can be interpreted as one of two dates, "1709-1-5" and "2017-09-15".

the first digits in "MA20170915C00075000", "20170915", can be interpreted as one date only, "2017-09-15".

the first digits in "MA20172115C00075000", "20172115", do not represent a valid date, so  an empty array is returned.

the first digits in "GILD15111H117", "15111", could represent the date "2015-11-01" or "2015-01-11".


问:
ClassNotFoundException when submitting JAR to Spark via spark-submit
I'm struggling to submit a JAR to Apache Spark using spark-submit.

To make things easier, I've experimented using this blog post. The code is

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkConf

object SimpleScalaSpark {
  def main(args: Array[String]) {
    val logFile = "/Users/toddmcgrath/Development/spark-1.6.1-bin-hadoop2.4/README.md" // I've replaced this with the path to an existing file
    val conf = new SparkConf().setAppName("Simple Application").setMaster("local[*]")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
  }
}
</code>```

I'm running building this with Intellij Idea 2017.1 and running on Spark 2.1.0. Everything is running fine when I run it in the IDE.

I then build it as a JAR and attempt to use spark-submit as follows

```<code>./spark-submit --class SimpleScalaSpark --master local[*] ~/Documents/Spark/Scala/supersimple/out/artifacts/supersimple_jar/supersimple.jar
</code>```

This results in the following error

```<code>java.lang.ClassNotFoundException: SimpleScalaSpark
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:229)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:695)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

I'm at a loss as to what I'm missing...especially given that it runs as expected in the IDE.

答:
IDEs work differently from shell in many ways.
I believe for shell you need to add --jars parameter

spark submit add multiple jars in classpath

Body:
I'm struggling to submit a JAR to Apache Spark using spark-submit.

To make things easier, I've experimented using this blog post. The code is

import org.apache.spark.SparkContext
import org.apache.spark.SparkConf

object SimpleScalaSpark {
  def main(args: Array[String]) {
    val logFile = "/Users/toddmcgrath/Development/spark-1.6.1-bin-hadoop2.4/README.md" // I've replaced this with the path to an existing file
    val conf = new SparkConf().setAppName("Simple Application").setMaster("local[*]")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
  }
}

I'm running building this with Intellij Idea 2017.1 and running on Spark 2.1.0. Everything is running fine when I run it in the IDE.

I then build it as a JAR and attempt to use spark-submit as follows

./spark-submit --class SimpleScalaSpark --master local[*] ~/Documents/Spark/Scala/supersimple/out/artifacts/supersimple_jar/supersimple.jar

This results in the following error

java.lang.ClassNotFoundException: SimpleScalaSpark
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:229)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:695)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

I'm at a loss as to what I'm missing...especially given that it runs as expected in the IDE.


问:
How to convert IP address range to CIDR in Java?
I am trying to convert the IP address range into the CIDR notation in Java. Can someone provide an example of how this can be achieved?

I used the SubnetUtils for converting the CIDR to IP address range, but I can't figure out the other way round.

For example: (using http://ip2cidr.com/)

Input 1: 5.10.64.0

  Input 2: 5.10.127.255

  Result: 5.10.64.0/18

Thanks,
Dhaval

答:
Something short and sweet in Python:</p>

```<code>#!/usr/bin/env python
import ipaddress
import math

ip_from = '5.10.64.0'
ip_to = '5.10.127.255'
ip_from_long = int(ipaddress.ip_address(unicode(ip_from)))
ip_to_long = int(ipaddress.ip_address(unicode(ip_to)))
ip_range = ip_to_long - ip_from_long
ip_range +=1
# the clever line of code
cidr_range = math.log(4294967296/ip_range)/math.log(2)
# test for a zero/non-zero fractional part
if cidr_range % 1 == 0:
  # the output will be: 5.10.64.0/18
  print ip_from + '/' + str(int(cidr_range))
else:
  print "Error: Not an exact CIDR range - " + str(cidr_range)
</code>```

Body:
Something short and sweet in Python:

#!/usr/bin/env python
import ipaddress
import math

ip_from = '5.10.64.0'
ip_to = '5.10.127.255'
ip_from_long = int(ipaddress.ip_address(unicode(ip_from)))
ip_to_long = int(ipaddress.ip_address(unicode(ip_to)))
ip_range = ip_to_long - ip_from_long
ip_range +=1
# the clever line of code
cidr_range = math.log(4294967296/ip_range)/math.log(2)
# test for a zero/non-zero fractional part
if cidr_range % 1 == 0:
  # the output will be: 5.10.64.0/18
  print ip_from + '/' + str(int(cidr_range))
else:
  print "Error: Not an exact CIDR range - " + str(cidr_range)


问:
Including the current branch name in the commit template
I have a commit template set up for git, and I would like to include the name of the current branch in it. I usually set up the branch to be the bug id, and it would help me with filling in boilerplate such as:

```<code>Bug : $BUG
</code>```

How can I perform such a substitution with the git comment template?

答:
Just cobbling together the comments from Jefromi's answer, I end up with something like this. Surely it could be tighter (if I knew what I was doing):</p>

```<code>tempFile='/tmp/git-commit-template'
git config commit.template "$tempFile"
rm $tempFile
branch=$(git symbolic-ref HEAD|sed s#refs/heads/##) exec 3<> "$tempFile" && awk -v TEXT="[$branch]" 'BEGIN {print TEXT}{print}' "$tempFile" >&3
git add .
git commit -a
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a commit template set up for git, and I would like to include the name of the current branch in it. I usually set up the branch to be the bug id, and it would help me with filling in boilerplate such as:

Bug : $BUG

How can I perform such a substitution with the git comment template?

Body:
Just cobbling together the comments from Jefromi's answer, I end up with something like this. Surely it could be tighter (if I knew what I was doing):

tempFile='/tmp/git-commit-template'
git config commit.template "$tempFile"
rm $tempFile
branch=$(git symbolic-ref HEAD|sed s#refs/heads/##) exec 3<> "$tempFile" && awk -v TEXT="[$branch]" 'BEGIN {print TEXT}{print}' "$tempFile" >&3
git add .
git commit -a


问:
How can I dynamically set destination component in Vue router
I am trying to dynamically set the target component for a vue-router route.

The reason is that I need to retrieve data from the server to know the correct component to target.

One solution I thought about was to add a global guard similar to:

```<code>router.beforeEach((to, from, next) => {
  get_data_from_server(to.fullPath).then(() => {
    // set the "to" component, but how?
    next();
})
</code>```

But, as the comment says, how would I set "component" - there is no component property in the "to" object. (It looks like it is in components.default.render but that isn't documented and doesn't look like it should be messed with.)

Another alternative is to the use above logic but add special-case code to redirect but then I found there was no way to create a dynamic/new route that targeted the correct component.

How should one go about creating a route to a destination that is not known at build-time?

答:
This solution seems to work.

```<code>router.beforeEach((to, from, next) => {
  get_data_from_server(to.fullPath).then(component => {
    if (to.matched.length === 0) {
      // the target route doesn't exist yet
      router.addRoutes({path: to.path, component: component})
      next(to.fullPath)
      return
    } else {
      // the route and component are known and data is available
      next()
    }
})
</code>```

The key was finding the link in my comment above that shows the vue-router commit that implements addRoutes().

One thing to be aware of is that new routes are added at the end (makes sense) so any wildcards present might create unintended matches. I had a catchall route in place that redirected to a default page. But that matched before the newly added match because it was earlier the list. And that caused a stack overflow. In effect the code after if (to.matched.length === 0) is the default route.

Body:
I am trying to dynamically set the target component for a vue-router route.

The reason is that I need to retrieve data from the server to know the correct component to target.

One solution I thought about was to add a global guard similar to:

router.beforeEach((to, from, next) => {
  get_data_from_server(to.fullPath).then(() => {
    // set the "to" component, but how?
    next();
})

But, as the comment says, how would I set "component" - there is no component property in the "to" object. (It looks like it is in components.default.render but that isn't documented and doesn't look like it should be messed with.)

Another alternative is to the use above logic but add special-case code to redirect but then I found there was no way to create a dynamic/new route that targeted the correct component.

How should one go about creating a route to a destination that is not known at build-time?

Body:
This solution seems to work.

router.beforeEach((to, from, next) => {
  get_data_from_server(to.fullPath).then(component => {
    if (to.matched.length === 0) {
      // the target route doesn't exist yet
      router.addRoutes({path: to.path, component: component})
      next(to.fullPath)
      return
    } else {
      // the route and component are known and data is available
      next()
    }
})

The key was finding the link in my comment above that shows the vue-router commit that implements addRoutes().

One thing to be aware of is that new routes are added at the end (makes sense) so any wildcards present might create unintended matches. I had a catchall route in place that redirected to a default page. But that matched before the newly added match because it was earlier the list. And that caused a stack overflow. In effect the code after if (to.matched.length === 0) is the default route.


问:
Problems with Stripe Gem
I'm getting this error message whenever  I tried to start Rails server after installing Stripe gem.

```<code>$ rails s
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe.rb:23:in `require': /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: syntax error, unexpected tLABEL (SyntaxError)
...alize(message=nil, http_status: nil, http_body: nil, json_bo...
...                               ^
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: Can't assign to nil
...(message=nil, http_status: nil, http_body: nil, json_body: n...
...                               ^
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: Can't assign to nil
...tp_status: nil, http_body: nil, json_body: nil,
...                               ^
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: Can't assign to nil
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:39: class definition in method body
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:45: class definition in method body
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:52: class definition in method body
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:57: class definition in method body
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:60: syntax error, unexpected tLABEL
...sage, param, code, http_status: nil, http_body: nil, json_bo...
</code>```

I think that is a problem with my ruby version which is 1.9.3, as far as I know Stripe doesn't support ruby version 1.9, but I haven't find anything concrete about this. Do you guys know if is possible to have Stripe working with ruby 1.9?

Thank you!

答: Your server should start up with Stripe version <= 1.58.0. It may be missing some features, but I was able to get a server running with that version and Ruby 1.9.3.</p>

Title: Problems with Stripe Gem

Body:
I'm getting this error message whenever  I tried to start Rails server after installing Stripe gem.

$ rails s
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe.rb:23:in `require': /home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: syntax error, unexpected tLABEL (SyntaxError)
...alize(message=nil, http_status: nil, http_body: nil, json_bo...
...                               ^
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: Can't assign to nil
...(message=nil, http_status: nil, http_body: nil, json_body: n...
...                               ^
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: Can't assign to nil
...tp_status: nil, http_body: nil, json_body: nil,
...                               ^
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:20: Can't assign to nil
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:39: class definition in method body
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:45: class definition in method body
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:52: class definition in method body
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:57: class definition in method body
/home/alex/.rvm/gems/ruby-1.9.3-p551@rails323/gems/stripe-2.0.1/lib/stripe/errors.rb:60: syntax error, unexpected tLABEL
...sage, param, code, http_status: nil, http_body: nil, json_bo...

I think that is a problem with my ruby version which is 1.9.3, as far as I know Stripe doesn't support ruby version 1.9, but I haven't find anything concrete about this. Do you guys know if is possible to have Stripe working with ruby 1.9?

Thank you!


问:
Calculating 1/r*d/dr(r*f) numerically in python when r=0. f is a function of r
Usually when you do this by hand there's no problem as the 1/r usually gets cancelled with another r. But doing this numerically with scipy.misc.derivative works like a charm for r different from zero. But of course, as soon as I ask for r = 0, I get division by zero, which I expected. So how else could you calculate this numerically. I insist on the fact that everything has to be done numerically as my function are now so complicated that I won't be able to find a derivative manually. Thank you!

My code:

```<code>rAtheta = lambda _r: _r*Atheta(_r,theta,z,t)
if r != 0:
    return derivative(rAtheta,r,dx=1e-10,order=3)/r
else:
    #What should go here so that it doesn't blow up when calculating the gradient?
</code>```

答:
tl;dr: use symbolic differentiation, or complex step differentiation if that fails

If you insist on using numerical methods, you really have to approximate the limit of the derivative as r->0 one way or the other.

I suggest trying complex step differentiation. The idea is to use complex arguments inside the function you're trying to differentiate, but it usually gets rid of the numerical instability that is imposed by standard finite difference schemes. The result is a procedure that needs complex arithmetic (hooray numpy, and python in general!) but in turn can be much more stable at small dx values.

Here's another point: complex step differentiation uses

```<code>F′(x0) = Im(F(x0+ih))/h + O(h^2)
</code>```

Let's apply this to your r=0 case:

```<code>F′(0) = Im(F(ih))/h + O(h^2)
</code>```

There are no singularities even for r=0! Choose a small h, possibly the same dx you're passing to your function, and use that:

```<code>def rAtheta(_r):
    # note that named lambdas are usually frowned upon
    return _r*Atheta(_r,theta,z,t)

tol = 1e-10
dr = 1e-12

if np.abs(r) > tol: # or math.abs or your favourite other abs
    return derivative(rAtheta,r,dx=dr,order=3)/r
else:
    return rAtheta(r + 1j*dr).imag/dr/r
</code>```

Here is the above in action for f = r*ln(r):

The result is straightforwardly smooth, even though the points below r=1e-10 were computed with complex step differentiation.

Very important note: notice the separation between tol and dr in the code. The former is used to determine when to switch between methods, and the latter is used as a step in complex step differentiation. Look what happens when tol=dr=1e-10:

the result is a smoothly wrong function below r=1e-10! That's why you always have to be careful with numerical differentiation. And I wouldn't advise going too much below that in dr, as machine precision will bite you sooner or later.

But why stop here? I'm fairly certain that your functions could be written in a vectorized way, i.e. they could accept an array of radial points. Using complex step differentiation you don't have to loop over the radial points (which you would have to resort to using scipy.misc.derivative). Example:

```<code>import numpy as np
import matplotlib.pyplot as plt

def Atheta(r,*args):
    return r*np.log(r) # <-- vectorized expression

def rAtheta(r):
    return r*Atheta(r) #,theta,z,t) # <-- vectorized as much as Atheta is

def vectorized_difffun(rlist):
    r = np.asarray(rlist)
    dr = 1e-12

    return (rAtheta(r + 1j*dr)).imag/dr/r

rarr = np.logspace(-12,-2,20)
darr = vectorized_difffun(rarr)
plt.figure()
plt.loglog(rarr,np.abs(darr),'.-')
plt.xlabel(r'$r$')
plt.ylabel(r'$|\frac{1}{r} \frac{d}{dr}(r^2 \ln r)|$')
plt.tight_layout()

plt.show()
</code>```

The result should be familiar:

Having cleared the fun weirdness that is complex step differentiation, I should note that you should strongly consider using symbolic math. In cases like this when 1/r factors disappear exactly, it wouldn't hurt if you reached this conclusion exactly. After all double precision is still just double precision.

For this you'll need the sympy module, define your function symbolically once, differentiate it symbolically once, turn your simplified result into a numpy function using sympy.lambdify, and use this numerical function as much as you need (assuming that this whole process runs in finite time and the resulting function is not too slow to use). Example:

```<code>import sympy as sym

# only needed for the example:
import numpy as np
import matplotlib.pyplot as plt

r = sym.symbols('r')
f = r*sym.ln(r)
df = sym.diff(r*f,r)
res_sym = sym.simplify(df/r)
res_num = sym.lambdify(r,res_sym,'numpy')

rarr = np.logspace(-12,-2,20)
darr = res_num(rarr)

plt.figure()
plt.loglog(rarr,np.abs(darr),'.-')
plt.xlabel(r'$r$')
plt.ylabel(r'$|\frac{1}{r} \frac{d}{dr}(r^2 \ln r)|$')
plt.tight_layout()
plt.show()
</code>```

resulting in

As you see, the resulting function was vectorized thanks to lambdify using numpy during the conversion from symbolic to numeric function. Obviously, the best solution is the symbolic one as long as the resulting function is not so complicated to make its practical use impossible. I urge you to first try the symbolic version, and if for some reason it's not applicable, switch to complex step differentiation, with due caution.

Body:
Usually when you do this by hand there's no problem as the 1/r usually gets cancelled with another r. But doing this numerically with scipy.misc.derivative works like a charm for r different from zero. But of course, as soon as I ask for r = 0, I get division by zero, which I expected. So how else could you calculate this numerically. I insist on the fact that everything has to be done numerically as my function are now so complicated that I won't be able to find a derivative manually. Thank you!

My code:

rAtheta = lambda _r: _r*Atheta(_r,theta,z,t)
if r != 0:
    return derivative(rAtheta,r,dx=1e-10,order=3)/r
else:
    #What should go here so that it doesn't blow up when calculating the gradient?

Body:
tl;dr: use symbolic differentiation, or complex step differentiation if that fails

If you insist on using numerical methods, you really have to approximate the limit of the derivative as r->0 one way or the other.

I suggest trying complex step differentiation. The idea is to use complex arguments inside the function you're trying to differentiate, but it usually gets rid of the numerical instability that is imposed by standard finite difference schemes. The result is a procedure that needs complex arithmetic (hooray numpy, and python in general!) but in turn can be much more stable at small dx values.

Here's another point: complex step differentiation uses

F′(x0) = Im(F(x0+ih))/h + O(h^2)

Let's apply this to your r=0 case:

F′(0) = Im(F(ih))/h + O(h^2)

There are no singularities even for r=0! Choose a small h, possibly the same dx you're passing to your function, and use that:

def rAtheta(_r):
    # note that named lambdas are usually frowned upon
    return _r*Atheta(_r,theta,z,t)

tol = 1e-10
dr = 1e-12

if np.abs(r) > tol: # or math.abs or your favourite other abs
    return derivative(rAtheta,r,dx=dr,order=3)/r
else:
    return rAtheta(r + 1j*dr).imag/dr/r

Here is the above in action for f = r*ln(r):

The result is straightforwardly smooth, even though the points below r=1e-10 were computed with complex step differentiation.

Very important note: notice the separation between tol and dr in the code. The former is used to determine when to switch between methods, and the latter is used as a step in complex step differentiation. Look what happens when tol=dr=1e-10:

the result is a smoothly wrong function below r=1e-10! That's why you always have to be careful with numerical differentiation. And I wouldn't advise going too much below that in dr, as machine precision will bite you sooner or later.

But why stop here? I'm fairly certain that your functions could be written in a vectorized way, i.e. they could accept an array of radial points. Using complex step differentiation you don't have to loop over the radial points (which you would have to resort to using scipy.misc.derivative). Example:

import numpy as np
import matplotlib.pyplot as plt

def Atheta(r,*args):
    return r*np.log(r) # <-- vectorized expression

def rAtheta(r):
    return r*Atheta(r) #,theta,z,t) # <-- vectorized as much as Atheta is

def vectorized_difffun(rlist):
    r = np.asarray(rlist)
    dr = 1e-12

    return (rAtheta(r + 1j*dr)).imag/dr/r

rarr = np.logspace(-12,-2,20)
darr = vectorized_difffun(rarr)
plt.figure()
plt.loglog(rarr,np.abs(darr),'.-')
plt.xlabel(r'$r$')
plt.ylabel(r'$|\frac{1}{r} \frac{d}{dr}(r^2 \ln r)|$')
plt.tight_layout()

plt.show()

The result should be familiar:

Having cleared the fun weirdness that is complex step differentiation, I should note that you should strongly consider using symbolic math. In cases like this when 1/r factors disappear exactly, it wouldn't hurt if you reached this conclusion exactly. After all double precision is still just double precision.

For this you'll need the sympy module, define your function symbolically once, differentiate it symbolically once, turn your simplified result into a numpy function using sympy.lambdify, and use this numerical function as much as you need (assuming that this whole process runs in finite time and the resulting function is not too slow to use). Example:

import sympy as sym

# only needed for the example:
import numpy as np
import matplotlib.pyplot as plt

r = sym.symbols('r')
f = r*sym.ln(r)
df = sym.diff(r*f,r)
res_sym = sym.simplify(df/r)
res_num = sym.lambdify(r,res_sym,'numpy')

rarr = np.logspace(-12,-2,20)
darr = res_num(rarr)

plt.figure()
plt.loglog(rarr,np.abs(darr),'.-')
plt.xlabel(r'$r$')
plt.ylabel(r'$|\frac{1}{r} \frac{d}{dr}(r^2 \ln r)|$')
plt.tight_layout()
plt.show()

resulting in

As you see, the resulting function was vectorized thanks to lambdify using numpy during the conversion from symbolic to numeric function. Obviously, the best solution is the symbolic one as long as the resulting function is not so complicated to make its practical use impossible. I urge you to first try the symbolic version, and if for some reason it's not applicable, switch to complex step differentiation, with due caution.


问:
MVC 3 broke uncomment ctrl+k, ctrl+u in views?
I don't know if is related but after installing MVC 3 RC, I can't uncomment HTML tags in the views in either WebForm Views or Razor Views. Uncomment works with javascript and C# in controllers though.

Related to Razor View installation possibly?

Edit->Advanced->Uncomment Selection is grayed out.

答:
Works pretty well for me (ASP.NET MVC 3 RC):

Make sure you have selected the entire commented text:

```<code>@*
<h2>@View.Message</h2>
*@
</code>```

Body:
Works pretty well for me (ASP.NET MVC 3 RC):

Make sure you have selected the entire commented text:

@*
<h2>@View.Message</h2>
*@


问:
Rails 5 and Rspec 3.5: application_controller method in a view partial
Just started learning Rspec, and I'm trying to test for the existence of the header partial on my Home page, and then later on the rest of my pages.

My header partial uses a current_user method from application_controller.rb

```<code>def current_user
  @current_user ||= User.find_by(id: session[:user_id])
end
</code>```

to test whether or not a User is logged in

```<code>  <% if current_user %>
    <%= image_tag(current_user.image_url, size: "30", :class => "profile_image") %>
  <% end %>
  <ul class="nav navbar-nav navbar-right">
    <li><%= link_to "Home", root_path %></li>
    <% if current_user %>
      <li><%= link_to "TODOs", todos_path %></li>
      <li><%= link_to "Log Out", logout_path, method: :delete %></li>
    <% else %>
      <li><%= link_to "Log In", 'auth/google' %></li>
    <% end %>
</code>```

Attempting to test my view:

```<code>require 'rails_helper'

RSpec.describe "home_page/home.html.erb", type: :view do
  context "When viewing the home page" do

    it "the home page should render the _header partial" do
      render :partial => "layouts/header"

      expect(view).to render_template(:partial => 'header')
    end

  end
end
</code>```

Returns

```<code> Failure/Error: <% if current_user %>

 ActionView::Template::Error:
   undefined local variable or method `current_user' for #<#<Class:0x007fc9d85409f8>:0x007fc9d77a4858>
   Did you mean?  current_page?
</code>```

I want to test this both when there is a logged in user and when there isn't, but I'm unsure how to stub this.

Any suggestions?

答:
In your rails_helper you should have...

```<code>require 'devise'

RSpec.configure do |config|
  # For Devise <= 4.1.0
  # config.include Devise::Test::ControllerHelpers, :type => :controller
  # Use the following instead if you are on Devise >= 4.1.1
  config.include Devise::TestHelpers, :type => :controller
end
</code>```

then in your tests you can do...

```<code>before(:each) do
  user = User.create(name: 'John') # <-include other params as req'd
  user.confirm! # if you're using devise's confirmable module
  sign_in user
end
</code>```

Body:
Just started learning Rspec, and I'm trying to test for the existence of the header partial on my Home page, and then later on the rest of my pages.

My header partial uses a current_user method from application_controller.rb

def current_user
  @current_user ||= User.find_by(id: session[:user_id])
end

to test whether or not a User is logged in

  <% if current_user %>
    <%= image_tag(current_user.image_url, size: "30", :class => "profile_image") %>
  <% end %>

<%= link_to "Home", root_path %>

    <% if current_user %>

<%= link_to "TODOs", todos_path %>

<%= link_to "Log Out", logout_path, method: :delete %>

    <% else %>

<%= link_to "Log In", 'auth/google' %>

    <% end %>

Attempting to test my view:

require 'rails_helper'

RSpec.describe "home_page/home.html.erb", type: :view do
  context "When viewing the home page" do

    it "the home page should render the _header partial" do
      render :partial => "layouts/header"

      expect(view).to render_template(:partial => 'header')
    end

  end
end

Returns

 Failure/Error: <% if current_user %>

 ActionView::Template::Error:
   undefined local variable or method `current_user' for #<#<Class:0x007fc9d85409f8>:0x007fc9d77a4858>
   Did you mean?  current_page?

I want to test this both when there is a logged in user and when there isn't, but I'm unsure how to stub this.

Any suggestions?

Body:
In your rails_helper you should have...

require 'devise'

RSpec.configure do |config|
  # For Devise <= 4.1.0
  # config.include Devise::Test::ControllerHelpers, :type => :controller
  # Use the following instead if you are on Devise >= 4.1.1
  config.include Devise::TestHelpers, :type => :controller
end

then in your tests you can do...

before(:each) do
  user = User.create(name: 'John') # <-include other params as req'd
  user.confirm! # if you're using devise's confirmable module
  sign_in user
end


问:
Ideal cross-platform library
One has to create a new software library. This library has no system I/O routines and contains only Init(config), Run(some_data_inputs), and DeInit(config) functions and a few typedefs and defines. Run() function just processes given input data and generates output data, no interrupts, threads, locks, etc. However, it requires some RAM for its internal needs. The interface is described in a header file and a static library contains the implementation.

This library must be as much multi-plarform as possible. It must be matter of minutes to port this library to any new platform onto any new OS+CPU. Sometimes this lib can be used even on the platforms without operating systems.

So, before starting development, one has to decide:

Must this lib be written in ANSI-C or even in a sub-set of ANSI-C because some platforms may not support ANSI-C completely?

Whether to write an abstraction
layer, which encapsulates an
underlying OS+CPU?

Should this abstraction layer
include its own memory manager
(malloc/free routines) or all
platforms today provide it already?

答:
In reverse order:

(3). You need your own memory management routines, if not for any other reason, then simply because you expect that it may be ported to a bare platform without an underlying OS. Then you also need an implementation for pretty much everything else: string libraries, math libraries etc. You have to either code them yourself, or try to find ready-made code libraries that provide them for each platform.

(2). The OS and CPU are somewhat orthogonal variables. You would probably have a better time creating two abstraction layers (one for different operating systems, one for different hardware platforms) and then include/override definitions as necessary for each new platform. But yes, an abstraction layer is a more manageable solution than riddling your code with whole hordes of #ifdefs.

(1). This is not an easy question to answer. For example if you expect your library to run on an embedded system or even a microcontroller then it's quite probable that not all of ANSI C features are available, depending on the maturity of the development tools. There could also be restrictions not necessarily related to the language itself. Hardware floating point units are relatively rare in embedded systems. Stack sizes could be limited etc. I suggest that you make a survey of the platforms that you are interested in and try to select a common subset.

(0). You could very well find from an economic (or even a feasibility) point of view that it is preferrable to develop for a rather rich subset that is supported in your most common target platforms and refactor your code if you encounter a new platform. Trying to restrict youserlf to the most common subset could essentially cripple both your development effort and the effectiveness of your library in slightly more capable systems.

(-1). You should realise from the scarsity (or even complete lack) of libraries with your required level of portability that what you want to achieve is not going to be easy. Be prepared!

Title: Ideal cross-platform library


问:
Swift Compiler Errors caused by Importing Header File in Bridging Header

My project builds and runs successfully.

I create a bridging header, so that I can segue between my Swift and Objective-C views.

I import my Objective-C header file in my bridging header.

All of a sudden, I have 40 swift compiler errors in my Objective-C header file that I imported. (image attached for details)

Image

Why does this happen, and how can I fix it? My ViewController.h file ran perfectly before I imported it in my bridging header.

答:
To define constants in an Objective C header file, you'll want to do something like this:</p>

```<code>// header file
FOUNDATION_EXPORT static CGFloat MyNamespaceAlpha;

// implementation file
static CGFloat MyNamespaceAlpha = 0.8f;
</code>```

Body:
To define constants in an Objective C header file, you'll want to do something like this:

// header file
FOUNDATION_EXPORT static CGFloat MyNamespaceAlpha;

// implementation file
static CGFloat MyNamespaceAlpha = 0.8f;