问:
How to logout of Facebook using selenium.WebDriver and HtmlUnitDriver
I am using selenium.WebDriver and HtmlUnitDriver to login to Facebook, but I can't logout.

```<code>public static void main(String[] args) throws InterruptedException {

WebDriver driver = new HtmlUnitDriver();
driver.get("http://www.facebook.com");
System.out.println("Title of the page "+ driver.getTitle());
WebElement username = driver.findElement(By.id("email"));
username.sendKeys("xxxxx@gmail.com");
WebElement password = driver.findElement(By.id("pass"));
password.sendKeys("xxxxx");
WebElement Signup_button = driver.findElement(By.id("loginbutton"));
Signup_button.click();
Thread.sleep(5000);
System.out.println("After login title is = " + driver.getTitle());
</code>```

Until now it works. And The following steps cover the logout part (not working):

```<code>WebElement logOut = driver.findElement(By.id("userNavigationLabel"));
logOut.click();
Thread.sleep(5000);
WebElement signOut = driver.findElement(By.name("Log Out"));
logOut.click();

System.out.println("Logged Out Successfully!!!!!!!!!!!!!!!!!!!");
String pagetitle = driver.getTitle();
System.out.println(pagetitle);

}}
</code>```

Error:

```<code>Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element with name: Log Out
</code>```

Facebook Logout html code

```<code><span><span class="_54nh"><form class="_w0d"
 action="https://www.facebook.com/logout.php" data-nocookies="1"
id="show_me_how_logout_1" method="post" onsubmit="return window.Event
 && Event.__inlineSubmit &&
Event.__inlineSubmit(this,event)"><input name="fb_dtsg"
value="AQGzvtPjFD1W:AQFslBEMcQG9" autocomplete="off" type="hidden"><input
 autocomplete="off" name="ref" value="mb" type="hidden"><input
autocomplete="off" name="h" value="AfeziZXPRhN6ncxD" type="hidden">
</form>Log Out</span></span>
</code>```

I have also tried this Code by  Saurabh Gaur Selenium WebDriver Log Out from Facebook

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement accountSettings = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Account Settings")));
accountSettings.click() //this will click on setting link to open menu
WebElement logOut = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Log Out")));
logOut.click() // this will click on logout link
</code>```

Error

```<code>Exception in thread "main" org.openqa.selenium.TimeoutException: Timed out after 10 seconds waiting for element to be clickable: By.linkText: Log Out
Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:03'
System info: xxxxxxxxxxx java.version: '1.8.0_101'
Driver info: driver.version: unknown
    at org.openqa.selenium.support.ui.FluentWait.timeoutException(FluentWait.java:259)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:228)
    at HtmlDemoProgram1.main(HtmlDemoProgram1.java:53)
Caused by: org.openqa.selenium.NoSuchElementException: No link found with text: Log Out
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
</code>```

答:
Below code may help you.... Thanks.

package open_website;

```<code>import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;

    public class Open_website_1
    {

     public static void main(String[] args) {
     // TODO Auto-generated method stub

    String expath = "D:\\Eclipse\\chromedriver_win32\\chromedriver.exe";

    System.setProperty("webdriver.chrome.driver", "D:\\Eclipse\\chromedriver_win32\\chromedriver.exe");

    WebDriver driver = new ChromeDriver();

    driver.get("http:\\www.facebook.com");
    WebElement element1 = driver.findElement(By.id("email"));
    element1.sendKeys("patil_y7@yahoo.com");

    WebElement element2 = driver.findElement(By.id("pass"));
    element2.sendKeys("pa$$word123");

    WebElement element3 = driver.findElement(By.id("u_0_q"));
    element3.click();

    System.out.println("Login");

    WebElement lstitem=driver.findElement(By.id("userNavigationLabel"));
    lstitem.click();

    driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);

    driver.findElement(By.partialLinkText("Log Out")).click();

    System.out.println("Log out");

}
</code>```

}

Body:
I am using selenium.WebDriver and HtmlUnitDriver to login to Facebook, but I can't logout.

public static void main(String[] args) throws InterruptedException {

WebDriver driver = new HtmlUnitDriver();
driver.get("http://www.facebook.com");
System.out.println("Title of the page "+ driver.getTitle());
WebElement username = driver.findElement(By.id("email"));
username.sendKeys("xxxxx@gmail.com");
WebElement password = driver.findElement(By.id("pass"));
password.sendKeys("xxxxx");
WebElement Signup_button = driver.findElement(By.id("loginbutton"));
Signup_button.click();
Thread.sleep(5000);
System.out.println("After login title is = " + driver.getTitle());

Until now it works. And The following steps cover the logout part (not working):

WebElement logOut = driver.findElement(By.id("userNavigationLabel"));
logOut.click();
Thread.sleep(5000);
WebElement signOut = driver.findElement(By.name("Log Out"));
logOut.click();

System.out.println("Logged Out Successfully!!!!!!!!!!!!!!!!!!!");
String pagetitle = driver.getTitle();
System.out.println(pagetitle);

}}

Error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element with name: Log Out

Facebook Logout html code

<form class="_w0d"
 action="https://www.facebook.com/logout.php" data-nocookies="1"
id="show_me_how_logout_1" method="post" onsubmit="return window.Event
 && Event.__inlineSubmit &&
Event.__inlineSubmit(this,event)"><input name="fb_dtsg"
value="AQGzvtPjFD1W:AQFslBEMcQG9" autocomplete="off" type="hidden"><input
 autocomplete="off" name="ref" value="mb" type="hidden"><input
autocomplete="off" name="h" value="AfeziZXPRhN6ncxD" type="hidden">
</form>Log Out

I have also tried this Code by  Saurabh Gaur Selenium WebDriver Log Out from Facebook

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement accountSettings = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Account Settings")));
accountSettings.click() //this will click on setting link to open menu
WebElement logOut = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Log Out")));
logOut.click() // this will click on logout link

Error

Exception in thread "main" org.openqa.selenium.TimeoutException: Timed out after 10 seconds waiting for element to be clickable: By.linkText: Log Out
Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:03'
System info: xxxxxxxxxxx java.version: '1.8.0_101'
Driver info: driver.version: unknown
    at org.openqa.selenium.support.ui.FluentWait.timeoutException(FluentWait.java:259)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:228)
    at HtmlDemoProgram1.main(HtmlDemoProgram1.java:53)
Caused by: org.openqa.selenium.NoSuchElementException: No link found with text: Log Out
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html

Body:
Below code may help you.... Thanks.

package open_website;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;

    public class Open_website_1
    {

     public static void main(String[] args) {
     // TODO Auto-generated method stub

    String expath = "D:\\Eclipse\\chromedriver_win32\\chromedriver.exe";

    System.setProperty("webdriver.chrome.driver", "D:\\Eclipse\\chromedriver_win32\\chromedriver.exe");

    WebDriver driver = new ChromeDriver();

    driver.get("http:\\www.facebook.com");
    WebElement element1 = driver.findElement(By.id("email"));
    element1.sendKeys("patil_y7@yahoo.com");

    WebElement element2 = driver.findElement(By.id("pass"));
    element2.sendKeys("pa$$word123");

    WebElement element3 = driver.findElement(By.id("u_0_q"));
    element3.click();

    System.out.println("Login");

    WebElement lstitem=driver.findElement(By.id("userNavigationLabel"));
    lstitem.click();

    driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);

    driver.findElement(By.partialLinkText("Log Out")).click();

    System.out.println("Log out");

}

}


来源: stackexchange

问:
Receive mic input and process
I am writing a small program in C++ that receives mic input and does some simple live audio processing. I have been looking around and the only things I have been able to find that work on Linux are PortAudio, QAudioInput, and fmod.

I am trying to stay away from any super low level programming and use a minimal amount of lines.

Which one of these would fit my needs best?

答: Check out JUCE. Juce will build on many platforms. JUCE does a lot more than just audio, but it was made with audio programmers in mind. Look at he JUCE demo application and then just chop up the source code from the audio demo to suit your needs. The API documentation is really good also. The abstraction from the low level stuff is good.</p>

ContentLicense: CC BY-SA 3.0

Title: Receive mic input and process

ContentLicense: CC BY-SA 2.5


问:
Pure javascript slider bar limit
Im working with 3 slider bars with max=100 min=0, the first one its the principal, the other two bars value can't be higher or equal than the first one, and the third one value can't be higher or equal than the second one.
I dont know if it's there an operator or function to do that, to limit the value between a min max range.

<!DOCTYPE html>

 <title></title>

Foundations
<input type="range" name="s1" min="0" max="100"  id="bar1" value="0" oninput="mover1();">

Walls
<input type="range" name="s2" min="0" max="100"  id="bar2" value="0" style="margin-left: 1.9em;" >

Roof
<input type="range" name="s3" min="0" max="100" id="bar3" value="0" style="margin-left: 2.7em;" >

```

答:
<!DOCTYPE html>

  <title></title>

    Foundations
    <input type="range" name="s1" min="0" max="100" id="bar1" value="0" oninput="mover1();">

    Walls
    <input type="range" name="s2" min="0" max="100" id="bar2" value="0" oninput="mover1();">

    Roof
    <input type="range" name="s3" min="0" max="100" id="bar3" value="0" oninput="mover1();">

```

Title: Pure javascript slider bar limit

Body:
<!DOCTYPE html>
<html>

<head>
  <title></title>
  <script>
    var ranges;
    window.onload = function() {
      ranges = document.querySelectorAll("[id^=bar]");
    }

    function mover1() {
      if (+ranges[1].value >= ranges[0].value) {
        ranges[1].value = +ranges[0].value - 1
      }
      if (+ranges[2].value >= ranges[1].value) {
        ranges[2].value = +ranges[1].value - 1
      }
    }
  </script>
</head>

<body>
  <div>
    Foundations
    <input type="range" name="s1" min="0" max="100" id="bar1" value="0" oninput="mover1();">

  </div>
  <div>
    Walls
    <input type="range" name="s2" min="0" max="100" id="bar2" value="0" oninput="mover1();">
    <!-- style="margin-left: 1.9em;" -->
  </div>
  <div>
    Roof
    <input type="range" name="s3" min="0" max="100" id="bar3" value="0" oninput="mover1();">
    <!-- style="margin-left: 2.7em;" -->
  </div>
</body>

</html>


问:
Scrolling Image using PixelWriter / Reader
I'm trying to create a scrolling image that wraps around a canvas to follow its own tail. I've been trying to use PixelWriters and Readers to save off the vertical pixel lines that are scrolling off the screen to the West, and append these to a new image which, should grow on the RHS (East) of the screen.

It scrolls, but that's all that's happening. I don't understand how to calculate the scanlines, so apologies for this part.

Any help appreciated.

```<code>package controller;

import javafx.animation.AnimationTimer;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import util.GraphicsUtils;

import java.io.File;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;

