问:
ngConstant:dev returns null
I'm almost there with a jhipster generated app that I'm upgrading from v3.0.0 to v4.11, but I've been banging my head against a wall with gulp for almost a whole day now

When running serve/build tasks it seems to have an error when generating the environment from the ngconstant task.

If I understand right, gulp will run the task serve or build and then call the run-sequence, which should go to the ngconstant task and generate the contents for app.constants.js.

Well, it seems to fail when trying to pick up the name of the environment from ngconstant, here's the error:

```<code>[11:08:29] 'ngconstant:dev' errored after 37 ms
[11:08:29] Error in plugin 'gulp-tslint-log'
TypeError: Path must be a string. Received null
    at assertPath (path.js:7:11)
    at Object.dirname (path.js:1324:5)
    at getFilePath (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:95:27)
    at DestroyableTransform.objectStream [as _transform] (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:60:25)
    at DestroyableTransform.Transform._read (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at DestroyableTransform.Writable.end (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:352:10)
    at ngConstantPlugin (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:33:16)
    at Gulp.<anonymous> (/home/steven/Desktop/Upgraded_MQ/gulpfile.js:162:12)
    at module.exports (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:134:8)
[11:08:29] Starting 'watch'...
[11:08:29] Finished 'watch' after 147 ms
[11:08:29] Error in plugin 'run-sequence(ngconstant:dev)'
Message:
    TypeError: Path must be a string. Received null
    at assertPath (path.js:7:11)
    at Object.dirname (path.js:1324:5)
    at getFilePath (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:95:27)
    at DestroyableTransform.objectStream [as _transform] (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:60:25)
    at DestroyableTransform.Transform._read (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at DestroyableTransform.Writable.end (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:352:10)
    at ngConstantPlugin (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:33:16)
    at Gulp.<anonymous> (/home/steven/Desktop/Upgraded_MQ/gulpfile.js:162:12)
    at module.exports (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:134:8)
Stack:
Error: TypeError: Path must be a string. Received null
    at assertPath (path.js:7:11)
    at Object.dirname (path.js:1324:5)
    at getFilePath (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:95:27)
    at DestroyableTransform.objectStream [as _transform] (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:60:25)
    at DestroyableTransform.Transform._read (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at DestroyableTransform.Writable.end (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:352:10)
    at ngConstantPlugin (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:33:16)
    at Gulp.<anonymous> (/home/steven/Desktop/Upgraded_MQ/gulpfile.js:162:12)
    at module.exports (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:134:8)
    at pluginError (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:99:12)
    at DestroyableTransform.objectStream [as _transform] (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:65:33)
    at DestroyableTransform.Transform._read (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at DestroyableTransform.Writable.end (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:352:10)
    at ngConstantPlugin (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:33:16)
    at Gulp.<anonymous> (/home/steven/Desktop/Upgraded_MQ/gulpfile.js:162:12)
    at module.exports (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:134:8)
    at runNextSet (/home/steven/Desktop/Upgraded_MQ/node_modules/run-sequence/index.js:86:16)
    at runSequence (/home/steven/Desktop/Upgraded_MQ/node_modules/run-sequence/index.js:97:2)
</code>```

My gulpfile.js:

```<code>'use strict';

var gulp = require('gulp'),
    expect = require('gulp-expect-file'),
    sass = require('gulp-sass'),
    rev = require('gulp-rev'),
    templateCache = require('gulp-angular-templatecache'),
    htmlmin = require('gulp-htmlmin'),
    imagemin = require('gulp-imagemin'),
    ngConstant = require('gulp-ng-constant-fork'),
    eslint = require('gulp-eslint'),
    es = require('event-stream'),
    flatten = require('gulp-flatten'),
    del = require('del'),
    wiredep = require('wiredep').stream,
    runSequence = require('run-sequence'),
    browserSync = require('browser-sync'),
    KarmaServer = require('karma').Server,
    plumber = require('gulp-plumber'),
    changed = require('gulp-changed'),
    gulpIf = require('gulp-if'),
    inject = require('gulp-inject'),
    angularFilesort = require('gulp-angular-filesort');

var handleErrors = require('./gulp/handleErrors'),
    serve = require('./gulp/serve'),
    util = require('./gulp/utils'),
    build = require('./gulp/build');

var config = require('./gulp/config');

gulp.task('clean', function () {
    return del([config.dist], { dot: true });
});

gulp.task('copy', function () {
    return es.merge(
        gulp.src(config.app + 'content/**/*.{woff,woff2,svg,ttf,eot,otf}')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/fonts/'))
        .pipe(flatten())
        .pipe(rev())
        .pipe(gulp.dest(config.dist + 'content/fonts/'))
        .pipe(rev.manifest(config.revManifest, {
            base: config.dist,
            merge: true
        }))
        .pipe(gulp.dest(config.dist)),
        gulp.src([config.app + 'robots.txt', config.app + 'favicon.ico', config.app + '.htaccess'], { dot: true })
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist))
        .pipe(gulp.dest(config.dist))
    );
});

gulp.task('images', function () {
    return gulp.src(config.app + 'content/images/**')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/images'))
        .pipe(imagemin({optimizationLevel: 5, progressive: true, interlaced: true}))
        .pipe(rev())
        .pipe(gulp.dest(config.dist + 'content/images'))
        .pipe(rev.manifest(config.revManifest, {
            base: config.dist,
            merge: true
        }))
        .pipe(gulp.dest(config.dist))
        .pipe(browserSync.reload({stream: true}));
});

gulp.task('sass', function () {
    return es.merge(
        gulp.src(config.sassSrc)
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(expect(config.sassSrc))
        .pipe(changed(config.cssDir, {extension: '.css'}))
        .pipe(sass({includePaths:config.bower}).on('error', sass.logError))
        .pipe(gulp.dest(config.cssDir)),
        gulp.src(config.bower + '**/fonts/**/*.{woff,woff2,svg,ttf,eot,otf}')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.app + 'content/fonts'))
        .pipe(flatten())
        .pipe(gulp.dest(config.app + 'content/fonts'))
    );
});

gulp.task('styles', ['sass'], function () {
    return gulp.src(config.app + 'content/css')
        .pipe(browserSync.reload({stream: true}));
});

gulp.task('inject', function () {
    return gulp.src(config.app + 'index.html')
        .pipe(inject(gulp.src(config.app + 'app/**/*.js').pipe(angularFilesort()), {relative: true}))
        .pipe(gulp.dest(config.app));
});

gulp.task('wiredep', ['wiredep:test', 'wiredep:app']);

gulp.task('wiredep:app', function () {
    var stream = gulp.src(config.app + 'index.html')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(wiredep({
            exclude: [
                /angular-i18n/,  // localizations are loaded dynamically
                'bower_components/bootstrap-sass/assets/javascripts/' // Exclude Bootstrap js files as we use ui-bootstrap
            ]
        }))
        .pipe(gulp.dest(config.app));

    return es.merge(stream, gulp.src(config.sassSrc)
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(wiredep({
            ignorePath: /\.\.\/webapp\/bower_components\// // remove ../webapp/bower_components/ from paths of injected sass files
        }))
        .pipe(gulp.dest(config.scss)));
});

gulp.task('wiredep:test', function () {
    return gulp.src(config.test + 'karma.conf.js')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(wiredep({
            exclude: [
                /angular-i18n/,  // localizations are loaded dynamically
                /angular-scenario/,
                'bower_components/bootstrap-sass/assets/javascripts/' // Exclude Bootstrap js files as we use ui-bootstrap
            ],
            ignorePath: /\.\.\/\.\.\//, // remove ../../ from paths of injected JavaScript files
            devDependencies: true,
            fileTypes: {
                js: {
                    block: /(([\s\t]*)\/\/\s*bower:*(\S*))(\n|\r|.)*?(\/\/\s*endbower)/gi,
                    detect: {
                        js: /'(.*\.js)'/gi
                    },
                    replace: {
                        js: '\'src/{{filePath}}\','
                    }
                }
            }
        }))
        .pipe(gulp.dest(config.test));
});

gulp.task('assets:prod', ['images', 'styles', 'html'], build);

gulp.task('html', function () {
    return gulp.src(config.app + 'app/**/*.html')
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(templateCache({
            module: 'drugQualityDataManagerApp',
            root: 'app/',
            moduleSystem: 'IIFE'
        }))
        .pipe(gulp.dest(config.tmp));
});

gulp.task('ngconstant:dev', function () {
    return ngConstant({
        dest: 'app.constants.js',
        name: 'drugQualityDataManagerApp',
        deps: false,
        noFile: true,
        interpolate: /\{%=(.+?)%\}/g,
        wrap:
            '(function () {\n' +
            '    "use strict";\n' +
            '    // DO NOT EDIT THIS FILE, EDIT THE GULP TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE\n' +
            '    {%= __ngModule %}\n' +
            '})();\n',
        constants: {
            ENV: 'dev',
            VERSION: util.parseVersion()
        }
    })
    .pipe(gulp.dest(config.app + 'app/'));
});

gulp.task('ngconstant:prod', function () {
    return ngConstant({
        dest: 'app.constants.js',
        name: 'drugQualityDataManagerApp',
        deps: false,
        noFile: true,
        interpolate: /\{%=(.+?)%\}/g,
        wrap:
            '(function () {\n' +
            '    "use strict";\n' +
            '    // DO NOT EDIT THIS FILE, EDIT THE GULP TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE\n' +
            '    {%= __ngModule %}\n' +
            '})();\n',
        constants: {
            ENV: 'prod',
            VERSION: util.parseVersion()
        }
    })
    .pipe(gulp.dest(config.app + 'app/'));
});

// check app for eslint errors
gulp.task('eslint', function () {
    return gulp.src(['gulpfile.js', config.app + 'app/**/*.js'])
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failOnError());
});

// check app for eslint errors anf fix some of them
gulp.task('eslint:fix', function () {
    return gulp.src(config.app + 'app/**/*.js')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(eslint({
            fix: true
        }))
        .pipe(eslint.format())
        .pipe(gulpIf(util.isLintFixed, gulp.dest(config.app + 'app')));
});

gulp.task('test', ['wiredep:test', 'ngconstant:dev'], function (done) {
    new KarmaServer({
        configFile: __dirname + '/' + config.test + 'karma.conf.js',
        singleRun: true
    }, done).start();
});

gulp.task('watch', function () {
    gulp.watch('bower.json', ['install']);
    gulp.watch(['gulpfile.js', 'pom.xml'], ['ngconstant:dev']);
    gulp.watch(config.sassSrc, ['styles']);
    gulp.watch(config.app + 'content/images/**', ['images']);
    gulp.watch(config.app + 'app/**/*.js', ['inject']);
    gulp.watch([config.app + '*.html', config.app + 'app/**', config.app + 'i18n/**']).on('change', browserSync.reload);
});

gulp.task('install', function () {
    runSequence(['wiredep', 'ngconstant:dev'], 'sass', 'inject');
});

gulp.task('serve', function () {
    runSequence('install', serve);
});

gulp.task('build', ['clean'], function (cb) {
    runSequence(['copy', 'wiredep:app', 'ngconstant:prod'], 'inject', 'assets:prod', cb);
});

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

There's not much I have been able to try, I've basically been toying around with the differences between this gulp configuration and the pre-upgrade one, to find not many differences at all, and when changing, finding no positive results.  I've also toyed around with the pom profile for deployment on server, no changes

答:
So far, the only thing that lets the app build is to remove ngconstant calls from runSequence, leaving install, serve and build tasks like:

```<code>gulp.task('install', function () {
    runSequence(['wiredep'], 'sass', 'inject');
});

