问:
What is wrong in this Query why i am getting this Error?
```<code> with cte as(
            Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
            Sum(Price) AS Amount
            FROM [sTMS 3].dbo.Orders
            INNER JOIN [sTMS 3].dbo.MenuItems ON [sTMS 3].dbo.Orders.MenuItemId = [sTMS 3].dbo.MenuItems.Id
            INNER JOIN [sTMS 3].dbo.Tickets TCK ON TCK.Id = [sTMS 3].dbo.Orders.TicketId
            INNER JOIN [sTMS 3].dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
            WHERE
            (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
            AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
            Group by MenuItemName
            Order by Amount Desc  UNION ALL
            Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
            Sum(Price) AS Amount
            FROM sTMS10.dbo.Orders
            INNER JOIN sTMS10.dbo.MenuItems ON sTMS10.dbo.Orders.MenuItemId = sTMS10.dbo.MenuItems.Id
            INNER JOIN sTMS10.dbo.Tickets TCK ON TCK.Id = sTMS10.dbo.Orders.TicketId
            INNER JOIN sTMS10.dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
            WHERE
            (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
            AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
            Group by MenuItemName
            Order by Amount Desc)
            Select top 5 Name,Sum(Quantity) AS Quantity,Sum(Amount)/``
            (Select SUM(Amount) FROM (Select top 5 Sum(e.Amount) Amount From cte e Group by e.Name order by e.Amount desc)a) * 100 AS Percentage,Sum(Amount) AS Amount
            ,CONVERT(DATETIME,'Jan  1 2017 12:00AM',101) FromDate
            ,CONVERT(DATETIME,'Mar  3 2017 12:00AM',101) ToDate
            From cte Group by Name order by Amount desc
</code>```

Column "cte.Amount" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

答:
You are just ordering by e.Amount instead of the aggregated column SUM(Amount) Amount in the forth row from the last:

```<code>with cte as(
        Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
        Sum(Price) AS Amount
        FROM [sTMS 3].dbo.Orders
        INNER JOIN [sTMS 3].dbo.MenuItems ON [sTMS 3].dbo.Orders.MenuItemId = [sTMS 3].dbo.MenuItems.Id
        INNER JOIN [sTMS 3].dbo.Tickets TCK ON TCK.Id = [sTMS 3].dbo.Orders.TicketId
        INNER JOIN [sTMS 3].dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
        WHERE
        (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
        AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
        Group by MenuItemName
        Order by Amount Desc  UNION ALL
        Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
        Sum(Price) AS Amount
        FROM sTMS10.dbo.Orders
        INNER JOIN sTMS10.dbo.MenuItems ON sTMS10.dbo.Orders.MenuItemId = sTMS10.dbo.MenuItems.Id
        INNER JOIN sTMS10.dbo.Tickets TCK ON TCK.Id = sTMS10.dbo.Orders.TicketId
        INNER JOIN sTMS10.dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
        WHERE
        (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
        AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
        Group by MenuItemName
        Order by Amount Desc)
        Select top 5 Name,Sum(Quantity) AS Quantity,Sum(Amount)/``
        (Select SUM(Amount) FROM (Select top 5 Sum(e.Amount) Amount From cte e Group by e.Name order by Amount desc)a) * 100 AS Percentage,Sum(Amount) AS Amount
        ,CONVERT(DATETIME,'Jan  1 2017 12:00AM',101) FromDate
        ,CONVERT(DATETIME,'Mar  3 2017 12:00AM',101) ToDate
        From cte Group by Name order by Amount desc
</code>```

