问:
nodemon app crashed - waiting for file changes before starting
EDIT
After further testing, I have found that this is happening with both gulp and grunt on this app and on the default install of mean.js.  I'm running this locally on a Mac.  When I running either app using "node server.js" they don't crash.

I'm using a MEAN stack with grunt-nodemon and node is crashing when an express URL is accessed.  It isn't always consistent though.  Sometimes it works, sometimes node crashes right when the URL is hit retiring no data, and other times I get a response and node crashed immediately after.

Browser console response:

```<code>http://localhost:8000/api/users net::ERR_CONNECTION_REFUSED
</code>```

Terminal output:

```<code>Mongoose: users.insert({ firstname: 'mike', lastname: 'jones', email:'mike@gmail.com', role: 'admin', password: 'mike', _id: ObjectId("57485c16fc11894b96c28057"), created: new Date("Fri, 27 May 2016 14:39:18 GMT"), __v: 0 })
user.save success
node crash
[nodemon] app crashed - waiting for file changes before starting...
</code>```

In this case, the POST request went through, the user was added, then node crashed, but sometimes it crashes before a successful POST.  Node also occasionally crashes on the GET request.

gruntfile.js:

```<code>module.exports = function(grunt) {
    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    var pkg = grunt.file.readJSON('package.json');

    var options = {
        paths: {
            app: 'app',
            assets: 'app/assets',
            dist: 'app/dist',
            distAssets: 'app/dist/assets',
            html: 'app/html',
            htmlTmp: '.tmp/htmlsnapshot',
            htmlAssets: 'app/html/assets',
            index: 'app/dist/index.html',
            indexDev: 'app/index.html',
            indexTmp: '.tmp/html/index.html'
        },
        pkg: pkg,
        env: {
            test: {
                NODE_ENV: 'test'
            },
            dev: {
                NODE_ENV: 'development'
            },
            prod: {
                NODE_ENV: 'production'
            }
        }
    };

    // Load grunt configurations automatically
    var configs = require('load-grunt-configs')(grunt, options);

    // Define the configuration for all the tasks
    grunt.initConfig(configs);

    // Connect to the MongoDB instance and load the models
    grunt.task.registerTask('mongoose', 'Task that connects to the MongoDB instance and loads the application models.', function () {
        // Get the callback
        var done = this.async();

        // Use mongoose configuration
        var mongoose = require('./config/lib/mongoose.js');

        // Connect to database
        mongoose.connect(function (db) {
            done();
        });
    });

    grunt.registerTask('bumper', ['bump-only']);
    grunt.registerTask('css', ['sass']);
    grunt.registerTask('default', [
        'sass',
        'copy:dev',
        'nodemon',
        'concurrent:dev',
        'watch',
        'mongoose'
    ]);

    grunt.registerTask('shared', [
        'clean:demo',
        'copy:demo',
        'sass',
        'ngconstant',
        'useminPrepare',
        'concat:generated',
        'cssmin:generated',
        'uglify:generated',
        'filerev',
        'usemin',
        'imagemin',
        'usebanner'
    ]);

    grunt.registerTask('demo', [
        'shared',
        'copy:postusemin',
        'grep:demo'
    ]);

    grunt.registerTask('dist', [
        'shared',
        'copy:postusemin',
        'copy:dist',
        'grep:dist',
        'compress',
        'copy:postusemin',
        'grep:demo',
    ]);

    grunt.loadNpmTasks('grunt-forever');

};
</code>```

default.js

```<code>module.exports.tasks = {
    // version update
    bump: {
        options: {
            files: ['package.json', 'bower.json'],
            pushTo: 'origin'
        }
    },

    // application constants
    ngconstant: {
        options: {
            dest: '<%= paths.assets %>/js/app.constants.js',
            name: 'app.constants',
        }
    },

    // remove all bs from css
    cssmin: {
        options: {
            keepSpecialComments: 0
        }
    },
    markdown: {
        all: {
            files: [
                {
                    src: 'README.md',
                    dest: '<%= paths.assets %>/tpl/documentation.html'
                }
            ],
            options: {
                template: '<%= paths.assets %>/tpl/_documentation_template.html',
            }
        }
    }
};
</code>```

dev.js:

```<code>var _ = require('lodash'),
defaultAssets = require('./assets/default'),
testAssets = require('./assets/test'),
testConfig = require('./env/test'),
fs = require('fs'),
path = require('path');

module.exports.tasks = {
    // copy files to correct folders
    copy: {
        dev: {
            files: [
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/font-awesome/fonts',                    dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/material-design-iconic-font/fonts',     dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/roboto-fontface/fonts',                 dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/weather-icons/font',                    dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/bootstrap-sass/assets/fonts/bootstrap', dest: '<%= paths.assets %>/fonts' }
            ]
        }
    },

    // watch for changes during development
    watch: {
        js: {
            files: ['Gruntfile.js', '<%= paths.assets %>/js/**/*.js'],
            tasks: ['jshint'],
            options: {
                livereload: true
            }
        },
        css: {
            files: [
                '<%= paths.assets %>/css/**/*.scss'
            ],
            tasks: ['sass'],
            options: {
                livereload: true
            }
        },
        markdown: {
            files: [
                'README.md'
            ],
            tasks: ['markdown']
        },
        tasks:  [ 'express:dev' ],
    },

    // debug while developing
    jshint: {
        all: ['Gruntfile.js', '<%= paths.assets %>/js/**/*.js']
    },
    concurrent: {
        dev: {
            tasks: ['nodemon', 'node-inspector', 'watch'],
            options: {
                logConcurrentOutput: true
            }
        }
    },
    nodemon: {
        dev: {
            script: 'server.js',
            options: {
                nodeArgs: ['--debug'],
                ext: 'js,html',
                callback: function (nodemon) {

                    nodemon.on('crash', function (event) {
                        console.log(event);
                    });

                },
                watch: _.union(defaultAssets.server.gruntConfig, defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
            }
        }
    },
    forever: {
        server1: {
            options: {
                index: 'server.js',
                //logDir: 'logs'
            }
        }
    }
};
</code>```

Angular controller function:

```<code>  $scope.addUser = function(){

      var user = {
          firstname: $scope.firstname,
          lastname: $scope.lastname,
          email: $scope.email,
          role: $scope.role.selected,
          password: $scope.password
      };

      $http.post('/api/userAdd', user ).then(function successCallback(response) {
          $location.path('/users');
      }, function errorCallback(response) {
          console.log('error addding user');
          console.log(response);
      });
  };
</code>```

Express route:

```<code>User = require('../models/user.js');

module.exports = function (app) {

    app.get('/api/users', function (req, res) {

        User.find({}, function (err, users) {
            if ( err ) {
                res.send({
                    message : 'error finding users',
                    success: false
                });
            } else {
                res.json(users);
            }
        });

    });

    app.get('/api/users', function (req, res) {
        User.find({fields: {}}, function (err, docs) {
            res.json(docs);
        });
    });

    app.post('/api/userAdd', function (req, res) {

        var user = new User(req.body);

        user.save( function( err, user ){

            if (err){
                console.log('user.save error');
                console.log(err);
                res.send({
                    success: false
                });
            } else {
                console.log('user.save success');
                res.send({
                    success: true
                });
            }
        });

    });

};
</code>```

I'm also testing with Chromes Advanced REST extension and with any request using this tool node crashes immediately.

I'm new to MEAN so am I missing something here that is causing the crash?  Any ideas?

答: Simply try to move your app.js in outside the public folder.</p>

Body:
EDIT
After further testing, I have found that this is happening with both gulp and grunt on this app and on the default install of mean.js.  I'm running this locally on a Mac.  When I running either app using "node server.js" they don't crash.

