问:
Async Await Equivalent
When I run this code everything works fine:

```<code>public async void InvokePlugin(MyObject xTask)
{
    try
    {
        var hndlr = new TimeoutHandler(RunTask);
        var asyncResult = hndlr.BeginInvoke(xTask, null, new object());
        if (!asyncResult.AsyncWaitHandle.WaitOne(xTask.Timeout, false))
        {
            throw new TimeoutException("Plugin didn't complete processing in a timely manner.");
        }
        hndlr.EndInvoke(asyncResult);
    }
    catch (Exception ex)
    {
        //Handle Exceptions
    }
}

private delegate void TimeoutHandler(MyObject xTask);
</code>```

I want to update this code to use Async/Await.  I tried doing it like this:

```<code>public async void InvokePlugin(MyObject xTask)
{
    try
    {
        var runTask = Task.Run(() => { RunTask(xTask); });
        if (await Task.WhenAny(runTask, Task.Delay(xTask.Timeout)) == runTask)
        {
            // Task completed within timeout.
            // Consider that the task may have faulted or been canceled.
            // We re-await the task so that any exceptions/cancellation is rethrown.
            await runTask;
        }
        else
        {
            throw new TimeoutException("Plugin didn't complete processing in a timely manner.");
        }
    }
    catch (Exception ex)
    {
        //Handle Exceptions
    }
}
</code>```

...but it's not working.  Clearly I'm doing somethign wring.  It does call the RunTask Method and executes the first 2 lines fine but then it just ends and I can't seem to catch the exception in either the TaskRun method or code above.  All I see in the Output windows is "Program has exited with code 0 (0x0)."

If the experts out there can either point me to what I'm doing wrong or give me suggestions as to how I can catch the exception and handle it I would be very grateful.

Also if you feel I missed any important details please ask and I will update my question.

Usually I'd say if it works don't fix it but in this case I'm trying to rearchitect a bit to allow for some enhancements so here I am.

答:
Change async void to async Task. See my article on async best practices for more information.

After you do this, consume it asynchronously:

await the task, allowing async to grow.

async and await will naturally grow upward through your code base, until they reach Main, which cannot be async.

In your Main method, call GetAwaiter().GetResult() on the "top" task.

Blocking on asynchronous code is generally not a good idea, but blocking on a single task in a Console app's Main method is an exception to that rule.

Title: Async Await Equivalent

Body:
When I run this code everything works fine:

public async void InvokePlugin(MyObject xTask)
{
    try
    {
        var hndlr = new TimeoutHandler(RunTask);
        var asyncResult = hndlr.BeginInvoke(xTask, null, new object());
        if (!asyncResult.AsyncWaitHandle.WaitOne(xTask.Timeout, false))
        {
            throw new TimeoutException("Plugin didn't complete processing in a timely manner.");
        }
        hndlr.EndInvoke(asyncResult);
    }
    catch (Exception ex)
    {
        //Handle Exceptions
    }
}

private delegate void TimeoutHandler(MyObject xTask);

I want to update this code to use Async/Await.  I tried doing it like this:

public async void InvokePlugin(MyObject xTask)
{
    try
    {
        var runTask = Task.Run(() => { RunTask(xTask); });
        if (await Task.WhenAny(runTask, Task.Delay(xTask.Timeout)) == runTask)
        {
            // Task completed within timeout.
            // Consider that the task may have faulted or been canceled.
            // We re-await the task so that any exceptions/cancellation is rethrown.
            await runTask;
        }
        else
        {
            throw new TimeoutException("Plugin didn't complete processing in a timely manner.");
        }
    }
    catch (Exception ex)
    {
        //Handle Exceptions
    }
}

...but it's not working.  Clearly I'm doing somethign wring.  It does call the RunTask Method and executes the first 2 lines fine but then it just ends and I can't seem to catch the exception in either the TaskRun method or code above.  All I see in the Output windows is "Program has exited with code 0 (0x0)."

If the experts out there can either point me to what I'm doing wrong or give me suggestions as to how I can catch the exception and handle it I would be very grateful.

Also if you feel I missed any important details please ask and I will update my question.

Usually I'd say if it works don't fix it but in this case I'm trying to rearchitect a bit to allow for some enhancements so here I am.


来源: stackexchange

问:
My scrip works fine in java class but same script fails when I use testng. It just opens the browser and fails my script
Please Find the below code: I have performed the following steps, but didn't worked.
Please Help:

```<code>public class ForSe_TestCases
public WebDriver driver;

@BeforeTest
public void setup ()
{
System.setProperty("webdriver.chrome.driver", "path");
WebDriver driver =new ChromeDriver();
driver.manage().deleteAllCookies();
}

@Test(priority = 0)
public void Validlogin_IO () throws InterruptedException {
driver.navigate().to("http://**URL**");
driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("Pass12345");
driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
System.out.println("Login button pressed");
}
</code>```

What can be the issue with TestNG ?

答:
Update to Chrome driver 2.28, Google Chrome to 57.x and Selenium to 3.x.x  You also have to set the path of the Chrome driver before you open the browser.

```<code>package demo;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestAnyURL_TestNG
{

    WebDriver driver;

    @BeforeTest
    public void setup ()
    {
    System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    options.addArguments("start-maximized");
    options.addArguments("--js-flags=--expose-gc");
    options.addArguments("--enable-precise-memory-info");
    options.addArguments("--disable-popup-blocking");
    options.addArguments("--disable-default-apps");
    options.addArguments("test-type=browser");
    options.addArguments("disable-infobars");
    driver = new ChromeDriver(options);
    driver.manage().deleteAllCookies();
    }

    @Test(priority = 0)
    public void Validlogin_IO () throws InterruptedException
    {
    driver.navigate().to("http://google.com"); //ForSe test environment URL
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com"); //this is official email
    driver.findElement(By.xpath("//*[@id='password']")).sendKeys("Pass12345"); //this is password
    driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click(); //click on submit button to login
    System.out.println("Login button pressed");     }       //This code is to add new case

    @Test (priority = 1)
    public void AddCase() throws InterruptedException
    {
    WebElement element = driver.findElement(By.partialLinkText("Add Case")); //To find 'Add Case' button on dashboard
    Actions action = new Actions (driver);      action.moveToElement(element); //Move mouse and hover to 'Add Case' button
    action.click().build().perform(); //Click on 'Add Case' button
    driver.findElement(By.id("name")).sendKeys("Perak Murder Case -53311");//Provide Case Name
    driver.findElement(By.id("fileupload")).sendKeys("C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\FisheyeImages\\IMG_1187.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\FisheyeImages\\IMG_1188.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\FisheyeImages\\IMG_1189.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\Fisheye Images\\IMG_1190.JPG");  //Upload files
    driver.findElement(By.id("fileupload1")).sendKeys("C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\EvidenceImages\\_DSC0970.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSI>Images\\EvidenceImages\\_DSC0971.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\Evidence Images\\_DSC0972.JPG");
    Thread.sleep(6000);         //wait for files to load
    driver.findElement(By.id("btnSubmit")).click();//click on submit button
   }
}
</code>```

Check this code. This code successfully opens the google.co.in

Execute this file "Run As TestNG Test"

Let me know if this helps you.

ContentLicense: CC BY-SA 3.0

Body:
Please Find the below code: I have performed the following steps, but didn't worked.
Please Help:

public class ForSe_TestCases
public WebDriver driver;

@BeforeTest
public void setup ()
{
System.setProperty("webdriver.chrome.driver", "path");
WebDriver driver =new ChromeDriver();
driver.manage().deleteAllCookies();
}

@Test(priority = 0)
public void Validlogin_IO () throws InterruptedException {
driver.navigate().to("http://**URL**");
driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com");
driver.findElement(By.xpath("//*[@id='password']")).sendKeys("Pass12345");
driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
System.out.println("Login button pressed");
}

What can be the issue with TestNG ?

Body:
Update to Chrome driver 2.28, Google Chrome to 57.x and Selenium to 3.x.x  You also have to set the path of the Chrome driver before you open the browser.

package demo;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestAnyURL_TestNG
{

    WebDriver driver;

    @BeforeTest
    public void setup ()
    {
    System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    options.addArguments("start-maximized");
    options.addArguments("--js-flags=--expose-gc");
    options.addArguments("--enable-precise-memory-info");
    options.addArguments("--disable-popup-blocking");
    options.addArguments("--disable-default-apps");
    options.addArguments("test-type=browser");
    options.addArguments("disable-infobars");
    driver = new ChromeDriver(options);
    driver.manage().deleteAllCookies();
    }

    @Test(priority = 0)
    public void Validlogin_IO () throws InterruptedException
    {
    driver.navigate().to("http://google.com"); //ForSe test environment URL
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("tengku.forse@gmail.com"); //this is official email
    driver.findElement(By.xpath("//*[@id='password']")).sendKeys("Pass12345"); //this is password
    driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click(); //click on submit button to login
    System.out.println("Login button pressed");     }       //This code is to add new case

    @Test (priority = 1)
    public void AddCase() throws InterruptedException
    {
    WebElement element = driver.findElement(By.partialLinkText("Add Case")); //To find 'Add Case' button on dashboard
    Actions action = new Actions (driver);      action.moveToElement(element); //Move mouse and hover to 'Add Case' button
    action.click().build().perform(); //Click on 'Add Case' button
    driver.findElement(By.id("name")).sendKeys("Perak Murder Case -53311");//Provide Case Name
    driver.findElement(By.id("fileupload")).sendKeys("C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\FisheyeImages\\IMG_1187.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\FisheyeImages\\IMG_1188.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\FisheyeImages\\IMG_1189.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\Fisheye Images\\IMG_1190.JPG");  //Upload files
    driver.findElement(By.id("fileupload1")).sendKeys("C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\EvidenceImages\\_DSC0970.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSI>Images\\EvidenceImages\\_DSC0971.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\Evidence Images\\_DSC0972.JPG");
    Thread.sleep(6000);         //wait for files to load
    driver.findElement(By.id("btnSubmit")).click();//click on submit button
   }
}

Check this code. This code successfully opens the google.co.in

Execute this file "Run As TestNG Test"

Let me know if this helps you.


问:
c++ win32 console app adding a "choose file" dialog box using windows api
I am trying to add a choose file dialog box to my project which now can only take the filename input by the user.