Body:
 with cte as(
            Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
            Sum(Price) AS Amount
            FROM [sTMS 3].dbo.Orders
            INNER JOIN [sTMS 3].dbo.MenuItems ON [sTMS 3].dbo.Orders.MenuItemId = [sTMS 3].dbo.MenuItems.Id
            INNER JOIN [sTMS 3].dbo.Tickets TCK ON TCK.Id = [sTMS 3].dbo.Orders.TicketId
            INNER JOIN [sTMS 3].dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
            WHERE
            (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
            AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
            Group by MenuItemName
            Order by Amount Desc  UNION ALL
            Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
            Sum(Price) AS Amount
            FROM sTMS10.dbo.Orders
            INNER JOIN sTMS10.dbo.MenuItems ON sTMS10.dbo.Orders.MenuItemId = sTMS10.dbo.MenuItems.Id
            INNER JOIN sTMS10.dbo.Tickets TCK ON TCK.Id = sTMS10.dbo.Orders.TicketId
            INNER JOIN sTMS10.dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
            WHERE
            (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
            AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
            Group by MenuItemName
            Order by Amount Desc)
            Select top 5 Name,Sum(Quantity) AS Quantity,Sum(Amount)/``
            (Select SUM(Amount) FROM (Select top 5 Sum(e.Amount) Amount From cte e Group by e.Name order by e.Amount desc)a) * 100 AS Percentage,Sum(Amount) AS Amount
            ,CONVERT(DATETIME,'Jan  1 2017 12:00AM',101) FromDate
            ,CONVERT(DATETIME,'Mar  3 2017 12:00AM',101) ToDate
            From cte Group by Name order by Amount desc

Column "cte.Amount" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

Body:
You are just ordering by e.Amount instead of the aggregated column SUM(Amount) Amount in the forth row from the last:

with cte as(
        Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
        Sum(Price) AS Amount
        FROM [sTMS 3].dbo.Orders
        INNER JOIN [sTMS 3].dbo.MenuItems ON [sTMS 3].dbo.Orders.MenuItemId = [sTMS 3].dbo.MenuItems.Id
        INNER JOIN [sTMS 3].dbo.Tickets TCK ON TCK.Id = [sTMS 3].dbo.Orders.TicketId
        INNER JOIN [sTMS 3].dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
        WHERE
        (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
        AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
        Group by MenuItemName
        Order by Amount Desc  UNION ALL
        Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
        Sum(Price) AS Amount
        FROM sTMS10.dbo.Orders
        INNER JOIN sTMS10.dbo.MenuItems ON sTMS10.dbo.Orders.MenuItemId = sTMS10.dbo.MenuItems.Id
        INNER JOIN sTMS10.dbo.Tickets TCK ON TCK.Id = sTMS10.dbo.Orders.TicketId
        INNER JOIN sTMS10.dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
        WHERE
        (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
        AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
        AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
        Group by MenuItemName
        Order by Amount Desc)
        Select top 5 Name,Sum(Quantity) AS Quantity,Sum(Amount)/``
        (Select SUM(Amount) FROM (Select top 5 Sum(e.Amount) Amount From cte e Group by e.Name order by Amount desc)a) * 100 AS Percentage,Sum(Amount) AS Amount
        ,CONVERT(DATETIME,'Jan  1 2017 12:00AM',101) FromDate
        ,CONVERT(DATETIME,'Mar  3 2017 12:00AM',101) ToDate
        From cte Group by Name order by Amount desc


来源: stackexchange

问:
Omitting certain migration files in Flyway
There are certain migrations that insert a lot of data into our production database. They slow down the integration tests and are completely not needed during the testing phase. I'd rather not solve this by boilerplate conditionals in SQL.

Is there a way to apply profiles to Flyway scripts and omit chosen migrations when necessary?

答: You can split them out in a separate directory and configure flyway.locations to selectively include it.

ContentLicense: CC BY-SA 3.0


问:
How to fix this error: Grunt build not found, Use --force to continue
I am doing a project with Grunt. The project has 2 part: dev and build.
The dev part has no problem, but the build part got an error.

And I think I have a serious problem with my gruntfiles.js file.

Here is content of it:

```<code>module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    // define reusable paths
    paths: {
        app: 'app',
        dist: 'dist',
        app_css:'<%= paths.app %>/css',
        app_js:'<%= paths.app %>/js',
        app_img: '<%= paths.img %>/img'
        source_scss: '<%= paths.app %>/src/scss',
        source_js: '<%= paths.app %>/src/js',
        source_bower: '<%= paths.app %>/src/bower',
        dist_css: '<%= paths.dist %>/css',
        dist_js: '<%= paths.dist %>/js',
        dist_img: '<%= paths.dist %>/img'
    },

    sass: {
        dev: {
            options: {
                outputStyle: 'expanded',
                sourceMap: false
                     },

            files: {
                '<%= paths.app_css %>/styles.css': '<%= paths.source_scss %>/app.scss'
                   }
             },

        build: {
            options: {
                outputStyle: 'compressed',
                sourceMap: false
            },
            files: {
                '<%= paths.dist_css %>/styles.css': '<%= paths.app_scss %>/styles.scss'
                    }
                }
        },

    browserSync: {
        files: {
            src: ['<%= paths.app_css %>/*.css', '<%= paths.app_js %>/*.js', '<%= paths.app %>/*.html']
        },
        options: {
            browser: 'firefox',
            server: '<%= paths.app %>',
            watchTask: true
        }
    },

    watch: {
        sass: {
            files: ['<%= paths.source_scss %>/**/*.scss'],
            tasks: ['sass:dev', 'concat:css']
        },
        js: {
            files: ['<%= paths.source_js %>/*.js'],
            tasks: ['jshint', 'uglify:dev']
        }
    },

    jshint: {
        dev: {
            files: {
                src: '<%= paths.source_js %>/*.js'
            }
        },
        options: {
            reporter: require('jshint-stylish')
        }
    },

    bower: {
        dev: {
            dest: '<%= paths.source_bower %>',
            js_dest: '<%= paths.source_bower %>/js',
            css_dest: '<%= paths.source_bower %>/styles'
        }
    },

    copy: {

        html: {
            expand: true,
            cwd: '<%= paths.app %>',
            src: '*.html',
            dest: '<$= paths.dist $>/',
            options: {
                process: function(content, srcpath){
                    return content.replace('scripts.js', 'scripts.min.js')
                                                    }
                    }
               }

         },

    clean: {
        dist: {
            src: '<%= paths.dist %>/css'
            }
    },

    imagemin: {
        build: {
            files: [
                {
                    expand: true,
                    cwd: '<%= paths.app_img %>',
                    src: ['<%= **/*.{png,jpg,gif,svg,ico}'],
                    dest: '<%= paths.dist_img %>'
                }
                    ]
                }
            },

    concat: {
        css: {
            src: ['<%= paths.app_css %>/styles.css', '<%= paths.source_bower %>/styles/**/*.css'],
            dest: '<%= paths.app_css %>/styles.css'
        }
    },

    uglify: {
        dev: {
            options: {
                beautify: true,
                mangle: false,
                compress: false,
                preserveComments: 'all'
            },
            src: ['<%= paths.source_js %>/*.js', '<%= paths.source_bower %>/js/**/*.js'],
            dest: '<%= paths.app_js %>/scripts.js'
            },
        build: {
            src: ['<%= paths.source_js %>/*.js', '<%= paths.source_bower %>/js/**/*.js'],
            dest: '<%= paths.dist_js %>/scripts.min.js'
            }

    }

  });

  // Load the plugin that provides the "uglify" task.

  // Browser sync
  grunt.loadNpmTasks('grunt-browser-sync');

  // Sass
  grunt.loadNpmTasks('grunt-sass');

  // Contribu watch
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Jshint
  grunt.loadNpmTasks('grunt-contrib-jshint');

  // Bower
  grunt.loadNpmTasks('grunt-bower');

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-imagemin');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');

  //Creat tasks

  // Default task(s).
  grunt.registerTask('default', ['browserSync', 'watch']);
  grunt.registerTask('build', ['clean:dist', 'copy', 'imagemin', 'uglify:build', 'concat:css', 'sass:build']);

};
</code>```

And here is my package.json file:

```<code>{
  "name": "dev",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "grunt": "^1.0.1",
    "grunt-bower": "^0.21.4",
    "grunt-browser-sync": "^2.2.0",
    "grunt-contrib-clean": "^1.0.0",
    "grunt-contrib-concat": "^1.0.1",
    "grunt-contrib-copy": "^1.0.0",
    "grunt-contrib-imagemin": "^1.0.1",
    "grunt-contrib-jshint": "^1.1.0",
    "grunt-contrib-uglify": "^2.2.0",
    "grunt-contrib-watch": "^1.0.0",
    "grunt-sass": "^2.0.0",
    "jshint-stylish": "^2.2.1"
  }
}
</code>```

When run

```<code>grunt build
</code>```

I got this error:

```<code>   Loading "gruntfile.js" tasks...ERROR
   >> SyntaxError: Unexpected identifier
   Warning: Task "build" not found. Use --force to continue.
</code>```

My project files:

```<code>├── css
│   └── styles.css
├── img
│   └── Screenshot from 2017-03-31 22-23-33.png
├── index.html
├── js
│   └── scripts.js
├── src
│   ├── bower
│   │   ├── js
│   │   │   └── dist
│   │   │       └── jquery.js
│   │   └── styles
│   │       └── normalize.css
│   ├── js
│   │   └── scripts.js
│   └── scss
│       └── app.scss
└── terminal.glue
</code>```

Could you please help me to fix this problem!

Thank you so much!

答:
You seems missed a comma here:

// define reusable paths
    paths: {
        app: 'app',
        dist: 'dist',
        app_css:'<%= paths.app %>/css',
        app_js:'<%= paths.app %>/js',
        app_img: '<%= paths.img %>/img'   // <---------------------miss here
        source_scss: '<%= paths.app %>/src/scss',
        source_js: '<%= paths.app %>/src/js',
        source_bower: '<%= paths.app %>/src/bower',

try use jshint/jslint(etc.) to avoid problem like this with your editor or ide.

Body:
I am doing a project with Grunt. The project has 2 part: dev and build.
The dev part has no problem, but the build part got an error.

And I think I have a serious problem with my gruntfiles.js file.

Here is content of it:

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    // define reusable paths
    paths: {
        app: 'app',
        dist: 'dist',
        app_css:'<%= paths.app %>/css',
        app_js:'<%= paths.app %>/js',
        app_img: '<%= paths.img %>/img'
        source_scss: '<%= paths.app %>/src/scss',
        source_js: '<%= paths.app %>/src/js',
        source_bower: '<%= paths.app %>/src/bower',
        dist_css: '<%= paths.dist %>/css',
        dist_js: '<%= paths.dist %>/js',
        dist_img: '<%= paths.dist %>/img'
    },

    sass: {
        dev: {
            options: {
                outputStyle: 'expanded',
                sourceMap: false
                     },

            files: {
                '<%= paths.app_css %>/styles.css': '<%= paths.source_scss %>/app.scss'
                   }
             },

        build: {
            options: {
                outputStyle: 'compressed',
                sourceMap: false
            },
            files: {
                '<%= paths.dist_css %>/styles.css': '<%= paths.app_scss %>/styles.scss'
                    }
                }
        },

    browserSync: {
        files: {
            src: ['<%= paths.app_css %>/*.css', '<%= paths.app_js %>/*.js', '<%= paths.app %>/*.html']
        },
        options: {
            browser: 'firefox',
            server: '<%= paths.app %>',
            watchTask: true
        }
    },

    watch: {
        sass: {
            files: ['<%= paths.source_scss %>/**/*.scss'],
            tasks: ['sass:dev', 'concat:css']
        },
        js: {
            files: ['<%= paths.source_js %>/*.js'],
            tasks: ['jshint', 'uglify:dev']
        }
    },

    jshint: {
        dev: {
            files: {
                src: '<%= paths.source_js %>/*.js'
            }
        },
        options: {
            reporter: require('jshint-stylish')
        }
    },

    bower: {
        dev: {
            dest: '<%= paths.source_bower %>',
            js_dest: '<%= paths.source_bower %>/js',
            css_dest: '<%= paths.source_bower %>/styles'
        }
    },

    copy: {

        html: {
            expand: true,
            cwd: '<%= paths.app %>',
            src: '*.html',
            dest: '<$= paths.dist $>/',
            options: {
                process: function(content, srcpath){
                    return content.replace('scripts.js', 'scripts.min.js')
                                                    }
                    }
               }

         },

    clean: {
        dist: {
            src: '<%= paths.dist %>/css'
            }
    },

    imagemin: {
        build: {
            files: [
                {
                    expand: true,
                    cwd: '<%= paths.app_img %>',
                    src: ['<%= **/*.{png,jpg,gif,svg,ico}'],
                    dest: '<%= paths.dist_img %>'
                }
                    ]
                }
            },

    concat: {
        css: {
            src: ['<%= paths.app_css %>/styles.css', '<%= paths.source_bower %>/styles/**/*.css'],
            dest: '<%= paths.app_css %>/styles.css'
        }
    },

    uglify: {
        dev: {
            options: {
                beautify: true,
                mangle: false,
                compress: false,
                preserveComments: 'all'
            },
            src: ['<%= paths.source_js %>/*.js', '<%= paths.source_bower %>/js/**/*.js'],
            dest: '<%= paths.app_js %>/scripts.js'
            },
        build: {
            src: ['<%= paths.source_js %>/*.js', '<%= paths.source_bower %>/js/**/*.js'],
            dest: '<%= paths.dist_js %>/scripts.min.js'
            }

    }

  });

  // Load the plugin that provides the "uglify" task.

  // Browser sync
  grunt.loadNpmTasks('grunt-browser-sync');

  // Sass
  grunt.loadNpmTasks('grunt-sass');

  // Contribu watch
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Jshint
  grunt.loadNpmTasks('grunt-contrib-jshint');

  // Bower
  grunt.loadNpmTasks('grunt-bower');

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-imagemin');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');

  //Creat tasks

  // Default task(s).
  grunt.registerTask('default', ['browserSync', 'watch']);
  grunt.registerTask('build', ['clean:dist', 'copy', 'imagemin', 'uglify:build', 'concat:css', 'sass:build']);

};

And here is my package.json file:

{
  "name": "dev",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "grunt": "^1.0.1",
    "grunt-bower": "^0.21.4",
    "grunt-browser-sync": "^2.2.0",
    "grunt-contrib-clean": "^1.0.0",
    "grunt-contrib-concat": "^1.0.1",
    "grunt-contrib-copy": "^1.0.0",
    "grunt-contrib-imagemin": "^1.0.1",
    "grunt-contrib-jshint": "^1.1.0",
    "grunt-contrib-uglify": "^2.2.0",
    "grunt-contrib-watch": "^1.0.0",
    "grunt-sass": "^2.0.0",
    "jshint-stylish": "^2.2.1"
  }
}

When run

grunt build

I got this error:

   Loading "gruntfile.js" tasks...ERROR
   >> SyntaxError: Unexpected identifier
   Warning: Task "build" not found. Use --force to continue.

My project files:

├── css
│   └── styles.css
├── img
│   └── Screenshot from 2017-03-31 22-23-33.png
├── index.html
├── js
│   └── scripts.js
├── src
│   ├── bower
│   │   ├── js
│   │   │   └── dist
│   │   │       └── jquery.js
│   │   └── styles
│   │       └── normalize.css
│   ├── js
│   │   └── scripts.js
│   └── scss
│       └── app.scss
└── terminal.glue

Could you please help me to fix this problem!

Thank you so much!


问:
Regex getting subgoups
I have faced with the following issue:

```<code>change = "1,23 2,54 1,85 "
results = re.findall(r"((\d+),(\d+) )+((\d+),(\d+) )+", change)
print(results)
</code>```

Results are:

```<code>('2,54 ', '2', '54', '1,85 ', '1', '85')
</code>```

But I want something like this:

```<code>('1,23 ', '1', '23', '2,54 ', '2', '54', '1,85 ', '1', '85')
</code>```

I have not found any solutions unfortunately

答:
Your repetition of the regex group is redundant. You should simply use 1 and just do findall. I've used the itertools.chain but you could achieve it by simple list comprehension too.

```<code>change = "1,23 2,54 1,85 "
results = re.findall(r"((\d+),(\d+) )", change)
print(results)
# [('1,23 ', '1', '23'), ('2,54 ', '2', '54'), ('1,85 ', '1', '85')]
from itertools import chain
print(list(chain(*results)))
# ['1,23 ', '1', '23', '2,54 ', '2', '54', '1,85 ', '1', '85']
# simple list comprehension
print([single for group in results for single in group])
# ['1,23 ', '1', '23', '2,54 ', '2', '54', '1,85 ', '1', '85']
</code>```

Title: Regex getting subgoups

Body:
I have faced with the following issue:

change = "1,23 2,54 1,85 "
results = re.findall(r"((\d+),(\d+) )+((\d+),(\d+) )+", change)
print(results)

Results are:

('2,54 ', '2', '54', '1,85 ', '1', '85')

But I want something like this:

('1,23 ', '1', '23', '2,54 ', '2', '54', '1,85 ', '1', '85')

I have not found any solutions unfortunately

Body:
Your repetition of the regex group is redundant. You should simply use 1 and just do findall. I've used the itertools.chain but you could achieve it by simple list comprehension too.

change = "1,23 2,54 1,85 "
results = re.findall(r"((\d+),(\d+) )", change)
print(results)
# [('1,23 ', '1', '23'), ('2,54 ', '2', '54'), ('1,85 ', '1', '85')]
from itertools import chain
print(list(chain(*results)))
# ['1,23 ', '1', '23', '2,54 ', '2', '54', '1,85 ', '1', '85']
# simple list comprehension
print([single for group in results for single in group])
# ['1,23 ', '1', '23', '2,54 ', '2', '54', '1,85 ', '1', '85']


问:
Tooltips for high points on low-height charts not displaying
I have a problem with tooltips not showing depending on the size of the chart/browser window. This originally looked to me like a problem with facet charts but the behaviour is also evident on regular/single charts. I've done a lot of searching for this and not found anything so far. There is a similar post over on plotly forums with no answers as of yet.

