问:
Shiny: what is the difference between observeEvent and eventReactive?
I read the Shiny documentation about reactive programming a few times now, but I can't properly understand the difference between observeEvent and eventReactive.

The documentation says:

Use observeEvent whenever you want to perform an action in response to an event. (Note that "recalculate a value" does not generally count as performing an action–see eventReactive for that.)

....

Use eventReactive to create a calculated value that only updates in response to an event. This is just like a normal reactive expression except it ignores all the usual invalidations that come from its reactive dependencies;

In all the situation I tried I saw no difference between using observeEvent and eventReactive (the code works just fine regardless the function I use, with no apparent impact in performances).

Can you help me figure out what is the real difference between the two? Ideally I would like a few examples showing when they are interchangeable, one when observeEvent would work but not eventReactive and vice versa.

答:
Providing the way I understand this , correct me and add more information as required . Most of the information is from https://shiny.rstudio.com/articles/action-buttons.html

Also may be this has been asked long ago, I had the same question while going through eventReactive() and observeEvent()

ObeserveEvent , being more like a trigger for an event while eventReactive , being more like a delay

Below I try the same code , using both the reactive functions

To build several action buttons that control the same object, combine observeEvent() calls with reactiveValues() , Here I can use two actionButtons which are working at the same time in the same code.

Code.1 Gives the effect of observeElement()

Code.2 Uses eventReactive() , but if I try to use two different actionButtons, only the latest one works the earlier button is null and did not react

Code 1

```<code>    library(shiny)

    ui<-fluidPage(
      actionButton("runif", "uniform"),
      actionButton("rnorm", "Normal"),
      hr(),
      plotOutput("plot")
    )

    server<-function(input, output){
      v<-reactiveValues(data=NULL)

      observeEvent(
        input$runif,
        {
        v$data<-runif(100)
        }
      )

      observeEvent(
        input$rnorm,
        {
        v$data<-rnorm(100)
        }
      )

      output$plot <- renderPlot(
        {
          if (is.null(v$data)) return()
          hist(v$data)
        }
      )
    }

shinyApp(ui, server)
</code>```

code2

```<code>   library(shiny)

   ui<-fluidPage(
    actionButton(inputId = "norm", label = "Normal"),
    actionButton(inputId = "unif", label = "Uniform"),

  #Normal
  plotOutput("hist")
)

server <- function(input, output) {

  dnorm <- eventReactive(input$norm, {rnorm(100)})
  dunif <- eventReactive(input$unif, {runif(100)})

  output$hist <- renderPlot({
    hist(dfnorm())
  })

  output$hist <- renderPlot({
    hist(dunif())
  })
}

shinyApp(ui, server)
</code>```

Body:
Providing the way I understand this , correct me and add more information as required . Most of the information is from https://shiny.rstudio.com/articles/action-buttons.html

Also may be this has been asked long ago, I had the same question while going through eventReactive() and observeEvent()

ObeserveEvent , being more like a trigger for an event while eventReactive , being more like a delay

Below I try the same code , using both the reactive functions

To build several action buttons that control the same object, combine observeEvent() calls with reactiveValues() , Here I can use two actionButtons which are working at the same time in the same code.

Code.1 Gives the effect of observeElement()

Code.2 Uses eventReactive() , but if I try to use two different actionButtons, only the latest one works the earlier button is null and did not react

Code 1

    library(shiny)

    ui<-fluidPage(
      actionButton("runif", "uniform"),
      actionButton("rnorm", "Normal"),
      hr(),
      plotOutput("plot")
    )

    server<-function(input, output){
      v<-reactiveValues(data=NULL)

      observeEvent(
        input$runif,
        {
        v$data<-runif(100)
        }
      )

      observeEvent(
        input$rnorm,
        {
        v$data<-rnorm(100)
        }
      )

      output$plot <- renderPlot(
        {
          if (is.null(v$data)) return()
          hist(v$data)
        }
      )
    }

shinyApp(ui, server)

code2

   library(shiny)

   ui<-fluidPage(
    actionButton(inputId = "norm", label = "Normal"),
    actionButton(inputId = "unif", label = "Uniform"),

  #Normal
  plotOutput("hist")
)

server <- function(input, output) {

  dnorm <- eventReactive(input$norm, {rnorm(100)})
  dunif <- eventReactive(input$unif, {runif(100)})

  output$hist <- renderPlot({
    hist(dfnorm())
  })

  output$hist <- renderPlot({
    hist(dunif())
  })
}

shinyApp(ui, server)


来源: stackexchange

问:
How to merge two programs on processing ide in order to run them sequentially?
I am trying to merge two programs. One is for a video player that plays the intro video, and the other is for displaying a radar (I found the coding online). What I want to do is, play the video first, which is an introduction to the Radar, and then have the radar displayed. The radar display is linked with Arduino Mega 2560 and that has its own coding. Here are the two codes.

```<code>import processing.video.*;

String PATH = "D:\\FullZord.mp4";
Movie mov;

void setup()
  {
   size(1920, 1080);
   frameRate(30);
   mov = new Movie(this, PATH);
   mov.play();
   mov.speed(1);
   mov.volume(10);
  }

void movieEvent(Movie m)
  {
   m.read();
  }

void draw()
  {
   image(mov, 0, 0, width, height);
  }
</code>```

and

```<code>import processing.serial.*; // imports library for serial communication
import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
import java.io.IOException;
Serial myPort; // defines Object Serial
// defubes variables
String angle="";
String distance="";
String data="";
String noObject;
float pixsDistance;
int iAngle, iDistance;
int index1=0;
int index2=0;
PFont orcFont;

void setup()
  {

    size (1920, 1080);
    smooth();
    myPort = new Serial(this,"COM4", 9600); // starts the serial communication
    myPort.bufferUntil('.'); // reads the data from the serial port up to the character '.'. So actually it reads this: angle,distance.
    orcFont = loadFont("OCRAExtended-30.vlw");
  }

void draw()
  {

   fill(98,245,31);
   textFont(orcFont);
   // simulating motion blur and slow fade of the moving line
   noStroke();
   fill(0,4);
   rect(0, 0, width, 1010);

   fill(98,245,31); // green color
   // calls the functions for drawing the radar
   drawRadar();
   drawLine();
   drawObject();
   drawText();
  }

void serialEvent (Serial myPort)
  { // starts reading data from the Serial Port
// reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
   data = myPort.readStringUntil('.');
   data = data.substring(0,data.length()-1);

   index1 = data.indexOf(","); // find the character ',' and puts it into
   the
   variable "index1"
   angle= data.substring(0, index1); // read the data from position "0" to position of the variable index1 or thats the value of the angle the Arduino Board sent into the Serial Port
   distance= data.substring(index1+1, data.length()); // read the data from position "index1" to the end of the data pr thats the value of the distance

// converts the String variables into Integer
   iAngle = int(angle);
   iDistance = int(distance);
  }

void drawRadar()
  {
   pushMatrix();
   translate(960,1000); // moves the starting coordinats to new location
   noFill();
   strokeWeight(2);
   stroke(98,245,31);
// draws the arc lines
   arc(0,0,1800,1800,PI,TWO_PI);
   arc(0,0,1400,1400,PI,TWO_PI);
   arc(0,0,1000,1000,PI,TWO_PI);
   arc(0,0,600,600,PI,TWO_PI);
// draws the angle lines
   line(-960,0,960,0);
   line(0,0,-960*cos(radians(30)),-960*sin(radians(30)));
   line(0,0,-960*cos(radians(60)),-960*sin(radians(60)));
   line(0,0,-960*cos(radians(90)),-960*sin(radians(90)));
   line(0,0,-960*cos(radians(120)),-960*sin(radians(120)));
   line(0,0,-960*cos(radians(150)),-960*sin(radians(150)));
   line(-960*cos(radians(30)),0,960,0);
   popMatrix();
  }

void drawObject()
  {
   pushMatrix();
   translate(960,1000); // moves the starting coordinats to new location
   strokeWeight(9);
   stroke(255,10,10); // red color
   pixsDistance = iDistance*22.5; // covers the distance from the sensor from cm to pixels
// limiting the range to 40 cms
   if(iDistance<40){
// draws the object according to the angle and the distance
   line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAn
 gle)));
   }
    popMatrix();
   }
 void drawLine()
   {
    pushMatrix();
    strokeWeight(9);
    stroke(30,250,60);
    translate(960,1000); // moves the starting coordinats to new location
    line(0,0,950*cos(radians(iAngle)),-950*sin(radians(iAngle))); // draws the line according to the angle
    popMatrix();
   }

 void drawText()
   { // draws the texts on the screen

     pushMatrix();
     if(iDistance>40)
       {
        noObject = "Out of Range";
       }
     else
         {
          noObject = "In Range";
         }
     fill(0,0,0);
     noStroke();
     rect(0, 1010, width, 1080);
     fill(98,245,31);
     textSize(25);
     text("10cm",1180,990);
     text("20cm",1380,990);
     text("30cm",1580,990);
     text("40cm",1780,990);
     textSize(40);
     text("Object: " + noObject, 240, 1050);
     text("Angle: " + iAngle +" °", 1050, 1050);
     text("Distance: ", 1380, 1050);

     if(iDistance<40)
       {
        text("        " + iDistance +" cm", 1400, 1050);
       }
     textSize(25);
     fill(98,245,60);
     translate(961+960*cos(radians(30)),982-960*sin(radians(30)));
     rotate(-radians(-60));
     text("30°",0,0);
     resetMatrix();
     translate(954+960*cos(radians(60)),984-960*sin(radians(60)));
     rotate(-radians(-30));
     text("60°",0,0);
     resetMatrix();
     translate(945+960*cos(radians(90)),990-960*sin(radians(90)));
     rotate(radians(0));
     text("90°",0,0);
     resetMatrix();
     translate(935+960*cos(radians(120)),1003-960*sin(radians(120)));
     rotate(radians(-30));
     text("120°",0,0);
     resetMatrix();
     translate(940+960*cos(radians(150)),1018-960*sin(radians(150)));
     rotate(radians(-60));
     text("150°",0,0);
     popMatrix();
    }
</code>```

答:
You're going to have to read the reference material for the video library. You're looking for a way to detect when the movie is playing, or when it's stopped. It's probably something like an isPlaying() function in the Movie class.

When you have that, you can call that in the draw() function to detect whether the movie is still playing. If so, draw it. If not, then show the radar.

But start smaller. First off, can you just print something to the console when the movie is done playing? Build off of that.