class ImageContainer extends HBox {
int w, h;
int translatedAmount = 0;
Image image;
Canvas canvas;
long startNanoTime = System.nanoTime();
WritableImage eastImage = null;

public ImageContainer() {
    setVisible(true);
    load();
    w = (int) image.getWidth();
    h = (int) image.getHeight();
    canvas = new Canvas(w, h);
    int edgeX = (int) canvas.getWidth(); //You can set this a little west for visibility sake...whilst debugging
    getChildren().addAll(canvas);
    GraphicsContext gc = canvas.getGraphicsContext2D();
    canvas.setVisible(true);
    gc.drawImage(image, 0, 0, w, h);
    setPrefSize(w, h);
    eastImage = new WritableImage(translatedAmount+1, h); //create a new eastImage

    new AnimationTimer() {
        public void handle(long currentNanoTime) {
            if (((System.nanoTime() - startNanoTime) / 1000000000.0) < 0.05) {
                return;
            } else {
                startNanoTime = System.nanoTime();
            }

            translatedAmount++;

            Image westLine = getSubImageRectangle(image, 1, 0, 1, h); //get a 1 pixel strip from west of main image
            PixelReader westLinepixelReader = westLine.getPixelReader(); //create a pixel reader for this image
            byte[] westLinePixelBuffer = new byte[1 * h * 4]; //create a buffer to store the pixels collected from the about to vanish westLine
            westLinepixelReader.getPixels(0, 0, 1, h, PixelFormat.getByteBgraInstance(), westLinePixelBuffer, 0, 4); //collect the pixels from westLine strip

            Image tempImg = eastImage; //save away the current east side image

            byte[] tempBuffer = new byte[(int)tempImg.getWidth() * h * 4];
            PixelReader tempImagePixelReader = tempImg.getPixelReader(); //create a pixel reader for our temp copy of the east side image
            tempImagePixelReader.getPixels(0, 0, (int)tempImg.getWidth(), h, PixelFormat.getByteBgraInstance(), tempBuffer, 0, 4); //save the tempImage into the tempBuffer

            eastImage = new WritableImage(translatedAmount+1, h); //create a new eastImage, but one size larger
            PixelWriter eastImagePixelWriter = eastImage.getPixelWriter(); //create a pixel writer for this new east side image
            eastImagePixelWriter.setPixels(1, 0, (int)tempImg.getWidth(), h, PixelFormat.getByteBgraInstance(), tempBuffer, 0, 4); //copy the temp image in at x=1
            eastImagePixelWriter.setPixels((int)tempImg.getWidth(), 0, 1, h, PixelFormat.getByteBgraInstance(), westLinePixelBuffer, 0, 4); //copy the westLine at x=tempImg.width

            image = getSubImageRectangle(image, 1, 0, (int) image.getWidth() - 1, h);
            gc.drawImage(image, 0, 0); //draw main image
            System.out.println(edgeX-eastImage.getWidth());
            gc.drawImage(eastImage, edgeX-eastImage.getWidth(), 0); //add lost image lines
        }
    }.start();
}

public void load() {
    Path imagePath = Paths.get("./src/main/resources/ribbonImages/clouds.png");
    File f = imagePath.toFile();
    assert f.exists();
    image = new Image(f.toURI().toString());
}

public Image getSubImageRectangle(Image image, int x, int y, int w, int h) {
    PixelReader pixelReader = image.getPixelReader();
    WritableImage newImage = new WritableImage(pixelReader, x, y, w, h);
    ImageView imageView = new ImageView();
    imageView.setImage(newImage);
    return newImage;
}
}
</code>```

答:
Why make this more difficult than necessary? Simply draw the image to the Canvas twice:

```<code>public static void drawImage(Canvas canvas, Image sourceImage, double offset, double wrapWidth) {
    GraphicsContext gc = canvas.getGraphicsContext2D();
    gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());

    // make |offset| < wrapWidth
    offset %= wrapWidth;
    if (offset < 0) {
        // make sure positive offsets do not result in the previous version
        // of the image not being drawn
        offset += wrapWidth;
    }
    gc.drawImage(sourceImage, -offset, 0);
    gc.drawImage(sourceImage, wrapWidth - offset, 0);
}

@Override
public void start(Stage primaryStage) {
    Image image = new Image("https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/402px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg");
    Canvas canvas = new Canvas(image.getWidth(), image.getHeight());
    primaryStage.setResizable(false);

    Scene scene = new Scene(new Group(canvas));

    DoubleProperty offset = new SimpleDoubleProperty();
    offset.addListener((observable, oldOffset, newOffset) -> drawImage(canvas, image, newOffset.doubleValue(), canvas.getWidth()));
    Timeline timeline = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(offset, 0, Interpolator.LINEAR)),
            new KeyFrame(Duration.seconds(10), new KeyValue(offset, image.getWidth()*2, Interpolator.LINEAR))
    );
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();

    primaryStage.setScene(scene);
    primaryStage.sizeToScene();
    primaryStage.show();
}
</code>```

Body:
I'm trying to create a scrolling image that wraps around a canvas to follow its own tail. I've been trying to use PixelWriters and Readers to save off the vertical pixel lines that are scrolling off the screen to the West, and append these to a new image which, should grow on the RHS (East) of the screen.

It scrolls, but that's all that's happening. I don't understand how to calculate the scanlines, so apologies for this part.

Any help appreciated.

package controller;

import javafx.animation.AnimationTimer;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import util.GraphicsUtils;

import java.io.File;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;

class ImageContainer extends HBox {
int w, h;
int translatedAmount = 0;
Image image;
Canvas canvas;
long startNanoTime = System.nanoTime();
WritableImage eastImage = null;

public ImageContainer() {
    setVisible(true);
    load();
    w = (int) image.getWidth();
    h = (int) image.getHeight();
    canvas = new Canvas(w, h);
    int edgeX = (int) canvas.getWidth(); //You can set this a little west for visibility sake...whilst debugging
    getChildren().addAll(canvas);
    GraphicsContext gc = canvas.getGraphicsContext2D();
    canvas.setVisible(true);
    gc.drawImage(image, 0, 0, w, h);
    setPrefSize(w, h);
    eastImage = new WritableImage(translatedAmount+1, h); //create a new eastImage

    new AnimationTimer() {
        public void handle(long currentNanoTime) {
            if (((System.nanoTime() - startNanoTime) / 1000000000.0) < 0.05) {
                return;
            } else {
                startNanoTime = System.nanoTime();
            }

            translatedAmount++;

            Image westLine = getSubImageRectangle(image, 1, 0, 1, h); //get a 1 pixel strip from west of main image
            PixelReader westLinepixelReader = westLine.getPixelReader(); //create a pixel reader for this image
            byte[] westLinePixelBuffer = new byte[1 * h * 4]; //create a buffer to store the pixels collected from the about to vanish westLine
            westLinepixelReader.getPixels(0, 0, 1, h, PixelFormat.getByteBgraInstance(), westLinePixelBuffer, 0, 4); //collect the pixels from westLine strip

            Image tempImg = eastImage; //save away the current east side image

            byte[] tempBuffer = new byte[(int)tempImg.getWidth() * h * 4];
            PixelReader tempImagePixelReader = tempImg.getPixelReader(); //create a pixel reader for our temp copy of the east side image
            tempImagePixelReader.getPixels(0, 0, (int)tempImg.getWidth(), h, PixelFormat.getByteBgraInstance(), tempBuffer, 0, 4); //save the tempImage into the tempBuffer

            eastImage = new WritableImage(translatedAmount+1, h); //create a new eastImage, but one size larger
            PixelWriter eastImagePixelWriter = eastImage.getPixelWriter(); //create a pixel writer for this new east side image
            eastImagePixelWriter.setPixels(1, 0, (int)tempImg.getWidth(), h, PixelFormat.getByteBgraInstance(), tempBuffer, 0, 4); //copy the temp image in at x=1
            eastImagePixelWriter.setPixels((int)tempImg.getWidth(), 0, 1, h, PixelFormat.getByteBgraInstance(), westLinePixelBuffer, 0, 4); //copy the westLine at x=tempImg.width

            image = getSubImageRectangle(image, 1, 0, (int) image.getWidth() - 1, h);
            gc.drawImage(image, 0, 0); //draw main image
            System.out.println(edgeX-eastImage.getWidth());
            gc.drawImage(eastImage, edgeX-eastImage.getWidth(), 0); //add lost image lines
        }
    }.start();
}

public void load() {
    Path imagePath = Paths.get("./src/main/resources/ribbonImages/clouds.png");
    File f = imagePath.toFile();
    assert f.exists();
    image = new Image(f.toURI().toString());
}

public Image getSubImageRectangle(Image image, int x, int y, int w, int h) {
    PixelReader pixelReader = image.getPixelReader();
    WritableImage newImage = new WritableImage(pixelReader, x, y, w, h);
    ImageView imageView = new ImageView();
    imageView.setImage(newImage);
    return newImage;
}
}

Body:
Why make this more difficult than necessary? Simply draw the image to the Canvas twice:

public static void drawImage(Canvas canvas, Image sourceImage, double offset, double wrapWidth) {
    GraphicsContext gc = canvas.getGraphicsContext2D();
    gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());

    // make |offset| < wrapWidth
    offset %= wrapWidth;
    if (offset < 0) {
        // make sure positive offsets do not result in the previous version
        // of the image not being drawn
        offset += wrapWidth;
    }
    gc.drawImage(sourceImage, -offset, 0);
    gc.drawImage(sourceImage, wrapWidth - offset, 0);
}

@Override
public void start(Stage primaryStage) {
    Image image = new Image("https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/402px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg");
    Canvas canvas = new Canvas(image.getWidth(), image.getHeight());
    primaryStage.setResizable(false);

    Scene scene = new Scene(new Group(canvas));

    DoubleProperty offset = new SimpleDoubleProperty();
    offset.addListener((observable, oldOffset, newOffset) -> drawImage(canvas, image, newOffset.doubleValue(), canvas.getWidth()));
    Timeline timeline = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(offset, 0, Interpolator.LINEAR)),
            new KeyFrame(Duration.seconds(10), new KeyValue(offset, image.getWidth()*2, Interpolator.LINEAR))
    );
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();

    primaryStage.setScene(scene);
    primaryStage.sizeToScene();
    primaryStage.show();
}


问:
Fixed Header on Mobile with oversized page body
I have a webpage with a fixed header like usual:

```<code>.header{
position: fixed;
top: 0px;
left: 0px;
width: 100%;
}
</code>```

The main body of the page is a svg image that is 1200px wide. On mobile, this makes the header stretch to 1200px and require scrolling to view it all.

I want the header to behave as a fixed header should - be exactly the width of the screen, and remain fixed - regardless if the main body is scrolled vertically or horizontally, and optimally, even if it is zoomed.

EDIT: I tried using 100vw instead of 100% and it works a little better - the header doesn't expand wider than the screen. But the header still scrolls out of site when scrolling the body.

Update: From the comments, it looks like you all aren't getting the problem. Here is a codepen to demonstrate. If you view it on desktop, it works fine. But when I view it on my iphone 5 safari browser, the header is stretched to the width of the image.

http://codepen.io/life4ants/full/LWybQZ/

答:
I fixed this by adding this meta tag:

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0,
   maximum-scale=1.0, user-scalable=no"/>
</code>```