Here is an MRE for a single chart (HT)...

```<code>require(ggplot2)
require(plotly)

randomName <- function(n) {
    random.string <- rep(NA, n)
    randomizeString <- function(x) {
        a <-sample(letters, 1, replace = TRUE)
        return(a)
    }
    return(paste(c(sapply(random.string, randomizeString, simplify = TRUE)), collapse = ""))
}

xvar = replicate(10, randomName(15))

df1 <- data.frame(x = xvar, y = xvar, z = runif(10) )

df1$tooltip <- sprintf("x: %s<br>y: %s<br>z: %s<br>2x: %s<br>2y: %s<br>2z: %s<br>3x: %s<br>3y: %s<br>3z: %s"
                                        ,df1$x, df1$y, df1$z, df1$x, df1$y, df1$z, df1$x, df1$y, df1$z)

g = ggplot(df1, aes(x,y,fill=z, text = tooltip)) +
        geom_tile()

ggplotly(g, tooltip = "tooltip")
</code>```

If you resize the browser window to a small enough height you will notice that the tooltip will not be displayed when hovering over the tiles near the top of the chart. The problem appears to be that the tooltip is too tall to display whereby the hover position would place the top of the tooltip box outside the top of the chart. This kind of makes sense even if problematic. However, this MRE example is a bit contrived and unrealistic.

This behaviour becomes a real issue on a facet chart with a large number of facets requiring tooltips. Here is an MRE for a facet chart. Even with a maximised browser window the same tooltip issue is evident.

```<code>require(ggplot2)
require(plotly)

randomName <- function(n) {
    random.string <- rep(NA, n)
    randomizeString <- function(x) {
        a <-sample(letters, 1, replace = TRUE)
        return(a)
    }
    return(paste(c(sapply(random.string, randomizeString, simplify = TRUE)), collapse = ""))
}

xvar = replicate(10, randomName(15))
facet_var = replicate(12, randomName(2))

df1 <- data.frame(x = xvar, y = xvar, z = runif(10) )
df1 <- merge(x = facet_var, y = df1, by = NULL)

#df1$tooltip <- sprintf("x: %s<br>y: %s<br>z: %s<br>x+x: %s<br>y+y: %s<br>z+z: %s"
df1$tooltip <- sprintf("facet: %s<br>x: %s<br>y: %s<br>z: %s<br>2x: %s<br>2y: %s<br>2z: %s<br>3x: %s<br>3y: %s<br>3z: %s"
                                        ,df1$x.x, df1$x.y, df1$y, df1$z, df1$x.y, df1$y, df1$z, df1$x.y, df1$y, df1$z)

g = ggplot(df1, aes(x.y,y,fill=z, text = tooltip)) +
        geom_tile() +
        facet_wrap(~x.x, ncol=2)

ggplotly(g, tooltip = "tooltip")
</code>```

This issue exists both for default and bespoke tooltips - tested in Chrome(v56) and Edge(v38).

I had an earlier question posted on SO regarding this issue but my analysis was off the mark, and my example not an MRE, and I have closed/answered that question since.

I could reduce the number of lines in the tooltip to obviate the problem but I'd prefer not to have to do that. Is this a known feature or is there a workaround for this behaviour?

答:
One possibility/workaround would be to set hovermode to 'y', i.e. change the last line of your example to:

```<code>gp <- ggplotly(g, tooltip = "tooltip")
gp[['x']][['layout']][['hovermode']]='y'
</code>```

Reduced window size in RStudio for your first example

Part of the fullscreen for your second example.

Body:
I have a problem with tooltips not showing depending on the size of the chart/browser window. This originally looked to me like a problem with facet charts but the behaviour is also evident on regular/single charts. I've done a lot of searching for this and not found anything so far. There is a similar post over on plotly forums with no answers as of yet.

Here is an MRE for a single chart (HT)...

require(ggplot2)
require(plotly)

randomName <- function(n) {
    random.string <- rep(NA, n)
    randomizeString <- function(x) {
        a <-sample(letters, 1, replace = TRUE)
        return(a)
    }
    return(paste(c(sapply(random.string, randomizeString, simplify = TRUE)), collapse = ""))
}

xvar = replicate(10, randomName(15))

df1 <- data.frame(x = xvar, y = xvar, z = runif(10) )

df1$tooltip <- sprintf("x: %s
y: %s
z: %s
2x: %s
2y: %s
2z: %s
3x: %s
3y: %s
3z: %s"
                                        ,df1$x, df1$y, df1$z, df1$x, df1$y, df1$z, df1$x, df1$y, df1$z)

g = ggplot(df1, aes(x,y,fill=z, text = tooltip)) +
        geom_tile()

ggplotly(g, tooltip = "tooltip")

If you resize the browser window to a small enough height you will notice that the tooltip will not be displayed when hovering over the tiles near the top of the chart. The problem appears to be that the tooltip is too tall to display whereby the hover position would place the top of the tooltip box outside the top of the chart. This kind of makes sense even if problematic. However, this MRE example is a bit contrived and unrealistic.

This behaviour becomes a real issue on a facet chart with a large number of facets requiring tooltips. Here is an MRE for a facet chart. Even with a maximised browser window the same tooltip issue is evident.

require(ggplot2)
require(plotly)

randomName <- function(n) {
    random.string <- rep(NA, n)
    randomizeString <- function(x) {
        a <-sample(letters, 1, replace = TRUE)
        return(a)
    }
    return(paste(c(sapply(random.string, randomizeString, simplify = TRUE)), collapse = ""))
}

xvar = replicate(10, randomName(15))
facet_var = replicate(12, randomName(2))

df1 <- data.frame(x = xvar, y = xvar, z = runif(10) )
df1 <- merge(x = facet_var, y = df1, by = NULL)

#df1$tooltip <- sprintf("x: %s
y: %s
z: %s
x+x: %s
y+y: %s
z+z: %s"
df1$tooltip <- sprintf("facet: %s
x: %s
y: %s
z: %s
2x: %s
2y: %s
2z: %s
3x: %s
3y: %s
3z: %s"
                                        ,df1$x.x, df1$x.y, df1$y, df1$z, df1$x.y, df1$y, df1$z, df1$x.y, df1$y, df1$z)

g = ggplot(df1, aes(x.y,y,fill=z, text = tooltip)) +
        geom_tile() +
        facet_wrap(~x.x, ncol=2)

ggplotly(g, tooltip = "tooltip")

This issue exists both for default and bespoke tooltips - tested in Chrome(v56) and Edge(v38).

I had an earlier question posted on SO regarding this issue but my analysis was off the mark, and my example not an MRE, and I have closed/answered that question since.

I could reduce the number of lines in the tooltip to obviate the problem but I'd prefer not to have to do that. Is this a known feature or is there a workaround for this behaviour?

Body:
One possibility/workaround would be to set hovermode to 'y', i.e. change the last line of your example to:

gp <- ggplotly(g, tooltip = "tooltip")
gp[['x']][['layout']][['hovermode']]='y'

Reduced window size in RStudio for your first example

Part of the fullscreen for your second example.


问:
Database which can remove records automatically by checking date column
Suppose there is a database which contains a table that has date and events column, there are total 10 records now I want that the records which are older then the current date should automatically be deleted and the present date records should be present in the database so as the future records should also be present, does anyone know something like this or can help me how to achieve this. any references would be helpful. I am open to php, phpmyadmin, sql. Any help would be appreciated.</p>

答: First it's too broad. You can consider using MySQL Event Scheduler for this purpose. Which you can set to run on every 24 hours and delete all records less than NOW()


问:
Can SVN show information relating to a partial checkout?
If a Subversion working copy is a partial check-out from a repository, using --depth and/or --set-depth (perhaps with exclude), is there a way to reveal the nodes that are 'missing' (either recursively, or non-recursively)? I don't mean missing in the sense of svn status and ! where a node was checked out but deleted locally without telling SVN. Rather, I mean a node in the repository that was not been checked out from the repository originally, or has been excluded later.

svn info can be used to show the depth of a node.

ls or dir might be compared with svn ls. (ls -r BASE doesn't bahave as I'd expect to get a working copy listing.)

svnversion will indicate that the WC is partial with a 'P'.

(There seems to be no --dry-run option to use in conjunction with --set-depth for svn update. Likewise svn diff -rBASE:HEAD --depth=immediates does not produce the information I seek either.)

Is there some direct method? It would be nice to have a list of 'eligible' nodes available for checkout or update.

Thanks.

答:
May be I misunderstand but

```<code>svn update
</code>```

has an --set-depth option so you could change an existing working copy to a new level.

ContentLicense: CC BY-SA 2.5

Body:
May be I misunderstand but

svn update

has an --set-depth option so you could change an existing working copy to a new level.


问:
deleting and creating new RTP streams after event loop started
I'm using Live555 to stream 1 or more video streams. Following the example of testH264VideoStreamer.cpp, various objects are created, and then an event loop is started. Here's an excerpt from my initialization code that handles creation of objects for a single video stream:

```<code>// Setup usage environment
this->scheduler = BasicTaskScheduler::createNew();
this->env = BasicUsageEnvironment::createNew(*scheduler);

// Setup framed source
this->framedSource = H264FramedSource::createNew(*this->env, 0, 0);
this->discreteFramer = H264VideoStreamDiscreteFramer::createNew(*env, framedSource);

// Setup sockets
this->rtpGroupsock = new Groupsock(
        *this->env,
        this->destinationAddress,
        this->rtpPort,
        this->ttl);

this->rtcpGroupsock = new Groupsock(
        *this->env,
        this->destinationAddress,
        this->rtcpPort,
        this->ttl);

this->videoSink = H264VideoRTPSink::createNew(
        *this->env,
        this->rtpGroupsock,
        DEF_RTP_PT);

this->rtcp = RTCPInstance::createNew(
        *this->env,
        this->rtcpGroupsock,
        DEF_SESSION_BW,
        cname,
        videoSink,
        0,                   // We are a server
        True);               // We are an SSM source
// Create RTSP server
this->rtspServer = RTSPServer::createNew(*this->env, rtsp_port);
this->sms = ServerMediaSession::createNew(
        *this->env, "test",
        ip.c_str(),
        0,
        True);
this->sms->addSubsession(PassiveServerMediaSubsession::createNew(
        *this->videoSink,
        this->rtcp));
this->rtspServer->addServerMediaSession(this->sms);
this->videoSink->startPlaying(*this->discreteFramer, 0, this->videoSink);
this->env->taskScheduler().doEventLoop();
</code>```

So my question is: suppose I wanted my environment/scheduler to handle events for a 2nd video stream, or I wanted to delete the existing stream. I see that I can add an argument to doEventLoop() to allow the event loop to exit. Then I can clean up an old stream, start new streams, and restart the event loop.  Is it possible to do these operations once the event loop has already been started? Would stopping and restarting the stream interrupt existing sessions? (and thus I should use a different thread its own scheduler/env for each video stream?)

