问:
Convert ActiveSupport::TimeWithZone to DateTime
I'm trying to step every N days between two dates. I tried the following code but is wasn't working because startDate and endDate are ActiveSupport::TimeWithZone objects and not DateTime objects like I thought.

```<code>startDate.step(endDate, step=7) { |d| puts d.to_s}
  min.step(max, step=stepInt){ |d|
  puts d.to_s
}
</code>```

How do I covert the TimeWithZone object to a DateTime?

答:
DateTime is an old class which you generally want to avoid using. Time and Date are the two you want to be using. ActiveSupport::TimeWithZone acts like Time.

For stepping over dates you probably want to deal with Date objects. You can convert a Time (or ActiveSupport::TimeWithZone) into a Date with Time#to_date:

```<code>from.to_date.step(to.to_date, 7) { |d| puts d.to_s }
</code>```

Body:
I'm trying to step every N days between two dates. I tried the following code but is wasn't working because startDate and endDate are ActiveSupport::TimeWithZone objects and not DateTime objects like I thought.

startDate.step(endDate, step=7) { |d| puts d.to_s}
  min.step(max, step=stepInt){ |d|
  puts d.to_s
}

How do I covert the TimeWithZone object to a DateTime?

Body:
DateTime is an old class which you generally want to avoid using. Time and Date are the two you want to be using. ActiveSupport::TimeWithZone acts like Time.

For stepping over dates you probably want to deal with Date objects. You can convert a Time (or ActiveSupport::TimeWithZone) into a Date with Time#to_date:

from.to_date.step(to.to_date, 7) { |d| puts d.to_s }


来源: stackexchange

问:
How I get $key when I using ngFor using angularfire2?
I have some question, example I have a json file:

```<code>{
  "items" : {
    "khanh" : {
      "name":"2017 shirt",
      "size":["S","M","L"],
      "image":"http://placehold.it/650x450",
      "likes":0,
      "price":123
    },
    "-KdleehAQm0HgVFYdkUo" : {
      "name":"2017 shirt",
      "size":["S","M","L"],
      "image":"http://placehold.it/650x450",
      "likes":0,
      "price":123
    },
    "-Kdlg3AqKNTnbhjAVT8h" : {
      "name":"2017 shirt",
      "size":["S","M","L"],
      "image":"http://placehold.it/650x450",
      "likes":0,
      "price":123
    }
  }
}
</code>```

I have a button that update how many likes. But I have a problem. I don't know how to get the "key". Example:"khanh","-KdleehAQm0HgVFYdkUo"

答:
This worked for me.

Component:

```<code>import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

dbcomplextest: FirebaseListObservable<any[]>;

constructor(afDB: AngularFireDatabase) {
    this.dbcomplextest = afDB.list('/complex/');
}
</code>```

View:

```<code><span *ngFor="let value of dbcomplextest | async">
    {{ value.$key }} - {{ value.$value }}
</span>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some question, example I have a json file:

{
  "items" : {
    "khanh" : {
      "name":"2017 shirt",
      "size":["S","M","L"],
      "image":"http://placehold.it/650x450",
      "likes":0,
      "price":123
    },
    "-KdleehAQm0HgVFYdkUo" : {
      "name":"2017 shirt",
      "size":["S","M","L"],
      "image":"http://placehold.it/650x450",
      "likes":0,
      "price":123
    },
    "-Kdlg3AqKNTnbhjAVT8h" : {
      "name":"2017 shirt",
      "size":["S","M","L"],
      "image":"http://placehold.it/650x450",
      "likes":0,
      "price":123
    }
  }
}

I have a button that update how many likes. But I have a problem. I don't know how to get the "key". Example:"khanh","-KdleehAQm0HgVFYdkUo"

Body:
This worked for me.

Component:

import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

dbcomplextest: FirebaseListObservable<any[]>;

constructor(afDB: AngularFireDatabase) {
    this.dbcomplextest = afDB.list('/complex/');
}

View:

<span *ngFor="let value of dbcomplextest | async">
    {{ value.$key }} - {{ value.$value }}
</span>


问:
Gulp error - Error: Cannot find module 'sigmund'
My Gulp was working fine until I installed browser-sync

npm install browser-sync gulp --save-dev

Then I started to get this error:

Error: Cannot find module 'lru-cache'

Which I solved using this: npm link lru-cache answer from https://github.com/npm/npm/issues/1154

However, now when I try to run gulp I get this new error:

~/Projects/starfeeder
      ❯ npm install browser-sync gulp --save-dev
      npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
      npm WARN deprecated node-uuid@1.4.8: Use uuid module instead

fsevents@1.1.2 install
      /Users/leongaban/Projects/starfeeder/node_modules/fsevents
  node install

My gulpfile if that helps:

```<code>"use strict";
const gulp        = require('gulp'),
      _           = require('lodash'), // https://www.npmjs.com/package/lodash
      del         = require('del'), // https://www.npmjs.com/package/del
      fs          = require('fs'), // Node file system
      gutil       = require('gulp-util'), // https://www.npmjs.com/package/gulp-util
      htmlReplace = require('gulp-html-replace'), // https://www.npmjs.com/package/gulp-html-replace
      notify      = require("gulp-notify"), // https://www.npmjs.com/package/gulp-notify
      runSequence = require('run-sequence'), // https://www.npmjs.com/package/run-sequence
      sass        = require('gulp-ruby-sass'), // https://www.npmjs.com/package/gulp-ruby-sass
      sourcemaps  = require('gulp-sourcemaps'); // https://www.npmjs.com/package/gulp-sourcemaps

const rootPath = process.cwd();

const paths = {
    files: ['src/static/**']
};

const errorlog = err => {
    gutil.log(gutil.colors.red.bold.inverse('  ERROR: '+err));
    this.emit('end');
};

// Build tasks chain ///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
gulp.task('build', function(cb) {
    runSequence(
        'build:app-css',      // Minify and concat app styles
        'build:move-files',
        'build:index',        // Replace scripts in index.html
        'build:final', cb);   // Remove app.min.js from build folder
});

gulp.task('build:move-files', () => gulp.src(paths.files).pipe(gulp.dest('starfeeder/')) );

// Preprocess SASS into CSS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
gulp.task('build:app-css', () => sass('src/sass/starfeeder.scss', { style: 'compressed' }).on('error', errorlog).pipe(gulp.dest('src/static/css/')) );

// Clear out all files and folders from build folder \\\\\\\\\\\\\\\\\\\\\\\\\\\
gulp.task('build:cleanfolder', cb => { del(['starfeeder/**'], cb); });

// Task to make the index file production ready \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
gulp.task('build:index', () => {
    process.stdout.write(gutil.colors.white.inverse(' New asset paths in markup: \n'));
    process.stdout.write(gutil.colors.yellow(' static/css/starfeeder.css\n'));

    gulp.src('index.html')
        .pipe(htmlReplace({
            'app-css': 'css/starfeeder.css'
        }))
        .pipe(gulp.dest('starfeeder/'))
        .pipe(notify('Starfeeder build created!'));
});

gulp.task('build:final', cb => {
    process.stdout.write(gutil.colors.blue.bold   ('######################################################     \n'));
    process.stdout.write(gutil.colors.blue.inverse('               Starfeeder build created!                   \n'));
    process.stdout.write(gutil.colors.blue.bold   ('######################################################     \n'));
});

// Main Styles /////////////////////////////////////////////////////////////////
gulp.task('app-css', () => {
    return sass('src/sass/starfeeder.scss', { style: 'compressed' })
    .pipe(sourcemaps.init())
    .on('error', errorlog)
    .pipe(sourcemaps.write('./maps'))
    .pipe(gulp.dest('src/static/css/'))
});

// Development watch /////////////////////////////////////////////////////////// ☕⏎→
gulp.task('watch', () => {
    gulp.watch('src/sass/**/*.scss', ['app-css']).on('change', file => {
        let filePath = file.path.split(rootPath);
        logFileChanged(filePath[1]);
    });
});