gulp.task('serve', function () {
    runSequence('install', serve);
});

gulp.task('build', ['clean'], function (cb) {
    runSequence(['copy', 'wiredep:app'], 'inject', 'assets:prod', cb);
});
</code>```

Where they used to be like:

```<code>gulp.task('install', function () {
    runSequence(['wiredep', 'ngconstant:dev'], 'sass', 'inject');
});

gulp.task('serve', function () {
    runSequence('install', serve);
});

gulp.task('build', ['clean'], function (cb) {
    runSequence(['copy', 'wiredep:app', 'ngconstant:prod'], 'inject', 'assets:prod', cb);
});
</code>```

This is far from an ideal workaround, but at least it keeps me on my feet, I would highly appreciate better recommendations for this

Title: ngConstant:dev returns null

Body:
I'm almost there with a jhipster generated app that I'm upgrading from v3.0.0 to v4.11, but I've been banging my head against a wall with gulp for almost a whole day now

When running serve/build tasks it seems to have an error when generating the environment from the ngconstant task.

If I understand right, gulp will run the task serve or build and then call the run-sequence, which should go to the ngconstant task and generate the contents for app.constants.js.

Well, it seems to fail when trying to pick up the name of the environment from ngconstant, here's the error:

[11:08:29] 'ngconstant:dev' errored after 37 ms
[11:08:29] Error in plugin 'gulp-tslint-log'
TypeError: Path must be a string. Received null
    at assertPath (path.js:7:11)
    at Object.dirname (path.js:1324:5)
    at getFilePath (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:95:27)
    at DestroyableTransform.objectStream [as _transform] (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:60:25)
    at DestroyableTransform.Transform._read (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at DestroyableTransform.Writable.end (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:352:10)
    at ngConstantPlugin (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:33:16)
    at Gulp.<anonymous> (/home/steven/Desktop/Upgraded_MQ/gulpfile.js:162:12)
    at module.exports (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:134:8)
[11:08:29] Starting 'watch'...
[11:08:29] Finished 'watch' after 147 ms
[11:08:29] Error in plugin 'run-sequence(ngconstant:dev)'
Message:
    TypeError: Path must be a string. Received null
    at assertPath (path.js:7:11)
    at Object.dirname (path.js:1324:5)
    at getFilePath (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:95:27)
    at DestroyableTransform.objectStream [as _transform] (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:60:25)
    at DestroyableTransform.Transform._read (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at DestroyableTransform.Writable.end (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:352:10)
    at ngConstantPlugin (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:33:16)
    at Gulp.<anonymous> (/home/steven/Desktop/Upgraded_MQ/gulpfile.js:162:12)
    at module.exports (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:134:8)
Stack:
Error: TypeError: Path must be a string. Received null
    at assertPath (path.js:7:11)
    at Object.dirname (path.js:1324:5)
    at getFilePath (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:95:27)
    at DestroyableTransform.objectStream [as _transform] (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:60:25)
    at DestroyableTransform.Transform._read (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at DestroyableTransform.Writable.end (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:352:10)
    at ngConstantPlugin (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:33:16)
    at Gulp.<anonymous> (/home/steven/Desktop/Upgraded_MQ/gulpfile.js:162:12)
    at module.exports (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:134:8)
    at pluginError (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:99:12)
    at DestroyableTransform.objectStream [as _transform] (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:65:33)
    at DestroyableTransform.Transform._read (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at DestroyableTransform.Writable.end (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/node_modules/readable-stream/lib/_stream_writable.js:352:10)
    at ngConstantPlugin (/home/steven/Desktop/Upgraded_MQ/node_modules/gulp-ng-constant-fork/index.js:33:16)
    at Gulp.<anonymous> (/home/steven/Desktop/Upgraded_MQ/gulpfile.js:162:12)
    at module.exports (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/home/steven/Desktop/Upgraded_MQ/node_modules/orchestrator/index.js:134:8)
    at runNextSet (/home/steven/Desktop/Upgraded_MQ/node_modules/run-sequence/index.js:86:16)
    at runSequence (/home/steven/Desktop/Upgraded_MQ/node_modules/run-sequence/index.js:97:2)

My gulpfile.js:

'use strict';

var gulp = require('gulp'),
    expect = require('gulp-expect-file'),
    sass = require('gulp-sass'),
    rev = require('gulp-rev'),
    templateCache = require('gulp-angular-templatecache'),
    htmlmin = require('gulp-htmlmin'),
    imagemin = require('gulp-imagemin'),
    ngConstant = require('gulp-ng-constant-fork'),
    eslint = require('gulp-eslint'),
    es = require('event-stream'),
    flatten = require('gulp-flatten'),
    del = require('del'),
    wiredep = require('wiredep').stream,
    runSequence = require('run-sequence'),
    browserSync = require('browser-sync'),
    KarmaServer = require('karma').Server,
    plumber = require('gulp-plumber'),
    changed = require('gulp-changed'),
    gulpIf = require('gulp-if'),
    inject = require('gulp-inject'),
    angularFilesort = require('gulp-angular-filesort');

var handleErrors = require('./gulp/handleErrors'),
    serve = require('./gulp/serve'),
    util = require('./gulp/utils'),
    build = require('./gulp/build');

var config = require('./gulp/config');

gulp.task('clean', function () {
    return del([config.dist], { dot: true });
});

gulp.task('copy', function () {
    return es.merge(
        gulp.src(config.app + 'content/**/*.{woff,woff2,svg,ttf,eot,otf}')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/fonts/'))
        .pipe(flatten())
        .pipe(rev())
        .pipe(gulp.dest(config.dist + 'content/fonts/'))
        .pipe(rev.manifest(config.revManifest, {
            base: config.dist,
            merge: true
        }))
        .pipe(gulp.dest(config.dist)),
        gulp.src([config.app + 'robots.txt', config.app + 'favicon.ico', config.app + '.htaccess'], { dot: true })
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist))
        .pipe(gulp.dest(config.dist))
    );
});

gulp.task('images', function () {
    return gulp.src(config.app + 'content/images/**')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.dist + 'content/images'))
        .pipe(imagemin({optimizationLevel: 5, progressive: true, interlaced: true}))
        .pipe(rev())
        .pipe(gulp.dest(config.dist + 'content/images'))
        .pipe(rev.manifest(config.revManifest, {
            base: config.dist,
            merge: true
        }))
        .pipe(gulp.dest(config.dist))
        .pipe(browserSync.reload({stream: true}));
});

gulp.task('sass', function () {
    return es.merge(
        gulp.src(config.sassSrc)
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(expect(config.sassSrc))
        .pipe(changed(config.cssDir, {extension: '.css'}))
        .pipe(sass({includePaths:config.bower}).on('error', sass.logError))
        .pipe(gulp.dest(config.cssDir)),
        gulp.src(config.bower + '**/fonts/**/*.{woff,woff2,svg,ttf,eot,otf}')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(changed(config.app + 'content/fonts'))
        .pipe(flatten())
        .pipe(gulp.dest(config.app + 'content/fonts'))
    );
});

gulp.task('styles', ['sass'], function () {
    return gulp.src(config.app + 'content/css')
        .pipe(browserSync.reload({stream: true}));
});

gulp.task('inject', function () {
    return gulp.src(config.app + 'index.html')
        .pipe(inject(gulp.src(config.app + 'app/**/*.js').pipe(angularFilesort()), {relative: true}))
        .pipe(gulp.dest(config.app));
});

gulp.task('wiredep', ['wiredep:test', 'wiredep:app']);

gulp.task('wiredep:app', function () {
    var stream = gulp.src(config.app + 'index.html')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(wiredep({
            exclude: [
                /angular-i18n/,  // localizations are loaded dynamically
                'bower_components/bootstrap-sass/assets/javascripts/' // Exclude Bootstrap js files as we use ui-bootstrap
            ]
        }))
        .pipe(gulp.dest(config.app));

    return es.merge(stream, gulp.src(config.sassSrc)
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(wiredep({
            ignorePath: /\.\.\/webapp\/bower_components\// // remove ../webapp/bower_components/ from paths of injected sass files
        }))
        .pipe(gulp.dest(config.scss)));
});

gulp.task('wiredep:test', function () {
    return gulp.src(config.test + 'karma.conf.js')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(wiredep({
            exclude: [
                /angular-i18n/,  // localizations are loaded dynamically
                /angular-scenario/,
                'bower_components/bootstrap-sass/assets/javascripts/' // Exclude Bootstrap js files as we use ui-bootstrap
            ],
            ignorePath: /\.\.\/\.\.\//, // remove ../../ from paths of injected JavaScript files
            devDependencies: true,
            fileTypes: {
                js: {
                    block: /(([\s\t]*)\/\/\s*bower:*(\S*))(\n|\r|.)*?(\/\/\s*endbower)/gi,
                    detect: {
                        js: /'(.*\.js)'/gi
                    },
                    replace: {
                        js: '\'src/{{filePath}}\','
                    }
                }
            }
        }))
        .pipe(gulp.dest(config.test));
});

gulp.task('assets:prod', ['images', 'styles', 'html'], build);

gulp.task('html', function () {
    return gulp.src(config.app + 'app/**/*.html')
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(templateCache({
            module: 'drugQualityDataManagerApp',
            root: 'app/',
            moduleSystem: 'IIFE'
        }))
        .pipe(gulp.dest(config.tmp));
});

gulp.task('ngconstant:dev', function () {
    return ngConstant({
        dest: 'app.constants.js',
        name: 'drugQualityDataManagerApp',
        deps: false,
        noFile: true,
        interpolate: /\{%=(.+?)%\}/g,
        wrap:
            '(function () {\n' +
            '    "use strict";\n' +
            '    // DO NOT EDIT THIS FILE, EDIT THE GULP TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE\n' +
            '    {%= __ngModule %}\n' +
            '})();\n',
        constants: {
            ENV: 'dev',
            VERSION: util.parseVersion()
        }
    })
    .pipe(gulp.dest(config.app + 'app/'));
});

gulp.task('ngconstant:prod', function () {
    return ngConstant({
        dest: 'app.constants.js',
        name: 'drugQualityDataManagerApp',
        deps: false,
        noFile: true,
        interpolate: /\{%=(.+?)%\}/g,
        wrap:
            '(function () {\n' +
            '    "use strict";\n' +
            '    // DO NOT EDIT THIS FILE, EDIT THE GULP TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE\n' +
            '    {%= __ngModule %}\n' +
            '})();\n',
        constants: {
            ENV: 'prod',
            VERSION: util.parseVersion()
        }
    })
    .pipe(gulp.dest(config.app + 'app/'));
});

// check app for eslint errors
gulp.task('eslint', function () {
    return gulp.src(['gulpfile.js', config.app + 'app/**/*.js'])
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failOnError());
});

// check app for eslint errors anf fix some of them
gulp.task('eslint:fix', function () {
    return gulp.src(config.app + 'app/**/*.js')
        .pipe(plumber({errorHandler: handleErrors}))
        .pipe(eslint({
            fix: true
        }))
        .pipe(eslint.format())
        .pipe(gulpIf(util.isLintFixed, gulp.dest(config.app + 'app')));
});

gulp.task('test', ['wiredep:test', 'ngconstant:dev'], function (done) {
    new KarmaServer({
        configFile: __dirname + '/' + config.test + 'karma.conf.js',
        singleRun: true
    }, done).start();
});

gulp.task('watch', function () {
    gulp.watch('bower.json', ['install']);
    gulp.watch(['gulpfile.js', 'pom.xml'], ['ngconstant:dev']);
    gulp.watch(config.sassSrc, ['styles']);
    gulp.watch(config.app + 'content/images/**', ['images']);
    gulp.watch(config.app + 'app/**/*.js', ['inject']);
    gulp.watch([config.app + '*.html', config.app + 'app/**', config.app + 'i18n/**']).on('change', browserSync.reload);
});

gulp.task('install', function () {
    runSequence(['wiredep', 'ngconstant:dev'], 'sass', 'inject');
});

gulp.task('serve', function () {
    runSequence('install', serve);
});

gulp.task('build', ['clean'], function (cb) {
    runSequence(['copy', 'wiredep:app', 'ngconstant:prod'], 'inject', 'assets:prod', cb);
});

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

There's not much I have been able to try, I've basically been toying around with the differences between this gulp configuration and the pre-upgrade one, to find not many differences at all, and when changing, finding no positive results.  I've also toyed around with the pom profile for deployment on server, no changes

Body:
So far, the only thing that lets the app build is to remove ngconstant calls from runSequence, leaving install, serve and build tasks like:

gulp.task('install', function () {
    runSequence(['wiredep'], 'sass', 'inject');
});

gulp.task('serve', function () {
    runSequence('install', serve);
});

gulp.task('build', ['clean'], function (cb) {
    runSequence(['copy', 'wiredep:app'], 'inject', 'assets:prod', cb);
});

Where they used to be like:

gulp.task('install', function () {
    runSequence(['wiredep', 'ngconstant:dev'], 'sass', 'inject');
});

gulp.task('serve', function () {
    runSequence('install', serve);
});

gulp.task('build', ['clean'], function (cb) {
    runSequence(['copy', 'wiredep:app', 'ngconstant:prod'], 'inject', 'assets:prod', cb);
});

This is far from an ideal workaround, but at least it keeps me on my feet, I would highly appreciate better recommendations for this


来源: stackexchange

问:
Symfony - findAll() returns ok if render, empty if response
I created a custom Bundle in my Symfony 2.7 website.
One of the entity works perfectly :

Entity class is Version.php

Custom repository is VersionRepository

The MainController.php of my bundle is :

```<code>$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