I did some search and it seems windows API with GetOpenFileName function is the easiest way for me to do that. However, when I copy&paste the example code whether from MSDN or other websites, I got some build errors.

I am using visual studio 2017. And the example code I used is from http://www.cplusplus.com/forum/windows/169960/:

```<code>#include <iostream>

#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>

int main()
{
  char filename[ MAX_PATH ];

  OPENFILENAME ofn;
    ZeroMemory( &filename, sizeof( filename ) );
    ZeroMemory( &ofn,      sizeof( ofn ) );
    ofn.lStructSize  = sizeof( ofn );
    ofn.hwndOwner    = NULL;  // If you have a window to center over, put its HANDLE here
    ofn.lpstrFilter  = "Text Files\0*.txt\0Any File\0*.*\0";
    ofn.lpstrFile    = filename;
    ofn.nMaxFile     = MAX_PATH;
    ofn.lpstrTitle   = "Select a File, yo!";
    ofn.Flags        = OFN_DONTADDTORECENT | OFN_FILEMUSTEXIST;

  if (GetOpenFileNameA( &ofn ))
  {
    std::cout << "You chose the file \"" << filename << "\"\n";
  }
  else
  {
    // All this stuff below is to tell you exactly how you messed up above.
    // Once you've got that fixed, you can often (not always!) reduce it to a 'user cancelled' assumption.
    switch (CommDlgExtendedError())
    {
      case CDERR_DIALOGFAILURE   : std::cout << "CDERR_DIALOGFAILURE\n";   break;
      case CDERR_FINDRESFAILURE  : std::cout << "CDERR_FINDRESFAILURE\n";  break;
      case CDERR_INITIALIZATION  : std::cout << "CDERR_INITIALIZATION\n";  break;
      case CDERR_LOADRESFAILURE  : std::cout << "CDERR_LOADRESFAILURE\n";  break;
      case CDERR_LOADSTRFAILURE  : std::cout << "CDERR_LOADSTRFAILURE\n";  break;
      case CDERR_LOCKRESFAILURE  : std::cout << "CDERR_LOCKRESFAILURE\n";  break;
      case CDERR_MEMALLOCFAILURE : std::cout << "CDERR_MEMALLOCFAILURE\n"; break;
      case CDERR_MEMLOCKFAILURE  : std::cout << "CDERR_MEMLOCKFAILURE\n";  break;
      case CDERR_NOHINSTANCE     : std::cout << "CDERR_NOHINSTANCE\n";     break;
      case CDERR_NOHOOK          : std::cout << "CDERR_NOHOOK\n";          break;
      case CDERR_NOTEMPLATE      : std::cout << "CDERR_NOTEMPLATE\n";      break;
      case CDERR_STRUCTSIZE      : std::cout << "CDERR_STRUCTSIZE\n";      break;
      case FNERR_BUFFERTOOSMALL  : std::cout << "FNERR_BUFFERTOOSMALL\n";  break;
      case FNERR_INVALIDFILENAME : std::cout << "FNERR_INVALIDFILENAME\n"; break;
      case FNERR_SUBCLASSFAILURE : std::cout << "FNERR_SUBCLASSFAILURE\n"; break;
      default                    : std::cout << "You cancelled.\n";
    }
  }
}
</code>```

When I copy&paste to vs, it shows the following:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   C2440   '=': cannot convert from 'char [260]' to 'LPWSTR'   ConsoleApplication1 c:\users\xfan0\documents\visual studio 2017\projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp    18
Severity    Code    Description Project File    Line    Suppression State
Error   C2440   '=': cannot convert from 'const char [19]' to 'LPCWSTR' ConsoleApplication1 c:\users\xfan0\documents\visual studio 2017\projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp    20
Severity    Code    Description Project File    Line    Suppression State
Error   C2664   'BOOL GetOpenFileNameA(LPOPENFILENAMEA)': cannot convert argument 1 from 'OPENFILENAME *' to 'LPOPENFILENAMEA'  ConsoleApplication1 c:\users\xfan0\documents\visual studio 2017\projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp    23

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0167   argument of type "OPENFILENAME *" is incompatible with parameter of type "LPOPENFILENAMEA"  ConsoleApplication1 c:\Users\XFAN0\Documents\Visual Studio 2017\Projects\ConsoleApplication1\ConsoleApplication1\ConsoleApplication1.cpp    23
</code>```

Tried to search for that but had not found my luck :(

答:
The method Microsoft normally advocates is to use their "generic text" macros, so your string literals would look like this:

```<code>ofn.lpstrFilter = _T("Text Files\0*.txt\0Any File\0*.*\0");
ofn.lpstrTitle = _T("Select a File, yo!");
</code>```

This way, you can build for narrow or wide character strings (the latter by defining UNICODE and _UNICODE). The _T will map to nothing for a narrow-character build, and to a L for a wide-character build, so you automatically get the right kind of string for the way you're building.

To use this, you include <tchar.h>.

For example:

```<code>#include <iostream>
#include <tchar.h>

#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>