I'm using a MEAN stack with grunt-nodemon and node is crashing when an express URL is accessed.  It isn't always consistent though.  Sometimes it works, sometimes node crashes right when the URL is hit retiring no data, and other times I get a response and node crashed immediately after.

Browser console response:

http://localhost:8000/api/users net::ERR_CONNECTION_REFUSED

Terminal output:

Mongoose: users.insert({ firstname: 'mike', lastname: 'jones', email:'mike@gmail.com', role: 'admin', password: 'mike', _id: ObjectId("57485c16fc11894b96c28057"), created: new Date("Fri, 27 May 2016 14:39:18 GMT"), __v: 0 })
user.save success
node crash
[nodemon] app crashed - waiting for file changes before starting...

In this case, the POST request went through, the user was added, then node crashed, but sometimes it crashes before a successful POST.  Node also occasionally crashes on the GET request.

gruntfile.js:

module.exports = function(grunt) {
    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    var pkg = grunt.file.readJSON('package.json');

    var options = {
        paths: {
            app: 'app',
            assets: 'app/assets',
            dist: 'app/dist',
            distAssets: 'app/dist/assets',
            html: 'app/html',
            htmlTmp: '.tmp/htmlsnapshot',
            htmlAssets: 'app/html/assets',
            index: 'app/dist/index.html',
            indexDev: 'app/index.html',
            indexTmp: '.tmp/html/index.html'
        },
        pkg: pkg,
        env: {
            test: {
                NODE_ENV: 'test'
            },
            dev: {
                NODE_ENV: 'development'
            },
            prod: {
                NODE_ENV: 'production'
            }
        }
    };

    // Load grunt configurations automatically
    var configs = require('load-grunt-configs')(grunt, options);

    // Define the configuration for all the tasks
    grunt.initConfig(configs);

    // Connect to the MongoDB instance and load the models
    grunt.task.registerTask('mongoose', 'Task that connects to the MongoDB instance and loads the application models.', function () {
        // Get the callback
        var done = this.async();

        // Use mongoose configuration
        var mongoose = require('./config/lib/mongoose.js');

        // Connect to database
        mongoose.connect(function (db) {
            done();
        });
    });

    grunt.registerTask('bumper', ['bump-only']);
    grunt.registerTask('css', ['sass']);
    grunt.registerTask('default', [
        'sass',
        'copy:dev',
        'nodemon',
        'concurrent:dev',
        'watch',
        'mongoose'
    ]);

    grunt.registerTask('shared', [
        'clean:demo',
        'copy:demo',
        'sass',
        'ngconstant',
        'useminPrepare',
        'concat:generated',
        'cssmin:generated',
        'uglify:generated',
        'filerev',
        'usemin',
        'imagemin',
        'usebanner'
    ]);

    grunt.registerTask('demo', [
        'shared',
        'copy:postusemin',
        'grep:demo'
    ]);

    grunt.registerTask('dist', [
        'shared',
        'copy:postusemin',
        'copy:dist',
        'grep:dist',
        'compress',
        'copy:postusemin',
        'grep:demo',
    ]);

    grunt.loadNpmTasks('grunt-forever');

};

default.js

module.exports.tasks = {
    // version update
    bump: {
        options: {
            files: ['package.json', 'bower.json'],
            pushTo: 'origin'
        }
    },

    // application constants
    ngconstant: {
        options: {
            dest: '<%= paths.assets %>/js/app.constants.js',
            name: 'app.constants',
        }
    },

    // remove all bs from css
    cssmin: {
        options: {
            keepSpecialComments: 0
        }
    },
    markdown: {
        all: {
            files: [
                {
                    src: 'README.md',
                    dest: '<%= paths.assets %>/tpl/documentation.html'
                }
            ],
            options: {
                template: '<%= paths.assets %>/tpl/_documentation_template.html',
            }
        }
    }
};

dev.js:

var _ = require('lodash'),
defaultAssets = require('./assets/default'),
testAssets = require('./assets/test'),
testConfig = require('./env/test'),
fs = require('fs'),
path = require('path');

module.exports.tasks = {
    // copy files to correct folders
    copy: {
        dev: {
            files: [
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/font-awesome/fonts',                    dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/material-design-iconic-font/fonts',     dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/roboto-fontface/fonts',                 dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/weather-icons/font',                    dest: '<%= paths.assets %>/fonts' },
                { expand: true, src: '**', cwd: '<%= paths.app %>/bower_components/bootstrap-sass/assets/fonts/bootstrap', dest: '<%= paths.assets %>/fonts' }
            ]
        }
    },

    // watch for changes during development
    watch: {
        js: {
            files: ['Gruntfile.js', '<%= paths.assets %>/js/**/*.js'],
            tasks: ['jshint'],
            options: {
                livereload: true
            }
        },
        css: {
            files: [
                '<%= paths.assets %>/css/**/*.scss'
            ],
            tasks: ['sass'],
            options: {
                livereload: true
            }
        },
        markdown: {
            files: [
                'README.md'
            ],
            tasks: ['markdown']
        },
        tasks:  [ 'express:dev' ],
    },

    // debug while developing
    jshint: {
        all: ['Gruntfile.js', '<%= paths.assets %>/js/**/*.js']
    },
    concurrent: {
        dev: {
            tasks: ['nodemon', 'node-inspector', 'watch'],
            options: {
                logConcurrentOutput: true
            }
        }
    },
    nodemon: {
        dev: {
            script: 'server.js',
            options: {
                nodeArgs: ['--debug'],
                ext: 'js,html',
                callback: function (nodemon) {

                    nodemon.on('crash', function (event) {
                        console.log(event);
                    });

                },
                watch: _.union(defaultAssets.server.gruntConfig, defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
            }
        }
    },
    forever: {
        server1: {
            options: {
                index: 'server.js',
                //logDir: 'logs'
            }
        }
    }
};

Angular controller function:

  $scope.addUser = function(){

      var user = {
          firstname: $scope.firstname,
          lastname: $scope.lastname,
          email: $scope.email,
          role: $scope.role.selected,
          password: $scope.password
      };

      $http.post('/api/userAdd', user ).then(function successCallback(response) {
          $location.path('/users');
      }, function errorCallback(response) {
          console.log('error addding user');
          console.log(response);
      });
  };

Express route:

User = require('../models/user.js');

module.exports = function (app) {

    app.get('/api/users', function (req, res) {

        User.find({}, function (err, users) {
            if ( err ) {
                res.send({
                    message : 'error finding users',
                    success: false
                });
            } else {
                res.json(users);
            }
        });

    });

    app.get('/api/users', function (req, res) {
        User.find({fields: {}}, function (err, docs) {
            res.json(docs);
        });
    });

    app.post('/api/userAdd', function (req, res) {

        var user = new User(req.body);

        user.save( function( err, user ){

            if (err){
                console.log('user.save error');
                console.log(err);
                res.send({
                    success: false
                });
            } else {
                console.log('user.save success');
                res.send({
                    success: true
                });
            }
        });

    });

};

I'm also testing with Chromes Advanced REST extension and with any request using this tool node crashes immediately.

I'm new to MEAN so am I missing something here that is causing the crash?  Any ideas?


来源: stackexchange

问:
Write Chunked data array to HDF5
I have this code to write an array to Hdf5 with HDF5Sharp.
But the problem is that I need the data to be written in chunks of 1 x 100 x 500 instead of 100k x 100 x 500 and I cannot figure out how to do it.</p>
```<code>using HDF5CSharp;

// array of 100k x 100 x 500
float[,,] traindata = new float[100000, 100, 500];

// ...
// fill the array with data
// ...

long fileId = Hdf5.CreateFile("d:\\Temp\\Test.H5");
var groupId = Hdf5.CreateOrOpenGroup(fileId, "data");

Hdf5.WriteDataset(groupId, "data", traindata);

Hdf5.CloseGroup(groupId);
Hdf5.CloseFile(fileId);
</code>```