答:
When the event loop is running you can do actions in almost 2 different ways :

using a trigger from an other thread

using a scheduled task

Using trigger from an other thread

Implement an event callback to do the work

```<code> static void eventCallback(void* clientData) {
  ....
 }
</code>```

Register your event callback:

int triggerId = this->scheduler->createEventTrigger(eventCallback);

Call the trigger when you need :

this->scheduler->triggerEvent(m_eventTriggerId, this);

Using a scheduled task

Create a Task callback

```<code>static void TaskCallback(void* clientData) {
  ...
}
</code>```

Schedule it before running the eventloop:

this->scheduler->scheduleDelayedTask(1000000, TaskCallback, this);

In static callbacks you can redirect to your class instance using the clientData that contains the this pointer.

Body:
I'm using Live555 to stream 1 or more video streams. Following the example of testH264VideoStreamer.cpp, various objects are created, and then an event loop is started. Here's an excerpt from my initialization code that handles creation of objects for a single video stream:

// Setup usage environment
this->scheduler = BasicTaskScheduler::createNew();
this->env = BasicUsageEnvironment::createNew(*scheduler);

// Setup framed source
this->framedSource = H264FramedSource::createNew(*this->env, 0, 0);
this->discreteFramer = H264VideoStreamDiscreteFramer::createNew(*env, framedSource);

// Setup sockets
this->rtpGroupsock = new Groupsock(
        *this->env,
        this->destinationAddress,
        this->rtpPort,
        this->ttl);

this->rtcpGroupsock = new Groupsock(
        *this->env,
        this->destinationAddress,
        this->rtcpPort,
        this->ttl);

this->videoSink = H264VideoRTPSink::createNew(
        *this->env,
        this->rtpGroupsock,
        DEF_RTP_PT);

this->rtcp = RTCPInstance::createNew(
        *this->env,
        this->rtcpGroupsock,
        DEF_SESSION_BW,
        cname,
        videoSink,
        0,                   // We are a server
        True);               // We are an SSM source
// Create RTSP server
this->rtspServer = RTSPServer::createNew(*this->env, rtsp_port);
this->sms = ServerMediaSession::createNew(
        *this->env, "test",
        ip.c_str(),
        0,
        True);
this->sms->addSubsession(PassiveServerMediaSubsession::createNew(
        *this->videoSink,
        this->rtcp));
this->rtspServer->addServerMediaSession(this->sms);
this->videoSink->startPlaying(*this->discreteFramer, 0, this->videoSink);
this->env->taskScheduler().doEventLoop();

So my question is: suppose I wanted my environment/scheduler to handle events for a 2nd video stream, or I wanted to delete the existing stream. I see that I can add an argument to doEventLoop() to allow the event loop to exit. Then I can clean up an old stream, start new streams, and restart the event loop.  Is it possible to do these operations once the event loop has already been started? Would stopping and restarting the stream interrupt existing sessions? (and thus I should use a different thread its own scheduler/env for each video stream?)

Body:
When the event loop is running you can do actions in almost 2 different ways :

using a trigger from an other thread

using a scheduled task

Using trigger from an other thread

Implement an event callback to do the work

 static void eventCallback(void* clientData) {
  ....
 }

Register your event callback:

int triggerId = this->scheduler->createEventTrigger(eventCallback);

Call the trigger when you need :

this->scheduler->triggerEvent(m_eventTriggerId, this);

Using a scheduled task

Create a Task callback

static void TaskCallback(void* clientData) {
  ...
}

Schedule it before running the eventloop:

this->scheduler->scheduleDelayedTask(1000000, TaskCallback, this);

In static callbacks you can redirect to your class instance using the clientData that contains the this pointer.


Title: Regex getting subgoups

Body:
Use the following approach:

change = "1,23 2,54 1,85 "
results = [n for t in re.findall(r"((\d+),(\d+))", change) for n in t]
print(results)

The output:

['1,23', '1', '23', '2,54', '2', '54', '1,85', '1', '85']


问:
In Java, what is the order of initialization for those statements after main method
I learned that the principle for order of initialization is:

Superclass first (not discussed here in this case)

Static variable declarations and static initialization blocks in the order of appearance

Instance variable declarations and static initialization blocks in the order of appearance

The constructor

But I'm still confused by the output of this code:

```<code>public class Test1 {

    static {
        add(2);
    }

    static void add (int num) {
        System.out.println(num + " ");
    }

    public Test1() {
        add(5);
        System.out.println("Constructor!");
    }

    static {
        add(4);
    }

    {
        add(6);
    }

    static {
        new Test1();
    }

    {
        add(8);
    }

    public static void main(String[] args) {
        System.out.println("Main method!");
        add(10);
    }

    {
        add(11);
    }
    static {
        add(12);
    }
}
</code>```

The result is:

```<code>2
4
6
8
11
5
Constructor!
12
Main method!
10
</code>```

If without the statements of add(10); add(11); add(12); I can totally understand. Can you please explain the order of initialization for those 3 statements?

答:
In Java, for one class all static initializers are executed in order (top to bottom of a class) before all constructors. The terms within {} are add to the constructor, these are not static initializers (see http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html).

So instance 1 of Test1 :

```<code>static {
    add(2);
}
...
static {
    add(4);
}
</code>```

Then, there is a constructor of Test1 inside a static block. It is called, so the instance member are initialized because previous static initializers have been called :

```<code>{
    add(6);
}
...
{
    add(8);
}
...
{
    add(11);
}
</code>```

After, the next operation in the constructor is called :

```<code>add(5);
</code>```

Then we return in the first instance to have the last static initiazer to be called :

```<code>static {
    add(12);
}
</code>```

Finally, the class if fully initialized, so main method is called :

```<code>public static void main(String[] args) {
    System.out.println("Main method!");
    add(10);
}
</code>```

So, output :

```<code>2
4
6
8
11
5
Constructor!
12
Main method!
10
</code>```

Body:
I learned that the principle for order of initialization is:

Superclass first (not discussed here in this case)

Static variable declarations and static initialization blocks in the order of appearance

Instance variable declarations and static initialization blocks in the order of appearance

The constructor

But I'm still confused by the output of this code:

public class Test1 {

    static {
        add(2);
    }

    static void add (int num) {
        System.out.println(num + " ");
    }

    public Test1() {
        add(5);
        System.out.println("Constructor!");
    }

    static {
        add(4);
    }

    {
        add(6);
    }

    static {
        new Test1();
    }

    {
        add(8);
    }

    public static void main(String[] args) {
        System.out.println("Main method!");
        add(10);
    }

    {
        add(11);
    }
    static {
        add(12);
    }
}

The result is:

2
4
6
8
11
5
Constructor!
12
Main method!
10

If without the statements of add(10); add(11); add(12); I can totally understand. Can you please explain the order of initialization for those 3 statements?

Body:
In Java, for one class all static initializers are executed in order (top to bottom of a class) before all constructors. The terms within {} are add to the constructor, these are not static initializers (see http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html).

So instance 1 of Test1 :

static {
    add(2);
}
...
static {
    add(4);
}

Then, there is a constructor of Test1 inside a static block. It is called, so the instance member are initialized because previous static initializers have been called :

{
    add(6);
}
...
{
    add(8);
}
...
{
    add(11);
}

After, the next operation in the constructor is called :

add(5);

Then we return in the first instance to have the last static initiazer to be called :

static {
    add(12);
}

Finally, the class if fully initialized, so main method is called :

public static void main(String[] args) {
    System.out.println("Main method!");
    add(10);
}

So, output :

2
4
6
8
11
5
Constructor!
12
Main method!
10


问:
Display canvas as gif for video preview
I'm working on a website and I am dealing with videos.

My need is to display a gif a a preview / teaser for the videos on another page, that redirects to the video.

What I found & added so far

HTML

```<code><div id=thumbs></div>
</code>```

CSS

```<code>#video {width:320px}
</code>```

JS

```<code>var i =0;
var video = document.createElement("video");
var thumbs = document.getElementById("thumbs");

video.addEventListener('loadeddata', function() {
    thumbs.innerHTML = "";
    video.currentTime = i;
}, false);

video.addEventListener('seeked', function() {
    var j = video.duration;
    var u = j/4;
    // now video has seeked and current frames will show
    // at the time as we expect
    generateThumbnail(i);

    // when frame is captured, increase
    i+=u;

    // if we are not passed end, seek to next interval
    if (i <= video.duration) {
        // this will trigger another seeked event
        video.currentTime = i;
    }
}, false);

video.preload = "auto";
video.src = "https://www.html5rocks.com/en/tutorials/video/basics/devstories.webm";

function generateThumbnail() {
  var c = document.createElement("canvas");
  var ctx = c.getContext("2d");
  c.width = 160;
  c.height = 90;
  ctx.drawImage(video, 0, 0, 160, 90);
  thumbs.appendChild(c);
  thumbs.replaceChild(c, thumbs.childNodes[0]);
}
</code>```

What I do is I get a video from its Url and I get 5 frames at equal timing. It gives me canvas and I'd like to display them as a gif or a succession of images.

答:
Since you only want to display it, instead of trying to generate a gif, the easiest way is probably to do the animation yourself.

You already have the code to fetch the video frames, but you are currently showing it in the DOM, and forget about it once displayed.

What you can do from this, is to store these frames, directly as canvas, and draw all these canvases on a final, visible canvas, in a timed loop.

var thumbsList = []; // we will save our frames as canvas in here
var delay = 500; // the speed of the animation (ms)

function generateThumbnail() {
  var c = document.createElement("canvas");
  var ctx = c.getContext("2d");
  c.width = 160;
  c.height = 90;
  ctx.drawImage(video, 0, 0, 160, 90);
  thumbsList.push(c); // store this frame in our list
  if (thumbsList.length === 1) {
    displayThumbs(); // start animating as soon as we got a frame
  }
}
// initialises the display canvas, and starts the animation loop
function displayThumbs() {
  var c = document.createElement("canvas");
  var ctx = c.getContext("2d");
  c.width = 160;
  c.height = 90;
  thumbs.appendChild(c);
  startAnim(ctx); // pass our visible canvas' context
}

function startAnim(ctx) {

  var currentFrame = 0;
  // here is the actual loop
  function anim() {
    ctx.drawImage(thumbsList[currentFrame], 0, 0); // draw the currentFrame
    // increase our counter, and set it to 0 if too large
    currentFrame = (currentFrame + 1) % thumbsList.length;
    setTimeout(anim, delay); // do it again in x ms
  }
  anim(); // let's go !
}
var i = 0;
var video = document.createElement("video");
var thumbs = document.getElementById("thumbs");

/* OP's code */
video.addEventListener('loadeddata', function() {
  thumbs.innerHTML = "";
  video.currentTime = i;
}, false);