And wrapping the page with:

```<code>.bg{
  width: 100%;
  height: 100%;
  overflow: scroll;
  -webkit-overflow-scrolling: touch;
}
</code>```

Body:
I have a webpage with a fixed header like usual:

.header{
position: fixed;
top: 0px;
left: 0px;
width: 100%;
}

The main body of the page is a svg image that is 1200px wide. On mobile, this makes the header stretch to 1200px and require scrolling to view it all.

I want the header to behave as a fixed header should - be exactly the width of the screen, and remain fixed - regardless if the main body is scrolled vertically or horizontally, and optimally, even if it is zoomed.

EDIT: I tried using 100vw instead of 100% and it works a little better - the header doesn't expand wider than the screen. But the header still scrolls out of site when scrolling the body.

Update: From the comments, it looks like you all aren't getting the problem. Here is a codepen to demonstrate. If you view it on desktop, it works fine. But when I view it on my iphone 5 safari browser, the header is stretched to the width of the image.

http://codepen.io/life4ants/full/LWybQZ/

Body:
I fixed this by adding this meta tag:

<meta name="viewport" content="width=device-width, initial-scale=1.0,
   maximum-scale=1.0, user-scalable=no"/>

And wrapping the page with:

.bg{
  width: 100%;
  height: 100%;
  overflow: scroll;
  -webkit-overflow-scrolling: touch;
}


问:
Map properties to state in react-redux
I have a component that uses state to provide data to user. For example
this.state.variableInState
. This component can dispatch some method (for example on onClick action). I'm currently using react-redux an connect method to map store to props. Is there a way I can setState after dispatch?

```<code>// actions
export function executeAction() {
  return function (dispatch, getState) {
    dispatch({
      type: 'MY_ACTION',
      payload: axios.get('/some/url')
    });
  };
}
// reducer

export default function (state = {}, action) {
  switch (action.type) {
    case 'MY_ACTION_FULFILLED':
      return {...state, myVariable: action.payload.data}
  }
}
//component
class MyComponent extends Component {
  render() {
    (<div onClick={this.props.executeAction.bind(this)}>
      {this.state.variableInState}
      </div>)
  }

  someOtherMethod() {
    // I want to operate with state here, not with props
    // that's why my div gets state from this.state instead of this.props
    this.setState({variableInState: 'someValue'})
  }
}

export default connect((state, ownProperties) => {
  return {
    // So I want to change MyComponent.state.variableInState here
    // but this method updates MyComponent props only
    // What can I do?
    variableInProps: state.myVariable
  }
}, {executeAction})(MyComponent);
</code>```

答:
Whatever i understand, all you want to do is to convert the component's props to component's own state. You can always change the component's props to component's state in the componentWillReceiveProps life cycle method in component like this.

```<code>//component
class MyComponent extends Component {
  componentWillReceiveProps(newProps){
     if(newProps.variableInProps != this.props.variableInProps){
         this.setState({variableInState: newProps.variableInProps })
     }
  }
  render() {
    (<div onClick={this.props.executeAction.bind(this)}>
      {this.state.variableInState}
      </div>)
  }

  someOtherMethod() {
    // I want to operate with state here, not with props
    // that's why my div gets state from this.state instead of this.props
    this.setState({variableInState: 'someValue'})
  }
}

export default connect((state, ownProperties) => {
  return {
    // So I want to change MyComponent.state.variableInState here
    // but this method updates MyComponent props only
    // What can I do?
    variableInProps: state.myVariable
  }
}, {executeAction})(MyComponent);
</code>```

componentWillReceiveProps method is always executed by react whenever a new props is coming to component so this is the right place to update your component's state according to your props.

UPDATE :

The componentWillReceiveProps has been deprecated. So instead of this method you can use componentDidUpdate method to do this. componentDidUpdate method takes previous props and previous state as arguments. So you can check for the change in props and then set the state.

```<code>componentDidUpdate(prevProps) {
  if(prevProps.variableInProps !== this.props.variableInProps){
    this.setState({variableInState: this.props.variableInProps })
  }
}
</code>```

Title: Map properties to state in react-redux

Body:
I have a component that uses state to provide data to user. For example
this.state.variableInState
. This component can dispatch some method (for example on onClick action). I'm currently using react-redux an connect method to map store to props. Is there a way I can setState after dispatch?

// actions
export function executeAction() {
  return function (dispatch, getState) {
    dispatch({
      type: 'MY_ACTION',
      payload: axios.get('/some/url')
    });
  };
}
// reducer

export default function (state = {}, action) {
  switch (action.type) {
    case 'MY_ACTION_FULFILLED':
      return {...state, myVariable: action.payload.data}
  }
}
//component
class MyComponent extends Component {
  render() {
    (

      {this.state.variableInState}

)
  }

  someOtherMethod() {
    // I want to operate with state here, not with props
    // that's why my div gets state from this.state instead of this.props
    this.setState({variableInState: 'someValue'})
  }
}

export default connect((state, ownProperties) => {
  return {
    // So I want to change MyComponent.state.variableInState here
    // but this method updates MyComponent props only
    // What can I do?
    variableInProps: state.myVariable
  }
}, {executeAction})(MyComponent);

Body:
Whatever i understand, all you want to do is to convert the component's props to component's own state. You can always change the component's props to component's state in the componentWillReceiveProps life cycle method in component like this.

//component
class MyComponent extends Component {
  componentWillReceiveProps(newProps){
     if(newProps.variableInProps != this.props.variableInProps){
         this.setState({variableInState: newProps.variableInProps })
     }
  }
  render() {
    (<div onClick={this.props.executeAction.bind(this)}>
      {this.state.variableInState}
      </div>)
  }

  someOtherMethod() {
    // I want to operate with state here, not with props
    // that's why my div gets state from this.state instead of this.props
    this.setState({variableInState: 'someValue'})
  }
}

export default connect((state, ownProperties) => {
  return {
    // So I want to change MyComponent.state.variableInState here
    // but this method updates MyComponent props only
    // What can I do?
    variableInProps: state.myVariable
  }
}, {executeAction})(MyComponent);

componentWillReceiveProps method is always executed by react whenever a new props is coming to component so this is the right place to update your component's state according to your props.

UPDATE :

The componentWillReceiveProps has been deprecated. So instead of this method you can use componentDidUpdate method to do this. componentDidUpdate method takes previous props and previous state as arguments. So you can check for the change in props and then set the state.

componentDidUpdate(prevProps) {
  if(prevProps.variableInProps !== this.props.variableInProps){
    this.setState({variableInState: this.props.variableInProps })
  }
}

ContentLicense: CC BY-SA 4.0


问:
How can I hide FAB button while playing video fullscreen?
How to hide fab button while i play video in fullscreen? Show button until video goes fullscreen. I have a webview app with fab button.</p>

答:
Find you FAB by id then just set visibility to false.

myFAB.setVisibility(false)


问:
PHP MySQL order by first column, if second NULL
I have table:

```<code>id  |  post_date  |  bumped_post_date
1   |    date     |       NULL
2   |    date     |       date2
</code>```

Ok, I know how to order by post_date, but I wan't to order by post_date only when bumped_post_date is NULL.

When bumped_post_date is not NULL, then order by it, not by post_date ( But if NULL, then order by post_date ). Thanks and sorry for my bad English.

答:
You can use CASE in the ORDER BY:

```<code>select *
from your_table
order by case
        when bumped_post_date is not null
            then bumped_post_date
        else post_date
        end;
</code>```

Body:
I have table:

id  |  post_date  |  bumped_post_date
1   |    date     |       NULL
2   |    date     |       date2

Ok, I know how to order by post_date, but I wan't to order by post_date only when bumped_post_date is NULL.

When bumped_post_date is not NULL, then order by it, not by post_date ( But if NULL, then order by post_date ). Thanks and sorry for my bad English.

Body:
You can use CASE in the ORDER BY:

select *
from your_table
order by case
        when bumped_post_date is not null
            then bumped_post_date
        else post_date
        end;


问:
How to access default Rails sqlite db?
I would like to view the data in my DB while developing with Rails (actually in all 3 of them development, test and production). I have not touched the configs, so it should be easy, but I was not able to find any usable info.

I have no idea what the connection string could be or where to enter it, since Aptana (v.3) seems to lack the good old data source explorer view I know from Eclipse. Could someone point me into the right direction?

EDIT: I am working on linux - Mint 12

答:
You can have online access to your database if you use activeadmin.

Just add the gem activeadmin-sqlpage:

```<code>gem 'activeadmin-sqlpage'
</code>```

And create activeadmin page:

```<code># file app/admin/sql.rb
ActiveAdmin::SqlPage::register
</code>```

Restart your server. Then go to admin panel and navigate the menu SQL. Enter any sql command and press Ctrl+Enter or Submit button.

Title: How to access default Rails sqlite db?

Body:
You can have online access to your database if you use activeadmin.

Just add the gem activeadmin-sqlpage:

gem 'activeadmin-sqlpage'

And create activeadmin page:

# file app/admin/sql.rb
ActiveAdmin::SqlPage::register

Restart your server. Then go to admin panel and navigate the menu SQL. Enter any sql command and press Ctrl+Enter or Submit button.


问:
Using Python Regex to Automate Text Extraction
I am working on an automation project that involves using a python script that parses a txt file and repeatedly extracts 3 lines of data that come after a keyword. To give context, the txt files contains hundreds of form letters that are the same except for the name and address at their end. My end goal is to step through all of these form letters and extract the names and address and put them into an Excel spreadsheet using openpyxl. Here is an example of what the txt document looks like...

```<code>Dear Sir,

Body of letter that is the same for all of the letters. Etc.

Sincerely,

Mr. John Smith
123 Any Street
Anytown, USA 11111
</code>```

```<code>Dear Sir,

Body of letter that is the same for all of the letters. Etc.

Sincerely,

[Ms.] [Jane] [Doe]
[456 Some Lane]
[Sometown, USA 22222]
</code>```

etc. (These letters go on and on with different names that need to be extracted)

My question is how can I use regex in python to set a "last word keyword" (in this particular batch of letters "Sincerely," but could change to something else like "Regards" in another separate txt file) and commit to memory each bracketed item shown above (brackets correspond to eventual Excel columns like suffix, first name, Last Name, address, town) and step through each of the hundreds of letters? Is this simple to do using regex or python in general? I think I can manage to do it for one letter, but am stuck at how to move on to the next end keyword for the next letter. If anyone has any thoughts on what would be the most efficient way to approach this, I would greatly appreciate it! Also, I know it is costumery to post my initial approach to the problem, however being completely unfamiliar to regex operations, my attempt was not even close. Also, let me know if I am doing something unorthodox with a Stack Overflow question as I am new here.

