问:
Pause/user input (warndlg) issue in Matlab GUI
Prior to saving a file I wish to have a Warning Dialog. In the script below there is no stop for pressing the warndlg OK and the script moves automatically continue to the uiputfile. How can I pause between them/enforce user to press the OK before the uiputfile?

Script:

```<code>warndlg('May take time due to image size')
[file,path] = uiputfile('*.tif', 'Save As');
if file == 0
  return;
end
</code>```

答:
You need to either set the createmode option of the warndlg to 'modal':

```<code>warndlg('May take time due to image size', 'Warning!', 'modal');
</code>```

or pass the warndlg handle to the uiwait function to pause continuation of the program until the warning dialog is closed:

```<code>hWarn = warndlg('May take time due to image size');
uiwait(hWarn);
</code>```

Body:
Prior to saving a file I wish to have a Warning Dialog. In the script below there is no stop for pressing the warndlg OK and the script moves automatically continue to the uiputfile. How can I pause between them/enforce user to press the OK before the uiputfile?

Script:

warndlg('May take time due to image size')
[file,path] = uiputfile('*.tif', 'Save As');
if file == 0
  return;
end

Body:
You need to either set the createmode option of the warndlg to 'modal':

warndlg('May take time due to image size', 'Warning!', 'modal');

or pass the warndlg handle to the uiwait function to pause continuation of the program until the warning dialog is closed:

hWarn = warndlg('May take time due to image size');
uiwait(hWarn);


来源: stackexchange

问:
Composer update breaks the website Laravel 5.2
I accidentally run composer update which breaks my website. I am using Laravel 5.2. Now, I am getting this error

```<code>  ErrorException in EventServiceProvider.php line 8:
 Declaration of
 App\Providers\
 EventServiceProvider::boot(Illuminate\Contracts\Events\ Dispatcher $events) should be compatible with
  Illuminate\Foundation\Support\Providers\EventServiceProvider::boot()
</code>```

I tries to remove arguments from EventServiceProvider like this

```<code>  /**
 * Register any other events for your application.
 *
 * @param  \Illuminate\Contracts\Events\Dispatcher  $events
 * @return void
 */
public function boot()
{
    parent::boot();

    //
}
</code>```

EventServiceProvider before changes:

```<code>  <?php

  namespace App\Providers;

  use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
  use Illuminate\Foundation\Support\Providers\EventServiceProvider as
  ServiceProvider;

 class EventServiceProvider extends ServiceProvider
 {
/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'App\Events\SomeEvent' => [
        'App\Listeners\EventListener',
    ],
];
   /**
 * Register any other events for your application.
 *
 * @param  \Illuminate\Contracts\Events\Dispatcher  $events
 * @return void
 */
public function boot(DispatcherContract $events)
{
    parent::boot($events);

    //
}
</code>```

and from RouteServiceProvider.php

```<code> /**
 * Define your route model bindings, pattern filters, etc.
 *
 * @param  \Illuminate\Routing\Router  $router
 * @return void
 */
public function boot()
{
    //

    parent::boot();
}
</code>```

RouteServiceProvider before changes:

```<code>   <?php

   namespace App\Providers;

   use Illuminate\Routing\Router;
   use Illuminate\Foundation\Support\Providers\RouteServiceProvider as
   ServiceProvider;

  class RouteServiceProvider extends ServiceProvider
  {
/**
 * This namespace is applied to your controller routes.
 *
 * In addition, it is set as the URL generator's root namespace.
 *
 * @var string
 */
protected $namespace = 'App\Http\Controllers';

  /**
 * Define your route model bindings, pattern filters, etc.
 *
 * @param  \Illuminate\Routing\Router  $router
 * @return void
 */
public function boot(Router $router)
{
    //

    parent::boot($router);
}
</code>```

Now, I am getting this error:
      BadMethodCallException in Macroable.php line 74:
      Method controllers does not exist.

Please help me. Thank you.

答:
Based on the comments and discussion, you've somehow ended up updating your Laravel framework to 5.3.31 which has breaking changes with 5.2. The solution would to be to either downgrade to the latest version under 5.2 or upgrade the complete application to 5.3 following the upgrade guide.

To fix with the downgrade replace the current framework package in composer.json with "laravel/framework": "5.2.*", and run composer update

ContentLicense: CC BY-SA 3.0

Body:
I accidentally run composer update which breaks my website. I am using Laravel 5.2. Now, I am getting this error

  ErrorException in EventServiceProvider.php line 8:
 Declaration of
 App\Providers\
 EventServiceProvider::boot(Illuminate\Contracts\Events\ Dispatcher $events) should be compatible with
  Illuminate\Foundation\Support\Providers\EventServiceProvider::boot()

I tries to remove arguments from EventServiceProvider like this

  /**
 * Register any other events for your application.
 *
 * @param  \Illuminate\Contracts\Events\Dispatcher  $events
 * @return void
 */
public function boot()
{
    parent::boot();

    //
}

EventServiceProvider before changes:

  <?php

  namespace App\Providers;

  use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
  use Illuminate\Foundation\Support\Providers\EventServiceProvider as
  ServiceProvider;

 class EventServiceProvider extends ServiceProvider
 {
/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'App\Events\SomeEvent' => [
        'App\Listeners\EventListener',
    ],
];
   /**
 * Register any other events for your application.
 *
 * @param  \Illuminate\Contracts\Events\Dispatcher  $events
 * @return void
 */
public function boot(DispatcherContract $events)
{
    parent::boot($events);

    //
}

and from RouteServiceProvider.php

 /**
 * Define your route model bindings, pattern filters, etc.
 *
 * @param  \Illuminate\Routing\Router  $router
 * @return void
 */
public function boot()
{
    //

    parent::boot();
}