int main()
{
  char filename[ MAX_PATH ];

  OPENFILENAME ofn;
    ZeroMemory( &filename, sizeof( filename ) );
    ZeroMemory( &ofn,      sizeof( ofn ) );
    ofn.lStructSize  = sizeof( ofn );
    ofn.hwndOwner    = NULL;  // If you have a window to center over, put its HANDLE here
    ofn.lpstrFilter  = _T("Text Files\0*.txt\0Any File\0*.*\0");
    ofn.lpstrFile    = filename;
    ofn.nMaxFile     = MAX_PATH;
    ofn.lpstrTitle   = _T("Select a File, yo!");
    ofn.Flags        = OFN_DONTADDTORECENT | OFN_FILEMUSTEXIST;

  if (GetOpenFileName( &ofn ))
  {
    std::cout << "You chose the file \"" << filename << "\"\n";
  }
  else
  {
    // All this stuff below is to tell you exactly how you messed up above.
    // Once you've got that fixed, you can often (not always!) reduce it to a 'user cancelled' assumption.
    switch (CommDlgExtendedError())
    {
      case CDERR_DIALOGFAILURE   : std::cout << "CDERR_DIALOGFAILURE\n";   break;
      case CDERR_FINDRESFAILURE  : std::cout << "CDERR_FINDRESFAILURE\n";  break;
      case CDERR_INITIALIZATION  : std::cout << "CDERR_INITIALIZATION\n";  break;
      case CDERR_LOADRESFAILURE  : std::cout << "CDERR_LOADRESFAILURE\n";  break;
      case CDERR_LOADSTRFAILURE  : std::cout << "CDERR_LOADSTRFAILURE\n";  break;
      case CDERR_LOCKRESFAILURE  : std::cout << "CDERR_LOCKRESFAILURE\n";  break;
      case CDERR_MEMALLOCFAILURE : std::cout << "CDERR_MEMALLOCFAILURE\n"; break;
      case CDERR_MEMLOCKFAILURE  : std::cout << "CDERR_MEMLOCKFAILURE\n";  break;
      case CDERR_NOHINSTANCE     : std::cout << "CDERR_NOHINSTANCE\n";     break;
      case CDERR_NOHOOK          : std::cout << "CDERR_NOHOOK\n";          break;
      case CDERR_NOTEMPLATE      : std::cout << "CDERR_NOTEMPLATE\n";      break;
      case CDERR_STRUCTSIZE      : std::cout << "CDERR_STRUCTSIZE\n";      break;
      case FNERR_BUFFERTOOSMALL  : std::cout << "FNERR_BUFFERTOOSMALL\n";  break;
      case FNERR_INVALIDFILENAME : std::cout << "FNERR_INVALIDFILENAME\n"; break;
      case FNERR_SUBCLASSFAILURE : std::cout << "FNERR_SUBCLASSFAILURE\n"; break;
      default                    : std::cout << "You cancelled.\n";
    }
  }
}
</code>```

To get a "save" filename instead, just change the GetOpenFilename to GetSaveFilename. There are a few differences in the flags you're likely to pass in the OPENFILENAME though--for example, it's pretty common to pass OFN_FILEMUSTEXIST when you're opening a file, but you almost never want to when you're saving a file.

Body:
I am trying to add a choose file dialog box to my project which now can only take the filename input by the user.

I did some search and it seems windows API with GetOpenFileName function is the easiest way for me to do that. However, when I copy&paste the example code whether from MSDN or other websites, I got some build errors.

I am using visual studio 2017. And the example code I used is from http://www.cplusplus.com/forum/windows/169960/:

#include <iostream>

#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>

int main()
{
  char filename[ MAX_PATH ];

  OPENFILENAME ofn;
    ZeroMemory( &filename, sizeof( filename ) );
    ZeroMemory( &ofn,      sizeof( ofn ) );
    ofn.lStructSize  = sizeof( ofn );
    ofn.hwndOwner    = NULL;  // If you have a window to center over, put its HANDLE here
    ofn.lpstrFilter  = "Text Files\0*.txt\0Any File\0*.*\0";
    ofn.lpstrFile    = filename;
    ofn.nMaxFile     = MAX_PATH;
    ofn.lpstrTitle   = "Select a File, yo!";
    ofn.Flags        = OFN_DONTADDTORECENT | OFN_FILEMUSTEXIST;

  if (GetOpenFileNameA( &ofn ))
  {
    std::cout << "You chose the file \"" << filename << "\"\n";
  }
  else
  {
    // All this stuff below is to tell you exactly how you messed up above.
    // Once you've got that fixed, you can often (not always!) reduce it to a 'user cancelled' assumption.
    switch (CommDlgExtendedError())
    {
      case CDERR_DIALOGFAILURE   : std::cout << "CDERR_DIALOGFAILURE\n";   break;
      case CDERR_FINDRESFAILURE  : std::cout << "CDERR_FINDRESFAILURE\n";  break;
      case CDERR_INITIALIZATION  : std::cout << "CDERR_INITIALIZATION\n";  break;
      case CDERR_LOADRESFAILURE  : std::cout << "CDERR_LOADRESFAILURE\n";  break;
      case CDERR_LOADSTRFAILURE  : std::cout << "CDERR_LOADSTRFAILURE\n";  break;
      case CDERR_LOCKRESFAILURE  : std::cout << "CDERR_LOCKRESFAILURE\n";  break;
      case CDERR_MEMALLOCFAILURE : std::cout << "CDERR_MEMALLOCFAILURE\n"; break;
      case CDERR_MEMLOCKFAILURE  : std::cout << "CDERR_MEMLOCKFAILURE\n";  break;
      case CDERR_NOHINSTANCE     : std::cout << "CDERR_NOHINSTANCE\n";     break;
      case CDERR_NOHOOK          : std::cout << "CDERR_NOHOOK\n";          break;
      case CDERR_NOTEMPLATE      : std::cout << "CDERR_NOTEMPLATE\n";      break;
      case CDERR_STRUCTSIZE      : std::cout << "CDERR_STRUCTSIZE\n";      break;
      case FNERR_BUFFERTOOSMALL  : std::cout << "FNERR_BUFFERTOOSMALL\n";  break;
      case FNERR_INVALIDFILENAME : std::cout << "FNERR_INVALIDFILENAME\n"; break;
      case FNERR_SUBCLASSFAILURE : std::cout << "FNERR_SUBCLASSFAILURE\n"; break;
      default                    : std::cout << "You cancelled.\n";
    }
  }
}

When I copy&paste to vs, it shows the following:

Severity    Code    Description Project File    Line    Suppression State
Error   C2440   '=': cannot convert from 'char [260]' to 'LPWSTR'   ConsoleApplication1 c:\users\xfan0\documents\visual studio 2017\projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp    18
Severity    Code    Description Project File    Line    Suppression State
Error   C2440   '=': cannot convert from 'const char [19]' to 'LPCWSTR' ConsoleApplication1 c:\users\xfan0\documents\visual studio 2017\projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp    20
Severity    Code    Description Project File    Line    Suppression State
Error   C2664   'BOOL GetOpenFileNameA(LPOPENFILENAMEA)': cannot convert argument 1 from 'OPENFILENAME *' to 'LPOPENFILENAMEA'  ConsoleApplication1 c:\users\xfan0\documents\visual studio 2017\projects\consoleapplication1\consoleapplication1\consoleapplication1.cpp    23

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0167   argument of type "OPENFILENAME *" is incompatible with parameter of type "LPOPENFILENAMEA"  ConsoleApplication1 c:\Users\XFAN0\Documents\Visual Studio 2017\Projects\ConsoleApplication1\ConsoleApplication1\ConsoleApplication1.cpp    23

Tried to search for that but had not found my luck :(

Body:
The method Microsoft normally advocates is to use their "generic text" macros, so your string literals would look like this:

ofn.lpstrFilter = _T("Text Files\0*.txt\0Any File\0*.*\0");
ofn.lpstrTitle = _T("Select a File, yo!");

This way, you can build for narrow or wide character strings (the latter by defining UNICODE and _UNICODE). The _T will map to nothing for a narrow-character build, and to a L for a wide-character build, so you automatically get the right kind of string for the way you're building.

To use this, you include <tchar.h>.

For example:

#include <iostream>
#include <tchar.h>

#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>

int main()
{
  char filename[ MAX_PATH ];

  OPENFILENAME ofn;
    ZeroMemory( &filename, sizeof( filename ) );
    ZeroMemory( &ofn,      sizeof( ofn ) );
    ofn.lStructSize  = sizeof( ofn );
    ofn.hwndOwner    = NULL;  // If you have a window to center over, put its HANDLE here
    ofn.lpstrFilter  = _T("Text Files\0*.txt\0Any File\0*.*\0");
    ofn.lpstrFile    = filename;
    ofn.nMaxFile     = MAX_PATH;
    ofn.lpstrTitle   = _T("Select a File, yo!");
    ofn.Flags        = OFN_DONTADDTORECENT | OFN_FILEMUSTEXIST;

  if (GetOpenFileName( &ofn ))
  {
    std::cout << "You chose the file \"" << filename << "\"\n";
  }
  else
  {
    // All this stuff below is to tell you exactly how you messed up above.
    // Once you've got that fixed, you can often (not always!) reduce it to a 'user cancelled' assumption.
    switch (CommDlgExtendedError())
    {
      case CDERR_DIALOGFAILURE   : std::cout << "CDERR_DIALOGFAILURE\n";   break;
      case CDERR_FINDRESFAILURE  : std::cout << "CDERR_FINDRESFAILURE\n";  break;
      case CDERR_INITIALIZATION  : std::cout << "CDERR_INITIALIZATION\n";  break;
      case CDERR_LOADRESFAILURE  : std::cout << "CDERR_LOADRESFAILURE\n";  break;
      case CDERR_LOADSTRFAILURE  : std::cout << "CDERR_LOADSTRFAILURE\n";  break;
      case CDERR_LOCKRESFAILURE  : std::cout << "CDERR_LOCKRESFAILURE\n";  break;
      case CDERR_MEMALLOCFAILURE : std::cout << "CDERR_MEMALLOCFAILURE\n"; break;
      case CDERR_MEMLOCKFAILURE  : std::cout << "CDERR_MEMLOCKFAILURE\n";  break;
      case CDERR_NOHINSTANCE     : std::cout << "CDERR_NOHINSTANCE\n";     break;
      case CDERR_NOHOOK          : std::cout << "CDERR_NOHOOK\n";          break;
      case CDERR_NOTEMPLATE      : std::cout << "CDERR_NOTEMPLATE\n";      break;
      case CDERR_STRUCTSIZE      : std::cout << "CDERR_STRUCTSIZE\n";      break;
      case FNERR_BUFFERTOOSMALL  : std::cout << "FNERR_BUFFERTOOSMALL\n";  break;
      case FNERR_INVALIDFILENAME : std::cout << "FNERR_INVALIDFILENAME\n"; break;
      case FNERR_SUBCLASSFAILURE : std::cout << "FNERR_SUBCLASSFAILURE\n"; break;
      default                    : std::cout << "You cancelled.\n";
    }
  }
}

To get a "save" filename instead, just change the GetOpenFilename to GetSaveFilename. There are a few differences in the flags you're likely to pass in the OPENFILENAME though--for example, it's pretty common to pass OFN_FILEMUSTEXIST when you're opening a file, but you almost never want to when you're saving a file.


问:
Single MySQL Insert with PHP is inputting multiple Records
New to OOP with PHP, a bit lost, thanks in advance.

Issue I am having is that when I create a New User, it is inserting 5 records for the same user (new unique primary ID for each). Found lots of issue with people trying to learn to insert multiple records, but think this is the first issue posted on here about multiple records inserting into MySQL Database when only trying to insert one!

Let me know if you need to see any additional code -- Thanks!

User Class

```<code>class User{

protected static $table_name="users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public $email;

public static function find_all(){
    return self::find_by_sql("SELECT * FROM users");
}

public static function find_by_id($id=0){
    global $database;
    $result_array = self::find_by_sql("SELECT * FROM users WHERE id={$id} LIMIT 1");
    return !empty($result_array) ? array_shift($result_array) : false;
}

public static function find_by_sql($sql=""){
    global $database;
    $result_set = $database->query($sql);
    $object_array = array();
    while ($row = $database->fetch_array($result_set)){
        $object_array[] = self::instantiate($row);
    }
    return $object_array;
}

public static function authenticate($username="", $password=""){
    global $database;
    $username = $database->escape_value($username);
    $password = $database->escape_value($password);
    $sql  = "SELECT * FROM users ";
    $sql .= "WHERE username = '{$username}' ";
    $sql .= "AND password = '{$password}' ";
    $sql .= "LIMIT 1";
    $result_array = self::find_by_sql($sql);
    return !empty($result_array) ? array_shift($result_array) : false;
}

public function full_name(){
    if(isset($this->first_name) && isset($this->last_name)){
        return $this->first_name . " " . $this->last_name;
    } else {
        return "";
    }
}

private static function instantiate($record){
    $object = new self;
    foreach($record as $attribute=>$value){
        if($object->has_attribute($attribute)){
            $object->$attribute = $value;
        }
    }
    return $object;
}

private function has_attribute($attribute){
    $object_vars = get_object_vars($this);
    return array_key_exists($attribute, $object_vars);
}

public function create(){
    global $database;
    $sql  = "INSERT INTO users (";
    $sql .= "username, password, first_name, last_name, email";
    $sql .= ") VALUES ('";
    $sql .= $database->escape_value($this->username) ."', '";
    $sql .= $database->escape_value($this->password) ."', '";
    $sql .= $database->escape_value($this->first_name) ."', '";
    $sql .= $database->escape_value($this->last_name) ."', '";
    $sql .= $database->escape_value($this->email) ."')";
    if($database->query($sql)){
        $this->id = $database->insert_id();
        return true;
    } else {
        return false;
    }
}
}
</code>```

Database Class

```<code>class MySQLDatabase{

private $connection;

function __construct(){
    $this->open_connection();
}

public function open_connection(){
    $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    if(mysqli_connect_errno()){
        die("Database Connection Failed: " .
             mysqli_connect_error() .
             " (" . mysqli_connect_errno() . ")"
        );
    }
}

public function close_connection(){
    if(isset($this->connection)){
        mysqli_close($this->connection);
        unset($this->connection);
    }
}

public function query($sql){
    $result = mysqli_query($this->connection, $sql);
    $this->confirm_query($result);
    return $result;
}

private function confirm_query($result){
    if(!$result) {
        die("Database query failed.");
    }
}

public function escape_value($string){
    $escaped_string = mysqli_real_escape_string($this->connection, $string);
    return $escaped_string;
}

public function fetch_array($result_set){
    return mysqli_fetch_array($result_set);
}

public function num_rows($result_set){
    return mysqli_num_rows($result_set);
}

public function insert_id(){
    return mysqli_insert_id($this->connection);
}

public function affected_rows(){
    return mysqli_affected_rows($this->connection);
}

}
</code>```

Instantiation

```<code>$user = new User();
$user->username = "test";
$user->password = "testing";
$user->first_name = "Bob";
$user->last_name = "Smith";
$user->email = "bsmith@gmail.com";
$user->create();
</code>```

答: Blokeish was correct, issue was around an include/require which was occurring in the framework prior to being defined.</p>

Body:
New to OOP with PHP, a bit lost, thanks in advance.

Issue I am having is that when I create a New User, it is inserting 5 records for the same user (new unique primary ID for each). Found lots of issue with people trying to learn to insert multiple records, but think this is the first issue posted on here about multiple records inserting into MySQL Database when only trying to insert one!

Let me know if you need to see any additional code -- Thanks!

User Class

class User{

protected static $table_name="users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public $email;

public static function find_all(){
    return self::find_by_sql("SELECT * FROM users");
}

public static function find_by_id($id=0){
    global $database;
    $result_array = self::find_by_sql("SELECT * FROM users WHERE id={$id} LIMIT 1");
    return !empty($result_array) ? array_shift($result_array) : false;
}

public static function find_by_sql($sql=""){
    global $database;
    $result_set = $database->query($sql);
    $object_array = array();
    while ($row = $database->fetch_array($result_set)){
        $object_array[] = self::instantiate($row);
    }
    return $object_array;
}

public static function authenticate($username="", $password=""){
    global $database;
    $username = $database->escape_value($username);
    $password = $database->escape_value($password);
    $sql  = "SELECT * FROM users ";
    $sql .= "WHERE username = '{$username}' ";
    $sql .= "AND password = '{$password}' ";
    $sql .= "LIMIT 1";
    $result_array = self::find_by_sql($sql);
    return !empty($result_array) ? array_shift($result_array) : false;
}

public function full_name(){
    if(isset($this->first_name) && isset($this->last_name)){
        return $this->first_name . " " . $this->last_name;
    } else {
        return "";
    }
}

private static function instantiate($record){
    $object = new self;
    foreach($record as $attribute=>$value){
        if($object->has_attribute($attribute)){
            $object->$attribute = $value;
        }
    }
    return $object;
}

private function has_attribute($attribute){
    $object_vars = get_object_vars($this);
    return array_key_exists($attribute, $object_vars);
}

public function create(){
    global $database;
    $sql  = "INSERT INTO users (";
    $sql .= "username, password, first_name, last_name, email";
    $sql .= ") VALUES ('";
    $sql .= $database->escape_value($this->username) ."', '";
    $sql .= $database->escape_value($this->password) ."', '";
    $sql .= $database->escape_value($this->first_name) ."', '";
    $sql .= $database->escape_value($this->last_name) ."', '";
    $sql .= $database->escape_value($this->email) ."')";
    if($database->query($sql)){
        $this->id = $database->insert_id();
        return true;
    } else {
        return false;
    }
}
}

Database Class

class MySQLDatabase{

private $connection;

function __construct(){
    $this->open_connection();
}

public function open_connection(){
    $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    if(mysqli_connect_errno()){
        die("Database Connection Failed: " .
             mysqli_connect_error() .
             " (" . mysqli_connect_errno() . ")"
        );
    }
}

public function close_connection(){
    if(isset($this->connection)){
        mysqli_close($this->connection);
        unset($this->connection);
    }
}

public function query($sql){
    $result = mysqli_query($this->connection, $sql);
    $this->confirm_query($result);
    return $result;
}

private function confirm_query($result){
    if(!$result) {
        die("Database query failed.");
    }
}

public function escape_value($string){
    $escaped_string = mysqli_real_escape_string($this->connection, $string);
    return $escaped_string;
}

public function fetch_array($result_set){
    return mysqli_fetch_array($result_set);
}

public function num_rows($result_set){
    return mysqli_num_rows($result_set);
}

public function insert_id(){
    return mysqli_insert_id($this->connection);
}

public function affected_rows(){
    return mysqli_affected_rows($this->connection);
}

}

Instantiation

$user = new User();
$user->username = "test";
$user->password = "testing";
$user->first_name = "Bob";
$user->last_name = "Smith";
$user->email = "bsmith@gmail.com";
$user->create();


问:
Caching queryset choices for ModelChoiceField or ModelMultipleChoiceField in a Django form
When using ModelChoiceField or ModelMultipleChoiceField in a Django form, is there a way to pass in a cached set of choices? Currently, if I specify the choices via the queryset parameter, it results in a database hit.

I'd like to cache these choices using memcached and prevent unnecessary hits to the database when displaying a form with such a field.

答:
Here is a little hack I use with Django 1.10 to cache a queryset in a formset:</p>

```<code>qs = my_queryset