Also, I highly recommend that you don't just use code that you copy-pasted from the internet. That's only going to give you a ton of headaches. Instead, try to understand exactly what the code is doing. Otherwise it's going to be impossible to debug or make changes. You need to really understand the code before you can use it.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to merge two programs. One is for a video player that plays the intro video, and the other is for displaying a radar (I found the coding online). What I want to do is, play the video first, which is an introduction to the Radar, and then have the radar displayed. The radar display is linked with Arduino Mega 2560 and that has its own coding. Here are the two codes.

import processing.video.*;

String PATH = "D:\\FullZord.mp4";
Movie mov;

void setup()
  {
   size(1920, 1080);
   frameRate(30);
   mov = new Movie(this, PATH);
   mov.play();
   mov.speed(1);
   mov.volume(10);
  }

void movieEvent(Movie m)
  {
   m.read();
  }

void draw()
  {
   image(mov, 0, 0, width, height);
  }

and

import processing.serial.*; // imports library for serial communication
import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
import java.io.IOException;
Serial myPort; // defines Object Serial
// defubes variables
String angle="";
String distance="";
String data="";
String noObject;
float pixsDistance;
int iAngle, iDistance;
int index1=0;
int index2=0;
PFont orcFont;

void setup()
  {

    size (1920, 1080);
    smooth();
    myPort = new Serial(this,"COM4", 9600); // starts the serial communication
    myPort.bufferUntil('.'); // reads the data from the serial port up to the character '.'. So actually it reads this: angle,distance.
    orcFont = loadFont("OCRAExtended-30.vlw");
  }

void draw()
  {

   fill(98,245,31);
   textFont(orcFont);
   // simulating motion blur and slow fade of the moving line
   noStroke();
   fill(0,4);
   rect(0, 0, width, 1010);

   fill(98,245,31); // green color
   // calls the functions for drawing the radar
   drawRadar();
   drawLine();
   drawObject();
   drawText();
  }

void serialEvent (Serial myPort)
  { // starts reading data from the Serial Port
// reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
   data = myPort.readStringUntil('.');
   data = data.substring(0,data.length()-1);

   index1 = data.indexOf(","); // find the character ',' and puts it into
   the
   variable "index1"
   angle= data.substring(0, index1); // read the data from position "0" to position of the variable index1 or thats the value of the angle the Arduino Board sent into the Serial Port
   distance= data.substring(index1+1, data.length()); // read the data from position "index1" to the end of the data pr thats the value of the distance

// converts the String variables into Integer
   iAngle = int(angle);
   iDistance = int(distance);
  }

void drawRadar()
  {
   pushMatrix();
   translate(960,1000); // moves the starting coordinats to new location
   noFill();
   strokeWeight(2);
   stroke(98,245,31);
// draws the arc lines
   arc(0,0,1800,1800,PI,TWO_PI);
   arc(0,0,1400,1400,PI,TWO_PI);
   arc(0,0,1000,1000,PI,TWO_PI);
   arc(0,0,600,600,PI,TWO_PI);
// draws the angle lines
   line(-960,0,960,0);
   line(0,0,-960*cos(radians(30)),-960*sin(radians(30)));
   line(0,0,-960*cos(radians(60)),-960*sin(radians(60)));
   line(0,0,-960*cos(radians(90)),-960*sin(radians(90)));
   line(0,0,-960*cos(radians(120)),-960*sin(radians(120)));
   line(0,0,-960*cos(radians(150)),-960*sin(radians(150)));
   line(-960*cos(radians(30)),0,960,0);
   popMatrix();
  }

void drawObject()
  {
   pushMatrix();
   translate(960,1000); // moves the starting coordinats to new location
   strokeWeight(9);
   stroke(255,10,10); // red color
   pixsDistance = iDistance*22.5; // covers the distance from the sensor from cm to pixels
// limiting the range to 40 cms
   if(iDistance<40){
// draws the object according to the angle and the distance
   line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAn
 gle)));
   }
    popMatrix();
   }
 void drawLine()
   {
    pushMatrix();
    strokeWeight(9);
    stroke(30,250,60);
    translate(960,1000); // moves the starting coordinats to new location
    line(0,0,950*cos(radians(iAngle)),-950*sin(radians(iAngle))); // draws the line according to the angle
    popMatrix();
   }

 void drawText()
   { // draws the texts on the screen

     pushMatrix();
     if(iDistance>40)
       {
        noObject = "Out of Range";
       }
     else
         {
          noObject = "In Range";
         }
     fill(0,0,0);
     noStroke();
     rect(0, 1010, width, 1080);
     fill(98,245,31);
     textSize(25);
     text("10cm",1180,990);
     text("20cm",1380,990);
     text("30cm",1580,990);
     text("40cm",1780,990);
     textSize(40);
     text("Object: " + noObject, 240, 1050);
     text("Angle: " + iAngle +" °", 1050, 1050);
     text("Distance: ", 1380, 1050);

     if(iDistance<40)
       {
        text("        " + iDistance +" cm", 1400, 1050);
       }
     textSize(25);
     fill(98,245,60);
     translate(961+960*cos(radians(30)),982-960*sin(radians(30)));
     rotate(-radians(-60));
     text("30°",0,0);
     resetMatrix();
     translate(954+960*cos(radians(60)),984-960*sin(radians(60)));
     rotate(-radians(-30));
     text("60°",0,0);
     resetMatrix();
     translate(945+960*cos(radians(90)),990-960*sin(radians(90)));
     rotate(radians(0));
     text("90°",0,0);
     resetMatrix();
     translate(935+960*cos(radians(120)),1003-960*sin(radians(120)));
     rotate(radians(-30));
     text("120°",0,0);
     resetMatrix();
     translate(940+960*cos(radians(150)),1018-960*sin(radians(150)));
     rotate(radians(-60));
     text("150°",0,0);
     popMatrix();
    }


问:
Process.start() in a loop doesn't maintain FIFO
I want to print pdf files in a foreach loop which doesn't maintain FIFO. Applied even lock and semaphore using concurrent queue. But, sometimes misses the sequence. How can I make printing process maintaining confirm FIFO and Thread-safe?  My code is as follows,</p>

```<code>foreach(string pfile in printdoc)
{
    ProcessStartInfo info = new ProcessStartInfo();
    info.Verb = "print";
    info.CreateNoWindow = true;
    info.FileName = pfile;
    info.WindowStyle = ProcessWindowStyle.Hidden;

    Process p = new Process();
    p.StartInfo = info;
    p.Start();
}
</code>```

答:
You need the previous one to finish before you start the next itteration. Throw a p.WaitForExit() on the end to wait for the print to finish before queuing the next one.

```<code>foreach(string pfile in printdoc)
{
    ProcessStartInfo info = new ProcessStartInfo();
    info.Verb = "print";
    info.CreateNoWindow = true;
    info.FileName = pfile;
    info.WindowStyle = ProcessWindowStyle.Hidden;

    //You can shorten your existing code to a single line using Process.Start(
    Process p = Process.Start(info);
    p.WaitForExit();
}
</code>```

For thread safety it depends on what kind of collection printdoc is, the easiest solution is to use a BlockingCollection<string> and make your foreach in to foreach(string pfile in printdoc.GetConsumingEnumerable())

Body:
I want to print pdf files in a foreach loop which doesn't maintain FIFO. Applied even lock and semaphore using concurrent queue. But, sometimes misses the sequence. How can I make printing process maintaining confirm FIFO and Thread-safe?  My code is as follows,

foreach(string pfile in printdoc)
{
    ProcessStartInfo info = new ProcessStartInfo();
    info.Verb = "print";
    info.CreateNoWindow = true;
    info.FileName = pfile;
    info.WindowStyle = ProcessWindowStyle.Hidden;

    Process p = new Process();
    p.StartInfo = info;
    p.Start();
}

Body:
You need the previous one to finish before you start the next itteration. Throw a p.WaitForExit() on the end to wait for the print to finish before queuing the next one.

foreach(string pfile in printdoc)
{
    ProcessStartInfo info = new ProcessStartInfo();
    info.Verb = "print";
    info.CreateNoWindow = true;
    info.FileName = pfile;
    info.WindowStyle = ProcessWindowStyle.Hidden;

    //You can shorten your existing code to a single line using Process.Start(
    Process p = Process.Start(info);
    p.WaitForExit();
}

For thread safety it depends on what kind of collection printdoc is, the easiest solution is to use a BlockingCollection<string> and make your foreach in to foreach(string pfile in printdoc.GetConsumingEnumerable())


问:
How do you pass a function as a parameter of a function swift?
Looking to pass a function as a parameter (like an onCompletion) that will be invoked as part of the function call in Swift (similar to javascript closures). What's the best practice here?

Code:

```<code>func didFinishFunc(onCompletion: func) {
    func()
}

func onCompletionFunc()
{
    print("completed.")
}

func caller()
{
   didFinishFunc(onCompletion: onCompletionFunc)
}

// caller is called
caller()
</code>```

答:
Use Swift closure. E.g.

```<code>func didFinishFunc(onCompletion handler: () -> Void) {
    handler()
}
</code>```

See The Swift Programming Language: Closures.

Body:
Looking to pass a function as a parameter (like an onCompletion) that will be invoked as part of the function call in Swift (similar to javascript closures). What's the best practice here?

Code:

func didFinishFunc(onCompletion: func) {
    func()
}

func onCompletionFunc()
{
    print("completed.")
}

func caller()
{
   didFinishFunc(onCompletion: onCompletionFunc)
}

// caller is called
caller()

Body:
Use Swift closure. E.g.

func didFinishFunc(onCompletion handler: () -> Void) {
    handler()
}

See The Swift Programming Language: Closures.


问:
How can I manipulate this object in jQuery
```<code>jQuery(function () {
    $('#square a').click(function(e) {
    // How is the e object structured
    });
})
</code>```

I have a div with an id of square and links in that. When the links are clicked they trigger a game loop function. I need to know which id the click is coming from. There are five links within the square and each one has an id. Is there a better way to track this. Or should I have a function for each link with its own id but this doesn't seem DRY to me.

答:
Another way to get clicked element's id that has not been mentioned is through the event object and answers your question about e parameter:

```<code>jQuery(function () {
    $('#square a').click(function(e) {
       alert(e.target.id);
    });
});
</code>```

The advantage of using e.target.id is that you can obtain id of the child object that was actually clicked on, while this.id will always return id of the element click event handler was bound to.