答:
Not sure how this is done with the library you have indicated but with HDFql, a high-level language that abstracts you from low-level details of HDF5, your use-case can be solved as follows in C#:</p>
```<code>// use HDFql namespace (make sure it can be found by the C# compiler)
using AS.HDFql;

// declare variables
float[,,] traindata = new float[1, 100, 500];
int number;
int i;

// create an HDF5 file named 'Test.h5' and use (i.e. open) it
HDFql.Execute("create and use file Test.h5");

// create a chunked dataset named 'data' (within a group named 'grp') of data type float with three dimensions (the first dimension is extendible)
HDFql.Execute("create chunked(1, 100, 500) dataset grp/data as float(0 to unlimited, 100, 500)");

// register variable 'traindata'
number = HDFql.VariableRegister(traindata);

// loop 100000 times
for(i = 0; i < 100000; i++)
{
   // populate variable 'traindata'
   // (...)

   // insert (i.e. write) data stored in 'traindata' into the last position of 'data' (using a hyperslab selection)
   HDFql.Execute("insert into grp/data(-1:::) values from memory " + number);

   // alter (i.e. extend) first dimension of 'data' plus one unit
   HDFql.Execute("alter dimension grp/data to +1");
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Write Chunked data array to HDF5

Body:
I have this code to write an array to Hdf5 with HDF5Sharp.
But the problem is that I need the data to be written in chunks of 1 x 100 x 500 instead of 100k x 100 x 500 and I cannot figure out how to do it.

using HDF5CSharp;

// array of 100k x 100 x 500
float[,,] traindata = new float[100000, 100, 500];

// ...
// fill the array with data
// ...

long fileId = Hdf5.CreateFile("d:\\Temp\\Test.H5");
var groupId = Hdf5.CreateOrOpenGroup(fileId, "data");

Hdf5.WriteDataset(groupId, "data", traindata);

Hdf5.CloseGroup(groupId);
Hdf5.CloseFile(fileId);

Body:
Not sure how this is done with the library you have indicated but with HDFql, a high-level language that abstracts you from low-level details of HDF5, your use-case can be solved as follows in C#:

// use HDFql namespace (make sure it can be found by the C# compiler)
using AS.HDFql;

// declare variables
float[,,] traindata = new float[1, 100, 500];
int number;
int i;

// create an HDF5 file named 'Test.h5' and use (i.e. open) it
HDFql.Execute("create and use file Test.h5");

// create a chunked dataset named 'data' (within a group named 'grp') of data type float with three dimensions (the first dimension is extendible)
HDFql.Execute("create chunked(1, 100, 500) dataset grp/data as float(0 to unlimited, 100, 500)");

// register variable 'traindata'
number = HDFql.VariableRegister(traindata);

// loop 100000 times
for(i = 0; i < 100000; i++)
{
   // populate variable 'traindata'
   // (...)

   // insert (i.e. write) data stored in 'traindata' into the last position of 'data' (using a hyperslab selection)
   HDFql.Execute("insert into grp/data(-1:::) values from memory " + number);

   // alter (i.e. extend) first dimension of 'data' plus one unit
   HDFql.Execute("alter dimension grp/data to +1");
}


问:
How to SELECT LAST PING as "seconds" from a table in SQL
I'm trying to write just a simple sql query on an observability platform like Grafana that will check if a server is up and running - On my database there is a table called ping and what it does is that it usually sends ping request every 15mins to check if the server is up and then stores all the records on the ping table.

I would like to create a query on Grafana sp if I don't get any ping from the server in 15mins, I would be able to see it on Grafana so I can set alerts.

```<code>SELECT DATE_FORMAT((
    SELECT timeint
    from mio.nyp_ping
    ORDER BY timeint DESC
    LIMIT 1) , '%Y-%M-%D-%H-%') AS Result;

2022-February-3rd-10-02
</code>```

Trying to achieve something like this as an SQL query so I can run it on Grafana:

Metric:

```<code>SELECT (NOW() - LAST PING ) as "seconds from last ping"
</code>```

答:
Use the MAX() function to get the last ping time.

```<code>SELECT TIME_TO_SEC(TIMEDIFF(NOW(), MAX(ping_time))) AS "seconds from last ping"
FROM ping
</code>```

Body:
I'm trying to write just a simple sql query on an observability platform like Grafana that will check if a server is up and running - On my database there is a table called ping and what it does is that it usually sends ping request every 15mins to check if the server is up and then stores all the records on the ping table.

I would like to create a query on Grafana sp if I don't get any ping from the server in 15mins, I would be able to see it on Grafana so I can set alerts.

SELECT DATE_FORMAT((
    SELECT timeint
    from mio.nyp_ping
    ORDER BY timeint DESC
    LIMIT 1) , '%Y-%M-%D-%H-%') AS Result;

2022-February-3rd-10-02

Trying to achieve something like this as an SQL query so I can run it on Grafana:

Metric:

SELECT (NOW() - LAST PING ) as "seconds from last ping"

Body:
Use the MAX() function to get the last ping time.

SELECT TIME_TO_SEC(TIMEDIFF(NOW(), MAX(ping_time))) AS "seconds from last ping"
FROM ping


问:
Its showing me a module not found error but the module is installed on my computer
Whenever I run my code code I am getting an Module Not Found Error for the tkvideoplayer module</p>
```<code>"Traceback (most recent call last):
  File "C:\Code\Proj1\Video_Player.py", line 2, in <module>
    from tkvideoplayer import TkinterVideo
ModuleNotFoundError: No module named 'tkvideoplayer'"
</code>```
```<code>from tkinter import *
from tkvideoplayer import TkinterVideo
from tkinter.filedialog import askopenfile
window = Tk()
window.title("My Video Player")
window.geometry("500x500")
window.config(bg="Turquoise")
heading = Label(window, text="My Video Player", bg="Orange Red", fg="white", font="4 none bold")
heading.config(anchor=CENTER)

def openFile():
    file = askopenfile(mode="r", filetypes=[('Video Files', '*.mp4', '*.mov')])
    if file is not None:
        global filename
        filename = file.name
        global videoPlayer
        videoPlayer = TkinterVideo(master=window, scaled=True, pre_load=False)
        videoPlayer.load(r"{}".format(filename))
        videoPlayer.pack(expand=True, fill="both")
        videoPlayer.play()

def playFile():
    videoPlayer.play()

def stopFile():
    videoPlayer.stop()

def pauseFile():
    videoPlayer.pause()

openbtn = Button(window, text="Open", command=lambda: openFile())
stopbtn = Button(window, text="Stop", command=lambda: stopFile())
playbtn = Button(window, text="Play", command=lambda: playFile())
pausebtn = Button(window, text="Pause", command=lambda: pauseFile())

openbtn.pack(side=TOP, pady=2)
stopbtn.pack(side=TOP, pady=4)
playbtn.pack(side=TOP, pady=3)
pausebtn.pack(side=TOP, pady=5)
heading.pack()

window.mainloop()
</code>```

答:
I deleted my code then made a different video player and this one doesn't give an error</p>
```<code>import datetime
import tkinter as tk
from tkinter import filedialog
from tkVideoPlayer import TkinterVideo

def update_duration(event):
    """ updates the duration after finding the duration """
    end_time["text"] = str(datetime.timedelta(seconds=vid_player.duration()))
    progress_slider["to"] = vid_player.duration()

def update_scale(event):
    """ updates the scale value """
    progress_slider.set(vid_player.current_duration())