return $this->render('IpadUpdaterBundle:Version:index.html.twig', array(
'versions' => $versions
));
</code>```

Output in Twig is perfect :

My first version row

My second version row

BUT ... if I want to change the ouput and render a JSON response with the same datas, I make this change in the controller :

```<code>$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

$versions = json_encode($versions);
$rep_finale = new Response($versions);
$rep_finale->headers->set('Content-Type', 'application/json');
return $rep_finale;
</code>```

or :

```<code>$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

return new JsonResponse($versions);
</code>```

.. and the ouput becomes an empty array with 2 children :

[{},{}]

!I can not understand what's wrong and what changes I would implement to solve this issue. I already use "use Symfony\Component\HttpFoundation\Response" and "use Symfony\Component\HttpFoundation\JsonResponse" in the header of my controller.php.

Thanks for your help !

答:
json_encode and JSONResponse don't do well with complex entities, especially with links to other complex entities. Mostly, those are for encoding strings or arrays as JSON.

If you only need some of the information from your entities you can make an array and pass that.

```<code>$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versionInformation = $repository->getIdNameOfVersionsAsArray();
$versionInformation = array_column($versionInformation, 'id', 'name');

return new JSONResponse($versionInformation);
</code>```

You'll have to implement the getIdNameOfVersionsAsArray function in your repository to just return an array of values.

If you need every field of your version entity it may be easier to use a serializer. JMSSerializer Bundle is the most popular and well-supported.

```<code>$serializer = $this->container->get('serializer');
$versionJSON = $serializer->serialize($versions, 'json');