Also, if you're going to use this there is no reason to declare e:

```<code>$(document).ready(function() {
    $('#square a').click(function() {
       alert(this.id);
    });
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
jQuery(function () {
    $('#square a').click(function(e) {
    // How is the e object structured
    });
})

I have a div with an id of square and links in that. When the links are clicked they trigger a game loop function. I need to know which id the click is coming from. There are five links within the square and each one has an id. Is there a better way to track this. Or should I have a function for each link with its own id but this doesn't seem DRY to me.

Body:
Another way to get clicked element's id that has not been mentioned is through the event object and answers your question about e parameter:

jQuery(function () {
    $('#square a').click(function(e) {
       alert(e.target.id);
    });
});

The advantage of using e.target.id is that you can obtain id of the child object that was actually clicked on, while this.id will always return id of the element click event handler was bound to.

Also, if you're going to use this there is no reason to declare e:

$(document).ready(function() {
    $('#square a').click(function() {
       alert(this.id);
    });
});


问:
PHP mailer - double emails (Joomla module)
I have php form (Joomla module) that submits emails and saves user emails to database.
Form is checking if user email already exists in database, if not email is saved (new joomla user is created) and mail is submitted to admin email and user email. This part works fine.
But if email is already in database (returning user scenario) form sends double emails to both administrator and user.</p>

```<code> $mailer = & JFactory::getMailer();

        $mailer->isHTML();
        $mailer->setSender($params->get('email_from'));
        $mailer->addRecipient($params->get('email_to'));
        $mailer->addBCC($email);
        $mailer->setSubject($params->get('subject'));
        $mailer->setBody($message);

$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = 'SELECT id FROM #__users WHERE email = ' . $db->Quote($email);
$db->setQuery($query, 0, 1);
$check = $db->loadResult();

if(!$check){

    $udate = date('d/m/Y');
    $utime= date("h:i:s");
    $udata = array(
    "name"=>"user".$udate."-".$utime,
    "username"=>"user".$utime,
    "password"=>$utime,
    "password2"=>$utime,
    "email"=>$email,
    "block"=>0,
    "groups"=>array("9")
);
$user = clone(JFactory::getUser());

if(!$user->bind($udata)) {
    throw new Exception("Could not bind data. Error: " . $user->getError());
}
if (!$user->save()) {
     throw new Exception("Could not save user. Error: " . $user->getError());
}
   return $user->id;

 JFactory::getSession()->clear('user');

    }

    $send = & $mailer->Send();
    $mailer->ClearAddresses();
    $mailer->ClearAllRecipients();
        if($send = true){
            echo "Mail sent";
            return true;
            }
        else if ($send != true)
        {
            echo "Error sending email: ". $send->message;
            return false;

            }

        }