# cache the queryset results
cache = [p for p in qs]

# build an iterable class to override the queryset's all() method
class CacheQuerysetAll(object):
    def __iter__(self):
        return iter(cache)
    def _prefetch_related_lookups(self):
        return False
qs.all = CacheQuerysetAll

# update the forms field in the formset
for form in formset.forms:
    form.fields['my_field'].queryset = qs
</code>```

Body:
Here is a little hack I use with Django 1.10 to cache a queryset in a formset:

qs = my_queryset

# cache the queryset results
cache = [p for p in qs]

# build an iterable class to override the queryset's all() method
class CacheQuerysetAll(object):
    def __iter__(self):
        return iter(cache)
    def _prefetch_related_lookups(self):
        return False
qs.all = CacheQuerysetAll

# update the forms field in the formset
for form in formset.forms:
    form.fields['my_field'].queryset = qs


问:
Migration from Webpack 1 to Webpack 2
I'm currently migrating Webpack1 to the second version.
As I saw here,

"Webpack is now using Postcss and cssnano in CSS-loader."

That means that I don't need to install postcss-loader?

In my old Webpack.config.js file I have this:

webpackConfig.postcss = [
  cssnano({
    autoprefixer : {
      add      : true,
      remove   : true,
      browsers : ['last 5 versions']
    },
    discardComments : {
      removeAll : true
    },
    discardUnused : false,
    mergeIdents   : false,
    reduceIdents  : false,
    safe          : true,
    sourcemap     : true
  })
];```

How do I use those options in the new Webpack 2?

答:
You could pass in the 'mimimize' option to css-loader</p>

```<code>...
    loader: 'css-loader',
    options: {
        minimize: true,
...
</code>```

Title: Migration from Webpack 1 to Webpack 2

Body:
I'm currently migrating Webpack1 to the second version.
As I saw here,

"Webpack is now using Postcss and cssnano in CSS-loader."

That means that I don't need to install postcss-loader?

In my old Webpack.config.js file I have this:

webpackConfig.postcss = [
  cssnano({
    autoprefixer : {
      add      : true,
      remove   : true,
      browsers : ['last 5 versions']
    },
    discardComments : {
      removeAll : true
    },
    discardUnused : false,
    mergeIdents   : false,
    reduceIdents  : false,
    safe          : true,
    sourcemap     : true
  })
];

How do I use those options in the new Webpack 2?

Body:
You could pass in the 'mimimize' option to css-loader