video.addEventListener('seeked', function() {
  var j = video.duration;
  var u = j / 4;
  // now video has seeked and current frames will show
  // at the time as we expect
  generateThumbnail(i);
  // when frame is captured, increase
  i += u;

  // if we are not passed end, seek to next interval
  if (i <= video.duration) {
    // this will trigger another seeked event
    video.currentTime = i;
  } else {
    //      displayFrame(); // wait for all images to be parsed before animating
  }
}, false);

video.preload = "auto";
video.src = "https://www.html5rocks.com/en/tutorials/video/basics/devstories.webm";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id=thumbs></div></code>```

Title: Display canvas as gif for video preview

Body:
I'm working on a website and I am dealing with videos.

My need is to display a gif a a preview / teaser for the videos on another page, that redirects to the video.

What I found & added so far

HTML

CSS

#video {width:320px}

JS

var i =0;
var video = document.createElement("video");
var thumbs = document.getElementById("thumbs");

video.addEventListener('loadeddata', function() {
    thumbs.innerHTML = "";
    video.currentTime = i;
}, false);

video.addEventListener('seeked', function() {
    var j = video.duration;
    var u = j/4;
    // now video has seeked and current frames will show
    // at the time as we expect
    generateThumbnail(i);

    // when frame is captured, increase
    i+=u;

    // if we are not passed end, seek to next interval
    if (i <= video.duration) {
        // this will trigger another seeked event
        video.currentTime = i;
    }
}, false);

video.preload = "auto";
video.src = "https://www.html5rocks.com/en/tutorials/video/basics/devstories.webm";

function generateThumbnail() {
  var c = document.createElement("canvas");
  var ctx = c.getContext("2d");
  c.width = 160;
  c.height = 90;
  ctx.drawImage(video, 0, 0, 160, 90);
  thumbs.appendChild(c);
  thumbs.replaceChild(c, thumbs.childNodes[0]);
}

What I do is I get a video from its Url and I get 5 frames at equal timing. It gives me canvas and I'd like to display them as a gif or a succession of images.

Body:
Since you only want to display it, instead of trying to generate a gif, the easiest way is probably to do the animation yourself.

You already have the code to fetch the video frames, but you are currently showing it in the DOM, and forget about it once displayed.

What you can do from this, is to store these frames, directly as canvas, and draw all these canvases on a final, visible canvas, in a timed loop.

var thumbsList = []; // we will save our frames as canvas in here
var delay = 500; // the speed of the animation (ms)

function generateThumbnail() {
  var c = document.createElement("canvas");
  var ctx = c.getContext("2d");
  c.width = 160;
  c.height = 90;
  ctx.drawImage(video, 0, 0, 160, 90);
  thumbsList.push(c); // store this frame in our list
  if (thumbsList.length === 1) {
    displayThumbs(); // start animating as soon as we got a frame
  }
}
// initialises the display canvas, and starts the animation loop
function displayThumbs() {
  var c = document.createElement("canvas");
  var ctx = c.getContext("2d");
  c.width = 160;
  c.height = 90;
  thumbs.appendChild(c);
  startAnim(ctx); // pass our visible canvas' context
}

function startAnim(ctx) {

  var currentFrame = 0;
  // here is the actual loop
  function anim() {
    ctx.drawImage(thumbsList[currentFrame], 0, 0); // draw the currentFrame
    // increase our counter, and set it to 0 if too large
    currentFrame = (currentFrame + 1) % thumbsList.length;
    setTimeout(anim, delay); // do it again in x ms
  }
  anim(); // let's go !
}
var i = 0;
var video = document.createElement("video");
var thumbs = document.getElementById("thumbs");

/* OP's code */
video.addEventListener('loadeddata', function() {
  thumbs.innerHTML = "";
  video.currentTime = i;
}, false);

video.addEventListener('seeked', function() {
  var j = video.duration;
  var u = j / 4;
  // now video has seeked and current frames will show
  // at the time as we expect
  generateThumbnail(i);
  // when frame is captured, increase
  i += u;

  // if we are not passed end, seek to next interval
  if (i <= video.duration) {
    // this will trigger another seeked event
    video.currentTime = i;
  } else {
    //      displayFrame(); // wait for all images to be parsed before animating
  }
}, false);

video.preload = "auto";
video.src = "https://www.html5rocks.com/en/tutorials/video/basics/devstories.webm";

<div id=thumbs></div>


问:
This version of android studio is incompatible with the gradle version used.Try disabling the instant run
I am able to build the app properly, but when I run it I get this error: </p>

```<code>This version of android studio is incompatible with the gradle version used.Try disabling the instant run
</code>```

答:
I did fix by this way.

Update your classpath to classpath 'com.android.tools.build:gradle:2.0.0' in your top level build.gradle file.

Done

Body:
I am able to build the app properly, but when I run it I get this error:

This version of android studio is incompatible with the gradle version used.Try disabling the instant run


问:
Cover image position relative to text
I am trying to set a text to overlap an image but the position should stay same on all screen sizes.

Example:

Here is an example of what I have tried demo

.c-txt-on-img{
      position: relative;
    }
    .c-txt-on-img .txt{
      font-size: 30px;
      font-weight: bold;
      font-family: arial, sans-serif;
      max-width: 200px;
      position: absolute;
      top: 80px;
      left: 158px;
    }
    .c-txt-on-img .img {
      width: 100vw;
      height: 100vh;
      background-size: cover;
      background-position: center center;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="c-txt-on-img">
      <div class="txt">Tony where are you !!!!</div>
      <div class="img" style="background-image: url(http://theprojectstagingserver.com/stackoverflow/txt-on-img/comic.jpg)"></div>
    </div></code>```

It works on a specific screen-size only, I can fix this on different sizes using different media queries but that will take too much time!

答:
There are 2 main challenges:

1) Align the image and text to always stay on the same spot.

2) Aligning will leave extra uneven space on top/bottom & left/right side of the image so we need to increase image size enough that it covers the whole screen.

For first part we can define same top left position to text and image, then give a negative translate percentage to image so that top left origin of image is the same spot where the text bubble is.

Next we can calculate the space on right/left/top/bottom of image & increase its width till no negative space is left.

Below is a GIF image to explain this better:

Here is the DEMO

var viewportOffset = [],
    winWidth,
    winHeight,
    inLoop = false,
    resizeTimeout;

$(function(){
  init();
});

$(window).resize(function(){
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(function(){
      init();
    }, 500);
});

function init() {
  winWidth = $(window).width();
  winHeight = $(window).height();
  inLoop = false;
  coverImage();
}

function coverImage() {
  $('.js-cover-img').each(function (i) {

      viewportOffset[i] = getViewportOffset($(this));

    if(!inLoop){
      $(this).width('auto');
      $(this).height('auto');
    }

    var imgWidth = $(this).width();
    var imgHeight = $(this).height();

    viewportOffset[i].right = winWidth - imgWidth- (viewportOffset[i].left);
    viewportOffset[i].bot = winHeight - imgHeight- (viewportOffset[i].top);

    if(viewportOffset[i].top < 0){
      var vertViewportOffest = viewportOffset[i].bot;
    }else if(viewportOffset[i].bot <= 0){
      var vertViewportOffest = viewportOffset[i].top;
    }else{
      var vertViewportOffest = viewportOffset[i].top + viewportOffset[i].bot;
    }

    if(viewportOffset[i].right < 0){
      var horViewportOffest = viewportOffset[i].left;
    }else if(viewportOffset[i].left < 0){
      var horViewportOffest = viewportOffset[i].right;
    }else{
      var horViewportOffest = viewportOffset[i].left + viewportOffset[i].right;
    }

    if(horViewportOffest > 0 || vertViewportOffest > 0){
      $(this).width(imgWidth + 20);
      inLoop = true;
      coverImage();
      return false;
    }
  });
}