Example input: letters input.txt

email received 3/30/17:

```<code>Dear Sir,

I would be delighted to be placed on your mailing list. Please keep up the great work!

Sincerely,

Mr. Thomas Dahlmer
46 Alpine Street
Evanston, Il 60201
</code>```

email received 3/30/17:

Dear Sir,

I would be delighted to be placed on your mailing list. Please keep up the great work!

Sincerely,

Mr. Robert Nolan

1104 Madison Avenue

New York, NY 10021

email received 3/30/17:

```<code>Dear Sir,

I would be delighted to be placed on your mailing list. Please keep up the great work!

Sincerely,

Ms. Angela Carraway <br/>
402 Arlington Drive <br/>
Concord, MA 01742
</code>```

example output

lettersoutput.txt

```<code>Mr. Thomas Dahlmer <br/>
46 Alpine Street <br/>
Evanston, Il 60201

Mr. Robert Nolan <br/>
1104 Madison Avenue <br/>
New York, NY 10021

Ms. Angela Carraway <br/>
402 Arlington Drive <br/>
Concord, MA 01742
</code>```

答:
It's kinda long: Sincerely,[\s\n]+([\w\.]+)\s+(\w+)\s+(\w+)[\s\n]+(\d+\s\w+\s\w+)[\s\n]+(\w+\s?\w+,\s\w+\s\d+)

It captures as 5 groups: Title, Firstname, Lastname, Address1, Address2

Demo: https://regex101.com/r/kkNWWB/3

There are five parantheses and each parantesis represent a capturing group:

([\w\.]+) matches and captures first group: Title

(\w+) matches and captures second group: Firstname

(\w+) matches and captures third group: Lastname

(\d+\s\w+\s\w+) matches and captures fourth group: Address1

(\w+\s?\w+,\s\w+\s\d+) matches and captures fifth group: Address2

Rest of the regex just fills the gap between capturing groups, they only match but do not capture.

Body:
I am working on an automation project that involves using a python script that parses a txt file and repeatedly extracts 3 lines of data that come after a keyword. To give context, the txt files contains hundreds of form letters that are the same except for the name and address at their end. My end goal is to step through all of these form letters and extract the names and address and put them into an Excel spreadsheet using openpyxl. Here is an example of what the txt document looks like...

Dear Sir,

Body of letter that is the same for all of the letters. Etc.

Sincerely,

Mr. John Smith
123 Any Street
Anytown, USA 11111

Dear Sir,

Body of letter that is the same for all of the letters. Etc.

Sincerely,

[Ms.] [Jane] [Doe]
[456 Some Lane]
[Sometown, USA 22222]

etc. (These letters go on and on with different names that need to be extracted)

My question is how can I use regex in python to set a "last word keyword" (in this particular batch of letters "Sincerely," but could change to something else like "Regards" in another separate txt file) and commit to memory each bracketed item shown above (brackets correspond to eventual Excel columns like suffix, first name, Last Name, address, town) and step through each of the hundreds of letters? Is this simple to do using regex or python in general? I think I can manage to do it for one letter, but am stuck at how to move on to the next end keyword for the next letter. If anyone has any thoughts on what would be the most efficient way to approach this, I would greatly appreciate it! Also, I know it is costumery to post my initial approach to the problem, however being completely unfamiliar to regex operations, my attempt was not even close. Also, let me know if I am doing something unorthodox with a Stack Overflow question as I am new here.

Example input: letters input.txt

email received 3/30/17:

Dear Sir,

I would be delighted to be placed on your mailing list. Please keep up the great work!

Sincerely,

Mr. Thomas Dahlmer
46 Alpine Street
Evanston, Il 60201

email received 3/30/17:

Dear Sir,

I would be delighted to be placed on your mailing list. Please keep up the great work!

Sincerely,

Mr. Robert Nolan

1104 Madison Avenue

New York, NY 10021

email received 3/30/17:

Dear Sir,

I would be delighted to be placed on your mailing list. Please keep up the great work!

Sincerely,

Ms. Angela Carraway

402 Arlington Drive

Concord, MA 01742

example output

lettersoutput.txt

Mr. Thomas Dahlmer

46 Alpine Street

Evanston, Il 60201

Mr. Robert Nolan

1104 Madison Avenue

New York, NY 10021

Ms. Angela Carraway

402 Arlington Drive

Concord, MA 01742


答:
you could use  a case when </p>

```<code>select * from my_table
order by case when  bumped_post_date is null
            then post_date else bumped_post_date end
</code>```

Title: PHP MySQL order by first column, if second NULL

Body:
you could use  a case when

select * from my_table
order by case when  bumped_post_date is null
            then post_date else bumped_post_date end


问:
How to filter out words with low tf-idf in a corpus with gensim?
I am using gensim for some NLP task. I've created a corpus from dictionary.doc2bow where dictionary is an object of corpora.Dictionary. Now I want to filter out the terms with low tf-idf values before running an LDA model. I looked into the documentation of the corpus class but cannot find a way to access the terms. Any ideas? Thank you.

答:
This is old, but if you wanted to look at in on a per document level do something like this:</p>

```<code>#same as before
dictionary = corpora.Dictionary(doc_list)
corpus = [dictionary.doc2bow(doc) for doc in doc_list]
tfidf = models.TfidfModel(corpus, id2word = dictionary)

#filter low value words
low_value = 0.025

for i in range(0, len(corpus)):
    bow = corpus[i]
    low_value_words = [] #reinitialize to be safe. You can skip this.
    low_value_words = [id for id, value in tfidf[bow] if value < low_value]
    new_bow = [b for b in bow if b[0] not in low_value_words]

    #reassign
    corpus[i] = new_bow
</code>```

Body:
This is old, but if you wanted to look at in on a per document level do something like this:

#same as before
dictionary = corpora.Dictionary(doc_list)
corpus = [dictionary.doc2bow(doc) for doc in doc_list]
tfidf = models.TfidfModel(corpus, id2word = dictionary)

#filter low value words
low_value = 0.025

for i in range(0, len(corpus)):
    bow = corpus[i]
    low_value_words = [] #reinitialize to be safe. You can skip this.
    low_value_words = [id for id, value in tfidf[bow] if value < low_value]
    new_bow = [b for b in bow if b[0] not in low_value_words]

    #reassign
    corpus[i] = new_bow


问:
Why do I get a Memory Error when trying to overwrite a variable in a while loop? (Python)
Hello I am new to python and decided to practice writing some algorithms.
The problem I am trying to solve can be found here if interested > http://codeforces.com/problemset/problem/791/A

This is the code that I have written to solve that problem.

```<code>a = input("Enter Limak's weight:")
b = input("Enter Bob's Weight:")
i = 0

while (a < b):
    a = (a * 3)
    b = (b * 2)
    i= (i + 1)

print(i)
</code>```

When I attempt to the run the code I receive the following error-

```<code>Enter Limak's weight:4
Enter Bob's Weight:7
Traceback (most recent call last):
  File "s.py", line 6, in <module>
    a = (a * 3)
MemoryError
</code>```

Any ideas?

答:
I can not reproduce your crash using python 2.7.12.
Assuming you are using python 3, my guess is that your variables a and b are of type str and not int.
You need to cast them as int after reading them from the console.

Try changing:

```<code>a = input("Enter Limak's weight:")
</code>```

with:

```<code>a = int(input("Enter Limak's weight:"))
</code>```

And a little tip, in python you can write the expression:

```<code>i = i * 1
</code>```

as

```<code>i += 1
</code>```

As @Pfonks pointed out, this notation applies to most operators like *, - or /

Body:
Hello I am new to python and decided to practice writing some algorithms.
The problem I am trying to solve can be found here if interested > http://codeforces.com/problemset/problem/791/A

This is the code that I have written to solve that problem.

a = input("Enter Limak's weight:")
b = input("Enter Bob's Weight:")
i = 0

while (a < b):
    a = (a * 3)
    b = (b * 2)
    i= (i + 1)

print(i)

When I attempt to the run the code I receive the following error-

Enter Limak's weight:4
Enter Bob's Weight:7
Traceback (most recent call last):
  File "s.py", line 6, in <module>
    a = (a * 3)
MemoryError

Any ideas?

Body:
I can not reproduce your crash using python 2.7.12.
Assuming you are using python 3, my guess is that your variables a and b are of type str and not int.
You need to cast them as int after reading them from the console.

Try changing:

a = input("Enter Limak's weight:")

with:

a = int(input("Enter Limak's weight:"))

And a little tip, in python you can write the expression:

i = i * 1

as

i += 1

As @Pfonks pointed out, this notation applies to most operators like *, - or /


问:
Sending data using jquery/ajax to mvc controller
Inside my MVC application this is my model:

```<code>public class Student
    {
        public string StudentId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }
</code>```

My .cshtml is like:

```<code>@using (Ajax.BeginForm(null, "TestAjaxBeginForm", null , null))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.StudentId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StudentId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" onclick="GetData()"/>
            </div>
        </div>
    </div>
}
</code>```

I am using jquery to send data in controller from .cshtml file.

```<code><script>
    function GetData()
    {
        debugger;
         var Student = [
        {
            'StudentId': $('#StudentId').val(),
            'Name': $('#Name').val(),
            'Address': $('#Address').val()
        }
        ];
        Student = JSON.stringify({ 'Student': Student });

        $.ajax({
            type: "POST",
            url: "/Student/GetData/",
            dataType: "json",
            contentType: "application/json",
            data: Student,
            processData: true,
            success: function (data) {
                alert("Hi");
                //alert(data);
            },
            error: function (xhr, ajaxOptions, error) {
                alert(xhr.status);
                alert("Error: " + xhr.responseText);
                //alert(error);
            }
        });
    }

</script>
</code>```

And my controller is:

```<code>   [HttpPost]
    public ActionResult GetData(Student Student)
    {
        var StudentId = Student.StudentId.ToString();
        var StudentName = Student.Name.ToString();
        var Address = Student.Address.ToString();
        return Json(JsonRequestBehavior.AllowGet);
    }
</code>```

I my getting form data inside jscript function, but inside controller(GetData) values of StudentId, StudentName and address are showing null.
Any help will be thankfully accepted.

Thanks
Partha

答:
Changing it to the following should work:

```<code>    var Student =
    {
        StudentId: $('[name="StudentId"').val(),
        Name: $('[name="Name"]').val(),
        Address: $('[name="Address"]').val()
    }
</code>```

Also there is no need for the JSON.stringify call

Body:
Inside my MVC application this is my model:

public class Student
    {
        public string StudentId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

My .cshtml is like:

@using (Ajax.BeginForm(null, "TestAjaxBeginForm", null , null))
{
    @Html.AntiForgeryToken()

Student

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.StudentId, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.StudentId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentId, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })

                <input type="submit" value="Create" class="btn btn-default" onclick="GetData()"/>

}

I am using jquery to send data in controller from .cshtml file.

