问:
Unable to apply background color to a login box when a background image is used in the body tag
On my login page, I have a background image attached to the body tag. On top of this image, I have a login box. But somehow I am not able to get a   background color to the login-box via class "bground_box" which i have applied to the div tag as shown below.

This is my css / html code.

```<code><style type="text/css">
  .bground { background: url(images/bg-turquoise-waves.jpg) no-repeat center center fixed; -webkit-background-size: cover;  -o-background-size: cover; background-size: cover;}
  .bground_box { background-color:#25A8AF border: 3px solid white; border-radius: 25px; }
  .turqousie_text { color:#75F8FF;}
  .pgheight {  height:100%;  min-height:100%; }

</style>

<body class="bground">

<div class="container">
  <div class="row">

   <!-- Login Box -->
   <div class="col-md-6 col-md-offset-3 bground_box">
    <h2 class="text-center turqousie_text"><strong>App Login</strong></h2><br/>
    <div class="col-md-6 col-md-offset-3">
     <form action="login.php" method="POST"  autocomplete="off" >
           <div class="form-group"><label for="uname"><span><i class="glyphicon glyphicon-user"></i></span> UserName</label>
              <input type="text" class="form-control" id="uname" name="uname" placeholder="Enter Your UserName">
           </div>
           <div class="form-group"><label for="upwd"><span><i class="glyphicon glyphicon-lock"></i></span> UserPassword</label>
              <input type="password" class="form-control" id="upwd" name="upwd" placeholder="Enter Your Password">
           </div>
           <button type="submit" name="login_button" class="btn btn-primary btn-block">Login</button>
     </form>
    </div>
    </div>
    <!-- end login box -->

</div> <!-- end  div row -->
</div> <!-- end  div container -->
</body>
</code>```

Note - the solid white border appears nicely around the login box. That part works. Just CANT get a background color in the login box

答: SOLVED by using !important on .bground_box  background-color. This allows an override of the image background. Thanks.</p>

Body:
On my login page, I have a background image attached to the body tag. On top of this image, I have a login box. But somehow I am not able to get a   background color to the login-box via class "bground_box" which i have applied to the div tag as shown below.

This is my css / html code.

App Login

     <form action="login.php" method="POST"  autocomplete="off" >

 UserName
              <input type="text" class="form-control" id="uname" name="uname" placeholder="Enter Your UserName">

 UserPassword
              <input type="password" class="form-control" id="upwd" name="upwd" placeholder="Enter Your Password">

           <button type="submit" name="login_button" class="btn btn-primary btn-block">Login</button>
     </form>

Note - the solid white border appears nicely around the login box. That part works. Just CANT get a background color in the login box


来源: stackexchange

问:
Passing a input value from one method to another
The following code is for a lab for the java course I'm taking for which just started the chapter on parameters and objects. I've hit a major choke-point past which I can't get past.

The issue I'm having is that I need to get the input assigned to destinationAmount, in the method GetAmountOfDestinations, to the method GetItinerary so I can use it in the for loop. I can't have any code within the main method other than the calls to the other methods. I cannot change the nature of the methods as the instructions say they must be made in a certain way.

Just how would I get the input to the other method? Do I create a third method to route the value through? I've looked for hours on this website and youtube and I haven't seen anything like this situation. I'd appreciate the help.

```<code>import java.util.*;
public class TripPlanner
{
  public static final Scanner CONSOLE = new Scanner ( System.in );
  public static void main(String [] args)
  {
    GetAmountOfDestinations();
    GetItinerary();
  }
  public static int GetAmountOfDestinations()
  {
    System.out.println( "Please enter the amount of destinations." );
    int destinationAmount = CONSOLE.nextInt();
    System.out.println( "You entered " + destinationAmount + "." );
  }
  public static void GetItinerary()
  {

    System.out.println( "Your starting airport is SAT." );

    int amountOfDestinations = ??????;
    System.out.println(amountOfDestinations);

    double currentDestinationLatitude = Airports.getAirportLatitude( "SAT" );
    double currentDestinationLongitude = Airports.getAirportLongitude( "SAT" );
    for( int x = 0; x <  amountOfDestinations; x = x + 1 )
    {
      System.out.println( "Please enter the next destination." );
      String nextDestination = CONSOLE.next();

      double nextDestinationLatitude = Airports.getAirportLatitude( nextDestination );
      double nextDestinationLongitude = Airports.getAirportLongitude( nextDestination );

      System.out.println( nextDestinationLatitude + " " + nextDestinationLongitude );
    }
  }
}
</code>```

答:
You need to read more about method return values and parameters to make sense of the code below. But all you need to do is use the value returned from one method and pass it as a parameter to the next method to achieve what you are trying to do. </p>

```<code>import java.util.*;
public class TripPlanner
{
  public static final Scanner CONSOLE = new Scanner ( System.in );
  public static void main(String [] args)
  {
    int amtDestinations = GetAmountOfDestinations();
    GetItinerary(amtDestinations);
  }
  public static int GetAmountOfDestinations()
  {
    System.out.println( "Please enter the amount of destinations." );
    int destinationAmount = CONSOLE.nextInt();
    System.out.println( "You entered " + destinationAmount + "." );
    return destinationAmount
  }
  public static void GetItinerary(int amountOfDestinations)
  {

    System.out.println( "Your starting airport is SAT." );

    System.out.println(amountOfDestinations);

    double currentDestinationLatitude = Airports.getAirportLatitude( "SAT" );
    double currentDestinationLongitude = Airports.getAirportLongitude( "SAT" );
    for( int x = 0; x <  amountOfDestinations; x = x + 1 )
    {
      System.out.println( "Please enter the next destination." );
      String nextDestination = CONSOLE.next();

      double nextDestinationLatitude = Airports.getAirportLatitude( nextDestination );
      double nextDestinationLongitude = Airports.getAirportLongitude( nextDestination );

      System.out.println( nextDestinationLatitude + " " + nextDestinationLongitude );
    }
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The following code is for a lab for the java course I'm taking for which just started the chapter on parameters and objects. I've hit a major choke-point past which I can't get past.

The issue I'm having is that I need to get the input assigned to destinationAmount, in the method GetAmountOfDestinations, to the method GetItinerary so I can use it in the for loop. I can't have any code within the main method other than the calls to the other methods. I cannot change the nature of the methods as the instructions say they must be made in a certain way.

Just how would I get the input to the other method? Do I create a third method to route the value through? I've looked for hours on this website and youtube and I haven't seen anything like this situation. I'd appreciate the help.

import java.util.*;
public class TripPlanner
{
  public static final Scanner CONSOLE = new Scanner ( System.in );
  public static void main(String [] args)
  {
    GetAmountOfDestinations();
    GetItinerary();
  }
  public static int GetAmountOfDestinations()
  {
    System.out.println( "Please enter the amount of destinations." );
    int destinationAmount = CONSOLE.nextInt();
    System.out.println( "You entered " + destinationAmount + "." );
  }
  public static void GetItinerary()
  {

    System.out.println( "Your starting airport is SAT." );

    int amountOfDestinations = ??????;
    System.out.println(amountOfDestinations);

    double currentDestinationLatitude = Airports.getAirportLatitude( "SAT" );
    double currentDestinationLongitude = Airports.getAirportLongitude( "SAT" );
    for( int x = 0; x <  amountOfDestinations; x = x + 1 )
    {
      System.out.println( "Please enter the next destination." );
      String nextDestination = CONSOLE.next();

      double nextDestinationLatitude = Airports.getAirportLatitude( nextDestination );
      double nextDestinationLongitude = Airports.getAirportLongitude( nextDestination );

      System.out.println( nextDestinationLatitude + " " + nextDestinationLongitude );
    }
  }
}

Body:
You need to read more about method return values and parameters to make sense of the code below. But all you need to do is use the value returned from one method and pass it as a parameter to the next method to achieve what you are trying to do.

import java.util.*;
public class TripPlanner
{
  public static final Scanner CONSOLE = new Scanner ( System.in );
  public static void main(String [] args)
  {
    int amtDestinations = GetAmountOfDestinations();
    GetItinerary(amtDestinations);
  }
  public static int GetAmountOfDestinations()
  {
    System.out.println( "Please enter the amount of destinations." );
    int destinationAmount = CONSOLE.nextInt();
    System.out.println( "You entered " + destinationAmount + "." );
    return destinationAmount
  }
  public static void GetItinerary(int amountOfDestinations)
  {

    System.out.println( "Your starting airport is SAT." );

    System.out.println(amountOfDestinations);

    double currentDestinationLatitude = Airports.getAirportLatitude( "SAT" );
    double currentDestinationLongitude = Airports.getAirportLongitude( "SAT" );
    for( int x = 0; x <  amountOfDestinations; x = x + 1 )
    {
      System.out.println( "Please enter the next destination." );
      String nextDestination = CONSOLE.next();

      double nextDestinationLatitude = Airports.getAirportLatitude( nextDestination );
      double nextDestinationLongitude = Airports.getAirportLongitude( nextDestination );

      System.out.println( nextDestinationLatitude + " " + nextDestinationLongitude );
    }
  }
}


问:
bash script for creating multiple files using forloop
I am brand new at bash script. I want to write a script using forloop which will give me the following line and execute also these lines.

```<code>gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 1000 -e 10000 -skip 10 -o 1.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 2000 -e 20000 -skip 10 -o 2.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 3000 -e 30000 -skip 10 -o 3.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 4000 -e 40000 -skip 10 -o 4.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 5000 -e 50000 -skip 10 -o 5.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 6000 -e 60000 -skip 10 -o 6.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 7000 -e 70000 -skip 10 -o 7.out
</code>```

....

答:
Using a basic bash for loop:</p>

```<code>for i in {1..7}; do
  gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b ${i}000 -e ${i}0000 -skip 10 -o $i.out