</code>```

答:
There are some obvious errors in your code. The line:

```<code>JFactory::getSession()->clear('user');
</code>```

is never reached, as the script is returning before this line. Also, the line:

```<code>if($send = true){
</code>```

simply assigns true to send and will always be true.

I also question this line:

```<code>$send = & $mailer->Send();
</code>```

You are here assigning a reference to $send for some reason. Dont.

I'm not sure why you get the errors you observe, but: I would really consider properly formatting your code with correct indents, it makes it much easier to spot errors. And try to clean out other errors... Consider that your function might be called twice for some reason...

Body:
I have php form (Joomla module) that submits emails and saves user emails to database.
Form is checking if user email already exists in database, if not email is saved (new joomla user is created) and mail is submitted to admin email and user email. This part works fine.
But if email is already in database (returning user scenario) form sends double emails to both administrator and user.

 $mailer = & JFactory::getMailer();

        $mailer->isHTML();
        $mailer->setSender($params->get('email_from'));
        $mailer->addRecipient($params->get('email_to'));
        $mailer->addBCC($email);
        $mailer->setSubject($params->get('subject'));
        $mailer->setBody($message);

$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = 'SELECT id FROM #__users WHERE email = ' . $db->Quote($email);
$db->setQuery($query, 0, 1);
$check = $db->loadResult();

if(!$check){

    $udate = date('d/m/Y');
    $utime= date("h:i:s");
    $udata = array(
    "name"=>"user".$udate."-".$utime,
    "username"=>"user".$utime,
    "password"=>$utime,
    "password2"=>$utime,
    "email"=>$email,
    "block"=>0,
    "groups"=>array("9")
);
$user = clone(JFactory::getUser());

if(!$user->bind($udata)) {
    throw new Exception("Could not bind data. Error: " . $user->getError());
}
if (!$user->save()) {
     throw new Exception("Could not save user. Error: " . $user->getError());
}
   return $user->id;

 JFactory::getSession()->clear('user');

    }

    $send = & $mailer->Send();
    $mailer->ClearAddresses();
    $mailer->ClearAllRecipients();
        if($send = true){
            echo "Mail sent";
            return true;
            }
        else if ($send != true)
        {
            echo "Error sending email: ". $send->message;
            return false;

            }

        }

Body:
There are some obvious errors in your code. The line:

JFactory::getSession()->clear('user');

is never reached, as the script is returning before this line. Also, the line:

if($send = true){

simply assigns true to send and will always be true.

I also question this line:

$send = & $mailer->Send();

You are here assigning a reference to $send for some reason. Dont.

I'm not sure why you get the errors you observe, but: I would really consider properly formatting your code with correct indents, it makes it much easier to spot errors. And try to clean out other errors... Consider that your function might be called twice for some reason...


问:
Use the same JComboBox from one class to another Java Swing
I have 2 classes. I'd like to have 2 identical JComboBox in each class.
I did it successfully in the first class, because the values in my JComboBox are the same as the values in a JList, filled with text from a text field.
But I could not manage to get the same result in the other class !

Extract of my first class :

```<code>    DefaultComboBoxModel Ajout = new DefaultComboBoxModel();
    btnValidate.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            String newCategorie = textCreerCategorie.getText();
            Ajout.addElement(newCategorie);
            list.setModel(Ajout);
            myComboB.setModel(Ajout);
</code>```

So that's it ! How can I have the same JComboBox in my other class and use my JList in it ?

答:
Thanks everyone for your answers. To be more specific, it is a shopping list where I have two class, one is for the main window where you can choose a category and product and display in a list.

The otherone is for a windows that manage your categories and products so when a categorie is created (from a jtext field and add to my jlist) I want it to add it in a ComboBox that is in the main window. I hope you guys will understand me (french girl over here).

In the modification class :

```<code>    DefaultComboBoxModel Ajout = new DefaultComboBoxModel();
    btnValiderCategorie.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            String newCategorie = textCreerCategorie.getText();
            Ajout.addElement(newCategorie);
            list.setModel(Ajout);
            ajouterACategorie.setModel(Ajout);
</code>```

This allows me to add at the same time a new categorie in my jlist and in a comboBox that is in the modification windows.
Then I'd like to have the same combobox in the main window so the user can choose a categorie that he created in the other class.
The main class does a lot of other things but my preocupation in to have the same effect in this combobox

```<code>    JComboBox<String> categories_content = new JComboBox<String>();
    categories_content.setBounds(140, 63, 157, 30);
</code>```

than the other comboBox in the modification class.
Sorry guys if it's too confuse i'd understand

Body:
I have 2 classes. I'd like to have 2 identical JComboBox in each class.
I did it successfully in the first class, because the values in my JComboBox are the same as the values in a JList, filled with text from a text field.
But I could not manage to get the same result in the other class !

Extract of my first class :

    DefaultComboBoxModel Ajout = new DefaultComboBoxModel();
    btnValidate.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            String newCategorie = textCreerCategorie.getText();
            Ajout.addElement(newCategorie);
            list.setModel(Ajout);
            myComboB.setModel(Ajout);

So that's it ! How can I have the same JComboBox in my other class and use my JList in it ?

Body:
Thanks everyone for your answers. To be more specific, it is a shopping list where I have two class, one is for the main window where you can choose a category and product and display in a list.

The otherone is for a windows that manage your categories and products so when a categorie is created (from a jtext field and add to my jlist) I want it to add it in a ComboBox that is in the main window. I hope you guys will understand me (french girl over here).

In the modification class :

    DefaultComboBoxModel Ajout = new DefaultComboBoxModel();
    btnValiderCategorie.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            String newCategorie = textCreerCategorie.getText();
            Ajout.addElement(newCategorie);
            list.setModel(Ajout);
            ajouterACategorie.setModel(Ajout);

This allows me to add at the same time a new categorie in my jlist and in a comboBox that is in the modification windows.
Then I'd like to have the same combobox in the main window so the user can choose a categorie that he created in the other class.
The main class does a lot of other things but my preocupation in to have the same effect in this combobox

    JComboBox<String> categories_content = new JComboBox<String>();
    categories_content.setBounds(140, 63, 157, 30);

than the other comboBox in the modification class.
Sorry guys if it's too confuse i'd understand


问:
Java Stream digits to number
I am struggling to get a functioning code for this.
I have a stream of digits between 0 and 9. I want to get a BigInteger out of those digits.
Example:

```<code>IntStream digits = IntStream.of(1, 2, 3) // should get me a Biginteger 123.
IntStream digits = IntStream.of(9, 5, 3) // should get me a Biginteger 953.
</code>```

Is there a way to concatenate all elements out of the stream?
Here is my basic idea:

```<code>digits.forEach(element -> result=result.concat(result, element.toString()));
</code>```

答:
You could reduce as follows:

```<code>BigInteger big1 = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
    .mapToObj(BigInteger::valueOf)
    .sequential() // if parallel, reduce would return sweet potatoes
    .reduce((a, b) -> a.multiply(BigInteger.TEN).add(b))
    .orElse(BigInteger.ZERO);

System.out.println(big1); // 123456789
</code>```

Though I think it would be better to create a String and use it as the argument of BigInteger's constructor, as in @Mureinik's answer. Here I'm using a variant that doesn't create a String object per digit:

```<code>String digits = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
    .toString();
BigInteger big2 = new BigInteger(digits);

System.out.println(big2); // 123456789
</code>```

Title: Java Stream digits to number

Body:
I am struggling to get a functioning code for this.
I have a stream of digits between 0 and 9. I want to get a BigInteger out of those digits.
Example:

IntStream digits = IntStream.of(1, 2, 3) // should get me a Biginteger 123.
IntStream digits = IntStream.of(9, 5, 3) // should get me a Biginteger 953.

Is there a way to concatenate all elements out of the stream?
Here is my basic idea:

digits.forEach(element -> result=result.concat(result, element.toString()));

Body:
You could reduce as follows:

BigInteger big1 = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
    .mapToObj(BigInteger::valueOf)
    .sequential() // if parallel, reduce would return sweet potatoes
    .reduce((a, b) -> a.multiply(BigInteger.TEN).add(b))
    .orElse(BigInteger.ZERO);

System.out.println(big1); // 123456789

Though I think it would be better to create a String and use it as the argument of BigInteger's constructor, as in @Mureinik's answer. Here I'm using a variant that doesn't create a String object per digit:

String digits = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
    .toString();
BigInteger big2 = new BigInteger(digits);

System.out.println(big2); // 123456789


问:
Eloquent Eager Loading with $append Attribute
I'm kinda stuck with this here and don't know how to move forward with this one.

I have two Models: user and child and they are in a Relationship.

( Keep in mind that this only illustrate the problem )

```<code>class Child extends Model{

    protected $primaryKey = 'id_child';

    public $appends = ['is_alive'];

    public function user(){

        return $this->belongsTo('Models\User','id_user');

    }

    public function getIsAliveAttribute(){

        if (!is_null($this->lifetime_updated_at))
            return (Carbon::parse($this->lifetime_updated_at)->addMinute($this->lifetime) >= Carbon::now());
        else
            return false;
    }
}

class User extends Model{

    protected $primaryKey = 'id_user';

    public $appends = ['is_alive'];

    public function childs(){

        return $this->hasMany('Models\Child','id_user');
}

public function getIsAliveAttribute(){

    if (!is_null($this->lifetime_updated_at))
        return (Carbon::parse($this->lifetime_updated_at)->addMinute($this->lifetime) >= Carbon::now());
    else
        return false;
}
</code>```

}

Now I want to use Eager Loading in the Controller to retrieve my Childs data from User.

But my User Model Object comes from an MiddleWare in my Application. So I only have the User Model Object to use and I don't want to Query the User again using "with()".

```<code>$user = User::where('name','DoctorWho')->first();

return user->childs()->find(3);
</code>```

What this operation returns:

```<code>    {
        "id_child": 3,
        "name": "JayZ",
        "last_name": "Etc",
        "lifetime": 1,
        "lifetime_updated_at": null,
        "created_at": "2017-05-29 21:40:02",
        "updated_at": "2017-05-29 21:40:02",
        "active": 1
}
</code>```

What I needed ( With Attribute Appended)

```<code>{
    "id_child": 3,
    "name": "JayZ",
    "last_name": "Etc",
    "lifetime": 1,
    "lifetime_updated_at": null,
    "created_at": "2017-05-29 21:40:02",
    "updated_at": "2017-05-29 21:40:02",
    "active": 1,
    "is_alive": true
  }
</code>```

Is even possible to retrieve Child Data with Appended Attributes using Eager Loading ?

Notes: This user object come from an Middleware, I must use the User Model Object to get its child's with the appended attribute.

Thanks in Advance,
LosLobos

答:
What you're doing here is not eager loading. Your childs relationship is wrong. Should be return $this->hasMany('Models\Child', 'id_user'); based on the model and the other relationship defined.

Here are some ways you can access the child information. These by default should respect the $appends property and load the field.

```<code>$childId = 3;

$user = User::with('childs')
    ->where('name', 'DoctorWho')
    ->first();

return $user->childs()->where('id_child', $childId)->first();

// Or

$user = User::with(['childs' => function ($query) use ($childId) {
        $query->where('id_child', $childId);
    }])
    ->where('name', 'DoctorWho')
    ->first();

return $user->childs->first();

// Or

$child = Child::whereHas('user', function ($query) {
        $query->where('name', 'DoctorWho');
    })
    ->find(3);

return $child;
</code>```

Edit :

If you already have the user model then you can do this.

```<code>$child = Child::where('id_user', $user->id_user)
    ->where('id_child', 3)
    ->first();

return $child;
</code>```

Body:
I'm kinda stuck with this here and don't know how to move forward with this one.

I have two Models: user and child and they are in a Relationship.

( Keep in mind that this only illustrate the problem )

class Child extends Model{

    protected $primaryKey = 'id_child';

    public $appends = ['is_alive'];

    public function user(){

        return $this->belongsTo('Models\User','id_user');

    }

    public function getIsAliveAttribute(){

        if (!is_null($this->lifetime_updated_at))
            return (Carbon::parse($this->lifetime_updated_at)->addMinute($this->lifetime) >= Carbon::now());
        else
            return false;
    }
}

class User extends Model{

    protected $primaryKey = 'id_user';

    public $appends = ['is_alive'];

    public function childs(){

        return $this->hasMany('Models\Child','id_user');
}

public function getIsAliveAttribute(){

    if (!is_null($this->lifetime_updated_at))
        return (Carbon::parse($this->lifetime_updated_at)->addMinute($this->lifetime) >= Carbon::now());
    else
        return false;
}

}

Now I want to use Eager Loading in the Controller to retrieve my Childs data from User.

But my User Model Object comes from an MiddleWare in my Application. So I only have the User Model Object to use and I don't want to Query the User again using "with()".

$user = User::where('name','DoctorWho')->first();

return user->childs()->find(3);

What this operation returns:

    {
        "id_child": 3,
        "name": "JayZ",
        "last_name": "Etc",
        "lifetime": 1,
        "lifetime_updated_at": null,
        "created_at": "2017-05-29 21:40:02",
        "updated_at": "2017-05-29 21:40:02",
        "active": 1
}

What I needed ( With Attribute Appended)

{
    "id_child": 3,
    "name": "JayZ",
    "last_name": "Etc",
    "lifetime": 1,
    "lifetime_updated_at": null,
    "created_at": "2017-05-29 21:40:02",
    "updated_at": "2017-05-29 21:40:02",
    "active": 1,
    "is_alive": true
  }

Is even possible to retrieve Child Data with Appended Attributes using Eager Loading ?

Notes: This user object come from an Middleware, I must use the User Model Object to get its child's with the appended attribute.

Thanks in Advance,
LosLobos

Body:
What you're doing here is not eager loading. Your childs relationship is wrong. Should be return $this->hasMany('Models\Child', 'id_user'); based on the model and the other relationship defined.

Here are some ways you can access the child information. These by default should respect the $appends property and load the field.

$childId = 3;

$user = User::with('childs')
    ->where('name', 'DoctorWho')
    ->first();

return $user->childs()->where('id_child', $childId)->first();

// Or

$user = User::with(['childs' => function ($query) use ($childId) {
        $query->where('id_child', $childId);
    }])
    ->where('name', 'DoctorWho')
    ->first();

return $user->childs->first();

// Or

$child = Child::whereHas('user', function ($query) {
        $query->where('name', 'DoctorWho');
    })
    ->find(3);

return $child;

Edit :

If you already have the user model then you can do this.

$child = Child::where('id_user', $user->id_user)
    ->where('id_child', 3)
    ->first();

return $child;


问:
Timezone UTC to Europe/London +- 0 hours?
I am a little confused about timezone calculations... Of course London is 1 hour ahead of UTC, but why does this list say, that there is no difference between London and UTC???

Thanks for your help!

答:
London time is the same as UTC and GMT during the winter.

This is from that link:

Places that observe daylight saving time (DST) during their respective summer periods are listed only once, at the offset for their winter (usually known as "standard") period; see their individual articles for more information.

It lists places using winter time and ignores DST.


问:
Database driver-class dynamic loading
I want to develop a DB-Agnostic application in java. I have chosen hibernate as ORM. The problem with jdbc is that , it is just an interface and we need the driver class of the db in the class path.  Since the database should be configurable i have to go for  loading the driver class of DB dynamically. (User should keep the driver class in a folder and it should be loaded dynamically )
Below is my code.

```<code>File driverJar = new File("E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar");
URL[] urls = new URL[] { driverJar.toURL() };
URLClassLoader classLoader = new URLClassLoader(urls,DBUtils.class.getClassLoader());
Class.forName("org.postgresql.Driver", true, classLoader);
</code>```

No error till now.
But after this, while initializing hibernate connection, I am getting error java.lang.ClassNotFoundException: org.postgresql.Driver.

May I know what is the problem here.

答:
Finally I got the solution by myself,
The problem here is , I have created a new classloader and loaded the jar into it.

The hibernate is searching for driver class in system class loader , not in the user defined class loaders.

The problem here can be solved by load the jar into system class loader as below.

```<code>File driverJar = new File("E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar");
URL myJarFile = new URL("jar", "", "file:" + driverJar.getAbsolutePath() + "!/");
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

Class sysClass = URLClassLoader.class;
Method sysMethod = sysClass.getDeclaredMethod("addURL", new Class[] { URL.class });
sysMethod.setAccessible(true);
sysMethod.invoke(sysLoader, new Object[] { myJarFile });

Class.forName("org.postgresql.Driver", true, classLoader); // Now no error in this line.
</code>```

Title: Database driver-class dynamic loading

Body:
I want to develop a DB-Agnostic application in java. I have chosen hibernate as ORM. The problem with jdbc is that , it is just an interface and we need the driver class of the db in the class path.  Since the database should be configurable i have to go for  loading the driver class of DB dynamically. (User should keep the driver class in a folder and it should be loaded dynamically )
Below is my code.

File driverJar = new File("E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar");
URL[] urls = new URL[] { driverJar.toURL() };
URLClassLoader classLoader = new URLClassLoader(urls,DBUtils.class.getClassLoader());
Class.forName("org.postgresql.Driver", true, classLoader);

No error till now.
But after this, while initializing hibernate connection, I am getting error java.lang.ClassNotFoundException: org.postgresql.Driver.

May I know what is the problem here.

Body:
Finally I got the solution by myself,
The problem here is , I have created a new classloader and loaded the jar into it.

The hibernate is searching for driver class in system class loader , not in the user defined class loaders.

The problem here can be solved by load the jar into system class loader as below.

File driverJar = new File("E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar");
URL myJarFile = new URL("jar", "", "file:" + driverJar.getAbsolutePath() + "!/");
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

Class sysClass = URLClassLoader.class;
Method sysMethod = sysClass.getDeclaredMethod("addURL", new Class[] { URL.class });
sysMethod.setAccessible(true);
sysMethod.invoke(sysLoader, new Object[] { myJarFile });

Class.forName("org.postgresql.Driver", true, classLoader); // Now no error in this line.


问:
Java, Using javaFX for the main menu then switching over to JFrame for the game itself
I am here to ask if it is possible to use JavaFX for the main menu of my game and then switch over to JFrame for the game itself.

The reason I want to do this is because I know how to make pretty fancy game menus in JavaFX and not in JFrame and JavaFX to me also looks alot more fancy then JFrame..

I will truly appreciate any help you give me.

答:
This can be done: you just need to make sure you use the correct threads for everything. In particular, ensure you launch the Swing application on the AWT Event Dispatch Thread.

Here is a simple example.

SwingApp:

```<code>import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class SwingApp extends JFrame {

    public SwingApp() {
        setLayout(new BorderLayout());
        add(new JLabel("This is the Swing App", JLabel.CENTER), BorderLayout.CENTER);
        JButton quitButton = new JButton("Exit");
        quitButton.addActionListener(e -> System.exit(0));
        add(quitButton, BorderLayout.SOUTH);
        setSize(600, 600);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}
</code>```

and then

```<code>import javax.swing.SwingUtilities;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class LaunchSwingFromFX extends Application {

    @Override
    public void start(Stage primaryStage) {

        Platform.setImplicitExit(false);

        Button launch = new Button("Launch");
        launch.setOnAction(e -> {
            SwingUtilities.invokeLater(SwingApp::new);
            primaryStage.hide();
        });
        StackPane root = new StackPane(launch);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Body:
This can be done: you just need to make sure you use the correct threads for everything. In particular, ensure you launch the Swing application on the AWT Event Dispatch Thread.

Here is a simple example.

SwingApp:

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class SwingApp extends JFrame {

    public SwingApp() {
        setLayout(new BorderLayout());
        add(new JLabel("This is the Swing App", JLabel.CENTER), BorderLayout.CENTER);
        JButton quitButton = new JButton("Exit");
        quitButton.addActionListener(e -> System.exit(0));
        add(quitButton, BorderLayout.SOUTH);
        setSize(600, 600);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

and then

import javax.swing.SwingUtilities;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class LaunchSwingFromFX extends Application {

    @Override
    public void start(Stage primaryStage) {

        Platform.setImplicitExit(false);

        Button launch = new Button("Launch");
        launch.setOnAction(e -> {
            SwingUtilities.invokeLater(SwingApp::new);
            primaryStage.hide();
        });
        StackPane root = new StackPane(launch);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


答:
You can define your function like this.

```<code>func didFinishFunc(onCompletion: () -> Void) {
    // your function implementation here

    onCompletion()
}
</code>```

This function takes in a closure (sometimes called a callback or anonymous function in other languages) as a parameter. This closure has no parameters and no return value.

If you want the closure to have parameters you could do something like this:

```<code>func didFinishFunc(onCompletion: (String, Int) -> Void) {
    // your function implementation here

    onCompletion("foo", 5)
}
</code>```

This function takes in two parameters a String and an Int.

If you want the closure to have a return type, change the type (above it is Void) after the ->.

Title: How do you pass a function as a parameter of a function swift?

Body:
You can define your function like this.

func didFinishFunc(onCompletion: () -> Void) {
    // your function implementation here

    onCompletion()
}

This function takes in a closure (sometimes called a callback or anonymous function in other languages) as a parameter. This closure has no parameters and no return value.

If you want the closure to have parameters you could do something like this:

func didFinishFunc(onCompletion: (String, Int) -> Void) {
    // your function implementation here

    onCompletion("foo", 5)
}

This function takes in two parameters a String and an Int.

If you want the closure to have a return type, change the type (above it is Void) after the ->.


问:
Displaying an image with PHP from a database
I have a problem displaying images for URLs that are saved in a database.

This is my HTML source code:

```<code><div id="posts">
<img id="images" src="php/getImage.php?id=1">
<footer>
<a href="php/getImage.php?id=1" download><p>Download</p></a>
</footer>
</div>
</code>```

And my getImage.php file:

<?php
$id = $_GET['id'];
$db = mysqli_connect("host", "username", "password", "DB name");
$sql = "SELECT image FROM images WHERE imageID=$id";
$result=mysql_query($sql);
mysql_fetch_array($result);
echo "images/$result";
?>
```

答:
The code posted with the question has used mysql_query / mysql_fetch_array which is deprecated to use in PHP anymore. Even with deprecated mysql_* version, this part

```<code>mysql_fetch_array($result);
echo "images/$result";
</code>```

of posted code should be

```<code>$row = mysql_fetch_array($result, MYSQL_ASSOC);
echo "images/".$row["image"];
</code>```

(I haven't tested this code as PHP version in my machine is above 5.5 which doesn't support mysql_* extensions).

Each row requires being fetched from the result ($result) of SQL query. From the fetched row ($row) each cell can be accessed using the column header (image).

Try following code in getimage.php,

```<code><?php
    $id = $_GET['id'];

    $db = new mysqli("host", "username", "password", "DB name");
    $sql = "SELECT image FROM images WHERE imageID=$id";

    $result=$db->query($sql);

    $row = $result->fetch_assoc();

    echo 'images/'.$row['image'];
?>
</code>```

FYI, mysqli supports both procedural and object-oriented programming paradigm. http://php.net/manual/en/mysqli.quickstart.dual-interface.php

Body:
I have a problem displaying images for URLs that are saved in a database.

This is my HTML source code:

Download

And my getImage.php file:

<?php
$id = $_GET['id'];
$db = mysqli_connect("host", "username", "password", "DB name");
$sql = "SELECT image FROM images WHERE imageID=$id";
$result=mysql_query($sql);
mysql_fetch_array($result);
echo "images/$result";
?>

Body:
The code posted with the question has used mysql_query / mysql_fetch_array which is deprecated to use in PHP anymore. Even with deprecated mysql_* version, this part

mysql_fetch_array($result);
echo "images/$result";

of posted code should be

$row = mysql_fetch_array($result, MYSQL_ASSOC);
echo "images/".$row["image"];

(I haven't tested this code as PHP version in my machine is above 5.5 which doesn't support mysql_* extensions).

Each row requires being fetched from the result ($result) of SQL query. From the fetched row ($row) each cell can be accessed using the column header (image).

Try following code in getimage.php,

<?php
    $id = $_GET['id'];

    $db = new mysqli("host", "username", "password", "DB name");
    $sql = "SELECT image FROM images WHERE imageID=$id";

    $result=$db->query($sql);

    $row = $result->fetch_assoc();

    echo 'images/'.$row['image'];
?>

FYI, mysqli supports both procedural and object-oriented programming paradigm. http://php.net/manual/en/mysqli.quickstart.dual-interface.php


问:
Where is cached RDD stored (i.e. in a distributed way or on a single node)?
When we cache an RDD in Spark, is it then stored in a distributed way or on a single node? In which systems memory is it stored?</p>

答:
cache is a lazy operator (it's more a hint than a transformation or an action in RDD sense).

Quoting the scaladoc of cache:

cache(): RDD.this.type Persist this RDD with the default storage level (MEMORY_ONLY).

When a Spark application is submitted for execution (using spark-submit) it requests Spark executors. Quoting the official documentation's Components:

Once connected, Spark acquires executors on nodes in the cluster, which are processes that run computations and store data for your application.

Every executor starts its own BlockManager (with BlockManagerMaster hosted on the driver). Quoting Mastering Apache Spark gitbook:

BlockManager is a key-value store for blocks of data (simply blocks) in Spark. BlockManager acts as a local cache that runs on every "node" in a Spark application, i.e. the driver and executors.

Once you execute an action, it triggers loading the dataset from external data sources and the data starts flowing through the Spark distributed computation pipeline.

That's when the data gets cached in every BlockManager that participates in the computation. Their number is exactly the number of partitions of the RDD that was cached and can be checked using so-called RDD lineage:

RDD Lineage (aka RDD operator graph or RDD dependency graph) is a graph of all the parent RDDs of a RDD. It is built as a result of applying transformations to the RDD and creates a logical execution plan.

You can see the RDD lineage of a Spark computation using RDD.toDebugString:

toDebugString: String A description of this RDD and its recursive dependencies for debugging.

One could be as follows:

```<code>val rdd = sc.parallelize(0 to 9).groupBy(_ % 3).flatMap { case (_, ns) => ns }
scala> rdd.toDebugString
res4: String =
(8) MapPartitionsRDD[7] at flatMap at <console>:24 []
 |  ShuffledRDD[6] at groupBy at <console>:24 []
 +-(8) MapPartitionsRDD[5] at groupBy at <console>:24 []
    |  ParallelCollectionRDD[4] at parallelize at <console>:24 []
</code>```

(8 partitions are due to local[*] master URL that I used to start spark-shell with * mapped to the number of CPU cores on my machine)

Actually, the number of BlockManagers in use is the number of tasks per stage (in a Spark job) and could be as many as the number of Spark executors. It varies per stage.

Wrapping up...

When we cache an RDD in Spark, is it then stored in a distributed way or on a single node?

Distributed way, but could happen to be on a single node if the number of partitions in a stage is 1.

In which systems memory is it stored?

In "systems memory" of the Spark executor that hosts the BlockManager which happens to be in charge of RDD blocks.

RDD is a description of a distributed computation and is "gone" when DAGScheduler (that runs on the driver) maps it to TaskSets per stage with as many tasks as partitions.

RDD and partitions "disappear" once you execute an action and are transformed into stages and tasks.

Body:
cache is a lazy operator (it's more a hint than a transformation or an action in RDD sense).

Quoting the scaladoc of cache:

cache(): RDD.this.type Persist this RDD with the default storage level (MEMORY_ONLY).

When a Spark application is submitted for execution (using spark-submit) it requests Spark executors. Quoting the official documentation's Components:

Once connected, Spark acquires executors on nodes in the cluster, which are processes that run computations and store data for your application.

Every executor starts its own BlockManager (with BlockManagerMaster hosted on the driver). Quoting Mastering Apache Spark gitbook:

BlockManager is a key-value store for blocks of data (simply blocks) in Spark. BlockManager acts as a local cache that runs on every "node" in a Spark application, i.e. the driver and executors.

Once you execute an action, it triggers loading the dataset from external data sources and the data starts flowing through the Spark distributed computation pipeline.

That's when the data gets cached in every BlockManager that participates in the computation. Their number is exactly the number of partitions of the RDD that was cached and can be checked using so-called RDD lineage:

RDD Lineage (aka RDD operator graph or RDD dependency graph) is a graph of all the parent RDDs of a RDD. It is built as a result of applying transformations to the RDD and creates a logical execution plan.

You can see the RDD lineage of a Spark computation using RDD.toDebugString:

toDebugString: String A description of this RDD and its recursive dependencies for debugging.

One could be as follows:

val rdd = sc.parallelize(0 to 9).groupBy(_ % 3).flatMap { case (_, ns) => ns }
scala> rdd.toDebugString
res4: String =
(8) MapPartitionsRDD[7] at flatMap at <console>:24 []
 |  ShuffledRDD[6] at groupBy at <console>:24 []
 +-(8) MapPartitionsRDD[5] at groupBy at <console>:24 []
    |  ParallelCollectionRDD[4] at parallelize at <console>:24 []

(8 partitions are due to local[*] master URL that I used to start spark-shell with * mapped to the number of CPU cores on my machine)

Actually, the number of BlockManagers in use is the number of tasks per stage (in a Spark job) and could be as many as the number of Spark executors. It varies per stage.

Wrapping up...

When we cache an RDD in Spark, is it then stored in a distributed way or on a single node?

Distributed way, but could happen to be on a single node if the number of partitions in a stage is 1.

In which systems memory is it stored?

In "systems memory" of the Spark executor that hosts the BlockManager which happens to be in charge of RDD blocks.

RDD is a description of a distributed computation and is "gone" when DAGScheduler (that runs on the driver) maps it to TaskSets per stage with as many tasks as partitions.

RDD and partitions "disappear" once you execute an action and are transformed into stages and tasks.


问:
countourf doesn't show colored regions in Matlab
What should I change in my code that countorf shows regions with more color differences?</p>

```<code>clear all;
close all;
phi=90;
[xx,yy] = meshgrid(-20:0.1:20,-20:0.1:20);
Idontwantthis = (xx.^2+yy.^2)<0.1;
u = (xx./(xx.^2+yy.^2).^(3/2));
v = (yy./(xx.^2+yy.^2).^(3/2));
data= sqrt(u.^2+v.^2);
data(Idontwantthis)=NaN;
u(Idontwantthis)=NaN;
v(Idontwantthis)=NaN;
contourf(xx,yy,data,20);
</code>```

答:
First, you don't need meshgrid over [-20 20]. Try reducing the range to like [-2 2]. After you run contourf, change colormap:

```<code>clear all;
close all;
phi=90;

[xx,yy] = meshgrid(-2:0.01:2,-2:0.01:2);

Idontwantthis = (xx.^2+yy.^2)<0.1;
u = (xx./(xx.^2+yy.^2).^(3/2));
v = (yy./(xx.^2+yy.^2).^(3/2));
data= sqrt(u.^2+v.^2);
data(Idontwantthis)=NaN;
u(Idontwantthis)=NaN;
v(Idontwantthis)=NaN;

contourf(xx,yy,data,20);
colormap hsv;
</code>```

This is what your result will look like:

Hope that helps!

Body:
What should I change in my code that countorf shows regions with more color differences?

clear all;
close all;
phi=90;
[xx,yy] = meshgrid(-20:0.1:20,-20:0.1:20);
Idontwantthis = (xx.^2+yy.^2)<0.1;
u = (xx./(xx.^2+yy.^2).^(3/2));
v = (yy./(xx.^2+yy.^2).^(3/2));
data= sqrt(u.^2+v.^2);
data(Idontwantthis)=NaN;
u(Idontwantthis)=NaN;
v(Idontwantthis)=NaN;
contourf(xx,yy,data,20);

Body:
First, you don't need meshgrid over [-20 20]. Try reducing the range to like [-2 2]. After you run contourf, change colormap:

clear all;
close all;
phi=90;

[xx,yy] = meshgrid(-2:0.01:2,-2:0.01:2);

Idontwantthis = (xx.^2+yy.^2)<0.1;
u = (xx./(xx.^2+yy.^2).^(3/2));
v = (yy./(xx.^2+yy.^2).^(3/2));
data= sqrt(u.^2+v.^2);
data(Idontwantthis)=NaN;
u(Idontwantthis)=NaN;
v(Idontwantthis)=NaN;

contourf(xx,yy,data,20);
colormap hsv;

This is what your result will look like:

Hope that helps!


问:
clearInterval not working when clicked left and right mouse button at the same time
```

    myDirectives.directive("mouseholdevent", function () {
    return {
        restrict: 'A',
        link: function (scope, element) {
            var el = element[0];
            el.mousehold = true;
            var setint = '';
            var rightClick = false;
            ele(element).mousedown(function (e) {
                setint = setInterval(function () {
                    if (rightClick) {
                        clearInterval(setint);
                    } else {
                        if (element.hasClass("zoom_out")) {
                            scope.zoomOutOnCanvasImage();
                        } else if (element.hasClass("zoom_in")) {
                            scope.zoomInOnCanvasImage();
                        }
                    }
                }, 100);
            });
            ele(element).on("mouseleave mouseup contextmenu", function () {
                rightClick = true;
                clearInterval(setint);
            });
        }
    };
});

```

答:
```

    myDirectives.directive("mouseholdevent", function () {
    return {
        restrict: 'A',
        link: function (scope, element) {
            var setint = '';
            ele(element).mousedown(function (e) {
                clearInterval(setint);
                if (e.button === 2) {
                    return false;
                }
                setint = setInterval(function () {
                    if (element.hasClass("zoom_out")) {
                        scope.zoomOutOnCanvasImage();
                    } else if (element.hasClass("zoom_in")) {
                        scope.zoomInOnCanvasImage();
                    }
                }, 100);
            });
            ele(element).on("mouseleave mouseup", function () {
                clearInterval(setint);
            });
        }
    };
});

```


问:
Modifying a json collection within jquery
I have a list of invoices displayed on the screen.  Right now, a user can select or unselect an invoice with a checkbox or change the amount they would like to pay.  When this happens, the total amount to be paid for all invoices is being summed up and displayed.

The ultimate goal here is to keep track of an array of arrays of data, which comes from the server.  I'm using json because it is standardized.

Then I have a hidden with json data like so:

```<code><input id="InvoicingGridRows" name="InvoicingGridRows" type="hidden"
value="[[{"Value":"TST-1000"},{"Value":346.230000},
{"Value":null},{"Value":null},{"Value":null},
{"Value":null}],
[{"Value":"TST-1001"},
{"Value":126.970000},{"Value":null},{"Value":null},
{"Value":null},{"Value":null}]]" />
</code>```

Right now, the data has a lot of empty placeholders for data.

What I am trying to do is create a javascript object so that when the events happen above that cause the summation to occur, I can initiate targeted edits/deletes/adds.  Here;s what I have so far.

```<code>var invoiceRows = function () {
    var targetControl = '';

    var getByInvoiceId = function (invoiceId) {
        var data = $(targetControl.val());

        for (var x = 0; x < data.length; x++) {
            if (data[x][0].Value == invoiceId)
                return data[x];
        }

        return null;
    };

    return {

        init: function (selector, invoices) {
            targetControl = $(selector);

            //set up the gridrows to defaulted values
            targetControl.val(invoices);
        },

        save: function (invoiceId, amount) {
            var invoiceData = getByInvoiceId(invoiceId);

            if (invoiceData) {
                //update
            } else {
                //add new
            }
        },

        remove: function (invoiceId) {
            //remove row with invoiceid
        }

    }

} ();
</code>```

My question is how do I easily modify/delete rows as well as add new rows into my json object, and then save it back into the hidden field? Is that even possible or is there a better way?  I'm open to suggestions.

答:
You can convert the string in the hidden input into a javascript object by using eval:

```<code>var dataObj = eval($("#InvoicingGridRows").val());
</code>```

I'd do this only once, and then do all your operations such as remove on this object. When you're ready to send it back to the server, convert the object back into a string:

```<code>var dataStr = JSON.stringify(dataObj);
$("#InvoicingGridRows").val(dataStr);
</code>```

Alternatively, if you can modify how your server works, get the server to create a
```

No need for eval() now.

Body:
I have a list of invoices displayed on the screen.  Right now, a user can select or unselect an invoice with a checkbox or change the amount they would like to pay.  When this happens, the total amount to be paid for all invoices is being summed up and displayed.

The ultimate goal here is to keep track of an array of arrays of data, which comes from the server.  I'm using json because it is standardized.

Then I have a hidden with json data like so:

<input id="InvoicingGridRows" name="InvoicingGridRows" type="hidden"
value="[[{"Value":"TST-1000"},{"Value":346.230000},
{"Value":null},{"Value":null},{"Value":null},
{"Value":null}],
[{"Value":"TST-1001"},
{"Value":126.970000},{"Value":null},{"Value":null},
{"Value":null},{"Value":null}]]" />

Right now, the data has a lot of empty placeholders for data.

What I am trying to do is create a javascript object so that when the events happen above that cause the summation to occur, I can initiate targeted edits/deletes/adds.  Here;s what I have so far.

var invoiceRows = function () {
    var targetControl = '';

    var getByInvoiceId = function (invoiceId) {
        var data = $(targetControl.val());

        for (var x = 0; x < data.length; x++) {
            if (data[x][0].Value == invoiceId)
                return data[x];
        }

        return null;
    };

    return {

        init: function (selector, invoices) {
            targetControl = $(selector);

            //set up the gridrows to defaulted values
            targetControl.val(invoices);
        },

        save: function (invoiceId, amount) {
            var invoiceData = getByInvoiceId(invoiceId);

            if (invoiceData) {
                //update
            } else {
                //add new
            }
        },

        remove: function (invoiceId) {
            //remove row with invoiceid
        }

    }

} ();

My question is how do I easily modify/delete rows as well as add new rows into my json object, and then save it back into the hidden field? Is that even possible or is there a better way?  I'm open to suggestions.

Body:
You can convert the string in the hidden input into a javascript object by using eval:

var dataObj = eval($("#InvoicingGridRows").val());

I'd do this only once, and then do all your operations such as remove on this object. When you're ready to send it back to the server, convert the object back into a string:

var dataStr = JSON.stringify(dataObj);
$("#InvoicingGridRows").val(dataStr);

Alternatively, if you can modify how your server works, get the server to create a <script> tag containing the data ready for use as a javascript object - basically the string in the hidden input, but without the quotes around the whole thing and with a variable assignment in front of it. E.g. get your server to output:

<script type="text/javascript">
   var dataObj = {...};
</script>

No need for eval() now.


问:
trigger d3.js update when data changes using angular.js
I am using Angular.js to create some visualizations. I got a directive for a bar chart that looks like this:

```<code>angular.module('MissionControlApp').directive('d3Bars', ['d3', function(d3) {
    return {
        restrict: 'EA',
        scope: {
            data: "=",
            label: "=",
            onClick: "&"
        },
        link: function(scope, iElement) {
            var svg = d3.select(iElement[0])
                .append("svg")
                .attr("width", "100%");

            // on window resize, re-render d3 canvas
            window.onresize = function() {
                return scope.$apply();
            };
            scope.$watch(function(){
                    return angular.element(window)[0].innerWidth;
                }, function(){
                    return scope.render(scope.data);
                }
            );

            // watch for data changes and re-render
            scope.$watch('data', function(newVals) {
                return scope.render(newVals);
            }, true);

            // define render function
            scope.render = function(data){
                if(data === undefined){
                    return;
                }
                // remove all previous items before render
                svg.selectAll("*").remove();

                // setup variables
                var width, height, max;
                var margin = {top: 5, right: 30, bottom: 10, left: 150};

                width = d3.select(iElement[0])[0][0].offsetWidth - margin.left - margin.right;
                height = (scope.data.length * 35) + margin.top + margin.bottom;
                max = 100;

                // set the height based on the calculations above
                svg.attr('height', height);

                var x = d3.scale.linear()
                    .domain([0, 100])
                    .range([0, width]);

                var y = d3.scale.ordinal()
                    .domain(data.map(function (d) { return d.user; }))
                    .rangeBands([0, height], 0.1, 0.35);

                // var color = d3.scale.category20c();
                var color = d3.scale.linear()
                    .domain([0, 25, 50, 75, 100])
                    .range(["#51b75d", "#90eb9d","#ffff8c","#f5c93f","#c45c44"])
                    .interpolate(d3.interpolateHcl);

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .orient("bottom")
                    .innerTickSize(-(height-5));

                //create the rectangles for the bar chart
                svg.selectAll("rect")
                    .data(data)
                    .enter()
                    .append("rect")
                    .attr("fill", function(d){return color(d.value); })
                    .on("click", function(d){return scope.onClick({item: d});})
                    .attr("height", y.rangeBand()) // height of each bar
                    .attr("width", 0) // initial width of 0 for transition
                    .attr("x", margin.left) // half of the 20 side margin specified above
                    .attr("y", function (d) { return y(d.user); }) // height + margin between bars
                    .transition()
                    .duration(1000)
                    .attr("width", function(d){ return d.value/(max/width); });

                svg.selectAll("text")
                    .data(data)
                    .enter()
                    .append("text")
                    .attr("fill", "#000")
                    .attr("y", function(d){return y(d.user) + (y.rangeBand() / 2);})
                    .attr("x", 150)
                    .attr("text-anchor", "end")
                    .attr("dy", ".35em")
                    .attr("dx", -5)
                    .text(function(d){return d[scope.label];});

                svg.append("g")
                    .selectAll("valueLabels")
                    .data(data)
                    .enter()
                    .append("text")
                    .attr("fill", "#000")
                    .attr("y", function(d){return y(d.user) + (y.rangeBand() / 2);})
                    .attr("x", function(d){return x(d.value) + margin.left;})
                    .attr("dx", 5)
                    .attr("dy", ".35em")
                    .text(function(d){return parseFloat(d.value).toFixed(0) + "%";})
                    .attr("fill-opacity", 0)
                    .transition()
                    .duration(1500)
                    .attr("fill-opacity", 1);

                svg.append("g")
                    .attr("class", "x axisHorizontal")
                    .attr("transform", "translate(" +  margin.left + "," + (height-margin.bottom) + ")")
                    .call(xAxis);
            };
        }
    };
}]);
</code>```

This defines a "onClick" event which in turns sets a piece of data in my controller like so:

```<code>vm.d3OnClick = function(item){
        // item {user: konrad.sobon, value: 26}
        SetUserData(item);
    };

    function SetUserData (item) {
        var allData = vm.selectedWorkset.onOpened;
        var userData = [];
        allData.forEach(function (d) {
            if(d.user === item.user){
                userData.push({
                    name: d.user,
                    value: (d.opened * 100) / (d.closed + d.opened),
                    createdOn: d.createdOn
                })
            }
        });
        console.log("SettingData to: ", userData);
        vm.userData = userData;
    }
</code>```

vm.userData is being used to construct a different chart which looks like this:

```<code>angular.module('MissionControlApp').directive('d3WorksetUser', ['d3', function(d3) {
    return {
        restrict: 'E',
        scope: {
            data: "=",
            label: "=",
            onClick: "&"
        },
        link: function(scope, iElement) {
            var svg = d3.select(iElement[0])
                .append("svg")
                .attr("width", "100%");

            // on window resize, re-render d3 canvas
            window.onresize = function() {
                return scope.$apply();
            };
            scope.$watch(function(){
                    return angular.element(window)[0].innerWidth;
                }, function(){
                    return scope.render(scope.data);
                }
            );

            // watch for data changes and re-render
            scope.$watch('data', function(newVals) {
                return scope.render(newVals);
            }, true);

            // define render function
            scope.render = function(data){
                if(data === undefined){
                    return;
                }
                // remove all previous items before render
                svg.selectAll("*").remove();

                // setup variables
                var width, height;
                var margin = {top: 5, right: 10, bottom: 20, left: 25};

                width = d3.select(iElement[0])[0][0].offsetWidth - margin.left - margin.right;
                height = 300 - margin.top - margin.bottom;

                // set the height based on the calculations above
                svg.attr('height', height + margin.top + margin.bottom);

                var parseDate = d3.time.format('%Y-%m-%dT%H:%M:%S.%LZ').parse;

                var x = d3.time.scale().range([0, width]);
                var y = d3.scale.linear().range([height, 0]);

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .orient("bottom")
                    .ticks(5);

                var yAxis = d3.svg.axis()
                    .scale(y)
                    .orient("left")
                    .ticks(9);

                var line = d3.svg.line()
                    .x(function(d) { return x(d.date) + margin.left; })
                    .y(function(d) { return y(d.value); });

                data.forEach(function(d) {
                    d.date = parseDate(d.createdOn);
                    d.value = +d.value;
                });

                x.domain(d3.extent(data, function(d) { return d.date; }));
                y.domain([0, 100]);

                // Add the valueline path.
                svg.append("path")
                    .datum(data)
                    .attr("d", line)
                    .attr("stroke", "steelblue")
                    .attr("fill", "none")
                    .attr("stroke-width", 1.5);

                // Add the X Axis
                svg.append("g")
                    .attr("class", "axisMain")
                    .attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
                    .call(xAxis);

                // Add the Y Axis
                svg.append("g")
                    .attr("class", "axisMain")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .call(yAxis);
            };
        }
    };
}]);
</code>```

When I am debugging this in Chrome i can see that my click events trigger the appropriate methods on my controller and that vm.userData gets set to new data, but my line chart doesn't update...basically nothing happens. Is there something obvious that I am missing that will make the click event in one chart refresh/redraw the other chart?

HTML:

```<code><div class="row">
    <div class="panel-group" id="accordion">
        <div class="panel panel-default">
            <div class="panel-heading" data-toggle="collapse" data-parent="#accordion" data-target="#collapseOne">
                <h4 class="panel-title">Workset on Opened</h4>
            </div>
            <div id="collapseOne" class="panel-collapse collapse in">
                <div class="panel-body">
                    <d3-bars data="vm.DataOpened" label="vm.d3Label" on-click="vm.d3OnClick(item)"></d3-bars>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="panel-group" id="userDetail">
        <div class="panel panel-default">
            <div class="panel-heading" data-toggle="collapse" data-parent="#userDetail" data-target="#collapseUserDetail">
                <h4 class="panel-title">User detail info.</h4>
            </div>
            <div id="collapseUserDetail" class="panel-collapse collapse in">
                <div class="panel-body">
                    <d3-workset-user data="vm.userData"></d3-workset-user>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Both charts draw fine on the first load, but then the second one never updates.

Here's a console log to support that:

Where: Setting data to: is fired by the controller when i first get the data from the server and set it.
Then my scope.$watch fires twice in response to that. I think the first one is when data is still undefined and then again after it was resolved.
Finally there are events associated with mouse click and data being updated but as you can see watch never re-fires.

答:
Change your second $watch function to the following:

```<code>// watch for data changes and re-render
scope.$watch('data', function(newVals) {
    $timeout(function() { scope.render(newVals) });
}, true);
</code>```

I would still keep the $watch and use $timeout instead of $interval so your application doesn't waste digest cycles.

This happens because scope.$watch gets triggered inside a digest cycle, and because angular is event-based, changing a value inside the cycle doesn't re-trigger the watches. A $timeout with 0 ms timeout schedules another digest cycle after the current one. Basically (iirc), $timeout is a setTimeout with a scope.$apply inside of it.

Body:
I am using Angular.js to create some visualizations. I got a directive for a bar chart that looks like this:

angular.module('MissionControlApp').directive('d3Bars', ['d3', function(d3) {
    return {
        restrict: 'EA',
        scope: {
            data: "=",
            label: "=",
            onClick: "&"
        },
        link: function(scope, iElement) {
            var svg = d3.select(iElement[0])
                .append("svg")
                .attr("width", "100%");

            // on window resize, re-render d3 canvas
            window.onresize = function() {
                return scope.$apply();
            };
            scope.$watch(function(){
                    return angular.element(window)[0].innerWidth;
                }, function(){
                    return scope.render(scope.data);
                }
            );

            // watch for data changes and re-render
            scope.$watch('data', function(newVals) {
                return scope.render(newVals);
            }, true);

            // define render function
            scope.render = function(data){
                if(data === undefined){
                    return;
                }
                // remove all previous items before render
                svg.selectAll("*").remove();

                // setup variables
                var width, height, max;
                var margin = {top: 5, right: 30, bottom: 10, left: 150};

                width = d3.select(iElement[0])[0][0].offsetWidth - margin.left - margin.right;
                height = (scope.data.length * 35) + margin.top + margin.bottom;
                max = 100;

                // set the height based on the calculations above
                svg.attr('height', height);

                var x = d3.scale.linear()
                    .domain([0, 100])
                    .range([0, width]);

                var y = d3.scale.ordinal()
                    .domain(data.map(function (d) { return d.user; }))
                    .rangeBands([0, height], 0.1, 0.35);

                // var color = d3.scale.category20c();
                var color = d3.scale.linear()
                    .domain([0, 25, 50, 75, 100])
                    .range(["#51b75d", "#90eb9d","#ffff8c","#f5c93f","#c45c44"])
                    .interpolate(d3.interpolateHcl);

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .orient("bottom")
                    .innerTickSize(-(height-5));

                //create the rectangles for the bar chart
                svg.selectAll("rect")
                    .data(data)
                    .enter()
                    .append("rect")
                    .attr("fill", function(d){return color(d.value); })
                    .on("click", function(d){return scope.onClick({item: d});})
                    .attr("height", y.rangeBand()) // height of each bar
                    .attr("width", 0) // initial width of 0 for transition
                    .attr("x", margin.left) // half of the 20 side margin specified above
                    .attr("y", function (d) { return y(d.user); }) // height + margin between bars
                    .transition()
                    .duration(1000)
                    .attr("width", function(d){ return d.value/(max/width); });

                svg.selectAll("text")
                    .data(data)
                    .enter()
                    .append("text")
                    .attr("fill", "#000")
                    .attr("y", function(d){return y(d.user) + (y.rangeBand() / 2);})
                    .attr("x", 150)
                    .attr("text-anchor", "end")
                    .attr("dy", ".35em")
                    .attr("dx", -5)
                    .text(function(d){return d[scope.label];});

                svg.append("g")
                    .selectAll("valueLabels")
                    .data(data)
                    .enter()
                    .append("text")
                    .attr("fill", "#000")
                    .attr("y", function(d){return y(d.user) + (y.rangeBand() / 2);})
                    .attr("x", function(d){return x(d.value) + margin.left;})
                    .attr("dx", 5)
                    .attr("dy", ".35em")
                    .text(function(d){return parseFloat(d.value).toFixed(0) + "%";})
                    .attr("fill-opacity", 0)
                    .transition()
                    .duration(1500)
                    .attr("fill-opacity", 1);

                svg.append("g")
                    .attr("class", "x axisHorizontal")
                    .attr("transform", "translate(" +  margin.left + "," + (height-margin.bottom) + ")")
                    .call(xAxis);
            };
        }
    };
}]);

This defines a "onClick" event which in turns sets a piece of data in my controller like so:

vm.d3OnClick = function(item){
        // item {user: konrad.sobon, value: 26}
        SetUserData(item);
    };

    function SetUserData (item) {
        var allData = vm.selectedWorkset.onOpened;
        var userData = [];
        allData.forEach(function (d) {
            if(d.user === item.user){
                userData.push({
                    name: d.user,
                    value: (d.opened * 100) / (d.closed + d.opened),
                    createdOn: d.createdOn
                })
            }
        });
        console.log("SettingData to: ", userData);
        vm.userData = userData;
    }

vm.userData is being used to construct a different chart which looks like this:

angular.module('MissionControlApp').directive('d3WorksetUser', ['d3', function(d3) {
    return {
        restrict: 'E',
        scope: {
            data: "=",
            label: "=",
            onClick: "&"
        },
        link: function(scope, iElement) {
            var svg = d3.select(iElement[0])
                .append("svg")
                .attr("width", "100%");

            // on window resize, re-render d3 canvas
            window.onresize = function() {
                return scope.$apply();
            };
            scope.$watch(function(){
                    return angular.element(window)[0].innerWidth;
                }, function(){
                    return scope.render(scope.data);
                }
            );

            // watch for data changes and re-render
            scope.$watch('data', function(newVals) {
                return scope.render(newVals);
            }, true);

            // define render function
            scope.render = function(data){
                if(data === undefined){
                    return;
                }
                // remove all previous items before render
                svg.selectAll("*").remove();

                // setup variables
                var width, height;
                var margin = {top: 5, right: 10, bottom: 20, left: 25};

                width = d3.select(iElement[0])[0][0].offsetWidth - margin.left - margin.right;
                height = 300 - margin.top - margin.bottom;

                // set the height based on the calculations above
                svg.attr('height', height + margin.top + margin.bottom);

                var parseDate = d3.time.format('%Y-%m-%dT%H:%M:%S.%LZ').parse;

                var x = d3.time.scale().range([0, width]);
                var y = d3.scale.linear().range([height, 0]);

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .orient("bottom")
                    .ticks(5);

                var yAxis = d3.svg.axis()
                    .scale(y)
                    .orient("left")
                    .ticks(9);

                var line = d3.svg.line()
                    .x(function(d) { return x(d.date) + margin.left; })
                    .y(function(d) { return y(d.value); });

                data.forEach(function(d) {
                    d.date = parseDate(d.createdOn);
                    d.value = +d.value;
                });

                x.domain(d3.extent(data, function(d) { return d.date; }));
                y.domain([0, 100]);

                // Add the valueline path.
                svg.append("path")
                    .datum(data)
                    .attr("d", line)
                    .attr("stroke", "steelblue")
                    .attr("fill", "none")
                    .attr("stroke-width", 1.5);

                // Add the X Axis
                svg.append("g")
                    .attr("class", "axisMain")
                    .attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
                    .call(xAxis);

                // Add the Y Axis
                svg.append("g")
                    .attr("class", "axisMain")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .call(yAxis);
            };
        }
    };
}]);

When I am debugging this in Chrome i can see that my click events trigger the appropriate methods on my controller and that vm.userData gets set to new data, but my line chart doesn't update...basically nothing happens. Is there something obvious that I am missing that will make the click event in one chart refresh/redraw the other chart?

HTML:

Workset on Opened

                    <d3-bars data="vm.DataOpened" label="vm.d3Label" on-click="vm.d3OnClick(item)"></d3-bars>

User detail info.

                    <d3-workset-user data="vm.userData"></d3-workset-user>

Both charts draw fine on the first load, but then the second one never updates.

Here's a console log to support that:

Where: Setting data to: is fired by the controller when i first get the data from the server and set it.
Then my scope.$watch fires twice in response to that. I think the first one is when data is still undefined and then again after it was resolved.
Finally there are events associated with mouse click and data being updated but as you can see watch never re-fires.

Body:
Change your second $watch function to the following:

// watch for data changes and re-render
scope.$watch('data', function(newVals) {
    $timeout(function() { scope.render(newVals) });
}, true);

I would still keep the $watch and use $timeout instead of $interval so your application doesn't waste digest cycles.

This happens because scope.$watch gets triggered inside a digest cycle, and because angular is event-based, changing a value inside the cycle doesn't re-trigger the watches. A $timeout with 0 ms timeout schedules another digest cycle after the current one. Basically (iirc), $timeout is a setTimeout with a scope.$apply inside of it.


问:
JS if else statements and timer
1)I have a problem with timer. It is starting when the screen loads, it should start on button START.
2)If else. When timer hits 00: 00 it should show message (alert) if i have won or lost. http://prntscr.com/ffi4bu wallvalue is constantly changing. My code is not working but you get the idea.

1)JS code timer

```<code>function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
 var timers = setInterval(runner, 1000);
 function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
       clearInterval(timers)
    }
  }

}

window.onload = function() {
  var oneMinutes = 60 * 1,
    display = document.querySelector('#time');
  startTimer(oneMinutes, display);
};
</code>```

HTML

```<code><div class="timer" ><b>Battle time: <span id="time"></span></b></div>
<BUTTON class="begin" onclick="startTimer(60,document.querySelector('#time'))"><b>START</b></BUTTON>
</code>```

2) JS

```<code>function finish(){
    var g = function startTimer;
    var h = document.getElementById('wallvalue');

if (function startTimer = 0 )&& ( h<500 ) {
    alert("You won!");
}
 else {
 alert("You lost!");
}
}
</code>```

答:
1st Remove your startTimer function call from window.onload if you want to call on button click. otherwise it will immediateload after window load.

```<code>window.onload = function() {
  var oneMinutes = 60 * 1,
  display = document.querySelector('#time');
  //startTimer(oneMinutes, display);
};
</code>```

Inside startTimer on "zero" value call finish and remove ambiguous function call lines from finish. Also just check "h" because "finsh" will be called when timer value is already zero.

```<code>function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}

function finish(){

var h = document.getElementById('wallvalue');

if ( h<500 ) {
    alert("You won!");
}
 else {
 alert("You lost!");
}
}
</code>```

Title: JS if else statements and timer

Body:
1)I have a problem with timer. It is starting when the screen loads, it should start on button START.
2)If else. When timer hits 00: 00 it should show message (alert) if i have won or lost. http://prntscr.com/ffi4bu wallvalue is constantly changing. My code is not working but you get the idea.

1)JS code timer

function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
 var timers = setInterval(runner, 1000);
 function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
       clearInterval(timers)
    }
  }

}

window.onload = function() {
  var oneMinutes = 60 * 1,
    display = document.querySelector('#time');
  startTimer(oneMinutes, display);
};

HTML

Battle time:

<BUTTON class="begin" onclick="startTimer(60,document.querySelector('#time'))">START</BUTTON>

2) JS

function finish(){
    var g = function startTimer;
    var h = document.getElementById('wallvalue');

if (function startTimer = 0 )&& ( h<500 ) {
    alert("You won!");
}
 else {
 alert("You lost!");
}
}

Body:
1st Remove your startTimer function call from window.onload if you want to call on button click. otherwise it will immediateload after window load.

window.onload = function() {
  var oneMinutes = 60 * 1,
  display = document.querySelector('#time');
  //startTimer(oneMinutes, display);
};

Inside startTimer on "zero" value call finish and remove ambiguous function call lines from finish. Also just check "h" because "finsh" will be called when timer value is already zero.

function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}

function finish(){

var h = document.getElementById('wallvalue');

if ( h<500 ) {
    alert("You won!");
}
 else {
 alert("You lost!");
}
}


问:
Add google fonts to html
I have html page and I want to add 2 google font to my page. And I try to add 2 fonts in one row:

```<code><link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Lato:300,400|Roboto:400">
</code>```

But I get validation error ( validator.w3.org )

```<code>Illegal character in query: | is not allowed.
</code>```

So is it possible to add 2 google fonts in one row?

答: Try to linking what google fonts generate for you after making the selection, since what you have up there looks a bit different. </p>

Title: Add google fonts to html

Body:
I have html page and I want to add 2 google font to my page. And I try to add 2 fonts in one row:

<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Lato:300,400|Roboto:400">

But I get validation error ( validator.w3.org )

Illegal character in query: | is not allowed.

So is it possible to add 2 google fonts in one row?