RouteServiceProvider before changes:

   <?php

   namespace App\Providers;

   use Illuminate\Routing\Router;
   use Illuminate\Foundation\Support\Providers\RouteServiceProvider as
   ServiceProvider;

  class RouteServiceProvider extends ServiceProvider
  {
/**
 * This namespace is applied to your controller routes.
 *
 * In addition, it is set as the URL generator's root namespace.
 *
 * @var string
 */
protected $namespace = 'App\Http\Controllers';

  /**
 * Define your route model bindings, pattern filters, etc.
 *
 * @param  \Illuminate\Routing\Router  $router
 * @return void
 */
public function boot(Router $router)
{
    //

    parent::boot($router);
}

Now, I am getting this error:
      BadMethodCallException in Macroable.php line 74:
      Method controllers does not exist.

Please help me. Thank you.


问:
Visual Studio Shared Library (Android, iOS) headers not found on mac
I am building a multi-platform library for Android and iOS in Visual Studio 2017 using the 'Shared Library (Android, iOS)' template.

I have properly configured visual studio to pair with my Mac to build the iOS library by following this webpage from Microsoft:

https://blogs.msdn.microsoft.com/vcblog/2015/06/04/developing-cross-platform-ios-applications-using-visual-studio/

Everything works fine. I am able to build the Android and iOS libraries without any problem.

However, I want to add the GLM include headers to my project. To do so, I need to have a copy of the GLM headers on the windows desktop and the mac, and reference the GLM directory on the mac in the 'Local-Remote Directories Map' section in the project settings, as explained in the 'Setting up and editing my iOS code' section in the above link.

My problem is the GLM headers cannot be found on the mac when compiling. I get:

1>/Users/James/.../Renderer.h:8:10: fatal error: 'glm\glm.hpp' file not found.

1>#include <glm\glm.hpp>

1>         ^

Here is a screenshot of 'Local-Remote Directories Map' in the project settings in VS. Which should essentialy replace the directory of GLM on my windows pc to the directory of GLM on the mac.

And here is a print out from the terminal on the mac indicating the location of the GLM headers:

JamesMacBookAir:Libraries James$ ls

glm

JamesMacBookAir:Libraries James$ pwd

/Users/James/Libraries

The android library is compiling without a problem with the GLM headers, but it is being compiled on the windows desktop, not the mac.

Any idea what could be causing this?

Update:

I have just tried putting the glm headers in the same folder as the source files and I am getting the same error on the mac.

答:
Solved it.

I needed to change the backslash in the glm include to a forward slash:

#include <glm\glm.hpp>

to

#include <glm/glm.hpp>


问:
Change string in other class (without making it global) in swift
I would like to modify a string in another class. This class will then use the variable in a function.

Here is what I've tried so far. I always get an error when unwrapping it: fatal error: unexpectedly found nil while unwrapping an Optional value. Does anyone have an idea how to change the urlString (preferably without making it global)? I couldn't find solutions for swift which also involved functions on stackoverflow... If you think I will have to make it global, please let me know!

In class #1

```<code>let videoUrl =  "https:...sometestvideo.mov"
videoPlayerView.urlString = videoUrl
</code>```

In class #2

```<code>var urlString : String?

//setup video player
func setupPlayerView() {

    print(urlString)

    //URL needed here
    if let videoURL = NSURL(string: urlString!){ //here the error occurs
</code>```

I would like to add that it is very important that the function is called asap in the second class. Therefore I didn't use setupPlayerView(_urlString)...

Accordingly it currently looks like this (class 2, a UIView):

```<code>override init(frame: CGRect){

    super.init(frame: frame)

    //function below this override init
    setupPlayerView()
</code>```

EDIT:

First of all, thank you for your solution! Nonetheless, one little problem remains (and I thought calling the function immediately would solve it... quite new to swift): namely the video player (which is set up using this function) is now above all the other subviews (one can only see the video covering the entire screen) although the opposite is desired (video using entire screen but subviews cover some parts). I will provide more code below regarding the addition of other subviews (all of these are closures) and the function setting up the view. Is there a way I can keep the videoplayer below all the other subviews (even if it needs to be loaded from a server first)? What would you suggest me to do?

Code below incorporates code from the first answer, but does not necessarily have to start from there

Class 2

```<code>override init(frame: CGRect){

    super.init(frame: frame)

    setupPlayerView()

    //add subview with controls (e.g. spinner)
    controlsContainerView.frame = frame
    addSubview(controlsContainerView)

    //add to subview and center spinner in subview
    controlsContainerView.addSubview(activityIndicatorView)
    activityIndicatorView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    activityIndicatorView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    //add various subviews
    controlsContainerView.addSubview(whiteDummyView)
    controlsContainerView.addSubview(userProfilePicture)
    //... add further subviews

    //enable interaction
    controlsContainerView.isUserInteractionEnabled = true
    //... set to true for other subviews as well

    //function below this override init
    defInteractions()

    //backgorund color of player
    backgroundColor = .black

}

//create controls container view (a closure, like the (most of the) other subviews)
let controlsContainerView: UIView = {

    //set properties of controls container view
    let controlView = UIView()
    controlView.backgroundColor = UIColor(white: 0, alpha: 1)

    return controlView

}()
</code>```

function setupPlayerView()

```<code>//setup video player
func setupPlayerView() {

    //check URL if can be converted to NSURL
    if let urlString = self.urlString, let videoURL = NSURL(string: urlString){

        print(urlString)

        //player's video
        if self.player == nil {
            player = AVPlayer(url: videoURL as URL)
        }

        //add sub-layer
        let playerLayer = AVPlayerLayer(player: player)
        self.controlsContainerView.layer.addSublayer(playerLayer)
        playerLayer.frame = self.frame

        //when are frames actually rendered (when is video loaded)
        player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)

        //loop through video
        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: nil, using: { (_) in
            DispatchQueue.main.async {
                self.player?.seek(to: kCMTimeZero)
                self.player?.play()
            }
        })

    }

}
</code>```

答:
Without too much context about the relationship between your classes, looks like a potentially good solution is to use a property observer pattern.</p>

```<code>class Class2 {
    var urlString: String? {
        didSet {
            setupPlayerView()
        }
    }

    override init(frame: CGRect){
        super.init(frame: frame)
        setupPlayerView()
    }

    func setupPlayerView() {
        if let urlString = self.urlString, let videoURL = NSURL(string: urlString) {
            // do stuff here
        }
    }
}
</code>```

Body:
I would like to modify a string in another class. This class will then use the variable in a function.

Here is what I've tried so far. I always get an error when unwrapping it: fatal error: unexpectedly found nil while unwrapping an Optional value. Does anyone have an idea how to change the urlString (preferably without making it global)? I couldn't find solutions for swift which also involved functions on stackoverflow... If you think I will have to make it global, please let me know!

In class #1

let videoUrl =  "https:...sometestvideo.mov"
videoPlayerView.urlString = videoUrl

In class #2

var urlString : String?

//setup video player
func setupPlayerView() {

    print(urlString)

    //URL needed here
    if let videoURL = NSURL(string: urlString!){ //here the error occurs

I would like to add that it is very important that the function is called asap in the second class. Therefore I didn't use setupPlayerView(_urlString)...

Accordingly it currently looks like this (class 2, a UIView):

override init(frame: CGRect){

    super.init(frame: frame)

    //function below this override init
    setupPlayerView()

EDIT:

First of all, thank you for your solution! Nonetheless, one little problem remains (and I thought calling the function immediately would solve it... quite new to swift): namely the video player (which is set up using this function) is now above all the other subviews (one can only see the video covering the entire screen) although the opposite is desired (video using entire screen but subviews cover some parts). I will provide more code below regarding the addition of other subviews (all of these are closures) and the function setting up the view. Is there a way I can keep the videoplayer below all the other subviews (even if it needs to be loaded from a server first)? What would you suggest me to do?

Code below incorporates code from the first answer, but does not necessarily have to start from there

Class 2

override init(frame: CGRect){

    super.init(frame: frame)

    setupPlayerView()

    //add subview with controls (e.g. spinner)
    controlsContainerView.frame = frame
    addSubview(controlsContainerView)

    //add to subview and center spinner in subview
    controlsContainerView.addSubview(activityIndicatorView)
    activityIndicatorView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    activityIndicatorView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    //add various subviews
    controlsContainerView.addSubview(whiteDummyView)
    controlsContainerView.addSubview(userProfilePicture)
    //... add further subviews

    //enable interaction
    controlsContainerView.isUserInteractionEnabled = true
    //... set to true for other subviews as well

    //function below this override init
    defInteractions()

    //backgorund color of player
    backgroundColor = .black

}

//create controls container view (a closure, like the (most of the) other subviews)
let controlsContainerView: UIView = {

    //set properties of controls container view
    let controlView = UIView()
    controlView.backgroundColor = UIColor(white: 0, alpha: 1)

    return controlView

}()

function setupPlayerView()

//setup video player
func setupPlayerView() {

    //check URL if can be converted to NSURL
    if let urlString = self.urlString, let videoURL = NSURL(string: urlString){

        print(urlString)

        //player's video
        if self.player == nil {
            player = AVPlayer(url: videoURL as URL)
        }

        //add sub-layer
        let playerLayer = AVPlayerLayer(player: player)
        self.controlsContainerView.layer.addSublayer(playerLayer)
        playerLayer.frame = self.frame

        //when are frames actually rendered (when is video loaded)
        player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)

        //loop through video
        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: nil, using: { (_) in
            DispatchQueue.main.async {
                self.player?.seek(to: kCMTimeZero)
                self.player?.play()
            }
        })

    }

}

Body:
Without too much context about the relationship between your classes, looks like a potentially good solution is to use a property observer pattern.

class Class2 {
    var urlString: String? {
        didSet {
            setupPlayerView()
        }
    }

    override init(frame: CGRect){
        super.init(frame: frame)
        setupPlayerView()
    }

    func setupPlayerView() {
        if let urlString = self.urlString, let videoURL = NSURL(string: urlString) {
            // do stuff here
        }
    }
}


问:
Cucumber Capybara scroll to bottom of page
I'd like to use my Cucumber/Capybara setup to test endless scroll by driving a browser and scrolling to the bottom of the page to ensure that the new content is loaded.  Is there a way to do this?</p>

答: I solved this with visit '#footer' inside a "scroll to the bottom of the page" step.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
My javascript doesn't give any output and when i reload the page it crashes
This is my code and when run instead of a black box containing my game in the centre of the screen there is just a gap and no website can seem to tell me where I went wrong:

console.log("start")
//Global functions
var canvas = document.getElementById("canva");
var canvasCon;
var snakeX = 400;
var snakeY = 300;
var direction;
var snakeSpeed = 1;
var apple = false;
var appleX;
var appleY
var snakeSize = 30;
var scoreboard = document.getElementById("score");
var Score = 0;
var trailX = new Array();
var trailY = new Array();

console.log("set global variables!")

window.onload = function(){
    console.log("ran on window load function")
    canvasCon = canvas.getContext('2d');

    //Calls "drawing" and "move" fps times per second
    var fps = 30
    setInterval(function(){
        move()
        drawing()
    },1000/fps);
}

document.addEventListener('keydown', getKey);
function getKey(event){
    //gets the keycode
    direction = event.keyCode;
    return direction;
    }

//moves the objsects
function move(){
    //creates a easier to read way to check the value of getKey
    var left = 37;
    var up = 38;
    var right = 39;
    var down = 40;

    //changing the position of the snake
    switch(direction){
        case right:
            snakeX = snakeX + snakeSpeed;
            break;
        case left:
            snakeX = snakeX - snakeSpeed;
            break;
        case up:
            snakeY = snakeY - snakeSpeed;
            break;
        case down:
            snakeY = snakeY + snakeSpeed;
            break;
    }
    trail()
    //checks if snake has gone off the board and then moves the snake to the other end of the board if that returns True
    if(snakeX > canvas.width){
        snakeX = 0
    }else if(snakeX < 0){
        snakeX = canvas.width
    }

    if(snakeY > canvas.height){
        snakeY = 0
    }else if(snakeY < 0){
        snakeY = canvas.height
    }
}

//draws everything /w updated coordinates
function drawing(){

    //Backround of the Game
    canvasCon.fillStyle = 'black';
    canvasCon.fillRect(0,0,canvas.width,canvas.height);

    //The snake
    canvasCon.fillStyle = 'green';
    canvasCon.fillRect(snakeX,snakeY,snakeSize,snakeSize);

    //apple creation
    apples()
    canvasCon.fillStyle = 'red';
    canvasCon.fillRect(appleX,appleY,25,25);
}

//makes the apples work
function apples(){
    if(collision()){
        Score += 1
        console.log(Score)
        scoreboard.innerHTML = "Score: "+Score+""
        apple = false
    }
    if(apple == false){
        apple = true
        appleX = Math.floor(Math.random() * (canvas.width - 50));
        appleY = Math.floor(Math.random() * (canvas.height - 50));
    }

}
function collision(){
    var distX = Math.abs(appleX - snakeX-snakeSize/2);
  var distY = Math.abs(appleY - snakeY-snakeSize/2);
  if (distX <= (snakeSize/2) && distY <= (snakeSize/2)) { return true; }
}
function trail(){
    //adds X and Y coordinates to their respective lists
    trailX.push(snakeX)
    trailY.push(snakeY)
    //makes sure the lists are the right length
    while(trailX.length > Score){
        var index = trailX.indexOf(0);
        trailX.splice(index, 1);
    }
    while(trailY.length > Score){
        var index = trailY.indexOf(0);
        trailY.splice(index, 1);
    }
    if(trailY.length != trailX.length){
        console.log("trailY != trailX")
    }
    for(i= trailX.length-1; i<=0; i--){
        canvasCon.fillStyle = 'yellow';
        canvasCon.fillRect(trailX[i],trailY[i],25,25);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><title>SNAKE!!</title>

<body>
<p style="text-align:center; text-color:red"><b>Hope you Enjoy Ma GREAT GAME!!</b></p>
<br/><br/><br/>
<div style="width:800px; margin:0 auto;">
<canvas id=canva width="800" height="600"></canvas>
<br/>
<p id="score">Score: </p>
</div>
</body></code>```

whenever the page gets reloaded even on jsfiddle.net it crashes.
plz help I have no idea what i did wrong!

答:
First rule of JS - if it is stuck, you probably have an endless loop.

And indeed You have an endless loop with your final for:

```<code>for(i= trailX.length-1; i<=0; i--){
        canvasCon.fillStyle = 'yellow';
        canvasCon.fillRect(trailX[i],trailY[i],25,25);
    }
</code>```

i<=0

If i start with 0 and goes down by 1 each iteration, it will always be less or equal to 0 so the end condition will never be met.

Body:
This is my code and when run instead of a black box containing my game in the centre of the screen there is just a gap and no website can seem to tell me where I went wrong:

console.log("start")
//Global functions
var canvas = document.getElementById("canva");
var canvasCon;
var snakeX = 400;
var snakeY = 300;
var direction;
var snakeSpeed = 1;
var apple = false;
var appleX;
var appleY
var snakeSize = 30;
var scoreboard = document.getElementById("score");
var Score = 0;
var trailX = new Array();
var trailY = new Array();

console.log("set global variables!")

window.onload = function(){
    console.log("ran on window load function")
    canvasCon = canvas.getContext('2d');

    //Calls "drawing" and "move" fps times per second
    var fps = 30
    setInterval(function(){
        move()
        drawing()
    },1000/fps);
}

document.addEventListener('keydown', getKey);
function getKey(event){
    //gets the keycode
    direction = event.keyCode;
    return direction;
    }

//moves the objsects
function move(){
    //creates a easier to read way to check the value of getKey
    var left = 37;
    var up = 38;
    var right = 39;
    var down = 40;

    //changing the position of the snake
    switch(direction){
        case right:
            snakeX = snakeX + snakeSpeed;
            break;
        case left:
            snakeX = snakeX - snakeSpeed;
            break;
        case up:
            snakeY = snakeY - snakeSpeed;
            break;
        case down:
            snakeY = snakeY + snakeSpeed;
            break;
    }
    trail()
    //checks if snake has gone off the board and then moves the snake to the other end of the board if that returns True
    if(snakeX > canvas.width){
        snakeX = 0
    }else if(snakeX < 0){
        snakeX = canvas.width
    }

    if(snakeY > canvas.height){
        snakeY = 0
    }else if(snakeY < 0){
        snakeY = canvas.height
    }
}

//draws everything /w updated coordinates
function drawing(){

    //Backround of the Game
    canvasCon.fillStyle = 'black';
    canvasCon.fillRect(0,0,canvas.width,canvas.height);

    //The snake
    canvasCon.fillStyle = 'green';
    canvasCon.fillRect(snakeX,snakeY,snakeSize,snakeSize);

    //apple creation
    apples()
    canvasCon.fillStyle = 'red';
    canvasCon.fillRect(appleX,appleY,25,25);
}

//makes the apples work
function apples(){
    if(collision()){
        Score += 1
        console.log(Score)
        scoreboard.innerHTML = "Score: "+Score+""
        apple = false
    }
    if(apple == false){
        apple = true
        appleX = Math.floor(Math.random() * (canvas.width - 50));
        appleY = Math.floor(Math.random() * (canvas.height - 50));
    }

}
function collision(){
    var distX = Math.abs(appleX - snakeX-snakeSize/2);
  var distY = Math.abs(appleY - snakeY-snakeSize/2);
  if (distX <= (snakeSize/2) && distY <= (snakeSize/2)) { return true; }
}
function trail(){
    //adds X and Y coordinates to their respective lists
    trailX.push(snakeX)
    trailY.push(snakeY)
    //makes sure the lists are the right length
    while(trailX.length > Score){
        var index = trailX.indexOf(0);
        trailX.splice(index, 1);
    }
    while(trailY.length > Score){
        var index = trailY.indexOf(0);
        trailY.splice(index, 1);
    }
    if(trailY.length != trailX.length){
        console.log("trailY != trailX")
    }
    for(i= trailX.length-1; i<=0; i--){
        canvasCon.fillStyle = 'yellow';
        canvasCon.fillRect(trailX[i],trailY[i],25,25);
    }
}

<title>SNAKE!!</title>

Hope you Enjoy Ma GREAT GAME!!

<canvas id=canva width="800" height="600"></canvas>

Score:

whenever the page gets reloaded even on jsfiddle.net it crashes.
plz help I have no idea what i did wrong!

Body:
First rule of JS - if it is stuck, you probably have an endless loop.

And indeed You have an endless loop with your final for:

for(i= trailX.length-1; i<=0; i--){
        canvasCon.fillStyle = 'yellow';
        canvasCon.fillRect(trailX[i],trailY[i],25,25);
    }

i<=0

If i start with 0 and goes down by 1 each iteration, it will always be less or equal to 0 so the end condition will never be met.


问:
read data file with mixed numbers and texts in r
I have data files that contain the following:
the first 10 columns are numbers, the last column is text. They are separated by space. The problem is that the text in the last column may also contain space. So when I used read.table() I got the following error:

```<code>Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
line 21 did not have 11 elements
</code>```

what's the easiest way of reading the first 10 columns into a data matrix, and the last column into a string vector? Should I use readLines() first then process it?

答:
If you cannot re-export or recreate your data files with different, non-whitespace separators or with quotation marks around the last column to avoid that problem, you can use read.table(... , fill = TRUE) to read in a file with unequal columns and then combine columns 11+ with dat$col11 <- do.call(paste, c(dat[11:nrow(dat)], sep=" ")) (or something like that) and then drop the now unwanted columns with dat[11:(nrow(dat)-1)] <- NULL. Finally, you may need to trim the whitespace from the end of the eleventh column with trimws(dat$col11).

Note that fill only considers the first five lines of your file, so you may need to find out the number of 'pseudo-columns' in the longest line manually and specify an appropriate number of col.names in read.table (see the linked answer).

Body:
I have data files that contain the following:
the first 10 columns are numbers, the last column is text. They are separated by space. The problem is that the text in the last column may also contain space. So when I used read.table() I got the following error:

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
line 21 did not have 11 elements

what's the easiest way of reading the first 10 columns into a data matrix, and the last column into a string vector? Should I use readLines() first then process it?


问:
Can you use LINQ or lambdas to perform matrix operations?
I know how to do this using for loops.  Is it possible to do something like this using LINQ or lambdas?</p>

```<code>int[] a = { 10, 20, 30 };
int[] b = { 2, 4, 10 };
int[] c = a * b; //resulting array should be { 20, 80, 300 }
</code>```

答:
You can write a simple extension that works with matrices of any rank.

```<code>public static class TwodimensionalArrayExtensions
{
    public static int[][] MultiplyBy(this int[][] leftMatrix, int[][] rightMatrix)
    {
        if (leftMatrix[0].Length != rightMatrix.Length)
        {
            return null; // Matrices are of incompatible dimensions
        }

        return leftMatrix.Select( // goes through <leftMatrix matrix> row by row

                (leftMatrixRow, leftMatrixRowIndexThatIsNotUsed) =>

                    rightMatrix[0].Select( // goes through first row of <rightMatrix> cell by cell

                            (rightFirstRow, rightMatrixColumnIndex) =>

                                rightMatrix
                                    .Select(rightRow => rightRow[rightMatrixColumnIndex]) // selects column from <rightMatrix> for <rightMatrixColumnIndex>
                                    .Zip(leftMatrixRow, (rowCell, columnCell) => rowCell * columnCell) // does scalar product
                                    .Sum() // computes the sum of the products (rowCell * columnCell) sequence.
                        )
                        .ToArray() // the new cell within computed matrix
            )
            .ToArray(); // the computed matrix itself
    }
}
</code>```

Here are some test values:

```<code>// Test1
int[][] A = { new[] { 1, 2, 3 } };
int[][] B = { new[] { 1 }, new[] { 2 }, new[] { 3 } };
int[][] result = A.MultiplyBy(B);
</code>```

```<code>// Test2
int[][] A = { new[] { 1 }, new[] { 2 }, new[] { 3 } };
int[][] B = { new[] { 1, 2, 3 } };
int[][] result = A.MultiplyBy(B);
</code>```

```<code>// Test3
int[][] A = new int[][] { new[] { 1, 2 }, new[] { 2, 2 }, new[] { 3, 1 } };
int[][] B = new int[][] { new[] { 1, 1, 1 }, new[] { 2, 3, 2 } };
int[][] result = A.MultiplyBy(B);
</code>```

OwnerDisplayName: Jason Z

Body:
I know how to do this using for loops.  Is it possible to do something like this using LINQ or lambdas?

int[] a = { 10, 20, 30 };
int[] b = { 2, 4, 10 };
int[] c = a * b; //resulting array should be { 20, 80, 300 }

Body:
You can write a simple extension that works with matrices of any rank.

public static class TwodimensionalArrayExtensions
{
    public static int[][] MultiplyBy(this int[][] leftMatrix, int[][] rightMatrix)
    {
        if (leftMatrix[0].Length != rightMatrix.Length)
        {
            return null; // Matrices are of incompatible dimensions
        }

        return leftMatrix.Select( // goes through <leftMatrix matrix> row by row

                (leftMatrixRow, leftMatrixRowIndexThatIsNotUsed) =>

                    rightMatrix[0].Select( // goes through first row of <rightMatrix> cell by cell

                            (rightFirstRow, rightMatrixColumnIndex) =>

                                rightMatrix
                                    .Select(rightRow => rightRow[rightMatrixColumnIndex]) // selects column from <rightMatrix> for <rightMatrixColumnIndex>
                                    .Zip(leftMatrixRow, (rowCell, columnCell) => rowCell * columnCell) // does scalar product
                                    .Sum() // computes the sum of the products (rowCell * columnCell) sequence.
                        )
                        .ToArray() // the new cell within computed matrix
            )
            .ToArray(); // the computed matrix itself
    }
}

Here are some test values:

// Test1
int[][] A = { new[] { 1, 2, 3 } };
int[][] B = { new[] { 1 }, new[] { 2 }, new[] { 3 } };
int[][] result = A.MultiplyBy(B);

// Test2
int[][] A = { new[] { 1 }, new[] { 2 }, new[] { 3 } };
int[][] B = { new[] { 1, 2, 3 } };
int[][] result = A.MultiplyBy(B);

// Test3
int[][] A = new int[][] { new[] { 1, 2 }, new[] { 2, 2 }, new[] { 3, 1 } };
int[][] B = new int[][] { new[] { 1, 1, 1 }, new[] { 2, 3, 2 } };
int[][] result = A.MultiplyBy(B);


问:
Combination of a list with permutations of another list
I have two lists:

```<code>object = ['square','circle','triangle']
description = ['red','green']
</code>```

I want as output a list of dictionaries:

```<code>{'square': 'red', 'circle': 'red', 'triangle': 'red'}
{'square': 'red', 'circle': 'red', 'triangle': 'green'}
{'square': 'green', 'circle': 'red', 'triangle': 'green'}
</code>```

etc.

So the objects don't repeat, but the descriptions may. Each dictionary has as its keys the original list of objects.

I'm not sure of the name of the algorithm I want, so I'm having trouble finding the correct one. (I've looked at permutations of two lists in python, but that's seeking a different result. Permutations of two lists is the same question, but using OCAML.)

答:
You could use itertools.product to generate all possible combinations of your descriptions.

Then create a dictionary with the objects as keys and the "combination" as values:

```<code>>>> import itertools

>>> objects = ['square','circle','triangle']
>>> description = ['red','green']

>>> [dict(zip(objects, comb)) for comb in itertools.product(description, repeat=len(objects))]
[{'circle': 'red', 'square': 'red', 'triangle': 'red'},
 {'circle': 'red', 'square': 'red', 'triangle': 'green'},
 {'circle': 'green', 'square': 'red', 'triangle': 'red'},
 {'circle': 'green', 'square': 'red', 'triangle': 'green'},
 {'circle': 'red', 'square': 'green', 'triangle': 'red'},
 {'circle': 'red', 'square': 'green', 'triangle': 'green'},
 {'circle': 'green', 'square': 'green', 'triangle': 'red'},
 {'circle': 'green', 'square': 'green', 'triangle': 'green'}]
</code>```

Body:
I have two lists:

object = ['square','circle','triangle']
description = ['red','green']

I want as output a list of dictionaries:

{'square': 'red', 'circle': 'red', 'triangle': 'red'}
{'square': 'red', 'circle': 'red', 'triangle': 'green'}
{'square': 'green', 'circle': 'red', 'triangle': 'green'}

etc.

So the objects don't repeat, but the descriptions may. Each dictionary has as its keys the original list of objects.

I'm not sure of the name of the algorithm I want, so I'm having trouble finding the correct one. (I've looked at permutations of two lists in python, but that's seeking a different result. Permutations of two lists is the same question, but using OCAML.)

Body:
You could use itertools.product to generate all possible combinations of your descriptions.

Then create a dictionary with the objects as keys and the "combination" as values:

>>> import itertools

>>> objects = ['square','circle','triangle']
>>> description = ['red','green']

>>> [dict(zip(objects, comb)) for comb in itertools.product(description, repeat=len(objects))]
[{'circle': 'red', 'square': 'red', 'triangle': 'red'},
 {'circle': 'red', 'square': 'red', 'triangle': 'green'},
 {'circle': 'green', 'square': 'red', 'triangle': 'red'},
 {'circle': 'green', 'square': 'red', 'triangle': 'green'},
 {'circle': 'red', 'square': 'green', 'triangle': 'red'},
 {'circle': 'red', 'square': 'green', 'triangle': 'green'},
 {'circle': 'green', 'square': 'green', 'triangle': 'red'},
 {'circle': 'green', 'square': 'green', 'triangle': 'green'}]


问:
How do I spyOn Typescript getters and setters?
When I unit test my getters are setters for Typescript, I cannot find a way to spy on those getters and setters. Instead, the object immediately gets evaluated. I am using Jasmine to unit test.</p>

答:
spyOnProperty is now available in Jasmine:

```<code>const foop = {
    get value() {},
    set value(v) {}
};

it('can spy on getter', () => {
    spyOnProperty(foop, 'value', 'get').and.returnValue(1);
    expect(foop.value).toBe(1);
});

it('and on setters', () => {
    const spiez = spyOnProperty(foop, 'value', 'set');
    foop.value = true;
    expect(spiez).toHaveBeenCalled();
});
</code>```

Body:
spyOnProperty is now available in Jasmine:

const foop = {
    get value() {},
    set value(v) {}
};

it('can spy on getter', () => {
    spyOnProperty(foop, 'value', 'get').and.returnValue(1);
    expect(foop.value).toBe(1);
});

it('and on setters', () => {
    const spiez = spyOnProperty(foop, 'value', 'set');
    foop.value = true;
    expect(spiez).toHaveBeenCalled();
});


问:
what is the use of if else statements?
I don't quite understand the meaning of else if statements.

why not just to continue with the if statements in case one is false?

it works the same.

example with if only that will work the same with else if:

```<code>function testSize(num) {

  if (num < 5){

     return "Tiny";
  }

  if (num < 10){

    return "small";
  }

  return "Change Me";

}

testSize(7);
</code>```

答:
Well, there is a bit different from this two statement.Consider the follow samples

```<code>if(a > 0) {
 ...
}
if( a == 0) {
...
}
if(a < 0) {
...
}
</code>```

and

```<code>if(a > 0) {
   ...
}
else if( a == 0) {
   ...
}
else if(a < 0) {
   ...
}
</code>```

when a is zero the last else if statement will not be execute while if need to compare third time.If a equals to 10, else if could be execute once while if is third.From this else if statement could be execute less and let your program a bit fast.

Title: what is the use of if else statements?

Body:
I don't quite understand the meaning of else if statements.

why not just to continue with the if statements in case one is false?

it works the same.

example with if only that will work the same with else if:

function testSize(num) {

  if (num < 5){

     return "Tiny";
  }

  if (num < 10){

    return "small";
  }

  return "Change Me";

}

testSize(7);

Body:
Well, there is a bit different from this two statement.Consider the follow samples

if(a > 0) {
 ...
}
if( a == 0) {
...
}
if(a < 0) {
...
}

and

if(a > 0) {
   ...
}
else if( a == 0) {
   ...
}
else if(a < 0) {
   ...
}

when a is zero the last else if statement will not be execute while if need to compare third time.If a equals to 10, else if could be execute once while if is third.From this else if statement could be execute less and let your program a bit fast.


问:
Tornado WSGI Unittest
I have an ongoing project in Google App Engine, and it uses Tornado as the web framework. That being said, I'm not sure how to do an Unittest with Tornado using WSGI mode. Can someone please give me some examples how should I write an unittest for Tornado using WSGI?</p>

答:
You can test this by ignoring either half of the equation:

Tornado's WSGI mode doesn't allow any of the things that make regular Tornado apps tricky to test, so you can use App Engine's testing tools to test the app in the same way you would with any other WSGI framework (I don't know App Engine well enough to give you any pointers here)

Or you can ignore the App Engine part and use Tornado's testing tools instead. You can test the Application before wrapping it in WSGIAdapter (if you're using WSGIApplication, I recommend switching to a regular tornado.web.Application and WSGIAdapter instead) using Tornado's AsyncHTTPTestCase

Title: Tornado WSGI Unittest


问:
SQL 2005 - quick way to quickly duplicate a database + data
I have my development database, I want to spin off a duplicate for testing.  I want to do this often.

What's the fastest and easiest way to do this often?  I can get the job done by generating scripts w/ data included but I feel like there must be a better way.  Should I back up database 1 then screw around with it so I can restore it as a different name?

答:
I would use scripts, as this aids transparency of what you're doing.

(Especially if you want to do it often, as changes are each one will have slightly different data.)

However if you don't want to go to the hassle of creating the scripts, the easiest way is to backup and then restore to a different name.

OwnerDisplayName: BPAndrew

OwnerDisplayName: Bravax


问:
Upnp: list portmappings
I'm currently looking at the miranda upnp tool (http://code.google.com/p/mirandaupnptool/). Is there a way for upnp to list all portmappings. I was able to forward ports an delete portmappings but I couldn't find a way to list all mappings.

I've read somewhere that this mac os x tool does list all portmappings on your router

答: Some devices support the GetGenericPortMappingEntry method.</p>

Title: Upnp: list portmappings


问:
How to count users per group assuming many-to-many relation?
I have two tables users and groups, as well as a third table that defines many-to-many relationship users_groups:

Table "group":

```<code>CREATE TABLE `group` (
  `ID` int(11) NOT NULL,
  `creation_date` date NOT NULL,
  `type` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `group` (`ID`, `creation_date`, `type`) VALUES
(1, '2017-06-01', 'AAA'),
(2, '2017-06-01', 'BBB'),
(3, '2017-06-01', 'CCC');
</code>```

Table "user":

```<code>CREATE TABLE `user` (
  `ID` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `surnames` varchar(100) NOT NULL,
  `birthdate` date NOT NULL,
  `qualification` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user` (`ID`, `name`, `surnames`, `birthdate`, `qualification`) VALUES
(1, 'xxx', 'xxx', '1989-03-03', 'A'),
(2, 'xxx', 'xxx', '1990-06-15', 'A'),
(3, 'xxx', 'xxx', '1982-06-14', 'B'),
(4, 'xxx', 'xxx', '1988-06-19', 'B'),
(5, 'xxx', 'xxx', '1984-03-12', 'B'),
(6, 'xxx', 'xxx', '1987-12-19', 'C');
</code>```

Table "users_groups":

```<code>CREATE TABLE `user_group` (
  `ID` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `group_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user_group` (`ID`, `user_id`, `group_id`) VALUES
(1, 1, 1),
(2, 2, 1),
(3, 3, 2),
(4, 4, 2),
(5, 5, 2),
(6, 6, 3);
</code>```

I need to count the number of users per group and summarize results as follows:

```<code>ID   creation_date    type   users_count_per_group
1    2017-06-01       AAA    2
2    2017-06-01       BBB    3
3    2017-06-01       CCC    1
</code>```

This is my current query. I get stuck with many-to-many relation, which means that the same user may appear in different groups (though in my sample data all users appear just once per group):

```<code>SELECT `group`.`ID`, `group`.`creation_date`, `group`.`type`, COUNT(*)
FROM `group`, `user`, `user_group`
WHERE `group`.`ID`=`user_group`.`group_id`
      AND `user`.`ID`=`user_group`.`user_id`;
</code>```

答:
You do not need to join in the users table to do what you want.  So, the query only requires one join:

```<code>SELECT g.id, g.creation_date, g.type, COUNT(*) as users_count_per_group
FROM `group` g JOIN
     user_group ug
     ON g.id = ug.group_id
GROUP BY g.id, g.creation_date, g.type;
</code>```

Addition notes:

group is a really bad name for a table, because it is a SQL keyword.  I name tables in the plural, which general avoids this problem.

Table aliases make the query easier to write and to read.

Backticks make the query harder to write and to read.

Body:
I have two tables users and groups, as well as a third table that defines many-to-many relationship users_groups:

Table "group":

CREATE TABLE `group` (
  `ID` int(11) NOT NULL,
  `creation_date` date NOT NULL,
  `type` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `group` (`ID`, `creation_date`, `type`) VALUES
(1, '2017-06-01', 'AAA'),
(2, '2017-06-01', 'BBB'),
(3, '2017-06-01', 'CCC');

Table "user":

CREATE TABLE `user` (
  `ID` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `surnames` varchar(100) NOT NULL,
  `birthdate` date NOT NULL,
  `qualification` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user` (`ID`, `name`, `surnames`, `birthdate`, `qualification`) VALUES
(1, 'xxx', 'xxx', '1989-03-03', 'A'),
(2, 'xxx', 'xxx', '1990-06-15', 'A'),
(3, 'xxx', 'xxx', '1982-06-14', 'B'),
(4, 'xxx', 'xxx', '1988-06-19', 'B'),
(5, 'xxx', 'xxx', '1984-03-12', 'B'),
(6, 'xxx', 'xxx', '1987-12-19', 'C');

Table "users_groups":

CREATE TABLE `user_group` (
  `ID` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `group_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `user_group` (`ID`, `user_id`, `group_id`) VALUES
(1, 1, 1),
(2, 2, 1),
(3, 3, 2),
(4, 4, 2),
(5, 5, 2),
(6, 6, 3);

I need to count the number of users per group and summarize results as follows:

ID   creation_date    type   users_count_per_group
1    2017-06-01       AAA    2
2    2017-06-01       BBB    3
3    2017-06-01       CCC    1

This is my current query. I get stuck with many-to-many relation, which means that the same user may appear in different groups (though in my sample data all users appear just once per group):

SELECT `group`.`ID`, `group`.`creation_date`, `group`.`type`, COUNT(*)
FROM `group`, `user`, `user_group`
WHERE `group`.`ID`=`user_group`.`group_id`
      AND `user`.`ID`=`user_group`.`user_id`;

Body:
You do not need to join in the users table to do what you want.  So, the query only requires one join:

SELECT g.id, g.creation_date, g.type, COUNT(*) as users_count_per_group
FROM `group` g JOIN
     user_group ug
     ON g.id = ug.group_id
GROUP BY g.id, g.creation_date, g.type;

Addition notes:

group is a really bad name for a table, because it is a SQL keyword.  I name tables in the plural, which general avoids this problem.

Table aliases make the query easier to write and to read.

Backticks make the query harder to write and to read.


问:
C++ vector element erase versus new vector creation
I'm working with a vector of elements that need to be selected at random and effectively removed until either either a condition is met, or until all the elements have been selected. However, they won't actually be removed until some later stage in code execution, so I need to maintain a list of valid, available elements. I can erase elements from this second vector, or I can recreate it each time. Please see a minimal version of my code below showing the example of where the vector is created each time in a while loop:

```<code>    Random mRandom; // Pseudo-random number generator
    std::vector< Element* > mElements;
    for( unsigned index = 0; index < ARBITRARY_VALUE; index++ )
      mElements.push_back( new Element( ) );

    std::vector< bool > removedElements;
    bool condition = true;

    while( condition == true ) {
      std::vector< unsigned > availableIndices;

      for( unsigned index = 0; index < mElements.size( ); index++ ) {
        if( removedElements[ index ] == false )
          availableIndices.push_back( index );
      }

      if( availableIndices.size( ) > 0 ) {
        unsigned maximum = availableIndices.size( ) - 1;
        unsigned randomIndex = mRandom.GetUniformInt( maximum ); // Zero to max
        removedElements[ availableIndices[ randomIndex ] ] = true;
        Element* element = mElements[ availableIndices[ randomIndex ] ];
        condition = element->DoStuff( ); // May change condition and exit while
      } else
        break;
    }
</code>```

It's clear that erasing an element in the middle of a vector requires the underlying system to iterate through the remaining elements and 'move' them to their new, valid position. Obviously that means fewer iterations if the erased elements are near the end of a vector.

I've read a few posts regarding the costs associated with erasing vector elements, but I haven't seen anything that directly addresses my question. Does the process of 'moving' elements following an erasure introduce overheads that could make it cheaper to iterate through all of the elements every time by creating a new vector that points to the valid ones? As in my code example above.

Cheers, Phil

答:
The problem of random elimination of elements presented by you seems to me solvable only in O(n^2) time and O(n) space complexity. Because you have to pass all the elements once and on each pass you have to find a random index in a sequence of still existing elements and maintain this sequence. There might be few approaches with different algorithmic primitives. Below I present my solution that archives this goal while doing that in a CPU/memory operation friendly way.

```<code>void runRandomTasks() {
  Random mRandom; // Pseudo-random number generator
  std::vector<Element*> mElements;
  for (unsigned index = 0; index < ARBITRARY_VALUE; ++index) {
    mElements.push_back(new Element);
  }
  size_t current_size = mElements.size();
  if (!current_size)
    return;
  std::vector<Element*> current_elements(current_size, nullptr);
  for (unsigned index = 0; index < current_size; ++index) {
    current_elements[index] = mElements[index];
  }
  Element** last_ptr = &current_elements[0] + current_size - 1;

  bool condition = true;

  while (condition && current_size) {
    unsigned random_size = mRandom.GetUniformInt(current_size - 1) + 1; // Zero to max
    Element** ptr = last_ptr;
    while (true) {
      random_size -= (bool)(*ptr);
      if (random_size) {
        --ptr;
      } else {
        break;
      }
    }

    condition = (*ptr)->DoStuff(); // May change condition and exit while
    *ptr = nullptr;
    --current_size;
  }
}
</code>```

Concerning your question of vector element erasure, you can find in my solution that there is a loop of finding a random index, that is equivalent to element erasure in a vector in time complexity but with a smaller constant since the element shifting is omitted, instead the element value is checked to be 0 or not. Doing any memory allocation in a loop is always costly, so avoid that.

Body:
I'm working with a vector of elements that need to be selected at random and effectively removed until either either a condition is met, or until all the elements have been selected. However, they won't actually be removed until some later stage in code execution, so I need to maintain a list of valid, available elements. I can erase elements from this second vector, or I can recreate it each time. Please see a minimal version of my code below showing the example of where the vector is created each time in a while loop:

    Random mRandom; // Pseudo-random number generator
    std::vector< Element* > mElements;
    for( unsigned index = 0; index < ARBITRARY_VALUE; index++ )
      mElements.push_back( new Element( ) );

    std::vector< bool > removedElements;
    bool condition = true;

    while( condition == true ) {
      std::vector< unsigned > availableIndices;

      for( unsigned index = 0; index < mElements.size( ); index++ ) {
        if( removedElements[ index ] == false )
          availableIndices.push_back( index );
      }

      if( availableIndices.size( ) > 0 ) {
        unsigned maximum = availableIndices.size( ) - 1;
        unsigned randomIndex = mRandom.GetUniformInt( maximum ); // Zero to max
        removedElements[ availableIndices[ randomIndex ] ] = true;
        Element* element = mElements[ availableIndices[ randomIndex ] ];
        condition = element->DoStuff( ); // May change condition and exit while
      } else
        break;
    }

It's clear that erasing an element in the middle of a vector requires the underlying system to iterate through the remaining elements and 'move' them to their new, valid position. Obviously that means fewer iterations if the erased elements are near the end of a vector.

I've read a few posts regarding the costs associated with erasing vector elements, but I haven't seen anything that directly addresses my question. Does the process of 'moving' elements following an erasure introduce overheads that could make it cheaper to iterate through all of the elements every time by creating a new vector that points to the valid ones? As in my code example above.

Cheers, Phil

Body:
The problem of random elimination of elements presented by you seems to me solvable only in O(n^2) time and O(n) space complexity. Because you have to pass all the elements once and on each pass you have to find a random index in a sequence of still existing elements and maintain this sequence. There might be few approaches with different algorithmic primitives. Below I present my solution that archives this goal while doing that in a CPU/memory operation friendly way.

void runRandomTasks() {
  Random mRandom; // Pseudo-random number generator
  std::vector<Element*> mElements;
  for (unsigned index = 0; index < ARBITRARY_VALUE; ++index) {
    mElements.push_back(new Element);
  }
  size_t current_size = mElements.size();
  if (!current_size)
    return;
  std::vector<Element*> current_elements(current_size, nullptr);
  for (unsigned index = 0; index < current_size; ++index) {
    current_elements[index] = mElements[index];
  }
  Element** last_ptr = &current_elements[0] + current_size - 1;

  bool condition = true;

  while (condition && current_size) {
    unsigned random_size = mRandom.GetUniformInt(current_size - 1) + 1; // Zero to max
    Element** ptr = last_ptr;
    while (true) {
      random_size -= (bool)(*ptr);
      if (random_size) {
        --ptr;
      } else {
        break;
      }
    }

    condition = (*ptr)->DoStuff(); // May change condition and exit while
    *ptr = nullptr;
    --current_size;
  }
}

Concerning your question of vector element erasure, you can find in my solution that there is a loop of finding a random index, that is equivalent to element erasure in a vector in time complexity but with a smaller constant since the element shifting is omitted, instead the element value is checked to be 0 or not. Doing any memory allocation in a loop is always costly, so avoid that.


问:
Simple JWT authentication in ASP.NET Core 1.0 Web API
I'm looking for the simplest way to setup a Web API server that uses JWTs for authentication in ASP.NET Core (aka ASP.NET 5). This project (blog post / github) does exactly what I'm looking for but it uses ASP.NET 4.

I just want to be able to:

setup a login route that can create a JWT token and return it in the header. I'm integrating this with an existing RESTful service that will tell me if the username and password are valid. In the ASP.NET 4 project I'm looking at this could be done with the following route https://github.com/stewartm83/Jwt-WebApi/blob/master/src/JwtWebApi/Controllers/AccountController.cs#L24-L54

Intercept incoming requests to routes that require authorization, decrypt and validate the JWT token coming in the header and make the user information in the JWT token's payload accessible to the route. e.g. something like this: https://github.com/stewartm83/Jwt-WebApi/blob/master/src/JwtWebApi/App_Start/AuthHandler.cs

All of the examples I've seen in ASP.NET Core are very complex and rely on some or all of OAuth, IS, OpenIddict, and EF which I would like to avoid.

Can anyone point me towards an example of how to do this in ASP.NET Core or help me get started with this?

EDIT: Answer
I ended up using this answer: https://stackoverflow.com/a/33217340/373655

答:
There is a full example for ASP.NET Core + JWT Auth + SQL Server + Swagger: https://github.com/wilsonwu/netcoreauth

Hope this can help you.


问:
Filtering a list of item components based on string property, without case-sensitivity
I have this code, which generates item components, from my list of objects (Frivillig)

```<code><app-frivillig-item
  *ngFor="let frivilligEl of frivillige"
  [frivillig]="frivilligEl">
</app-frivillig-item>
</code>```

I now want to add a search field, which should dynamically change the list to whatever the user types. The list contains an array of objects, which each has several string properties. I only want to filter the list based on a single of these string properties. A property is a match if each character in the search text exists in the property at the same index (case-insensitive).

The list itself is located in a service, which is injected into the list component that instantiates the item components with *ngFor:

```<code>frivillige: Frivillig[]
</code>```

This is my input field so far. It is currently 2-way bound to a string property in my list component:

```<code><input type="text" class="form-control" id="id" placeholder="Søg efter
frivillig..." [(ngModel)]="term">
</code>```

I am unsure how to approach this problem. I have tried using pipes, but found it confusing to implement, when the list is not just a set of strings. Let me know if you need more information.

答:
You could filter in your component by maintaining a separate list of filtered items:

Template:

```<code><app-frivillig-item
  *ngFor="let frivilligEl of filteredList"
  [frivillig]="frivilligEl">
</app-frivillig-item>

<input type="text" [(ngModel)]="term" (ngModelChange)="onChange()"/>
</code>```

Component:

```<code>export class YourComponent {
  public term: string;

  // Initialize the filtered list to the complete list
  public filteredList = this.frivillige;

  public onChange() {
    // If nothing is in the search box, return to the complete list
    if (!this.term) {
      this.filteredList = this.frivillige;

      return;
    }

    // Filter the list for items that have the same characters at the same
    // indices as this.term (case-insensitive)
    this.filteredList = this.frivillige.filter(item => {
        return item.YOUR_PROPERTY.substring(0, this.term.length).toLowerCase() === this.term.toLowerCase();
    });
  }
}
</code>```

Body:
I have this code, which generates item components, from my list of objects (Frivillig)

<app-frivillig-item
  *ngFor="let frivilligEl of frivillige"
  [frivillig]="frivilligEl">
</app-frivillig-item>

I now want to add a search field, which should dynamically change the list to whatever the user types. The list contains an array of objects, which each has several string properties. I only want to filter the list based on a single of these string properties. A property is a match if each character in the search text exists in the property at the same index (case-insensitive).

The list itself is located in a service, which is injected into the list component that instantiates the item components with *ngFor:

frivillige: Frivillig[]

This is my input field so far. It is currently 2-way bound to a string property in my list component:

<input type="text" class="form-control" id="id" placeholder="Søg efter
frivillig..." [(ngModel)]="term">

I am unsure how to approach this problem. I have tried using pipes, but found it confusing to implement, when the list is not just a set of strings. Let me know if you need more information.

Body:
You could filter in your component by maintaining a separate list of filtered items:

Template:

<app-frivillig-item
  *ngFor="let frivilligEl of filteredList"
  [frivillig]="frivilligEl">
</app-frivillig-item>

<input type="text" [(ngModel)]="term" (ngModelChange)="onChange()"/>

Component:

export class YourComponent {
  public term: string;

  // Initialize the filtered list to the complete list
  public filteredList = this.frivillige;

  public onChange() {
    // If nothing is in the search box, return to the complete list
    if (!this.term) {
      this.filteredList = this.frivillige;

      return;
    }

    // Filter the list for items that have the same characters at the same
    // indices as this.term (case-insensitive)
    this.filteredList = this.frivillige.filter(item => {
        return item.YOUR_PROPERTY.substring(0, this.term.length).toLowerCase() === this.term.toLowerCase();
    });
  }
}


问:
Best Way to Implement Tags (Similar to StackOverflow)

Possible Duplicate:

  How do you recommend implementing tags or tagging

I have a website with a database that contains a number of articles. I'd like to implement tags similar to the tags on stackoverflow.

I can think of two basic ways to implement them:

Create a separate Tags table with a one-to-many relationship with my Articles table.

Add a Tags text field to my Articles table.

The first approach seems the best but would require two additional tables that would grow quite large. It seems like there would also be considerable overhead updating and maintaining that data.

The second approach would be far easier to implement and maintain, and use less resources. But searching would be less efficient. I'd probably use LIKE or maybe even full-text searching.

I'm interested in which approach others think is best. Or perhaps there another approach altogether.

答:
The first option is clearly the best of the two.  This works with the relational model, and leaves your data normalized.  The second option works against the relational model, and breaks normalization.  How are you going to run queries such as "give me the top 10 most popular tags"?  Or "how many times has the tag 'x' been used?"  These queries become trivial with option 1, especially as (assuming Robb's schema) you can keep a Count column against each tag.

Option 2 gains you a slight simplification for a great loss in functionality (and in the long run, I contend, efficiency too).  The relational model is tried, tested and works! Use it!


问:
PHP - take element from array and push it at the beginning
Is there a simple way to take specific array element, and place it at the beginning of the array?

For example I have this array:

```<code>$array = [

    [
        'name' => 'Jon Doe',
        'age'  => 44,
        'sex'  => 'm'
    ],
    [
        'name' => 'Joana Doe',
        'age'  => 44,
        'sex'  => 'f'
    ],
    [
        'name' => 'Jon Doe',
        'age'  => 44,
        'sex'  => 'm'
    ],
    [
        'name' => 'Some Name',
        'age'  => 44,
        'sex'  => 'f'
    ],
    [
        'name' => 'Another Name',
        'age'  => 44,
        'sex'  => 'f'
    ],

];
</code>```

and I want to take array where name is Some Name, and place it at the beginning  of the array.

答:
If you want to search by value and reindex the array, then something like that should do.</p>

```<code>function searchForId($name, $array) {
   foreach ($array as $key => $val) {
       if ($val['name'] === $name) {
           return $key;
       }
   }
   return null;
}
$id = searchForId('name', $array);
if($id !== null) {
   $tmp = $array[$id];
   unset($array[$id]);
   $array = array_values($array);
   array_unshift($array, $tmp);
}
</code>```

Body:
Is there a simple way to take specific array element, and place it at the beginning of the array?

For example I have this array:

$array = [

    [
        'name' => 'Jon Doe',
        'age'  => 44,
        'sex'  => 'm'
    ],
    [
        'name' => 'Joana Doe',
        'age'  => 44,
        'sex'  => 'f'
    ],
    [
        'name' => 'Jon Doe',
        'age'  => 44,
        'sex'  => 'm'
    ],
    [
        'name' => 'Some Name',
        'age'  => 44,
        'sex'  => 'f'
    ],
    [
        'name' => 'Another Name',
        'age'  => 44,
        'sex'  => 'f'
    ],

];

and I want to take array where name is Some Name, and place it at the beginning  of the array.

Body:
If you want to search by value and reindex the array, then something like that should do.

function searchForId($name, $array) {
   foreach ($array as $key => $val) {
       if ($val['name'] === $name) {
           return $key;
       }
   }
   return null;
}
$id = searchForId('name', $array);
if($id !== null) {
   $tmp = $array[$id];
   unset($array[$id]);
   $array = array_values($array);
   array_unshift($array, $tmp);
}


问:
what is the solution for Crystal Report Filter option in C#
i'm using asp.net/c# with crystal report to export as PDF format, it is exporting Pdf fine. but we refereed the DB Table to Crystal Report so it is binding all data's to report not filter by parameter or select Formula model.

Here is My Code:

```<code>ReportDocument myreportdocument = new ReportDocument();
            DataSet dsReport = new DataSet();
            clsiCMSBLBase omenu = new clsiCMSBLBase();
            string errMsg = string.Empty;
            dsReport = omenu.GetListData(ref errMsg, parameters, "DBSP_PCPrintSlipRDLC");

            myreportdocument = ReportFactory.GetReport(myreportdocument.GetType());
            myreportdocument.Load(Server.MapPath("~/CrysReports/PCPrintSlipPUD.rpt"));

            myreportdocument.SetParameterValue("UserID", Convert.ToInt32(2));
            myreportdocument.SetDataSource(dsReport);

            string dbUserName = ConfigurationManager.AppSettings["CrystalUserName"];
            string dbPassword = ConfigurationManager.AppSettings["CrystalPassword"];
            myreportdocument.SetDatabaseLogon(dbUserName, dbPassword);

            cRY1.ReportSource = myreportdocument;
            cRY1.SelectionFormula = " {TMP_PlotPCSlip.UserID} =" + 2;
            cRY1.ReportSource = myreportdocument;
            cRY1.HasCrystalLogo = false;
            cRY1.DataBind();
            cRY1.RefreshReport();
            cRY1.BorderColor = System.Drawing.Color.Gray;
            cRY1.BorderWidth = 1;
            cRY1.BackColor = System.Drawing.Color.White;
            cRY1.Style.Add("width", "100%");

            //string filename = fact + "_" + flag + "_" + DateTime.Now.ToString("dd-MM-yyyy-HH-mm") + ".pdf";
            myreportdocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, filename);
            Response.End();
</code>```

this Filter Code not filtering:

```<code>myreportdocument.SetParameterValue("UserID", Convert.ToInt32(2));
</code>```

even i tried TableName.UserID but there is also not filter, so please share your experience..

Body:
i'm using asp.net/c# with crystal report to export as PDF format, it is exporting Pdf fine. but we refereed the DB Table to Crystal Report so it is binding all data's to report not filter by parameter or select Formula model.

Here is My Code:

ReportDocument myreportdocument = new ReportDocument();
            DataSet dsReport = new DataSet();
            clsiCMSBLBase omenu = new clsiCMSBLBase();
            string errMsg = string.Empty;
            dsReport = omenu.GetListData(ref errMsg, parameters, "DBSP_PCPrintSlipRDLC");

            myreportdocument = ReportFactory.GetReport(myreportdocument.GetType());
            myreportdocument.Load(Server.MapPath("~/CrysReports/PCPrintSlipPUD.rpt"));

            myreportdocument.SetParameterValue("UserID", Convert.ToInt32(2));
            myreportdocument.SetDataSource(dsReport);

            string dbUserName = ConfigurationManager.AppSettings["CrystalUserName"];
            string dbPassword = ConfigurationManager.AppSettings["CrystalPassword"];
            myreportdocument.SetDatabaseLogon(dbUserName, dbPassword);

            cRY1.ReportSource = myreportdocument;
            cRY1.SelectionFormula = " {TMP_PlotPCSlip.UserID} =" + 2;
            cRY1.ReportSource = myreportdocument;
            cRY1.HasCrystalLogo = false;
            cRY1.DataBind();
            cRY1.RefreshReport();
            cRY1.BorderColor = System.Drawing.Color.Gray;
            cRY1.BorderWidth = 1;
            cRY1.BackColor = System.Drawing.Color.White;
            cRY1.Style.Add("width", "100%");

            //string filename = fact + "_" + flag + "_" + DateTime.Now.ToString("dd-MM-yyyy-HH-mm") + ".pdf";
            myreportdocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, filename);
            Response.End();

this Filter Code not filtering:

myreportdocument.SetParameterValue("UserID", Convert.ToInt32(2));

even i tried TableName.UserID but there is also not filter, so please share your experience..

Body: Myreportdocument.RecordSelectionFormula="{table.column}=2"


问:
Why does my ternary operator give a different result to an if else?
The problem I am having is I am trying to use ternary operators over if else for smaller code but when using it in my case it is returning a different result than if I use an if else.

The problem code is below;

If Else

```<code>if(string.IsNullOrEmpty(jn["LARM"].Value))
            pm.ItemLeftArm = null;
        else
            pm.ItemLeftArm = jn["LARM"];
</code>```

Ternary

```<code>pm.ItemLeftArm = string.IsNullOrEmpty(jn["LARM"].Value) ? null : jn["LARM"];
</code>```

The jn["LARM"] is a json node from simpleJSON and it is either a number e.g. "0" or nothing e.g. "".

It returns null form the if else but it returns the jn object which transforms from "" into 0.

Im not sure why Im getting this issue.

答:
The code is ok, the problem must be in the JSON. Have you tried logging the jn["LARM"].Value just before the terniary operator in order to be sure that the value is null/empty or not?

BTW, why are you using simpleJSON instead of the new Unity integrated JsonUtility?

Body:
The problem I am having is I am trying to use ternary operators over if else for smaller code but when using it in my case it is returning a different result than if I use an if else.

The problem code is below;

If Else

if(string.IsNullOrEmpty(jn["LARM"].Value))
            pm.ItemLeftArm = null;
        else
            pm.ItemLeftArm = jn["LARM"];

Ternary

pm.ItemLeftArm = string.IsNullOrEmpty(jn["LARM"].Value) ? null : jn["LARM"];

The jn["LARM"] is a json node from simpleJSON and it is either a number e.g. "0" or nothing e.g. "".

It returns null form the if else but it returns the jn object which transforms from "" into 0.

Im not sure why Im getting this issue.


问:
Change HTML Content using jQuery 3, then change it back
Basically, what I want to do:
When you press the button #change, the content in the div #board has to change to nothing but:

```<code><h2>Hi!</h2>
<button type="button" onclick="ChangeAgain();">
</code>```

Then when you click that button, it has to change back to what it used to be, that is:

```<code><h2>Welcome to this page.</h2>
<p>It's quite boring in here. Why don't you click the button?</p>
<button onClick="Change();">Button for you to Click</button>
</code>```

Here's my JavaScript (jQuery 3.2.1), which is not working.

```<code>$(function () {
  var inThere = "";
  function Change() {
    inThere += $("#board").html();
    $("#board").html("<h2>Hi!</h2> \n
    <button type=\"button\" onclick=\"ChangeAgain();\">")
  }
  function ChangeAgain () {
    $("#board").html(inThere);
  }
})
</code>```

答:
Your functions are not available in the global namespace, which is considered a good practice. But due to this you should not call a function from your HTML, but listen to the click event of your button in your code:

$(function() {
    var inThere = "";
    var changed = false;
    var $board = $("#board");

    $board.on("click", "button", function() {
        if (changed) {
             $board.html(inThere);
        } else {
            inThere = $board.html();
            $board.html("
Hi!
<button>Button for you to Click</button>");
        }

        changed = !changed;
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board">
  <h2>Welcome to this page.</h2>
  <p>It's quite boring in here. Why don't you click the button?</p>
  <button>Button for you to Click</button>
</div></code>```

Body:
Basically, what I want to do:
When you press the button #change, the content in the div #board has to change to nothing but:

Hi!

<button type="button" onclick="ChangeAgain();">

Then when you click that button, it has to change back to what it used to be, that is:

Welcome to this page.

It's quite boring in here. Why don't you click the button?

<button onClick="Change();">Button for you to Click</button>

Here's my JavaScript (jQuery 3.2.1), which is not working.

$(function () {
  var inThere = "";
  function Change() {
    inThere += $("#board").html();
    $("#board").html("
Hi!
 \n
    <button type=\"button\" onclick=\"ChangeAgain();\">")
  }
  function ChangeAgain () {
    $("#board").html(inThere);
  }
})

Body:
Your functions are not available in the global namespace, which is considered a good practice. But due to this you should not call a function from your HTML, but listen to the click event of your button in your code:

$(function() {
    var inThere = "";
    var changed = false;
    var $board = $("#board");

    $board.on("click", "button", function() {
        if (changed) {
             $board.html(inThere);
        } else {
            inThere = $board.html();
            $board.html("<h2>Hi!</h2><button>Button for you to Click</button>");
        }

        changed = !changed;
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board">
  <h2>Welcome to this page.</h2>
  <p>It's quite boring in here. Why don't you click the button?</p>
  <button>Button for you to Click</button>
</div>


问:
Indexing in MATLAB with vectors
I am trying to index a matrix (image read with imread()) with vectors for row and column numbers.

map is the image read with imread(), and rows and columns are the 1-dimensional index vectors.

But when I do map(rows, columns) it returns a 2-dimensional matrix, where I presume it is using every single permutation of rows and columns to index map.

How do I index map with each corresponding element at (rows,columns)?

I believe the answer I am looking for is equivalent to diag( map(rows,columns ) but it's a bit inefficient I think.

答:
If I got you right what you want is to extract a vector of pixels where each pixel is a combination of row and column index.

If I got you right, the way to do it is using sub2ind.

You can do something like that (Assuming Image is Grayscale Image):

```<code>vPixelIdx = sub2ind(size(mInputImage), vRowsIdx, vColIdx);
vPixels = mInputImage(vPixelIdx);
</code>```

I didn't test it as I don't have access to MATLAB now, but it should work.

Title: Indexing in MATLAB with vectors

Body:
If I got you right what you want is to extract a vector of pixels where each pixel is a combination of row and column index.

If I got you right, the way to do it is using sub2ind.

You can do something like that (Assuming Image is Grayscale Image):

vPixelIdx = sub2ind(size(mInputImage), vRowsIdx, vColIdx);
vPixels = mInputImage(vPixelIdx);

I didn't test it as I don't have access to MATLAB now, but it should work.


问:
Execute PHP code using javascript confirm method
I know PHP runs on the server while JS runs on the client, but I also know it's possible to do this during input validation:

```<code><?php
echo "<script type=\"text/javascript\">window.alert('Please enter a valid number.');
window.location.href = '/index.html';</script>";
exit;
?>
</code>```

So I'm wondering, is it possible for me to use the Javascript confirm method to do something like this on button click:

```<code><?php
    echo "<script type=\"text/javascript\">var q = confirm('Are you sure you want to exit?.');
    //if q == true {  //ok is clicked
      window.location.href = '/page_x.php';
    } else { //cancel is clicked
      window.location.href = '/index.php';</script>";
    exit;
    ?>
</code>```

I don't know much about Javascript. I just want a simple way to execute PHP code on button click, but using Javascript confirm dialog. When the button is clicked, it asks the user whether they wish to continue (or something) or not. If they click Ok, they are taken to some php page. If they click Cancel, nothing happens, the dialog just exits.

I have searched round the web (even on StackOverFlow) for a solution, and everyone points to Ajax or JQuery, and I don't know how to use either.

So I was thinking in the line of using something as simple as the pseudo code I posted above, but I don't know if it's legal to do that, and even if it is, I don't know how.

Any help would be greatly appreciated.

答:
Well first, the confirm is a JS function so you can only treat it on JS level. If you are willing execute anything php from JS after confirmation you need to make an AJAX call.

Although, everything you have written in that answer is correct on technical level.

```<code> echo "
<script type=\"text/javascript\">
 var q = confirm('Are you sure you want to exit?.');
    if q == true
      window.location.href = '/page_x.php'; //THIS IS JAVASCRIPT so it is fine
    else
      window.location.href = '/index.php'; //THIS IS JAVASCRIPT so it is fine
</script>";
</code>```

Body:
I know PHP runs on the server while JS runs on the client, but I also know it's possible to do this during input validation:

<?php
echo "";
exit;
?>

So I'm wondering, is it possible for me to use the Javascript confirm method to do something like this on button click:

<?php
    echo "";
    exit;
    ?>

I don't know much about Javascript. I just want a simple way to execute PHP code on button click, but using Javascript confirm dialog. When the button is clicked, it asks the user whether they wish to continue (or something) or not. If they click Ok, they are taken to some php page. If they click Cancel, nothing happens, the dialog just exits.

I have searched round the web (even on StackOverFlow) for a solution, and everyone points to Ajax or JQuery, and I don't know how to use either.

So I was thinking in the line of using something as simple as the pseudo code I posted above, but I don't know if it's legal to do that, and even if it is, I don't know how.

Any help would be greatly appreciated.

Body:
Well first, the confirm is a JS function so you can only treat it on JS level. If you are willing execute anything php from JS after confirmation you need to make an AJAX call.

Although, everything you have written in that answer is correct on technical level.

 echo "
<script type=\"text/javascript\">
 var q = confirm('Are you sure you want to exit?.');
    if q == true
      window.location.href = '/page_x.php'; //THIS IS JAVASCRIPT so it is fine
    else
      window.location.href = '/index.php'; //THIS IS JAVASCRIPT so it is fine
</script>";


问:
How to get which pointer points to a specific object in c/c++？
I want to know which pointers point to a specific object at runtime in c/c++.

For example, I have an object A, now I want to do something for A, such as changing the memory address of A, at this moment I have to know there are how many pointer pointing to A, and,at least, the name of these pointers at runtime.

In fact I just want to realize the migration of an object or some data else, without making the program wrong. Because in c/c++ if I want to migrate an object A I must figure out how many pointer pointing to the object A, and than make these pointer pointing to the new address which is the address of the object A after migration.

Totally speaking, it likes the std::shared_ptr, and I also have realized a self-defined class to achieve this goal. But now, I just want to know are there some ways to achieve this goal by using some compiler tools such as LLVM, and without modifying the source code or modifying the source automatically.

*******problem description**********

In fact, I have two types of memory, typeA and typeB, and now I want to realize a function which can migrate an object X in typeA to typeB. To make sure the validity of programs, after migrating object X form typeA to typeB,I have to know how many pointers point to the object X and than make these pointers pointing to the new address of object X.

答:
I want to know which pointers point to a specific object at runtime in c/c++.

In general this is not possible. BTW, it looks that you want to implement something quite similar to a precise copying garbage collector. If this is not clear to you, read the GC handbook (for the concepts and the terminology). Notice that variables (and their names) don't exist at runtime (only memory locations, perhaps on the call stack, are relevant then) but only at compile time.

Totally speaking, it likes the std::shared_ptr, and I also have realized a self-defined class to achieve this goal. But now, I just want to know are there some ways to achieve this goal by using some compiler tools such as LLVM, and without modifying the source code or modifying the source automatically.

Again, in general that is not possible. For an intuition about why, imagine that you deal with a union { Foo* fooptr; std::uintptr foonum; }; which is in fact discriminated by some arbitrary external property, like e.g. the oddness of your current pid. If you could solve that you have solved the halting problem. Read also about Rice's theorem. Both are very relevant for static source code analysis.

However, what you could do is define explicitly some additional strong coding rules and constraints, (perhaps with some support runtime library) and design and implement, e.g. with LLVM or some GCC plugin, a static analyzer which check against these coding rules and constraints.

Notice that in practice you can use some GCs with C++, e.g. Boehm's GC or

Ravenbrook's MPS.

Your question is still lacking a real motivation (which I am trying to guess) and looks like some XY problem. "Like a GC" is not enough.

See also this. Perhaps read about dynamic software updating or application checkpointing.

addenda

your problem (even with the problem description edit, I don't understand it well) looks similar to copying garbage collection techniques like Cheney's algorithm.


问:
Parsing a string containing a date in a specific format into a Date object in Javascript
I'm learning Javascript as a new language, and I figured a good way to get used to how JS handles reg exp and string manipulation is to parse a string containing a date into a Date object.

I have a string in the form "2005-05-28".  What is the best Javascript-y way to parse that into a Date object?

答:
Non-RegExp

I don't know about "best", but you don't need a regex:

```<code>var str = "2005-05-28";
var parts = str.split("-");
var dt = new Date(parseInt(parts[0], 10),
                  parseInt(parts[1], 10) - 1,
                  parseInt(parts[2], 10));
</code>```

Live example

That uses String#split to break the string on the - characters, then the Date constructor that accepts year, month (starting with 0), and day (starting with 1).

RegExp

Mind you, if you really want to use a regexp, you can:

```<code>var str = "2005-05-28";
var parts = str.match(/^(\d{1,4})-(\d{1,2})-(\d{1,2})$/);
if (parts) {
    var dt = new Date(parseInt(parts[1], 10),
                      parseInt(parts[2], 10) - 1,
                      parseInt(parts[3], 10));
}
</code>```

Live example

That uses a regex with capture groups, doing the match via String#match, which returns an array with the full match at index 0 followed by the capture groups. But for my money, the regex isn't really buying you anything.

Beyond

If your date strings get more complicated or may vary, I'd look at farming the problem out to a library like DateJS. But if your format is that regular, you're golden.

Body:
Non-RegExp

I don't know about "best", but you don't need a regex:

var str = "2005-05-28";
var parts = str.split("-");
var dt = new Date(parseInt(parts[0], 10),
                  parseInt(parts[1], 10) - 1,
                  parseInt(parts[2], 10));

Live example

That uses String#split to break the string on the - characters, then the Date constructor that accepts year, month (starting with 0), and day (starting with 1).

RegExp

Mind you, if you really want to use a regexp, you can:

var str = "2005-05-28";
var parts = str.match(/^(\d{1,4})-(\d{1,2})-(\d{1,2})$/);
if (parts) {
    var dt = new Date(parseInt(parts[1], 10),
                      parseInt(parts[2], 10) - 1,
                      parseInt(parts[3], 10));
}

Live example

That uses a regex with capture groups, doing the match via String#match, which returns an array with the full match at index 0 followed by the capture groups. But for my money, the regex isn't really buying you anything.

Beyond

If your date strings get more complicated or may vary, I'd look at farming the problem out to a library like DateJS. But if your format is that regular, you're golden.


问:
Multiplying Columns in SAS using loop condition
Table from SAS

In this table, the Trans_Date column continues up to 31/07/2016.

How do I multiply the Value column to the Rate column (currency exchange for AUD in terms of NZD, CAD, GBP as seen in currency_conv for a particular date) under a loop to display the Value of each Order_Number only in AUD?

The Currency column should only be in terms AUD.

答:
Are you asking take the AUD conversion rate for each day for each currency and multiply each entry accordingly?

For that you might try the following:

First, create a new table:

```<code>proc sql noprint;
create table rates as
select * from table
where Currency = 'AUD'
order by Trans_date;
quit;

data rates;
set rates;
by Trans_date;
output;
if last.Trans_date then do;
  currency_conv = 'AUD';
  rate = 1.;
  output;
end;
run;
</code>```

now join tables:

```<code>proc sql noprint;
create table as newTable
select a.*,a.value*b.rate as newValue
from table as a
left join (select * from rates) as b
on a.Trans_date = b.Trans_date
and a.currency = b.currency_conv;
quit;
</code>```

Body:
Are you asking take the AUD conversion rate for each day for each currency and multiply each entry accordingly?

For that you might try the following:

First, create a new table:

proc sql noprint;
create table rates as
select * from table
where Currency = 'AUD'
order by Trans_date;
quit;

data rates;
set rates;
by Trans_date;
output;
if last.Trans_date then do;
  currency_conv = 'AUD';
  rate = 1.;
  output;
end;
run;

now join tables:

proc sql noprint;
create table as newTable
select a.*,a.value*b.rate as newValue
from table as a
left join (select * from rates) as b
on a.Trans_date = b.Trans_date
and a.currency = b.currency_conv;
quit;


问:
Model Data is not getting transferred to the jsp page
I have designed a Login page using Spring MVC,JPA(Hibernate) and Jsp.

Please find the login.jsp :-

```<code>    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <body>
        <h2>Login page</h2>
        <form:form method="POST" modelAttribute="loginBean" action="showProfile">
            <table>
                <tr>
                    <td>UserName :<form:input path="userName"/></td>
                </tr>
                <tr>
                    <td>Organization Id :<form:input path="OrgId" /></td>
                </tr>
                <tr>
                    <td>Password : <form:input path="password" /></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="Submit" /></td>
                </tr>
            </table>
        </form:form>
    </body>
    </html>
</code>```

profilePage.jsp:-

```<code>    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
        <table border="2" width="70%" cellpadding="2">
            <tr>
                <th>UserName</th>
                <th>Password</th>
            </tr>
            <c:forEach var="staff" items="${staffData}">
                <tr>
                    <td>${staff.userName}</td>
                    <td>${staff.password}</td>
                </tr>
            </c:forEach>
        </table>
    </body>
    </html>
</code>```

LoginController.java:-

```<code>@Controller
public class LoginController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showLoginPage(Model model) {
        model.addAttribute("loginBean", new LoginBean());
        return "login";
    }

    @RequestMapping(value = "/showProfile", method = RequestMethod.POST)
    public ModelAndView redirectToprofile(@ModelAttribute("loginBean") LoginBean loginBean) {
        StaffServiceImpl staffServiceImpl = new StaffServiceImpl();
        Staff staff = staffServiceImpl.authenticateStaff(loginBean);
        if (null != staff) {
            return new ModelAndView("redirect:/profilePage","staffData",staff);
        }
        return new ModelAndView("profileNotFound");
        }
@RequestMapping(value = "/profilePage", method = RequestMethod.GET)
    public String showProfilePage() {
        return "profilePage";
    }
</code>```

After giving the valid details in the Login.jsp page it is redirecting to profilePage.jsp but the data in profilePage.jsp is not correct. Please help me to understand where i am doing the mistake.

The profilePage.jsp is displayed a below:-

UserName    Password
${staff.userName}   ${staff.password}

The Value of this variable is not getting displayed.

答:
profilePage.jsp  : Add isELIgnored="false" in page directive.

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1" isELIgnored="false"%>
</code>```

Update your controller with the following :

```<code>@Controller
public class LoginController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showLoginPage(Model model) {
        model.addAttribute("loginBean", new LoginBean());
        return "login";
    }

    @RequestMapping(value = "/showProfile", method = RequestMethod.POST)
    public String redirectToprofile(@ModelAttribute("loginBean") LoginBean loginBean , Model model) {
        StaffServiceImpl staffServiceImpl = new StaffServiceImpl();
        Staff staff = staffServiceImpl.authenticateStaff(loginBean);
        if (null != staff) {
           model.addAttribute("staffData",staff);
           return "profilePage";
        }
        return "profileNotFound";
    }
</code>```

Body:
I have designed a Login page using Spring MVC,JPA(Hibernate) and Jsp.

Please find the login.jsp :-

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Login page

        <form:form method="POST" modelAttribute="loginBean" action="showProfile">

                    UserName :<form:input path="userName"/>

                    Organization Id :<form:input path="OrgId" />

                    Password : <form:input path="password" />

                    <input type="submit" value="Submit" />

        </form:form>

profilePage.jsp:-

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>

                UserName
                Password

            <c:forEach var="staff" items="${staffData}">

                    ${staff.userName}
                    ${staff.password}

            </c:forEach>

LoginController.java:-

@Controller
public class LoginController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showLoginPage(Model model) {
        model.addAttribute("loginBean", new LoginBean());
        return "login";
    }

    @RequestMapping(value = "/showProfile", method = RequestMethod.POST)
    public ModelAndView redirectToprofile(@ModelAttribute("loginBean") LoginBean loginBean) {
        StaffServiceImpl staffServiceImpl = new StaffServiceImpl();
        Staff staff = staffServiceImpl.authenticateStaff(loginBean);
        if (null != staff) {
            return new ModelAndView("redirect:/profilePage","staffData",staff);
        }
        return new ModelAndView("profileNotFound");
        }
@RequestMapping(value = "/profilePage", method = RequestMethod.GET)
    public String showProfilePage() {
        return "profilePage";
    }

After giving the valid details in the Login.jsp page it is redirecting to profilePage.jsp but the data in profilePage.jsp is not correct. Please help me to understand where i am doing the mistake.

The profilePage.jsp is displayed a below:-

UserName    Password
${staff.userName}   ${staff.password}

The Value of this variable is not getting displayed.

Body:
profilePage.jsp  : Add isELIgnored="false" in page directive.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1" isELIgnored="false"%>

Update your controller with the following :

@Controller
public class LoginController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showLoginPage(Model model) {
        model.addAttribute("loginBean", new LoginBean());
        return "login";
    }

    @RequestMapping(value = "/showProfile", method = RequestMethod.POST)
    public String redirectToprofile(@ModelAttribute("loginBean") LoginBean loginBean , Model model) {
        StaffServiceImpl staffServiceImpl = new StaffServiceImpl();
        Staff staff = staffServiceImpl.authenticateStaff(loginBean);
        if (null != staff) {
           model.addAttribute("staffData",staff);
           return "profilePage";
        }
        return "profileNotFound";
    }