done
</code>```

Body:
I am brand new at bash script. I want to write a script using forloop which will give me the following line and execute also these lines.

gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 1000 -e 10000 -skip 10 -o 1.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 2000 -e 20000 -skip 10 -o 2.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 3000 -e 30000 -skip 10 -o 3.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 4000 -e 40000 -skip 10 -o 4.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 5000 -e 50000 -skip 10 -o 5.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 6000 -e 60000 -skip 10 -o 6.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 7000 -e 70000 -skip 10 -o 7.out

....

Body:
Using a basic bash for loop:

for i in {1..7}; do
  gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b ${i}000 -e ${i}0000 -skip 10 -o $i.out
done


问:
Compile extjs-all with only required components
I'm new in the extjs world. Currently I'm trying to remove unnecesary components from my ext-all.js file. How and where I can tell to the sencha cmd wich components compile in my ext-all.js to make use, for example, only of the grid?  </p>

<p>Note: I'm trying to use extjs without the directory structure recommended by the sencha's guides.   </p>

答:
Did you create your app with Sencha Cmd?

You are taking the wrong end. You don't have to remove unused code from ext-all.js.

You should not use ext-all.js at all. Sencha Cmd analyses your code and adds only those classes in the built app.js, that you really need.

After your comment, things become more clear.

How ExtJs works : You have a single, empty html file. All the layout is generated by JavaScript. Data is fetched via Ajax and managed in stores. There is never a page reload, and there is one single optimized js and css file in production. Also, there is a clear difference between development and production build, the latter contains only the minimal, minified code.

If you want to use symfony and extjs together, I think the first principle should be: Do symfony the symfony way, and do ExtJs te ExtJs way.

With this in mind I think you have two main options:

Embrace ExtJs: Opt for a single page app, ExtJs for the frontend, symfony for the backend, nest custom html inside ExtJs panels.

Use ExtJs as topping: go for a Symfony app, with here a ExtJs grid, and there an ExtJs chart. Create ExtJs widgets inside symfony html. You then have to find how to work with data, because the ExtJs way is quite different...

Either way, you will have a ExtJs directory structure nested into the Symfony directories. Sencha Cmd will build the ExtJs part and generate one single Js and one CSS file. This file will be optimized for your app. You will have one optimized js file not one for each page. Finally this is a better optimization, because you will load the whole js only once.

Body:
I'm new in the extjs world. Currently I'm trying to remove unnecesary components from my ext-all.js file. How and where I can tell to the sencha cmd wich components compile in my ext-all.js to make use, for example, only of the grid?

Note: I'm trying to use extjs without the directory structure recommended by the sencha's guides.


问:
Jpa: where put toString() custom methods?
I have used Netbeans to create automatically jpa entities starting from a db.
Now I need to insert some logic code inside these entities.
For example, first of all I need to write a custom toString() method for every
jpa entity class.
The problem is where I have to put that code ? I know that jpa classes could be
overwritten by Netbeans when I'll launch again the jpa "wizard" after the next db schema update.
So I'd like to write some entity logic without renounce the jpa auto-generation
features of Netbeans.
Does I need to use an external tools like a merging tools, a preprocessor
features or I need to implement some inheritance class or a specific pattern ?
In the past I have used Apache Cayenne. For every db entity it creates two java
classes. The first (the parent), with the fields entity mapping, and the second
 (an empty child class) as a container for the logic, which is never overwritten
(and nor regenerated).

Any advices will be appreciated.

Best regards from Italy

答:
Yes, I could use a revision control system to synchronize the custom source with the auto-generated code.
But is it correct to code business logic inside jpa entity class ???</p>

ContentLicense: CC BY-SA 2.5


问:
Select last duplicate row with different id Oracle 11g
I have a table that look like this:

The problem is I need to get the last record with duplicates in the column "NRODENUNCIA".

答:
You can use MAX(DENUNCIAID), along with GROUP BY... HAVING to find the duplicates and select the row with the largest DENUNCIAID:

```<code>SELECT MAX(DENUNCIAID), NRODENUNCIA, FECHAEMISION, ADUANA, MES, NOMBREESTADO
FROM YourTable
GROUP BY NRODENUNCIA, FECHAEMISION, ADUANA, MES, NOMBREESTADO
HAVING COUNT(1) > 1
</code>```

This will only show rows that have at least one duplicate.  If you want to see non-duplicate rows too, just remove the HAVING COUNT(1) > 1

ContentLicense: CC BY-SA 4.0

Body:
You can use MAX(DENUNCIAID), along with GROUP BY... HAVING to find the duplicates and select the row with the largest DENUNCIAID:

SELECT MAX(DENUNCIAID), NRODENUNCIA, FECHAEMISION, ADUANA, MES, NOMBREESTADO
FROM YourTable
GROUP BY NRODENUNCIA, FECHAEMISION, ADUANA, MES, NOMBREESTADO
HAVING COUNT(1) > 1

This will only show rows that have at least one duplicate.  If you want to see non-duplicate rows too, just remove the HAVING COUNT(1) > 1


问:
How to make a regex to check for other symbols than a given string?
I need to make a regex that checks if an input string contains symbols other than symbols that I have in the charRange string.

given string:

```<code>string charRange =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&\"";
</code>```

答:
Here is full example how you should use this :

```<code>    string charRange = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;\-?! '()$%&""";
    foreach(Match a in new Regex("[^"+charRange+"]").Matches("-7Rt1Vp2RV"))
    {
        Console.WriteLine(a.Value);
    }
</code>```

- is special symbol and must be with \.
That was the reason you get true.

Body:
I need to make a regex that checks if an input string contains symbols other than symbols that I have in the charRange string.

given string:

string charRange =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&\"";

Body:
Here is full example how you should use this :

    string charRange = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;\-?! '()$%&""";
    foreach(Match a in new Regex("[^"+charRange+"]").Matches("-7Rt1Vp2RV"))
    {
        Console.WriteLine(a.Value);
    }

- is special symbol and must be with \.
That was the reason you get true.


问:
jqueryui remove styling applied to buttons in modal form
Im a complete beginner with jquery and need some help please.

Im using jqueryui, Im using the modal form: http://jqueryui.com/demos/dialog/#modal-form

Ive got this working fine, However I want it so that a regular looking hyperlink can invoke this dialog. Anything I use just appears as the "create new user" like from the example above.

How can I remove all this styling, and just make a regular unstyled hyperlink invoke the dialog

答:
The button's classes are as follows:

```<code>.ui-state-default, .ui-widget-content .ui-state-default
</code>```

You can find these in CSS and change the styles to fit your design :)

OR you can override them by putting them further down teh cascade (Nearer the bottom of teh CSS file) and this will override any default CSS styles.

Body:
The button's classes are as follows:

.ui-state-default, .ui-widget-content .ui-state-default

You can find these in CSS and change the styles to fit your design :)

OR you can override them by putting them further down teh cascade (Nearer the bottom of teh CSS file) and this will override any default CSS styles.


问:
Ncurses and Linux pipeline
I'd like to write a simple program using ncurses for displaying some data.  I would then like for the program to write to stdout in such a way that I can then use a pipe (|) on the command line to pipe some data out.

My current attempt doesn't work.  I can see the "GOT HERE"'s in a file using '>', but there's a whole bunch of other stuff.  The program also exits immediately.

```<code>#include <stdio.h>
#include <ncurses.h>