/* Get's the viewport position */
function getViewportOffset($e) {
  var $window = $(window),
    scrollLeft = $window.scrollLeft(),
    scrollTop = $window.scrollTop(),
    offset = $e.offset();
  return {
    left: offset.left - scrollLeft,
    top: offset.top - scrollTop
  };
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body, html{
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
.c-txt-on-img {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.c-txt-on-img .txt {
  font-size: 30px;
  font-weight: bold;
  font-family: arial, sans-serif;
  max-width: 200px;
  position: absolute;
  top: 30%;
  left: 30%;
  z-index: 2;
  transform: translate(-50%, -50%);
  text-align: center;
}

.c-txt-on-img .img {
    transform: translate(-28.5%, -23%);
    z-index: 1;
    position: absolute;
    top: 30%;
    left: 30%;
    min-width: 870px;
}
.c-txt-on-img img{
  display:block;
  width: 100%;
}</code>```

Tony where are you !!!!

```

Title: Cover image position relative to text

Body:
I am trying to set a text to overlap an image but the position should stay same on all screen sizes.

Example:

Here is an example of what I have tried demo

.c-txt-on-img{
      position: relative;
    }
    .c-txt-on-img .txt{
      font-size: 30px;
      font-weight: bold;
      font-family: arial, sans-serif;
      max-width: 200px;
      position: absolute;
      top: 80px;
      left: 158px;
    }
    .c-txt-on-img .img {
      width: 100vw;
      height: 100vh;
      background-size: cover;
      background-position: center center;
    }

Tony where are you !!!!

It works on a specific screen-size only, I can fix this on different sizes using different media queries but that will take too much time!

Body:
There are 2 main challenges:

1) Align the image and text to always stay on the same spot.

2) Aligning will leave extra uneven space on top/bottom & left/right side of the image so we need to increase image size enough that it covers the whole screen.

For first part we can define same top left position to text and image, then give a negative translate percentage to image so that top left origin of image is the same spot where the text bubble is.

Next we can calculate the space on right/left/top/bottom of image & increase its width till no negative space is left.

Below is a GIF image to explain this better:

Here is the DEMO

var viewportOffset = [],
    winWidth,
    winHeight,
    inLoop = false,
    resizeTimeout;

$(function(){
  init();
});

$(window).resize(function(){
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(function(){
      init();
    }, 500);
});

function init() {
  winWidth = $(window).width();
  winHeight = $(window).height();
  inLoop = false;
  coverImage();
}

function coverImage() {
  $('.js-cover-img').each(function (i) {

      viewportOffset[i] = getViewportOffset($(this));

    if(!inLoop){
      $(this).width('auto');
      $(this).height('auto');
    }

    var imgWidth = $(this).width();
    var imgHeight = $(this).height();

    viewportOffset[i].right = winWidth - imgWidth- (viewportOffset[i].left);
    viewportOffset[i].bot = winHeight - imgHeight- (viewportOffset[i].top);

    if(viewportOffset[i].top < 0){
      var vertViewportOffest = viewportOffset[i].bot;
    }else if(viewportOffset[i].bot <= 0){
      var vertViewportOffest = viewportOffset[i].top;
    }else{
      var vertViewportOffest = viewportOffset[i].top + viewportOffset[i].bot;
    }

    if(viewportOffset[i].right < 0){
      var horViewportOffest = viewportOffset[i].left;
    }else if(viewportOffset[i].left < 0){
      var horViewportOffest = viewportOffset[i].right;
    }else{
      var horViewportOffest = viewportOffset[i].left + viewportOffset[i].right;
    }

    if(horViewportOffest > 0 || vertViewportOffest > 0){
      $(this).width(imgWidth + 20);
      inLoop = true;
      coverImage();
      return false;
    }
  });
}

/* Get's the viewport position */
function getViewportOffset($e) {
  var $window = $(window),
    scrollLeft = $window.scrollLeft(),
    scrollTop = $window.scrollTop(),
    offset = $e.offset();
  return {
    left: offset.left - scrollLeft,
    top: offset.top - scrollTop
  };
}

body, html{
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
.c-txt-on-img {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.c-txt-on-img .txt {
  font-size: 30px;
  font-weight: bold;
  font-family: arial, sans-serif;
  max-width: 200px;
  position: absolute;
  top: 30%;
  left: 30%;
  z-index: 2;
  transform: translate(-50%, -50%);
  text-align: center;
}

.c-txt-on-img .img {
    transform: translate(-28.5%, -23%);
    z-index: 1;
    position: absolute;
    top: 30%;
    left: 30%;
    min-width: 870px;
}
.c-txt-on-img img{
  display:block;
  width: 100%;
}

<script
  src="https://code.jquery.com/jquery-1.12.2.min.js"
  integrity="sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk="
  crossorigin="anonymous"></script>

<div class="c-txt-on-img">
  <div class="txt">Tony where are you !!!!</div>
  <div class="img js-cover-img">
    <img src="http://theprojectstagingserver.com/stackoverflow/txt-on-img/comic.jpg">
  </div>
</div>


问:
Objective-C Programming: Will Learning C and/or Smalltalk Help?
Objective-C is an object-oriented programming language that adds Smalltalk-style messaging to the C programming language. I understand that learning Smalltalk might be good in the same way that learning Lisp is good for one's knowledge, but I want to know if learning Smalltalk-specific concepts will help me to understand Objective-C more completely, given Smalltalk's role in its "origin story". If so, what specifically?

Assuming that one already knows C programming, what can we learn from Smalltalk? Obviously, there's a lot of concepts in Objective-C that just aren't in C (ie. messaging, interfaces, protocols, dynamic typing, delegation, reflection; it's object-oriented!) but are derived from Smalltalk.

Edit: I've added the C programming language to the question, as the general consensus is that learning C is a better use of one's time than learning Smalltalk (when it comes to programming in Objective-C).

答:
I have to disagree with Knodel just an example see this

[someObject message]
and see

someObject message.

You see Objective-C uses the same "positioning" and yes it comes from Smalltalk.
Learning Smalltalk is always a good investment of time. And the meaning in this area is 100% smalltalk send some message to either an Object or an Class which itself has some MetaClass.

And yes learning C is good to know how to use part of Objective-C but getting used to OO is not taught by C. So knowing C and Smalltalk makes it easier to use Objective-C. BUT Objective-C is not just the language the "power" comes from the class libraries. So spending time on that is surely good spent time.

And yes you better knew C and Smalltalk to make the best out of Objective-C.


问:
How do I shutdown my linux based computer remotely?
I have absolutely basic knowledge regarding networking. And I know about ssh tunneling or connections but I have no clue how to apply it or use it. I'm designing an application for security and I need help getting past this hurdle. </p>

答:
You can create a user on the server you need to shutdown, that has rights to perform the action. Then add a key-pair, so your client can access this account without a password to perform the actual shutdown.

Now you can shutdown over ssh. The basic method to do this, is:

```<code>ssh -t <options> <user>@<hostname> sudo poweroff
</code>```

(via)

It looks like you want to do this in a python program, so now you need to call this via python. A simple way is this

```<code>   commands.getstatusoutput("ssh machine 1 'your script'")
</code>```

(via note, there are more options in that question, and more questions about it to be found)

Body:
You can create a user on the server you need to shutdown, that has rights to perform the action. Then add a key-pair, so your client can access this account without a password to perform the actual shutdown.

Now you can shutdown over ssh. The basic method to do this, is:

ssh -t <options> <user>@<hostname> sudo poweroff

(via)

It looks like you want to do this in a python program, so now you need to call this via python. A simple way is this

   commands.getstatusoutput("ssh machine 1 'your script'")

(via note, there are more options in that question, and more questions about it to be found)


问:
cassandra getendpoints with partition key has space
my partition keys are id(int) and name(text).
Below command works fine until there is no space in name(text).
nodetool getendpoints test testtable2 1:aaa;

if am using
nodetool getendpoints test testtable2 3:aac cc;
it throws an error as :nodetool: getendpoints requires keyspace, table and partition key arguments
See 'nodetool help' or 'nodetool help '.

i got token by executing
SELECT id,name, token(id,name) FROM test.testtable2 where name='aac cc'AND id=3;
and tried to search
nodetool getendpoints test testtable2 -7072928299163215694;
error: For input string: "-7072928299163215694"
-- StackTrace --
java.lang.NumberFormatException: For input string: "-7072928299163215694"

how can i search if partition key (name) has space?

答:
This is an issue of nodetool command.

I have modified the nodetool script and create getendpoints script to support getendpoints with partition key has space

Here is the getendpoints code :

```<code>#!/bin/sh
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

if [ "`basename "$0"`" = 'nodeprobe' ]; then
    echo "***************************************************************" >&2
    echo "WARNING: $0 is obsolete, use `dirname "$0"`/nodetool instead" >&2
    echo "***************************************************************" >&2
fi

if [ "x$CASSANDRA_INCLUDE" = "x" ]; then
    for include in "`dirname "$0"`/cassandra.in.sh" \
                   "$HOME/.cassandra.in.sh" \
                   /usr/share/cassandra/cassandra.in.sh \
                   /usr/local/share/cassandra/cassandra.in.sh \
                   /opt/cassandra/cassandra.in.sh; do
        if [ -r "$include" ]; then
            . "$include"
            break
        fi
    done
elif [ -r "$CASSANDRA_INCLUDE" ]; then
    . "$CASSANDRA_INCLUDE"
fi

# Use JAVA_HOME if set, otherwise look for java in PATH
if [ -x "$JAVA_HOME/bin/java" ]; then
    JAVA="$JAVA_HOME/bin/java"
else
    JAVA="`which java`"
fi

if [ -z "$CASSANDRA_CONF" -o -z "$CLASSPATH" ]; then
    echo "You must set the CASSANDRA_CONF and CLASSPATH vars" >&2
    exit 1
fi

# Run cassandra-env.sh to pick up JMX_PORT
if [ -f "$CASSANDRA_CONF/cassandra-env.sh" ]; then
    . "$CASSANDRA_CONF/cassandra-env.sh"
fi

# JMX Port passed via cmd line args (-p 9999 / --port 9999 / --port=9999)
# should override the value from cassandra-env.sh
ARGS=""
JVM_ARGS=""
SSL_FILE=$HOME/.cassandra/nodetool-ssl.properties
KS=""
CF=""
KEY=""

while true
do
  if [ ! $1 ]; then break; fi
  case $1 in
    -p)
      JMX_PORT=$2
      shift
      ;;
    --port=*)
      JMX_PORT=$(echo $1 | cut -d '=' -f 2)
      ;;
    --port)
      JMX_PORT=$2
      shift
      ;;
    --ssl)
      if [ -f $SSL_FILE ]
      then
          SSL_ARGS=$(cat $SSL_FILE | tr '\n' ' ')
      fi
      JVM_ARGS="$JVM_ARGS -Dssl.enable=true $SSL_ARGS"
      ;;
    -D*)
      JVM_ARGS="$JVM_ARGS $1"
      ;;
    -k)
      KS=$2
      shift
      ;;
    -t)
      CF=$2
      shift
      ;;
    *)
      if [ ! $KEY ]; then
    KEY="$1"
      else
    KEY="$KEY $1"
      fi
      ;;
  esac
  shift
done

# Special-case path variables.
case "`uname`" in
    CYGWIN*)
        CLASSPATH="`cygpath -p -w "$CLASSPATH"`"
        CASSANDRA_CONF="`cygpath -p -w "$CASSANDRA_CONF"`"
    ;;
esac

"$JAVA" $JAVA_AGENT -cp "$CLASSPATH" \
      -Xmx128m \
      -Dcassandra.storagedir="$cassandra_storagedir" \
      -Dlogback.configurationFile=logback-tools.xml \
      -Dstorage-config="$CASSANDRA_CONF" \
      $JVM_ARGS \
      org.apache.cassandra.tools.NodeTool -p $JMX_PORT getendpoints $KS $CF "$KEY"
</code>```

Put getendpoints file under $CASSANDRA_HOME/bin directory.

Now you can run this file with nodetool argument,along with below argument

```<code>getendpoints -k keyspace_name -t table_name key
</code>```

Example :

```<code>getendpoints -k test -t testtable2 3:aac cc
</code>```

Body:
This is an issue of nodetool command.

I have modified the nodetool script and create getendpoints script to support getendpoints with partition key has space

Here is the getendpoints code :

#!/bin/sh
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

if [ "`basename "$0"`" = 'nodeprobe' ]; then
    echo "***************************************************************" >&2
    echo "WARNING: $0 is obsolete, use `dirname "$0"`/nodetool instead" >&2
    echo "***************************************************************" >&2
fi

if [ "x$CASSANDRA_INCLUDE" = "x" ]; then
    for include in "`dirname "$0"`/cassandra.in.sh" \
                   "$HOME/.cassandra.in.sh" \
                   /usr/share/cassandra/cassandra.in.sh \
                   /usr/local/share/cassandra/cassandra.in.sh \
                   /opt/cassandra/cassandra.in.sh; do
        if [ -r "$include" ]; then
            . "$include"
            break
        fi
    done
elif [ -r "$CASSANDRA_INCLUDE" ]; then
    . "$CASSANDRA_INCLUDE"
fi

# Use JAVA_HOME if set, otherwise look for java in PATH
if [ -x "$JAVA_HOME/bin/java" ]; then
    JAVA="$JAVA_HOME/bin/java"
else
    JAVA="`which java`"
fi

if [ -z "$CASSANDRA_CONF" -o -z "$CLASSPATH" ]; then
    echo "You must set the CASSANDRA_CONF and CLASSPATH vars" >&2
    exit 1
fi

# Run cassandra-env.sh to pick up JMX_PORT
if [ -f "$CASSANDRA_CONF/cassandra-env.sh" ]; then
    . "$CASSANDRA_CONF/cassandra-env.sh"
fi

# JMX Port passed via cmd line args (-p 9999 / --port 9999 / --port=9999)
# should override the value from cassandra-env.sh
ARGS=""
JVM_ARGS=""
SSL_FILE=$HOME/.cassandra/nodetool-ssl.properties
KS=""
CF=""
KEY=""

while true
do
  if [ ! $1 ]; then break; fi
  case $1 in
    -p)
      JMX_PORT=$2
      shift
      ;;
    --port=*)
      JMX_PORT=$(echo $1 | cut -d '=' -f 2)
      ;;
    --port)
      JMX_PORT=$2
      shift
      ;;
    --ssl)
      if [ -f $SSL_FILE ]
      then
          SSL_ARGS=$(cat $SSL_FILE | tr '\n' ' ')
      fi
      JVM_ARGS="$JVM_ARGS -Dssl.enable=true $SSL_ARGS"
      ;;
    -D*)
      JVM_ARGS="$JVM_ARGS $1"
      ;;
    -k)
      KS=$2
      shift
      ;;
    -t)
      CF=$2
      shift
      ;;
    *)
      if [ ! $KEY ]; then
    KEY="$1"
      else
    KEY="$KEY $1"
      fi
      ;;
  esac
  shift