...
    loader: 'css-loader',
    options: {
        minimize: true,
...


问:
How to make this code less repetitive? (openpyxl)
I'm a teacher and I'm making a program to facilitate myself to catalog my students' grades. This isn't so much of a problem, the deal is, I'm doing it mostly to practice programming.

```<code># Name the first line
sheet['A1'] = 'Index'
sheet['B1'] = 'Name'
sheet['C1'] = 'Grade'

# Changes the style of the first line to bold
sheet['A1'].font = font_bold
sheet['B1'].font = font_bold
sheet['C1'].font = font_bold

# Widens the columns
sheet.column_dimensions['A'].width = 10
sheet.column_dimensions['B'].width = 30
sheet.column_dimensions['C'].width = 30

# Aligns to center
sheet.cell('A1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('B1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('C1').alignment = Alignment(horizontal='center', vertical='center')

# Freeze the first row
sheet.freeze_panes = 'A2'

# Index number of the lines
i = 2

--

--

# function to calculate the grade
def grade():
</code>```

As you may notice, it is all, to some extent, repetitive. The code functions exactly as I want it to, but I would like to know some other way to make it more... succint.

It is important to remember the variables reach, because up next a function will start, and, soon after, a While loop.

The irrelevant parts of the code for this question have been omitted with a ---. If they are somehow needed I'll edit them in, but to my knowledge, they are not.

Thank you in advance.

答:
Objects and DRY (Don't Repeat Yourself) Principle

In general, whenever you have some parallel arrays of the same length that keep some related attribute, it is a good indication that you can combine those attributes and make an object out of them.
For your case, I see that suggest to define an object Sheet with the following attributes:

title

font

column_dimensions

cell

...

Body:
I'm a teacher and I'm making a program to facilitate myself to catalog my students' grades. This isn't so much of a problem, the deal is, I'm doing it mostly to practice programming.

# Name the first line
sheet['A1'] = 'Index'
sheet['B1'] = 'Name'
sheet['C1'] = 'Grade'

# Changes the style of the first line to bold
sheet['A1'].font = font_bold
sheet['B1'].font = font_bold
sheet['C1'].font = font_bold

# Widens the columns
sheet.column_dimensions['A'].width = 10
sheet.column_dimensions['B'].width = 30
sheet.column_dimensions['C'].width = 30

# Aligns to center
sheet.cell('A1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('B1').alignment = Alignment(horizontal='center', vertical='center')
sheet.cell('C1').alignment = Alignment(horizontal='center', vertical='center')

# Freeze the first row
sheet.freeze_panes = 'A2'

# Index number of the lines
i = 2

--

--

# function to calculate the grade
def grade():

As you may notice, it is all, to some extent, repetitive. The code functions exactly as I want it to, but I would like to know some other way to make it more... succint.

It is important to remember the variables reach, because up next a function will start, and, soon after, a While loop.

The irrelevant parts of the code for this question have been omitted with a ---. If they are somehow needed I'll edit them in, but to my knowledge, they are not.

Thank you in advance.


问:
MySQL Query avoid usage of variable
Is there a way to put the first query into the main query and to avoid set of a variable?

```<code>SET @domain_id = (SELECT id FROM stop_domain LIMIT 1);
SELECT
  IFNULL(MAX(duid), 0) + 1 AS duid
  , @domain_id
FROM
  stop_link
WHERE domain_id = @domain_id;
</code>```

stop_domain

```<code>id | url
</code>```

stop_link

```<code>id | duid | domain_id
</code>```

答:
Indeed there is,</p>

```<code>SELECT
  IFNULL(MAX(duid), 0) + 1 AS duid
  , domain_id
FROM
  stop_link
WHERE domain_id = (SELECT id FROM stop_domain LIMIT 1);
</code>```

Title: MySQL Query avoid usage of variable

Body:
Is there a way to put the first query into the main query and to avoid set of a variable?

SET @domain_id = (SELECT id FROM stop_domain LIMIT 1);
SELECT
  IFNULL(MAX(duid), 0) + 1 AS duid
  , @domain_id
FROM
  stop_link
WHERE domain_id = @domain_id;

stop_domain

id | url

stop_link

id | duid | domain_id

Body:
Indeed there is,

SELECT
  IFNULL(MAX(duid), 0) + 1 AS duid
  , domain_id
FROM
  stop_link
WHERE domain_id = (SELECT id FROM stop_domain LIMIT 1);


问:
Jenkins Pipeline conditional stage succeeds but Jenkins shows build as failed
Jenkins version = 2.19
Jenkins Multibranch Pipeline plugin version = 2.92

I have a Jenkinsfile with a few conditional stages based on the branch.

Here is a modified for the sake of brevity version of my Jenkinsfile:

```<code>node {
    stage('Checkout') {
        checkout scm
    }

    stage('Clean Verify') {
        sh 'mvn clean verify'
    }

    if (env.BRANCH_NAME == "develop") {
        stage('Docker') {
            sh 'mvn docker:build -DpushImage'
        }
    }
}
</code>```

I am using the multibranch pipeline plugin.

It successfully detects and builds all my branches.

The problem I have is that all builds report as failed even though if i hover each stage it reports 'Success'.

I have attached an image showing a feature branch where the two stages i wanted to run have run and completed with success but you can see the build has actually reported as failed.

I get the exact same outcome for develop branch as well - it executes the Docker stage successfully but the build reports failed.

My expectation is that each branch will report success as the stages that ran for that branch all passed.

EDIT 1

Here's the end of the build log (i'm hoping this is sufficient as i didn't want to pick out all the private info but let me know if required)

```<code>[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 30.459 s
[INFO] Finished at: 2017-02-21T15:13:02+11:00
[INFO] Final Memory: 84M/769M
[INFO] ------------------------------------------------------------------------
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] sh
Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
[Pipeline] End of Pipeline
org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing
    at org.jenkinsci.plugins.workflow.steps.StepDescriptor.checkContextAvailability(StepDescriptor.java:253)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:179)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:126)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:108)
at groovy.lang.GroovyObject$invokeMethod.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:151)
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:21)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:115)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:103)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:149)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:146)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:16)
at WorkflowScript.run(WorkflowScript:93)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:57)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:109)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:82)
at sun.reflect.GeneratedMethodAccessor501.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
at com.cloudbees.groovy.cps.Next.step(Next.java:58)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:33)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:30)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:108)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:30)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:163)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:328)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:80)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:240)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:228)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:63)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Finished: FAILURE
</code>```

答:
So after looking more closely at the log file it helped me to track down the problem.

It's worth noting that clicking on the build stage to view the logs is what threw me - this is what I had been doing.  When I actually went to the full console log output i saw the error about:

```<code>Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
</code>```

Underneath the node {} section that I had I had a statement for deploys:

```<code>def branch = readFile('branch').trim()
if (branch == master) {
    ...
}
</code>```

The problem was that the readFile statement was defined outside of a node.

The answer was to put the readFile statement within a node {} section.

Body:
Jenkins version = 2.19
Jenkins Multibranch Pipeline plugin version = 2.92

I have a Jenkinsfile with a few conditional stages based on the branch.

Here is a modified for the sake of brevity version of my Jenkinsfile:

node {
    stage('Checkout') {
        checkout scm
    }

    stage('Clean Verify') {
        sh 'mvn clean verify'
    }

    if (env.BRANCH_NAME == "develop") {
        stage('Docker') {
            sh 'mvn docker:build -DpushImage'
        }
    }
}

I am using the multibranch pipeline plugin.

It successfully detects and builds all my branches.

The problem I have is that all builds report as failed even though if i hover each stage it reports 'Success'.

I have attached an image showing a feature branch where the two stages i wanted to run have run and completed with success but you can see the build has actually reported as failed.

I get the exact same outcome for develop branch as well - it executes the Docker stage successfully but the build reports failed.

My expectation is that each branch will report success as the stages that ran for that branch all passed.

EDIT 1

Here's the end of the build log (i'm hoping this is sufficient as i didn't want to pick out all the private info but let me know if required)

[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 30.459 s
[INFO] Finished at: 2017-02-21T15:13:02+11:00
[INFO] Final Memory: 84M/769M
[INFO] ------------------------------------------------------------------------
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] sh
Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
[Pipeline] End of Pipeline
org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing
    at org.jenkinsci.plugins.workflow.steps.StepDescriptor.checkContextAvailability(StepDescriptor.java:253)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:179)
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:126)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:108)
at groovy.lang.GroovyObject$invokeMethod.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:151)
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:21)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:115)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:103)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:149)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:146)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:16)
at WorkflowScript.run(WorkflowScript:93)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:57)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:109)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:82)
at sun.reflect.GeneratedMethodAccessor501.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
at com.cloudbees.groovy.cps.Next.step(Next.java:58)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:33)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:30)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:108)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:30)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:163)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:328)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:80)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:240)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:228)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:63)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Finished: FAILURE

Body:
So after looking more closely at the log file it helped me to track down the problem.

It's worth noting that clicking on the build stage to view the logs is what threw me - this is what I had been doing.  When I actually went to the full console log output i saw the error about:

Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node

Underneath the node {} section that I had I had a statement for deploys:

def branch = readFile('branch').trim()
if (branch == master) {
    ...
}

The problem was that the readFile statement was defined outside of a node.

The answer was to put the readFile statement within a node {} section.


问:
Facing issue to open Macro document in Modern Browser(FF, chrome) and Export As Fixed Format, Some could help here
Facing issue to open Macro document in Modern Browser(FF, chrome) and Export As Fixed Format.The below code user open macro document and set value as per the condition, next export it as fixed format.</p>

```<code>function launch_alwaysprint (loc)
var i;
{
    var w= new ActiveXObject("Word.Application");
    w.Visible = true;
    w.WindowState = 2; //Minimize
    w.WindowState = 1; //Maximize
    var obj= w.documents.open(loc);

    for (i=1; i<=obj.FormFields.count; i++) {
        if (obj.FormFields(i).name == "AccountOwner") {
                        if (document.forms[0].AccountOwnerOverride.value != "") {
                            obj.FormFields(obj.FormFields(i).name).Range.Fields(1).result.text = document.forms[0].AccountOwnerOverride.value;
                        }
                        else {
                                obj.FormFields(obj.FormFields(i).name).Range.Fields(1).result.text = document.forms[0][obj.FormFields(i).name].value;
                        }
                 }
    } //End For

    obj.RunAutoMacro(2);
    //obj.Protect(1,true,"Xz123Asdf34");
    var shell = new ActiveXObject("WScript.Shell");
    var pathToMyDocuments = shell.SpecialFolders('MyDocuments')+"\\test1.pdf";
    alert("Contract will be opened as a PDF but it will not be automatically saved");
    obj.ExportAsFixedFormat(pathToMyDocuments,"17","true");
    obj.Close(0)
    w.Quit(0)

} // End Main fnc
</code>```

答:
You can't do this in a web browser.

Launching and interacting with applications on the user's computer is a security risk, and web pages are no longer allowed to do it. (This code would only have ever worked on Internet Explorer, and even then, only on certain older versions with nonstandard security zone settings.)

You will need to find another way of doing this -- probably by processing the document and generating a PDF on the server.

Body:
Facing issue to open Macro document in Modern Browser(FF, chrome) and Export As Fixed Format.The below code user open macro document and set value as per the condition, next export it as fixed format.

function launch_alwaysprint (loc)
var i;
{
    var w= new ActiveXObject("Word.Application");
    w.Visible = true;
    w.WindowState = 2; //Minimize
    w.WindowState = 1; //Maximize
    var obj= w.documents.open(loc);

    for (i=1; i<=obj.FormFields.count; i++) {
        if (obj.FormFields(i).name == "AccountOwner") {
                        if (document.forms[0].AccountOwnerOverride.value != "") {
                            obj.FormFields(obj.FormFields(i).name).Range.Fields(1).result.text = document.forms[0].AccountOwnerOverride.value;
                        }
                        else {
                                obj.FormFields(obj.FormFields(i).name).Range.Fields(1).result.text = document.forms[0][obj.FormFields(i).name].value;
                        }
                 }
    } //End For

    obj.RunAutoMacro(2);
    //obj.Protect(1,true,"Xz123Asdf34");
    var shell = new ActiveXObject("WScript.Shell");
    var pathToMyDocuments = shell.SpecialFolders('MyDocuments')+"\\test1.pdf";
    alert("Contract will be opened as a PDF but it will not be automatically saved");
    obj.ExportAsFixedFormat(pathToMyDocuments,"17","true");
    obj.Close(0)
    w.Quit(0)

} // End Main fnc


答:
I'd take the whole thing and break it down into functions.

```<code>def name_column(cell, name):
    sheet[cell] = name

def style_name_column(cell, style):
    sheet[cell].font = style

def change_width(column, width):
    sheet.column_dimensions[column].width = width

def align_column(cell):
    sheet.cell(cell).alignment = Alignment(horizontal='center', vertical='center')
</code>```

then use some sort of data structure to loop over and do this stuff.

```<code>indexes_and_names = [['A1','Index']
                     ['B1','Name' ]
                     ['C1','Grade']]

for item in indexes_and_names:
    name_column(item[0], item[1])
</code>```

and then repeat for the other functions, or use a bigger data structure, like Jack's dictionary.

Your code will be readable, and easily maintainable.

Title: How to make this code less repetitive? (openpyxl)

Body:
I'd take the whole thing and break it down into functions.

def name_column(cell, name):
    sheet[cell] = name

def style_name_column(cell, style):
    sheet[cell].font = style

def change_width(column, width):
    sheet.column_dimensions[column].width = width

def align_column(cell):
    sheet.cell(cell).alignment = Alignment(horizontal='center', vertical='center')

then use some sort of data structure to loop over and do this stuff.

indexes_and_names = [['A1','Index']
                     ['B1','Name' ]
                     ['C1','Grade']]

for item in indexes_and_names:
    name_column(item[0], item[1])

and then repeat for the other functions, or use a bigger data structure, like Jack's dictionary.

Your code will be readable, and easily maintainable.