int main(int _argc, char ** _argv)
{
    initscr();          /* Start curses mode          */

    printw("Hello World !!!");  /* Print Hello World          */

    refresh();          /* Print it on to the real screen */

    getch();            /* Wait for user input */

    printf("GOT HERE");

    endwin();           /* End curses mode        */

    printf("GOT HERE");

    return 0;
}
</code>```

This is the final output using >

```<code>^[[?1049h^[[1;29r^[(B^[[m^[[4l^[[?7h^[[H^[[2JHello World !!!^MGOT HERE^[[29;1H^[[?1049l^M^[[?1l^[>GOT HERE
</code>```

Is it possible to use stdout through a pipeline and ncurses at the same time?

答:
By default, curses writes to the standard output, which is where your pipe goes.  But there are two different initialization functions for curses: initscr and newterm.  The latter lets you do what was asked, like this:

```<code>#include <stdio.h>
#include <ncurses.h>

int main(int _argc, char ** _argv)
{
    newterm(NULL, stderr, stdin);          /* Start curses mode          */
    printw("Hello World !!!");  /* Print Hello World          */
    refresh();          /* Print it on to the real screen */
    getch();            /* Wait for user input */
    printf("GOT HERE");
    endwin();           /* End curses mode        */
    printf("GOT HERE");
    return 0;
}
</code>```

Further reading: manual page for newterm and initscr.

Title: Ncurses and Linux pipeline

Body:
I'd like to write a simple program using ncurses for displaying some data.  I would then like for the program to write to stdout in such a way that I can then use a pipe (|) on the command line to pipe some data out.

My current attempt doesn't work.  I can see the "GOT HERE"'s in a file using '>', but there's a whole bunch of other stuff.  The program also exits immediately.

#include <stdio.h>
#include <ncurses.h>

int main(int _argc, char ** _argv)
{
    initscr();          /* Start curses mode          */

    printw("Hello World !!!");  /* Print Hello World          */

    refresh();          /* Print it on to the real screen */

    getch();            /* Wait for user input */

    printf("GOT HERE");

    endwin();           /* End curses mode        */

    printf("GOT HERE");

    return 0;
}

This is the final output using >

^[[?1049h^[[1;29r^[(B^[[m^[[4l^[[?7h^[[H^[[2JHello World !!!^MGOT HERE^[[29;1H^[[?1049l^M^[[?1l^[>GOT HERE

Is it possible to use stdout through a pipeline and ncurses at the same time?

Body:
By default, curses writes to the standard output, which is where your pipe goes.  But there are two different initialization functions for curses: initscr and newterm.  The latter lets you do what was asked, like this:

#include <stdio.h>
#include <ncurses.h>

int main(int _argc, char ** _argv)
{
    newterm(NULL, stderr, stdin);          /* Start curses mode          */
    printw("Hello World !!!");  /* Print Hello World          */
    refresh();          /* Print it on to the real screen */
    getch();            /* Wait for user input */
    printf("GOT HERE");
    endwin();           /* End curses mode        */
    printf("GOT HERE");
    return 0;
}

Further reading: manual page for newterm and initscr.


问:
multigraphs in postscript file
I am creating two graphs in one window,

(1) when I display it works but when I try to save as postscript file then it only saves one graph and not the second part. I am attaching the code and the images (display that I would like to see and the eps file).

(2) How can I display pi symbol in axis labels?

(3) How can I display subscripts in legends such as $y_1$, $y_2$ (like tex)

```<code>rm(list=ls())
par(mfrow=c(2,1))
par(mar = c(4,4.5,1,1))
postscript(file="Test.eps", onefile = TRUE, horizontal = FALSE)

x <- seq(-pi, pi, by=0.1)
y1<-abs(cos(x)); y2<-abs(sin(x))
m<-cbind(x,y1,y2,y1+y2,abs(y1-y2))

matplot(m[,1],(m[,c(2,3,4)]), type="l", lty=c(1,2,3,4),ylim=c(0,max(unlist(m[,2:5]))), xaxt="n",xlab="Time",ylab="Y",lwd=2,col=c("black","black","black","black"))
axis(1,c(-pi,-pi/2,0,pi,pi/2))
legend("topright", c("y1","y2","y1+y2","y1-y2"),lty=c(1,2,3,4),lwd=2,col="black")

matplot(m[,1],(m[,c(2,3,5)]), type="l", lty=c(1,2,3,4),ylim=c(0,max(unlist(m[,2:5]))),
       xaxt="n",xlab="Time",ylab="Y",lwd=2,col=c("black","black","black","black"))
axis(1,c(-pi,-pi/2,0,pi,pi/2))
legend("topright", c("y1","y2","y1+y2","y1-y2"),lty=c(1,2,3,4),lwd=2,col="black")

par(mfrow=c(1,1))
graphics.off()
</code>```

I am not able to upload eps file, but this does not show the last plot.

答:
Please see comments above for explanation. Here is the working code

```<code>rm(list=ls())
par(mfrow=c(2,1))
par(mar = c(4,4.5,1,1))

postscript(file="Test.eps", onefile = TRUE, horizontal = FALSE)
par(mfrow=c(2,1))
par(mar = c(4,4.5,1,1))

x <- seq(-pi, pi, by=0.1)
y1<-abs(cos(x)); y2<-abs(sin(x))
m<-cbind(x,y1,y2,y1+y2,abs(y1-y2))

matplot(m[,1],(m[,c(2,3,4)]), type="l", lty=c(1,2,3,4),ylim=c(0,max(unlist(m[,2:5]))),
        xaxt="n",xlab="Time",ylab="Y",lwd=2,col=c("black","black","black","black"))
axis(1,c(-pi,-pi/2,0,pi,pi/2),expression(-pi,-pi/2,0,pi,pi/2))
legend("topright", expression("y"[1],"y"[2],"y"[1]+"y"[2],"y"[1]-"y"[2]),lty=c(1,2,3,4),lwd=2,col="black")

matplot(m[,1],(m[,c(2,3,5)]), type="l", lty=c(1,2,3,4),ylim=c(0,max(unlist(m[,2:5]))),
        xaxt="n",xlab="Time",ylab="Y",lwd=2,col=c("black","black","black","black"))
axis(1,c(-pi,-pi/2,0,pi,pi/2),expression(-pi,-pi/2,0,pi,pi/2))
legend("topright", expression("y"[1],"y"[2],"y"[1]+"y"[2],"y"[1]-"y"[2]),lty=c(1,2,3,4),lwd=2,col="black")

par(mfrow=c(1,1))
graphics.off()
</code>```

Title: multigraphs in postscript file

Body:
I am creating two graphs in one window,

(1) when I display it works but when I try to save as postscript file then it only saves one graph and not the second part. I am attaching the code and the images (display that I would like to see and the eps file).

(2) How can I display pi symbol in axis labels?

(3) How can I display subscripts in legends such as $y_1$, $y_2$ (like tex)

rm(list=ls())
par(mfrow=c(2,1))
par(mar = c(4,4.5,1,1))
postscript(file="Test.eps", onefile = TRUE, horizontal = FALSE)

x <- seq(-pi, pi, by=0.1)
y1<-abs(cos(x)); y2<-abs(sin(x))
m<-cbind(x,y1,y2,y1+y2,abs(y1-y2))

matplot(m[,1],(m[,c(2,3,4)]), type="l", lty=c(1,2,3,4),ylim=c(0,max(unlist(m[,2:5]))), xaxt="n",xlab="Time",ylab="Y",lwd=2,col=c("black","black","black","black"))
axis(1,c(-pi,-pi/2,0,pi,pi/2))
legend("topright", c("y1","y2","y1+y2","y1-y2"),lty=c(1,2,3,4),lwd=2,col="black")

matplot(m[,1],(m[,c(2,3,5)]), type="l", lty=c(1,2,3,4),ylim=c(0,max(unlist(m[,2:5]))),
       xaxt="n",xlab="Time",ylab="Y",lwd=2,col=c("black","black","black","black"))
axis(1,c(-pi,-pi/2,0,pi,pi/2))
legend("topright", c("y1","y2","y1+y2","y1-y2"),lty=c(1,2,3,4),lwd=2,col="black")

par(mfrow=c(1,1))
graphics.off()

I am not able to upload eps file, but this does not show the last plot.

Body:
Please see comments above for explanation. Here is the working code

rm(list=ls())
par(mfrow=c(2,1))
par(mar = c(4,4.5,1,1))

postscript(file="Test.eps", onefile = TRUE, horizontal = FALSE)
par(mfrow=c(2,1))
par(mar = c(4,4.5,1,1))

x <- seq(-pi, pi, by=0.1)
y1<-abs(cos(x)); y2<-abs(sin(x))
m<-cbind(x,y1,y2,y1+y2,abs(y1-y2))

matplot(m[,1],(m[,c(2,3,4)]), type="l", lty=c(1,2,3,4),ylim=c(0,max(unlist(m[,2:5]))),
        xaxt="n",xlab="Time",ylab="Y",lwd=2,col=c("black","black","black","black"))
axis(1,c(-pi,-pi/2,0,pi,pi/2),expression(-pi,-pi/2,0,pi,pi/2))
legend("topright", expression("y"[1],"y"[2],"y"[1]+"y"[2],"y"[1]-"y"[2]),lty=c(1,2,3,4),lwd=2,col="black")

matplot(m[,1],(m[,c(2,3,5)]), type="l", lty=c(1,2,3,4),ylim=c(0,max(unlist(m[,2:5]))),
        xaxt="n",xlab="Time",ylab="Y",lwd=2,col=c("black","black","black","black"))
axis(1,c(-pi,-pi/2,0,pi,pi/2),expression(-pi,-pi/2,0,pi,pi/2))
legend("topright", expression("y"[1],"y"[2],"y"[1]+"y"[2],"y"[1]-"y"[2]),lty=c(1,2,3,4),lwd=2,col="black")

par(mfrow=c(1,1))
graphics.off()


问:
HTML Agility Pack - retrieving multiple values from TD & TR tags
I am new to HTML agility pack, there are some values on a web page I need to get but couldn't findout how to. Hope you can help me.

Best regards.

Sample HTML portion:

```<code>...
<div id="page-bgtop">
    <div id="page-bgbtm">
    <div id="content">
    <div class="post">
    <div class="entry">
    <center>
    <div/>
    <div>
    <table class="CSSTableGenerator" cellspacing="0" cellpadding="4" border="0" id="GridView2" style="width: 98%; border-collapse: collapse;">
    <tbody>
    <tr style="font-weight: bold;">
    <tr style="background-color: rgb(239, 243, 251);">
    <td>
    <a href="Super-Loto-Cekilis-Sonucu.aspx?ID=506.Hafta-29/06/2017-Super-Loto-Sonucu">506</a>
    </td>
    <td>
    <a href="Super-Loto-Cekilis-Sonucu.aspx?ID=506.Hafta-29/06/2017-Super-Loto-Sonucu">29/06/2017</a>
    </td>
    <td>
    <a href="Super-Loto-Cekilis-Sonucu.aspx?ID=506.Hafta-29/06/2017-Super-Loto-Sonucu">4</a>
    </td>
    <td>
    <a href="Super-Loto-Cekilis-Sonucu.aspx?ID=506.Hafta-29/06/2017-Super-Loto-Sonucu">20</a>
    </td>
    <td>
    <a href="Super-Loto-Cekilis-Sonucu.aspx?ID=506.Hafta-29/06/2017-Super-Loto-Sonucu">21</a>
    </td>
    <td>
    <a href="Super-Loto-Cekilis-Sonucu.aspx?ID=506.Hafta-29/06/2017-Super-Loto-Sonucu">32</a>
    </td>
    <td>
    <a href="Super-Loto-Cekilis-Sonucu.aspx?ID=506.Hafta-29/06/2017-Super-Loto-Sonucu">43</a>
    </td>
    <td>
    <a href="Super-Loto-Cekilis-Sonucu.aspx?ID=506.Hafta-29/06/2017-Super-Loto-Sonucu">47</a>
    </td>
    </tr>
    <tr style="background-color: white;">
    <td>
...
</code>```

Values I would like to get:
506
29/06/2017
4
20
21
32
43
47

PS: This is just a sample html portion, there are many rows of value.

答:
Use the XPath descendant-or-self axis (//), specifically //tr to select the all table rows, then check the row(s) for hyperlinks in each cell:

```<code>var document = new HtmlDocument();
document.LoadHtml(html);
//               ^^^^^^ your HTML snippet above
var rows = document.DocumentNode.SelectNodes("//tr");

if (rows != null && rows.Count > 0)
{
    foreach (var row in rows)
    {
        var links = row.SelectNodes("./td/a");
        if (links != null) Console.WriteLine(string.Join(" ", links.Select(x => x.InnerText)));

    }
}
</code>```

Output:

506 29/06/2017 4 20 21 32 43 47

Body:
I am new to HTML agility pack, there are some values on a web page I need to get but couldn't findout how to. Hope you can help me.

Best regards.

Sample HTML portion:

...

    506

    29/06/2017

    4

    20

    21

    32

    43

    47

...

Values I would like to get:
506
29/06/2017
4
20
21
32
43
47

PS: This is just a sample html portion, there are many rows of value.

Body:
Use the XPath descendant-or-self axis (//), specifically //tr to select the all table rows, then check the row(s) for hyperlinks in each cell:

var document = new HtmlDocument();
document.LoadHtml(html);
//               ^^^^^^ your HTML snippet above
var rows = document.DocumentNode.SelectNodes("//tr");

if (rows != null && rows.Count > 0)
{
    foreach (var row in rows)
    {
        var links = row.SelectNodes("./td/a");
        if (links != null) Console.WriteLine(string.Join(" ", links.Select(x => x.InnerText)));

    }
}

Output:

506 29/06/2017 4 20 21 32 43 47


问:
While creating a backup in sql server using query i am getting the following error?
i have a database named students. for that i can able to create the database using the tool backup. but i am not able to create  using the query.

```<code>use students
go
backup database students to disk = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup' with format, medianame = 'test',name = 'back  up of the student database'
go
</code>```

while doing this i am getting the following errror.
could any one help me in this issue?
thank you all/......

Msg 3201, Level 16, State 1, Line 1
Cannot open backup device 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup'. Operating system error 5(Access is denied.).
Msg 3013, Level 16, State 1, Line 1
BACKUP DATABASE is terminating abnormally.

答:
You need to specify the filename of the backup

e.g `TO DISK='C:\Backups\BackupFile.BAK'

See MSDN for a full description of options

Body:
i have a database named students. for that i can able to create the database using the tool backup. but i am not able to create  using the query.

use students
go
backup database students to disk = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup' with format, medianame = 'test',name = 'back  up of the student database'
go

while doing this i am getting the following errror.
could any one help me in this issue?
thank you all/......

Msg 3201, Level 16, State 1, Line 1
Cannot open backup device 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup'. Operating system error 5(Access is denied.).
Msg 3013, Level 16, State 1, Line 1
BACKUP DATABASE is terminating abnormally.


问:
SQL - Crossing 'Crossed' Tables
The title is not good, but it is the way I've found to differentiate my issue from a simple table crossing since my previous researches always get me to these kind of topics.

I have several tables - for simplification, let's name them in only 3: A, B, C. I want to crossing them all in a single table, beeing A the main table.

However, the header in Table B is correlated also with keys in Table C. That is how it looks like my tables:

```<code>Table A
KEY.1      KEY.2       A.HEADER
A          NULL         X
B          NULL         X
NULL       AA           X
NULL       BB           X
C          NULL         X
A          NULL         X
NULL       AA           X

Table B
KEY.1      B.HEADER
A          1
B          2
C          3
D          4
E          5
F          6

Table C
KEY.2       KEY.1
AA          D
BB          E
CC          F
</code>```

I want:

```<code>Final Table
    KEY.1     KEY.2      B.HEADER  A.HEADER
    A         NULL       1         X
    B         NULL       2         X
    D         AA         4         X
    E         BB         5         X
    C         NULL       3         X
</code>```

Can someone help me?

答:
Judging from your example, you want to join on the value in table C when there is no key in table A -- if that's the case then you should be able to join on "whichever one is available" using the coalesce function.  I can't test, but this should get you close:

```<code>Select , b.header, c.header, a.header
from TableA a
LEFT JOIN TableC as c on (a.key = c.key)
LEFT JOIN TableB as b on (COALESCE(a.key,c.b.key) = b.key)
</code>```

(Order matters with coalesce - it'll use the first non-null value it finds, so you may want to flip the order if that's preferable - I dunno whether your table has cases where both values are defined, or what your desired behavior would be...)

Title: SQL - Crossing 'Crossed' Tables

Body:
The title is not good, but it is the way I've found to differentiate my issue from a simple table crossing since my previous researches always get me to these kind of topics.

I have several tables - for simplification, let's name them in only 3: A, B, C. I want to crossing them all in a single table, beeing A the main table.

However, the header in Table B is correlated also with keys in Table C. That is how it looks like my tables:

Table A
KEY.1      KEY.2       A.HEADER
A          NULL         X
B          NULL         X
NULL       AA           X
NULL       BB           X
C          NULL         X
A          NULL         X
NULL       AA           X

Table B
KEY.1      B.HEADER
A          1
B          2
C          3
D          4
E          5
F          6

Table C
KEY.2       KEY.1
AA          D
BB          E
CC          F

I want:

Final Table
    KEY.1     KEY.2      B.HEADER  A.HEADER
    A         NULL       1         X
    B         NULL       2         X
    D         AA         4         X
    E         BB         5         X
    C         NULL       3         X

Can someone help me?

Body:
Judging from your example, you want to join on the value in table C when there is no key in table A -- if that's the case then you should be able to join on "whichever one is available" using the coalesce function.  I can't test, but this should get you close:

Select , b.header, c.header, a.header
from TableA a
LEFT JOIN TableC as c on (a.key = c.key)
LEFT JOIN TableB as b on (COALESCE(a.key,c.b.key) = b.key)

(Order matters with coalesce - it'll use the first non-null value it finds, so you may want to flip the order if that's preferable - I dunno whether your table has cases where both values are defined, or what your desired behavior would be...)


问:
Sortable performance
<s>I have a situation with the Sortable I can't seem to replicate in Plunker.</s>

From what I can tell, Sortable slows down a lot because of something in change detection. Slow to the point of unusable. Visually, you can see the first animation, but then it very slowly refreshes as it slowly finishes change detection.

<s>Here's a plunker that mimics what I have in my code.
http://plnkr.co/edit/veH2Y6CkFZ1Dc5jwcPWZ?p=preview</s>

```<code><kendo-sortable [data]="columns"
                zone="abcdefg"
                [animation]="true"
                [activeIndex]="activeIndex"
                itemClass="item"
                emptyItemClass="emptyItem"
                activeItemClass="activeItem item">
  <ng-template let-column="item">
    <div class="container" (click)="itemClick(column)">
      <span class="col-name">
          {{column.title || column.field}}
      </span>
      <span class="col-width">{{column.width}}</span>
    </div>
  </ng-template>
</kendo-sortable>
</code>```

Basically the dialog is wrapped in a reusable component where I feed strings, templates or components into.
The "columns" array coming into the Input of SortableThingComponent is a copy of the array (all new'd Column objects) from a kendo grid.

<s>Since I can't replicate the slow-down, I'm not sure what's going on. Does anyone see anything or have any tidbits about Sortable?</s>

Edit

Here's an updated plunker that includes a grid. I noticed that if I didn't have data in the grid, the Sortable was faster. Workable, but still a little bit slow. The grid is virtual scrolling, page size 100.

http://plnkr.co/edit/hw8HaKpyZ0lRlVwF2tYp?p=preview

Edit 2

Updated the last plunker with data. Now I'm repro'ing the issue.
What can be done about this?

答:
Here's a fix for now; detach the change detector for the grid component while the dialog with the sortable is open: http://plnkr.co/edit/yy1Z4rWC53vS3xCnxrWT?p=preview

```<code>constructor(private changeDetectorRef: ChangeDetectorRef) { }
this.changeDetectorRef.detach(); // when dialog opens
this.changeDetectorRef.reattach(); // when dialog closes
</code>```

In the plunker, I had to add a this.changeDetectorRef.detectChanges() because of the way I'm opening the dialog.
For now, this is an OK workaround. I might play with the change detection strategy to get it all a little more efficient

Title: Sortable performance

Body:
<s>I have a situation with the Sortable I can't seem to replicate in Plunker.</s>

From what I can tell, Sortable slows down a lot because of something in change detection. Slow to the point of unusable. Visually, you can see the first animation, but then it very slowly refreshes as it slowly finishes change detection.

<s>Here's a plunker that mimics what I have in my code.
http://plnkr.co/edit/veH2Y6CkFZ1Dc5jwcPWZ?p=preview</s>

<kendo-sortable [data]="columns"
                zone="abcdefg"
                [animation]="true"
                [activeIndex]="activeIndex"
                itemClass="item"
                emptyItemClass="emptyItem"
                activeItemClass="activeItem item">
  <ng-template let-column="item">

          {{column.title || column.field}}

      {{column.width}}

  </ng-template>
</kendo-sortable>

Basically the dialog is wrapped in a reusable component where I feed strings, templates or components into.
The "columns" array coming into the Input of SortableThingComponent is a copy of the array (all new'd Column objects) from a kendo grid.

<s>Since I can't replicate the slow-down, I'm not sure what's going on. Does anyone see anything or have any tidbits about Sortable?</s>

Edit

Here's an updated plunker that includes a grid. I noticed that if I didn't have data in the grid, the Sortable was faster. Workable, but still a little bit slow. The grid is virtual scrolling, page size 100.

http://plnkr.co/edit/hw8HaKpyZ0lRlVwF2tYp?p=preview

Edit 2

Updated the last plunker with data. Now I'm repro'ing the issue.
What can be done about this?

Body:
Here's a fix for now; detach the change detector for the grid component while the dialog with the sortable is open: http://plnkr.co/edit/yy1Z4rWC53vS3xCnxrWT?p=preview

constructor(private changeDetectorRef: ChangeDetectorRef) { }
this.changeDetectorRef.detach(); // when dialog opens
this.changeDetectorRef.reattach(); // when dialog closes

In the plunker, I had to add a this.changeDetectorRef.detectChanges() because of the way I'm opening the dialog.
For now, this is an OK workaround. I might play with the change detection strategy to get it all a little more efficient


问:
How to dynamicly include all source files in a folder with clojure?
I define a map of functions:

```<code>(ns fs
  (:require [folder/a :as a]
            [folder/b :as b]
            [folder/c :as c])

(def functions {:a  a/f :b b/f :c c/f})

(doseq [[_ f] functions] (f))
</code>```

Now I want to add more namespaces within the folder, and I don't want to modify the above code. How can functions be dynamically populated with the f from each namespace in a folder.

答:
First some helpers:

```<code>(defn directory
  "Get directory from path"
  [path]
  (clojure.java.io/file path))

(defn file-names
  "Get file names of the files in the directory."
  [files]
  (map (fn [file] (.getName file)) files))

(defn namespace
  "Remove the extension from the file name and prefix with folder-name"
  [folder-name file-name]
  (->> (clojure.string/split file-name #"\.")
       (butlast)
       (apply str)
       (str folder-name ".")
       (symbol)))
</code>```

Then retrieve all namespaces from your folder, you need the path and the folder name:

```<code>(def namespaces
  (let [names (->> "/path/to/your/folder-name"
                   directory
                   file-seq ;; Gets the tree structure of the directory
                   rest ;; Get rid of the the directory name
                   file-names)]
    (map (partial namespace "folder-name") names)))
</code>```

Next get the public functions in every namespace via ns-publics:

```<code>(def functions
  (->> namespaces
       (map (juxt keyword (comp vals ns-publics)))
       (into {})))

;; => prints {:namespace-key '(fn-a fn-b) :namespace-key2 '(fn-b fn-c)}
</code>```

Note that this gets a list of all the public functions in a namesapce after the namespace keys.

We can execute the functions as follows:

```<code>(doseq [[_ ns-fns] functions
        f ns-fns] (f))
</code>```

Of course, this only works for functions that have an arity of zero. Otherwise you have to pass arguments to f.

Body:
I define a map of functions:

(ns fs
  (:require [folder/a :as a]
            [folder/b :as b]
            [folder/c :as c])

(def functions {:a  a/f :b b/f :c c/f})

(doseq [[_ f] functions] (f))

Now I want to add more namespaces within the folder, and I don't want to modify the above code. How can functions be dynamically populated with the f from each namespace in a folder.

Body:
First some helpers:

(defn directory
  "Get directory from path"
  [path]
  (clojure.java.io/file path))

(defn file-names
  "Get file names of the files in the directory."
  [files]
  (map (fn [file] (.getName file)) files))

(defn namespace
  "Remove the extension from the file name and prefix with folder-name"
  [folder-name file-name]
  (->> (clojure.string/split file-name #"\.")
       (butlast)
       (apply str)
       (str folder-name ".")
       (symbol)))

Then retrieve all namespaces from your folder, you need the path and the folder name:

(def namespaces
  (let [names (->> "/path/to/your/folder-name"
                   directory
                   file-seq ;; Gets the tree structure of the directory
                   rest ;; Get rid of the the directory name
                   file-names)]
    (map (partial namespace "folder-name") names)))

Next get the public functions in every namespace via ns-publics:

(def functions
  (->> namespaces
       (map (juxt keyword (comp vals ns-publics)))
       (into {})))

;; => prints {:namespace-key '(fn-a fn-b) :namespace-key2 '(fn-b fn-c)}

Note that this gets a list of all the public functions in a namesapce after the namespace keys.

We can execute the functions as follows:

(doseq [[_ ns-fns] functions
        f ns-fns] (f))

Of course, this only works for functions that have an arity of zero. Otherwise you have to pass arguments to f.


问:
AutoComplete for property grid field
I've a class which I set as source object to a property grid. The values are coming from a value list:

```<code>class Person
{
    ...

    [TypeConverter(NationalityStringConverter)]
    public string Nationality
    ...

class NationalityStringConverter: StringConverter
{
    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
    {
        return true;
    }

    public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
    {
        return true;
    }

    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        // return my value collection
</code>```

Now my question. It it possible to make this list as a suggestion list. In the same way you would set it to a ComboBox like:

```<code>comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
</code>```

Thx 4 answers

答:
If you create a custom UITypeEditor you should be able to override the behaviour and create your own listbox which you can display when EditValue is called using IWindowsFormsEditorService.DropDownControl. That might give you access to the control you need.

The PropertyGrid also has a ControlAdded event, you might be able to use that to get access to the listbox it creates for editing.

I'm currently wrestling with the PropertyGrid myself so I'm not sure if either of these options gives you what you need, but it may help.

Title: AutoComplete for property grid field

Body:
I've a class which I set as source object to a property grid. The values are coming from a value list:

class Person
{
    ...

    [TypeConverter(NationalityStringConverter)]
    public string Nationality
    ...

class NationalityStringConverter: StringConverter
{
    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
    {
        return true;
    }

    public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
    {
        return true;
    }

    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        // return my value collection

Now my question. It it possible to make this list as a suggestion list. In the same way you would set it to a ComboBox like:

comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;

Thx 4 answers


问:
How to fix Google Analytics "analytics.js" net::ERR_FILE_NOT_FOUND?
The relevant line of the Google script is:

```<code>(window,document,'script','//www.google-analytics.com/analytics.js','ga');
</code>```

I am running this particular file locally (as in, I double-click "index.html" on Windows Explorer and it opens in Chrome.

After about a minute of trying to load this file it fails with net::ERR_FILE_NOT_FOUND reported in the Developer Console.

I understand why this is happening, it is trying to load this as a local file.  If I do this it works just fine:

```<code>(window,document,'script','www.google-analytics.com/analytics.js','ga');
</code>```

In other words, I eliminated the //.  This would work just as well:

```<code>(window,document,'script','http://www.google-analytics.com/analytics.js','ga');
</code>```

Is going explicitly doing it this way to only track real websites?

If so, how are you dealing with this issue for local development?

I do run a VM with Ubuntu server for local development of more elaborate sites.  In this case I was working on a single file landing page that I knocked out quickly and wanted to just test just as easily but ran into the browser hanging waiting for analytics.js

Is it safe to remove the // or add http: in general terms.  I don't generally like to modify Google code unless I fully understand why they are doing things in a specific way and what the consequences of my actions might be.

答:
It can be that you are using a VPN(Virtual private network) which analytics blocks. Try loading https://www.google-analytics.com/analytics.js
If id does not work try disabling the VPN and try again.

Or as someone else mentioned it could be that your AdBlock is blocking it.

Body:
The relevant line of the Google script is:

(window,document,'script','//www.google-analytics.com/analytics.js','ga');

I am running this particular file locally (as in, I double-click "index.html" on Windows Explorer and it opens in Chrome.

After about a minute of trying to load this file it fails with net::ERR_FILE_NOT_FOUND reported in the Developer Console.

I understand why this is happening, it is trying to load this as a local file.  If I do this it works just fine:

(window,document,'script','www.google-analytics.com/analytics.js','ga');

In other words, I eliminated the //.  This would work just as well:

(window,document,'script','http://www.google-analytics.com/analytics.js','ga');

Is going explicitly doing it this way to only track real websites?

If so, how are you dealing with this issue for local development?

I do run a VM with Ubuntu server for local development of more elaborate sites.  In this case I was working on a single file landing page that I knocked out quickly and wanted to just test just as easily but ran into the browser hanging waiting for analytics.js

Is it safe to remove the // or add http: in general terms.  I don't generally like to modify Google code unless I fully understand why they are doing things in a specific way and what the consequences of my actions might be.


问:
Angular 2 Passing data from Parent component to child
I am passing products from a parent component to a child component using input binding and it works the first time the child component is invoked. I expect change to products in filterProduct() to be reflected in the child every time it is modified in the parent but this is not happening. How do I get this to happen.

Parent template:

    <app-product-card [products]=products></app-product-card>

```

<p></p>

<p>Parent component:</p>

<pre class="lang-ts prettyprint-override"><code>@Component({
  selector: 'app-appliances-product-card',
  moduleId: module.id,
  templateUrl: 'appliances-product-card.component.html'
})

export class AppliancesProductCardComponent implements OnInit{
   products: Product[];

   filterProduct(filter) {
     this.products = this.filteredProducts;
  }
}
</code>```

Child component:

@Component({
  selector: 'app-product-card',
  moduleId: module.id,
  templateUrl: 'product-card.component.html'
})

export class ProductCardComponent {
  @Input() products: Product[];
}
```

答:
Here's plunker of what might work for  you:

https://plnkr.co/edit/S47fBh2xdT1gp2zrznk4?p=preview

Instead of passing the data from parent to child component, both parent and child component will use service to get the data.

Parent Component:

```<code>import { Component, OnInit } from '@angular/core';
import { Product } from './product'
import { ProductsService } from './products.service';

@Component({
  selector: 'app-appliances-product-card',
  template: `
    <div class="container-fluid">
      <button (click)="filterProduct('Type 1')">Filter Type 1</button>
      <button (click)="filterProduct('')">Clear Filter</button>
      <div class="col-sm-9">
        <app-products-card></app-products-card>
      </div>
    </div>
  `
})
export class AppliancesProductCardComponent implements OnInit {
  products: Product[];
  constructor(private _productsService: ProductsService){ }

  filterProduct(type: string) {
    this.products = this._productsService.filterProduct(type);
  }

  ngOnInit() {
    this.products = this._productsService.getAllProducts();
  }
}
</code>```

Child Component:

```<code>import { Component, OnInit, Input } from '@angular/core';
import { Product } from './product';
import { ProductsService } from './products.service';

@Component({
  selector: 'app-products-card',
  template: `
    <h1>Product Card</h1>
      <div *ngFor="let product of products">{{product.name}} - {{product.type}}</div>
  `
})
export class ProductsCardComponent implements OnInit {
  constructor(private _productsService: ProductsService){ }

  ngOnInit() {
    this.products = this._productsService.getAllProducts();
    this._productsService.filteredProducts.subscribe(products => {
      console.log(products);
      this.products = products
    });
  }
}
</code>```

Service:

```<code>import { EventEmitter, Injectable } from '@angular/core';
import { Product } from './product';

export class ProductsService {
  filteredProducts = new EventEmitter<Product[]>;

  private products: Product[] = [
      { id: 1, name: 'Product 1', price: 10.50, type: 'Type 1' },
      { id: 2, name: 'Product 2', price: 15.50, type: 'Type 1' },
      { id: 3, name: 'Product 3', price: 1.50, type: 'Type 2' },
      { id: 4, name: 'Product 4', price: 100.50, type: 'Type 3' }
    ];

  getAllProducts(): Product[] {
    return this.products.slice();
  }

  filterProduct(type: string): Product[]{
    let filteredProducts = this.products.filter(p => !type || p.type == type).slice();
    this.filteredProducts.emit(filteredProducts);
  }
}
</code>```

I came across similar problems when I first started writing angular application. Passing data from parent to child component all the time is not a manageable way to write application. Specially if it's a big application with too many nested components.

In this example, I'm using the services and event emitter (both part of angular framework) to provide relevant data to both the child and the parent component.

One way to improve the code is to use rxjs. This is what angular event emitter uses behind the scene.

And even more advanced solution is to use ngrx/store (redux library for Angular). This is particularly suited for huge applications.

No matter which solution you choose, the idea is to have a single place to maintain the state of the application and avoid nesting data too much.

Body:
I am passing products from a parent component to a child component using input binding and it works the first time the child component is invoked. I expect change to products in filterProduct() to be reflected in the child every time it is modified in the parent but this is not happening. How do I get this to happen.

Parent template:

    <app-product-card [products]=products></app-product-card>

Parent component:

@Component({
  selector: 'app-appliances-product-card',
  moduleId: module.id,
  templateUrl: 'appliances-product-card.component.html'
})

export class AppliancesProductCardComponent implements OnInit{
   products: Product[];

   filterProduct(filter) {
     this.products = this.filteredProducts;
  }
}

Child component:

@Component({
  selector: 'app-product-card',
  moduleId: module.id,
  templateUrl: 'product-card.component.html'
})

export class ProductCardComponent {
  @Input() products: Product[];
}

Body:
Here's plunker of what might work for  you:

https://plnkr.co/edit/S47fBh2xdT1gp2zrznk4?p=preview

Instead of passing the data from parent to child component, both parent and child component will use service to get the data.

Parent Component:

import { Component, OnInit } from '@angular/core';
import { Product } from './product'
import { ProductsService } from './products.service';

@Component({
  selector: 'app-appliances-product-card',
  template: `
    <div class="container-fluid">
      <button (click)="filterProduct('Type 1')">Filter Type 1</button>
      <button (click)="filterProduct('')">Clear Filter</button>
      <div class="col-sm-9">
        <app-products-card></app-products-card>
      </div>
    </div>
  `
})
export class AppliancesProductCardComponent implements OnInit {
  products: Product[];
  constructor(private _productsService: ProductsService){ }

  filterProduct(type: string) {
    this.products = this._productsService.filterProduct(type);
  }

  ngOnInit() {
    this.products = this._productsService.getAllProducts();
  }
}

Child Component:

import { Component, OnInit, Input } from '@angular/core';
import { Product } from './product';
import { ProductsService } from './products.service';

@Component({
  selector: 'app-products-card',
  template: `
    <h1>Product Card</h1>
      <div *ngFor="let product of products">{{product.name}} - {{product.type}}</div>
  `
})
export class ProductsCardComponent implements OnInit {
  constructor(private _productsService: ProductsService){ }

  ngOnInit() {
    this.products = this._productsService.getAllProducts();
    this._productsService.filteredProducts.subscribe(products => {
      console.log(products);
      this.products = products
    });
  }
}

Service:

import { EventEmitter, Injectable } from '@angular/core';
import { Product } from './product';

export class ProductsService {
  filteredProducts = new EventEmitter<Product[]>;

  private products: Product[] = [
      { id: 1, name: 'Product 1', price: 10.50, type: 'Type 1' },
      { id: 2, name: 'Product 2', price: 15.50, type: 'Type 1' },
      { id: 3, name: 'Product 3', price: 1.50, type: 'Type 2' },
      { id: 4, name: 'Product 4', price: 100.50, type: 'Type 3' }
    ];

  getAllProducts(): Product[] {
    return this.products.slice();
  }

  filterProduct(type: string): Product[]{
    let filteredProducts = this.products.filter(p => !type || p.type == type).slice();
    this.filteredProducts.emit(filteredProducts);
  }
}

I came across similar problems when I first started writing angular application. Passing data from parent to child component all the time is not a manageable way to write application. Specially if it's a big application with too many nested components.

In this example, I'm using the services and event emitter (both part of angular framework) to provide relevant data to both the child and the parent component.

One way to improve the code is to use rxjs. This is what angular event emitter uses behind the scene.

And even more advanced solution is to use ngrx/store (redux library for Angular). This is particularly suited for huge applications.

No matter which solution you choose, the idea is to have a single place to maintain the state of the application and avoid nesting data too much.


问:
Custom VRP datasets using graph hopper
I am looking for a java code or library to generate the custom VRP datasets with road distances using graph hopper. Could you please share the details.</p>

答:
See my repo that needs to be cleaned up and some code added in optaplanner-webexamples:
  https://github.com/ge0ffrey/vrp-dataset-generator</p>

Title: Custom VRP datasets using graph hopper


问:
sed delete between lines with tree lines
I have several tomcat servers where I want to manage dynamically the context.xml file via some bash scripts and I want to delete resources by using sed. I know how do it but the file is formatted as shown below across several servers for sake of readability I suppose and I can't identify the resource to delete just with this:

sed '/PATTERN-1/,/PATTERN-2/d' context.xml

But on pattern-1 I need to get the second line to substitute part of name attribute as a bash script variable. And I tried several ways as escaping \s or \n

```<code><Context>
  ...
  <Resource
        name="jdbc/EmployeeDB" auth="Container"
        type="javax.sql.DataSource"
        description="Employees Database for HR Applications"
  />
  <Resource
        name="jdbc/SportDB" auth="Container"
        type="javax.sql.DataSource"
        description="Sport Database for HR Applications"
  />
  <Resource
        name="jdbc/BackupDB" auth="Container"
        type="javax.sql.DataSource"
        description="Backup Database for HR Applications"
  />
  ...
</Context>
</code>```

答:
If I'm understanding your question correctly, you could try the following:

```<code>sed -ri '/<Resource/,/\/>/ {/name=.*$/d}' filename
</code>```

With -r to allow regular expressions to be interpreted and -i to amend the file directly, you would first isolate the data between  and /> and then delete the lines beginning with name="

Body:
I have several tomcat servers where I want to manage dynamically the context.xml file via some bash scripts and I want to delete resources by using sed. I know how do it but the file is formatted as shown below across several servers for sake of readability I suppose and I can't identify the resource to delete just with this:

sed '/PATTERN-1/,/PATTERN-2/d' context.xml

But on pattern-1 I need to get the second line to substitute part of name attribute as a bash script variable. And I tried several ways as escaping \s or \n

<Context>
  ...
  <Resource
        name="jdbc/EmployeeDB" auth="Container"
        type="javax.sql.DataSource"
        description="Employees Database for HR Applications"
  />
  <Resource
        name="jdbc/SportDB" auth="Container"
        type="javax.sql.DataSource"
        description="Sport Database for HR Applications"
  />
  <Resource
        name="jdbc/BackupDB" auth="Container"
        type="javax.sql.DataSource"
        description="Backup Database for HR Applications"
  />
  ...
</Context>

Body:
If I'm understanding your question correctly, you could try the following:

sed -ri '/<Resource/,/\/>/ {/name=.*$/d}' filename

With -r to allow regular expressions to be interpreted and -i to amend the file directly, you would first isolate the data between  and /> and then delete the lines beginning with name="


问:
In javascript, why is the string "true", after coercion, still not equal to boolean true?
In javascript, String(true) == "true" evaluates to true, and Boolean("true") == true evaluates to true, so why does "true" == true evaluate to false?

答:
In "true" == true the coercion is to number. So this becomes:

```<code>NaN == 1
</code>```

... which is false.

The loose equality operands table on mozilla.org might be useful to check out.

Body:
In "true" == true the coercion is to number. So this becomes:

NaN == 1

... which is false.

The loose equality operands table on mozilla.org might be useful to check out.


答:
Take a look to the MDN (Mozilla Developer Network). When we compare two operands of differents types, [the Abstract Equality Comparison Algorithm] will attempt to convert them to the same type before making the comparison.

Finally, the answer is the following:

If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.

Then

When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.

So, finally, we compare Nan == 1 which is false as pointed by @trincot.

Title: In javascript, why is the string "true", after coercion, still not equal to boolean true?

Body: In javascript, String(true) == "true" evaluates to true, and Boolean("true") == true evaluates to true, so why does "true" == true evaluate to false?


问:
Python sort a sublist by object attribute
I know how to sort by an attribute from this question where the top answer suggests doing:

```<code>someList.sort(key=lambda x: x.someAttr, reverse=True)
</code>```

and I have seen suggestions for sorting a sublist which suggest to do something like:

```<code>someList[i:j] = sorted(somelist[i:j])
</code>```

but how can I sort a sublist by an attribute? I tried:

```<code>someList[i:j].sort(key=lambda x: x.someAttr, reverse=True)
</code>```

but this did not work. Any suggestions?

答:
You're on the right track. You can sort a sublist with sorted() and assign it to the same splice. Here's an example:

```<code>>>> class Foo:
...    def __init__(self, val):
...        self.val = val
...    def __repr__(self):
...        return 'Foo(%d)' %self.val
...
>>>
>>> x = [Foo(5), Foo(3), Foo(2), Foo(7)]
>>> x
[Foo(5), Foo(3), Foo(2), Foo(7)]
>>> x[1:3] = sorted(x[1:3], key=lambda x: x.val)
>>> x
[Foo(5), Foo(2), Foo(3), Foo(7)]
</code>```

This has sorted the middle two elements. For your use case, don't forget the reverse=True keyword argument in the call.

On a related note, someList[i:j].sort(key=lambda x: x.someAttr, reverse=True) doesn't work as you expected. Well, it does sort a sublist, however, when you splice the original list, you end up creating an anonymous copy and sorting that in-place, and then losing that sorted copy (it is not assigned to anything, it is garbage collected). The original list is not affected.

Body:
I know how to sort by an attribute from this question where the top answer suggests doing:

someList.sort(key=lambda x: x.someAttr, reverse=True)

and I have seen suggestions for sorting a sublist which suggest to do something like:

someList[i:j] = sorted(somelist[i:j])

but how can I sort a sublist by an attribute? I tried:

someList[i:j].sort(key=lambda x: x.someAttr, reverse=True)

but this did not work. Any suggestions?

Body:
You're on the right track. You can sort a sublist with sorted() and assign it to the same splice. Here's an example:

>>> class Foo:
...    def __init__(self, val):
...        self.val = val
...    def __repr__(self):
...        return 'Foo(%d)' %self.val
...
>>>
>>> x = [Foo(5), Foo(3), Foo(2), Foo(7)]
>>> x
[Foo(5), Foo(3), Foo(2), Foo(7)]
>>> x[1:3] = sorted(x[1:3], key=lambda x: x.val)
>>> x
[Foo(5), Foo(2), Foo(3), Foo(7)]

This has sorted the middle two elements. For your use case, don't forget the reverse=True keyword argument in the call.

On a related note, someList[i:j].sort(key=lambda x: x.someAttr, reverse=True) doesn't work as you expected. Well, it does sort a sublist, however, when you splice the original list, you end up creating an anonymous copy and sorting that in-place, and then losing that sorted copy (it is not assigned to anything, it is garbage collected). The original list is not affected.


问:
How would one convert a razor loop into a Vue.js component?
I'm attempting to take a very dumb vue component and move more of the code (written in razor) into the component itself (to keep it as modular as possible).

Currently the component is more of a container where razor loops through a list of communities and renders out some html server-side.  That html is then passed through a slot into the component and styled.

Ideally, I would like to find a way to render only the bare minimum through razor, and instead move as much of the logic into the component as possible. For example, I know vue offers a mechanism for looping through data (v-for), however in this case, I'm not quite sure how to pass the data into the component in such a way as to utilize that.

Being new to vue (as I think most of us are), I'm still getting the hang of passing server-side data through to components.  I've tried creating props, but the complexity of the data being generated has thrown me off a bit.  I'm hoping someone here can shine a little light on the best way to approach this problem!

Thanks in advance!

index.cshtml:

```<code><community-list>
      @foreach (var region in regions)
      {
          var regPage = region.Pages.FirstOrDefault();
          if (regPage == null)
          {
              continue;
          }
          string isActive = "";
          int communityCount = 0;
          var cities = region.Children;
          for (int i = 0; i < cities.Count; i++) {
              communityCount += cities[i].Pages.Count;
          }
          if (HttpContext.Current.Request.IsAuthenticated && !Model.IsPreview) {
              var email = HttpContext.Current.User.Identity.Name;
              isActive = CompanyName.Core.Models.Users.IsRegionSubscribed(email, region.Name) ? "active" : "";
          }
        <div class="community container primary @isActive" data-name="@region.Name">
          <figure style="background-image: url('/assets/images/@regPage.GetAttributeValue("HeroImage")');"></figure>
          <h3>@regPage.GetAttributeValue("Title")</h3>
          <p>@(communityCount.ToString()) New Home Communities</p>
          <custom-button destination="@regPage.URL" appearance="primary" type="link" size="extra-large" text="Find New Homes in @stateName"></custom-button>
        </div>
      }
    </community-list>
</code>```

CommunityList.vue

```<code><template>
  <section class="community-list">
    <slot></slot>
  </section>
</template>

<script>
  export default {
    name: 'CommunityList',
  };
</script>

<style lang="scss" scoped>
  -- styling here --
</style>
</code>```

Update

------

To clarify further:

Assuming it's the proper approach, I would like to pull the html in the razor loop out of the slot and place it into the component.  Remove the slot altogether, and take the data from razor and populate the html in the component with the values that are returned from razor.

It seems to me the more html and logic I can move into the component the better.

Perhaps something like:

index.cshtml:

```<code>@foreach (var region in regions) {
  var foo = region.foo;
  var bar = region.bar;
}
<community-list foo="@foo" bar="@bar"></community-list>
</code>```

CommunityList.vue

```<code><template>
  <section v-for="region in regions">
    <p>{{ foo }}</p>
    <p>{{ bar }}</p>
  </section>
</template>
</code>```

I'm not quite sure how best to approach this from a vue-centric manner. If I converted the razor to simply spit out a list of vars to use like above, how would I then take that data, pass it into the component, and loop through it within the vue component itself (something like the example above)?  In the case above, I'm sure this won't work - but I imagine there must be some way to accomplish what I'm thinking of somehow?

(Or am I just approaching this the wrong way altogether?)

答: You would have to render the data into a  tag with razor, into a global variable. When you set up your vue component, use that global variable to set up the data function.

Body:
I'm attempting to take a very dumb vue component and move more of the code (written in razor) into the component itself (to keep it as modular as possible).

Currently the component is more of a container where razor loops through a list of communities and renders out some html server-side.  That html is then passed through a slot into the component and styled.

Ideally, I would like to find a way to render only the bare minimum through razor, and instead move as much of the logic into the component as possible. For example, I know vue offers a mechanism for looping through data (v-for), however in this case, I'm not quite sure how to pass the data into the component in such a way as to utilize that.

Being new to vue (as I think most of us are), I'm still getting the hang of passing server-side data through to components.  I've tried creating props, but the complexity of the data being generated has thrown me off a bit.  I'm hoping someone here can shine a little light on the best way to approach this problem!

Thanks in advance!

index.cshtml:

<community-list>
      @foreach (var region in regions)
      {
          var regPage = region.Pages.FirstOrDefault();
          if (regPage == null)
          {
              continue;
          }
          string isActive = "";
          int communityCount = 0;
          var cities = region.Children;
          for (int i = 0; i < cities.Count; i++) {
              communityCount += cities[i].Pages.Count;
          }
          if (HttpContext.Current.Request.IsAuthenticated && !Model.IsPreview) {
              var email = HttpContext.Current.User.Identity.Name;
              isActive = CompanyName.Core.Models.Users.IsRegionSubscribed(email, region.Name) ? "active" : "";
          }

@regPage.GetAttributeValue("Title")

@(communityCount.ToString()) New Home Communities

          <custom-button destination="@regPage.URL" appearance="primary" type="link" size="extra-large" text="Find New Homes in @stateName"></custom-button>

      }
    </community-list>

CommunityList.vue

<template>

    <slot></slot>

</template>

Update

------

To clarify further:

Assuming it's the proper approach, I would like to pull the html in the razor loop out of the slot and place it into the component.  Remove the slot altogether, and take the data from razor and populate the html in the component with the values that are returned from razor.

It seems to me the more html and logic I can move into the component the better.

Perhaps something like:

index.cshtml:

@foreach (var region in regions) {
  var foo = region.foo;
  var bar = region.bar;
}
<community-list foo="@foo" bar="@bar"></community-list>

CommunityList.vue

<template>

{{ foo }}

{{ bar }}

</template>

I'm not quite sure how best to approach this from a vue-centric manner. If I converted the razor to simply spit out a list of vars to use like above, how would I then take that data, pass it into the component, and loop through it within the vue component itself (something like the example above)?  In the case above, I'm sure this won't work - but I imagine there must be some way to accomplish what I'm thinking of somehow?

(Or am I just approaching this the wrong way altogether?)


问:
The Process Cannot Access The File...Because it is being used by another process
I'm taking a file and doing 2 things to it. Resizing it and placing it in a picturebox, then resizing it again and saving it.

The first resize operation goes well after dropping it into the window as a thumbnail, however after it has been resized, the second resize operation fails saying its in use.

From my understanding Im not closing the file or stream. A solution to this is the "using" command, but no matter where I put it, I get errors.

First Resize Code:

```<code>    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop);
        PB_Picture.Image = ScaleImage(Image.FromFile(droppedfiles[0]), 180, 140);
    }
</code>```

I tried:

```<code>    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        using (string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop));
        PB_Picture.Image = ScaleImage(Image.FromFile(droppedfiles[0]), 180, 140);
    }
</code>```

But get a number of errors.

Errors

答:
The using statement is not correct:

```<code>private void Form1_DragDrop(object sender, DragEventArgs e)
{
    using(string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop)){
        PB_Picture.Image = ScaleImage(Image.FromFile(droppedfiles[0]), 180, 140);
    }
}
</code>```

Body:
I'm taking a file and doing 2 things to it. Resizing it and placing it in a picturebox, then resizing it again and saving it.

The first resize operation goes well after dropping it into the window as a thumbnail, however after it has been resized, the second resize operation fails saying its in use.

From my understanding Im not closing the file or stream. A solution to this is the "using" command, but no matter where I put it, I get errors.

First Resize Code:

    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop);
        PB_Picture.Image = ScaleImage(Image.FromFile(droppedfiles[0]), 180, 140);
    }

I tried:

    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        using (string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop));
        PB_Picture.Image = ScaleImage(Image.FromFile(droppedfiles[0]), 180, 140);
    }

But get a number of errors.

Errors

Body:
The using statement is not correct:

private void Form1_DragDrop(object sender, DragEventArgs e)
{
    using(string[] droppedfiles = (string[])e.Data.GetData(DataFormats.FileDrop)){
        PB_Picture.Image = ScaleImage(Image.FromFile(droppedfiles[0]), 180, 140);
    }
}


问:
How to merge multiple RxJS AjaxObservable calls to make a single observable?
I have an Angular 4 app with a product list component that displays the names of the products. The names of the products are retrieved from the server API. There are 1000 products which has to be retrieved in a few ajax calls AjaxObservable. Every call return 200 products, so have to make 5 calls to return all the products.

How can I achieve the above with AjaxObservable? Should I merge all the observables or create single only and allow the UI to subscribe?

```<code>for (var i = 0; i < 5; i++) {
   var source = Rx.Observable.ajax({ url: 'products', method: 'GET' });
}
</code>```

答:
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/combinelatest.md

```<code>let obs1: Observable<any> = Observable.of('val1', 'val2');
let obs2: Observable<any> = Observable.of('val3', 'val4');
Rx.Observable.combineLatest(obs1, obs2).subscribe(values => {
    console.log(values) //values is array - this statement will print [val2, val4]
});
</code>```

Also you could take a look at this answer: Rxjs: Observable.combineLatest vs Observable.forkJoin

Body:
I have an Angular 4 app with a product list component that displays the names of the products. The names of the products are retrieved from the server API. There are 1000 products which has to be retrieved in a few ajax calls AjaxObservable. Every call return 200 products, so have to make 5 calls to return all the products.

How can I achieve the above with AjaxObservable? Should I merge all the observables or create single only and allow the UI to subscribe?

for (var i = 0; i < 5; i++) {
   var source = Rx.Observable.ajax({ url: 'products', method: 'GET' });
}

Body:
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/combinelatest.md

let obs1: Observable<any> = Observable.of('val1', 'val2');
let obs2: Observable<any> = Observable.of('val3', 'val4');
Rx.Observable.combineLatest(obs1, obs2).subscribe(values => {
    console.log(values) //values is array - this statement will print [val2, val4]
});

Also you could take a look at this answer: Rxjs: Observable.combineLatest vs Observable.forkJoin


问:
Load data from table using PHP & AJAX
I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:

{data: [{IdProduct: "1", Name: "Name here..........",…}]}

For example I want to select only Name, I tried doing this:

```<code>function LoadProductos() {

$.ajax({
    url: '../../class/loadProd.php',
    method: 'POST',
    success: function (data) {
      var aRC = JSON.parse(data);

      for (var i = 0; i < aRC.length; i++) {
        console.log(aRC[i].Name);
      }
    }

  });
}
</code>```

But this doesn't shows anything, how can I do this? This is my PHP code:

```<code>while($row = mysqli_fetch_array($registros)) {

    $table.='{
        "IdProduct":"'.$row['IdProduct'].'",
        "Name":"'.$row['Name'].'",
        "Description":"'.$row['Description'].'",
        "ImagePath":"'.$row['ImagePath'].'"
    },';

    $table = substr($table, 0, strlen($table) -1);

    echo '{"data":['.$table.']}';
}
</code>```

答:
First off, your shouldn't echo the json data in the loop. It should be outside the loop.
You shouldn't build your own json data either.

Let's build an array that looks like the json response you want. Then we'll use the function json_encode() to encode it as a proper json-string:

```<code>// Define the response array
$response = [
    'data' => []
];

while($row = mysqli_fetch_array($registros)) {

    // Push a new array to 'data' array
    $response['data'][] = [
        'IdProduct'   => $row['IdProduct'],
        'Name'        =>.$row['Name'],
        'Description' => $row['Description'],
        'ImagePath'   => $row['ImagePath']
    ];
}

// Now, let's encode the data:
echo json_encode($response);
</code>```

Title: Load data from table using PHP & AJAX

Body:
I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:

{data: [{IdProduct: "1", Name: "Name here..........",…}]}

For example I want to select only Name, I tried doing this:

function LoadProductos() {

$.ajax({
    url: '../../class/loadProd.php',
    method: 'POST',
    success: function (data) {
      var aRC = JSON.parse(data);

      for (var i = 0; i < aRC.length; i++) {
        console.log(aRC[i].Name);
      }
    }

  });
}

But this doesn't shows anything, how can I do this? This is my PHP code:

while($row = mysqli_fetch_array($registros)) {

    $table.='{
        "IdProduct":"'.$row['IdProduct'].'",
        "Name":"'.$row['Name'].'",
        "Description":"'.$row['Description'].'",
        "ImagePath":"'.$row['ImagePath'].'"
    },';

    $table = substr($table, 0, strlen($table) -1);

    echo '{"data":['.$table.']}';
}

Body:
First off, your shouldn't echo the json data in the loop. It should be outside the loop.
You shouldn't build your own json data either.

Let's build an array that looks like the json response you want. Then we'll use the function json_encode() to encode it as a proper json-string:

// Define the response array
$response = [
    'data' => []
];

while($row = mysqli_fetch_array($registros)) {

    // Push a new array to 'data' array
    $response['data'][] = [
        'IdProduct'   => $row['IdProduct'],
        'Name'        =>.$row['Name'],
        'Description' => $row['Description'],
        'ImagePath'   => $row['ImagePath']
    ];
}

// Now, let's encode the data:
echo json_encode($response);


问:
Could not call virtual member function after read object from file
Problem:

I wrote an object into a file in binary mode using std::fstream. However, when I read it back from that file to another object and then call one of the virtual member functions of this new object, there's a memory access violation error.

Here's what the code looks like:

```<code>class A
{
public:
   // data
   virtual void foo() = 0;
};

class B: public A
{
public:
   // added data
   virtual void foo() { ... }
}

int main()
{
  // ...
  A* a = new B();
  A* b = new B();

  file.write((char*)a, sizeof(B));
  // ...
  thatSameFile.read((char*)b, sizeof(B));

  b->foo(); // error here

}
</code>```

What I've figured out:

After a couple of hours debugging, I see that the __vfptr member of b (which, as far as I know, is the pointer to the virtual table of that object) is changing after the file read statement. I guess that not only did I write the data of a to file and copy those to b, I also copied the virtual table pointer of a to b.

Is what I said correct? How can I fix this problem?

答:
Is what I said correct?

No, it's not correct. The source of the problem is that you are merely writing addresses to a file and loading them back (additionally, with wrong sizes used).

```<code>file.write((char*)&a, sizeof(B));
</code>```

The preceding line writes the pointer that was stored in the variable a with the size of class B to the file.

Pointers cannot be reconstructed from a file, since they need to be memory-managed (dynamic allocation, in your case).

So the statement

```<code>thatSameFile.read((char*)&b, sizeof(B));
</code>```

just overwrites the pointer stored in b with some arbitrary, meaningless value, plus some additional bytes on the stack. This is basically undefined behavior.

As for your comment, this was a typo; it wouldn't change much about what I wrote above. Pointers cannot be reconstructed from files.

How can I fix this problem?

If you need to write binary images of your structs / classes. You can do so for plain POD types like

```<code>struct Foo {
    char c;
    int i;
    double d;
    long arrlong[25];
};
</code>```

that contain only integral types, or fixed size arrays of integral types.

Such types could be written "safely" to and restored from a binary file for the same target architecture (see Endianness):

```<code>Foo a;

file.write((const char*)&a, sizeof(Foo));

// ...

Foo b;
thatSameFile.read((char*)&b, sizeof(Foo));
</code>```

Also you cannot use types with virtual polymorphic inheritance for doing so. Just reloading a vtable (which isn't even specified by the C++ standard) isn't enough to tell the runtime what's actually the underlying type safely.

You should lookup serialization/deserialization to achieve what you want. There are several libraries that support binary formats well, like boost::serialization or google protocol buffers, which help you to build something more sophisticated than POD serialization/deserialization.

Body:
Problem:

I wrote an object into a file in binary mode using std::fstream. However, when I read it back from that file to another object and then call one of the virtual member functions of this new object, there's a memory access violation error.

Here's what the code looks like:

class A
{
public:
   // data
   virtual void foo() = 0;
};

class B: public A
{
public:
   // added data
   virtual void foo() { ... }
}

int main()
{
  // ...
  A* a = new B();
  A* b = new B();

  file.write((char*)a, sizeof(B));
  // ...
  thatSameFile.read((char*)b, sizeof(B));

  b->foo(); // error here

}

What I've figured out:

After a couple of hours debugging, I see that the __vfptr member of b (which, as far as I know, is the pointer to the virtual table of that object) is changing after the file read statement. I guess that not only did I write the data of a to file and copy those to b, I also copied the virtual table pointer of a to b.

Is what I said correct? How can I fix this problem?

Body:
Is what I said correct?

No, it's not correct. The source of the problem is that you are merely writing addresses to a file and loading them back (additionally, with wrong sizes used).

file.write((char*)&a, sizeof(B));

The preceding line writes the pointer that was stored in the variable a with the size of class B to the file.

Pointers cannot be reconstructed from a file, since they need to be memory-managed (dynamic allocation, in your case).

So the statement

thatSameFile.read((char*)&b, sizeof(B));

just overwrites the pointer stored in b with some arbitrary, meaningless value, plus some additional bytes on the stack. This is basically undefined behavior.

As for your comment, this was a typo; it wouldn't change much about what I wrote above. Pointers cannot be reconstructed from files.

How can I fix this problem?

If you need to write binary images of your structs / classes. You can do so for plain POD types like

struct Foo {
    char c;
    int i;
    double d;
    long arrlong[25];
};

that contain only integral types, or fixed size arrays of integral types.

Such types could be written "safely" to and restored from a binary file for the same target architecture (see Endianness):

Foo a;

file.write((const char*)&a, sizeof(Foo));

// ...

Foo b;
thatSameFile.read((char*)&b, sizeof(Foo));

Also you cannot use types with virtual polymorphic inheritance for doing so. Just reloading a vtable (which isn't even specified by the C++ standard) isn't enough to tell the runtime what's actually the underlying type safely.

You should lookup serialization/deserialization to achieve what you want. There are several libraries that support binary formats well, like boost::serialization or google protocol buffers, which help you to build something more sophisticated than POD serialization/deserialization.


问:
Using divs on an image slider
I have code below for an image slider that stops when you hover on the image. I was wondering if there's anyway to do this but instead of using image tags using just use a div tag so I can create custom shapes to have on the slider with CSS. Can anyone point me in the right direction, when I try replacing the images with divs it stops working. Any thoughts?

#scroller {
  position: absolute;
  left: 33%;
  top: 14%;
}

#scroller .innerScrollArea {
  overflow: hidden;
  position: absolute;
  top: 10%;
  bottom: 0;
  left: 0;
  right: 0;
}

#scroller ul {
  padding: 0;
  top: 10%;
  position: relative;
}

#scroller li {
  padding: 0;
  top: 7%;
  list-style-type: none;
  position: absolute;
}

.test {
width:100px;
height:200px;
background-color:pink;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <!-- SCROLLING IMAGE GALLERY-->

  <div id="scroller" style="width: 536px; height: 263px; margin: 0 auto;">
    <div class="innerScrollArea">
      <ul>
        <li><img src="http://i1055.photobucket.com/albums/s511/Josh_Tilton/website/angels_landing_zpsn5dpgsui.jpg" width="536" height="263" /></li>
        <li><img src="http://i1055.photobucket.com/albums/s511/Josh_Tilton/website/big_cottonwood_zpszx8qyyik.jpg" width="536" height="263" /></li>
      </ul>
    </div>
  </div>

  <!-- JS SCROLLING IMAGES CODE-->

  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
  <script type="text/javascript">
    $(function(){
        var scroller = $('#scroller div.innerScrollArea');
        var scrollerContent = scroller.children('ul');
        scrollerContent.children().clone().appendTo(scrollerContent);
        var curX = 0;
        scrollerContent.children().each(function(){
            var $this = $(this);
            $this.css('left', curX);
            curX += $this.outerWidth(true);
        });
        var fullW = curX / 2;
        var viewportW = scroller.width();

        // Scrolling speed management
        var controller = {curSpeed:0, fullSpeed:2};
        var $controller = $(controller);
        var tweenToNewSpeed = function(newSpeed, duration)
        {
            if (duration === undefined)
                duration = 600;
            $controller.stop(true).animate({curSpeed:newSpeed}, duration);
        };

        // Pause on hover
        scroller.hover(function(){
            tweenToNewSpeed(0);
        }, function(){
            tweenToNewSpeed(controller.fullSpeed);
        });

        // Scrolling management; start the automatical scrolling
        var doScroll = function()
        {
            var curX = scroller.scrollLeft();
            var newX = curX + controller.curSpeed;
            if (newX > fullW*2 - viewportW)
                newX -= fullW;
            scroller.scrollLeft(newX);
        };
        setInterval(doScroll, 40);
        tweenToNewSpeed(controller.fullSpeed);
    });
  </script>
</body>

</html></code>```

答: yes you can use div tag, give class to your div tag and then insert image using css to that class.</p>

Title: Using divs on an image slider


问:
How to implement Security Protocols TLS 1.2 in .Net 3.5 framework
As Paypal updated their response, I need to update security protocols TLS to v1.2 in my existing application which is on .NET 3.5 framework.
What changes required to update this in existing code, I cannot update the application to newer framework. </p>

答:
I'm using VS 2008 with .net 3.5.30729.4926. All I had to do was:

Add imports:

```<code>Imports System.Security.Authentication
Imports System.Net
</code>```

Add this to my code (C#):

```<code>public const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
public const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
</code>```

VB.net version:

```<code>Const _Tls12 As SslProtocols = DirectCast(&HC00, SslProtocols)
Const Tls12 As SecurityProtocolType = DirectCast(_Tls12, SecurityProtocolType)
ServicePointManager.SecurityProtocol = Tls12

Dim wbrq As HttpWebRequest
Dim wbrs As HttpWebResponse
Dim sw As StreamWriter
Dim sr As StreamReader
Dim strResult As String

'Create a new HttpWebRequest object.
wbrq = WebRequest.Create(strURL)
wbrq.Method = "POST"
wbrq.ContentLength = DataString.Length
wbrq.ContentType = "application/x-www-form-urlencoded"

'upload data
sw = New StreamWriter(wbrq.GetRequestStream)
sw.Write(DataString)
sw.Close()

'get response
wbrs = wbrq.GetResponse
sr = New StreamReader(wbrs.GetResponseStream)
strResult = sr.ReadToEnd.Trim
sr.Close()
</code>```

Body:
I'm using VS 2008 with .net 3.5.30729.4926. All I had to do was:

Add imports:

Imports System.Security.Authentication
Imports System.Net

Add this to my code (C#):

public const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
public const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;

VB.net version:

Const _Tls12 As SslProtocols = DirectCast(&HC00, SslProtocols)
Const Tls12 As SecurityProtocolType = DirectCast(_Tls12, SecurityProtocolType)
ServicePointManager.SecurityProtocol = Tls12

Dim wbrq As HttpWebRequest
Dim wbrs As HttpWebResponse
Dim sw As StreamWriter
Dim sr As StreamReader
Dim strResult As String

'Create a new HttpWebRequest object.
wbrq = WebRequest.Create(strURL)
wbrq.Method = "POST"
wbrq.ContentLength = DataString.Length
wbrq.ContentType = "application/x-www-form-urlencoded"

'upload data
sw = New StreamWriter(wbrq.GetRequestStream)
sw.Write(DataString)
sw.Close()

'get response
wbrs = wbrq.GetResponse
sr = New StreamReader(wbrs.GetResponseStream)
strResult = sr.ReadToEnd.Trim
sr.Close()