done

# Special-case path variables.
case "`uname`" in
    CYGWIN*)
        CLASSPATH="`cygpath -p -w "$CLASSPATH"`"
        CASSANDRA_CONF="`cygpath -p -w "$CASSANDRA_CONF"`"
    ;;
esac

"$JAVA" $JAVA_AGENT -cp "$CLASSPATH" \
      -Xmx128m \
      -Dcassandra.storagedir="$cassandra_storagedir" \
      -Dlogback.configurationFile=logback-tools.xml \
      -Dstorage-config="$CASSANDRA_CONF" \
      $JVM_ARGS \
      org.apache.cassandra.tools.NodeTool -p $JMX_PORT getendpoints $KS $CF "$KEY"

Put getendpoints file under $CASSANDRA_HOME/bin directory.

Now you can run this file with nodetool argument,along with below argument

getendpoints -k keyspace_name -t table_name key

Example :

getendpoints -k test -t testtable2 3:aac cc


问:
Postgresql RULE order
What is the order that RULEs fire when applied to an INSERT?

Are they done AFTER or BEFORE the record is inserted.

What I am trying to do is create a new record in another table, which will link to the record that was INSERTed.

Take for example; To make a rule that will creating a new page, when a document is created, so that a document will always start with an empty page record.

I have looked high and low, and maybe I'm asking Google the wrong question, but I cannot find any documentation about the order of execution for RULES.

答:
Quote from the manual

Multiple rules on the same table and same event type are applied in alphabetical name order.

So the ordering does not depend on the type of the rule, only on the name.

And it also explains how the rule is "applied"

It is important to realize that a rule is really a command transformation mechanism, or command macro. The transformation happens before the execution of the command starts.

Emphasis mine

So the rule doesn't happen "before" or "after" a statement runs - it runs instead of that statement.

What I am trying to do is create a new record in another table, which will link to the record that was INSERTed.

You definitely want an AFTER INSERT trigger for that. Forget about rules.

Which is also what the manuals recommends:

If you actually want an operation that fires independently for each physical row, you probably want to use a trigger, not a rule

Title: Postgresql RULE order


问:
Return from a promise then()
I have got a javascript code like this:

```<code>function justTesting() {
  promise.then(function(output) {
    return output + 1;
  });
}

var test = justTesting();
</code>```

I have got always an undefined value for the var test. I think that it is because the promises are not resolved yet..there is a way to return a value from a promise?

答:
When you return something from a then() callback, it's a bit magic. If you return a value, the next then() is called with that value. However, if you return something promise-like, the next then() waits on it, and is only called when that promise settles (succeeds/fails).

Source: https://web.dev/promises/#queuing-asynchronous-actions

ContentLicense: CC BY-SA 4.0

Title: Return from a promise then()

Body:
I have got a javascript code like this:

function justTesting() {
  promise.then(function(output) {
    return output + 1;
  });
}

var test = justTesting();

I have got always an undefined value for the var test. I think that it is because the promises are not resolved yet..there is a way to return a value from a promise?


问:
Is is possible to send a link via email or text to an Android device that will open your own custom app with contained parameters?
I can't really add much more to the title. I want to send out alerts to users with links that open up my app directly.

Is this possible, and if so, how?

答:
I know from working with Google Adwords that it is indeed possible to send users to a specific deep link location in you app. As an example of sending a user to a specific product page, you would use a URL such as android-app://com.example.android/exampleapp/productid_1234

Read more - https://support.google.com/adwords/answer/6046977?hl=en-GB


问:
how to reformat a json in python
I am trying to make a json file as I am new in python
the json file
i have is as followed and i want to reformat it

```<code>{
   "A1":"a1",
   "aback":"\u0259b\u00e6k",
   "abaft":"abaft",
   "abandon":"\u0259b\u00e6nd\u0259n",
   "abandoned":"\u0259b\u00e6nd\u0259nd",
   "abandonment":"\u0259b\u00e6nd\u0259nm\u0259nt",
   "abase":"abase",
   "abash":"\u0259b\u00e6\u0283",
   "abashment":"abashment",
   "abate":"\u0259bet",
   "abatement":"\u0259betm\u0259nt",
   "abbey":"\u00e6bi",
   "abbreviate":"\u0259briviet",
   "abbreviation":"\u0259brivie\u0283\u0259n"
}
</code>```

the format that i want to achieve is

```<code>{
   word: "A1",
   transcription:"a1"
}
{
   word: "aback",
   transcription :"\u0259b\u00e6k"
}
{
  word:"abaft"
  transcrition:"abaft"
}
{
  word:"abbreviation",
  transcription:"\u0259brivie\u0283\u0259n"
}
</code>```

答:
Copy this code to a file such as convert.py

```<code>import sys
import json
from pprint import PrettyPrinter, pprint

def main():
    fn =   sys.argv[1]
    with open(fn, 'rb') as f:
        data = json.loads(f.read())

    for k, v in data.items():
        pprint({'word':k, 'transcription':v})

if __name__ == '__main__':
    main()
</code>```

and then run command python convert.py YOUR_JSON_FILE_NAME, enjoy it ~

Title: how to reformat a json in python

Body:
I am trying to make a json file as I am new in python
the json file
i have is as followed and i want to reformat it

{
   "A1":"a1",
   "aback":"\u0259b\u00e6k",
   "abaft":"abaft",
   "abandon":"\u0259b\u00e6nd\u0259n",
   "abandoned":"\u0259b\u00e6nd\u0259nd",
   "abandonment":"\u0259b\u00e6nd\u0259nm\u0259nt",
   "abase":"abase",
   "abash":"\u0259b\u00e6\u0283",
   "abashment":"abashment",
   "abate":"\u0259bet",
   "abatement":"\u0259betm\u0259nt",
   "abbey":"\u00e6bi",
   "abbreviate":"\u0259briviet",
   "abbreviation":"\u0259brivie\u0283\u0259n"
}

the format that i want to achieve is

{
   word: "A1",
   transcription:"a1"
}
{
   word: "aback",
   transcription :"\u0259b\u00e6k"
}
{
  word:"abaft"
  transcrition:"abaft"
}
{
  word:"abbreviation",
  transcription:"\u0259brivie\u0283\u0259n"
}

Body:
Copy this code to a file such as convert.py

import sys
import json
from pprint import PrettyPrinter, pprint

def main():
    fn =   sys.argv[1]
    with open(fn, 'rb') as f:
        data = json.loads(f.read())

    for k, v in data.items():
        pprint({'word':k, 'transcription':v})

if __name__ == '__main__':
    main()

and then run command python convert.py YOUR_JSON_FILE_NAME, enjoy it ~


问:
Get URL headers without the HTML
A bit of a strange question. Is there a way to ask a webserver to return only the headers and not the HTML itself ?

I want to ask a server for a URL and see if its valid (not 404/500/etc) and follow the redirections (if present) but not get the actual HTML content.

Thanks

Preferably a way to do this in Ruby

答:
use HEAD instead of GET or POST

http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html  Section 9.4

Title: Get URL headers without the HTML


答:
Whatever @DontPanic has answered is correct, the main point that I wanted to highlight is that the order (from top to bottom) of the code blocks in the source code also matters, you can look here from Java doc.

A class can have any number of static initialization blocks, and they
  can appear anywhere in the class body. The runtime system guarantees
  that static initialization blocks are called in the order that they
  appear in the source code.

Title: In Java, what is the order of initialization for those statements after main method


问:
multiple subplots on same figure with nan values
Hi so I have a function that plots timeseries data for a given argument (in my case its a country name). Now some of the columns have na values and when i try to plot them I cant because of thos NaN values. How can I solve this problem?
This is the code, which gets you dataframe and function im using:

```<code>url2='https://spreadsheets.google.com/pub?key=phAwcNAVuyj1jiMAkmq1iMg&output=xls'
source=io.BytesIO(requests.get(url2).content)
income=pd.read_excel(source)
income.head()
income.set_index("GDP per capita", inplace=True)
def gdpchange(country):
    dfff=income.loc[country]
    dfff.T.plot(kind='line')
    plt.legend([country])
</code>```

Now if I want to plot all of them on one graph it gives an error because of nan values in some columns. Any suggestions?

```<code>for ctr in income.index.values:
    gdpchange(ctr)
</code>```

答:
You have to drop all nan values with pandas.dropna():

```<code>income.dropna(inplace=True)
</code>```

This statement drops all rows that have any nan values in income dataframe.

Body:
Hi so I have a function that plots timeseries data for a given argument (in my case its a country name). Now some of the columns have na values and when i try to plot them I cant because of thos NaN values. How can I solve this problem?
This is the code, which gets you dataframe and function im using:

url2='https://spreadsheets.google.com/pub?key=phAwcNAVuyj1jiMAkmq1iMg&output=xls'
source=io.BytesIO(requests.get(url2).content)
income=pd.read_excel(source)
income.head()
income.set_index("GDP per capita", inplace=True)
def gdpchange(country):
    dfff=income.loc[country]
    dfff.T.plot(kind='line')
    plt.legend([country])

Now if I want to plot all of them on one graph it gives an error because of nan values in some columns. Any suggestions?

for ctr in income.index.values:
    gdpchange(ctr)

Body:
You have to drop all nan values with pandas.dropna():

income.dropna(inplace=True)

This statement drops all rows that have any nan values in income dataframe.


问:
Always shows Undefined index 'confirmPassword'
I am trying to run the below code...
HTML...signup.html

```<code><div>
    <label for="create-password">Create Password</label>
    <input id="create-password" type="password" placeholder="Atleast 6 characters" name="password" required>
</div>
<div>
    <label for="confirm-password">Confirm Password</label>
    <input id="confirm-password" type="password" placeholder="Atleast 6 characters" name="confirmPassword" required>
</div>
</code>```