答:
```<code>SELECT     IFNULL(MAX(duid), 0) + 1 AS duid
           ,t.id
FROM       (SELECT id FROM stop_domain LIMIT 1) t
INNER JOIN stop_link
ON         domain_id = t.id
GROUP BY   t.id;
</code>```

Title: MySQL Query avoid usage of variable


问:
Turn off wps on android
I would like to raise the level of my security. Often, I use my Sony E2303 like a wifi hotspot, but I don't know how to turn off WPS pin implementation.

Android 5.0 lolipop (root)
patch level secured:2015-11-01
Compilation: 26.1.A.3.111.

答: Ok, I solved it by turn on Invisible Mode (BSSID) after  the first connection to my hotspot. (next will be automaticly if you use auto-connect Network settings in your PC, or if you know BSSID you still can connect from your terminal).This is in Tethering/Hotspot settings on your android smartfon. </p>

Title: Turn off wps on android


问:
How to resolve modulus/division by zero error in python
I am struggling to debug the following code, which throws a ZeroDivisionError:

```<code>if num > 0:
    return filter(lambda x: abs(num) % x == 0, range(1:abs(num))
else:
    pass
</code>```

The error message is:

```<code>ZeroDivisionError: integer division or modulo by zero
</code>```

The code is a bit ugly because I was getting this error before adding the if and abs() statements.

I am using python 3.6 per my schools requirement, and the task is to return factors of int num using a filter.

答:
Your code returns this error because of how you have defined range().

The correct way to define range in python is below:

```<code>range(start, stop, step)
</code>```

If your case you have used slicing, this is causing your program to throw error.

For your program you need to define a function is order to return something from conditional statements, the following code will solve your issue

```<code>def fac(num):
    if num > 0:
        return list(filter(lambda x: num % x == 0, range(1, num+1)))

print(fac(5))  # [1, 5]
</code>```

Here I have used filter inside a list function because in Python 3 and above filter returns filter object.

Body:
I am struggling to debug the following code, which throws a ZeroDivisionError:

if num > 0:
    return filter(lambda x: abs(num) % x == 0, range(1:abs(num))
else:
    pass

The error message is:

ZeroDivisionError: integer division or modulo by zero

The code is a bit ugly because I was getting this error before adding the if and abs() statements.

I am using python 3.6 per my schools requirement, and the task is to return factors of int num using a filter.

Body:
Your code returns this error because of how you have defined range().

The correct way to define range in python is below:

range(start, stop, step)

If your case you have used slicing, this is causing your program to throw error.

For your program you need to define a function is order to return something from conditional statements, the following code will solve your issue

def fac(num):
    if num > 0:
        return list(filter(lambda x: num % x == 0, range(1, num+1)))

print(fac(5))  # [1, 5]

Here I have used filter inside a list function because in Python 3 and above filter returns filter object.


问:
Real time communication PC with PLC (protocol?)
Basically, I would like to creat my own piece of software something a la communication protocl between PC and PLC.

I would like to read real time values from PLC and display them in a table for example Data Base, OPC table, Excel and write to PLC from PC in real time mode as well.

The whole point is I would like to access this data via ethernet port. How I can do it ? I do not want to use 3rd party software. I want to create something my own.

答:
As already mentioned, OPC-UA is probably more preferable, otherwise, there are commercial libraries such as InGear and open projects on GitHub.

If you actually want to implement your own low level drivers, they will depend on the PLC manufacturer. For example:

If you are working with Allen-Bradley, you will have to implement Common Industrial Protocol (CIP).

If you are working with Siemens, you will have to implement S7 Communication (S7comm or S7 for short).

If you search GitHub for various search terms related to Allen Bradley CIP and Siemens S7, you will find many starting points for communicating directly with these controllers.


问:
Remove shadow - paper dialog (Polymer)
I know this is somewhat like a hack, and dialogs are meant to have shadows. However I'm using paper-dialog in the form of a bottom sheet in my application. I want to remove the elevation/shadow of the dialog. How can I achieve this?

答:
I just added the following style and the shadow is gone</p>

```<code><style>
    paper-dialog { box-shadow: none; }
</style>
</code>```

Title: Remove shadow - paper dialog (Polymer)

Body:
I just added the following style and the shadow is gone

<style>
    paper-dialog { box-shadow: none; }
</style>


问:
Resizing image using promise and pouch
I asked this before and tried to change it based on some answers but still have an issue with the promises.

This is actually multiple promises but the main issue is that I am calling pouch.get to get a list of images.  I then go through a for/loop to create some markup (which works fine if I don't have the resize promise code).  I am trying to create a bunch of thumbnail images to show on a phone in a grid.

I made the resize code a promise to try and get the resize to finish before going and getting another image to resize.  But it ends up only doing one onload event for the last image and that is all that shows.

What is happening is that for each loop it goes into the resize, sets the onload event, copies the url to the image then jumps out and does the next loop and the onload event doesn't get fired until the last loop (image), which displays on the screen.

My resize Promise:

```<code>function resizeImageToImgPromise(showImage, maxWidth, maxHeight, url) {
   // Set img src to ObjectURL

   return new Promise(function (resolve, reject) {
      var test;
      test = 'test';
      showImage.onload = function () {
     URL.revokeObjectURL(this.src);
     var canvas = document.createElement("canvas");
     var ctx = canvas.getContext("2d");

   ... removed code to make it easier to read and not germane to the issue

     showImage.src = canvas.toDataURL("image/png");
     showImage.width = width;
     showImage.height;
     showImage.style.display = "inline";
     showImage.style.margin = "10px"

     resolve();
      }

      showImage.src = url;
   })
}
</code>```

Here is the promise that calls this in a for loop:

```<code>function readAllImagesFromPouch(id, imageDisplay) {

   return new Promise(function (resolve, reject) {

      var startElement = document.getElementById(imageDisplay);
      var image = "";
      var imgBlob;
      var base64str;

      // Get all attachments for this id

      DB_TaskImages.get(id, { attachments: true }).then(function (doc) {

     for (var key in doc._attachments) {
        var img = document.createElement('img');
        base64str = doc._attachments[key].data;
        blobUtil.base64StringToBlob(base64str).then(function (myBlob) {
           console.log();
           return blobUtil.createObjectURL(myBlob);
        }).then(function (myUrl) {

           img.src = myUrl;

           resizeImageToImgPromise(img, "100", "60", myUrl).then(function () {

          $(startElement).append(img.outerHTML);                              return;
           }).catch(function () {    // this is the catch for the resize
          alert("this is an error");
           })
        }).catch(function (err) {   // this is the catch for the blobUtil
           // error
        });
     }
     return;
      }).then(function () {
     resolve();
      }).catch(function (err) {      // this is the catch for the DB_TaskImages.get
     reject(err);
      })
   });         // end of promise
}
</code>```

And this is originally called from:

```<code>    readAllImagesFromPouch("006", "divImages").then(function () {
    }).catch(function (err) {
       console.log("In catch for readAllImagesFromPouch with err: " + err);
    })
</code>```

答:
Firstly, avoid the promise constructor anti-pattern. As DB_TaskImages.get returns a promise, you don't need to wrap the code in one

Secondly, your for...in loop kicks off a bunch of asynchronous tasks - but you don't actually wait for them to complete

This code will loop through the doc._attachments and execute the resize in "parallel" - only once all resizes have completed will the resized images be shown

```<code>function readAllImagesFromPouch(id, imageDisplay) {
    var startElement = document.getElementById(imageDisplay);
    return DB_TaskImages.get(id, {
        attachments: true
    }).then(function(doc) {
        return Promise.all(Object.keys(doc._attachments)
            .map(function(key) {
                var base64str = doc._attachments[key].data;
                return blobUtil.base64StringToBlob(base64str)
                .then(blobUtil.createObjectURL)
                .then(function(myUrl) {
                    return resizeImageToImgPromise("100", "60", myUrl);
                });
            })
        );
    }).then(function(images) {
        images.forEach(function(img) {
            $(startElement).append(img.outerHTML);
        });
    });
}
</code>```

Note: no error handling done, so any error at any point will result in no images being displayed

Title: Resizing image using promise and pouch

Body:
I asked this before and tried to change it based on some answers but still have an issue with the promises.

This is actually multiple promises but the main issue is that I am calling pouch.get to get a list of images.  I then go through a for/loop to create some markup (which works fine if I don't have the resize promise code).  I am trying to create a bunch of thumbnail images to show on a phone in a grid.

I made the resize code a promise to try and get the resize to finish before going and getting another image to resize.  But it ends up only doing one onload event for the last image and that is all that shows.

What is happening is that for each loop it goes into the resize, sets the onload event, copies the url to the image then jumps out and does the next loop and the onload event doesn't get fired until the last loop (image), which displays on the screen.

My resize Promise:

function resizeImageToImgPromise(showImage, maxWidth, maxHeight, url) {
   // Set img src to ObjectURL

   return new Promise(function (resolve, reject) {
      var test;
      test = 'test';
      showImage.onload = function () {
     URL.revokeObjectURL(this.src);
     var canvas = document.createElement("canvas");
     var ctx = canvas.getContext("2d");

   ... removed code to make it easier to read and not germane to the issue

     showImage.src = canvas.toDataURL("image/png");
     showImage.width = width;
     showImage.height;
     showImage.style.display = "inline";
     showImage.style.margin = "10px"

     resolve();
      }

      showImage.src = url;
   })
}

Here is the promise that calls this in a for loop:

function readAllImagesFromPouch(id, imageDisplay) {

   return new Promise(function (resolve, reject) {

      var startElement = document.getElementById(imageDisplay);
      var image = "";
      var imgBlob;
      var base64str;

      // Get all attachments for this id

      DB_TaskImages.get(id, { attachments: true }).then(function (doc) {

     for (var key in doc._attachments) {
        var img = document.createElement('img');
        base64str = doc._attachments[key].data;
        blobUtil.base64StringToBlob(base64str).then(function (myBlob) {
           console.log();
           return blobUtil.createObjectURL(myBlob);
        }).then(function (myUrl) {

           img.src = myUrl;

           resizeImageToImgPromise(img, "100", "60", myUrl).then(function () {

          $(startElement).append(img.outerHTML);                              return;
           }).catch(function () {    // this is the catch for the resize
          alert("this is an error");
           })
        }).catch(function (err) {   // this is the catch for the blobUtil
           // error
        });
     }
     return;
      }).then(function () {
     resolve();
      }).catch(function (err) {      // this is the catch for the DB_TaskImages.get
     reject(err);
      })
   });         // end of promise
}

And this is originally called from:

    readAllImagesFromPouch("006", "divImages").then(function () {
    }).catch(function (err) {
       console.log("In catch for readAllImagesFromPouch with err: " + err);
    })

Body:
Firstly, avoid the promise constructor anti-pattern. As DB_TaskImages.get returns a promise, you don't need to wrap the code in one

Secondly, your for...in loop kicks off a bunch of asynchronous tasks - but you don't actually wait for them to complete

This code will loop through the doc._attachments and execute the resize in "parallel" - only once all resizes have completed will the resized images be shown

function readAllImagesFromPouch(id, imageDisplay) {
    var startElement = document.getElementById(imageDisplay);
    return DB_TaskImages.get(id, {
        attachments: true
    }).then(function(doc) {
        return Promise.all(Object.keys(doc._attachments)
            .map(function(key) {
                var base64str = doc._attachments[key].data;
                return blobUtil.base64StringToBlob(base64str)
                .then(blobUtil.createObjectURL)
                .then(function(myUrl) {
                    return resizeImageToImgPromise("100", "60", myUrl);
                });
            })
        );
    }).then(function(images) {
        images.forEach(function(img) {
            $(startElement).append(img.outerHTML);
        });
    });
}

Note: no error handling done, so any error at any point will result in no images being displayed


问:
How to convert anything to a String safely in JavaScript
If I have:

```<code>var test = {toString: function(){alert("evil code"); return "test";}};
</code>```

how can I convert test to a string? without calling test.toString() and without using a typeof x == "string" check since I want to allow non strings.

Note: this is for a FF extension dealing with objects from a content page's js scope.

答:
One option is:

```<code>Object.prototype.toString.call(test)
</code>```

This gives:

```<code>"[object Object]"
</code>```

in the case of test.  Basically, it just gives type information.  However, I wonder what the exact scenario is here.  How is the evil object getting loaded into the page?  If they can execute arbitrary code on the page, you're basically out of luck.  Among other things, it is then possible to redefine Object.prototype.toString.

Body:
If I have:

var test = {toString: function(){alert("evil code"); return "test";}};

how can I convert test to a string? without calling test.toString() and without using a typeof x == "string" check since I want to allow non strings.

Note: this is for a FF extension dealing with objects from a content page's js scope.

Body:
One option is:

Object.prototype.toString.call(test)

This gives:

"[object Object]"

in the case of test.  Basically, it just gives type information.  However, I wonder what the exact scenario is here.  How is the evil object getting loaded into the page?  If they can execute arbitrary code on the page, you're basically out of luck.  Among other things, it is then possible to redefine Object.prototype.toString.

ContentLicense: CC BY-SA 2.5


问:
Image gallery from folder with limit of images
I have some code below, but I cant get the array_splice to limit the number of images shown.

```<code><?php
$id = $_GET['id'];
  if (empty($id)) {
    $clientname = 'tazz';
} else {
    $clientname = $_GET['id'];
}

$total = $_GET['limit'];
  if (empty($total)) {
    $limit = '100';
} else {
    $limit = $_GET['limit'];
}

$basefolder = "client/client-galleries/";
$dirname = $basefolder.$clientname."/";

    $images = scandir($dirname);
    sort($images);
    //shuffle($images);
    $ignore = array(".", "..");
    $output = array_splice($ignore, 0, $limit);

foreach($images as $curimg) {
        if(!in_array($curimg, $output)) {

echo "
    <div class='gallery'>
        <img src='[[pThumb? &input=`$dirname$curimg` &options=`&w=300&h=300&zc=1&q=95&fltr[]=wmi|./client/images/gallery-watermark-white.png|BL|50|25|200`]]' alt='$curimg'>
        <div class='desc'></div>
    </div>\n ";

        }
    }
</code>```

This correctly shows the images in the gallery but doesnt limit the amount of images as set by http://website.address?id=client&limit=5

答:
You're not applying array_splice to your $images array, but to your $ignore array, which only contains "." and "..". Also, array_splice is used to search/replace within an array, you're probably looking for array_slice, which is used to get a specific part of an array.

If you use array_diff to remove unwanted values from $images, you can then use array_slice to only keep at most $limit images. Something like this:

```<code>$images = scandir($dirname);
$ignore = array(".", "..");
$images_filtered = array_diff($images, $ignore);
$images_limited = array_slice($images_filtered, 0, $limit);
</code>```

$images_filtered should contain all items from $images that are not in $ignore.
$images_limited should contain the first $limit items from $images_filtered.

Body:
I have some code below, but I cant get the array_splice to limit the number of images shown.

<?php
$id = $_GET['id'];
  if (empty($id)) {
    $clientname = 'tazz';
} else {
    $clientname = $_GET['id'];
}

$total = $_GET['limit'];
  if (empty($total)) {
    $limit = '100';
} else {
    $limit = $_GET['limit'];
}

$basefolder = "client/client-galleries/";
$dirname = $basefolder.$clientname."/";

    $images = scandir($dirname);
    sort($images);
    //shuffle($images);
    $ignore = array(".", "..");
    $output = array_splice($ignore, 0, $limit);

foreach($images as $curimg) {
        if(!in_array($curimg, $output)) {

echo "

        <img src='[[pThumb? &input=`$dirname$curimg` &options=`&w=300&h=300&zc=1&q=95&fltr[]=wmi|./client/images/gallery-watermark-white.png|BL|50|25|200`]]' alt='$curimg'>

\n ";

        }
    }

This correctly shows the images in the gallery but doesnt limit the amount of images as set by http://website.address?id=client&limit=5

Body:
You're not applying array_splice to your $images array, but to your $ignore array, which only contains "." and "..". Also, array_splice is used to search/replace within an array, you're probably looking for array_slice, which is used to get a specific part of an array.

If you use array_diff to remove unwanted values from $images, you can then use array_slice to only keep at most $limit images. Something like this:

$images = scandir($dirname);
$ignore = array(".", "..");
$images_filtered = array_diff($images, $ignore);
$images_limited = array_slice($images_filtered, 0, $limit);

$images_filtered should contain all items from $images that are not in $ignore.
$images_limited should contain the first $limit items from $images_filtered.


问:
Changing if else from static to dynamic in javascript
I have an if else condition where, if I upload a file, it will see for the 'code name' i.e, 'abc1' in the file name and compare it to a hard coded value and the returned value will then be compared to a ProductLine. Here I am doing a two way search. how to get rid of all these if elses and make it straight like if I upload a file compare it with productLine and then return it. Below is the code.</p>

```<code>    var findProductLineByFilename = function(filename, productLines) {
    filename = filename.replace(/( |\-|\.|_)/g, '');
    var i;
    for (i in productLines) {
        productLine = productLines[i];

        // XXX: Hard-code names
        if (productLine.code_name === 'abc1') {
            if (filename.search(/(war1)|(w1)|(abc1)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc2') {
            if (filename.search(/(w2)|(abc2)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc3') {
            if (filename.search(/(w3)|(abc3)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc4') {
            if (filename.search(/(w4)|(abc4)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc5') {
            if (filename.search(/(w5)|(abc5)/) >= 0) {
                return productLine;
            }
        }
    }
    return null;
};
</code>```

答:
Use an object to map code names to regular expressions.</p>

```<code>var findProductLineByFilename = function(filename, productLines) {
    filename = filename.replace(/( |\-|\.|_)/g, '');
    var map = {
        'abc1': /(war1)|(w1)|(abc1)/,
        'abc2': //(w2)|(abc2)/,
        ...
    };
    var i;
    for (var i = 0; i < productLines.length; i++) {
        productLine = productLines[i];
        if (productLine.code_name in map && map[productLine.code_name].test(filename)) {
            return productLine;
        }
    }
    return null;
};
</code>```

Body:
I have an if else condition where, if I upload a file, it will see for the 'code name' i.e, 'abc1' in the file name and compare it to a hard coded value and the returned value will then be compared to a ProductLine. Here I am doing a two way search. how to get rid of all these if elses and make it straight like if I upload a file compare it with productLine and then return it. Below is the code.

    var findProductLineByFilename = function(filename, productLines) {
    filename = filename.replace(/( |\-|\.|_)/g, '');
    var i;
    for (i in productLines) {
        productLine = productLines[i];

        // XXX: Hard-code names
        if (productLine.code_name === 'abc1') {
            if (filename.search(/(war1)|(w1)|(abc1)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc2') {
            if (filename.search(/(w2)|(abc2)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc3') {
            if (filename.search(/(w3)|(abc3)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc4') {
            if (filename.search(/(w4)|(abc4)/) >= 0) {
                return productLine;
            }
        } else if (productLine.code_name == 'abc5') {
            if (filename.search(/(w5)|(abc5)/) >= 0) {
                return productLine;
            }
        }
    }
    return null;
};

Body:
Use an object to map code names to regular expressions.

var findProductLineByFilename = function(filename, productLines) {
    filename = filename.replace(/( |\-|\.|_)/g, '');
    var map = {
        'abc1': /(war1)|(w1)|(abc1)/,
        'abc2': //(w2)|(abc2)/,
        ...
    };
    var i;
    for (var i = 0; i < productLines.length; i++) {
        productLine = productLines[i];
        if (productLine.code_name in map && map[productLine.code_name].test(filename)) {
            return productLine;
        }
    }
    return null;
};


问:
Passing member function to function pointer
I have to pass in a function pointer of a member function to another class. I couldn't get it to compile and I get the "undefined reference to classB::classB(classA::*)(std::shared_ptr) " error. Can someone help me with this?

Thanks.

```<code>classA{
  string functionA(share_ptr<int>);
  void functionB(){
     classB* ptr = new classB(&classA::functionA);
  }
}

//in other .h file
classA; //forward declaration

classB{
  classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}
</code>```

答:
Your code as I'm writing this:

```<code>classA{
  string functionA(share_ptr<int>);
  void functionB(){
     classB* ptr = new classB(&classA::functionA);
  }
}
</code>```

Here:

share_ptr should be shared_ptr.

There is a missing semicolon at the end of the class definition.

Then,

```<code>//in other .h file
classA; //forward declaration

classB{
  classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}
</code>```

Here:

There are three left parentheses ( but only two right parentheses ).

A semicolon is missing at the end of the class definition.

You're asking about a linking error, but your code should not even compile.

When you state "I couldn't get it to compile" that seems to be correct.

When you then state "I get [undefined reference to...]", well that's a mystery: with the toolchain that you're evidently using, the linker shouldn't be invoked when the compilation fails.

In summary, this question contains some incorrect information and any answer (such as the hypothesis that you haven't defined the function, or the hypothesis that you defined it somewhere but forgot to link in that, or the hypothesis that you're reporting errors from building something else than your code, so on) would be pure guesswork.

Please post a complete small program that compiles and illustrates the linking error.

Cheers & hth.,

Body:
I have to pass in a function pointer of a member function to another class. I couldn't get it to compile and I get the "undefined reference to classB::classB(classA::*)(std::shared_ptr) " error. Can someone help me with this?

Thanks.

classA{
  string functionA(share_ptr<int>);
  void functionB(){
     classB* ptr = new classB(&classA::functionA);
  }
}

//in other .h file
classA; //forward declaration

classB{
  classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}

Body:
Your code as I'm writing this:

classA{
  string functionA(share_ptr<int>);
  void functionB(){
     classB* ptr = new classB(&classA::functionA);
  }
}

Here:

share_ptr should be shared_ptr.

There is a missing semicolon at the end of the class definition.

Then,

//in other .h file
classA; //forward declaration

classB{
  classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}

Here:

There are three left parentheses ( but only two right parentheses ).

A semicolon is missing at the end of the class definition.

You're asking about a linking error, but your code should not even compile.

When you state "I couldn't get it to compile" that seems to be correct.

When you then state "I get [undefined reference to...]", well that's a mystery: with the toolchain that you're evidently using, the linker shouldn't be invoked when the compilation fails.

In summary, this question contains some incorrect information and any answer (such as the hypothesis that you haven't defined the function, or the hypothesis that you defined it somewhere but forgot to link in that, or the hypothesis that you're reporting errors from building something else than your code, so on) would be pure guesswork.

Please post a complete small program that compiles and illustrates the linking error.

Cheers & hth.,


问:
Can't access data inside array that looks like JSON. JavaScript
Below, I have an array that looks like JSON data. I get this result by querying something and pushing it to var test = [];. The way I append the strings and numbers into my test array is by running test.push({item_name: name, number_of_items: number});. Just to be clear, it is not JSON:

```<code>[{"item_name":"Peri Peri Chicken","number_of_items":6},{"item_name":"Deep fried beef","number_of_items":22},{"item_name":"Roast chicken","number_of_items":7},{"item_name":"Chow Mein","number_of_items":3},{"item_name":"Sweet and sour noodles","number_of_items":5},{"item_name":"Steak","number_of_items":32}]
</code>```

Now, I want to sort the array so that it shows the array from the largest number_of_items to the smallest number_of_items.

I have tried to sort it like you would do with a JSON array, but it doesn't work as I have realised that I cannot access the elements in that array by using test.number_of_items. I tried THIS method to sort the array, but it doesn't work for me as my data is not in JSON.

It would also really helpful if someone can tell me if there's a better way to append multiple data into the same index of an array, and also to be able to access the elements easier in the future? so for example, on index 1 I would have something like (elem1: string1, elem2: number1) and then index 2 (elem1: string2, elem2: number2) and ...

答:
Try this :

```<code>  test = [{"item_name":"Peri Peri Chicken","number_of_items":6},   {"item_name":"Deep fried beef","number_of_items":22},{"item_name":"Roast chicken","number_of_items":7},{"item_name":"Chow Mein","number_of_items":3},    {"item_name":"Sweet and sour noodles","number_of_items":5},{"item_name":"Steak","number_of_items":32}];

  test.sort(function(a, b) {
    return a.number_of_items - b.number_of_items;
  });
</code>```

Good luck

Body:
Below, I have an array that looks like JSON data. I get this result by querying something and pushing it to var test = [];. The way I append the strings and numbers into my test array is by running test.push({item_name: name, number_of_items: number});. Just to be clear, it is not JSON:

[{"item_name":"Peri Peri Chicken","number_of_items":6},{"item_name":"Deep fried beef","number_of_items":22},{"item_name":"Roast chicken","number_of_items":7},{"item_name":"Chow Mein","number_of_items":3},{"item_name":"Sweet and sour noodles","number_of_items":5},{"item_name":"Steak","number_of_items":32}]

Now, I want to sort the array so that it shows the array from the largest number_of_items to the smallest number_of_items.

I have tried to sort it like you would do with a JSON array, but it doesn't work as I have realised that I cannot access the elements in that array by using test.number_of_items. I tried THIS method to sort the array, but it doesn't work for me as my data is not in JSON.

It would also really helpful if someone can tell me if there's a better way to append multiple data into the same index of an array, and also to be able to access the elements easier in the future? so for example, on index 1 I would have something like (elem1: string1, elem2: number1) and then index 2 (elem1: string2, elem2: number2) and ...

Body:
Try this :

  test = [{"item_name":"Peri Peri Chicken","number_of_items":6},   {"item_name":"Deep fried beef","number_of_items":22},{"item_name":"Roast chicken","number_of_items":7},{"item_name":"Chow Mein","number_of_items":3},    {"item_name":"Sweet and sour noodles","number_of_items":5},{"item_name":"Steak","number_of_items":32}];

  test.sort(function(a, b) {
    return a.number_of_items - b.number_of_items;
  });

Good luck


问:
MVC Post Causes QueryString to Be Lost on Reload of Same View
Please let me explain the setup.

I have a Change Password Controller/Action and View.
Here are the Action Signatures in my Account Controller:

```<code>public ActionResult ChangePassword(ChangePasswordMessageId? message)

[HttpPost]
public ActionResult ChangePassword(ChangePasswordViewModel model)
</code>```

When change password is first loaded, I have some data in the querystring. Here is an example:

https://www.mywebsite.com/Account/ChangePassword?mobile=1

Here is the Form declaration from the view.

```<code>@using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
</code>```

The form is submitted with a simple submit button:

```<code><div class="form-group">
  <div class="col-md-offset-2 col-md-4">
    <input type="submit" value="Change Password" class="btn btn-primary btn-block" />
  </div>
</div>
</code>```

The form has 3 fields: Current Password, New Password, and Confirm Password.
If the user fills in all the data correctly, and passes all the client side validation the form works fine. Everything works fine except for one use case.

Suppose the user enters an Old Password value that is not correct. When I get to the HTTPPOST ChangePassword action above, it will fail. This is what that code looks like.

```<code>[HttpPost]
            public ActionResult ChangePassword(ChangePasswordViewModel model)
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        MembershipUser user = Membership.GetUser();
        //The NEXT line is the one that fails if they supply the wrong Old Password value.
        //The code then falls to the catch condition below.
                        bool changePassword = user.ChangePassword(model.OldPassword, model.NewPassword);
                        if (changePassword)
                        {
                            string path = Url.Action("ChangePassword", new { Message = ChangePasswordMessageId.ChangePasswordSuccess });
                            temp = Request.UrlReferrer.ToString();
                            pos = temp.IndexOf("?");
                            if (pos > 0) path += "&" + temp.Substring(pos + 1);
                            return RedirectToLocal(path);
                       }
                        else
                        {
                            ModelState.AddModelError("", "Change Password failed.");
                        }
                    }
                    catch //(Exception ex)
                    {
                        ModelState.AddModelError("", "Change Password failed.");
                        //ModelState.AddModelError("", ex.Message);
                    }
                }

                // If we got this far, something failed, redisplay form
    //The original query string will be gone. The URLwill now only show
    //https://www.mywebsite.com/Account/ChangePassword
                return View(model);
            }
</code>```

Is there away to call "return View(model);" so that the original query string will still be there?
I need to maintain the query string from page to page. I have it working everywhere except for this one use case.

Thanks!

答:
```<code>return RedirectToAction("Index", Request.QueryString.ToRouteValues());
</code>```

Body:
Please let me explain the setup.

I have a Change Password Controller/Action and View.
Here are the Action Signatures in my Account Controller:

public ActionResult ChangePassword(ChangePasswordMessageId? message)

[HttpPost]
public ActionResult ChangePassword(ChangePasswordViewModel model)

When change password is first loaded, I have some data in the querystring. Here is an example:

https://www.mywebsite.com/Account/ChangePassword?mobile=1

Here is the Form declaration from the view.

@using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()

The form is submitted with a simple submit button:

    <input type="submit" value="Change Password" class="btn btn-primary btn-block" />

The form has 3 fields: Current Password, New Password, and Confirm Password.
If the user fills in all the data correctly, and passes all the client side validation the form works fine. Everything works fine except for one use case.

Suppose the user enters an Old Password value that is not correct. When I get to the HTTPPOST ChangePassword action above, it will fail. This is what that code looks like.

[HttpPost]
            public ActionResult ChangePassword(ChangePasswordViewModel model)
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        MembershipUser user = Membership.GetUser();
        //The NEXT line is the one that fails if they supply the wrong Old Password value.
        //The code then falls to the catch condition below.
                        bool changePassword = user.ChangePassword(model.OldPassword, model.NewPassword);
                        if (changePassword)
                        {
                            string path = Url.Action("ChangePassword", new { Message = ChangePasswordMessageId.ChangePasswordSuccess });
                            temp = Request.UrlReferrer.ToString();
                            pos = temp.IndexOf("?");
                            if (pos > 0) path += "&" + temp.Substring(pos + 1);
                            return RedirectToLocal(path);
                       }
                        else
                        {
                            ModelState.AddModelError("", "Change Password failed.");
                        }
                    }
                    catch //(Exception ex)
                    {
                        ModelState.AddModelError("", "Change Password failed.");
                        //ModelState.AddModelError("", ex.Message);
                    }
                }

                // If we got this far, something failed, redisplay form
    //The original query string will be gone. The URLwill now only show
    //https://www.mywebsite.com/Account/ChangePassword
                return View(model);
            }

Is there away to call "return View(model);" so that the original query string will still be there?
I need to maintain the query string from page to page. I have it working everywhere except for this one use case.

Thanks!