And my controller is:

   [HttpPost]
    public ActionResult GetData(Student Student)
    {
        var StudentId = Student.StudentId.ToString();
        var StudentName = Student.Name.ToString();
        var Address = Student.Address.ToString();
        return Json(JsonRequestBehavior.AllowGet);
    }

I my getting form data inside jscript function, but inside controller(GetData) values of StudentId, StudentName and address are showing null.
Any help will be thankfully accepted.

Thanks
Partha

Body:
Changing it to the following should work:

    var Student =
    {
        StudentId: $('[name="StudentId"').val(),
        Name: $('[name="Name"]').val(),
        Address: $('[name="Address"]').val()
    }

Also there is no need for the JSON.stringify call


问:
How can I send a JSON object from a Python script to jQuery?
I've looked through APIs and all sorts of resources, but I can't seem to get the hang of fetching a JSON object from a Python script using AJAX. I'm sure the issue is with how I'm dealing with the JSON object.

First, in a python script on my server, I generate and print a JSON array

```<code>import json
print "Content-type: application/json"
print
print json.dumps(['Price',{'Cost':'99'}])
</code>```

Then, in a separate html file, I try something like

```<code><body>
<div id="test">
</div>

<script>
 $(document).ready(function() {
  $.getJSON("http://www.example.com/cgi-bin/makeJSON.py", function(data) {
        $('#test').html("JSON Data: " + data.Price);
    });
});
</script>
</body>
</code>```

But I don't get anything. I'm sure that data.Price is wrong, but I'm also pretty certain that I should be doing something instead of just printing the results of json.dumps

Any help is appreciated! Thanks in advance, and sorry if this is an obvious question.

答:
In your case you have enclosed the JSON response in an array. To access price you need to access data[0]. You need to structure your JSON data properly.

The following changes in your Python script should allow you to access data.Price. Let me know in case you still face any issues.

```<code>   import json
   print "Content-type: application/json"
   print
   response={'Price':54,'Cost':'99'}
   print(json.JSONEncoder().encode(response))
</code>```

Body:
I've looked through APIs and all sorts of resources, but I can't seem to get the hang of fetching a JSON object from a Python script using AJAX. I'm sure the issue is with how I'm dealing with the JSON object.

First, in a python script on my server, I generate and print a JSON array

import json
print "Content-type: application/json"
print
print json.dumps(['Price',{'Cost':'99'}])

Then, in a separate html file, I try something like

But I don't get anything. I'm sure that data.Price is wrong, but I'm also pretty certain that I should be doing something instead of just printing the results of json.dumps

Any help is appreciated! Thanks in advance, and sorry if this is an obvious question.

Body:
In your case you have enclosed the JSON response in an array. To access price you need to access data[0]. You need to structure your JSON data properly.

The following changes in your Python script should allow you to access data.Price. Let me know in case you still face any issues.

   import json
   print "Content-type: application/json"
   print
   response={'Price':54,'Cost':'99'}
   print(json.JSONEncoder().encode(response))


问:
How can I remove these DisplayObjects at end of a scene?
I want the balloons in this scene, which are DisplayObjects, to disappear when the scene ends. I have added them to the local sceneGroup = scene.view by passing this as the first argument to display.newImageRect() and assumed this would be enough for them to be removed as they are listed in the destroy.scene bit at the bottom. However when it transitions to the next scene they are still there.  Why are these DisplayObjects not being removed?

```<code>local composer = require( "composer" )

local scene = composer.newScene()

local Balloons

local positioninsheetOptions = 100

local sheetOptions =
{
    frames =
    {
        {
            x = 0,
            y = 0,
            width = 71,
            height = 100
        },
        {
            x = 0,
            y = positioninsheetOptions,
            width = 71,
            height = 100
        },
        {
            x = 0,
            y = positioninsheetOptions*2,
            width = 71,
            height = 100
        },
        {
            x = 0,
            y = positioninsheetOptions*3,
            width = 71,
            height = 100
        },
        {
            x = 0,
            y = positioninsheetOptions*4,
            width = 71,
            height = 100
        },
         {
            x = 0,
            y = positioninsheetOptions*5,
            width = 71,
            height = 100
        },
         {
            x = 0,
            y = positioninsheetOptions*6,
            width = 71,
            height = 100
        },
         {
            x = 0,
            y = positioninsheetOptions*7,
            width = 71,
            height = 100
        },
         {
            x = 0,
            y = positioninsheetOptions*8,
            width = 71,
            height = 100
        },

         {
            x = 0,
            y = positioninsheetOptions*9,
            width = 71,
            height = 100
        },

             {
            x = 0,
            y = positioninsheetOptions*10,
            width = 71,
            height = 100
        },

             {
            x = 0,
            y = positioninsheetOptions*11,
            width = 71,
            height = 100
        },

         },
        }
local objectSheet = graphics.newImageSheet( "gameObjects.png", sheetOptions )
Balloons = {}

-- -----------------------------------------------------------------------------------
-- Code outside of the scene event functions below will only be executed ONCE unless
-- the scene is removed entirely (not recycled) via "composer.removeScene()"
-- -----------------------------------------------------------------------------------

local function gotoGame()
    composer.gotoScene( "game" )
end

-- -----------------------------------------------------------------------------------
-- Scene event functions
-- -----------------------------------------------------------------------------------

-- create()
function scene:create( event )

    local sceneGroup = self.view
    -- Code here runs when the scene is first created but has not yet appeared on screen

    local background = display.newImageRect( sceneGroup, "background.png", 800, 1400 )
    background.x = display.contentCenterX
    background.y = display.contentCenterY

        local balloonBlue1 = display.newImageRect(sceneGroup, objectSheet, 6, 71, 100)
        local balloonYellow1 = display.newImageRect(sceneGroup, objectSheet, 8, 71, 100)
        local balloonRed1 = display.newImageRect(sceneGroup, objectSheet, 10, 71, 100)
        local balloonBlue2 = display.newImageRect(sceneGroup, objectSheet, 6, 71, 100)

        local Balloons = display.newGroup()

    Balloons:insert( balloonBlue1 )
    Balloons:insert( balloonYellow1 )
    Balloons:insert( balloonRed1 )
    Balloons:insert( balloonBlue2 )

    Balloons:addEventListener( "tap", gotoGame )

    balloonBlue1.x = (display.contentWidth/8)
    balloonBlue1.y = balloonBlue1.height

        balloonYellow1.x = (display.contentWidth/8)*3
    balloonYellow1.y = balloonBlue1.height

        balloonRed1.x = (display.contentWidth/8)*5
    balloonRed1.y = balloonBlue1.height

    balloonBlue2.x = (display.contentWidth/8)*7
    balloonBlue2.y = balloonBlue1.height

end

-- show()
function scene:show( event )

    local sceneGroup = self.view
    local phase = event.phase

    if ( phase == "will" ) then
        -- Code here runs when the scene is still off screen (but is about to come on screen)

    elseif ( phase == "did" ) then
        -- Code here runs when the scene is entirely on screen

    end
end

-- hide()
function scene:hide( event )

    local sceneGroup = self.view
    local phase = event.phase

    if ( phase == "will" ) then

    elseif ( phase == "did" ) then
        -- Code here runs immediately after the scene goes entirely off screen

    end
end

-- destroy()
function scene:destroy( event )

    local sceneGroup = self.view

    -- Code here runs prior to the removal of scene's view

end

-- -----------------------------------------------------------------------------------
-- Scene event function listeners
-- -----------------------------------------------------------------------------------
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
-- -----------------------------------------------------------------------------------

return scene
</code>```

答:
You need to add the  Balloon group (of which the balloons are children) to your sceneGroup.

In scene:destroy, make sure you remove any listeners and cancel any transitions on the things you want destroyed.  If you have, when the scene's view is destroyed, the Balloon group and all it's children will also be destroyed.

Body:
I want the balloons in this scene, which are DisplayObjects, to disappear when the scene ends. I have added them to the local sceneGroup = scene.view by passing this as the first argument to display.newImageRect() and assumed this would be enough for them to be removed as they are listed in the destroy.scene bit at the bottom. However when it transitions to the next scene they are still there.  Why are these DisplayObjects not being removed?

local composer = require( "composer" )

local scene = composer.newScene()

local Balloons

local positioninsheetOptions = 100

local sheetOptions =
{
    frames =
    {
        {
            x = 0,
            y = 0,
            width = 71,
            height = 100
        },
        {
            x = 0,
            y = positioninsheetOptions,
            width = 71,
            height = 100
        },
        {
            x = 0,
            y = positioninsheetOptions*2,
            width = 71,
            height = 100
        },
        {
            x = 0,
            y = positioninsheetOptions*3,
            width = 71,
            height = 100
        },
        {
            x = 0,
            y = positioninsheetOptions*4,
            width = 71,
            height = 100
        },
         {
            x = 0,
            y = positioninsheetOptions*5,
            width = 71,
            height = 100
        },
         {
            x = 0,
            y = positioninsheetOptions*6,
            width = 71,
            height = 100
        },
         {
            x = 0,
            y = positioninsheetOptions*7,
            width = 71,
            height = 100
        },
         {
            x = 0,
            y = positioninsheetOptions*8,
            width = 71,
            height = 100
        },

         {
            x = 0,
            y = positioninsheetOptions*9,
            width = 71,
            height = 100
        },

             {
            x = 0,
            y = positioninsheetOptions*10,
            width = 71,
            height = 100
        },

             {
            x = 0,
            y = positioninsheetOptions*11,
            width = 71,
            height = 100
        },

         },
        }
local objectSheet = graphics.newImageSheet( "gameObjects.png", sheetOptions )
Balloons = {}

-- -----------------------------------------------------------------------------------
-- Code outside of the scene event functions below will only be executed ONCE unless
-- the scene is removed entirely (not recycled) via "composer.removeScene()"
-- -----------------------------------------------------------------------------------

local function gotoGame()
    composer.gotoScene( "game" )
end

-- -----------------------------------------------------------------------------------
-- Scene event functions
-- -----------------------------------------------------------------------------------

-- create()
function scene:create( event )

    local sceneGroup = self.view
    -- Code here runs when the scene is first created but has not yet appeared on screen

    local background = display.newImageRect( sceneGroup, "background.png", 800, 1400 )
    background.x = display.contentCenterX
    background.y = display.contentCenterY

        local balloonBlue1 = display.newImageRect(sceneGroup, objectSheet, 6, 71, 100)
        local balloonYellow1 = display.newImageRect(sceneGroup, objectSheet, 8, 71, 100)
        local balloonRed1 = display.newImageRect(sceneGroup, objectSheet, 10, 71, 100)
        local balloonBlue2 = display.newImageRect(sceneGroup, objectSheet, 6, 71, 100)

        local Balloons = display.newGroup()

    Balloons:insert( balloonBlue1 )
    Balloons:insert( balloonYellow1 )
    Balloons:insert( balloonRed1 )
    Balloons:insert( balloonBlue2 )

    Balloons:addEventListener( "tap", gotoGame )

    balloonBlue1.x = (display.contentWidth/8)
    balloonBlue1.y = balloonBlue1.height

        balloonYellow1.x = (display.contentWidth/8)*3
    balloonYellow1.y = balloonBlue1.height

        balloonRed1.x = (display.contentWidth/8)*5
    balloonRed1.y = balloonBlue1.height

    balloonBlue2.x = (display.contentWidth/8)*7
    balloonBlue2.y = balloonBlue1.height