PHP Part

```<code>$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
if($password != $confirmPassword)
        echo "Passwords do not match";
</code>```

Whenever i try to run this it says

Notice: Undefined index: confirmPassword in E:\xampp\htdocs\Nishat's Web Design\signup_process.php on line 26
  Passwords do not match

I dont understand why it is not considering the second input name = confirmPassword...
If someone helps then it would be appreciateable

答:
There's no problem in your code. Just check that you specified form method to post I've tried code and it's working fine, and always first check input field isset or not. Here's my code

```<code><?php
if(isset($_POST['submit']))
{
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];

if($password != $confirmPassword)
echo "Passwords do not match";
}
?>
</code>```

HTML:

```<code><html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
<form method="post">
 <div>
                    <label for="create-password">Create Password</label>
                    <input id="create-password" type="password"
                    placeholder="Atleast 6 characters" name="password" required>
                </div>
                <div>
                    <label for="confirm-password">Confirm Password</label>
                    <input id="confirm-password" type="password"
                    placeholder="Atleast 6 characters" name="confirmPassword" required>
                </div>
                <input type="submit" name="submit">
    </form>
</body>
</html>
</code>```

Body:
I am trying to run the below code...
HTML...signup.html

    Create Password
    <input id="create-password" type="password" placeholder="Atleast 6 characters" name="password" required>

    Confirm Password
    <input id="confirm-password" type="password" placeholder="Atleast 6 characters" name="confirmPassword" required>

PHP Part

$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
if($password != $confirmPassword)
        echo "Passwords do not match";

Whenever i try to run this it says

Notice: Undefined index: confirmPassword in E:\xampp\htdocs\Nishat's Web Design\signup_process.php on line 26
  Passwords do not match

I dont understand why it is not considering the second input name = confirmPassword...
If someone helps then it would be appreciateable

Body:
There's no problem in your code. Just check that you specified form method to post I've tried code and it's working fine, and always first check input field isset or not. Here's my code

<?php
if(isset($_POST['submit']))
{
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];

if($password != $confirmPassword)
echo "Passwords do not match";
}
?>

HTML:

<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
<form method="post">
 <div>
                    <label for="create-password">Create Password</label>
                    <input id="create-password" type="password"
                    placeholder="Atleast 6 characters" name="password" required>
                </div>
                <div>
                    <label for="confirm-password">Confirm Password</label>
                    <input id="confirm-password" type="password"
                    placeholder="Atleast 6 characters" name="confirmPassword" required>
                </div>
                <input type="submit" name="submit">
    </form>
</body>
</html>


问:
Do not update or delete data from the database
I have doman class:

```<code>package testgrails12
class Teams {
String name
static mapping = {
version false
}
static constraints = {
name nullable: true
}
}
</code>```

I'm trying to delete or update data from a table In my controller:

```<code>def team = Teams.get(1)
team.delete()
</code>```

Update:

```<code>team.name = '123'
team.save()
</code>```

I do not get a result either in the first or in the second cases. Also I do not get any errors. I'm confused. It just does not work. I see the result in the database.

答:
A good place to start would be to generate the views and controller to get an idea of how 'stuff' happens between the view and controller, run the generate-all command.

```<code>generate-all testgrails12.Teams
</code>```

You'll end up with a TeamsController and all the relevant gsps.

You can also make use of scaffolding which is essentially the same as above but all the magic is hidden.
Create the following Teams controller:

```<code>class TeamsController {
    static scaffold = Teams
}
</code>```

Body:
I have doman class:

package testgrails12
class Teams {
String name
static mapping = {
version false
}
static constraints = {
name nullable: true
}
}

I'm trying to delete or update data from a table In my controller:

def team = Teams.get(1)
team.delete()

Update:

team.name = '123'
team.save()

I do not get a result either in the first or in the second cases. Also I do not get any errors. I'm confused. It just does not work. I see the result in the database.

Body:
A good place to start would be to generate the views and controller to get an idea of how 'stuff' happens between the view and controller, run the generate-all command.

generate-all testgrails12.Teams

You'll end up with a TeamsController and all the relevant gsps.

You can also make use of scaffolding which is essentially the same as above but all the magic is hidden.
Create the following Teams controller:

class TeamsController {
    static scaffold = Teams
}


问:
trouble creating a type list in C++98 without macros
So I'm reading this article from Andrei Alexandrescu about how to create type lists but the following code from the article does not compile with MSVC/GCC:

```<code>template <class H, class T>
struct typelist
{
    typedef H head;
    typedef T tail;
};

class null_typelist {};

template <class T1>
struct cons<T1, null_typelist, null_typelist,
    null_typelist>
{
    typedef typelist<T1, null_typelist> type;
};

template <class T1, class T2>
struct cons<T1, T2, null_typelist, null_typelist>
{
    typedef typelist<T1, typelist<T2,
        null_typelist> > type;
};

template <class T1, class T2, class T3>
struct cons<T1, T2, T3, null_typelist>
{
    typedef typelist<T1, typelist<T2, typelist<T3,
        null_typelist> > > type;
};

template <class T1, class T2, class T3, class T4>
struct cons
{
    typedef typelist<T1, typelist<T2, typelist<T3,
        typelist<T4, null_typelist> > > > type;
};

typedef cons<float, double, long double>::type
    floating_point_types;
</code>```

I get the following errors:

```<code>a.cpp:21:8: error: 'cons' is not a class template
 struct cons<T1, null_typelist, null_typelist,
        ^~~~
a.cpp:28:49: error: wrong number of template arguments (4, should be 1)
 struct cons<T1, T2, null_typelist, null_typelist>
                                                 ^
a.cpp:22:18: note: provided for 'template<class T1> struct cons'
     null_typelist>
                  ^
a.cpp:35:38: error: wrong number of template arguments (4, should be 1)
 struct cons<T1, T2, T3, null_typelist>
                                      ^
a.cpp:22:18: note: provided for 'template<class T1> struct cons'
     null_typelist>
                  ^
a.cpp:42:8: error: redeclared with 4 template parameters
 struct cons
        ^~~~
a.cpp:22:18: note: previous declaration 'template<class T1> struct cons' used 1
template parameter
     null_typelist>
                  ^
a.cpp:48:40: error: wrong number of template arguments (3, should be 1)
 typedef cons<float, double, long double>::type
                                        ^
a.cpp:22:18: note: provided for 'template<class T1> struct cons'
     null_typelist>
                  ^
a.cpp:49:5: error: expected initializer before 'floating_point_types'
     floating_point_types;
     ^~~~~~~~~~~~~~~~~~~~
</code>```

I need this in C++98 for a library that I'm writing and anything more like variadic templates or third-party like boost::mpl is not an option.

So what is the problem? I'm not much into template metaprogramming (yet)...

答:
I don't know if can work in msvc (but work with my g++) but, in your code, you declare cons partial specializations.

So, before the first partial specialization (off topic: I suggest the use of typename instead of class for template parameters)

```<code>template <typename T1>
struct cons<T1, null_typelist, null_typelist,
    null_typelist>
{
    typedef typelist<T1, null_typelist> type;
};
</code>```

you should insert the generic declaration that I suppose can be someting like

```<code>template <typename,
          typename = null_typelist,
          typename = null_typelist,
          typename = null_typelist>
struct cons;
</code>```

Body:
So I'm reading this article from Andrei Alexandrescu about how to create type lists but the following code from the article does not compile with MSVC/GCC:

template <class H, class T>
struct typelist
{
    typedef H head;
    typedef T tail;
};

class null_typelist {};

template <class T1>
struct cons<T1, null_typelist, null_typelist,
    null_typelist>
{
    typedef typelist<T1, null_typelist> type;
};

template <class T1, class T2>
struct cons<T1, T2, null_typelist, null_typelist>
{
    typedef typelist<T1, typelist<T2,
        null_typelist> > type;
};

template <class T1, class T2, class T3>
struct cons<T1, T2, T3, null_typelist>
{
    typedef typelist<T1, typelist<T2, typelist<T3,
        null_typelist> > > type;
};

template <class T1, class T2, class T3, class T4>
struct cons
{
    typedef typelist<T1, typelist<T2, typelist<T3,
        typelist<T4, null_typelist> > > > type;
};

typedef cons<float, double, long double>::type
    floating_point_types;

I get the following errors:

a.cpp:21:8: error: 'cons' is not a class template
 struct cons<T1, null_typelist, null_typelist,
        ^~~~
a.cpp:28:49: error: wrong number of template arguments (4, should be 1)
 struct cons<T1, T2, null_typelist, null_typelist>
                                                 ^
a.cpp:22:18: note: provided for 'template<class T1> struct cons'
     null_typelist>
                  ^
a.cpp:35:38: error: wrong number of template arguments (4, should be 1)
 struct cons<T1, T2, T3, null_typelist>
                                      ^
a.cpp:22:18: note: provided for 'template<class T1> struct cons'
     null_typelist>
                  ^
a.cpp:42:8: error: redeclared with 4 template parameters
 struct cons
        ^~~~
a.cpp:22:18: note: previous declaration 'template<class T1> struct cons' used 1
template parameter
     null_typelist>
                  ^
a.cpp:48:40: error: wrong number of template arguments (3, should be 1)
 typedef cons<float, double, long double>::type
                                        ^
a.cpp:22:18: note: provided for 'template<class T1> struct cons'
     null_typelist>
                  ^
a.cpp:49:5: error: expected initializer before 'floating_point_types'
     floating_point_types;
     ^~~~~~~~~~~~~~~~~~~~

I need this in C++98 for a library that I'm writing and anything more like variadic templates or third-party like boost::mpl is not an option.

So what is the problem? I'm not much into template metaprogramming (yet)...

Body:
I don't know if can work in msvc (but work with my g++) but, in your code, you declare cons partial specializations.

So, before the first partial specialization (off topic: I suggest the use of typename instead of class for template parameters)

template <typename T1>
struct cons<T1, null_typelist, null_typelist,
    null_typelist>
{
    typedef typelist<T1, null_typelist> type;
};

you should insert the generic declaration that I suppose can be someting like

template <typename,
          typename = null_typelist,
          typename = null_typelist,
          typename = null_typelist>
struct cons;


问:
Returning an Array from a C++ Function

Possible Duplicate:

  howto return a array in a c++ method?

How can an array be returned from a function?  I'm going for an effect like this:

```<code>int getArray()
{
    return {1, 2, 3, 4, 5};
}
</code>```

...

int myArray[5] = getArray();

答: Either dynamic allocation or std::vector. You can't return an array by value.

Title: Returning an Array from a C++ Function

Body:
Possible Duplicate:

  howto return a array in a c++ method?

How can an array be returned from a function?  I'm going for an effect like this:

int getArray()
{
    return {1, 2, 3, 4, 5};
}

...

int myArray[5] = getArray();