gulp.task('default', ['watch']);
</code>```

答: I had this same issue with installing through2. The project used shrink wrap and had a package-lock.json which caused the a dependencies to break. Once I removed the lock and re-installed, all was good.

Body:
My Gulp was working fine until I installed browser-sync

npm install browser-sync gulp --save-dev

Then I started to get this error:

Error: Cannot find module 'lru-cache'

Which I solved using this: npm link lru-cache answer from https://github.com/npm/npm/issues/1154

However, now when I try to run gulp I get this new error:

~/Projects/starfeeder
      ❯ npm install browser-sync gulp --save-dev
      npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
      npm WARN deprecated node-uuid@1.4.8: Use uuid module instead

fsevents@1.1.2 install
      /Users/leongaban/Projects/starfeeder/node_modules/fsevents
  node install

My gulpfile if that helps:

"use strict";
const gulp        = require('gulp'),
      _           = require('lodash'), // https://www.npmjs.com/package/lodash
      del         = require('del'), // https://www.npmjs.com/package/del
      fs          = require('fs'), // Node file system
      gutil       = require('gulp-util'), // https://www.npmjs.com/package/gulp-util
      htmlReplace = require('gulp-html-replace'), // https://www.npmjs.com/package/gulp-html-replace
      notify      = require("gulp-notify"), // https://www.npmjs.com/package/gulp-notify
      runSequence = require('run-sequence'), // https://www.npmjs.com/package/run-sequence
      sass        = require('gulp-ruby-sass'), // https://www.npmjs.com/package/gulp-ruby-sass
      sourcemaps  = require('gulp-sourcemaps'); // https://www.npmjs.com/package/gulp-sourcemaps

const rootPath = process.cwd();

const paths = {
    files: ['src/static/**']
};

const errorlog = err => {
    gutil.log(gutil.colors.red.bold.inverse('  ERROR: '+err));
    this.emit('end');
};

// Build tasks chain ///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
gulp.task('build', function(cb) {
    runSequence(
        'build:app-css',      // Minify and concat app styles
        'build:move-files',
        'build:index',        // Replace scripts in index.html
        'build:final', cb);   // Remove app.min.js from build folder
});

gulp.task('build:move-files', () => gulp.src(paths.files).pipe(gulp.dest('starfeeder/')) );

// Preprocess SASS into CSS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
gulp.task('build:app-css', () => sass('src/sass/starfeeder.scss', { style: 'compressed' }).on('error', errorlog).pipe(gulp.dest('src/static/css/')) );

// Clear out all files and folders from build folder \\\\\\\\\\\\\\\\\\\\\\\\\\\
gulp.task('build:cleanfolder', cb => { del(['starfeeder/**'], cb); });

// Task to make the index file production ready \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
gulp.task('build:index', () => {
    process.stdout.write(gutil.colors.white.inverse(' New asset paths in markup: \n'));
    process.stdout.write(gutil.colors.yellow(' static/css/starfeeder.css\n'));

    gulp.src('index.html')
        .pipe(htmlReplace({
            'app-css': 'css/starfeeder.css'
        }))
        .pipe(gulp.dest('starfeeder/'))
        .pipe(notify('Starfeeder build created!'));
});

gulp.task('build:final', cb => {
    process.stdout.write(gutil.colors.blue.bold   ('######################################################     \n'));
    process.stdout.write(gutil.colors.blue.inverse('               Starfeeder build created!                   \n'));
    process.stdout.write(gutil.colors.blue.bold   ('######################################################     \n'));
});

// Main Styles /////////////////////////////////////////////////////////////////
gulp.task('app-css', () => {
    return sass('src/sass/starfeeder.scss', { style: 'compressed' })
    .pipe(sourcemaps.init())
    .on('error', errorlog)
    .pipe(sourcemaps.write('./maps'))
    .pipe(gulp.dest('src/static/css/'))
});

// Development watch /////////////////////////////////////////////////////////// ☕⏎→
gulp.task('watch', () => {
    gulp.watch('src/sass/**/*.scss', ['app-css']).on('change', file => {
        let filePath = file.path.split(rootPath);
        logFileChanged(filePath[1]);
    });
});

gulp.task('default', ['watch']);


问:
Mean on subsets of a subset
Still learning R, but I've personally accepted that this is impossible, and I hope one of you can prove me wrong.

I'm looking to find the mean for values <= 25th percentile, and the mean for values >= 75th percentile; but not for the whole data set. I would like to find these means for subsets of data, from which the percentiles were found.

This will generate data that resembles my own:

```<code>library(data.table)
DT <- data.table(V1 <- c('AR','AR','AR','AR','AR','AR','AD','AD','AD','AD','AD','AD','BD',
                         'BD','BD','BD','BX','CX','DX','DX','DD','DD','DD','DD','DR','DR',
                         'DR','DR','DR','DR'),
                 V2 <- c(.12,.02,.03,.22,.44,.09,.11,.17,.15,.26,.29,.27,.16,.16,.02,.12,.02,
                         .03,.22,.44,.09,.11,.17,.15,.26,.29,.27,.16,.16,.02))
</code>```

Looks like:

```<code>    V1   V2
 1: AR 0.12
 2: AR 0.02
 3: AR 0.03
 4: AR 0.22
 5: AR 0.44
 6: AR 0.09
 7: AD 0.11
 8: AD 0.17
 9: AD 0.15
10: AD 0.26
11: AD 0.29
12: AD 0.27
13: BD 0.16
14: BD 0.16
15: BD 0.02
16: BD 0.12
17: BX 0.02
18: CX 0.03
19: DX 0.22
20: DX 0.44
21: DD 0.09
22: DD 0.11
23: DD 0.17
24: DD 0.15
25: DR 0.26
26: DR 0.29
27: DR 0.27
28: DR 0.16
29: DR 0.16
30: DR 0.02
</code>```

First step: Calulate median, 25th percentile, 75th percentile, and count appearances of each A_, B_, C_, D_. Got it:

```<code>dt.qtile <- DT[, list(Bottom = quantile(V2, .25),
                      Middle = quantile(V2, .5),
                         Top = quantile(V2, .75),
                 Appearances = .N), by = V1]
</code>```

Produces:

```<code>   V1 Bottom Middle    Top Appearances
1: AR  0.045  0.105 0.1950           6
2: AD  0.155  0.215 0.2675           6
3: BD  0.095  0.140 0.1600           4
4: BX  0.020  0.020 0.0200           1
5: CX  0.030  0.030 0.0300           1
6: DX  0.275  0.330 0.3850           2
7: DD  0.105  0.130 0.1550           4
8: DR  0.160  0.210 0.2675           6
</code>```

This is where I think it's impossible. I would like to find the values in the original V2 (DT$V2) that are less than or equal to the value of the 25th percentile, then greater than or equal to 75th percentile for each letter combination in V1.

```<code>    V1   V2
 1: AR 0.12 -  Ignore   -
 2: AR 0.02 <= 0.045    \
 3: AR 0.03 <= 0.045    / mean = 0.05 (Bottom)
 4: AR 0.22 >= 0.1950   \
 5: AR 0.44 >= 0.1950   / mean = 0.33 (Top)
 6: AR 0.09 -  Ignore   -
    ------
 7: AD 0.11 <= 0.155    > mean = 0.11 (Bottom)
 8: AD 0.17 -  Ignore   -
 9: AD 0.15 -  Ignore   -
10: AD 0.26 >= 0.2675   \
11: AD 0.29 >= 0.2675    | mean = 0.2733 (Top)
12: AD 0.27 >= 0.2675   /
      ...
25: DR 0.26 -  Ignore   -
26: DR 0.29 >= 0.2675   \
27: DR 0.27 >= 0.2675   / mean = 0.28 (Top)
28: DR 0.16 <= 0.16    \
29: DR 0.16 <= 0.16     | mean = 0.17 (Bottom)
30: DR 0.02 <= 0.16    /
</code>```

Average the values in V2 that are <= 25th percentile, then average the values that are >= 75th percentile.

The new output should be something like this:

```<code>   V1 Bottom Middle    Top Appearances
1: AR  0.025  0.105 0.3300           6
2: AD  0.110  0.215 0.2733           6
                   ...