end

-- show()
function scene:show( event )

    local sceneGroup = self.view
    local phase = event.phase

    if ( phase == "will" ) then
        -- Code here runs when the scene is still off screen (but is about to come on screen)

    elseif ( phase == "did" ) then
        -- Code here runs when the scene is entirely on screen

    end
end

-- hide()
function scene:hide( event )

    local sceneGroup = self.view
    local phase = event.phase

    if ( phase == "will" ) then

    elseif ( phase == "did" ) then
        -- Code here runs immediately after the scene goes entirely off screen

    end
end

-- destroy()
function scene:destroy( event )

    local sceneGroup = self.view

    -- Code here runs prior to the removal of scene's view

end

-- -----------------------------------------------------------------------------------
-- Scene event function listeners
-- -----------------------------------------------------------------------------------
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
-- -----------------------------------------------------------------------------------

return scene


问:
Pandas manupulation: Non-distinct groups
I have a dataframe:

```<code>Time    c_1     c_2
 t1      x       1
 t2      x       2
 t3      y       1
 t4      y       2
 t5      1       x
 t6      2       x
 t7      1       y
 t8      2       y
</code>```

I need to form 2 columns without looping, such that:

new_1: Next earliest Time that c_1.value appear in c_2 (eg. For t1, new_1 = t5, because c_1 value is 'x', and the next time 'x' appears in c_2 is at t5)

new_2: Next earliest Time that c_2.value appear in c_1 (eg. For t1, new_1 = t5, because c_2 value is '1', and the next time '1' appears in c_1 is at t3)

So for the above input, the output should be:

```<code>Time    c_1     c_2    new_1     new_2
 t1      x       1       t5        t5
 t2      x       2       t5        t6
 t3      y       1       t7        t5
 t4      y       2       t7        t6
 t5      1       x       NaT       NaT
 t6      2       x       NaT       NaT
 t7      1       y       NaT       NaT
 t8      2       y       NaT       NaT
</code>```

How would you approach this?

答:
Here is a solution that uses apply() and a lambda function to select the correct data from the original DataFrame for each row.

```<code>import pandas as pd

data = {'Time': pd.date_range('1/1/2000', periods=16, freq='D'),
        'c_1': ['x', 'x', 'y', 'y', '1', '2', '1', '2']*2,
        'c_2': ['1', '2', '1', '2', 'x', 'x', 'y', 'y']*2 }

df = pd.DataFrame(data)
df['new_1'] = df.apply(lambda r: (df.Time[(df.Time>r.Time) & (df.c_2 == r.c_1)].head(1).reset_index(drop=True)), axis=1)
df['new_2'] = df.apply(lambda r: (df.Time[(df.Time>r.Time) & (df.c_1 == r.c_2)].head(1).reset_index(drop=True)), axis=1)
print(df)
</code>```

The output is:

```<code>         Time c_1 c_2      new_1      new_2
0  2000-01-01   x   1 2000-01-05 2000-01-05
1  2000-01-02   x   2 2000-01-05 2000-01-06
2  2000-01-03   y   1 2000-01-07 2000-01-05
3  2000-01-04   y   2 2000-01-07 2000-01-06
4  2000-01-05   1   x 2000-01-09 2000-01-09
5  2000-01-06   2   x 2000-01-10 2000-01-09
6  2000-01-07   1   y 2000-01-09 2000-01-11
7  2000-01-08   2   y 2000-01-10 2000-01-11
8  2000-01-09   x   1 2000-01-13 2000-01-13
9  2000-01-10   x   2 2000-01-13 2000-01-14
10 2000-01-11   y   1 2000-01-15 2000-01-13
11 2000-01-12   y   2 2000-01-15 2000-01-14
12 2000-01-13   1   x        NaT        NaT
13 2000-01-14   2   x        NaT        NaT
14 2000-01-15   1   y        NaT        NaT
15 2000-01-16   2   y        NaT        NaT
</code>```

The apply is done with axis=1 so it iterates one row at a time. The lambda function selects only rows of the dataframe that occur after the current row and that have the correct values in the columns. There may be multiple rows that match these conditions. The head(1) selects the first match and the reset_index(drop=True) ensures that each Series returned has the same index (0), so that apply() places them all off the return values into a single column.

Body:
I have a dataframe:

Time    c_1     c_2
 t1      x       1
 t2      x       2
 t3      y       1
 t4      y       2
 t5      1       x
 t6      2       x
 t7      1       y
 t8      2       y

I need to form 2 columns without looping, such that:

new_1: Next earliest Time that c_1.value appear in c_2 (eg. For t1, new_1 = t5, because c_1 value is 'x', and the next time 'x' appears in c_2 is at t5)

new_2: Next earliest Time that c_2.value appear in c_1 (eg. For t1, new_1 = t5, because c_2 value is '1', and the next time '1' appears in c_1 is at t3)

So for the above input, the output should be:

Time    c_1     c_2    new_1     new_2
 t1      x       1       t5        t5
 t2      x       2       t5        t6
 t3      y       1       t7        t5
 t4      y       2       t7        t6
 t5      1       x       NaT       NaT
 t6      2       x       NaT       NaT
 t7      1       y       NaT       NaT
 t8      2       y       NaT       NaT

How would you approach this?

Body:
Here is a solution that uses apply() and a lambda function to select the correct data from the original DataFrame for each row.

import pandas as pd

data = {'Time': pd.date_range('1/1/2000', periods=16, freq='D'),
        'c_1': ['x', 'x', 'y', 'y', '1', '2', '1', '2']*2,
        'c_2': ['1', '2', '1', '2', 'x', 'x', 'y', 'y']*2 }

df = pd.DataFrame(data)
df['new_1'] = df.apply(lambda r: (df.Time[(df.Time>r.Time) & (df.c_2 == r.c_1)].head(1).reset_index(drop=True)), axis=1)
df['new_2'] = df.apply(lambda r: (df.Time[(df.Time>r.Time) & (df.c_1 == r.c_2)].head(1).reset_index(drop=True)), axis=1)
print(df)

The output is:

         Time c_1 c_2      new_1      new_2
0  2000-01-01   x   1 2000-01-05 2000-01-05
1  2000-01-02   x   2 2000-01-05 2000-01-06
2  2000-01-03   y   1 2000-01-07 2000-01-05
3  2000-01-04   y   2 2000-01-07 2000-01-06
4  2000-01-05   1   x 2000-01-09 2000-01-09
5  2000-01-06   2   x 2000-01-10 2000-01-09
6  2000-01-07   1   y 2000-01-09 2000-01-11
7  2000-01-08   2   y 2000-01-10 2000-01-11
8  2000-01-09   x   1 2000-01-13 2000-01-13
9  2000-01-10   x   2 2000-01-13 2000-01-14
10 2000-01-11   y   1 2000-01-15 2000-01-13
11 2000-01-12   y   2 2000-01-15 2000-01-14
12 2000-01-13   1   x        NaT        NaT
13 2000-01-14   2   x        NaT        NaT
14 2000-01-15   1   y        NaT        NaT
15 2000-01-16   2   y        NaT        NaT

The apply is done with axis=1 so it iterates one row at a time. The lambda function selects only rows of the dataframe that occur after the current row and that have the correct values in the columns. There may be multiple rows that match these conditions. The head(1) selects the first match and the reset_index(drop=True) ensures that each Series returned has the same index (0), so that apply() places them all off the return values into a single column.


问:
Segmentation Fault with string array
I'm experiencing some problems with an array of strings that seem to be invading a reserved space of memory. The code is too large to post here, so I'll post the important part below:

```<code>int main (  ){

 int i = 0, j = 0, k = 0, count = 0, numLinhas = 0, l = 0;
 char string[100][100];
 char line [17];
 char str[4];
 char str1[5];
 char str2[4];
 char str3[4];

 FILE *p;
 p = fopen("text.txt", "r");
 while(fgets(line, sizeof line, p)!=NULL){
  printf("%s", line);
  strncpy(string[i], line, 17);
  i++;
  numLinhas++;
  }
  fclose(p);
  char *temp[numLinhas];
</code>```

After that it goes into a loop in which stores in string [i] the meaning of the statement contained in the file. The beginning of the for and three examples are shown below:

```<code>    for (i = 0; i<numLinhas; i++){
    sscanf( string[i], "%s %s %s %s" ,str1, str,str2, str3);
    if(str[0]=='0' && str[1] == '0' && str[2]!= 'd') {
    temp[i] = "NOP";
    count++;
    }
    if(str[0]=='0'&& str[1] == '6' && str[2]!= 'd') {
    sprintf(temp[i],"%s,%s" , "MVI B", str2);
    count = count+2;
    }

    if(str[0]=='0'&& str[1] == '7' && str[2]!= 'd') {
    temp[i] = "RLC";
    count++;
    }
</code>```

The error is casual - it does not always happen. And it usually occurs when there is a call to sprintf.
Ah yes! And below is the txt file I'm loading as an example:

```<code>0000 21a 11r 00r
0003 7Ea
0004 21a 12r 00r
0007 46a
0008 80a
0009 21a 13r 00r
000C 77a
000D 3Ea 01a
000F 3Da
0010 76a
0011 0Ad
0012 03d
0013 01d
</code>```

Just saw something new. here's the compile window i'm getting:

```<code>marcos@john:~/Desktop$ ./paraler
0000 21a 11r 00rValor de l: 16

Valor de l: 1
0003 7Ea
Valor de l: 9
0004 21a 12r 00rValor de l: 16

Valor de l: 1
0007 46a
Valor de l: 9
0008 80a
Valor de l: 9
0009 21a 13r 00rValor de l: 16

Valor de l: 1
000C 77a
Valor de l: 9
000D 3Ea 01a
Valor de l: 13
000F 3Da
Valor de l: 9
0010 76a
Valor de l: 9
0011 0Ad
Valor de l: 9
0012 03d
Valor de l: 9
0013 01d
Valor de l: 9
string:0000 21a 11r 00r
string:

string:0003 7Ea

string:0004 21a 12r 00r
string:

string:0007 46a

string:0008 80a

string:0009 21a 13r 00r
string:

string:000C 77a

string:000D 3Ea 01a

string:000F 3Da

string:0010 76a

string:0011 0Ad

string:0012 03d

string:0013 01d

Segmentation fault
</code>```

The strange thing is that I get some empty spaces of the string array... Does it have anything to do with the error?

答:
There are some issues I see immediately:

edit the first point might not apply to your environment, but you should keep it in mind