return new Response($versionJSON);
</code>```

And you'll have to implement annotations in your entities to tell the serializer what to do. See the link above for that.

ContentLicense: CC BY-SA 3.0

Body:
I created a custom Bundle in my Symfony 2.7 website.
One of the entity works perfectly :

Entity class is Version.php

Custom repository is VersionRepository

The MainController.php of my bundle is :

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

return $this->render('IpadUpdaterBundle:Version:index.html.twig', array(
'versions' => $versions
));

Output in Twig is perfect :

My first version row

My second version row

BUT ... if I want to change the ouput and render a JSON response with the same datas, I make this change in the controller :

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

$versions = json_encode($versions);
$rep_finale = new Response($versions);
$rep_finale->headers->set('Content-Type', 'application/json');
return $rep_finale;

or :

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versions = $repository->findAll();

return new JsonResponse($versions);

.. and the ouput becomes an empty array with 2 children :

[{},{}]

!I can not understand what's wrong and what changes I would implement to solve this issue. I already use "use Symfony\Component\HttpFoundation\Response" and "use Symfony\Component\HttpFoundation\JsonResponse" in the header of my controller.php.

Thanks for your help !

Body:
json_encode and JSONResponse don't do well with complex entities, especially with links to other complex entities. Mostly, those are for encoding strings or arrays as JSON.

If you only need some of the information from your entities you can make an array and pass that.

$repository  = $this->getDoctrine()->getManager()->getRepository('MyBundle:Version');
$versionInformation = $repository->getIdNameOfVersionsAsArray();
$versionInformation = array_column($versionInformation, 'id', 'name');

return new JSONResponse($versionInformation);

You'll have to implement the getIdNameOfVersionsAsArray function in your repository to just return an array of values.

If you need every field of your version entity it may be easier to use a serializer. JMSSerializer Bundle is the most popular and well-supported.

$serializer = $this->container->get('serializer');
$versionJSON = $serializer->serialize($versions, 'json');

return new Response($versionJSON);

And you'll have to implement annotations in your entities to tell the serializer what to do. See the link above for that.


问:
ASP.net using a form to insert data into an sql server table
Hi
in php i would do a form with an action to lets say a process.php page and in that page i would take the post values and using a mysql_query would do an insertion.
now i am lost ,i am trying to create a from and do an inserstion in ASP.net with sql server 2008 using visual studio 2010.

i have defined a sql db in the App_Data folder.
basicly what i need (unless there is a better way) is:

how do i get the post values.

how do i insert them into the db.

thanks.

答:
There are tons of sample code online as to how to do this.

Here is just one example of how to do this:
http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx

you define the text boxes between the following tag:

```<code><form id="form1" runat="server">
</code>```

you create your textboxes and define them to runat="server" like so:

```<code><asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
</code>```

define a button to process your logic like so (notice the onclick):

```<code><asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
</code>```

in the code behind, you define what you want the server to do if the user clicks on the button by defining a method named

```<code>protected void Button1_Click(object sender, EventArgs e)
</code>```

or you could just double click the button in the design view.

Here is a very quick sample of code to insert into a table in the button click event (codebehind)

```<code>protected void Button1_Click(object sender, EventArgs e)
{
   string name = TxtName.Text; // Scrub user data

   string connString = ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
   SqlConnection conn = null;
   try
   {
          conn = new SqlConnection(connString);
          conn.Open();

          using(SqlCommand cmd = new SqlCommand())
          {
                 cmd.Conn = conn;
                 cmd.CommandType = CommandType.Text;
                 cmd.CommandText = "INSERT INTO dummyTable(name) Values (@var)";
                 cmd.Parameters.AddWithValue("@var", name);
                 int rowsAffected = cmd.ExecuteNonQuery();
                 if(rowsAffected ==1)
                 {
                        //Success notification
                 }
                 else
                 {
                        //Error notification
                 }
          }
   }
   catch(Exception ex)
   {
          //log error
          //display friendly error to user
   }
   finally
   {
          if(conn!=null)
          {
                 //cleanup connection i.e close
          }
   }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
There are tons of sample code online as to how to do this.

Here is just one example of how to do this:
http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx

you define the text boxes between the following tag:

<form id="form1" runat="server">

you create your textboxes and define them to runat="server" like so:

<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>

define a button to process your logic like so (notice the onclick):

<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />

in the code behind, you define what you want the server to do if the user clicks on the button by defining a method named

protected void Button1_Click(object sender, EventArgs e)

or you could just double click the button in the design view.

Here is a very quick sample of code to insert into a table in the button click event (codebehind)

protected void Button1_Click(object sender, EventArgs e)
{
   string name = TxtName.Text; // Scrub user data

   string connString = ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
   SqlConnection conn = null;
   try
   {
          conn = new SqlConnection(connString);
          conn.Open();

          using(SqlCommand cmd = new SqlCommand())
          {
                 cmd.Conn = conn;
                 cmd.CommandType = CommandType.Text;
                 cmd.CommandText = "INSERT INTO dummyTable(name) Values (@var)";
                 cmd.Parameters.AddWithValue("@var", name);
                 int rowsAffected = cmd.ExecuteNonQuery();
                 if(rowsAffected ==1)
                 {
                        //Success notification
                 }
                 else
                 {
                        //Error notification
                 }
          }
   }
   catch(Exception ex)
   {
          //log error
          //display friendly error to user
   }
   finally
   {
          if(conn!=null)
          {
                 //cleanup connection i.e close
          }
   }
}


问:
How to remove/delete last character from printed list in python
I am creating simple program which finds the smallest multiplicators of a number (not sure if this is the right term). However, I can not find a way to delete last "*" from the listed result. What am I doing wrong? Please help.

```<code>num = int(input("write number: "))
print(num, end = "=")
div = 2
while num > 1:
    if num % div == 0:
        num = num / div
        print(div, end = "*")
    else:
        div += 1
</code>```

Result I got:

```<code>24=2*2*2*3*
</code>```

Result I want:

```<code>24=2*2*2*3
</code>```

I tried to use sep="" instead of end="", tried \b, [:-1] but this does not work or I am just doing it wrong.
Thank you.

答:
You can create a list of divisors and then print the concatenated list.

```<code>num = int(input("write number: "))
print(num, end = "=")
div = 2
out = []
while num > 1:
    if num % div == 0:
        num = num / div
        out.append(div)
    else:
        div += 1
print('*'.join(map(str,out)))
</code>```

Test:

```<code>write number: 24
24=2*2*2*3
</code>```

Body:
I am creating simple program which finds the smallest multiplicators of a number (not sure if this is the right term). However, I can not find a way to delete last "*" from the listed result. What am I doing wrong? Please help.

num = int(input("write number: "))
print(num, end = "=")
div = 2
while num > 1:
    if num % div == 0:
        num = num / div
        print(div, end = "*")
    else:
        div += 1

Result I got:

24=2*2*2*3*

Result I want:

24=2*2*2*3

I tried to use sep="" instead of end="", tried \b, [:-1] but this does not work or I am just doing it wrong.
Thank you.

Body:
You can create a list of divisors and then print the concatenated list.

num = int(input("write number: "))
print(num, end = "=")
div = 2
out = []
while num > 1:
    if num % div == 0:
        num = num / div
        out.append(div)
    else:
        div += 1
print('*'.join(map(str,out)))

Test:

write number: 24
24=2*2*2*3


问:
Materialize Button only works when clicked some parts
Hello I have created a button with Materialize, but it only works for some areas of the button (primarily the area that surrounds the text). Any reason for this?

In my form all I do is add another input like this:

```<code><input name="mySubmit" type="submit" value="Log In!" class="waves-effect waves-light btn" />
</code>```

But when I click on the button only the boxed area actually recognizes it as input:

Thanks in advance for your help!

答:
It seems that Materialize wraps the input tag in an "i" tag, which is then rendered into a button-looking element, with clickability limited to the text portion.

I was able to solve this by simply transforming my input tag into a button tag.

Initial code:

```<code><input type="submit" value="List Employees" id="fetch-employees"
class="waves-effect waves-light btn">
</code>```

What is then rendered in the browser:

```<code><i class="waves-effect waves-light btn waves-input-wrapper" style="">
    <input type="submit" value="List Employees" id="fetch-employees"
    class="waves-button-input">
</i>
</code>```

Solution:

```<code><button type="submit" value="List Employees" id="fetch-employees"
class="waves-effect waves-light btn">List Employees</button>
</code>```

Body:
Hello I have created a button with Materialize, but it only works for some areas of the button (primarily the area that surrounds the text). Any reason for this?

In my form all I do is add another input like this:

<input name="mySubmit" type="submit" value="Log In!" class="waves-effect waves-light btn" />

But when I click on the button only the boxed area actually recognizes it as input:

Thanks in advance for your help!

Body:
It seems that Materialize wraps the input tag in an "i" tag, which is then rendered into a button-looking element, with clickability limited to the text portion.

I was able to solve this by simply transforming my input tag into a button tag.

Initial code:

<input type="submit" value="List Employees" id="fetch-employees"
class="waves-effect waves-light btn">

What is then rendered in the browser:

<i class="waves-effect waves-light btn waves-input-wrapper" style="">
    <input type="submit" value="List Employees" id="fetch-employees"
    class="waves-button-input">
</i>

Solution:

<button type="submit" value="List Employees" id="fetch-employees"
class="waves-effect waves-light btn">List Employees</button>


问:
Batch - Execute Macros from command line
I have a macro done by LibreOffice Calc it's a french version of OpenOffice.
This macro opens a csv file without the dialog box. But I'd like to execute it via Batch.

The ideia is, use system() commmand in matlab to run this macro.

This macro is in addressed as  Importcsv.ods --> Standard --> Module1 --> CSVOpen
How should I put the complete address of the file, and where put the name of the csv file I want to open?

Many thanks,

Bruno

PS: I'd forgot something. I want to run this in Calc and there, do anything I want. Because this file will be sabed in  xls to be used in SolidWorks (CAD software).

答:
```<code>"c:\Program Files (x86)\OpenOffice 4\program\swriter.exe" -invisible "macro:///Standard.Module1.Main"
</code>```

or from another source

```<code>"c:\Program Files (x86)\OpenOffice 4\program\swriter.exe" -nologo -norestore -nolockcheck "macro:///Standard.Module1.Main"
</code>```

Body:
"c:\Program Files (x86)\OpenOffice 4\program\swriter.exe" -invisible "macro:///Standard.Module1.Main"

or from another source

"c:\Program Files (x86)\OpenOffice 4\program\swriter.exe" -nologo -norestore -nolockcheck "macro:///Standard.Module1.Main"


问:
Filter results after date SQL Server
I need to filter my query to extract the results between 25th of the previous month and 25th of the current month. The SP receives a date as parameter, which I am using to extract the current month.I tried to make some casting but I can't figure how to deal with the January month when the last month has a different year(there must be a more efficient way also)</p>

```<code>@Date smalldatetime --received as parameter
select *
from mytable
where mytable.mydate between '25/'+cast(MONTH(@date)-1 as varchar(2))+'/'+cast(YEAR(@date) as varchar(4)) and '25/'+cast(MONTH(@date) as varchar(2))+'/'+cast(YEAR(@date) as varchar(4))
</code>```

答:
I would just do:

```<code>select t.*
from t
where mydate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 25)) and
      mydate < datefromparts(year(getdate()), month(getdate()), 25)
</code>```

I would use datefromparts() rather than trying to construct a date string for this purpose.

Title: Filter results after date SQL Server

Body:
I need to filter my query to extract the results between 25th of the previous month and 25th of the current month. The SP receives a date as parameter, which I am using to extract the current month.I tried to make some casting but I can't figure how to deal with the January month when the last month has a different year(there must be a more efficient way also)

@Date smalldatetime --received as parameter
select *
from mytable
where mytable.mydate between '25/'+cast(MONTH(@date)-1 as varchar(2))+'/'+cast(YEAR(@date) as varchar(4)) and '25/'+cast(MONTH(@date) as varchar(2))+'/'+cast(YEAR(@date) as varchar(4))

Body:
I would just do:

select t.*
from t
where mydate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 25)) and
      mydate < datefromparts(year(getdate()), month(getdate()), 25)