8: DR  0.170  0.210 0.2800           6
</code>```

This gets me close:

```<code>DT[V2 < quantile(V2, .25), mean(V2), by = V1]
</code>```

But it's computing the quantile for the whole data set, not each letter combination.

So I try:

```<code> DT[V2 < DT[, quantile(V2, .25), by = V1], mean(V2), by = V1]
</code>```

I get this:

```<code>Error in `[.data.table`(DT, V2 < DT[, quantile(V2, 0.25), by = V1], mean(V2),  :
  i is invalid type (matrix).
Perhaps in future a 2 column matrix could return a list of elements of DT
 (in the spirit of A[B] in FAQ 2.14).
Please let datatable-help know if you'd like this, or add your comments to FR #657.
</code>```

I know this has to be simple, but I just can't see it. What am I missing? Let me know where I can clarify.

I appreciate your help in advance!

EDIT

```<code>DT[, list( Bottom = mean(V2[V2 <= quantile(V2, 0.25)]),
           Middle = median(V2),
              Top = mean(V2[V2 >= quantile(V2, 0.75)]),
      Appearances = .N), by = V1]
</code>```

I would never have found this on my own.

Title: Mean on subsets of a subset

Body:
Still learning R, but I've personally accepted that this is impossible, and I hope one of you can prove me wrong.

I'm looking to find the mean for values <= 25th percentile, and the mean for values >= 75th percentile; but not for the whole data set. I would like to find these means for subsets of data, from which the percentiles were found.

This will generate data that resembles my own:

library(data.table)
DT <- data.table(V1 <- c('AR','AR','AR','AR','AR','AR','AD','AD','AD','AD','AD','AD','BD',
                         'BD','BD','BD','BX','CX','DX','DX','DD','DD','DD','DD','DR','DR',
                         'DR','DR','DR','DR'),
                 V2 <- c(.12,.02,.03,.22,.44,.09,.11,.17,.15,.26,.29,.27,.16,.16,.02,.12,.02,
                         .03,.22,.44,.09,.11,.17,.15,.26,.29,.27,.16,.16,.02))

Looks like:

    V1   V2
 1: AR 0.12
 2: AR 0.02
 3: AR 0.03
 4: AR 0.22
 5: AR 0.44
 6: AR 0.09
 7: AD 0.11
 8: AD 0.17
 9: AD 0.15
10: AD 0.26
11: AD 0.29
12: AD 0.27
13: BD 0.16
14: BD 0.16
15: BD 0.02
16: BD 0.12
17: BX 0.02
18: CX 0.03
19: DX 0.22
20: DX 0.44
21: DD 0.09
22: DD 0.11
23: DD 0.17
24: DD 0.15
25: DR 0.26
26: DR 0.29
27: DR 0.27
28: DR 0.16
29: DR 0.16
30: DR 0.02

First step: Calulate median, 25th percentile, 75th percentile, and count appearances of each A_, B_, C_, D_. Got it:

dt.qtile <- DT[, list(Bottom = quantile(V2, .25),
                      Middle = quantile(V2, .5),
                         Top = quantile(V2, .75),
                 Appearances = .N), by = V1]

Produces:

   V1 Bottom Middle    Top Appearances
1: AR  0.045  0.105 0.1950           6
2: AD  0.155  0.215 0.2675           6
3: BD  0.095  0.140 0.1600           4
4: BX  0.020  0.020 0.0200           1
5: CX  0.030  0.030 0.0300           1
6: DX  0.275  0.330 0.3850           2
7: DD  0.105  0.130 0.1550           4
8: DR  0.160  0.210 0.2675           6

This is where I think it's impossible. I would like to find the values in the original V2 (DT$V2) that are less than or equal to the value of the 25th percentile, then greater than or equal to 75th percentile for each letter combination in V1.

    V1   V2
 1: AR 0.12 -  Ignore   -
 2: AR 0.02 <= 0.045    \
 3: AR 0.03 <= 0.045    / mean = 0.05 (Bottom)
 4: AR 0.22 >= 0.1950   \
 5: AR 0.44 >= 0.1950   / mean = 0.33 (Top)
 6: AR 0.09 -  Ignore   -
    ------
 7: AD 0.11 <= 0.155    > mean = 0.11 (Bottom)
 8: AD 0.17 -  Ignore   -
 9: AD 0.15 -  Ignore   -
10: AD 0.26 >= 0.2675   \
11: AD 0.29 >= 0.2675    | mean = 0.2733 (Top)
12: AD 0.27 >= 0.2675   /
      ...
25: DR 0.26 -  Ignore   -
26: DR 0.29 >= 0.2675   \
27: DR 0.27 >= 0.2675   / mean = 0.28 (Top)
28: DR 0.16 <= 0.16    \
29: DR 0.16 <= 0.16     | mean = 0.17 (Bottom)
30: DR 0.02 <= 0.16    /

Average the values in V2 that are <= 25th percentile, then average the values that are >= 75th percentile.

The new output should be something like this:

   V1 Bottom Middle    Top Appearances
1: AR  0.025  0.105 0.3300           6
2: AD  0.110  0.215 0.2733           6
                   ...
8: DR  0.170  0.210 0.2800           6

This gets me close:

DT[V2 < quantile(V2, .25), mean(V2), by = V1]

But it's computing the quantile for the whole data set, not each letter combination.

So I try:

 DT[V2 < DT[, quantile(V2, .25), by = V1], mean(V2), by = V1]

I get this:

Error in `[.data.table`(DT, V2 < DT[, quantile(V2, 0.25), by = V1], mean(V2),  :
  i is invalid type (matrix).
Perhaps in future a 2 column matrix could return a list of elements of DT
 (in the spirit of A[B] in FAQ 2.14).
Please let datatable-help know if you'd like this, or add your comments to FR #657.

I know this has to be simple, but I just can't see it. What am I missing? Let me know where I can clarify.

I appreciate your help in advance!

EDIT

DT[, list( Bottom = mean(V2[V2 <= quantile(V2, 0.25)]),
           Middle = median(V2),
              Top = mean(V2[V2 >= quantile(V2, 0.75)]),
      Appearances = .N), by = V1]

I would never have found this on my own.

Body:
DT[, mean(V2[V2 < quantile(V2, 0.25)]), by = V1]
   V1    V1
1: AR 0.025
2: AD 0.130
3: BD 0.020
4: BX   NaN
5: CX   NaN
6: DX 0.220
7: DD 0.090
8: DR 0.020

DT[, mean(V2[V2 > quantile(V2, 0.75)]), by = V1]
   V1   V1
1: AR 0.33
2: AD 0.28
3: BD  NaN
4: BX  NaN
5: CX  NaN
6: DX 0.44
7: DD 0.17
8: DR 0.28


问:
Need recommendation for Node.js Gzip static resource
so, is connect's gzippo good?

I have two questions,

1) if i want to serve static javascript ( i use express), I can just do gzippo and do that:

app.use(gzippo.staticGzip(__dirname + '/public'));

is that right?  what if the client browser doesn't support gzip (in rare case)?  will it automatically send the uncompress version?  also, will the zipped file cached? or compress for every request?

2) If the app's get method returns JSON, what is the correct method to handle compress result?  should I first check the http.request header's "accept-encoding" and make sure it support gzip, then compress the JSON result?   or gzippo will automatically handle it?

one more question:
3)  If I have a uncompressed JS file (e.g. my.js)  and a manually gzipped JS file (e.g. my.js.gzip) in the public folder, which one will be served if client side script include is

do I have to specify as    ?

that a question not just on node.js but also on normal apache server. :)  thanks.

答:
Consider using some cloud API middleware like AWS APIGateway, some CDNs supporting GZipping and you always can craft your own reverse proxy server with nginx or HAproxy. See bullet 3 here:
http://goldbergyoni.com/checklist-best-practice-of-node-js-in-production/</p>


问:
Intent.EXTRA_CC not populating cc field in android app
I'm pre-filling an email which should launch in the users default email app but for some reason the CC line isn't populating with it's intended string. Any Idea what's going on?</p>

```<code>Intent toSupportIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" +  getString(R.string.support_email)));
toSupportIntent.putExtra(Intent.EXTRA_CC, getString(R.string.cc_support_email));
toSupportIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.support_email_subject));
toSupportIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.support_email_message));
startActivity(toSupportIntent);
</code>```

答: ACTION_SENDTO is not documented to support EXTRA_CC. Hence, you should not be surprised when it does not work with all apps.

Body:
I'm pre-filling an email which should launch in the users default email app but for some reason the CC line isn't populating with it's intended string. Any Idea what's going on?

Intent toSupportIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" +  getString(R.string.support_email)));
toSupportIntent.putExtra(Intent.EXTRA_CC, getString(R.string.cc_support_email));
toSupportIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.support_email_subject));
toSupportIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.support_email_message));
startActivity(toSupportIntent);


问:
How can I properly uninstall Anaconda?
I love Anaconda but it has given me so many headaches that I want to try removing it from my machine and starting over from scratch. The issues stem from paths changing behind the scenes and other things I don't understand. For example, I had to create a virtual environment within Anaconda (source create) just to use Spyder. I installed the Quantitative Economics package from home brew (brew install quantecon) and it too only works if I create a virtual environment for it. Weird stuff.

My question is: is starting over as simple as

```<code>conda install anaconda-clean
anaconda-clean --yes
rm -rf ~/anaconda
</code>```

and then reinstalling? Or are there other dependencies, possibly hidden, that I should be concerned about? My big concern is accidentally deleting the Mac OS python.

答:
You need to clean a few more files and directories:

OS X Anaconda uninstall

To uninstall Anaconda open a terminal window and remove the entire anaconda install directory: rm -rf ~/anaconda. You may also edit ~/.bash_profile and remove the anaconda directory from your PATH environment variable, and remove the hidden .condarc file and .conda and .continuum directories which may have been created in the home directory with rm -rf ~/.condarc ~/.conda ~/.continuum.

Title: How can I properly uninstall Anaconda?

Body:
I love Anaconda but it has given me so many headaches that I want to try removing it from my machine and starting over from scratch. The issues stem from paths changing behind the scenes and other things I don't understand. For example, I had to create a virtual environment within Anaconda (source create) just to use Spyder. I installed the Quantitative Economics package from home brew (brew install quantecon) and it too only works if I create a virtual environment for it. Weird stuff.

My question is: is starting over as simple as

conda install anaconda-clean
anaconda-clean --yes
rm -rf ~/anaconda

and then reinstalling? Or are there other dependencies, possibly hidden, that I should be concerned about? My big concern is accidentally deleting the Mac OS python.


问:
How to set fixed number of elements of array in Ruby
How to set fixed number of elements of an array in Ruby.

eg. a=["a","b","c","d"]
Setting array size to 3 would output

```<code>a=["a","b","cd"]
</code>```

答:
If you knew the elements were just one-character strings, you could do something like:

```<code>a.join.split '', 3
</code>```

Otherwise:

```<code>a[0..1] + [a[2..-1].join]
</code>```

Or perhaps:

```<code>a[0..1] << a[2..-1].join
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How to set fixed number of elements of an array in Ruby.

eg. a=["a","b","c","d"]
Setting array size to 3 would output

a=["a","b","cd"]

Body:
If you knew the elements were just one-character strings, you could do something like:

a.join.split '', 3

Otherwise:

a[0..1] + [a[2..-1].join]

Or perhaps:

a[0..1] << a[2..-1].join


问:
How to run two python application in docker
I want to run two python applicaiton in docker with different ports.

My shell script is below, the name is serverRun.sh

```<code>exec python __server_code.py &
exec python server_time_test.py &
</code>```

in dockerfile, I am trying to run these two python application

```<code>RUN ["chmod", "+x", "./serverRun.sh"]
</code>```

It did not work. Any idea?

答:
Your shell script must not terminate, so lock it within a while loop with a strong sleep.

Docker detects the termination of the entrypoint, and ends the container.

Eventually you might want to resort to an entrypoint (bash or other scripting languages) that is able to detect application crashes so your container quits on failure.

I published for you a fully-featured Bash entrypoint here which does exactly this, and more.

Body:
I want to run two python applicaiton in docker with different ports.

My shell script is below, the name is serverRun.sh

exec python __server_code.py &
exec python server_time_test.py &

in dockerfile, I am trying to run these two python application

RUN ["chmod", "+x", "./serverRun.sh"]

It did not work. Any idea?


问:
Error when converting C code to Web Assembly
I have successfully installed Emscripten and have it running on an Ubuntu 16.04 virtual machine. I have also successfully converted a helloworld.c file to web assembly. Currently, I am attempting to convert python to web assembly with emscripten. The issue is that emscripten does not support python currently, so as a work around I have attempted to convert the python code to C with Cython, which I successfully did. Though I am getting an error when attempting to convert the cython c file to Web assembly. Here is the console log:

```<code>$emcc pony_gp.c -o pony_gp.html

In file included from pony_gp.c:11:
In file included from /usr/include/python2.7/Python.h:58:
/usr/include/python2.7/pyport.h:886:2: error: "LONG_BIT definition appears
wrong for platform (bad gcc/glibc config?)."
#error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)."
ERROR:root:compiler frontend failed to generate LLVM bitcode, halting
</code>```

According to pyport.h, this error is generated because in some 32 bit systems LONG_BIT is defined incorrectly as 64 when it should be 32. I have tried commenting out this line, but this only allowed the program to silently run, in the end without producing any web assembly code, only html and javascript.

I have read here, that the issue is because "cmake is picking up one version of the python dylib and a separate version of python for the headers". This makes sense as I recently downgraded from Python 2.7.13-1 to Python 2.7.11-1 because Python 2.7.13-1 was not compatible with python-dev packages. Though, I don't know how I would fix this.

Does anyone have an idea on what to do?

答:
While not a full answer, you should be able to compile pony_gp.c directly to LLVM (.ll) using clang, preferably the same clang provided with Emscripten, for example:

```<code>source ~/emsdk/emsdk_env.sh
cython hello.py
clang `python2-config --cflags` -S -emit-llvm hello.c
</code>```

Then, the generated .ll file could be fed directly to Emscripten.

For producing a fully working Python -> WebAssembly you should probably also need to link against the Python runtime - you could use the one distributed with emcc which is already compiled into LLVM bytecode (.bc), emsdk/emscripten/incoming/tests/python/python.bc.

Also, this may be of help: https://github.com/dgym/cpython-emscripten

Body:
I have successfully installed Emscripten and have it running on an Ubuntu 16.04 virtual machine. I have also successfully converted a helloworld.c file to web assembly. Currently, I am attempting to convert python to web assembly with emscripten. The issue is that emscripten does not support python currently, so as a work around I have attempted to convert the python code to C with Cython, which I successfully did. Though I am getting an error when attempting to convert the cython c file to Web assembly. Here is the console log:

$emcc pony_gp.c -o pony_gp.html

In file included from pony_gp.c:11:
In file included from /usr/include/python2.7/Python.h:58:
/usr/include/python2.7/pyport.h:886:2: error: "LONG_BIT definition appears
wrong for platform (bad gcc/glibc config?)."
#error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)."
ERROR:root:compiler frontend failed to generate LLVM bitcode, halting

According to pyport.h, this error is generated because in some 32 bit systems LONG_BIT is defined incorrectly as 64 when it should be 32. I have tried commenting out this line, but this only allowed the program to silently run, in the end without producing any web assembly code, only html and javascript.

I have read here, that the issue is because "cmake is picking up one version of the python dylib and a separate version of python for the headers". This makes sense as I recently downgraded from Python 2.7.13-1 to Python 2.7.11-1 because Python 2.7.13-1 was not compatible with python-dev packages. Though, I don't know how I would fix this.

Does anyone have an idea on what to do?

Body:
While not a full answer, you should be able to compile pony_gp.c directly to LLVM (.ll) using clang, preferably the same clang provided with Emscripten, for example:

source ~/emsdk/emsdk_env.sh
cython hello.py
clang `python2-config --cflags` -S -emit-llvm hello.c

Then, the generated .ll file could be fed directly to Emscripten.

For producing a fully working Python -> WebAssembly you should probably also need to link against the Python runtime - you could use the one distributed with emcc which is already compiled into LLVM bytecode (.bc), emsdk/emscripten/incoming/tests/python/python.bc.

Also, this may be of help: https://github.com/dgym/cpython-emscripten


问:
Can't follow an organization in ckan
I setup ckan from source from the latest docs. When a user tries to follow an organization the following error appears on the interface in my browser:

```<code>404 Not Found

The resource could not be found.

Incorrect group type
</code>```

When I run the site using the "paster serve /etc/ckan/default/development.ini" command in my virtualenv I get the following error on my site when following an organization:

```<code>"Server Error

An internal server error occurred"
</code>```

And I get the following traceback on my terminal:

```<code>Error - <type 'exceptions.OSError'>: [Errno 13] Permission denied: '/tmp/default/sessions/container_file_lock/4'
URL: http://127.0.0.1:5000/group/follow/80a2d460-6c4d-436d-8e3b-45b2efca0752
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/weberror/errormiddleware.py', line 171 in __call__
  app_iter = self.application(environ, sr_checker)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
  resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
  return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/fanstatic/publisher.py', line 234 in __call__
  return request.get_response(self.app)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
  application, catch_exc_info=False)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
  app_iter = application(self.environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
  resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
  return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/fanstatic/injector.py', line 54 in __call__
  response = request.get_response(self.app)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
  application, catch_exc_info=False)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
  app_iter = application(self.environ, start_response)
File '/home/ammar/ckan/lib/default/src/ckan/ckan/config/middleware/pylons_app.py', line 245 in inner
  result = application(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 73 in __call__
  return self.app(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 155 in __call__
  return self.wrap_app(environ, session_start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/routes/middleware.py', line 131 in __call__
  response = self.app(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 125 in __call__
  response = self.dispatch(controller, environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 324 in dispatch
  return controller(environ, start_response)
File '/home/ammar/ckan/lib/default/src/ckan/ckan/lib/base.py', line 292 in __call__
  res = WSGIController.__call__(self, environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 284 in __call__
  return response(environ, self.start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/exc.py', line 341 in __call__
  return self.generate_response(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/exc.py', line 333 in generate_response
  return resp(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/response.py', line 917 in __call__
  start_response(self.status, headerlist)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 149 in session_start_response
  session.persist()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/session.py', line 735 in persist
  self._session().save()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/session.py', line 415 in save
  **self.namespace_args)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 635 in __init__
  OpenResourceNamespaceManager.__init__(self, namespace)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 190 in __init__
  self.access_lock = self.get_access_lock()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 647 in get_access_lock
  lock_dir=self.lock_dir)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 81 in file_synchronizer
  return _synchronizer(identifier, FileSynchronizer, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 74 in _synchronizer
  return _synchronizers.sync_get((identifier, cls), cls, identifier, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 177 in sync_get
  return self._create(key, createfunc, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 184 in _create
  self[key] = obj = createfunc(*args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 226 in __init__
  extension='.lock'
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 238 in encoded_path
  verify_directory(dir)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 85 in verify_directory
  os.makedirs(dir)
File '/usr/lib/ckan/default/lib/python2.7/os.py', line 150 in makedirs
  makedirs(head, mode)
File '/usr/lib/ckan/default/lib/python2.7/os.py', line 157 in makedirs
  mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/tmp/default/sessions/container_file_lock/4'
</code>```

Please help.

答:
It's purely directory permissions

drwxr-xr-x. 3 root root 16 May  8 17:33 4

Make sure the permissions are like this.

Also, make sure you have correct user and group permissions on this directory(recursively)

```<code>/tmp/default/sessions/container_file_lock/4
</code>```

Title: Can't follow an organization in ckan

Body:
I setup ckan from source from the latest docs. When a user tries to follow an organization the following error appears on the interface in my browser:

404 Not Found

The resource could not be found.

Incorrect group type

When I run the site using the "paster serve /etc/ckan/default/development.ini" command in my virtualenv I get the following error on my site when following an organization:

"Server Error

An internal server error occurred"

And I get the following traceback on my terminal:

Error - <type 'exceptions.OSError'>: [Errno 13] Permission denied: '/tmp/default/sessions/container_file_lock/4'
URL: http://127.0.0.1:5000/group/follow/80a2d460-6c4d-436d-8e3b-45b2efca0752
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/weberror/errormiddleware.py', line 171 in __call__
  app_iter = self.application(environ, sr_checker)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
  resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
  return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/fanstatic/publisher.py', line 234 in __call__
  return request.get_response(self.app)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
  application, catch_exc_info=False)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
  app_iter = application(self.environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
  resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
  return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/fanstatic/injector.py', line 54 in __call__
  response = request.get_response(self.app)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
  application, catch_exc_info=False)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
  app_iter = application(self.environ, start_response)