You are trying to create char *temp[numLinHas] from an integer whose value will be determined at run-time. This is permissible in C99, or may be provided via a compiler extension, but in older C standards, array sizes must be known at compile-time. Your code might really be doing this:

```<code>int numLinHas = 0;
char *temp[numLinHas];
</code>```

Another problem is that when you do sprintf, you are attempting to copy to something in temp without allocating memory for the pointer to store the string.

Title: Segmentation Fault with string array

Body:
I'm experiencing some problems with an array of strings that seem to be invading a reserved space of memory. The code is too large to post here, so I'll post the important part below:

int main (  ){

 int i = 0, j = 0, k = 0, count = 0, numLinhas = 0, l = 0;
 char string[100][100];
 char line [17];
 char str[4];
 char str1[5];
 char str2[4];
 char str3[4];

 FILE *p;
 p = fopen("text.txt", "r");
 while(fgets(line, sizeof line, p)!=NULL){
  printf("%s", line);
  strncpy(string[i], line, 17);
  i++;
  numLinhas++;
  }
  fclose(p);
  char *temp[numLinhas];

After that it goes into a loop in which stores in string [i] the meaning of the statement contained in the file. The beginning of the for and three examples are shown below:

    for (i = 0; i<numLinhas; i++){
    sscanf( string[i], "%s %s %s %s" ,str1, str,str2, str3);
    if(str[0]=='0' && str[1] == '0' && str[2]!= 'd') {
    temp[i] = "NOP";
    count++;
    }
    if(str[0]=='0'&& str[1] == '6' && str[2]!= 'd') {
    sprintf(temp[i],"%s,%s" , "MVI B", str2);
    count = count+2;
    }

    if(str[0]=='0'&& str[1] == '7' && str[2]!= 'd') {
    temp[i] = "RLC";
    count++;
    }

The error is casual - it does not always happen. And it usually occurs when there is a call to sprintf.
Ah yes! And below is the txt file I'm loading as an example:

0000 21a 11r 00r
0003 7Ea
0004 21a 12r 00r
0007 46a
0008 80a
0009 21a 13r 00r
000C 77a
000D 3Ea 01a
000F 3Da
0010 76a
0011 0Ad
0012 03d
0013 01d

Just saw something new. here's the compile window i'm getting:

marcos@john:~/Desktop$ ./paraler
0000 21a 11r 00rValor de l: 16

Valor de l: 1
0003 7Ea
Valor de l: 9
0004 21a 12r 00rValor de l: 16

Valor de l: 1
0007 46a
Valor de l: 9
0008 80a
Valor de l: 9
0009 21a 13r 00rValor de l: 16

Valor de l: 1
000C 77a
Valor de l: 9
000D 3Ea 01a
Valor de l: 13
000F 3Da
Valor de l: 9
0010 76a
Valor de l: 9
0011 0Ad
Valor de l: 9
0012 03d
Valor de l: 9
0013 01d
Valor de l: 9
string:0000 21a 11r 00r
string:

string:0003 7Ea

string:0004 21a 12r 00r
string:

string:0007 46a

string:0008 80a

string:0009 21a 13r 00r
string:

string:000C 77a

string:000D 3Ea 01a

string:000F 3Da

string:0010 76a

string:0011 0Ad

string:0012 03d

string:0013 01d

Segmentation fault

The strange thing is that I get some empty spaces of the string array... Does it have anything to do with the error?

Body:
There are some issues I see immediately:

edit the first point might not apply to your environment, but you should keep it in mind

You are trying to create char *temp[numLinHas] from an integer whose value will be determined at run-time. This is permissible in C99, or may be provided via a compiler extension, but in older C standards, array sizes must be known at compile-time. Your code might really be doing this:

int numLinHas = 0;
char *temp[numLinHas];

Another problem is that when you do sprintf, you are attempting to copy to something in temp without allocating memory for the pointer to store the string.


问:
Groovy Script error handling
We have the following groovy script. We want to add some error handling to it. Sometimes it can't find the URL api/xml. How can we fix it to handle not erroring out?</p>

```<code>def parameterName = "FRACTURE_NO";
def jenkinsUrl = System.getenv('JENKINS_URL');
def buildNumber = System.getenv('BUILD_NUMBER').toInteger();
def jobUrl = jenkinsUrl + "job/" + System.getenv('JOB_NAME');
def buildNumberUrl = jobUrl + "/" + buildNumber;
def myParameter = System.getenv(parameterName);

def projectXml = new XmlSlurper().parseText(new URL(jobUrl + "/api/xml").getText());
projectXml.build.each {
  def previousBuildNumber = it.number.text().toInteger();
  if(previousBuildNumber < buildNumber)
  {
    def previousBuildNumberUrl = jobUrl + "/" + previousBuildNumber;
    def jobXml = new XmlSlurper().parseText(new URL(previousBuildNumberUrl + "/api/xml").getText());
    if(jobXml.building.text() == "true")
    {
      jobXml.action.parameter.each {
        if(it.name.text() == parameterName) {
          if(it.value.text() == myParameter) {
            def url = new URL(previousBuildNumberUrl + "/stop?token=spark123");
            def connection = url.openConnection();
            connection.setRequestProperty("Authorization", "Basic " + "wscott:26accfcc2cf8a1f3503ac4a70483b4fe".getBytes("UTF-8").encodeBase64());
            connection.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
            connection.setRequestProperty( "Accept", "*/*" );
            connection.addRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            connection.setRequestMethod("POST");
            connection.connect();
            connection.content.text;
            println "Stopping " + previousBuildNumber;
          }
        }
      }
    }
  }
}
</code>```

答:
You can use a try/catch construct. The error is most likely a "FileNotFoundException", that is thrown when http response is 404 (not found). Other errors are likely, so I would be not too specific and catch "IOException", which I think covers all HTTP errors from that call:

```<code>try {
    String xmlContent = new URL(previousBuildNumberUrl + "/api/xml").getText()
} catch(IOException e) {
    // handle error...
}
</code>```

I think you got a downvote because there is much cruft in this question, that could be abstracted away. Please have a look at How to create a Minimal, Complete, and Verifiable example.

Edit: to answer question below, "IOException" should be enough, but you can use "Exception" instead to catch everything... although that's considered bad practice, because you end up also catching "programming errors" which by definition cannot be handled programmatically. But I have a suspicion that won't be a major concern here.

Title: Groovy Script error handling

Body:
We have the following groovy script. We want to add some error handling to it. Sometimes it can't find the URL api/xml. How can we fix it to handle not erroring out?

def parameterName = "FRACTURE_NO";
def jenkinsUrl = System.getenv('JENKINS_URL');
def buildNumber = System.getenv('BUILD_NUMBER').toInteger();
def jobUrl = jenkinsUrl + "job/" + System.getenv('JOB_NAME');
def buildNumberUrl = jobUrl + "/" + buildNumber;
def myParameter = System.getenv(parameterName);

def projectXml = new XmlSlurper().parseText(new URL(jobUrl + "/api/xml").getText());
projectXml.build.each {
  def previousBuildNumber = it.number.text().toInteger();
  if(previousBuildNumber < buildNumber)
  {
    def previousBuildNumberUrl = jobUrl + "/" + previousBuildNumber;
    def jobXml = new XmlSlurper().parseText(new URL(previousBuildNumberUrl + "/api/xml").getText());
    if(jobXml.building.text() == "true")
    {
      jobXml.action.parameter.each {
        if(it.name.text() == parameterName) {
          if(it.value.text() == myParameter) {
            def url = new URL(previousBuildNumberUrl + "/stop?token=spark123");
            def connection = url.openConnection();
            connection.setRequestProperty("Authorization", "Basic " + "wscott:26accfcc2cf8a1f3503ac4a70483b4fe".getBytes("UTF-8").encodeBase64());
            connection.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
            connection.setRequestProperty( "Accept", "*/*" );
            connection.addRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            connection.setRequestMethod("POST");
            connection.connect();
            connection.content.text;
            println "Stopping " + previousBuildNumber;
          }
        }
      }
    }
  }
}

Body:
You can use a try/catch construct. The error is most likely a "FileNotFoundException", that is thrown when http response is 404 (not found). Other errors are likely, so I would be not too specific and catch "IOException", which I think covers all HTTP errors from that call:

try {
    String xmlContent = new URL(previousBuildNumberUrl + "/api/xml").getText()
} catch(IOException e) {
    // handle error...
}

I think you got a downvote because there is much cruft in this question, that could be abstracted away. Please have a look at How to create a Minimal, Complete, and Verifiable example.

Edit: to answer question below, "IOException" should be enough, but you can use "Exception" instead to catch everything... although that's considered bad practice, because you end up also catching "programming errors" which by definition cannot be handled programmatically. But I have a suspicion that won't be a major concern here.


问:
Pointer getter to a reference
I have a class with a reference and want a getter that returns a pointer.

```<code>class X {
    std::string& text;
public:
    auto GetText() -> decltype(text) * { return &text); // doesn't work
    X(std::string& text): text(text) {}
};
</code>```

The easy way is to pass a pointer to this class. But if I pass a reference, can I get a pointer with a getter?

Edit: here is the error message

```<code>error: cannot declare pointer to 'std::__cxx11::string& {aka class std::__cxx11::basic_string<char>&}'
auto GetText() -> decltype(text) * { return &text);
                                 ^
</code>```

答:
I've made a  test program for my initial problem. The program has a class with a pointer and a getter that returns a reference and a second class with a reference and a getter that returns a pointer.

And it seems that -> std::remove_reference_t<decltype(text)> can be substituted with -> decltype(&text).

Feel free to comment.

```<code>// g++ main.cpp -o test_reference_pointer && strip -s test_reference_pointer && ./test_reference_pointer

#include <iostream>

// A class with a pointer and a getter that returns a reference.
class A {
    std::string *text;
public:
    std::string& GetText_old_way() { return *text; }
    auto GetText_pure_auto() { return *text; }
    auto GetText_pointer_arithmetic() -> decltype(*text) & { return *text; }
public:
    A(std::string *text): text(text) {}
};

// A class with a reference and a getter that returns a pointer.
class B {
    std::string& text;
public:
    std::string *GetText_old_way() { return &text; }
    auto GetText_pure_auto() { return &text; }
    auto GetText_pointer_arithmetic() -> decltype(&text) { return &text; }
    auto GetText_remove_reference() -> std::remove_reference_t<decltype(text)> * { return &text; }
public:
    B(std::string& text): text(text) {}
};

int main() {
    std::string text = "hello, world";

    {//TEST
        A a(&text);
        unsigned int i{0};

        std::cout << "-- Test 1:"<< std::endl;
        ++i; std::cout << i << ". " << a.GetText_old_way() << std::endl;
        ++i; std::cout << i << ". " << a.GetText_pointer_arithmetic() << std::endl;
        ++i; std::cout << i << ". " << a.GetText_pure_auto() << std::endl;
        std::cout << std::endl;
    }

    {//TEST
        B b(text);
        unsigned int i{0};

        std::cout << "-- Test 2:"<< std::endl;
        ++i; std::cout << i << ". " << *b.GetText_old_way() << std::endl;
        ++i; std::cout << i << ". " << *b.GetText_pointer_arithmetic() << std::endl;
        ++i; std::cout << i << ". " << *b.GetText_remove_reference() << std::endl;
        ++i; std::cout << i << ". " << *b.GetText_pure_auto() << std::endl;
        std::cout << std::endl;
    }

    return 0;
}
</code>```

Title: Pointer getter to a reference

Body:
I have a class with a reference and want a getter that returns a pointer.

class X {
    std::string& text;
public:
    auto GetText() -> decltype(text) * { return &text); // doesn't work
    X(std::string& text): text(text) {}
};

The easy way is to pass a pointer to this class. But if I pass a reference, can I get a pointer with a getter?

Edit: here is the error message

error: cannot declare pointer to 'std::__cxx11::string& {aka class std::__cxx11::basic_string<char>&}'
auto GetText() -> decltype(text) * { return &text);
                                 ^

Body:
I've made a  test program for my initial problem. The program has a class with a pointer and a getter that returns a reference and a second class with a reference and a getter that returns a pointer.

And it seems that -> std::remove_reference_t<decltype(text)> can be substituted with -> decltype(&text).

Feel free to comment.

// g++ main.cpp -o test_reference_pointer && strip -s test_reference_pointer && ./test_reference_pointer

#include <iostream>

// A class with a pointer and a getter that returns a reference.
class A {
    std::string *text;
public:
    std::string& GetText_old_way() { return *text; }
    auto GetText_pure_auto() { return *text; }
    auto GetText_pointer_arithmetic() -> decltype(*text) & { return *text; }
public:
    A(std::string *text): text(text) {}
};

// A class with a reference and a getter that returns a pointer.
class B {
    std::string& text;
public:
    std::string *GetText_old_way() { return &text; }
    auto GetText_pure_auto() { return &text; }
    auto GetText_pointer_arithmetic() -> decltype(&text) { return &text; }
    auto GetText_remove_reference() -> std::remove_reference_t<decltype(text)> * { return &text; }
public:
    B(std::string& text): text(text) {}
};

int main() {
    std::string text = "hello, world";

    {//TEST
        A a(&text);
        unsigned int i{0};

        std::cout << "-- Test 1:"<< std::endl;
        ++i; std::cout << i << ". " << a.GetText_old_way() << std::endl;
        ++i; std::cout << i << ". " << a.GetText_pointer_arithmetic() << std::endl;
        ++i; std::cout << i << ". " << a.GetText_pure_auto() << std::endl;
        std::cout << std::endl;
    }

    {//TEST
        B b(text);
        unsigned int i{0};

        std::cout << "-- Test 2:"<< std::endl;
        ++i; std::cout << i << ". " << *b.GetText_old_way() << std::endl;
        ++i; std::cout << i << ". " << *b.GetText_pointer_arithmetic() << std::endl;
        ++i; std::cout << i << ". " << *b.GetText_remove_reference() << std::endl;
        ++i; std::cout << i << ". " << *b.GetText_pure_auto() << std::endl;
        std::cout << std::endl;
    }

    return 0;
}


问:
Asynctask parallel execution
At application launch time I am making network call (resttemplate Get call) to fetch data.

Scenario is something like this,

1)Parent call which returns list of tokens(Id's)

2)Once I got list of tokens(Id's),I iterate through it make network call for   each token(Id) to get Data.

What I have done so for:

1)I have used Intent service to make parent network call to get list tokens(ID's).

2)Once I got list token(Id's) I started my AsyncTask executeOnExecutor,Passing list of tokens(ID's) to asynctask through constructor and starting AsyncTask executor.
Something like this,

```<code>MyAsyncExecutorTask executorTask = new MyAsyncExecutorTask(List<Integer> of tokens);
executorTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,(Void[]) null);
</code>```

And In MyAsyncExecutorTask this is what I am doing.

```<code> protected Void doInBackground(Void...params) {

    //Settimg max priority
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

    for (int i = 0; i < scheduleList.size(); i++) {
       ScheduleImpl scheduleImpl = new ScheduleImpl();
        //Making network call to get data using token
        scheduleImpl.getData(scheduleList(i));
    }

 }
</code>```

Its working as it should be.

My doubts or Questions are:

1)Am I using Async executeOnExecuter() in right way(I want to make parallel  network calls).I don't see any huge performance improvement after switching from AsyncTask execute() to Async executeOnExecuter().