I would use datefromparts() rather than trying to construct a date string for this purpose.


问:
Python: Removing a specific item that has a duplicate only knowing its index in a list
What I want this program to do is to delete all the 1's that are in the list that follow by index all the 2's.

This is the code:

```<code>a = [3, 1, 2, 1]
a.remove(a[3])
print(a)
</code>```

I really put this program into the basics but the point is that I have only got the index of the 1 that follows the 2, tho when I do this the result is:

```<code>[3, 2, 1]
</code>```

This means that it doesn't delete the 1 I want but just the first 1 it finds. Tho this is really a problem in a real program situation where the first 1 is an important value.

How can I fix it? Thanks

答:
I would use a good-ol' explicit loop for this one:

```<code>a = [3, 1, 2, 1]
b = [a[0]]

for i, item in enumerate(a[1:], 1):
  if item == 1 and a[i-1] == 2:
    continue
  else:
    b.append(item)
print(b)  # -> [3, 1, 2]
</code>```

Note that a does not get modified but rather a new list b is created.

Body:
What I want this program to do is to delete all the 1's that are in the list that follow by index all the 2's.

This is the code:

a = [3, 1, 2, 1]
a.remove(a[3])
print(a)

I really put this program into the basics but the point is that I have only got the index of the 1 that follows the 2, tho when I do this the result is:

[3, 2, 1]

This means that it doesn't delete the 1 I want but just the first 1 it finds. Tho this is really a problem in a real program situation where the first 1 is an important value.

How can I fix it? Thanks

Body:
I would use a good-ol' explicit loop for this one:

a = [3, 1, 2, 1]
b = [a[0]]

for i, item in enumerate(a[1:], 1):
  if item == 1 and a[i-1] == 2:
    continue
  else:
    b.append(item)
print(b)  # -> [3, 1, 2]

Note that a does not get modified but rather a new list b is created.


问:
Python. Replace elements using slice
I need to implement Sieve of Eratosthenes algorithm.
I have list:

bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]

I need to replace each odd element with "0".
Now I have code:

```<code>while viewIndex < maxNumber:
    bar[viewIndex] = 0
    viewIndex += 2
</code>```

But I remember about slices. And for me it will be nice to write something like this:

```<code>bar[currentIndex::2] = 0
</code>```

But I have error:

```<code>TypeError: must assign iterable to extended slice
</code>```

Maybe you know a beautiful solution to this task.

答:
Thank to all for answers. My implementation of Sieve of Eatosthenes algorithm:</p>

```<code>def resheto(data):
     print("\tStart Resheto")
     currentIndex = 0

     while currentIndex < len(data) - 1:
         data[currentIndex + data[currentIndex]::data[currentIndex]] = \
             [0] * ((len(data) + 1) // data[currentIndex] - 1)
         currentIndex += 1

         while currentIndex < len(data) - 1 and data[currentIndex] == 0:
             currentIndex += 1

         if currentIndex >= len(data) - 1:
             break
print("\tEnd Resheto") return data
</code>```

Title: Python. Replace elements using slice

Body:
I need to implement Sieve of Eratosthenes algorithm.
I have list:

bar = [2, 3, 4, 5, 6, 7, 8, 9, 10]

I need to replace each odd element with "0".
Now I have code:

while viewIndex < maxNumber:
    bar[viewIndex] = 0
    viewIndex += 2

But I remember about slices. And for me it will be nice to write something like this:

bar[currentIndex::2] = 0

But I have error:

TypeError: must assign iterable to extended slice

Maybe you know a beautiful solution to this task.

Body:
Thank to all for answers. My implementation of Sieve of Eatosthenes algorithm:

def resheto(data):
     print("\tStart Resheto")
     currentIndex = 0

     while currentIndex < len(data) - 1:
         data[currentIndex + data[currentIndex]::data[currentIndex]] = \
             [0] * ((len(data) + 1) // data[currentIndex] - 1)
         currentIndex += 1

         while currentIndex < len(data) - 1 and data[currentIndex] == 0:
             currentIndex += 1

         if currentIndex >= len(data) - 1:
             break
print("\tEnd Resheto") return data


问:
How i cannot ignore 0(zero) as a grade?
```<code>int main(){

    char students_number[30], students_grade[30];
    char *number, *value;
    int flag=0, students, i, grade, a=0, b=0, c=0, d=0, f=0;
    float sum=0;

    while(flag==0) // This while loop exist just because to run program until the number of students will be given correct..
    {

        printf("Please enter the number of students (It must be between 1-100): ");
        scanf("%s",&students_number); //  This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
        students = strtol(students_number, &number, 10); // strtol is a function of stdlib.h and checks the variable is whether int or not for this program..

        if(students<=100 && students>0)
        {
            for(i=1;i<=students;i++)
            {
                printf("Please enter %d. student's grade (in integer form):",i);
                scanf("%s",&students_grade);//  This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
                grade = strtol(students_grade, &value, 10); // This line checks the grade which was given is integer or not by using strtol which is in the stdlib.h..

                if(grade<0 || grade>100 || grade=='\0')
                {
                    printf("The grade of the student was given incorrect!\n");
                    i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..
                }
                else
                {
                    if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
                        f++;
                    else if(grade<=60 && grade>=51)
                        d++;
                    else if(grade<=73 && grade>=61)
                        c++;
                    else if(grade<=85 && grade>=74)
                        b++;
                    else if(grade<=100 && grade>=86)
                        a++;
                    sum += grade;
                }
            }
            sum /= students; // This command divides the sum of the grades to number of the students to get the average results in the class..

            printf("\nThe average result of the class is %.2f..\n",sum);
            printf("\nThe letter form of the all results are:\nNumber of F: %d\nNumber of D: %d\nNumber of C: %d\nNumber of B: %d\nNumber of A: %d\n",f,d,c,b,a);
            flag = 1; // As it was mentioned before, this commands exist to break the while loop because the program was done successfully..
        }
        else // This if command controls the number of students wheter was given right or not..
        {
            printf("Please enter a proper number of students.\n");
            flag = 0;
        }
    }
    return 0;
}
</code>```

Hello, this is my first question. I had to create a program which calculates the average of the results. But when i enter 0(zero) as a grade then it doesn't allow it just because i tried to exclude the every types except int type.

How can i make this correct?

答:
You can use scanf to read a number and check that scanf done correctly its work:

from man scanf:

Return Value
  These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

So you can check that you've read an integer with scanf, without writing if (value == '\0'), which prevents you to read 0 grades...

```<code>for(i=1;i<=students;i++)
{
    int ok;

    printf("Please enter %d. student's grade (in integer form):",i);

    /* read line from input. Why using fgets instead of scanf directly? See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html*/
    if (NULL == fgets(students_grade, sizeof students_grade, stdin))
    {
         perror("fgets");
         exit(1);
    }

    /* **try** to parse what have been read */
    ok = sscanf(students_grade, "%d", &value);

    /* check that scanf has done its work */
    if (1 != ok)
    {
        printf("The grade of the student was given incorrect!\n");
            i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..

    }
    else
    {
        if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
        f++;
        /* ... */
    }
</code>```

I also advice you to read this article: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html.

Title: How i cannot ignore 0(zero) as a grade?

Body:
int main(){

    char students_number[30], students_grade[30];
    char *number, *value;
    int flag=0, students, i, grade, a=0, b=0, c=0, d=0, f=0;
    float sum=0;

    while(flag==0) // This while loop exist just because to run program until the number of students will be given correct..
    {

        printf("Please enter the number of students (It must be between 1-100): ");
        scanf("%s",&students_number); //  This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
        students = strtol(students_number, &number, 10); // strtol is a function of stdlib.h and checks the variable is whether int or not for this program..

        if(students<=100 && students>0)
        {
            for(i=1;i<=students;i++)
            {
                printf("Please enter %d. student's grade (in integer form):",i);
                scanf("%s",&students_grade);//  This scanf gets the number of students as an array instead of integer because the number which was given needs to be checked..
                grade = strtol(students_grade, &value, 10); // This line checks the grade which was given is integer or not by using strtol which is in the stdlib.h..

                if(grade<0 || grade>100 || grade=='\0')
                {
                    printf("The grade of the student was given incorrect!\n");
                    i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..
                }
                else
                {
                    if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
                        f++;
                    else if(grade<=60 && grade>=51)
                        d++;
                    else if(grade<=73 && grade>=61)
                        c++;
                    else if(grade<=85 && grade>=74)
                        b++;
                    else if(grade<=100 && grade>=86)
                        a++;
                    sum += grade;
                }
            }
            sum /= students; // This command divides the sum of the grades to number of the students to get the average results in the class..

            printf("\nThe average result of the class is %.2f..\n",sum);
            printf("\nThe letter form of the all results are:\nNumber of F: %d\nNumber of D: %d\nNumber of C: %d\nNumber of B: %d\nNumber of A: %d\n",f,d,c,b,a);
            flag = 1; // As it was mentioned before, this commands exist to break the while loop because the program was done successfully..
        }
        else // This if command controls the number of students wheter was given right or not..
        {
            printf("Please enter a proper number of students.\n");
            flag = 0;
        }
    }
    return 0;
}

Hello, this is my first question. I had to create a program which calculates the average of the results. But when i enter 0(zero) as a grade then it doesn't allow it just because i tried to exclude the every types except int type.

How can i make this correct?

Body:
You can use scanf to read a number and check that scanf done correctly its work:

from man scanf:

Return Value
  These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

So you can check that you've read an integer with scanf, without writing if (value == '\0'), which prevents you to read 0 grades...

for(i=1;i<=students;i++)
{
    int ok;

    printf("Please enter %d. student's grade (in integer form):",i);

    /* read line from input. Why using fgets instead of scanf directly? See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html*/
    if (NULL == fgets(students_grade, sizeof students_grade, stdin))
    {
         perror("fgets");
         exit(1);
    }

    /* **try** to parse what have been read */
    ok = sscanf(students_grade, "%d", &value);

    /* check that scanf has done its work */
    if (1 != ok)
    {
        printf("The grade of the student was given incorrect!\n");
            i--; // To make the for loop which is on the 25th line work again until the grade will be given correct..

    }
    else
    {
        if(grade<=50 && grade>=0) // This if and else if commands work for to count how many f,d,c,b and a are exist..
        f++;
        /* ... */
    }

I also advice you to read this article: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html.


问:
LINQ statement with multiple Join is very slow
I have a LINQ statement to an Oracle DB with multiple JOINS that is taking a very long time to process (>30 seconds).  When I view the outputted SQL it looks very strange and contains many subqueries.  I am thinking I need to optimize this statement somehow but I am not quite sure.

```<code>  var WRs = (from c in db.WR_CONTACT
      join wr in db.WORK_REQUEST on c.WR_NO equals wr.WR_NO
      join z in db.TASKS on wr.WR_NO equals z.WR_NO
      join p in db.PEOPLE on z.RESPONSIBLE_PERSON_NO equals p.PERSON_NO
         where p.USERID == key && (z.WR_TASK_NO == 1 || z.WR_TASK_NO == 2)
            && wr.WR_CANCEL_DATE == null
            && wr.ACCOUNTING_CLOSE_DATE == null
      select c);
</code>```

I have also tried the OUTER JOIN approach and that did not significantly improve the performance.  The only thing I can think to do is break this off and create a new SQL view.

答: We ended up creating a SQL view and linking entity to that view.  Not the best solution but it was the best option for our timeline.</p>

Body:
I have a LINQ statement to an Oracle DB with multiple JOINS that is taking a very long time to process (>30 seconds).  When I view the outputted SQL it looks very strange and contains many subqueries.  I am thinking I need to optimize this statement somehow but I am not quite sure.

  var WRs = (from c in db.WR_CONTACT
      join wr in db.WORK_REQUEST on c.WR_NO equals wr.WR_NO
      join z in db.TASKS on wr.WR_NO equals z.WR_NO
      join p in db.PEOPLE on z.RESPONSIBLE_PERSON_NO equals p.PERSON_NO
         where p.USERID == key && (z.WR_TASK_NO == 1 || z.WR_TASK_NO == 2)
            && wr.WR_CANCEL_DATE == null
            && wr.ACCOUNTING_CLOSE_DATE == null
      select c);

I have also tried the OUTER JOIN approach and that did not significantly improve the performance.  The only thing I can think to do is break this off and create a new SQL view.


问:
Log4j Validating if Exception is passed as last argument
I am using slf4j with log4j. My POM dependency looks like below -

```<code><dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
</code>```

As mentioned in SLF4J FAQ

The SLF4J API supports parametrization in the presence of an
  exception, assuming the exception is the last parameter.

In a is there a way to identify if exception is passed as a last argument to all logger's method call (like error, info)?

答:
There is no simple way to do this kind of check at compile time, or even at runtime.

You can however use a combination of FindBugs and the findbugs-slf4j plugin to check this statically with SLF4J_PLACE_HOLDER_MISMATCH and SLF4J_FORMAT_SHOULD_BE_CONST.

Body:
I am using slf4j with log4j. My POM dependency looks like below -

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

As mentioned in SLF4J FAQ

The SLF4J API supports parametrization in the presence of an
  exception, assuming the exception is the last parameter.

In a is there a way to identify if exception is passed as a last argument to all logger's method call (like error, info)?


问:
httpd: Could not reliably determine the server's fully qualified domain name
I know this question's been looked at a lot, but the solutions here aren't solving them.

Let's start with a bit of background info:

OS X 10.8.4
Apache 2.2.22

The problem:
I get this error in the console and Apache can't find my localhost, but does start ok. Weird.

```<code>[Sat Aug 17 13:40:06 2013] [info] mod_ssl/2.2.22 compiled against Server: Apache/2.2.22, Library: OpenSSL/0.9.8r
httpd: Could not reliably determine the server's fully qualified domain name, using Specter.local for ServerName
</code>```

So normally this would point to my ServerName not being set right. Well it is :/ and I've tried with different variants like Specter.local, localhost, etc

Here's a copy of my /private/etc/httpd.conf & this is the same for /private/etc/apache2/httpd.conf

```<code># ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
ServerName localhost
</code>```

My host file is setup as follows:

```<code>127.0.0.1   localhost localhost.local
255.255.255.255 broadcasthost
127.0.0.1       themill.dev
127.0.0.1       phpmyadmin.dev
127.0.0.1       Specter.local
</code>```

In my /private/etc/apache2/users/ta.conf is the following

```<code>#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# DEV: THEMILL SITE
<VirtualHost *:80>
  ServerAdmin test@dummy.com
  DocumentRoot "/Users/ta/Sites/themill/htdocs"
  ServerName themill.dev
  ServerAlias *.themill.dev
  ErrorLog "/Users/ta/Sites/themill/log/error_log"
  CustomLog "/Users/ta/Sites/themill/log/access_log" common
</VirtualHost>

# PHPMYADMIN
<VirtualHost *:80>
  ServerAdmin test@dummy.com
  DocumentRoot "/Users/ta/Sites/phpmyadmin"
  ServerName phpmyadmin.dev
  ServerAlias *.phpmyadmin.dev
  ErrorLog "/Users/ta/Sites/phpmyadmin/log/error_log"
  CustomLog "/Users/ta/Sites/phpmyadmin/log/access_log" common
</VirtualHost>
</code>```

Not sure what else should be configured really. It used to work but post the 10.7 upgrade, it's never worked and now that I'm trying to solve it it's doing my head in.

Let me know if you need more info.

答:
The following line in your httpd.conf file is correct:

```<code>ServerName localhost
</code>```

The problem is that on macOS it is the wrong file (not /private/etc/httpd.conf).

To find the right location of your httpd.conf Apache configuration file, run:

```<code>apachectl -t -D DUMP_INCLUDES
</code>```

then double check whether ServerName is uncommented and set to localhost.

Body:
I know this question's been looked at a lot, but the solutions here aren't solving them.

Let's start with a bit of background info:

OS X 10.8.4
Apache 2.2.22

The problem:
I get this error in the console and Apache can't find my localhost, but does start ok. Weird.

[Sat Aug 17 13:40:06 2013] [info] mod_ssl/2.2.22 compiled against Server: Apache/2.2.22, Library: OpenSSL/0.9.8r
httpd: Could not reliably determine the server's fully qualified domain name, using Specter.local for ServerName

So normally this would point to my ServerName not being set right. Well it is :/ and I've tried with different variants like Specter.local, localhost, etc

Here's a copy of my /private/etc/httpd.conf & this is the same for /private/etc/apache2/httpd.conf

# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
ServerName localhost

My host file is setup as follows:

127.0.0.1   localhost localhost.local
255.255.255.255 broadcasthost
127.0.0.1       themill.dev
127.0.0.1       phpmyadmin.dev
127.0.0.1       Specter.local

In my /private/etc/apache2/users/ta.conf is the following

#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# DEV: THEMILL SITE
<VirtualHost *:80>
  ServerAdmin test@dummy.com
  DocumentRoot "/Users/ta/Sites/themill/htdocs"
  ServerName themill.dev
  ServerAlias *.themill.dev
  ErrorLog "/Users/ta/Sites/themill/log/error_log"
  CustomLog "/Users/ta/Sites/themill/log/access_log" common
</VirtualHost>

# PHPMYADMIN
<VirtualHost *:80>
  ServerAdmin test@dummy.com
  DocumentRoot "/Users/ta/Sites/phpmyadmin"
  ServerName phpmyadmin.dev
  ServerAlias *.phpmyadmin.dev
  ErrorLog "/Users/ta/Sites/phpmyadmin/log/error_log"
  CustomLog "/Users/ta/Sites/phpmyadmin/log/access_log" common
</VirtualHost>

Not sure what else should be configured really. It used to work but post the 10.7 upgrade, it's never worked and now that I'm trying to solve it it's doing my head in.

Let me know if you need more info.

Body:
The following line in your httpd.conf file is correct:

ServerName localhost

The problem is that on macOS it is the wrong file (not /private/etc/httpd.conf).

To find the right location of your httpd.conf Apache configuration file, run:

apachectl -t -D DUMP_INCLUDES

then double check whether ServerName is uncommented and set to localhost.


问:
A regex to remove all words which contains number in R
I want to write a regex in R to remove all words of a string containing numbers.

For example:

```<code>first_text = "a2c if3 clean 001mn10 string asw21"
second_text = "clean string
</code>```

答:
A bit longer than some of the answers but very tractable is to first convert the string to a vector of words, then check word by word if there are any numbers and use standard R subsetting.

```<code>first_text_vec <- strsplit(first_text, " ")[[1]]
first_text_vec
[1] "a2c"     "if3"     "clean"   "001mn10" "string"  "asw21"
paste(first_text_vec[!grepl("[0-9]", first_text_vec)], collapse = " ")
[1] "clean string"
</code>```

Body:
I want to write a regex in R to remove all words of a string containing numbers.

For example:

first_text = "a2c if3 clean 001mn10 string asw21"
second_text = "clean string

Body:
A bit longer than some of the answers but very tractable is to first convert the string to a vector of words, then check word by word if there are any numbers and use standard R subsetting.

first_text_vec <- strsplit(first_text, " ")[[1]]
first_text_vec
[1] "a2c"     "if3"     "clean"   "001mn10" "string"  "asw21"
paste(first_text_vec[!grepl("[0-9]", first_text_vec)], collapse = " ")
[1] "clean string"


问:
Automatic session expired in google chrome
I am storing login user information into session at login time
with below code :

```<code>Session["LoginUserId"] = txtUserName.Text;
</code>```

When I am running an application in google chrome my session will be automatically null after a few minutes, but for Mozila Firefox and internet explorer it is working Fine.

And I have set expire time for seesionState but it is also not working.

So, Please suggest me what can I do?

答:
Store session table instead of browser Session and check session and expired time every time of login and user activity.

You can manage session by increase logout/expire time, it will help you to increase session time.

Body:
I am storing login user information into session at login time
with below code :

Session["LoginUserId"] = txtUserName.Text;

When I am running an application in google chrome my session will be automatically null after a few minutes, but for Mozila Firefox and internet explorer it is working Fine.

And I have set expire time for seesionState but it is also not working.

So, Please suggest me what can I do?


问:
Kafka Producer error Expiring 10 record(s) for TOPIC:XXXXXX: 6686 ms has passed since batch creation plus linger time
Kafka Version : 0.10.2.1,</p>
```<code>Kafka Producer error Expiring 10 record(s) for TOPIC:XXXXXX: 6686 ms has passed since batch creation plus linger time
org.apache.kafka.common.errors.TimeoutException: Expiring 10 record(s) for TOPIC:XXXXXX: 6686 ms has passed since batch creation plus linger time
</code>```

答:
This exception is occuring because you are queueing records at a much faster rate than they can be sent.

When you call the send method, the ProducerRecord will be stored in an internal buffer for sending to the broker. The method returns immediately once the ProducerRecord has been buffered, regardless of whether it has been sent.

Records are grouped into batches for sending to the broker, to reduce the transport overheard per message and increase throughput.

Once a record is added into a batch, there is a time limit for sending that batch to ensure that it has been sent within a specified duration. This is controlled by the Producer configuration parameter, request.timeout.ms, which defaults to 30 seconds. See related answer

If the batch has been queued longer than the timeout limit, the exception will be thrown. Records in that batch will be removed from the send queue.

Producer configs block.on.buffer.full, metadata.fetch.timeout.ms and timeout.ms have been removed. They were initially deprecated in Kafka 0.9.0.0.

Therefore give a try for increasing request.timeout.ms

Still, if you have any problem related to throughput, you can also refer following blog

ContentLicense: CC BY-SA 4.0

Body:
Kafka Version : 0.10.2.1,

Kafka Producer error Expiring 10 record(s) for TOPIC:XXXXXX: 6686 ms has passed since batch creation plus linger time
org.apache.kafka.common.errors.TimeoutException: Expiring 10 record(s) for TOPIC:XXXXXX: 6686 ms has passed since batch creation plus linger time


问:
How do you remove the x-axis from a bar chart produced by Google's Visualization API?
Referring to the kind of chart shown here:
http://code.google.com/apis/visualization/documentation/gallery/barchart.html

There doesn't seem to be a simple switch, and changing the axis color to white (on a white background) didn't seem to do anything. I even tried jquery to hide the selectors produced by the api output but no dice.

答: let options = {legend: { position: 'none' }};

OwnerDisplayName: Dan


问:
MATLAB odd 'Too many input arguments' error
For a project, I'm trying to use matlab to call a function in another .m file. However, it says 'Not enough input arguments', even though I do pass what I am fairly certain is enough input arguments.

In eval_square.m:

```<code>function f = eval_square(x)

%   fitness function of the magic square
%
%   Parameters
%   ----------
%       x : array, the solution vector that represents a magic square.
%           By default, the solution vector is converted to a magic square
%           columnwisely.
%   Output
%   ----------
%       f : double, the error value of the input solution vector.
%           the mean squared error (MSE) of all each row, column and
%           diagonal sum to the magic constant is computed
%

n = sqrt(length(x));

%More stuff, but error occurs at this line.
</code>```

in MYNAME_sa.m:

```<code>function [xopt, fopt] = MYNAME_sa(dim, eval_budget, fitness_func)

%Stuff

if dim == 2
    len = 12^2;    % length of the solution vector, shoud be 12^2
                 % when dim == 2
elseif dim == 3
    len = 7^3;    % length of the solution vector, shoud be 7^3 when
                 % dim == 3
end

%Stuff

s = randperm(len)
f = fitness_func(s)

%More stuff.
</code>```

It's supposed to evaluate the random permutation of length 12^2 as a magic square, to see how close it is to optimum (i.e. how close it is to being an actual magic square) and in theory the same for a magic cube (eval_cube), but the same error occurs.

The error in question:

```<code>>> MYNAME_sa(2, 10000, eval_square)
Error using eval_square (line 18)
Not enough input arguments.

Note that line 18 is n = sqrt(length(x));
</code>```

It doesn't matter if I hardcode eval_square into the function - it seems to understand that I want to call eval_square just fine, but it just doesn't pass s or something? And I don't understand why. I tried hardcoding n to 12 as well, but that doesn't work either, the error pops up when I'm trying to actually use x then. Changing fitness_func to @fitness_func also changes nothing.
So my question is, why does this happen and how do I fix it?

答:
Try with </p>

```<code>MYNAME_sa(2, 10000, @eval_square)
</code>```

Body:
For a project, I'm trying to use matlab to call a function in another .m file. However, it says 'Not enough input arguments', even though I do pass what I am fairly certain is enough input arguments.

In eval_square.m:

function f = eval_square(x)

%   fitness function of the magic square
%
%   Parameters
%   ----------
%       x : array, the solution vector that represents a magic square.
%           By default, the solution vector is converted to a magic square
%           columnwisely.
%   Output
%   ----------
%       f : double, the error value of the input solution vector.
%           the mean squared error (MSE) of all each row, column and
%           diagonal sum to the magic constant is computed
%

n = sqrt(length(x));

%More stuff, but error occurs at this line.

in MYNAME_sa.m:

function [xopt, fopt] = MYNAME_sa(dim, eval_budget, fitness_func)

%Stuff

if dim == 2
    len = 12^2;    % length of the solution vector, shoud be 12^2
                 % when dim == 2
elseif dim == 3
    len = 7^3;    % length of the solution vector, shoud be 7^3 when
                 % dim == 3
end

%Stuff

s = randperm(len)
f = fitness_func(s)

%More stuff.

It's supposed to evaluate the random permutation of length 12^2 as a magic square, to see how close it is to optimum (i.e. how close it is to being an actual magic square) and in theory the same for a magic cube (eval_cube), but the same error occurs.

The error in question:

>> MYNAME_sa(2, 10000, eval_square)
Error using eval_square (line 18)
Not enough input arguments.

Note that line 18 is n = sqrt(length(x));

It doesn't matter if I hardcode eval_square into the function - it seems to understand that I want to call eval_square just fine, but it just doesn't pass s or something? And I don't understand why. I tried hardcoding n to 12 as well, but that doesn't work either, the error pops up when I'm trying to actually use x then. Changing fitness_func to @fitness_func also changes nothing.
So my question is, why does this happen and how do I fix it?

Body:
Try with

MYNAME_sa(2, 10000, @eval_square)


问:
CustomValidator doesnt display a message unless I use a validation summary
I want to output a message in case if an invalid date was supplied.

```<code><asp:TextBox ID="RegistrationFromTextBox2" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="RegistrationFromTextBox2" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="NewMailingItem" runat="server" ErrorMessage="The date is invalid"></asp:CustomValidator>

      protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        try
        {
            DateTime temp;
            if (DateTime.TryParse(args.Value, out temp))
            {
                args.IsValid =true;
            }
            else
            {
                args.IsValid = false;
            }

        }

        catch (Exception ex)
        {

            args.IsValid = false;

        }
    }
</code>```

I expect the output message to be located near the field.

Instead I get no response, even though the function works. I only get the error message if I put a validation summary to my form.

Is there away display the message without the validation summary?

答:
Is there away display the message without the validation summary?

You will need to use Text attribute instead of ErrorMessage.

```<code><asp:CustomValidator ID="CustomValidator1"
   ControlToValidate="RegistrationFromTextBox2"
   OnServerValidate="CustomValidator1_ServerValidate"
   ValidationGroup="NewMailingItem"
   runat="server"
   Text="The date is invalid">
</asp:CustomValidator>
</code>```

FYI: If you just want to validate date, you could use CompareValidator or Ajax Control Toolkit's Calendar control.

```<code><asp:TextBox ID="RegistrationFromTextBox2" runat="server"
    placeholder="MM/DD/YYYY">
</asp:TextBox>
<asp:CompareValidator
    ID="RegistrationFromCompareValidator" runat="server"
    Type="Date"
    Operator="DataTypeCheck"
    ControlToValidate="RegistrationFromTextBox2"
    Text="The date is invalid">
</asp:CompareValidator>
</code>```

Body:
I want to output a message in case if an invalid date was supplied.

<asp:TextBox ID="RegistrationFromTextBox2" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="RegistrationFromTextBox2" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="NewMailingItem" runat="server" ErrorMessage="The date is invalid"></asp:CustomValidator>

      protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        try
        {
            DateTime temp;
            if (DateTime.TryParse(args.Value, out temp))
            {
                args.IsValid =true;
            }
            else
            {
                args.IsValid = false;
            }

        }

        catch (Exception ex)
        {

            args.IsValid = false;

        }
    }

I expect the output message to be located near the field.

Instead I get no response, even though the function works. I only get the error message if I put a validation summary to my form.

Is there away display the message without the validation summary?

Body:
Is there away display the message without the validation summary?

You will need to use Text attribute instead of ErrorMessage.

<asp:CustomValidator ID="CustomValidator1"
   ControlToValidate="RegistrationFromTextBox2"
   OnServerValidate="CustomValidator1_ServerValidate"
   ValidationGroup="NewMailingItem"
   runat="server"
   Text="The date is invalid">
</asp:CustomValidator>

FYI: If you just want to validate date, you could use CompareValidator or Ajax Control Toolkit's Calendar control.

<asp:TextBox ID="RegistrationFromTextBox2" runat="server"
    placeholder="MM/DD/YYYY">
</asp:TextBox>
<asp:CompareValidator
    ID="RegistrationFromCompareValidator" runat="server"
    Type="Date"
    Operator="DataTypeCheck"
    ControlToValidate="RegistrationFromTextBox2"
    Text="The date is invalid">
</asp:CompareValidator>


问:
Replace multiple words in string
I have multiple words I want to replace with values, whats the best way to do this?

Example:
This is what I have done but it feels and looks so wrong

```<code>string s ="Dear <Name>, your booking is confirmed for the <EventDate>";
string s1 = s.Replace("<Name>", client.FullName);
string s2 =s1.Replace("<EventDate>", event.EventDate.ToString());

txtMessage.Text = s2;
</code>```

There has to be a better way?

thanks

答:
You could use String.Format.</p>

```<code>string.Format("Dear {0}, your booking is confirmed for the {1}",
   client.FullName, event.EventDate.ToString());
</code>```

Title: Replace multiple words in string

Body:
I have multiple words I want to replace with values, whats the best way to do this?

Example:
This is what I have done but it feels and looks so wrong

string s ="Dear <Name>, your booking is confirmed for the <EventDate>";
string s1 = s.Replace("<Name>", client.FullName);
string s2 =s1.Replace("<EventDate>", event.EventDate.ToString());

txtMessage.Text = s2;

There has to be a better way?

thanks

Body:
You could use String.Format.

string.Format("Dear {0}, your booking is confirmed for the {1}",
   client.FullName, event.EventDate.ToString());


问:
How to replace a part of a string with zeroes?
I need to replace part of a string with zeroes. To be more specific third to sixth position should be zeroes.

Example:

I have 123456789

I need 120000789

Any help would be appreciated!

Thanks.

答:
```<code>select rpad(substr('&str',1,2),6,'0')||substr('&str',7,3) from dual;
</code>```


问:
Variable was not declared in this class scope C++
I want to create class moneybox, that accepts adding to the sum coints with value 1,5 and 10 cents.

Here is my code:

```<code>#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;

class MoneyBox{
public:
    MoneyBox(int one_num = 0 ,int five_num = 0,int ten_num = 0);
    void print();
    MoneyBox add(int ones,int fives,int tens);

private:
    int sum;
    int one_num;
    int five_num;
    int ten_num;
};

MoneyBox::MoneyBox(int ones,int fives,int tens){
    sum = 1*ones + 5*fives + 10*tens;
    one_num = ones;
    five_num = fives;
    ten_num = tens;
}

void MoneyBox::print(){
    cout << one_num <<"*"<<"1Cent" << five_num <<"*"<<"5Cent" << ten_num <<"*"<<"10Cent" << "=" << sum;
}

MoneyBox MoneyBox::add(int ones,int fives,int tens){
    one_num += ones;
    five_num += fives;
    ten_num += tens;
    sum += 1 * ones + 5 * fives + 10*tens;
    return MoneyBox(one_num,five_num,ten_num);
}

int main(){
    MoneyBox m_1;
    MoneyBox m_2(five_num = 3);

    m_1.add(ones = 4, tens = 3);
    m_2.add(fives = 3, ones = 2);

    m_1.print();
    cout << "\n";
    m_2.print();

}
</code>```

But compiler throws me an error:

45:15: error: 'five_num' was not declared in this scope
47:10: error: 'ones' was not declared in this scope
47:20: error: 'tens' was not declared in this scope
48:10: error: 'fives' was not declared in this scope

Why it happends and how to fix it?

答:
You can't pass parameters by name in C++.

```<code>MoneyBox m_2(five_num = 3);
</code>```

needs to be written as

```<code>MoneyBox m_2(0/*required to pass explicitly*/, 3);
</code>```

and so on. five_num &c. are not declared at the calling site, hence the compiler diagnostic. C++ is a very powerful language, and with some clever coding you could effectively support named parameters to enable calling syntax such as

```<code>MoneyBox(Five(5), One(2), /*any number of parameters in any order*.)
</code>```

using variadic templates. Boost (www.boost.org) use this style a fair bit.

Body:
I want to create class moneybox, that accepts adding to the sum coints with value 1,5 and 10 cents.

Here is my code:

#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;

class MoneyBox{
public:
    MoneyBox(int one_num = 0 ,int five_num = 0,int ten_num = 0);
    void print();
    MoneyBox add(int ones,int fives,int tens);

private:
    int sum;
    int one_num;
    int five_num;
    int ten_num;
};

MoneyBox::MoneyBox(int ones,int fives,int tens){
    sum = 1*ones + 5*fives + 10*tens;
    one_num = ones;
    five_num = fives;
    ten_num = tens;
}

void MoneyBox::print(){
    cout << one_num <<"*"<<"1Cent" << five_num <<"*"<<"5Cent" << ten_num <<"*"<<"10Cent" << "=" << sum;
}

MoneyBox MoneyBox::add(int ones,int fives,int tens){
    one_num += ones;
    five_num += fives;
    ten_num += tens;
    sum += 1 * ones + 5 * fives + 10*tens;
    return MoneyBox(one_num,five_num,ten_num);
}

int main(){
    MoneyBox m_1;
    MoneyBox m_2(five_num = 3);

    m_1.add(ones = 4, tens = 3);
    m_2.add(fives = 3, ones = 2);

    m_1.print();
    cout << "\n";
    m_2.print();

}

But compiler throws me an error:

45:15: error: 'five_num' was not declared in this scope
47:10: error: 'ones' was not declared in this scope
47:20: error: 'tens' was not declared in this scope
48:10: error: 'fives' was not declared in this scope

Why it happends and how to fix it?

Body:
You can't pass parameters by name in C++.

MoneyBox m_2(five_num = 3);

needs to be written as

MoneyBox m_2(0/*required to pass explicitly*/, 3);

and so on. five_num &c. are not declared at the calling site, hence the compiler diagnostic. C++ is a very powerful language, and with some clever coding you could effectively support named parameters to enable calling syntax such as

MoneyBox(Five(5), One(2), /*any number of parameters in any order*.)

using variadic templates. Boost (www.boost.org) use this style a fair bit.