File '/home/ammar/ckan/lib/default/src/ckan/ckan/config/middleware/pylons_app.py', line 245 in inner
  result = application(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 73 in __call__
  return self.app(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 155 in __call__
  return self.wrap_app(environ, session_start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/routes/middleware.py', line 131 in __call__
  response = self.app(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 125 in __call__
  response = self.dispatch(controller, environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 324 in dispatch
  return controller(environ, start_response)
File '/home/ammar/ckan/lib/default/src/ckan/ckan/lib/base.py', line 292 in __call__
  res = WSGIController.__call__(self, environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 284 in __call__
  return response(environ, self.start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/exc.py', line 341 in __call__
  return self.generate_response(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/exc.py', line 333 in generate_response
  return resp(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/response.py', line 917 in __call__
  start_response(self.status, headerlist)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 149 in session_start_response
  session.persist()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/session.py', line 735 in persist
  self._session().save()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/session.py', line 415 in save
  **self.namespace_args)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 635 in __init__
  OpenResourceNamespaceManager.__init__(self, namespace)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 190 in __init__
  self.access_lock = self.get_access_lock()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 647 in get_access_lock
  lock_dir=self.lock_dir)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 81 in file_synchronizer
  return _synchronizer(identifier, FileSynchronizer, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 74 in _synchronizer
  return _synchronizers.sync_get((identifier, cls), cls, identifier, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 177 in sync_get
  return self._create(key, createfunc, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 184 in _create
  self[key] = obj = createfunc(*args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 226 in __init__
  extension='.lock'
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 238 in encoded_path
  verify_directory(dir)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 85 in verify_directory
  os.makedirs(dir)
File '/usr/lib/ckan/default/lib/python2.7/os.py', line 150 in makedirs
  makedirs(head, mode)
File '/usr/lib/ckan/default/lib/python2.7/os.py', line 157 in makedirs
  mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/tmp/default/sessions/container_file_lock/4'

Please help.

Body:
It's purely directory permissions

drwxr-xr-x. 3 root root 16 May  8 17:33 4

Make sure the permissions are like this.

Also, make sure you have correct user and group permissions on this directory(recursively)

/tmp/default/sessions/container_file_lock/4


问:
C++: set multiple variables from array
I have the following program:

```<code>#include <iostream>
using namespace std;

int main()
{
    int array[] = {1, 2, 3};
    int a = array[0],
        b = array[1],
        c = array[2];

    cout << c << endl;
}
</code>```

This prints 3, so far so good. But I wonder if there is a more elegant syntax for declaring multiple variables from an array at once. For example (just an idea, does not compile):

```<code>int [a, b, c] = array;
</code>```

Is there any feature like this in C++ or one of the new standards? I can't be the only one looking it.

Alternatively: what is your most elegant way to set multiple variables from an array at once?

答:
In C++17 you can use structured bindings - their syntax is very similar to what you have posted:

```<code>auto [a, b, c] = array;
</code>```

live example on wandbox

The closest thing to that in C++11/14 is std::tie, but it unfortunately doesn't work with arrays: it only supports std::tuple. You could however use metaprogramming to create an utility that creates a tuple from an array, and then use tie on it. There's a possible implementation in this answer by W.F..

Title: C++: set multiple variables from array

Body:
I have the following program:

#include <iostream>
using namespace std;

int main()
{
    int array[] = {1, 2, 3};
    int a = array[0],
        b = array[1],
        c = array[2];

    cout << c << endl;
}

This prints 3, so far so good. But I wonder if there is a more elegant syntax for declaring multiple variables from an array at once. For example (just an idea, does not compile):

int [a, b, c] = array;

Is there any feature like this in C++ or one of the new standards? I can't be the only one looking it.

Alternatively: what is your most elegant way to set multiple variables from an array at once?

Body:
In C++17 you can use structured bindings - their syntax is very similar to what you have posted:

auto [a, b, c] = array;

live example on wandbox

The closest thing to that in C++11/14 is std::tie, but it unfortunately doesn't work with arrays: it only supports std::tuple. You could however use metaprogramming to create an utility that creates a tuple from an array, and then use tie on it. There's a possible implementation in this answer by W.F..


问:
How to detect that the DrawerLayout started opening?
So I have tabs that I want to hide when the Navigation Drawer starts opening. The code I have hides them when it finished opening, but it's not what I want.

```<code>mDrawerToggle = new ActionBarDrawerToggle(
        this,
        mDrawerLayout,
        R.drawable.ic_drawer,
        R.string.drawer_open,
        R.string.drawer_close
) {
    @Override
    public void onDrawerClosed(View view) {
        invalidateOptionsMenu();
        setActionBarMode(ActionBar.NAVIGATION_MODE_TABS);
    }

    @Override
    public void onDrawerOpened(View drawerView) {
        invalidateOptionsMenu();
        setActionBarMode(ActionBar.NAVIGATION_MODE_STANDARD);
    }

};
mDrawerLayout.setDrawerListener(mDrawerToggle);
</code>```

Here's what I tried:

Setting an onClickListener to mDrawerLayout. onClick never gets called

Setting an onTouchListener to mDrawerLayout. onTouch never gets called

Researched ActionBarDrawerToggle and DrawerLayout classes. Could not find anything like onDrawerStartedOpening.

答:
fookwood answer did not work for me but slight modification in the if statment did the trick)</p>

```<code>ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, navigationDrawerLayout, topToolbar,
                R.string.open_drawer, R.string.close_drawer) {
            @Override public void onDrawerStateChanged(int newState) {
                if (newState == DrawerLayout.STATE_SETTLING && !navigationDrawerLayout.isDrawerOpen(navigationDrawerView)) {
                    // this where Drawer start opening
}
</code>```

Body:
So I have tabs that I want to hide when the Navigation Drawer starts opening. The code I have hides them when it finished opening, but it's not what I want.

mDrawerToggle = new ActionBarDrawerToggle(
        this,
        mDrawerLayout,
        R.drawable.ic_drawer,
        R.string.drawer_open,
        R.string.drawer_close
) {
    @Override
    public void onDrawerClosed(View view) {
        invalidateOptionsMenu();
        setActionBarMode(ActionBar.NAVIGATION_MODE_TABS);
    }

    @Override
    public void onDrawerOpened(View drawerView) {
        invalidateOptionsMenu();
        setActionBarMode(ActionBar.NAVIGATION_MODE_STANDARD);
    }

};
mDrawerLayout.setDrawerListener(mDrawerToggle);

Here's what I tried:

Setting an onClickListener to mDrawerLayout. onClick never gets called

Setting an onTouchListener to mDrawerLayout. onTouch never gets called

Researched ActionBarDrawerToggle and DrawerLayout classes. Could not find anything like onDrawerStartedOpening.

Body:
fookwood answer did not work for me but slight modification in the if statment did the trick)

ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, navigationDrawerLayout, topToolbar,
                R.string.open_drawer, R.string.close_drawer) {
            @Override public void onDrawerStateChanged(int newState) {
                if (newState == DrawerLayout.STATE_SETTLING && !navigationDrawerLayout.isDrawerOpen(navigationDrawerView)) {
                    // this where Drawer start opening
}


问:
AtmelStudio 7 default code won't build - 'no such file or directory' error
I keep getting the same two errors whenever I build any project:

```<code>../ ./main.c: No such file or directory
no input files
</code>```

Even if I start a new project and just use the default code provided, the same thing happens.

The type of project I am trying to build is a GCC C Executable Project.

I saw similar questions but they were all very complicated and didn't help me; I just want to get a project to build.

答:
Sometimes this issue can be due to spaces or bad characters in the file path. If your computer username has any of these, that's one reason it wouldn't work from the Desktop.

Suggest a dedicated folder on your drive without any special characters (e.g. C:\mySoftware\currentProject\).

Body:
I keep getting the same two errors whenever I build any project:

../ ./main.c: No such file or directory
no input files

Even if I start a new project and just use the default code provided, the same thing happens.

The type of project I am trying to build is a GCC C Executable Project.

I saw similar questions but they were all very complicated and didn't help me; I just want to get a project to build.


问:
Check if Rails association created in past x days
I'm trying to create a CRON job to monitor the activity status of a user on my platform.

It's supposed to check if the user has purchased something or messaged someone, and send an email if not. My method for the same is:

```<code>def self.create_new_user_reminders
  @new_users = User.where({ banned: false, admin: false })

  @new_users = @new_users.reject { |u| u.client.try(:purchases).any? or  u.client.try(:conversations).any? }

  @new_users.each do |nu|
    SalesMailer.delay.signup_no_engagement(nu)
  end
end
</code>```

Now I want to extend this to include a condition which would send an email if a client hasn't purchased something or messaged someone in the past 14 days.

Client is related to Purchases and Conversations as a has_many association.

One way I can think of doing this is buy creating nested loops and reject specific purchases and messages but this would be really inefficient.

What's a good way of implementing this on Rails?

答:
You can make use of created_at to check if the user has purchased something or messaged someone

```<code>@new_users = @new_users.reject { |u| u.client.try(:purchases).where('created_at > ?', 14.days.ago).any? or  u.client.try(:conversations).where('created_at > ?', 14.days.ago).any? }
</code>```

Body:
I'm trying to create a CRON job to monitor the activity status of a user on my platform.

It's supposed to check if the user has purchased something or messaged someone, and send an email if not. My method for the same is:

def self.create_new_user_reminders
  @new_users = User.where({ banned: false, admin: false })

  @new_users = @new_users.reject { |u| u.client.try(:purchases).any? or  u.client.try(:conversations).any? }

  @new_users.each do |nu|
    SalesMailer.delay.signup_no_engagement(nu)
  end
end

Now I want to extend this to include a condition which would send an email if a client hasn't purchased something or messaged someone in the past 14 days.

Client is related to Purchases and Conversations as a has_many association.

One way I can think of doing this is buy creating nested loops and reject specific purchases and messages but this would be really inefficient.

What's a good way of implementing this on Rails?

Body:
You can make use of created_at to check if the user has purchased something or messaged someone

@new_users = @new_users.reject { |u| u.client.try(:purchases).where('created_at > ?', 14.days.ago).any? or  u.client.try(:conversations).where('created_at > ?', 14.days.ago).any? }


问:
Compare list of strings in two different files vb.net
I have two different .txt files (requested_description.txt and all_description.txt).

In all_description.txt I have a list of strings, something like this:

all_description.txt

John is a policeman

  Mike is a doctor

  Barbara is a model

  etc...

In other file (requested_description.txt) I will search names from the first file (all_description.txt)

requested_description.txt

John

  Michael

  Ivan

  Donald

  Barbara

  etc...

I want to find if the strings (names) from requested_description.txt are the same in all_description.txt

Then I want to show results in output, for example:

John > John is a policeman

Barbara > Barbara is a model

For now I have only this sort of code, I want to use sort method, first to sort ascending then use for each... so I'm a little stuck here:

```<code>  Dim i As Integer = 0
  Dim ReadAllDescrpt As String() =File.ReadAllLines("all_description.txt")
  Dim RqstDescription As String()= File.ReadAllLines("rqst_description.txt")

  Dim allDescrpt As New List(Of String())
  allDescrpt.Sort()
  For Each descrpt In ReadAllDescrpt
     Console.WriteLine(ReadAllDescrpt)
  Next
  Console.WriteLine()
</code>```

答:
Simpler LINQ, use Join. Join on the name in rqst_description and first word in all_description. If you ever end up using first and last name, you need to join accordingly.

```<code>Sub Main()
    Dim descriptions As String() = File.ReadAllLines("all_description.txt")
    Dim names As String() = File.ReadAllLines("rqst_description.txt")

    Dim result = From name In names
                 Join description In descriptions On name Equals _
                    description.Split({" is a "}, StringSplitOptions.None).First()
                 Select String.Format("{0} > {1}", name, description)

    For Each s In result
        Console.WriteLine(s)
    Next
    Console.ReadLine()
End Sub
</code>```

According to your comment, the files have been changed

all_description.txt

John is a policeman

Mike is a doctor

Barbara is a model

Ivan The Terrible is a nice guy

rqst_description.txt

John Smith

Michael

Ivan The Terrible

Donald

Barbara

Output

Ivan The Terrible > Ivan The Terrible is a nice guy

 Barbara > Barbara is a model

Note: Contains works too, but I'm afraid of the etc.... If using Contains, you may get a false match i.e. Jon / Jonathan is a janitor (no offense to janitors, but Jon is not one).

Body:
I have two different .txt files (requested_description.txt and all_description.txt).

In all_description.txt I have a list of strings, something like this:

all_description.txt

John is a policeman

  Mike is a doctor

  Barbara is a model

  etc...

In other file (requested_description.txt) I will search names from the first file (all_description.txt)

requested_description.txt

John

  Michael

  Ivan

  Donald

  Barbara

  etc...

I want to find if the strings (names) from requested_description.txt are the same in all_description.txt

Then I want to show results in output, for example:

John > John is a policeman

Barbara > Barbara is a model

For now I have only this sort of code, I want to use sort method, first to sort ascending then use for each... so I'm a little stuck here:

  Dim i As Integer = 0
  Dim ReadAllDescrpt As String() =File.ReadAllLines("all_description.txt")
  Dim RqstDescription As String()= File.ReadAllLines("rqst_description.txt")

  Dim allDescrpt As New List(Of String())
  allDescrpt.Sort()
  For Each descrpt In ReadAllDescrpt
     Console.WriteLine(ReadAllDescrpt)
  Next
  Console.WriteLine()

Body:
Simpler LINQ, use Join. Join on the name in rqst_description and first word in all_description. If you ever end up using first and last name, you need to join accordingly.

Sub Main()
    Dim descriptions As String() = File.ReadAllLines("all_description.txt")
    Dim names As String() = File.ReadAllLines("rqst_description.txt")

    Dim result = From name In names
                 Join description In descriptions On name Equals _
                    description.Split({" is a "}, StringSplitOptions.None).First()
                 Select String.Format("{0} > {1}", name, description)

    For Each s In result
        Console.WriteLine(s)
    Next
    Console.ReadLine()
End Sub

According to your comment, the files have been changed

all_description.txt

John is a policeman

Mike is a doctor

Barbara is a model

Ivan The Terrible is a nice guy

rqst_description.txt

John Smith

Michael

Ivan The Terrible

Donald

Barbara

Output

Ivan The Terrible > Ivan The Terrible is a nice guy

 Barbara > Barbara is a model

Note: Contains works too, but I'm afraid of the etc.... If using Contains, you may get a false match i.e. Jon / Jonathan is a janitor (no offense to janitors, but Jon is not one).


问:
PHP Xpath Trying to get property of non-object
I have a problem with xpath. I'm trying to get data from this:

```<code><div class="clan__table">
      <div class="clan__headers">
        <div class="clan__headerCaption">Rank</div>
        <div class="clan__headerCaption">Name</div>
        <div class="clan__headerCaption">Level</div>
        <div class="clan__headerCaption">League</div>
        <div class="clan__headerCaption">Trophies</div>
        <div class="clan__headerCaption">Donations</div>
        <div class="clan__headerCaption">Role</div>
      </div>
      <div class="clan__rowContainer">
        <div class="clan__row">
                            #2
                    </div>
        <div class="clan__row">
          <a class="ui__blueLink" href='/profile/8C2PQYYL'>Voodoo</a>
        </div>
        <div class="clan__row">
          <span class="clan__playerLevel">11</span>
        </div>
        <div class="clan__row">
          <div class="clan__leagueContainer">
                            <div class="league__1"></div>
                        </div>
        </div>
        <div class="clan__row">
          <div class="clan__cup">4000</div>
        </div>
        <div class="clan__row">96</div>
        <div class="clan__row">
             Co-Leader
                    </div>
      </div>
....
....
</code>```

this is my code:

```<code>$xpath2 = new DOMXPath($doc2);
$text = "";
$playerlist_ul = $xpath2->query("//div[@class='clan__table']")->item(0);
$playernodes = $playerlist_ul->childNodes;
if (!empty($playernodes))
{
    foreach ($playernodes as $node2)
    {
        if ($node2->hasChildNodes())
        {

            $playerinfo = new DOMDocument();
            libxml_use_internal_errors(true);
            $playerinfo->loadHTML($node2->ownerDocument->saveHTML($node2));
            $xpath3 = new DOMXPath($playerinfo);

            $player['level'] = $xpath3->query("//span[@class='clan__playerLevel']")->item(0)->
                textContent;
            $player['name'] = $xpath3->query("//a[@class='ui__blueLink']")->item(0)->
                textContent;
            $player['id'] = $xpath3->query("//a[@class='ui__blueLink']/@href")->item(0)->
                textContent;
            $player['trophy'] = $xpath3->query("//div[@class='clan__cup']")->item(0)->
                textContent;
            $player['role'] = $xpath3->query("//div[@class='clan__row']")->item(6)->
                textContent;
            $player['donate'] = $xpath3->query("//div[@class='clan__row']")->item(5)->
                textContent;
            $player['clan_position'] = $xpath3->query("//div[@class='clan__row']")->item(0)->
                textContent;

            $players[] = $player;
        }
    }
}
</code>```

Everything almost working but i get error: Trying to get property of non-object in every line with  $player['....']
This is result

```<code>array (size=49)
  0 =>
    array (size=6)
      'level' => null
      'name' => null
      'trophy' => null
      'role' => null
      'donate' => null
      'clan_position' => null
  1 =>
    array (size=6)
      'level' => string '11' (length=2)
      'name' => string '/profile/8C2PQYYL' (length=17)
      'trophy' => string '4056' (length=4)
      'role' => string '
             Co-Leader
                    ' (length=44)
      'donate' => string '192' (length=3)
      'clan_position' => string '
                            #1
                    ' (length=52)
</code>```

There is something wrong with array[0]
So my question is: How to avoid this error?

答:
DOMXpath::query() will always return a DOMNodeList instance. You're fetching an node from that list and access its $textContent property. The error happens if here is no node.

It is easy to solve if you use DOMXpath::evaluate(). Xpath expression allow for typecasts, but only DOMXpath::evaluate() supports scalar return values.

So basically you use foreach() for expressions that return a node list and inside that expressions with typecasts for the details. Here is no need to save a fragment and load it as a separate document, you can provide a context node for the expression.

```<code>$document = new DOMDocument();
$document->loadHtml($html);
$xpath = new DOMXpath($document);

$expression = "//div[@class='clan__table']/div[@class='clan__rowContainer']";
foreach ($xpath->evaluate($expression) as $clanNode) {
  $result = [
    'level' => $xpath->evaluate("string(.//span[@class='clan__playerLevel'])", $clanNode),
    'name' => $xpath->evaluate("string(.//a[@class='ui__blueLink'])", $clanNode),
    'id' => $xpath->evaluate("string(.//a[@class='ui__blueLink']/@href)", $clanNode),
    'trophy' => $xpath->evaluate("string(.//div[@class='clan__cup'])", $clanNode),
    'role' => $xpath->evaluate("string(.//div[@class='clan__row'][7])", $clanNode),
    'donate' => $xpath->evaluate("string(.//div[@class='clan__row'][6])", $clanNode),
    'clan_position' => $xpath->evaluate(
       "normalize-space(.//div[@class='clan__row'][1])", $clanNode
    )
  ];
  var_dump($result);
}
</code>```

Output:

```<code>array(7) {
  ["level"]=>
  string(2) "11"
  ["name"]=>
  string(6) "Voodoo"
  ["id"]=>
  string(17) "/profile/8C2PQYYL"
  ["trophy"]=>
  string(4) "4000"
  ["role"]=>
  string(46) "
             Co-Leader
                    "
  ["donate"]=>
  string(2) "96"
  ["clan_position"]=>
  string(2) "#2"
}
</code>```

A little about the Xpath string() is an explicit typecast. It returns the text content of the first node of the list or an empty string. normalize-space() includes an implicit typecast, but it remove trims the string and replaces all groups of whitespaces with single spaces. [6] is the 6th element in the node list.

Body:
I have a problem with xpath. I'm trying to get data from this:

Rank

Name

Level

League

Trophies

Donations

Role

                            #2

          Voodoo

          11

4000

96

             Co-Leader

....
....

this is my code:

$xpath2 = new DOMXPath($doc2);
$text = "";
$playerlist_ul = $xpath2->query("//div[@class='clan__table']")->item(0);
$playernodes = $playerlist_ul->childNodes;
if (!empty($playernodes))
{
    foreach ($playernodes as $node2)
    {
        if ($node2->hasChildNodes())
        {

            $playerinfo = new DOMDocument();
            libxml_use_internal_errors(true);
            $playerinfo->loadHTML($node2->ownerDocument->saveHTML($node2));
            $xpath3 = new DOMXPath($playerinfo);

            $player['level'] = $xpath3->query("//span[@class='clan__playerLevel']")->item(0)->
                textContent;
            $player['name'] = $xpath3->query("//a[@class='ui__blueLink']")->item(0)->
                textContent;
            $player['id'] = $xpath3->query("//a[@class='ui__blueLink']/@href")->item(0)->
                textContent;
            $player['trophy'] = $xpath3->query("//div[@class='clan__cup']")->item(0)->
                textContent;
            $player['role'] = $xpath3->query("//div[@class='clan__row']")->item(6)->
                textContent;
            $player['donate'] = $xpath3->query("//div[@class='clan__row']")->item(5)->
                textContent;
            $player['clan_position'] = $xpath3->query("//div[@class='clan__row']")->item(0)->
                textContent;

            $players[] = $player;
        }
    }
}

Everything almost working but i get error: Trying to get property of non-object in every line with  $player['....']
This is result

array (size=49)
  0 =>
    array (size=6)
      'level' => null
      'name' => null
      'trophy' => null
      'role' => null
      'donate' => null
      'clan_position' => null
  1 =>
    array (size=6)
      'level' => string '11' (length=2)
      'name' => string '/profile/8C2PQYYL' (length=17)
      'trophy' => string '4056' (length=4)
      'role' => string '
             Co-Leader
                    ' (length=44)
      'donate' => string '192' (length=3)
      'clan_position' => string '
                            #1
                    ' (length=52)

There is something wrong with array[0]
So my question is: How to avoid this error?

Body:
DOMXpath::query() will always return a DOMNodeList instance. You're fetching an node from that list and access its $textContent property. The error happens if here is no node.

It is easy to solve if you use DOMXpath::evaluate(). Xpath expression allow for typecasts, but only DOMXpath::evaluate() supports scalar return values.

So basically you use foreach() for expressions that return a node list and inside that expressions with typecasts for the details. Here is no need to save a fragment and load it as a separate document, you can provide a context node for the expression.

$document = new DOMDocument();
$document->loadHtml($html);
$xpath = new DOMXpath($document);

$expression = "//div[@class='clan__table']/div[@class='clan__rowContainer']";
foreach ($xpath->evaluate($expression) as $clanNode) {
  $result = [
    'level' => $xpath->evaluate("string(.//span[@class='clan__playerLevel'])", $clanNode),
    'name' => $xpath->evaluate("string(.//a[@class='ui__blueLink'])", $clanNode),
    'id' => $xpath->evaluate("string(.//a[@class='ui__blueLink']/@href)", $clanNode),
    'trophy' => $xpath->evaluate("string(.//div[@class='clan__cup'])", $clanNode),
    'role' => $xpath->evaluate("string(.//div[@class='clan__row'][7])", $clanNode),
    'donate' => $xpath->evaluate("string(.//div[@class='clan__row'][6])", $clanNode),
    'clan_position' => $xpath->evaluate(
       "normalize-space(.//div[@class='clan__row'][1])", $clanNode
    )
  ];
  var_dump($result);
}

Output:

array(7) {
  ["level"]=>
  string(2) "11"
  ["name"]=>
  string(6) "Voodoo"
  ["id"]=>
  string(17) "/profile/8C2PQYYL"
  ["trophy"]=>
  string(4) "4000"
  ["role"]=>
  string(46) "
             Co-Leader
                    "
  ["donate"]=>
  string(2) "96"
  ["clan_position"]=>
  string(2) "#2"
}

A little about the Xpath string() is an explicit typecast. It returns the text content of the first node of the list or an empty string. normalize-space() includes an implicit typecast, but it remove trims the string and replaces all groups of whitespaces with single spaces. [6] is the 6th element in the node list.


问:
Pending BroadCastReceiver does not start using setDeleteIntnet
I make a notification and what i want to do is, when the user clicks the notification I sent to clear it, i want a pending broadcast to be executed.
there is a method called 'setDeleteIntent'. According to the documentation of this method, it should starts a pending BraodCast Receiver when the user clear the notification received.7

I create a Broadcast Receiver class as shown below in the code, and I supply the the 'setDeleteIntent' method with pending broadcast.
But at run time, when the notification received then cleared, the Log message in 'onReceive' of the BroadcastReceiver did not show on the console!!

please have a look at the code below, and please let em k know why the 'onReceive' of the broadcastReceiver never executes.

note: the BroadCasrReceiver was registered using 'LocalBroadCastReceiver' as shown in the code,.

code:

```<code>    String title = getString(R.string.app_name);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher);
    builder.setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg).setContentTitle(title);
    builder.setContentIntent(contentIntent).setAutoCancel(true);

    //builder.setWhen(Long.valueOf(eu.man.m24wsapp.utils.gcm.TimeUtils.getNowTS()) + 5000);
    builder.setLights(Color.argb(1, 0, 0, 255), 1000, 400);
    builder.setOngoing(false);
    builder.setAutoCancel(true);

    builder.setDeleteIntent(getPendingBroadCast());
    ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, builder.build());
    ....
    ....
    ....

    //getPendingBroadCast method
    private PendingIntent getPendingBroadCast() {
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(new BCRDismissNotification(),
            new IntentFilter(BCRDismissNotification.ACTION_DISMISSED_NOTIFICATION));

    Intent intent = new Intent(this, BCRDismissNotification.class);
    //intent.setAction(BCRDismissNotification.ACTION_DISMISSED_NOTIFICATION);
    return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
</code>```

BroadCast Receiver:

```<code>public class BCRDismissNotification extends BroadcastReceiver {
private final static String TAG = BCRDismissNotification.class.getSimpleName();
public final static String ACTION_DISMISSED_NOTIFICATION = "action_dismissed_notification";

@Override
public void onReceive(Context context, Intent intent) {

    Log.i(TAG, "*********************   BCR     **************");
}
</code>```

}

答:
You have pretty much answered your own question. This can't work with LocalBroadcastManager!

When you register a receiver with using LocalBroadcastManager, it only listens for broadcast Intents that are broadcast by your application. In your case, the broadcast Intent is sent by Android's notification framework, which is not part of your application. In this case, your registered receiver will not get triggered.

You need to register your receiver for global broadcasts. You can do this either by creating an instance of your receiver and calling registerReceiver() on the application Context OR you can just add your receiver to the manifest with a <receiver> tag and make sure that you set android:exported="true"

Body:
I make a notification and what i want to do is, when the user clicks the notification I sent to clear it, i want a pending broadcast to be executed.
there is a method called 'setDeleteIntent'. According to the documentation of this method, it should starts a pending BraodCast Receiver when the user clear the notification received.7

I create a Broadcast Receiver class as shown below in the code, and I supply the the 'setDeleteIntent' method with pending broadcast.
But at run time, when the notification received then cleared, the Log message in 'onReceive' of the BroadcastReceiver did not show on the console!!

please have a look at the code below, and please let em k know why the 'onReceive' of the broadcastReceiver never executes.

note: the BroadCasrReceiver was registered using 'LocalBroadCastReceiver' as shown in the code,.

code:

    String title = getString(R.string.app_name);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher);
    builder.setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg).setContentTitle(title);
    builder.setContentIntent(contentIntent).setAutoCancel(true);

    //builder.setWhen(Long.valueOf(eu.man.m24wsapp.utils.gcm.TimeUtils.getNowTS()) + 5000);
    builder.setLights(Color.argb(1, 0, 0, 255), 1000, 400);
    builder.setOngoing(false);
    builder.setAutoCancel(true);

    builder.setDeleteIntent(getPendingBroadCast());
    ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, builder.build());
    ....
    ....
    ....

    //getPendingBroadCast method
    private PendingIntent getPendingBroadCast() {
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(new BCRDismissNotification(),
            new IntentFilter(BCRDismissNotification.ACTION_DISMISSED_NOTIFICATION));

    Intent intent = new Intent(this, BCRDismissNotification.class);
    //intent.setAction(BCRDismissNotification.ACTION_DISMISSED_NOTIFICATION);
    return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

BroadCast Receiver:

public class BCRDismissNotification extends BroadcastReceiver {
private final static String TAG = BCRDismissNotification.class.getSimpleName();
public final static String ACTION_DISMISSED_NOTIFICATION = "action_dismissed_notification";

@Override
public void onReceive(Context context, Intent intent) {

    Log.i(TAG, "*********************   BCR     **************");
}

}


问:
allow the buddypress group administrator to add more admins
is there a way to allow the current group administrator to add more administrators from the front-end .. does buddypress include such feature , and if not , do you know any plugin doing help in that ? or where i should start from to develop this in my own .. i'm trying to use buddypress group as fan page .. and the main function i need from the buddypress groups is the multi admins feature .. i want to give the users the ability to create pages and add more admins , something similar to fb fan page .. hope someone can help</p>

答:
It's already possible to do that in BuddyPress.
Log in as a group admin, go to your group and open its "Manage" tab.
There you will see a subpage - Members. On this page, you will see the list of all members of the current group. If the member that you want to promote is not there - ask a user to join the group (or send him/her an invite). From "Manage -> Members" page you will be able to click on a "Promote to Admin" next to the member name - and thus the user will become an admin of this group.

More information can be found here: https://codex.buddypress.org/administrator-guide/groups/


问:
What are the differences between a pointer variable and a reference variable?
What is the difference between a pointer variable and a reference variable?</p>

答:
I feel like there is yet another point that hasn't been covered here.

Unlike the pointers, references are syntactically equivalent to the object they refer to, i.e. any operation that can be applied to an object works for a reference, and with the exact same syntax (the exception is of course the initialization).

While this may appear superficial, I believe this property is crucial for a number of C++ features, for example:

Templates. Since template parameters are duck-typed, syntactic properties of a type is all that matters, so often the same template can be used with both T and T&.

(or std::reference_wrapper<T> which still relies on an implicit cast
to T&)

Templates that cover both T& and T&& are even more common.

Lvalues. Consider the statement str[0] = 'X'; Without references it would only work for c-strings (char* str). Returning the character by reference allows user-defined classes to have the same notation.

Copy constructors. Syntactically it makes sense to pass objects to copy constructors, and not pointers to objects. But there is just no way for a copy constructor to take an object by value - it would result in a recursive call to the same copy constructor. This leaves references as the only option here.

Operator overloads. With references it is possible to introduce indirection to an operator call - say, operator+(const T& a, const T& b) while retaining the same infix notation. This also works for regular overloaded functions.

These points empower a considerable part of C++ and the standard library so this is quite a major property of references.

OwnerDisplayName: Prakash

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Prakash


问:
Array.reduce mutating state outside is not recommended?
Why is mutating variables outside .reduce() method considered bad practice? In the example below I am mutating a variable declared outside from inside the reduce method. Why is it not recommended to do so?

function balanceParens(string) {
    let max = 0;
    let res = string.split("").reduce((counter, char) => {
        // Handle if parens open and close out of order
        if (counter < 0) {
          return counter;
        }
        // Add 1 for each open in order
        if (char === "(") {
          if(++counter > max) {
            max = counter;
          }
          return counter;
        }
        // subtract 1 for each close in order
        if (char === ")") {
          return --counter;
        }
        // handle use case if char is not a paren
        return counter;
    }, 0);
    console.log("Max depth was :", max);
    return !res;
}
console.log(balanceParens("((()(((())))))((((()))))"));```

答:
Why is mutating variables outside .reduce() method considered bad practice?

Because you are mixing the functional with the imperative approach. Keep it to a single paradigm instead of confusing everyone.

You would go with

either reduce with a pure callback and no side effects

```<code>function step({max: oldMax, counter: oldCounter}, char) {
  const counter = oldCounter + (char=="(") - (char==")");
  const max = counter > oldMax ? counter : oldMax;
  return {max, counter};
}
function maxParensLevel(string) {
  assert(hasBalancedParens(string));
  const {max, counter} = string.split("").reduce(step, {max:0, counter:0});
  return max;
}
</code>```

or a simple loop and two mutable variables

```<code>function maxParensLevel(string) {
  assert(hasBalancedParens(string));
  let max = 0;
  let counter = 0;
  for (const char of string.split("")) {
    if (char == "(")
      counter++;
    else if (char == ")")
      counter--;
    if (counter > max)
      max = counter;
  }
  return max;
}
</code>```

but not both.

Body:
Why is mutating variables outside .reduce() method considered bad practice?

Because you are mixing the functional with the imperative approach. Keep it to a single paradigm instead of confusing everyone.

You would go with

either reduce with a pure callback and no side effects

function step({max: oldMax, counter: oldCounter}, char) {
  const counter = oldCounter + (char=="(") - (char==")");
  const max = counter > oldMax ? counter : oldMax;
  return {max, counter};
}
function maxParensLevel(string) {
  assert(hasBalancedParens(string));
  const {max, counter} = string.split("").reduce(step, {max:0, counter:0});
  return max;
}

or a simple loop and two mutable variables

function maxParensLevel(string) {
  assert(hasBalancedParens(string));
  let max = 0;
  let counter = 0;
  for (const char of string.split("")) {
    if (char == "(")
      counter++;
    else if (char == ")")
      counter--;
    if (counter > max)
      max = counter;
  }
  return max;
}

but not both.


问:
Reshaping pandas dataframe with a column containing lists
Let's say I have a dataframe that looks like this:

```<code>import pandas as pd

data = [{"Name" : "Project A", "Feedback" : ['we should do x', 'went well']},
            {"Name" : "Project B", "Feedback" : ['eat pop tarts', 'boo']},
            {"Name" : "Project C", "Feedback" : ['bar', 'baz']}
            ]

df = pd.DataFrame(data)
df = df[['Name','Feedback']]
df

    Name        Feedback
0   Project A   ['we should do x', 'went well']
1   Project B   ['eat pop tarts', 'boo']
2   Project C   ['bar', 'baz']
</code>```

What I would like to do is reshape the dataframe, such that Name is the key and each element in the list of the Feedback column is a value like so:

```<code>        Name          Feedback
0       Project A    'we should do x'
1       Project A    'went well'
2       Project B    'eat pop tarts'
3       Project B    'boo'
4       Project C    'bar'
5       Project C    'baz'
</code>```

What would be an efficient way to do this?

答:
One option is to reconstruct the data frame by flattening column Feedback and repeat column Name:

```<code>pd.DataFrame({
        'Name': df.Name.repeat(df.Feedback.str.len()),
        'Feedback': [x for s in df.Feedback for x in s]
    })

#         Feedback       Name
#0  we should do x  Project A
#0       went well  Project A
#1   eat pop tarts  Project B
#1             boo  Project B
#2             bar  Project C
#2             baz  Project C
</code>```

Body:
Let's say I have a dataframe that looks like this:

import pandas as pd

data = [{"Name" : "Project A", "Feedback" : ['we should do x', 'went well']},
            {"Name" : "Project B", "Feedback" : ['eat pop tarts', 'boo']},
            {"Name" : "Project C", "Feedback" : ['bar', 'baz']}
            ]

df = pd.DataFrame(data)
df = df[['Name','Feedback']]
df

    Name        Feedback
0   Project A   ['we should do x', 'went well']
1   Project B   ['eat pop tarts', 'boo']
2   Project C   ['bar', 'baz']

What I would like to do is reshape the dataframe, such that Name is the key and each element in the list of the Feedback column is a value like so:

        Name          Feedback
0       Project A    'we should do x'
1       Project A    'went well'
2       Project B    'eat pop tarts'
3       Project B    'boo'
4       Project C    'bar'
5       Project C    'baz'

What would be an efficient way to do this?

Body:
One option is to reconstruct the data frame by flattening column Feedback and repeat column Name:

pd.DataFrame({
        'Name': df.Name.repeat(df.Feedback.str.len()),
        'Feedback': [x for s in df.Feedback for x in s]
    })

#         Feedback       Name
#0  we should do x  Project A
#0       went well  Project A
#1   eat pop tarts  Project B
#1             boo  Project B
#2             bar  Project C
#2             baz  Project C


问:
Change file name when exporting to CSV in Angular UI Grid
We are using Angular UI Grid in out project. I need to put current date in file name with exported CSV data.
What I'm doing now on "export" button click:

```<code>$scope.exportCSV = function () {
     $scope.gridOptions.exporterCsvFilename = getDate() + ".csv";
     $scope.gridApi.exporter.csvExport("all", "visible");
};
</code>```

The problem is that filename is configured only once and doesn't change in next clicks. How can I set file name again?

答:
I was able to modify the export file name if I did not include it in the initial gridOptions before the onRegisterApi().

```<code>    $scope.gridOptions = {
        // exporterCsvFilename: 'Do not set here',
        exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
        columnDefs: [
            { field: 'Category' },
            { field: 'Description' },
            { field: 'RateCode' }
        ],
    };
</code>```

After that I could set it with javascript like this:

```<code>    $scope.gridOptions.exporterCsvFilename = 'Custom_' + $scope.selectedVersion.VersionNumber + '_2017-06-29.csv';
</code>```

Body:
We are using Angular UI Grid in out project. I need to put current date in file name with exported CSV data.
What I'm doing now on "export" button click:

$scope.exportCSV = function () {
     $scope.gridOptions.exporterCsvFilename = getDate() + ".csv";
     $scope.gridApi.exporter.csvExport("all", "visible");
};

The problem is that filename is configured only once and doesn't change in next clicks. How can I set file name again?

Body:
I was able to modify the export file name if I did not include it in the initial gridOptions before the onRegisterApi().

    $scope.gridOptions = {
        // exporterCsvFilename: 'Do not set here',
        exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
        columnDefs: [
            { field: 'Category' },
            { field: 'Description' },
            { field: 'RateCode' }
        ],
    };

After that I could set it with javascript like this:

    $scope.gridOptions.exporterCsvFilename = 'Custom_' + $scope.selectedVersion.VersionNumber + '_2017-06-29.csv';


问:
library not recognised in reactjs
clicke here to see pondjs folder inside node-modulesI've installed pondjs(https://www.npmjs.com/package/pondjs) using npm install pondjs --save in my react application. It's also present in package.json. I couldn't understand why in App. js when I'm doing :

```<code>import { TimeSeries , TimeRange} from 'pondjs';
</code>```

it says module not installed and hence unable to recognise it's functions.

Also, I have a js file which contains lots of data in Object form  and I'm trying to import that file in App.js using :

```<code>import pathtofile/inputdata.js';
</code>```

and storing in the variable as below :

```<code>var input_data = data;
</code>```

IS this the right way to do in react App.js file?  Please suggest

答: For pondjs, my code is working on Sumblime Text and Terminal. May be Webstorm IDE is not recognizing Pondjs or something.</p>

Title: library not recognised in reactjs

Body:
clicke here to see pondjs folder inside node-modulesI've installed pondjs(https://www.npmjs.com/package/pondjs) using npm install pondjs --save in my react application. It's also present in package.json. I couldn't understand why in App. js when I'm doing :

import { TimeSeries , TimeRange} from 'pondjs';

it says module not installed and hence unable to recognise it's functions.

Also, I have a js file which contains lots of data in Object form  and I'm trying to import that file in App.js using :

import pathtofile/inputdata.js';

and storing in the variable as below :

var input_data = data;

IS this the right way to do in react App.js file?  Please suggest