2)How to check how many number worker threads running.

答:
You can make it like this:

AsyncTaskGetTokens.java

```<code>public class AsyncTaskGetTokens extends AsyncTask<Void,Integer, List<Integer>> {

    private ProgressDialog pd;
    private Context context;
    private String dataURL;

    public AsyncTaskGetTokens (Context context, Integer token)
    {
        this.act = act;
        this.token = token;
    }

    protected void onPreExecute()
    {
        this.pd = ProgressDialog.show(context, "", "");
    }

    protected Integer doInBackground(Void... arg0) {
        List<Integer> tokenList = new List<Integer>();
        //get token list from URL here
        return tokenList;
    }

    protected void onPostExecute(List<Integer> tokenList)
    {
        this.pd.dismiss();
        AsyncTaskGetData.tokensDownloading = new List<AsyncTaskGetData>();
        foreach(Integer token : tokenList)
        {
            AsyncTaskGetData.tokensDownloading.add(new AsyncTaskGetData(context, token); // here you create a list with all the tokens that will be downloaded
        }
        foreach(AsyncTaskGetData asynctask : AsyncTaskGetData.tokensDownloading)
        {
            asynctask.execute(); // here you will start downloading the data from each token
        }
    }

}
</code>```

AsyncTaskGetData.java

```<code>public class AsyncTaskGetData extends AsyncTask<Void,Integer, Data> {

    public static List<AsyncTaskGetData> tokensDownloading;

    private ProgressDialog pd;
    private Context context;
    private Integer token;

    public AsyncTaskGetData (Context context, Integer token)
    {
        this.context = context;
        this.token = token;
    }

    protected void onPreExecute()
    {
        this.pd = ProgressDialog.show(context, "", "");
    }

    protected Data doInBackground(Void... arg0) {
        Data data = getDataFromURL(token);
        return data;
    }

    protected void onPostExecute(Data data)
    {
        //show data here
        this.pd.dismiss();
    }

}
</code>```

Title: Asynctask parallel execution

Body:
At application launch time I am making network call (resttemplate Get call) to fetch data.

Scenario is something like this,

1)Parent call which returns list of tokens(Id's)

2)Once I got list of tokens(Id's),I iterate through it make network call for   each token(Id) to get Data.

What I have done so for:

1)I have used Intent service to make parent network call to get list tokens(ID's).

2)Once I got list token(Id's) I started my AsyncTask executeOnExecutor,Passing list of tokens(ID's) to asynctask through constructor and starting AsyncTask executor.
Something like this,

MyAsyncExecutorTask executorTask = new MyAsyncExecutorTask(List<Integer> of tokens);
executorTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,(Void[]) null);

And In MyAsyncExecutorTask this is what I am doing.

 protected Void doInBackground(Void...params) {

    //Settimg max priority
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

    for (int i = 0; i < scheduleList.size(); i++) {
       ScheduleImpl scheduleImpl = new ScheduleImpl();
        //Making network call to get data using token
        scheduleImpl.getData(scheduleList(i));
    }

 }

Its working as it should be.

My doubts or Questions are:

1)Am I using Async executeOnExecuter() in right way(I want to make parallel  network calls).I don't see any huge performance improvement after switching from AsyncTask execute() to Async executeOnExecuter().

2)How to check how many number worker threads running.

Body:
You can make it like this:

AsyncTaskGetTokens.java

public class AsyncTaskGetTokens extends AsyncTask<Void,Integer, List<Integer>> {

    private ProgressDialog pd;
    private Context context;
    private String dataURL;

    public AsyncTaskGetTokens (Context context, Integer token)
    {
        this.act = act;
        this.token = token;
    }

    protected void onPreExecute()
    {
        this.pd = ProgressDialog.show(context, "", "");
    }

    protected Integer doInBackground(Void... arg0) {
        List<Integer> tokenList = new List<Integer>();
        //get token list from URL here
        return tokenList;
    }

    protected void onPostExecute(List<Integer> tokenList)
    {
        this.pd.dismiss();
        AsyncTaskGetData.tokensDownloading = new List<AsyncTaskGetData>();
        foreach(Integer token : tokenList)
        {
            AsyncTaskGetData.tokensDownloading.add(new AsyncTaskGetData(context, token); // here you create a list with all the tokens that will be downloaded
        }
        foreach(AsyncTaskGetData asynctask : AsyncTaskGetData.tokensDownloading)
        {
            asynctask.execute(); // here you will start downloading the data from each token
        }
    }

}

AsyncTaskGetData.java

public class AsyncTaskGetData extends AsyncTask<Void,Integer, Data> {

    public static List<AsyncTaskGetData> tokensDownloading;

    private ProgressDialog pd;
    private Context context;
    private Integer token;

    public AsyncTaskGetData (Context context, Integer token)
    {
        this.context = context;
        this.token = token;
    }

    protected void onPreExecute()
    {
        this.pd = ProgressDialog.show(context, "", "");
    }

    protected Data doInBackground(Void... arg0) {
        Data data = getDataFromURL(token);
        return data;
    }

    protected void onPostExecute(Data data)
    {
        //show data here
        this.pd.dismiss();
    }

}


问:
Graph not showing in Python plot
I have the following code in Python for plotting a simple graph:

```<code>import numpy as np
import matplotlib.pyplot as plt

for i in (2, 3, 4, 5, 6):
    plt.plot(i, 2*i, linewidth = 3, label='$n = {i}$'.format(i=i))
plt.legend(loc='upper left')
plt.show()
</code>```

When I execute it shows the window with the legend, but not the graph line. If I use plt.scatter() instead it plots the points normally. I was reading that it maybe an issue of the backend, but my matlibrc folder is empty and I don't have any config file there. Anyone with similar experience? Any ideas of the problem?

答: The problem is that each 'line' only comprises one point at (i,2i). Using a line only, this does not result in anything. One can plot the point for example by adding the option marker='o' to the plt.plot(...) command.

Title: Graph not showing in Python plot

Body:
I have the following code in Python for plotting a simple graph:

import numpy as np
import matplotlib.pyplot as plt

for i in (2, 3, 4, 5, 6):
    plt.plot(i, 2*i, linewidth = 3, label='$n = {i}$'.format(i=i))
plt.legend(loc='upper left')
plt.show()

When I execute it shows the window with the legend, but not the graph line. If I use plt.scatter() instead it plots the points normally. I was reading that it maybe an issue of the backend, but my matlibrc folder is empty and I don't have any config file there. Anyone with similar experience? Any ideas of the problem?