def load_video():
    """ loads the video """
    file_path = filedialog.askopenfilename()

    if file_path:
        vid_player.load(file_path)

        progress_slider.config(to=0, from_=0)
        progress_slider.set(0)
        play_pause_btn["text"] = "Play"

def seek(value):
    """ used to seek a specific timeframe """
    vid_player.seek(int(value))

def skip(value: int):
    """ skip seconds """
    vid_player.skip_sec(value)
    progress_slider.set(progress_slider.get() + value)

def play_pause():
    """ pauses and plays """
    if vid_player.is_paused():
        vid_player.play()
        play_pause_btn["text"] = "Pause"

    else:
        vid_player.pause()
        play_pause_btn["text"] = "Play"

def video_ended(event):
    """ handle video ended """
    progress_slider.set(progress_slider["to"])
    play_pause_btn["text"] = "Play"

root = tk.Tk()
root.title("Video Player")

load_btn = tk.Button(root, text="Load", command=load_video)
load_btn.pack()

vid_player = TkinterVideo(scaled=True, pre_load=False, master=root)
vid_player.pack(expand=True, fill="both")

play_pause_btn = tk.Button(root, text="Play", command=play_pause)
play_pause_btn.pack()

skip_plus_5sec = tk.Button(root, text="Skip -5 sec", command=lambda: skip(-5))
skip_plus_5sec.pack(side="left")

start_time = tk.Label(root, text=str(datetime.timedelta(seconds=0)))
start_time.pack(side="left")

progress_slider = tk.Scale(root, from_=0, to=0, orient="horizontal", command=seek)
progress_slider.pack(side="left", fill="x", expand=True)

end_time = tk.Label(root, text=str(datetime.timedelta(seconds=0)))
end_time.pack(side="left")

vid_player.bind("<<Duration>>", update_duration)
vid_player.bind("<<SecondChanged>>", update_scale)
vid_player.bind("<<Ended>>", video_ended )

skip_plus_5sec = tk.Button(root, text="Skip +5 sec", command=lambda: skip(5))
skip_plus_5sec.pack(side="left")

root.mainloop()
</code>```

Body:
Whenever I run my code code I am getting an Module Not Found Error for the tkvideoplayer module

"Traceback (most recent call last):
  File "C:\Code\Proj1\Video_Player.py", line 2, in <module>
    from tkvideoplayer import TkinterVideo
ModuleNotFoundError: No module named 'tkvideoplayer'"

from tkinter import *
from tkvideoplayer import TkinterVideo
from tkinter.filedialog import askopenfile
window = Tk()
window.title("My Video Player")
window.geometry("500x500")
window.config(bg="Turquoise")
heading = Label(window, text="My Video Player", bg="Orange Red", fg="white", font="4 none bold")
heading.config(anchor=CENTER)

def openFile():
    file = askopenfile(mode="r", filetypes=[('Video Files', '*.mp4', '*.mov')])
    if file is not None:
        global filename
        filename = file.name
        global videoPlayer
        videoPlayer = TkinterVideo(master=window, scaled=True, pre_load=False)
        videoPlayer.load(r"{}".format(filename))
        videoPlayer.pack(expand=True, fill="both")
        videoPlayer.play()

def playFile():
    videoPlayer.play()

def stopFile():
    videoPlayer.stop()

def pauseFile():
    videoPlayer.pause()

openbtn = Button(window, text="Open", command=lambda: openFile())
stopbtn = Button(window, text="Stop", command=lambda: stopFile())
playbtn = Button(window, text="Play", command=lambda: playFile())
pausebtn = Button(window, text="Pause", command=lambda: pauseFile())

openbtn.pack(side=TOP, pady=2)
stopbtn.pack(side=TOP, pady=4)
playbtn.pack(side=TOP, pady=3)
pausebtn.pack(side=TOP, pady=5)
heading.pack()

window.mainloop()

Body:
I deleted my code then made a different video player and this one doesn't give an error

import datetime
import tkinter as tk
from tkinter import filedialog
from tkVideoPlayer import TkinterVideo

def update_duration(event):
    """ updates the duration after finding the duration """
    end_time["text"] = str(datetime.timedelta(seconds=vid_player.duration()))
    progress_slider["to"] = vid_player.duration()

def update_scale(event):
    """ updates the scale value """
    progress_slider.set(vid_player.current_duration())

def load_video():
    """ loads the video """
    file_path = filedialog.askopenfilename()

    if file_path:
        vid_player.load(file_path)

        progress_slider.config(to=0, from_=0)
        progress_slider.set(0)
        play_pause_btn["text"] = "Play"

def seek(value):
    """ used to seek a specific timeframe """
    vid_player.seek(int(value))

def skip(value: int):
    """ skip seconds """
    vid_player.skip_sec(value)
    progress_slider.set(progress_slider.get() + value)

def play_pause():
    """ pauses and plays """
    if vid_player.is_paused():
        vid_player.play()
        play_pause_btn["text"] = "Pause"

    else:
        vid_player.pause()
        play_pause_btn["text"] = "Play"

def video_ended(event):
    """ handle video ended """
    progress_slider.set(progress_slider["to"])
    play_pause_btn["text"] = "Play"

root = tk.Tk()
root.title("Video Player")

load_btn = tk.Button(root, text="Load", command=load_video)
load_btn.pack()

vid_player = TkinterVideo(scaled=True, pre_load=False, master=root)
vid_player.pack(expand=True, fill="both")

play_pause_btn = tk.Button(root, text="Play", command=play_pause)
play_pause_btn.pack()

skip_plus_5sec = tk.Button(root, text="Skip -5 sec", command=lambda: skip(-5))
skip_plus_5sec.pack(side="left")

start_time = tk.Label(root, text=str(datetime.timedelta(seconds=0)))
start_time.pack(side="left")

progress_slider = tk.Scale(root, from_=0, to=0, orient="horizontal", command=seek)
progress_slider.pack(side="left", fill="x", expand=True)

end_time = tk.Label(root, text=str(datetime.timedelta(seconds=0)))
end_time.pack(side="left")

vid_player.bind("<<Duration>>", update_duration)
vid_player.bind("<<SecondChanged>>", update_scale)
vid_player.bind("<<Ended>>", video_ended )

skip_plus_5sec = tk.Button(root, text="Skip +5 sec", command=lambda: skip(5))
skip_plus_5sec.pack(side="left")

root.mainloop()


问:
Trying to implement proportional navigation into Unity using C#
I tried using the equation for proportional navigation found in this wiki article but when I attempted to implement it in game, the missile often goes off in some direction opposite of my target.

I am not sure if this has to do with the way I normalized the acceleration to give it a maximum velocity, the precision of the coordinates, or my calculations but I have not been able to find the root of the issue.

If anyone could help it would be greatly appreciated.

Here is my code

```<code>public class Missile : MonoBehaviour
{

    Target target;
    public Transform targetTransform;
    public float speed = 5;
    public float propCon = 3;
    Vector3 lastPos;
    Vector3 miLastPos;
    Vector3 velocity;

    void Start()
    {
        target = FindObjectOfType<Target>();
       lastPos = targetTransform.position;
       miLastPos = transform.position;
    }

    void Update()
    {
        Vector3 targetVelocity = (targetTransform.position - lastPos) / Time.deltaTime;
        Vector3 miVelocity = (transform.position - miLastPos) / Time.deltaTime;

        lastPos = targetTransform.position;
        miLastPos = transform.position;

        Vector3 range = targetTransform.position - transform.position;
        Vector3 relVelocity = targetVelocity - miVelocity;
        Vector3 rotVector = Vector3.Cross(range, relVelocity) / Vector3.Dot(range, range);
        Vector3 accNormal = propCon * Vector3.Cross(relVelocity, rotVector);
        Vector3 directionToTarget = accNormal.normalized;

        float distanceToTarget = range.magnitude;

        print ($"TV is: {targetVelocity} and lastPos {lastPos}\nmiVelocity is: {miVelocity} miPosition is: {miLastPos}");
        print ($"rotVector: {rotVector} and accNormal: {accNormal}\nrange: {range} and relVelocity: {relVelocity}");
        print ($"cross: {Vector3.Cross(range, relVelocity)} and dot: {Vector3.Dot(range, range)}");

        if (velocity.magnitude < speed)
        {
            velocity += (speed/10*directionToTarget);
        }

        if (distanceToTarget > 0.1f)
        {
            transform.Translate (velocity*Time.deltaTime);
        }
    }
}
</code>```

答:
Assuming the rest of the calculation is correct (seems so at first glance comparing to the article you linked) I think the issues comes down to

```<code>transform.Translate(velocity * Time.deltaTime);
</code>```

Note that Transform.translate by default uses local space. You are however working with world space vectors. If your missiles are anyhow rotated then your coordinate systems do not match anymore.

If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes. (the x, y and z axes shown when selecting the object inside the Scene View [addition by me: and the gizmos are set to Local].) If relativeTo is Space.World the movement is applied relative to the world coordinate system.

I think in general you rather want to use

```<code>transform.Translate (velocity * Time.deltaTime, Space.World);
</code>```

or also simply

```<code>transform.position += velocity * Time.deltaTime;
</code>```

and then I would probably do this

```<code>miLastPos = transform.position;
</code>```

after moving the object so the calculation should be more precise and not be based on the last frames delta movement.

Body:
I tried using the equation for proportional navigation found in this wiki article but when I attempted to implement it in game, the missile often goes off in some direction opposite of my target.

I am not sure if this has to do with the way I normalized the acceleration to give it a maximum velocity, the precision of the coordinates, or my calculations but I have not been able to find the root of the issue.

If anyone could help it would be greatly appreciated.

Here is my code

public class Missile : MonoBehaviour
{

    Target target;
    public Transform targetTransform;
    public float speed = 5;
    public float propCon = 3;
    Vector3 lastPos;
    Vector3 miLastPos;
    Vector3 velocity;

    void Start()
    {
        target = FindObjectOfType<Target>();
       lastPos = targetTransform.position;
       miLastPos = transform.position;
    }

    void Update()
    {
        Vector3 targetVelocity = (targetTransform.position - lastPos) / Time.deltaTime;
        Vector3 miVelocity = (transform.position - miLastPos) / Time.deltaTime;

        lastPos = targetTransform.position;
        miLastPos = transform.position;

        Vector3 range = targetTransform.position - transform.position;
        Vector3 relVelocity = targetVelocity - miVelocity;
        Vector3 rotVector = Vector3.Cross(range, relVelocity) / Vector3.Dot(range, range);
        Vector3 accNormal = propCon * Vector3.Cross(relVelocity, rotVector);
        Vector3 directionToTarget = accNormal.normalized;

        float distanceToTarget = range.magnitude;

        print ($"TV is: {targetVelocity} and lastPos {lastPos}\nmiVelocity is: {miVelocity} miPosition is: {miLastPos}");
        print ($"rotVector: {rotVector} and accNormal: {accNormal}\nrange: {range} and relVelocity: {relVelocity}");
        print ($"cross: {Vector3.Cross(range, relVelocity)} and dot: {Vector3.Dot(range, range)}");

        if (velocity.magnitude < speed)
        {
            velocity += (speed/10*directionToTarget);
        }

        if (distanceToTarget > 0.1f)
        {
            transform.Translate (velocity*Time.deltaTime);
        }
    }
}

Body:
Assuming the rest of the calculation is correct (seems so at first glance comparing to the article you linked) I think the issues comes down to

transform.Translate(velocity * Time.deltaTime);

Note that Transform.translate by default uses local space. You are however working with world space vectors. If your missiles are anyhow rotated then your coordinate systems do not match anymore.

If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes. (the x, y and z axes shown when selecting the object inside the Scene View [addition by me: and the gizmos are set to Local].) If relativeTo is Space.World the movement is applied relative to the world coordinate system.

I think in general you rather want to use

transform.Translate (velocity * Time.deltaTime, Space.World);

or also simply

transform.position += velocity * Time.deltaTime;

and then I would probably do this

miLastPos = transform.position;

after moving the object so the calculation should be more precise and not be based on the last frames delta movement.


问:
statsmodels linear regression model doesn't work because of the "invalid syntax"
I would like to use statsmodels linear regression model, but I have a problem: I get the nex error:

```<code>Traceback (most recent call last):
  File "C:\Users\aleks\PycharmProjects\statistics\econometrics.py", line 95, in <module>
    lr = sm.OLS.from_formula('rj13.2 ~ age+C(rh5)+C(r_diplom)+C(status)+C(rh6)+C(rj1.1.1)',df_stats_models).fit()
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\statsmodels\base\model.py", line 200, in from_formula
    tmp = handle_formula_data(data, None, formula, depth=eval_env,
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\statsmodels\formula\formulatools.py", line 63, in handle_formula_data
    result = dmatrices(formula, Y, depth, return_type='dataframe',
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\highlevel.py", line 309, in dmatrices
    (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env,
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\highlevel.py", line 164, in _do_highlevel_design
    design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env,
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\highlevel.py", line 66, in _try_incr_builders
    return design_matrix_builders([formula_like.lhs_termlist,
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\build.py", line 689, in design_matrix_builders
    factor_states = _factors_memorize(all_factors, data_iter_maker, eval_env)
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\build.py", line 354, in _factors_memorize
    which_pass = factor.memorize_passes_needed(state, eval_env)
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\eval.py", line 474, in memorize_passes_needed
    subset_names = [name for name in ast_names(self.code)
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\eval.py", line 474, in <listcomp>
    subset_names = [name for name in ast_names(self.code)
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\eval.py", line 105, in ast_names
    for node in ast.walk(ast.parse(code)):
  File "C:\Users\aleks\AppData\Local\Programs\Python\Python39\lib\ast.py", line 50, in parse
    return compile(source, filename, mode, flags,
  File "<unknown>", line 1
    C(rj1 .1 .1)
          ^
SyntaxError: invalid syntax
</code>```

My code:

```<code>lr = sm.OLS.from_formula('rj13.2 ~ age+C(rh5)+C(r_diplom)+C(status)+C(rh6)+C(rj1.1.1)',df_stats_models).fit()
print(lr.summary())
</code>```

df_stats_models.head() looks like that:

```<code>Index(['rj13.2', 'rh6', 'rh5', 'r_diplom', 'status', 'rj1.1.1', 'age'], dtype='object')
      rj13.2     rh6      rh5  ...           status                  rj1.1.1   age
46   30000.0  1986.0  МУЖСКОЙ  ...  областной центр  ПОЛНОСТЬЮ УДОВЛЕТВОРЕНЫ  27.0
178  22000.0  1992.0  МУЖСКОЙ  ...            город     СКОРЕЕ УДОВЛЕТВОРЕНЫ  21.0
271  10200.0  1964.0  ЖЕНСКИЙ  ...            город     СКОРЕЕ УДОВЛЕТВОРЕНЫ  49.0
537   6000.0  1952.0  ЖЕНСКИЙ  ...            город     СКОРЕЕ УДОВЛЕТВОРЕНЫ  61.0
538  13000.0  1964.0  ЖЕНСКИЙ  ...            город     СКОРЕЕ УДОВЛЕТВОРЕНЫ  49.0
</code>```

Why does it get angry at C(rj1 .1 .1)?

答:
To read R-style formulas, statsmodels use the patsy package whose parser does not like special characters (like . or -) in the variable names. To "protect" such names, you can use the Q() function (with double quotes for the formula):</p>
```<code>lr = sm.OLS.from_formula("Q('rj13.2') ~ age+C(rh5)+C(r_diplom)+C(status)+C(rh6)+C(Q('rj1.1.1'))", df_stats_models).fit()
</code>```

Body:
I would like to use statsmodels linear regression model, but I have a problem: I get the nex error:

Traceback (most recent call last):
  File "C:\Users\aleks\PycharmProjects\statistics\econometrics.py", line 95, in <module>
    lr = sm.OLS.from_formula('rj13.2 ~ age+C(rh5)+C(r_diplom)+C(status)+C(rh6)+C(rj1.1.1)',df_stats_models).fit()
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\statsmodels\base\model.py", line 200, in from_formula
    tmp = handle_formula_data(data, None, formula, depth=eval_env,
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\statsmodels\formula\formulatools.py", line 63, in handle_formula_data
    result = dmatrices(formula, Y, depth, return_type='dataframe',
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\highlevel.py", line 309, in dmatrices
    (lhs, rhs) = _do_highlevel_design(formula_like, data, eval_env,
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\highlevel.py", line 164, in _do_highlevel_design
    design_infos = _try_incr_builders(formula_like, data_iter_maker, eval_env,
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\highlevel.py", line 66, in _try_incr_builders
    return design_matrix_builders([formula_like.lhs_termlist,
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\build.py", line 689, in design_matrix_builders
    factor_states = _factors_memorize(all_factors, data_iter_maker, eval_env)
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\build.py", line 354, in _factors_memorize
    which_pass = factor.memorize_passes_needed(state, eval_env)
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\eval.py", line 474, in memorize_passes_needed
    subset_names = [name for name in ast_names(self.code)
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\eval.py", line 474, in <listcomp>
    subset_names = [name for name in ast_names(self.code)
  File "C:\Users\aleks\PycharmProjects\statistics\venv\lib\site-packages\patsy\eval.py", line 105, in ast_names
    for node in ast.walk(ast.parse(code)):
  File "C:\Users\aleks\AppData\Local\Programs\Python\Python39\lib\ast.py", line 50, in parse
    return compile(source, filename, mode, flags,
  File "<unknown>", line 1
    C(rj1 .1 .1)
          ^
SyntaxError: invalid syntax

My code:

lr = sm.OLS.from_formula('rj13.2 ~ age+C(rh5)+C(r_diplom)+C(status)+C(rh6)+C(rj1.1.1)',df_stats_models).fit()
print(lr.summary())

df_stats_models.head() looks like that:

Index(['rj13.2', 'rh6', 'rh5', 'r_diplom', 'status', 'rj1.1.1', 'age'], dtype='object')
      rj13.2     rh6      rh5  ...           status                  rj1.1.1   age
46   30000.0  1986.0  МУЖСКОЙ  ...  областной центр  ПОЛНОСТЬЮ УДОВЛЕТВОРЕНЫ  27.0
178  22000.0  1992.0  МУЖСКОЙ  ...            город     СКОРЕЕ УДОВЛЕТВОРЕНЫ  21.0
271  10200.0  1964.0  ЖЕНСКИЙ  ...            город     СКОРЕЕ УДОВЛЕТВОРЕНЫ  49.0
537   6000.0  1952.0  ЖЕНСКИЙ  ...            город     СКОРЕЕ УДОВЛЕТВОРЕНЫ  61.0
538  13000.0  1964.0  ЖЕНСКИЙ  ...            город     СКОРЕЕ УДОВЛЕТВОРЕНЫ  49.0

Why does it get angry at C(rj1 .1 .1)?

Body:
To read R-style formulas, statsmodels use the patsy package whose parser does not like special characters (like . or -) in the variable names. To "protect" such names, you can use the Q() function (with double quotes for the formula):

lr = sm.OLS.from_formula("Q('rj13.2') ~ age+C(rh5)+C(r_diplom)+C(status)+C(rh6)+C(Q('rj1.1.1'))", df_stats_models).fit()


问:
Global.asax.cs Application_BeginRequest - Throw WebFaultException
Is there a way in WCF to check some logic based on the type of Request it receives? Can this be done in the actual service endpoint code?

For example:

After Service Initialization my service receives a PUT Request. In myService.svc.cs I would like to have logic that looks like this:

```<code>if httpRequest.Type == PUT
{
    //Do Something
}
</code>```

Is this possible? I'm sure there is a better way to handle requests than adding logic for every Operation Contract that is of type PUT. Apologies if this question doesn't make sense I'm sort of new to WCF and am trying to learn. Please let me know if you need clarifiers.

EDIT:

This is what myService.svc.cs looks like currently:

```<code>[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public partial class MyService: IMyService
{
    public async Task<someObject> GetMethod1 () // Some GET Method
    {
        doSomethingForGetRequests();
        //method implementation
    }

    public async Task<someObject> GetMethod2 () // Some GET Method
    {
        doSomethingForGetRequests();
        //method implementation
    }

    public async Task<someObject> PutMethod1 () // Some PUTMethod
    {
        doSomethingForPutRequests();
        //method implementation
    }

    doSomethingForPutRequests()
    {
       if(config.IsReadOnly)
       {
           throw new WebFaultException(HttpStatusCode.BadRequest);
       }
    }
}

</code>```

I am wondering if there is a place where i can place doSomethingForGetRequest() and doSomethingForPutRequest() in a central location before the request reaches these methods so I don't have to add these methods to each one of my Service Methods.

Would global.asax.cs Application_BeginRequest() be an appropriate place for this logic?

答:
Maybe a message inspector can help you, it's called on every request that arrives at the service.

IDispatchMessageInspector defines the methods that enable custom inspection or modification of inbound and outbound application messages in service applications.

You can check out these posts:

Detect if action is a POST or GET method

 Call the method automatically for each and every request in the WCF REST

Body:
Is there a way in WCF to check some logic based on the type of Request it receives? Can this be done in the actual service endpoint code?

For example:

After Service Initialization my service receives a PUT Request. In myService.svc.cs I would like to have logic that looks like this:

if httpRequest.Type == PUT
{
    //Do Something
}

Is this possible? I'm sure there is a better way to handle requests than adding logic for every Operation Contract that is of type PUT. Apologies if this question doesn't make sense I'm sort of new to WCF and am trying to learn. Please let me know if you need clarifiers.

EDIT:

This is what myService.svc.cs looks like currently:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public partial class MyService: IMyService
{
    public async Task<someObject> GetMethod1 () // Some GET Method
    {
        doSomethingForGetRequests();
        //method implementation
    }

    public async Task<someObject> GetMethod2 () // Some GET Method
    {
        doSomethingForGetRequests();
        //method implementation
    }

    public async Task<someObject> PutMethod1 () // Some PUTMethod
    {
        doSomethingForPutRequests();
        //method implementation
    }

    doSomethingForPutRequests()
    {
       if(config.IsReadOnly)
       {
           throw new WebFaultException(HttpStatusCode.BadRequest);
       }
    }
}

I am wondering if there is a place where i can place doSomethingForGetRequest() and doSomethingForPutRequest() in a central location before the request reaches these methods so I don't have to add these methods to each one of my Service Methods.

Would global.asax.cs Application_BeginRequest() be an appropriate place for this logic?


问:
How to create a Multi-Column Index or Unique Constraint with NHibernate
How to create a Multi-Column Index and/or Unique Constraint using NHibernate Mapping or Fluent NHibernate.</p>

答:
Old, but I have something to add since I came across this same issue:

Stefan Steinegger answered correctly for non-unique multi-column indexes, but left out the code for unique multi-column indexes. For those you can use:

```<code><property name="A" unique-key="AB" />
<property name="B" unique-key="AB" />
</code>```

So, essentially the same but with a different attribute name.

An interesting thing to note is that for unique indexes, NHibernate generates its own name for the key, but for non-unique indexes it uses whatever you give it.

For example, the above code will NOT generate a unique index named "AB", but rather something like UQ__TableName__7944C87104A02EF4.

This is documented in section 19.1.1 of the NHibernate documentation:

Some tags accept an index attribute for specifying the name of an
  index for that column. A unique-key attribute can be used to group
  columns in a single unit key constraint. Currently, the specified
  value of the unique-key attribute is not used to name the constraint,
  only to group the columns in the mapping file.

However the following:

```<code><property name="A" index="AB" />
<property name="B" index="AB" />
</code>```

will just generate an index named "AB".

ContentLicense: CC BY-SA 2.5

Body:
Old, but I have something to add since I came across this same issue:

Stefan Steinegger answered correctly for non-unique multi-column indexes, but left out the code for unique multi-column indexes. For those you can use:

<property name="A" unique-key="AB" />
<property name="B" unique-key="AB" />

So, essentially the same but with a different attribute name.

An interesting thing to note is that for unique indexes, NHibernate generates its own name for the key, but for non-unique indexes it uses whatever you give it.

For example, the above code will NOT generate a unique index named "AB", but rather something like UQ__TableName__7944C87104A02EF4.

This is documented in section 19.1.1 of the NHibernate documentation:

Some tags accept an index attribute for specifying the name of an
  index for that column. A unique-key attribute can be used to group
  columns in a single unit key constraint. Currently, the specified
  value of the unique-key attribute is not used to name the constraint,
  only to group the columns in the mapping file.

However the following:

<property name="A" index="AB" />
<property name="B" index="AB" />

will just generate an index named "AB".

ContentLicense: CC BY-SA 3.0


问:
Firebase Firestore: Update a field of a document in a subcollection while retrieving information
How can I update a field to a document, while getting the the fields of that document? I am unsure how to do so given my setup. It appears that I can't use .update() with my code as I get an unresolved reference: update error.

```<code>class ReminderActivity : AppCompatActivity() {
    lateinit var reminderID: String

    val db = Firebase.firestore
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_reminder)

        val completeTask: Button = findViewById(R.id.complete_button)
        completeTask.setOnClickListener {
            db.collection("pets").document("vNkkDGAS1oBMpanEXhte").collection("reminders").document(iFdIMKSxJV79Mm64OHwp).get().addOnSuccessListener { document ->
                    val timeStamp = document.get("timestamp") as com.google.firebase.Timestamp
                    val millisec = timestamp.seconds * 1000 +timestamp.nanoseconds/1000000
                    val netDate = Date(millisec)
                    val frequency = document.get("frequency").toString()
                    val cal: Calendar = Calendar.getInstance()
                    cal.time = netDate

                    val time = Timestamp(cal.timeInMillis)
                    document.update({timestamp: time}) //<- line not working
                }
        }
    }
}
</code>```

pictures of cloud firestore database

答: I believe document is of type DocumentSnapshot class and you can't update with this object. Update can only be done from DocumentReference class object. You need to update the implementation for updating the document.

Body:
How can I update a field to a document, while getting the the fields of that document? I am unsure how to do so given my setup. It appears that I can't use .update() with my code as I get an unresolved reference: update error.

class ReminderActivity : AppCompatActivity() {
    lateinit var reminderID: String

    val db = Firebase.firestore
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_reminder)

        val completeTask: Button = findViewById(R.id.complete_button)
        completeTask.setOnClickListener {
            db.collection("pets").document("vNkkDGAS1oBMpanEXhte").collection("reminders").document(iFdIMKSxJV79Mm64OHwp).get().addOnSuccessListener { document ->
                    val timeStamp = document.get("timestamp") as com.google.firebase.Timestamp
                    val millisec = timestamp.seconds * 1000 +timestamp.nanoseconds/1000000
                    val netDate = Date(millisec)
                    val frequency = document.get("frequency").toString()
                    val cal: Calendar = Calendar.getInstance()
                    cal.time = netDate

                    val time = Timestamp(cal.timeInMillis)
                    document.update({timestamp: time}) //<- line not working
                }
        }
    }
}

pictures of cloud firestore database


问:
Vue 3: Setup Script, TS Problem: "An import declaration can only be used in a namespace or module."
when using in Vue 3 the setup script with typescript, I get an error in vscode saying:
"An import declaration can only be used in a namespace or module."

That happens for external libs and own vue components.

i. e.:

```<code><script setup lang="ts">
  // ...

  // ASSETS
  import SvgCircle from '@/assets/img/IconsSvg/SvgCircle.vue';

  // MODELS
  import { IApiParams } from '@/models/api/apiparams.interface
  //  import { EBp } from '@/models/enum/baseParams.enum';

  // LIBS
  import justSafeGet from 'just-safe-get';

  // ...
</script>
</code>```

All these are getting red lines in vscode. Others like import from vue or vue-router or own composables do not get red line.
I do not find something helpful to fix it.

Anybody understands that and has a clue?

答:
I could not repeat the error with enums (in SFC) but with interfaces. That's why I added now an interface import to my description.

After a longer search I found a working solution.

Solution 1: "import type"

import type { IApiParams } from '@/models/api/apiparams.interface'

Solution 2: "Import * as"

import * as IApi from '@/models/api/apiparams.interface';

const apiParmams: IApi.IApiParams = {
    // ...
}
```

Both seem to not throw an error.

Body:
when using in Vue 3 the setup script with typescript, I get an error in vscode saying:
"An import declaration can only be used in a namespace or module."

That happens for external libs and own vue components.

i. e.:

All these are getting red lines in vscode. Others like import from vue or vue-router or own composables do not get red line.
I do not find something helpful to fix it.

Anybody understands that and has a clue?

Body:
I could not repeat the error with enums (in SFC) but with interfaces. That's why I added now an interface import to my description.

After a longer search I found a working solution.

Solution 1: "import type"

import type { IApiParams } from '@/models/api/apiparams.interface'

Solution 2: "Import * as"

import * as IApi from '@/models/api/apiparams.interface';

const apiParmams: IApi.IApiParams = {
    // ...
}

Both seem to not throw an error.


问:
Passing a list on a Python Callable in Airflow
I have a dag that uses a list of CSV files then creates them into a data frame for imports.

```<code>#CREATING CSV FILES
def csv_filess():
    print("Creating CSV files....")
    csv_files = []
    for file in os.listdir(dataset_dir):
        if file.endswith('.csv'):
            csv_files.append(file)
    print("***Step 3: CSV files created***")
    return csv_files

#CREATING DATAFRAME
def create_df(csv_files):
    print("Creating dataframe....")
    df = {}
    for file in csv_files:
        try:
            df[file] = pd.read_csv(data_path+file)
        except UnicodeDecodeError:
            df[file] = pd.read_csv(dataset_dir+file, encoding="ISO-8859-1")

    print("***Step 4: CSV files created in df!***")
    return df

t3 = PythonOperator(
    task_id='create_csv',
    python_callable=csv_filess, provide_context=True,
    dag=dag)

t4 = PythonOperator(
    task_id='create_df',
    python_callable=create_df,
    op_args = t3.output,
    provide_context=True,
    dag=dag)
</code>```

But I get an error:

create_df() takes 1 positional argument but 4 were given

I think it's because I have to put it this way first?:

csv_files = csv_filess()

But how to define that on an Airflow task?

答:
Returning a value from a PythonOperator automatically stores the output as an XCom with key "return_value". So you'll get an XCom from task create_csv with key return_value and value ["file1.csv", "file2.csv", ...]. You can inspect all XComs in Airflow under Admin -> XComs, or per task by clicking a task -> Instance Details -> XCom.

In your create_df task, you then pass the output of create_csv using t3.output. This is a reference to the previously created XCom. When given a list to op_args, Airflow automatically unpacks the list. So you'll have to accept multiple arguments with a * to do the trick:

def create_df(*csv_files):
    ...
```
<p>Two notes:</p>
<p>You might be interested in exploring Airflow's TaskFlow API, which would reduce boilerplate code. Your code would look as:</p>
<pre class="lang-py prettyprint-override"><code>from airflow.decorators import task

with DAG(...) as dag:

    @task
    def csv_filess():
        ...

    @task
    def create_df(csv_files):
        ...

    create_df(csv_filess())
</code>```

(note that here create_df does not require unpacking.

And lastly note that returned values from PythonOperators are automatically stored as XCom (and are by default stored in the Airflow metastore). Fine if intended/custom XCom backend configured, but I'm a bit wary when it comes to returning Pandas DataFrames as these could potentially be very large.

Body:
I have a dag that uses a list of CSV files then creates them into a data frame for imports.

#CREATING CSV FILES
def csv_filess():
    print("Creating CSV files....")
    csv_files = []
    for file in os.listdir(dataset_dir):
        if file.endswith('.csv'):
            csv_files.append(file)
    print("***Step 3: CSV files created***")
    return csv_files

#CREATING DATAFRAME
def create_df(csv_files):
    print("Creating dataframe....")
    df = {}
    for file in csv_files:
        try:
            df[file] = pd.read_csv(data_path+file)
        except UnicodeDecodeError:
            df[file] = pd.read_csv(dataset_dir+file, encoding="ISO-8859-1")

    print("***Step 4: CSV files created in df!***")
    return df

t3 = PythonOperator(
    task_id='create_csv',
    python_callable=csv_filess, provide_context=True,
    dag=dag)

t4 = PythonOperator(
    task_id='create_df',
    python_callable=create_df,
    op_args = t3.output,
    provide_context=True,
    dag=dag)

But I get an error:

create_df() takes 1 positional argument but 4 were given

I think it's because I have to put it this way first?:

csv_files = csv_filess()

But how to define that on an Airflow task?

Body:
Returning a value from a PythonOperator automatically stores the output as an XCom with key "return_value". So you'll get an XCom from task create_csv with key return_value and value ["file1.csv", "file2.csv", ...]. You can inspect all XComs in Airflow under Admin -> XComs, or per task by clicking a task -> Instance Details -> XCom.

In your create_df task, you then pass the output of create_csv using t3.output. This is a reference to the previously created XCom. When given a list to op_args, Airflow automatically unpacks the list. So you'll have to accept multiple arguments with a * to do the trick:

def create_df(*csv_files):
    ...

Two notes:

You might be interested in exploring Airflow's TaskFlow API, which would reduce boilerplate code. Your code would look as:

from airflow.decorators import task

with DAG(...) as dag:

    @task
    def csv_filess():
        ...

    @task
    def create_df(csv_files):
        ...

    create_df(csv_filess())

(note that here create_df does not require unpacking.

And lastly note that returned values from PythonOperators are automatically stored as XCom (and are by default stored in the Airflow metastore). Fine if intended/custom XCom backend configured, but I'm a bit wary when it comes to returning Pandas DataFrames as these could potentially be very large.


问:
Import "spacy" could not be resolved Pylance (reportMissingImports)
I am new to python and I don't have much experience in constructing a good working directory. But in my past experience working with installed packages through pip, I don't have any issues.

I am trying to download, install and import spacy. According to my pip list, I see the spacy package is successfully downloaded. But when I try to create a python document on MS visual studio code, running the code import spacy in my terminal, it says

Import "spacy" could not be resolved Pylance (reportMissingImports).

When I run it on command, it says:

```<code>2021-07-10 15:41:04.164329: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2021-07-10 15:41:04.164530: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
INFO:tensorflow:Enabling eager execution
INFO:tensorflow:Enabling v2 tensorshape
INFO:tensorflow:Enabling resource variables
INFO:tensorflow:Enabling tensor equality
INFO:tensorflow:Enabling control flow v2
</code>```

I wonder if anyone is having a clue on what is going on.

答: You can simply create a requirements.txt file where all your installs are listed. Every time you add something, update the requirements file by running pip freeze > requirements.txt and then when you activate your virtual environment, you can just run py -m pip install -r requirements.txt to fix similar issues with missing imports, etc...

Body:
I am new to python and I don't have much experience in constructing a good working directory. But in my past experience working with installed packages through pip, I don't have any issues.

I am trying to download, install and import spacy. According to my pip list, I see the spacy package is successfully downloaded. But when I try to create a python document on MS visual studio code, running the code import spacy in my terminal, it says

Import "spacy" could not be resolved Pylance (reportMissingImports).

When I run it on command, it says:

2021-07-10 15:41:04.164329: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2021-07-10 15:41:04.164530: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
INFO:tensorflow:Enabling eager execution
INFO:tensorflow:Enabling v2 tensorshape
INFO:tensorflow:Enabling resource variables
INFO:tensorflow:Enabling tensor equality
INFO:tensorflow:Enabling control flow v2

I wonder if anyone is having a clue on what is going on.


问:
What does git remote command 'set-branches' do?
From the documentation, https://git-scm.com/docs/git-remote#Documentation/git-remote.txt-emset-branchesem, it is not clear to me what it actually does.</p>

答:
That was introduced with Git v1.7.2-rc0 in May 2010, commit 3d8b694 with the comment:

Add git remote set-branches

Add ‘git remote set-branches’ for changing the list of tracked refs
for a remote repository with one "porcelain-level" command.

This
complements the longstanding ‘git remote add --track’ option.

The interface is based on the ‘git remote set-url’ subcommand.

```<code>git remote set-branches base --add C
git remote set-branches base A B D
git remote set-branches base --delete D; # not implemented
</code>```

So instead of the default glob refspec for the remote to track all branches under the refs/remotes/<name>/ namespace, a refspec is updated to track only <branch>

```<code>git remote add -t main o2 https://github.com/git/git
</code>```

Would give:

```<code>[remote "o2"]
        url = https://github.com/git/git
        fetch = +refs/heads/main:refs/remotes/o2/main
</code>```

Instead of:

```<code>    fetch = +refs/heads/*:refs/remotes/origin/*
</code>```

Adding a branch would be:

```<code>   git remote set-branches o2 --add master
[remote "o2"]
        url = https://github.com/git/git
        fetch = +refs/heads/main:refs/remotes/o2/main
        fetch = +refs/heads/main:refs/remotes/o2/master
</code>```

Body:
That was introduced with Git v1.7.2-rc0 in May 2010, commit 3d8b694 with the comment:

Add git remote set-branches

Add ‘git remote set-branches’ for changing the list of tracked refs
for a remote repository with one "porcelain-level" command.

This
complements the longstanding ‘git remote add --track’ option.

The interface is based on the ‘git remote set-url’ subcommand.

git remote set-branches base --add C
git remote set-branches base A B D
git remote set-branches base --delete D; # not implemented

So instead of the default glob refspec for the remote to track all branches under the refs/remotes/<name>/ namespace, a refspec is updated to track only <branch>

git remote add -t main o2 https://github.com/git/git

Would give:

[remote "o2"]
        url = https://github.com/git/git
        fetch = +refs/heads/main:refs/remotes/o2/main

Instead of:

    fetch = +refs/heads/*:refs/remotes/origin/*

Adding a branch would be:

   git remote set-branches o2 --add master
[remote "o2"]
        url = https://github.com/git/git
        fetch = +refs/heads/main:refs/remotes/o2/main
        fetch = +refs/heads/main:refs/remotes/o2/master