问:
QAF Not able to update element onFailure method
Question :

Based on : QAF | Passing new locator on failure

Trying to update the element onFailure method.
Using OrangeHRM site to test and trying to fill the password value.

during the test locator value is : id = "txtpassword1" [ which is a wrong one ]
OnFailure trying to set it to id = "txtpassword" [ correct id ]

but QAF is not updating the element and the test fails.

```<code>   public void onFailure(QAFExtendedWebElement element, CommandTracker commandTracker ) {

           System.out.println("=====<<<<<<< FALLBACK element >>>>>>>------>  \n" + element);
           System.out.println("=====<<<<<<< FALLBACK commandTracker >>>>>>>------> \n " +commandTracker);

           element.setBy(By.id("txtPassword"));
           //element.setId("txtPassword");
           commandTracker.setRetry(true);

           System.out.println("=====<<<<<<< FALLBACK after element >>>>>>>------>  \n" + element);
           System.out.println("=====<<<<<<< FALLBACK after commandTracker >>>>>>>------> \n " + commandTracker);
           }
</code>```

Console output :

```<code>
=====<<<<<<< FALLBACK element >>>>>>>------>
Using any of[id=txtPassword1]
=====<<<<<<< FALLBACK commandTracker >>>>>>>------>
com.qmetry.qaf.automation.ui.webdriver.CommandTracker@3a8d467e
=====<<<<<<< FALLBACK after element >>>>>>>------>
Using any of[id=txtPassword1]
=====<<<<<<< FALLBACK after commandTracker >>>>>>>------>
com.qmetry.qaf.automation.ui.webdriver.CommandTracker@3a8d467e
18:03:18.104 [main] ERROR com.qmetry.qaf.automation.step.TestStepListener - Failure Teststep: And I fill password "admin123" into "test.loc.Password" with arguments: [admin123,test.loc.Password]
org.openqa.selenium.TimeoutException: Timed out after 30 seconds waiting for presence of element located by: Using any of[id=txtPassword1]
</code>```

Noticed that element value is same even after element.setby

######################## -- UPDATED CODE -- ############################
rt_retrylistner.java file

```<code>package com.rt.listener;

import org.openqa.selenium.By;
import com.qmetry.qaf.automation.core.QAFListenerAdapter;
import com.qmetry.qaf.automation.ui.webdriver.CommandTracker;
import com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebDriver;
import com.qmetry.qaf.automation.util.JSONUtil;
import com.qmetry.qaf.automation.util.LocatorUtil;
import java.util.HashMap;
import java.util.Map;

//public class rt_retrylistener extends QAFWebElementCommandAdapter
public class rt_retrylistener extends QAFListenerAdapter {

    private static final Map < String, Object > byToString = JSONUtil.toMap(
        "{'ByCssSelector':'css selector','ByClassName':'class name','ByXPath':'xpath','ByPartialLinkText':'partial link text','ById':'id','ByLinkText':'link text','ByName':'name'}");

    @Override
    public void onFailure(QAFExtendedWebDriver driver, CommandTracker commandTracker)

    {
        System.out.println("into on failure ");

        Map < String, Object > parameters = commandTracker.getParameters();
        if (parameters != null && parameters.containsKey("using") && parameters.containsKey("value")) {
            By actaulBy = LocatorUtil.getBy(String.format("%s=%s", parameters.get("using"), parameters.get("value")));
            By newBy = By.id("txtpassword");
            commandTracker.getParameters().putAll(toParams(newBy));
            commandTracker.setRetry(true);
        }
    }

    private static Map < String, String > toParams(By by) {
        Map < String, String > map = new HashMap < String, String > ();
        String val = by.toString().split(":", 2)[1].trim();
        map.put("using", byToString.get(by.getClass().getSimpleName()).toString());
        map.put("value", val);

        return map;

    }

}
</code>```

Have enabled the listener in application.properties
wd.command.listeners=com.rt.listener.rt_retrylistener

Error message from console :

```<code>14:29:16.132 [main] ERROR com.qmetry.qaf.automation.step.TestStepListener - Failure Teststep: And I fill password "admin123" into "Password||rt.loc.3EPsPFPj9" with arguments: [admin123, Password||rt.loc.3EPsPFPj9]
java.lang.NullPointerException: Cannot invoke "com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebElement.setBy(org.openqa.selenium.By)" because "element" is null
    at com.rt.steps.rt_globals.iFillPasswordInTo(rt_globals.java:837) ~[test-classes/:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?]
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
    at java.lang.reflect.Method.invoke(Method.java:568) ~[?:?]
    at com.qmetry.qaf.automation.step.JavaStep.doExecute(JavaStep.java:150) ~[qaf-3.0.1.jar:?]
    at com.qmetry.qaf.automation.step.BaseTestStep.execute(BaseTestStep.java:149) [qaf-3.0.1.jar:?]
    at com.qmetry.qaf.automation.step.StringTestStep.execute(StringTestStep.java:127) [qaf-3.0.1.jar:?]
    at com.qmetry.qaf.automation.step.client.Scenario.execute(Scenario.java:174) [qaf-3.0.1.jar:?]
    at com.qmetry.qaf.automation.step.client.Scenario.scenario(Scenario.java:237) [qaf-3.0.1.jar:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?]
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
    at java.lang.reflect.Method.invoke(Method.java:568) ~[?:?]
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104) [testng-6.10.jar:?]
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:645) [testng-6.10.jar:?]
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:851) [testng-6.10.jar:?]
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1177) [testng-6.10.jar:?]
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129) [testng-6.10.jar:?]
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112) [testng-6.10.jar:?]
    at org.testng.TestRunner.privateRun(TestRunner.java:756) [testng-6.10.jar:?]
    at org.testng.TestRunner.run(TestRunner.java:610) [testng-6.10.jar:?]
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387) [testng-6.10.jar:?]
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382) [testng-6.10.jar:?]
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340) [testng-6.10.jar:?]
    at org.testng.SuiteRunner.run(SuiteRunner.java:289) [testng-6.10.jar:?]
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) [testng-6.10.jar:?]
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) [testng-6.10.jar:?]
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293) [testng-6.10.jar:?]
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218) [testng-6.10.jar:?]
    at org.testng.TestNG.runSuites(TestNG.java:1133) [testng-6.10.jar:?]
    at org.testng.TestNG.run(TestNG.java:1104) [testng-6.10.jar:?]
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:122) [surefire-testng-2.9.jar:2.9]
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92) [surefire-testng-2.9.jar:2.9]
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:101) [surefire-testng-2.9.jar:2.9]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?]
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
    at java.lang.reflect.Method.invoke(Method.java:568) ~[?:?]
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) [surefire-api-2.9.jar:2.9]
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) [surefire-booter-2.9.jar:2.9]
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:172) [surefire-booter-2.9.jar:2.9]
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:104) [surefire-booter-2.9.jar:2.9]
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:70) [surefire-booter-2.9.jar:2.9]
Feb 11, 2022 2:29:16 PM org.openqa.selenium.os.ProcessUtils killWinProcess
WARNING: Process refused to die after 10 seconds, and couldn't taskkill it
java.lang.RuntimeException: Couldn't detect pid
    at org.openqa.selenium.os.ProcessUtils.getProcessId(ProcessUtils.java:194)
    at org.openqa.selenium.os.ProcessUtils.killWinProcess(ProcessUtils.java:127)
    at org.openqa.selenium.os.ProcessUtils.killProcess(ProcessUtils.java:80)
    at org.openqa.selenium.os.UnixProcess$SeleniumWatchDog.destroyHarder(UnixProcess.java:265)
    at org.openqa.selenium.os.UnixProcess$SeleniumWatchDog.access$200(UnixProcess.java:219)
    at org.openqa.selenium.os.UnixProcess.destroy(UnixProcess.java:127)
    at org.openqa.selenium.os.CommandLine.destroy(CommandLine.java:153)
    at org.openqa.selenium.remote.service.DriverService.stop(DriverService.java:220)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:95)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebDriver.execute(QAFExtendedWebDriver.java:236)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:643)
    at com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebDriver.execute(QAFExtendedWebDriver.java:224)
    at org.openqa.selenium.remote.RemoteWebDriver.quit(RemoteWebDriver.java:482)
    at com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebDriver.stop(QAFExtendedWebDriver.java:611)
    at com.qmetry.qaf.automation.ui.UiDriverFactory.tearDown(UiDriverFactory.java:96)
    at com.qmetry.qaf.automation.core.QAFTestBase.tearDown(QAFTestBase.java:184)
    at com.qmetry.qaf.automation.ui.AbstractTestBase.tearDown(AbstractTestBase.java:103)
    at com.qmetry.qaf.automation.ui.AbstractTestCase.tearDownPrrallelThreads(AbstractTestCase.java:87)
    at com.qmetry.qaf.automation.ui.AbstractTestCase.afterTest(AbstractTestCase.java:77)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:515)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:217)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:144)
    at org.testng.TestRunner.afterRun(TestRunner.java:983)
    at org.testng.TestRunner.run(TestRunner.java:614)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
    at org.testng.TestNG.runSuites(TestNG.java:1133)
    at org.testng.TestNG.run(TestNG.java:1104)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:122)
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92)
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:101)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:172)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:104)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:70)
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field private final long java.lang.ProcessImpl.handle accessible: module java.base does not "opens java.lang" to unnamed module @382db087
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
    at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:178)
    at java.base/java.lang.reflect.Field.setAccessible(Field.java:172)
    at org.openqa.selenium.os.ProcessUtils.getProcessId(ProcessUtils.java:180)
    ... 51 more

14:29:16.980 [main] ERROR com.qmetry.qaf.automation.ui.WebDriverCommandLogger - command: quit[ param-1: {}] Result: Error communicating with the remote browser. It may have died.
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'MAVCHN1121100', ip: '192.168.1.3', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.1'
Driver info: driver.version: QAFExtendedWebDriver
Capabilities [{networkConnectionEnabled=false, chrome={chromedriverVersion=97.0.4692.71 (adefa7837d02a07a604c1e6eff0b3a09422ab88d-refs/branch-heads/4692@{#1247}), userDataDir=C:\Users\C6D43~1.KAR\AppData\Local\Temp\scoped_dir41280_431193466}, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, unhandledPromptBehavior=dismiss and notify, strictFileInteractability=false, platform=WINDOWS, proxy=Proxy(), goog:chromeOptions={debuggerAddress=localhost:51187}, webauthn:extension:credBlob=true, acceptInsecureCerts=false, browserVersion=97.0.4692.99, browserName=chrome, javascriptEnabled=true, platformName=WINDOWS, setWindowRect=true, webauthn:extension:largeBlob=true, webauthn:virtualAuthenticators=true}]
Session ID: 7b06a2cc937bfa016f82089896f3c354
into on failure
14:29:16.980 [main] ERROR com.qmetry.qaf.automation.ui.UiDriverFactory - Error communicating with the remote browser. It may have died.
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'MAVCHN1121100', ip: '192.168.1.3', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.1'
Driver info: driver.version: QAFExtendedWebDriver
Capabilities [{networkConnectionEnabled=false, chrome={chromedriverVersion=97.0.4692.71 (adefa7837d02a07a604c1e6eff0b3a09422ab88d-refs/branch-heads/4692@{#1247}), userDataDir=C:\Users\C6D43~1.KAR\AppData\Local\Temp\scoped_dir41280_431193466}, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, unhandledPromptBehavior=dismiss and notify, strictFileInteractability=false, platform=WINDOWS, proxy=Proxy(), goog:chromeOptions={debuggerAddress=localhost:51187}, webauthn:extension:credBlob=true, acceptInsecureCerts=false, browserVersion=97.0.4692.99, browserName=chrome, javascriptEnabled=true, platformName=WINDOWS, setWindowRect=true, webauthn:extension:largeBlob=true, webauthn:virtualAuthenticators=true}]
Session ID: 7b06a2cc937bfa016f82089896f3c354
</code>```

答:
in order to handle find element failure use onFailure from driver listener:

```<code>package myapp.listener;
...
public class QAFListenerImpl extends QAFListenerAdapter{
private static final Map<String, Object> byToString = JSONUtil.toMap(
            "{'ByCssSelector':'css selector','ByClassName':'class name','ByXPath':'xpath','ByPartialLinkText':'partial link text','ById':'id','ByLinkText':'link text','ByName':'name'}");

    @Override
    public void onFailure(QAFExtendedWebDriver driver, CommandTracker commandTracker) {

        Map<String, Object> parameters = commandTracker.getParameters();
        if (parameters != null && parameters.containsKey("using") && parameters.containsKey("value")) {
            By actaulBy = LocatorUtil.getBy(String.format("%s=%s", parameters.get("using"), parameters.get("value")));
            By newBy = <do the needful>
            commandTracker.getParameters().putAll(toParams(newBy));
            commandTracker.setRetry(true);
        }
    }

    private static Map<String, String> toParams(By by) {
        Map<String, String> map = new HashMap<String, String>();
        String val = by.toString().split(":", 2)[1].trim();
        map.put("using", byToString.get(by.getClass().getSimpleName()).toString());
        map.put("value", val);

        return map;

    }
}
</code>```

register listener using qaf.listeners property, for this example it will be

```<code>qaf.listeners=myapp.listener.QAFListenerImpl
</code>```

Body:
Question :

Based on : QAF | Passing new locator on failure

Trying to update the element onFailure method.
Using OrangeHRM site to test and trying to fill the password value.

during the test locator value is : id = "txtpassword1" [ which is a wrong one ]
OnFailure trying to set it to id = "txtpassword" [ correct id ]

but QAF is not updating the element and the test fails.

   public void onFailure(QAFExtendedWebElement element, CommandTracker commandTracker ) {

           System.out.println("=====<<<<<<< FALLBACK element >>>>>>>------>  \n" + element);
           System.out.println("=====<<<<<<< FALLBACK commandTracker >>>>>>>------> \n " +commandTracker);

           element.setBy(By.id("txtPassword"));
           //element.setId("txtPassword");
           commandTracker.setRetry(true);

           System.out.println("=====<<<<<<< FALLBACK after element >>>>>>>------>  \n" + element);
           System.out.println("=====<<<<<<< FALLBACK after commandTracker >>>>>>>------> \n " + commandTracker);
           }

Console output :

=====<<<<<<< FALLBACK element >>>>>>>------>
Using any of[id=txtPassword1]
=====<<<<<<< FALLBACK commandTracker >>>>>>>------>
com.qmetry.qaf.automation.ui.webdriver.CommandTracker@3a8d467e
=====<<<<<<< FALLBACK after element >>>>>>>------>
Using any of[id=txtPassword1]
=====<<<<<<< FALLBACK after commandTracker >>>>>>>------>
com.qmetry.qaf.automation.ui.webdriver.CommandTracker@3a8d467e
18:03:18.104 [main] ERROR com.qmetry.qaf.automation.step.TestStepListener - Failure Teststep: And I fill password "admin123" into "test.loc.Password" with arguments: [admin123,test.loc.Password]
org.openqa.selenium.TimeoutException: Timed out after 30 seconds waiting for presence of element located by: Using any of[id=txtPassword1]

Noticed that element value is same even after element.setby

######################## -- UPDATED CODE -- ############################
rt_retrylistner.java file

package com.rt.listener;

import org.openqa.selenium.By;
import com.qmetry.qaf.automation.core.QAFListenerAdapter;
import com.qmetry.qaf.automation.ui.webdriver.CommandTracker;
import com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebDriver;
import com.qmetry.qaf.automation.util.JSONUtil;
import com.qmetry.qaf.automation.util.LocatorUtil;
import java.util.HashMap;
import java.util.Map;

//public class rt_retrylistener extends QAFWebElementCommandAdapter
public class rt_retrylistener extends QAFListenerAdapter {

    private static final Map < String, Object > byToString = JSONUtil.toMap(
        "{'ByCssSelector':'css selector','ByClassName':'class name','ByXPath':'xpath','ByPartialLinkText':'partial link text','ById':'id','ByLinkText':'link text','ByName':'name'}");

    @Override
    public void onFailure(QAFExtendedWebDriver driver, CommandTracker commandTracker)

    {
        System.out.println("into on failure ");

        Map < String, Object > parameters = commandTracker.getParameters();
        if (parameters != null && parameters.containsKey("using") && parameters.containsKey("value")) {
            By actaulBy = LocatorUtil.getBy(String.format("%s=%s", parameters.get("using"), parameters.get("value")));
            By newBy = By.id("txtpassword");
            commandTracker.getParameters().putAll(toParams(newBy));
            commandTracker.setRetry(true);
        }
    }

    private static Map < String, String > toParams(By by) {
        Map < String, String > map = new HashMap < String, String > ();
        String val = by.toString().split(":", 2)[1].trim();
        map.put("using", byToString.get(by.getClass().getSimpleName()).toString());
        map.put("value", val);

        return map;

    }

}

Have enabled the listener in application.properties
wd.command.listeners=com.rt.listener.rt_retrylistener

Error message from console :

14:29:16.132 [main] ERROR com.qmetry.qaf.automation.step.TestStepListener - Failure Teststep: And I fill password "admin123" into "Password||rt.loc.3EPsPFPj9" with arguments: [admin123, Password||rt.loc.3EPsPFPj9]
java.lang.NullPointerException: Cannot invoke "com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebElement.setBy(org.openqa.selenium.By)" because "element" is null
    at com.rt.steps.rt_globals.iFillPasswordInTo(rt_globals.java:837) ~[test-classes/:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?]
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
    at java.lang.reflect.Method.invoke(Method.java:568) ~[?:?]
    at com.qmetry.qaf.automation.step.JavaStep.doExecute(JavaStep.java:150) ~[qaf-3.0.1.jar:?]
    at com.qmetry.qaf.automation.step.BaseTestStep.execute(BaseTestStep.java:149) [qaf-3.0.1.jar:?]
    at com.qmetry.qaf.automation.step.StringTestStep.execute(StringTestStep.java:127) [qaf-3.0.1.jar:?]
    at com.qmetry.qaf.automation.step.client.Scenario.execute(Scenario.java:174) [qaf-3.0.1.jar:?]
    at com.qmetry.qaf.automation.step.client.Scenario.scenario(Scenario.java:237) [qaf-3.0.1.jar:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?]
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
    at java.lang.reflect.Method.invoke(Method.java:568) ~[?:?]
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104) [testng-6.10.jar:?]
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:645) [testng-6.10.jar:?]
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:851) [testng-6.10.jar:?]
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1177) [testng-6.10.jar:?]
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129) [testng-6.10.jar:?]
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112) [testng-6.10.jar:?]
    at org.testng.TestRunner.privateRun(TestRunner.java:756) [testng-6.10.jar:?]
    at org.testng.TestRunner.run(TestRunner.java:610) [testng-6.10.jar:?]
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387) [testng-6.10.jar:?]
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382) [testng-6.10.jar:?]
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340) [testng-6.10.jar:?]
    at org.testng.SuiteRunner.run(SuiteRunner.java:289) [testng-6.10.jar:?]
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) [testng-6.10.jar:?]
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) [testng-6.10.jar:?]
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293) [testng-6.10.jar:?]
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218) [testng-6.10.jar:?]
    at org.testng.TestNG.runSuites(TestNG.java:1133) [testng-6.10.jar:?]
    at org.testng.TestNG.run(TestNG.java:1104) [testng-6.10.jar:?]
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:122) [surefire-testng-2.9.jar:2.9]
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92) [surefire-testng-2.9.jar:2.9]
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:101) [surefire-testng-2.9.jar:2.9]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[?:?]
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
    at java.lang.reflect.Method.invoke(Method.java:568) ~[?:?]
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) [surefire-api-2.9.jar:2.9]
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) [surefire-booter-2.9.jar:2.9]
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:172) [surefire-booter-2.9.jar:2.9]
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:104) [surefire-booter-2.9.jar:2.9]
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:70) [surefire-booter-2.9.jar:2.9]
Feb 11, 2022 2:29:16 PM org.openqa.selenium.os.ProcessUtils killWinProcess
WARNING: Process refused to die after 10 seconds, and couldn't taskkill it
java.lang.RuntimeException: Couldn't detect pid
    at org.openqa.selenium.os.ProcessUtils.getProcessId(ProcessUtils.java:194)
    at org.openqa.selenium.os.ProcessUtils.killWinProcess(ProcessUtils.java:127)
    at org.openqa.selenium.os.ProcessUtils.killProcess(ProcessUtils.java:80)
    at org.openqa.selenium.os.UnixProcess$SeleniumWatchDog.destroyHarder(UnixProcess.java:265)
    at org.openqa.selenium.os.UnixProcess$SeleniumWatchDog.access$200(UnixProcess.java:219)
    at org.openqa.selenium.os.UnixProcess.destroy(UnixProcess.java:127)
    at org.openqa.selenium.os.CommandLine.destroy(CommandLine.java:153)
    at org.openqa.selenium.remote.service.DriverService.stop(DriverService.java:220)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:95)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebDriver.execute(QAFExtendedWebDriver.java:236)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:643)
    at com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebDriver.execute(QAFExtendedWebDriver.java:224)
    at org.openqa.selenium.remote.RemoteWebDriver.quit(RemoteWebDriver.java:482)
    at com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebDriver.stop(QAFExtendedWebDriver.java:611)
    at com.qmetry.qaf.automation.ui.UiDriverFactory.tearDown(UiDriverFactory.java:96)
    at com.qmetry.qaf.automation.core.QAFTestBase.tearDown(QAFTestBase.java:184)
    at com.qmetry.qaf.automation.ui.AbstractTestBase.tearDown(AbstractTestBase.java:103)
    at com.qmetry.qaf.automation.ui.AbstractTestCase.tearDownPrrallelThreads(AbstractTestCase.java:87)
    at com.qmetry.qaf.automation.ui.AbstractTestCase.afterTest(AbstractTestCase.java:77)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:515)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:217)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:144)
    at org.testng.TestRunner.afterRun(TestRunner.java:983)
    at org.testng.TestRunner.run(TestRunner.java:614)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
    at org.testng.TestNG.runSuites(TestNG.java:1133)
    at org.testng.TestNG.run(TestNG.java:1104)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:122)
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92)
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:101)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:172)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:104)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:70)
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field private final long java.lang.ProcessImpl.handle accessible: module java.base does not "opens java.lang" to unnamed module @382db087
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
    at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:178)
    at java.base/java.lang.reflect.Field.setAccessible(Field.java:172)
    at org.openqa.selenium.os.ProcessUtils.getProcessId(ProcessUtils.java:180)
    ... 51 more

14:29:16.980 [main] ERROR com.qmetry.qaf.automation.ui.WebDriverCommandLogger - command: quit[ param-1: {}] Result: Error communicating with the remote browser. It may have died.
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'MAVCHN1121100', ip: '192.168.1.3', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.1'
Driver info: driver.version: QAFExtendedWebDriver
Capabilities [{networkConnectionEnabled=false, chrome={chromedriverVersion=97.0.4692.71 (adefa7837d02a07a604c1e6eff0b3a09422ab88d-refs/branch-heads/4692@{#1247}), userDataDir=C:\Users\C6D43~1.KAR\AppData\Local\Temp\scoped_dir41280_431193466}, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, unhandledPromptBehavior=dismiss and notify, strictFileInteractability=false, platform=WINDOWS, proxy=Proxy(), goog:chromeOptions={debuggerAddress=localhost:51187}, webauthn:extension:credBlob=true, acceptInsecureCerts=false, browserVersion=97.0.4692.99, browserName=chrome, javascriptEnabled=true, platformName=WINDOWS, setWindowRect=true, webauthn:extension:largeBlob=true, webauthn:virtualAuthenticators=true}]
Session ID: 7b06a2cc937bfa016f82089896f3c354
into on failure
14:29:16.980 [main] ERROR com.qmetry.qaf.automation.ui.UiDriverFactory - Error communicating with the remote browser. It may have died.
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'MAVCHN1121100', ip: '192.168.1.3', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.1'
Driver info: driver.version: QAFExtendedWebDriver
Capabilities [{networkConnectionEnabled=false, chrome={chromedriverVersion=97.0.4692.71 (adefa7837d02a07a604c1e6eff0b3a09422ab88d-refs/branch-heads/4692@{#1247}), userDataDir=C:\Users\C6D43~1.KAR\AppData\Local\Temp\scoped_dir41280_431193466}, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, unhandledPromptBehavior=dismiss and notify, strictFileInteractability=false, platform=WINDOWS, proxy=Proxy(), goog:chromeOptions={debuggerAddress=localhost:51187}, webauthn:extension:credBlob=true, acceptInsecureCerts=false, browserVersion=97.0.4692.99, browserName=chrome, javascriptEnabled=true, platformName=WINDOWS, setWindowRect=true, webauthn:extension:largeBlob=true, webauthn:virtualAuthenticators=true}]
Session ID: 7b06a2cc937bfa016f82089896f3c354

Body:
in order to handle find element failure use onFailure from driver listener:

package myapp.listener;
...
public class QAFListenerImpl extends QAFListenerAdapter{
private static final Map<String, Object> byToString = JSONUtil.toMap(
            "{'ByCssSelector':'css selector','ByClassName':'class name','ByXPath':'xpath','ByPartialLinkText':'partial link text','ById':'id','ByLinkText':'link text','ByName':'name'}");

    @Override
    public void onFailure(QAFExtendedWebDriver driver, CommandTracker commandTracker) {

        Map<String, Object> parameters = commandTracker.getParameters();
        if (parameters != null && parameters.containsKey("using") && parameters.containsKey("value")) {
            By actaulBy = LocatorUtil.getBy(String.format("%s=%s", parameters.get("using"), parameters.get("value")));
            By newBy = <do the needful>
            commandTracker.getParameters().putAll(toParams(newBy));
            commandTracker.setRetry(true);
        }
    }

    private static Map<String, String> toParams(By by) {
        Map<String, String> map = new HashMap<String, String>();
        String val = by.toString().split(":", 2)[1].trim();
        map.put("using", byToString.get(by.getClass().getSimpleName()).toString());
        map.put("value", val);

        return map;

    }
}

register listener using qaf.listeners property, for this example it will be

qaf.listeners=myapp.listener.QAFListenerImpl


来源: stackexchange

问:
Differrent results in different compilers c++
I have created the following program:

```<code>#include <iostream>

int main(){
    int a,b,mod, a1,b1;
    std::cin >> a >> b;

    if(a >= b){
        mod = a % b;
    } else {
        mod = b % a;
    }

    if(mod == 0){
        std::cout << a;
    } else {
        while(a1 != 0 && b1 != 0){

        a1 = a % mod;
        b1 = b % mod;
        --mod;
    }
    std::cout << mod + 1;

}

    return 0;
}
</code>```

I have tested with the following input: 25 27 and got result 1 (as expected).
But in another compiler I got result 3 and unfortunately I don't have an access to testing with another compiler(only the final result). I don't know why and where the behaviour of my program is inconsistent.

答: a1 and b1 is not initialized by correct numbers. If you set correct initial version, you should get consistent behavior.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have created the following program:

#include <iostream>

int main(){
    int a,b,mod, a1,b1;
    std::cin >> a >> b;

    if(a >= b){
        mod = a % b;
    } else {
        mod = b % a;
    }

    if(mod == 0){
        std::cout << a;
    } else {
        while(a1 != 0 && b1 != 0){

        a1 = a % mod;
        b1 = b % mod;
        --mod;
    }
    std::cout << mod + 1;

}

    return 0;
}

I have tested with the following input: 25 27 and got result 1 (as expected).
But in another compiler I got result 3 and unfortunately I don't have an access to testing with another compiler(only the final result). I don't know why and where the behaviour of my program is inconsistent.


问:
Why toDouble method is not working ? in flutter
enter image description here

enter image description here
...

答:
Double values are not printed with zeroes after the decimal point if those zeros have no mathematical importance.

Printing 55.0 will just print "55". That is to quote the documentation:

The representation is a number literal such that the closest double value to the representation's mathematical value is this double.

In other words, "55" is the simplest form of "55.0" there is. Mathematically, you could also say it's "55.00" or "55.000" or even "55.00000000000". It doesn't change.


问:
SVN branching problems
I have a /Trunk in my Project X. On rev 69 we had to revert changes in three earlier revisions (61,63,64).

What I did was a reverse merge on the revisions 61,63,64 and committed this to rev 69. Then we could deploy again and everyone was happy.

Now we have learned that developing new features in a separate branch is a neat idea, and then the Trunk is always ready to deploy to production (and doing hotfixes on current release).

So now I have made a "/Branches/X"(rev 70) from the HEAD revision in the /Trunk (which is rev 69), but I want to have with me the changes I undid in the /Trunk (61,63,64)

What is the correct way to this?

btw, have I made meself clear about? :)

答:
First of all, watch your spell-checker: trunk and branches are conventionally all lower-case. That said, you should remove your branch and recreate it from revision 68.

```<code>svn delete <project_url>/branches/X -m"branch X removed"

svn copy <project_url>/trunk@68 project_url/branches/X -m"New branch X"
</code>```

Here I'm assuming that revision 68 contains all changes from revs. 61,63,64 and nothing you do not want.

I'm sure you already realized that you can't go far without the Subversion book.

ContentLicense: CC BY-SA 3.0

Title: SVN branching problems

Body:
First of all, watch your spell-checker: trunk and branches are conventionally all lower-case. That said, you should remove your branch and recreate it from revision 68.

svn delete <project_url>/branches/X -m"branch X removed"

svn copy <project_url>/trunk@68 project_url/branches/X -m"New branch X"

Here I'm assuming that revision 68 contains all changes from revs. 61,63,64 and nothing you do not want.

I'm sure you already realized that you can't go far without the Subversion book.


问:
Wordpress plugin & PHP choose selected element from a drop down menu
I have these 2 functions of the same class. I need to retrive the selected element from the drop down menu but I can not. What am I doing wrong??</p>
```<code>    global $wpdb;

    $results =$wpdb -> get_col("SELECT `user_login` FROM `wp_users`");

    echo'<form method="post">
    <select name="employees" id="employees">';

    foreach ($results as $value) {
        echo'<option value="' .$value . '" ">  ' .$value. '</option>"';
     }

 '</select>';

echo '<input type="text" class="regular-text" name="first_name" value="' .var_dump($_POST). '" placeholder="Write your First Name">';
echo '<input type="text" class="regular-text" name="first_name" value="' .var_dump($_POST['employees']). '" placeholder="Write your First Name">';
echo '<input type="text" class="regular-text" name="first_name" value="' .print_r($_POST['employees']). '" placeholder="Write your First Name">';
</code>```

答:
I had this code on the pagename.php which calls the callback class where was located my dropdownlis.

```<code><form method="post" action="options.php">
            <?php
                settings_fields( 'alecaddd_options_group' );
                do_settings_sections( 'alecaddd_plugin' );
                submit_button();
            ?>
        </form>

</code>```

After removing the action fild everything worked great

Body:
I have these 2 functions of the same class. I need to retrive the selected element from the drop down menu but I can not. What am I doing wrong??

    global $wpdb;

    $results =$wpdb -> get_col("SELECT `user_login` FROM `wp_users`");

    echo'<form method="post">
    <select name="employees" id="employees">';

    foreach ($results as $value) {
        echo'<option value="' .$value . '" ">  ' .$value. '</option>"';
     }

 '</select>';

echo '<input type="text" class="regular-text" name="first_name" value="' .var_dump($_POST). '" placeholder="Write your First Name">';
echo '<input type="text" class="regular-text" name="first_name" value="' .var_dump($_POST['employees']). '" placeholder="Write your First Name">';
echo '<input type="text" class="regular-text" name="first_name" value="' .print_r($_POST['employees']). '" placeholder="Write your First Name">';

Body:
I had this code on the pagename.php which calls the callback class where was located my dropdownlis.

<form method="post" action="options.php">
            <?php
                settings_fields( 'alecaddd_options_group' );
                do_settings_sections( 'alecaddd_plugin' );
                submit_button();
            ?>
        </form>

After removing the action fild everything worked great


问:
replicate rows by n times in python
I have a dataframe that the first column are strings, the 2nd column are the numbers that I want to replicate each string.

```<code>df = pd.DataFrame({'String':['a','b', 'c', 'd', 'e', 'f', 'g'],
        'Times':[2, 3, 5, 3, 2, 4, 5]})
df
</code>```

String
Times

a
2

b
3

c
5

d
3

e
2

f
4

g
5

How can I create a data frame into this in python? (stopped at d but you know the pattern). Thanks!

String
Times

a
1

a
2

b
1

b
2

b
3

c
1

c
2

c
3

c
4

c
5

答:
Use Index.repeat to replicate the rows and groupby+cumcount: to enumerate them:

```<code>(df.loc[df.index.repeat(df['Times'])]
   .assign(Times=lambda d: d.groupby('String').cumcount().add(1))
 )
</code>```

Output:

```<code>  String  Times
0      a      1
0      a      2
1      b      1
1      b      2
1      b      3
2      c      1
2      c      2
2      c      3
2      c      4
2      c      5
3      d      1
...
</code>```

comparison of all answers (7k rows):

```<code>@mozway
11.2 ms ± 1.63 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

@Onyambu
16 ms ± 685 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

@ifly6
27.3 ms ± 2.42 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

@ddejohn
28.5 ms ± 4.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

On 700k rows: 1s, 1.43s, 2.34s, 2.94s in the same order

Title: replicate rows by n times in python

Body:
I have a dataframe that the first column are strings, the 2nd column are the numbers that I want to replicate each string.

df = pd.DataFrame({'String':['a','b', 'c', 'd', 'e', 'f', 'g'],
        'Times':[2, 3, 5, 3, 2, 4, 5]})
df

String
Times

a
2

b
3

c
5

d
3

e
2

f
4

g
5

How can I create a data frame into this in python? (stopped at d but you know the pattern). Thanks!

String
Times

a
1

a
2

b
1

b
2

b
3

c
1

c
2

c
3

c
4

c
5

Body:
Use Index.repeat to replicate the rows and groupby+cumcount: to enumerate them:

(df.loc[df.index.repeat(df['Times'])]
   .assign(Times=lambda d: d.groupby('String').cumcount().add(1))
 )

Output:

  String  Times
0      a      1
0      a      2
1      b      1
1      b      2
1      b      3
2      c      1
2      c      2
2      c      3
2      c      4
2      c      5
3      d      1
...

comparison of all answers (7k rows):

@mozway
11.2 ms ± 1.63 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

@Onyambu
16 ms ± 685 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

@ifly6
27.3 ms ± 2.42 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

@ddejohn
28.5 ms ± 4.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

On 700k rows: 1s, 1.43s, 2.34s, 2.94s in the same order


问:
Embed Slippy Map in tkinter/python
I am looking for a ability to generate/embed a slippy map (i.e. OpenStreetMaps) into a Tkinter Application that I can then plot geodetic coordinates and elliptical data over it (coming from a pyodbc connection to an *.mdb file). The user needs the geographic information (city name, etc.) for more efficient analysis.

I've looked at mapnik, Leaflet, pyrender, TileMill, TileStache, et al to facilitate this pipe dream and none really seem to fit the bill. The data needs to be interactive (balloon info, select-able, etc.) and dynamic (update when new user-defined sql parses data for filtering). The reason being, the other half of this program is ran through Tkinter and MatPlotLib. A complete system overhaul is what I'm trying to avoid.

Any help pointing me in the right direction would be greatly appreciated.

Some of my code available below:

(I apologize in advance for any errors or idiocies. I've only been writing in python for the last 3 months...all self taught)

```<code>#!/usr/bin/env python
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import matplotlib.image as mpimg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
from tkFileDialog import askopenfilename
from pylab import *
import tkMessageBox as mb
import pyodbc
import sys
import ttk

if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

def connect_db():
    global c
    conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s' % filename)
    c = conn.cursor()

def query_db():
    global time
    global freq
    global pri
    global pw
    freq=[]
    time=[]
    pri = []
    pw = []

c.execute("SELECT utc_usec_time_stamp, freq_mhz, pri, pw FROM SampleData")
rows = c.fetchall()

for row in rows:
    time.append(row[0])
    freq.append(row[1])
    pri.append(row[2])
    pw.append(row[3])
    progressbar.step(0.0008)
    root.update_idletasks()

def plot():
    global sb1
    global sb2
    global sb3
    global canvas

    f = Figure()
    f.clf()
    f.subplots_adjust(bottom=0.05,top=0.98,left=0.08,right=0.98,hspace=0.1)
    sb1 = f.add_subplot(3,1,1)
    sb1.scatter(time,freq)
    setp(sb1.get_xticklabels(), visible=False)
    sb1.set_ylabel("FREQ (MHz)")

    sb2 = f.add_subplot(3,1,2, sharex=sb1)
    sb2.scatter(time,pri)
    setp(sb2.get_xticklabels(), visible=False)
    sb2.set_ylabel("PRI (usec)")

    sb3 = f.add_subplot(3,1,3, sharex=sb1)
    sb3.scatter(time,pw)
    setp(sb3.get_xticklabels(), visible=False)
    sb3.set_xlabel("TIME")
    sb3.set_ylabel("PW (usec)")

    canvas = FigureCanvasTkAgg(f, master=root)

    logo.pack_forget()

    canvas.show()
    canvas.get_tk_widget().pack(side=Tk.RIGHT, fill=Tk.BOTH, expand=1)

    toolbar = NavigationToolbar2TkAgg( canvas, root )
    toolbar.update()
    canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def test():
    global pri

    p = Tk.Toplevel(root)
    f = Tk.Frame(p)
    f.pack(side="top")
    f.grid_rowconfigure(1, weight=1)
    f.grid_columnconfigure(4, weight=1)
    lbl = Tk.Label(f, text="label")
    lbl.grid(row=1, column=1)
    e = Tk.Entry(f)
    e.grid(row=1, column=2)
    b = Tk.Button(f, text="Button")
    b.grid(row=1, column=3)
    lbl2 = Tk.Label(f, text=" ")
    lbl2.grid(row=1, column=4, padx=100)

    fig = Figure()
    sb1 = fig.add_subplot(1,1,1)
    sb1.hist(pri)

    canvas = FigureCanvasTkAgg(fig, master=p)

    canvas.show()
    canvas.get_tk_widget().pack(side=Tk.RIGHT, fill=Tk.BOTH, expand=1)

    toolbar = NavigationToolbar2TkAgg( canvas, p )
    toolbar.update()
    canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def __init__():
    global root
    global rmi
    global rma
    global prmi
    global prma
    global pwmi
    global pwma
    global pdf
    global progressbar
    global tf
    global logo

    root = Tk.Tk()
    root.wm_title("Airborne Tactical Analysis System (ATLAS)")
    root.wm_state('zoomed')

    menubar = Tk.Menu(root)
    File = Tk.Menu(menubar, tearoff=0)
    File.add_command(label="Open", command=open)
    File.add_separator()
    File.add_command(label="Exit", command=_quit)
    menubar.add_cascade(label="File", menu=File)
    Options = Tk.Menu(menubar, tearoff=0)
    Options.add_command(label="-Coming Soon-")
    menubar.add_cascade(label="Options", menu=Options)
    PlotData = Tk.Menu(menubar, tearoff=0)
    PlotData.add_command(label="FREQ v PW")
    PlotData.add_command(label="FREQ v PRI")
    PlotData.add_command(label="PRI v PW")
    PlotData.add_command(label="FREQ HISTOGRAM")
    PlotData.add_command(label="PRI HISTOGRAM", command=test)
    PlotData.add_command(label="PW HISTOGRAM")
    menubar.add_cascade(label="Plot Data", menu=PlotData)
    Geo = Tk.Menu(menubar, tearoff=0)
    Geo.add_command(label="Generate Map")
    menubar.add_cascade(label="Geo", menu=Geo)
    root.config(menu=menubar)

    pdf = Tk.Frame(borderwidth=1, relief="sunken")
    pdf.pack(side="left", fill="y")
    pdf.grid_rowconfigure(7, weight=1)
    pdf.grid_columnconfigure(1, weight=1)

    tf = Tk.Frame(borderwidth=1, relief="sunken")
    tf.pack(side="bottom", fill="x")
    progl = Tk.Label(text=" Processing: ")
    progl.pack(in_=tf, side="left", ipady=10)
    progressbar = ttk.Progressbar(orient='horizontal', length=200, mode='determinate')
    progressbar.pack(in_=tf, side="left")
    fl = Tk.Label(text="Current File:")
    fl.pack(in_=tf, side="left", ipadx=10)

    b1 = Tk.Button(pdf, text="Submit", command=filter_builder)
    b1.grid(in_=pdf, row=2, columnspan=3, pady=10)

    buf = Tk.Label(text="   ")
    mil = Tk.Label(text="MIN")
    mal = Tk.Label(text="MAX")
    rfl = Tk.Label(text="RF:")
    pwl = Tk.Label(text="PW:")
    prl = Tk.Label(text="PRI:")
    prmi = Tk.Entry()
    prma = Tk.Entry()
    pwmi = Tk.Entry()
    pwma = Tk.Entry()
    rmi = Tk.Entry()
    rma = Tk.Entry()
    buf.grid(in_=pdf, column=3,row=3)
    mil.grid(in_=pdf, column=1,row=3, pady=4)
    mal.grid(in_=pdf, column=2,row=3)
    rfl.grid(in_=pdf, column=0,row=4)
    rmi.grid(in_=pdf, column=1,row=4)
    rma.grid(in_=pdf, column=2,row=4)
    prl.grid(in_=pdf, column=0,row=5)
    prmi.grid(in_=pdf, column=1,row=5)
    prma.grid(in_=pdf, column=2,row=5)
    pwl.grid(in_=pdf, column=0,row=6)
    pwmi.grid(in_=pdf, column=1,row=6)
    pwma.grid(in_=pdf, column=2,row=6)

    photo = Tk.PhotoImage(file="image.gif")

    logo = Tk.Label(image=photo)
    logo.image = photo
    logo.pack(side="top", fill="both", pady=100)

    root.mainloop()

__init__()
</code>```

答:
This is an old question, but if somebody wants to have an interactive OpenStreetMap map inside their application, I wrote a library called TkinterMapView to display tile based maps like OpenStreetMap or Google-Maps inside of Tkinter:

Documentation: https://github.com/TomSchimansky/TkinterMapView

Install: pip3 install tkintermapview

You just create a TkinterMapView widget like you create a frame or a button and you have an interactive map, where you can also set position markers or a path. You can focus the map on a specific location with coordinates or by passing an address string to the widget like in the following example:

import tkinter
from tkintermapview import TkinterMapView

root_tk = tkinter.Tk()
root_tk.geometry(f"{600}x{400}")
root_tk.title("map_view_simple_example.py")

# create map widget
map_widget = TkinterMapView(root_tk, width=600, height=400, corner_radius=0)
map_widget.pack(fill="both", expand=True)

map_widget.set_address("Berlin Germany", marker=True)

root_tk.mainloop()
```

The above code will give you the following window:

Title: Embed Slippy Map in tkinter/python

Body:
I am looking for a ability to generate/embed a slippy map (i.e. OpenStreetMaps) into a Tkinter Application that I can then plot geodetic coordinates and elliptical data over it (coming from a pyodbc connection to an *.mdb file). The user needs the geographic information (city name, etc.) for more efficient analysis.

I've looked at mapnik, Leaflet, pyrender, TileMill, TileStache, et al to facilitate this pipe dream and none really seem to fit the bill. The data needs to be interactive (balloon info, select-able, etc.) and dynamic (update when new user-defined sql parses data for filtering). The reason being, the other half of this program is ran through Tkinter and MatPlotLib. A complete system overhaul is what I'm trying to avoid.

Any help pointing me in the right direction would be greatly appreciated.

Some of my code available below:

(I apologize in advance for any errors or idiocies. I've only been writing in python for the last 3 months...all self taught)

#!/usr/bin/env python
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import matplotlib.image as mpimg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
from tkFileDialog import askopenfilename
from pylab import *
import tkMessageBox as mb
import pyodbc
import sys
import ttk

if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

def connect_db():
    global c
    conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s' % filename)
    c = conn.cursor()

def query_db():
    global time
    global freq
    global pri
    global pw
    freq=[]
    time=[]
    pri = []
    pw = []

c.execute("SELECT utc_usec_time_stamp, freq_mhz, pri, pw FROM SampleData")
rows = c.fetchall()

for row in rows:
    time.append(row[0])
    freq.append(row[1])
    pri.append(row[2])
    pw.append(row[3])
    progressbar.step(0.0008)
    root.update_idletasks()

def plot():
    global sb1
    global sb2
    global sb3
    global canvas

    f = Figure()
    f.clf()
    f.subplots_adjust(bottom=0.05,top=0.98,left=0.08,right=0.98,hspace=0.1)
    sb1 = f.add_subplot(3,1,1)
    sb1.scatter(time,freq)
    setp(sb1.get_xticklabels(), visible=False)
    sb1.set_ylabel("FREQ (MHz)")

    sb2 = f.add_subplot(3,1,2, sharex=sb1)
    sb2.scatter(time,pri)
    setp(sb2.get_xticklabels(), visible=False)
    sb2.set_ylabel("PRI (usec)")

    sb3 = f.add_subplot(3,1,3, sharex=sb1)
    sb3.scatter(time,pw)
    setp(sb3.get_xticklabels(), visible=False)
    sb3.set_xlabel("TIME")
    sb3.set_ylabel("PW (usec)")

    canvas = FigureCanvasTkAgg(f, master=root)

    logo.pack_forget()

    canvas.show()
    canvas.get_tk_widget().pack(side=Tk.RIGHT, fill=Tk.BOTH, expand=1)

    toolbar = NavigationToolbar2TkAgg( canvas, root )
    toolbar.update()
    canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def test():
    global pri

    p = Tk.Toplevel(root)
    f = Tk.Frame(p)
    f.pack(side="top")
    f.grid_rowconfigure(1, weight=1)
    f.grid_columnconfigure(4, weight=1)
    lbl = Tk.Label(f, text="label")
    lbl.grid(row=1, column=1)
    e = Tk.Entry(f)
    e.grid(row=1, column=2)
    b = Tk.Button(f, text="Button")
    b.grid(row=1, column=3)
    lbl2 = Tk.Label(f, text=" ")
    lbl2.grid(row=1, column=4, padx=100)

    fig = Figure()
    sb1 = fig.add_subplot(1,1,1)
    sb1.hist(pri)

    canvas = FigureCanvasTkAgg(fig, master=p)

    canvas.show()
    canvas.get_tk_widget().pack(side=Tk.RIGHT, fill=Tk.BOTH, expand=1)

    toolbar = NavigationToolbar2TkAgg( canvas, p )
    toolbar.update()
    canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def __init__():
    global root
    global rmi
    global rma
    global prmi
    global prma
    global pwmi
    global pwma
    global pdf
    global progressbar
    global tf
    global logo

    root = Tk.Tk()
    root.wm_title("Airborne Tactical Analysis System (ATLAS)")
    root.wm_state('zoomed')

    menubar = Tk.Menu(root)
    File = Tk.Menu(menubar, tearoff=0)
    File.add_command(label="Open", command=open)
    File.add_separator()
    File.add_command(label="Exit", command=_quit)
    menubar.add_cascade(label="File", menu=File)
    Options = Tk.Menu(menubar, tearoff=0)
    Options.add_command(label="-Coming Soon-")
    menubar.add_cascade(label="Options", menu=Options)
    PlotData = Tk.Menu(menubar, tearoff=0)
    PlotData.add_command(label="FREQ v PW")
    PlotData.add_command(label="FREQ v PRI")
    PlotData.add_command(label="PRI v PW")
    PlotData.add_command(label="FREQ HISTOGRAM")
    PlotData.add_command(label="PRI HISTOGRAM", command=test)
    PlotData.add_command(label="PW HISTOGRAM")
    menubar.add_cascade(label="Plot Data", menu=PlotData)
    Geo = Tk.Menu(menubar, tearoff=0)
    Geo.add_command(label="Generate Map")
    menubar.add_cascade(label="Geo", menu=Geo)
    root.config(menu=menubar)

    pdf = Tk.Frame(borderwidth=1, relief="sunken")
    pdf.pack(side="left", fill="y")
    pdf.grid_rowconfigure(7, weight=1)
    pdf.grid_columnconfigure(1, weight=1)

    tf = Tk.Frame(borderwidth=1, relief="sunken")
    tf.pack(side="bottom", fill="x")
    progl = Tk.Label(text=" Processing: ")
    progl.pack(in_=tf, side="left", ipady=10)
    progressbar = ttk.Progressbar(orient='horizontal', length=200, mode='determinate')
    progressbar.pack(in_=tf, side="left")
    fl = Tk.Label(text="Current File:")
    fl.pack(in_=tf, side="left", ipadx=10)

    b1 = Tk.Button(pdf, text="Submit", command=filter_builder)
    b1.grid(in_=pdf, row=2, columnspan=3, pady=10)

    buf = Tk.Label(text="   ")
    mil = Tk.Label(text="MIN")
    mal = Tk.Label(text="MAX")
    rfl = Tk.Label(text="RF:")
    pwl = Tk.Label(text="PW:")
    prl = Tk.Label(text="PRI:")
    prmi = Tk.Entry()
    prma = Tk.Entry()
    pwmi = Tk.Entry()
    pwma = Tk.Entry()
    rmi = Tk.Entry()
    rma = Tk.Entry()
    buf.grid(in_=pdf, column=3,row=3)
    mil.grid(in_=pdf, column=1,row=3, pady=4)
    mal.grid(in_=pdf, column=2,row=3)
    rfl.grid(in_=pdf, column=0,row=4)
    rmi.grid(in_=pdf, column=1,row=4)
    rma.grid(in_=pdf, column=2,row=4)
    prl.grid(in_=pdf, column=0,row=5)
    prmi.grid(in_=pdf, column=1,row=5)
    prma.grid(in_=pdf, column=2,row=5)
    pwl.grid(in_=pdf, column=0,row=6)
    pwmi.grid(in_=pdf, column=1,row=6)
    pwma.grid(in_=pdf, column=2,row=6)

    photo = Tk.PhotoImage(file="image.gif")

    logo = Tk.Label(image=photo)
    logo.image = photo
    logo.pack(side="top", fill="both", pady=100)

    root.mainloop()

__init__()

Body:
This is an old question, but if somebody wants to have an interactive OpenStreetMap map inside their application, I wrote a library called TkinterMapView to display tile based maps like OpenStreetMap or Google-Maps inside of Tkinter:

Documentation: https://github.com/TomSchimansky/TkinterMapView

Install: pip3 install tkintermapview

You just create a TkinterMapView widget like you create a frame or a button and you have an interactive map, where you can also set position markers or a path. You can focus the map on a specific location with coordinates or by passing an address string to the widget like in the following example:

import tkinter
from tkintermapview import TkinterMapView

root_tk = tkinter.Tk()
root_tk.geometry(f"{600}x{400}")
root_tk.title("map_view_simple_example.py")

# create map widget
map_widget = TkinterMapView(root_tk, width=600, height=400, corner_radius=0)
map_widget.pack(fill="both", expand=True)

map_widget.set_address("Berlin Germany", marker=True)

root_tk.mainloop()

The above code will give you the following window:


问:
How to search an element in column of a dataframe containing lists
I have a pandas dataframe df which contains two columns. First column sentence contains the sentence and second column keywords contains the all the keywords in list from the sentence in the first column. So my dataframe looks something like this :

```<code>>>> df
                                       sentence                          keywords
0        What are the advantages of the prepaid             [advantages, prepaid]
1     is salon facility available in your hotel          [salon, facility, hotel]
2  I want to check my balance and usage history  [check, balance, usage, history]
</code>```

Now suppose I have a list like ["salon", "usage", "history"] containing the keywords which I want to search against the keywords column and in return I want to get all the sentences containing the keywords in the given list. So the output in this particular case would be :

```<code>>>> output
["is salon facility available in your hotel", "I want to check my balance and usage history"]
</code>```

What is the fastest and most efficient way of achieving this result because I have thousands of sentences in the sentence column. The only way I know to achieve this to get all the lists from keywords column in a separate list and enumerate over it and get the indexes of the all the sub-lists containing the keywords and then look for same indexes in the sentence column. But this would be very slow. Is there any other better way of doing this?

Data:

```<code>data = {'sentence': ['What are the advantages of the prepaid',
                     'is salon facility available in your hotel',
                     'I want to check my balance and usage history'],
        'keywords': [['advantages', 'prepaid'],
                     ['salon', 'facility', 'hotel'],
                     ['check', 'balance', 'usage', 'history']]}
</code>```

答:
For each row you should check the set intersection (or difference) to determine which sentences' keywords overlap with the search keywords:

search_words = {'salon', 'usage', 'history'}

def search(keywords, search_words):
  return not search_words.isdisjoint(keywords)

results = df['keywords'].apply(search, args=(search_words,))

df.loc[results, 'sentence'].tolist()
```

Body:
I have a pandas dataframe df which contains two columns. First column sentence contains the sentence and second column keywords contains the all the keywords in list from the sentence in the first column. So my dataframe looks something like this :

>>> df
                                       sentence                          keywords
0        What are the advantages of the prepaid             [advantages, prepaid]
1     is salon facility available in your hotel          [salon, facility, hotel]
2  I want to check my balance and usage history  [check, balance, usage, history]

Now suppose I have a list like ["salon", "usage", "history"] containing the keywords which I want to search against the keywords column and in return I want to get all the sentences containing the keywords in the given list. So the output in this particular case would be :

>>> output
["is salon facility available in your hotel", "I want to check my balance and usage history"]

What is the fastest and most efficient way of achieving this result because I have thousands of sentences in the sentence column. The only way I know to achieve this to get all the lists from keywords column in a separate list and enumerate over it and get the indexes of the all the sub-lists containing the keywords and then look for same indexes in the sentence column. But this would be very slow. Is there any other better way of doing this?

Data:

data = {'sentence': ['What are the advantages of the prepaid',
                     'is salon facility available in your hotel',
                     'I want to check my balance and usage history'],
        'keywords': [['advantages', 'prepaid'],
                     ['salon', 'facility', 'hotel'],
                     ['check', 'balance', 'usage', 'history']]}


问:
Fiddler not capturing traffic from browsers
I've been using Fiddler for quite a while, but all of a sudden it no longer captures internet traffic.  I'm on Chrome 29 and Fiddler v4.4.5.1.  I've checked all filters and rules and nothing is on.  I've deleted my rules file, turned on and off capture traffic, and a few other things with no luck.  I even uninstalled and re-installed Fiddler to see if that would help but to no avail.

What am I missing?

[Follow Up]:

Troubleshoot Filters has no effect.

I see no activity in the log tab beyond "Fiddler Running..."

I've tried multiple browsers and none show internet traffic in fiddler

http://localhost.fiddler:8888/ does not work

http://127.0.0.1:8888 works and shows the fiddler echo service.

答:
Another possibility is to hide the requests from the Fiddler's UI by using the FiddlerScript feature. So something like

```<code>   if (!oSession.host.StartsWith("localhost:")) {
       oSession["ui-hide"] = "true";
   }
</code>```

Body:
Another possibility is to hide the requests from the Fiddler's UI by using the FiddlerScript feature. So something like

   if (!oSession.host.StartsWith("localhost:")) {
       oSession["ui-hide"] = "true";
   }


问:
Save docker-compose logs to a file
I have unit tests running on my build server and would like to capture the log results for analysis when something fails. I have yet to find a way to redirect the output of docker-compose logs to a file, or to find where the log files themselves actually live.

I want the equivalent of:

```<code>docker-compose logs > logs.txt
</code>```

Edit - clarification:

All of my docker containers produce useful logs, which a manual run of docker-compose logs reveals. I want to script this process to save those same logs to a file that is an artifact on my build server. Essentially, the output of docker-compose logs saved to a file, however docker-compose logs never exits.

答:
In my case, docker was using journald by default and my LogPath was blank.

I added the following to my docker-compose and then got a log to view:

```<code>logging:
  driver: "json-file"
</code>```

View Log:

```<code>CONTNAME=
docker inspect --format='{{.LogPath}}' $CONTNAME | xargs tail -f
</code>```

Title: Save docker-compose logs to a file

Body:
I have unit tests running on my build server and would like to capture the log results for analysis when something fails. I have yet to find a way to redirect the output of docker-compose logs to a file, or to find where the log files themselves actually live.

I want the equivalent of:

docker-compose logs > logs.txt

Edit - clarification:

All of my docker containers produce useful logs, which a manual run of docker-compose logs reveals. I want to script this process to save those same logs to a file that is an artifact on my build server. Essentially, the output of docker-compose logs saved to a file, however docker-compose logs never exits.

Body:
In my case, docker was using journald by default and my LogPath was blank.

I added the following to my docker-compose and then got a log to view:

logging:
  driver: "json-file"

View Log:

CONTNAME=
docker inspect --format='{{.LogPath}}' $CONTNAME | xargs tail -f


问:
How can you tell Angular to send the Origin header?
I have an Angular application that connects with my server.  For internal reasons I want to be able to send the origin domain to the server as it can be accessed from a couple places, for example:

https://domain1.com/app
https://domain2.com/app

In order to do that I would like my Angular app to set the Origin header.  I have an interceptor and I tried to do something like this:

return next.handle(req.clone({setHeaders: {Origin: environment.origin}}));

However, it throws an error that says Refused to set unsafe header "Origin".  I understand why, but how can I tell Angular to include this header and set it to the current domain (or just set it how it normally would)?  I don't need it set to anything special, I just need it included.

答:
The Origin header is sent automatically (by the browser) on cross-origin Ajax requests (and on some other cross-origin requests such as those for fonts or involving the crossorigin attribute).

It isn't sent for same-origin requests, and you can't make it be sent because it is a Forbidden header (so websites can't lie about the Origin to bypass CORS checks).

Since it is set for cross-origin requests you can treat its absence as a signal that the request is a same origin request. Test for that instead.

Obviously, if the request does not come from a browser then it typically won't have an Origin header, but you can't depend on that for security as any non-browser source for a request could easily forge the Origin header.


问:
Check for child key/value pairs in JSON
I need to identify if my JSON feed has child key/value pairs and handle them differently. what i mean is:

```<code>{
    "dashboard" :[
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":"" },

    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        },
    "related" : [
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        },
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        }]
  ]
</code>```

How do i identify that this JSON has those child ("related") key/value pairs?

答:
Convert JSON into a JS object and see if what you want is undefined.

```<code>var obj = JSON.parse(json_string);

if ( obj.related == undefined ) {
  ...
</code>```

Title: Check for child key/value pairs in JSON

Body:
I need to identify if my JSON feed has child key/value pairs and handle them differently. what i mean is:

{
    "dashboard" :[
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":"" },

    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        },
    "related" : [
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        },
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        }]
  ]

How do i identify that this JSON has those child ("related") key/value pairs?

Body:
Convert JSON into a JS object and see if what you want is undefined.

var obj = JSON.parse(json_string);

if ( obj.related == undefined ) {
  ...


问:
R Markdown knit issue: "Error in -title : invalid argument to unary operator"
Im new to R and R markdown, Im trying to run R Markdown code from a teamproject, but it doesnt run probably and I have problems understanding the errors.</p>
```<code>title: "R"
Error in -title : invalid argument to unary operator
> output:
+   flexdashboard::flex_dashboard:
+     orientation: columns
Error: object 'output' not found
>     vertical_layout: fill
Error: object 'vertical_layout' not found

{r setup, include=FALSE}
Error: attempt to use zero-length variable name
library(flexdashboard)
library(rmarkdown)
library(knitr)
library(readxl)

Error: attempt to use zero-length variable name
 {data-width=100}
Error in data - width = 100 : could not find function "-<-"
</code>```

答:
The YAML header should be contained between ---, the R code in chuncks starting and endding with ```</code>, see.<br />
Try to knit following <code>.Rmd</code> file :</p>
```---
title: "R"
output:
   flexdashboard::flex_dashboard:
   orientation: columns
   vertical_layout: fill
---

```{r setup, include=FALSE}
library(flexdashboard)
library(rmarkdown)
library(knitr)
library(readxl)
```

Your text here
```

Body:
Im new to R and R markdown, Im trying to run R Markdown code from a teamproject, but it doesnt run probably and I have problems understanding the errors.

title: "R"
Error in -title : invalid argument to unary operator
> output:
+   flexdashboard::flex_dashboard:
+     orientation: columns
Error: object 'output' not found
>     vertical_layout: fill
Error: object 'vertical_layout' not found

{r setup, include=FALSE}
Error: attempt to use zero-length variable name
library(flexdashboard)
library(rmarkdown)
library(knitr)
library(readxl)

Error: attempt to use zero-length variable name
 {data-width=100}
Error in data - width = 100 : could not find function "-<-"

Body:
The YAML header should be contained between ---, the R code in chuncks starting and endding with ```</code>, <a href="https://pkgs.rstudio.com/flexdashboard/articles/flexdashboard.html" rel="nofollow noreferrer">see</a>.<br />
Try to knit following <code>.Rmd</code> file :</p>
<pre><code>---
title: "R"
output:
   flexdashboard::flex_dashboard:
   orientation: columns
   vertical_layout: fill
---

```{r setup, include=FALSE}
library(flexdashboard)
library(rmarkdown)
library(knitr)
library(readxl)
```

Your text here


问:
How can one overwrite the return address without buffers on on the stack?
In the below program, I have a few buffers, but they are global variables, not stored on the stack.  Thus, I'm not seeing a viable way of overwriting the return address to execute a shellcode.

Is there a vulnerability in the below that I am missing?  The path constructed in snprintf seems pretty solid - not seeing a way to redirect the execution path.

C program:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libgen.h>

char buffer[256] = "";
char filename[256] = "";

int main(int argc, char *argv[])
{
  setreuid(geteuid(), geteuid());
  setregid(getegid(), getegid());

  if (argv[1]) {
    snprintf(filename, 255, "/var/smash/g6/%s", basename(argv[1]));
    printf("Checking filename %s\n", filename);
    if (access(filename, X_OK)) {
      fprintf(stderr, "You do not have the permission to execute this file\n");
      return 1;
    }
  }
  else {
    fprintf(stderr, "Please provide the program name. Currently available programs:\n");
    system("/bin/ls /var/smash/v6");
    return 2;
  }

  if (argv[2]) {
    strcpy(buffer, argv[2]);
  }
  else {
    printf("Provide the parameter(s):\n");
    gets(buffer);
  }
  printf("Executing filename %s\n", filename);

  execlp(filename, filename, buffer, (char *)0);

  return 0;
}

</code>```

答: Without trying it, it looks as if the vulnerability is that you provide a filename, which is checked to see that you have access, but then you read a string that isn't constrained to buffer but can overflow into filename such that your program will then execute the new filename without being constrained by the earlier checks.

Body:
In the below program, I have a few buffers, but they are global variables, not stored on the stack.  Thus, I'm not seeing a viable way of overwriting the return address to execute a shellcode.

Is there a vulnerability in the below that I am missing?  The path constructed in snprintf seems pretty solid - not seeing a way to redirect the execution path.

C program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libgen.h>

char buffer[256] = "";
char filename[256] = "";

int main(int argc, char *argv[])
{
  setreuid(geteuid(), geteuid());
  setregid(getegid(), getegid());

  if (argv[1]) {
    snprintf(filename, 255, "/var/smash/g6/%s", basename(argv[1]));
    printf("Checking filename %s\n", filename);
    if (access(filename, X_OK)) {
      fprintf(stderr, "You do not have the permission to execute this file\n");
      return 1;
    }
  }
  else {
    fprintf(stderr, "Please provide the program name. Currently available programs:\n");
    system("/bin/ls /var/smash/v6");
    return 2;
  }

  if (argv[2]) {
    strcpy(buffer, argv[2]);
  }
  else {
    printf("Provide the parameter(s):\n");
    gets(buffer);
  }
  printf("Executing filename %s\n", filename);

  execlp(filename, filename, buffer, (char *)0);

  return 0;
}


问:
Exception: The starting row of the range is too small
I'm using this code to search column 1 on a spreadsheet for the value 'Net Income'. I want this code to return the row position of with the value 'Net Income' so I can apply some formatting specific to that row based on that value. Here's the code I currently have:

```<code>const netIncomeRow = values.reduce((pos, row, i) => {
    if(row[0] === 'Net Income') pos = i + 1
    return pos;
  },0);

  const netIncomeRange = sheet.getRange(netIncomeRow, 1, 1, sheet.getLastColumn());
  netIncomeRange.setFontWeight('bold');
</code>```

When I run the code, I get the error "Exception: The starting row of the range is too small." and cannot figure out how to fix this ):

*Edit - I was taught to search through the rows this way as the position of the 'Net Income' row will change over time and I would like the bold formatting to follow and apply to whatever row ends up with the value 'Net Income'.

答:
Prevent Error

```<code>const netIncomeRow = values.reduce((pos, row, i) => {
    if(row[0] === 'Net Income') pos = i + 1
    return pos;
  },0);
  if(netIncomeRow) {
    const netIncomeRange = sheet.getRange(netIncomeRow, 1, 1, sheet.getLastColumn());
    netIncomeRange.setFontWeight('bold');
  }
</code>```

Body:
I'm using this code to search column 1 on a spreadsheet for the value 'Net Income'. I want this code to return the row position of with the value 'Net Income' so I can apply some formatting specific to that row based on that value. Here's the code I currently have:

const netIncomeRow = values.reduce((pos, row, i) => {
    if(row[0] === 'Net Income') pos = i + 1
    return pos;
  },0);

  const netIncomeRange = sheet.getRange(netIncomeRow, 1, 1, sheet.getLastColumn());
  netIncomeRange.setFontWeight('bold');

When I run the code, I get the error "Exception: The starting row of the range is too small." and cannot figure out how to fix this ):

*Edit - I was taught to search through the rows this way as the position of the 'Net Income' row will change over time and I would like the bold formatting to follow and apply to whatever row ends up with the value 'Net Income'.

Body:
Prevent Error

const netIncomeRow = values.reduce((pos, row, i) => {
    if(row[0] === 'Net Income') pos = i + 1
    return pos;
  },0);
  if(netIncomeRow) {
    const netIncomeRange = sheet.getRange(netIncomeRow, 1, 1, sheet.getLastColumn());
    netIncomeRange.setFontWeight('bold');
  }


问:
Azure: How to ensure a static IP for both inbound and outbound requests?
I'm having troubles designing the infrastructure in Azure for my app. The app should communicate with customer's on-premise systems by-directionally (meaning that sometimes my app initiates the connections, other times the customer's).

The customer wants a single IP address that would be used for both inbound and outbound traffic.

I've managed with a single VM - that was simple because - you create a VM, it gets an IP address automatically. You can switch it to static and voilá.

But the problem is that the application can run for many years and the hosting requirements may change. We might want to switch to a VMSS, AKS or something else later as the app grows.

So, I'm looking for an easy solution that would allow us to start with just a single VM for now but switch to more complex hosting models later while keeping the same IP.

I know that you can go all-in and design a very complicated infrastructure with a load balancer that splits the network into a public and a private part, then create an AKS cluster in the private part, let it use a specific subnet etc. etc. But it feels like an overkill for what we need now.

I'm just worried that if the design if too simple, it will be limiting us later when we try to scale out from that single VM.

Steps I've tried:

Create a vnet and an IP address

Create a load balancer inside the vnet and assign it the IP.

Create a VM without it's own public IP (so that I can make it use the common IP)

Configure the load balancer to point traffic to the VM.

...but it doesn't feel right. Inbound traffic works but outbound traffic seems to be comming from random IP addresses. And at this point I'm overwhelmed by all the network services in Azure - not sure what now. Should I somehow instruct the VM to route all traffic back via the same load balancer? Or can I do it on the vnet level? So that the vnet would capture all traffic trying to escape and re-route it via the common IP?

Sorry for the long comment but it's just a complex issue.

答:
An Standard Load Balancer should allow you to use the same IP for inbound and outbound traffic.

On AKS you simply configure your Service to a type of LoadBalancer, and set the inbound IP using annotations.
Afterwards you configure the load-balancer-outbound-ip-prefixes on your AKS cluster via the CLI to the same IP address. That way you can communicate inbound and outbound via the same IP Address.

You should be able to do the same for VMSS. Looking at your steps your just missing the outbound rule on your load balancer.

Regarding the IP-reuse, both AKS and a regular Load Balancer can use an IP address that you already have allocated. Just make sure you create a Standard SKU IP, as that gives you the most options.


问:
How to fix empty Docker LogPath
I’m setting up a new Redis server via docker-compose and cannot find json docker log file.

Redis log are /dev/stdout and visible via docker-compose logs command.

Docker version 1.13.1, build 7f2769b/1.13.1

docker-compose version 1.24.1, build 4667896

docker inspect --format='{{.LogPath}}' docker-compose-redis_redis_1 shows nothing

Snippet from docker-compose.yml:

```<code>    logging:
    #limit logs to 200MB (4rotations of 50M each)
      driver: "json-file"
      options:
        max-size: "50m"
        max-file: "4"
</code>```

I expect to find json file in /var/lib/docker/containers/container-id/

答:
Add the following to docker-compose:

```<code>logging:
  driver: "json-file"
</code>```

Im not sure yet to figure out how to change system wide, but I noticed I'm using journald default.

```<code>cat /etc/docker/daemon.json.original
{
    "log-driver": "journald",
    "storage-driver": "overlay2"
}
</code>```

Title: How to fix empty Docker LogPath

Body:
I’m setting up a new Redis server via docker-compose and cannot find json docker log file.

Redis log are /dev/stdout and visible via docker-compose logs command.

Docker version 1.13.1, build 7f2769b/1.13.1

docker-compose version 1.24.1, build 4667896

docker inspect --format='{{.LogPath}}' docker-compose-redis_redis_1 shows nothing

Snippet from docker-compose.yml:

    logging:
    #limit logs to 200MB (4rotations of 50M each)
      driver: "json-file"
      options:
        max-size: "50m"
        max-file: "4"

I expect to find json file in /var/lib/docker/containers/container-id/

Body:
Add the following to docker-compose:

logging:
  driver: "json-file"

Im not sure yet to figure out how to change system wide, but I noticed I'm using journald default.

cat /etc/docker/daemon.json.original
{
    "log-driver": "journald",
    "storage-driver": "overlay2"
}


问:
Compiler complains about wrong number of template arguments even if its correct in a boost library file
There is a file in the boost library called has_new_operator.hpp. I am getting the following error when i complile the file using GCC 4.3.1

type_traits/has_new_operator.hpp:45: error: wrong number of template
  arguments (1, should be 2) type_traits/has_new_operator.hpp:24: error:
  provided for 'template struct boost::detail::test'

as per line 24 it expects 2 arguments and that is what is been passed in line 42. Also if you observe line 31, the same has been done but the compiler does not complain about it.

```<code>21: namespace boost {
22: namespace detail {
23: template <class U, U x>
24:    struct test;
25:
26: template <typename T>
27: struct has_new_operator_impl {
28:    template<class U>
29:    static type_traits::yes_type check_sig1(
30:        U*,
31:        test<
32:        void *(*)(std::size_t),
33:            &U::operator new
34:        >* = NULL
35:    );
36:    template<class U>
37:    static type_traits::no_type check_sig1(...);

39:    template<class U>
40:    static type_traits::yes_type check_sig2(
41:        U*,
42:        test<
43:        void *(*)(std::size_t, const std::nothrow_t&),
44:            &U::operator new
45:        >* = NULL
    );
</code>```

答: The problem is with std::nothrow_t (line:43) being not visible. I included a file which contained nothrow_t in the std namespace and it worked fine. Thanks for your responses.</p>

Body:
There is a file in the boost library called has_new_operator.hpp. I am getting the following error when i complile the file using GCC 4.3.1

type_traits/has_new_operator.hpp:45: error: wrong number of template
  arguments (1, should be 2) type_traits/has_new_operator.hpp:24: error:
  provided for 'template struct boost::detail::test'

as per line 24 it expects 2 arguments and that is what is been passed in line 42. Also if you observe line 31, the same has been done but the compiler does not complain about it.

21: namespace boost {
22: namespace detail {
23: template <class U, U x>
24:    struct test;
25:
26: template <typename T>
27: struct has_new_operator_impl {
28:    template<class U>
29:    static type_traits::yes_type check_sig1(
30:        U*,
31:        test<
32:        void *(*)(std::size_t),
33:            &U::operator new
34:        >* = NULL
35:    );
36:    template<class U>
37:    static type_traits::no_type check_sig1(...);

39:    template<class U>
40:    static type_traits::yes_type check_sig2(
41:        U*,
42:        test<
43:        void *(*)(std::size_t, const std::nothrow_t&),
44:            &U::operator new
45:        >* = NULL
    );


问:
Is that possible to create a custom input widget in Foundry Slate?
I know how to use input widget in Slate but I have a use case where I need to create several inputs from an array. Maybe one, maybe more, let's say around 10 or 15. Is that possible to create a input and to catch the user entry just by using an HTML widget.

One other way to say shoud be: I would like to have a table of 1 to 15 rows with one column dedicated to an input area. Number of row depend of the source data, so I want that the input is created dynamically. Is it possible in foundry-slate ?

Best regards

答:
You can't do this in a plain HTML widget - the dependency graph can't read state from arbitrary HTML input elements.

There are a couple other options here; the one that most directly works they way you would like it to in your question, would be to use the Code Sandbox widget, which effectively let's you build your own widget and wire it up to the Slate dependency graph for interaction with the rest of the app. You can use a 3rd-party library, assuming you have the license, to do something more advanced (you can search your Foundry instance for some examples in the Slate Reference Examples) or simply use HTML and Javascript to build the widget as you would in normal web development as you have access to the DOM and JQuery when working in the Sandbox.

Slightly more in-line with how Slate might expect you to build this functionality, you can use a single input widget, but toggle what you do with the associated input based on other state, for example what row the user has selected. This, in combination with a button that stores the input into a Variable with a click event, can be used to let users build up a "bag" of edits, that you can then apply with Actions (or you can apply them immediately - all depends on the workflow). You'll find some examples of that pattern in the "Events" folder in the Slate Reference Examples.

Thinking a bit more expansively, if you model your data in the ontology, you can set up an editable table pattern in Workshop and have a quite straightforward experience once you have the right Action and Object Type configuration. You'll find the documentation on this on your Foundry instance at https://www.palantir.com/docs/foundry/workshop/widgets-object-table/#inline-edits-or-cell-level-writeback and an example in the Flight Alert Inbox example application.


问:
How to create external storagea when it doesn't exist?

Introduction

I want to add a external medium to a vagrant box,and it works fine. However when I shutdown the VM and run it again it tries to create the medium again so it throws an error because it already exists.

Configuration

Here is the Vagrantfile:

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.hostmanager.enabled = true
  config.hostmanager.manage_host = true
  config.hostmanager.manage_guest = true
  config.vm.box = "ubuntu/focal64"
  config.vm.box_version = "20211026.0.0"
  config.vm.box_check_update = false
  config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
  config.vm.network "private_network", type: "dhcp"
  config.vm.network "private_network", ip: "192.168.56.10"
  config.vm.provider "virtualbox" do |vb|
    disk_name = "secondary.vdi"
    controller_name = "sas_controller"
    vm_name = "mybox"
    vb.name = vm_name
    vb.cpus = 2
    vb.memory = 2048
    vb.customize [ "createmedium", "disk", "--filename", disk_name, "--format", "VDI", "--size", 2048 ]
    vb.customize [ "storagectl", vm_name, "--name", controller_name, "--add", "sas" ]
    vb.customize [ "storageattach", vm_name, "--storagectl", controller_name, "--port", "1", "--device", "0", "--type", "hdd", "--medium", disk_name ]
  end
  config.vm.provision "shell", inline: <<-SHELL
    apt-get update
    apt-get install -y apache2
    systemctl enable apache2
    mkfs -t ext4 /dev/sda
    mkdir /mnt/jaas-aisi2122-disk
    mount /dev/sda  /mnt/jaas-aisi2122-disk
  SHELL
end
```
<h2>Steps to reproduce</h2>
<ul>
<li>Run box with <code>vagrant up</code></li>
<li>Stop box with <code>vagrant halt</code></li>
<li>Run box again:
```A customization command failed:

["createmedium", "disk", "--filename", "secondary.vdi", "--format", "VDI", "--size", 2048]

The following error was experienced:

#<Vagrant::Errors::VBoxManageError: There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["createmedium", "disk", "--filename", "secondary.vdi", "--format", "VDI", "--size", "2048"]

Stderr: 0%...
Progress state: VBOX_E_FILE_ERROR
VBoxManage.exe: error: Failed to create medium
VBoxManage.exe: error: Could not create the medium storage unit 'C:\...\secondary.vdi'.
VBoxManage.exe: error: VDI: cannot create image 'C:\...\secondary.vdi' (VERR_ALREADY_EXISTS)
VBoxManage.exe: error: Details: code VBOX_E_FILE_ERROR (0x80bb0004), component MediumWrap, interface IMedium
VBoxManage.exe: error: Context: "enum RTEXITCODE __cdecl handleCreateMedium(struct HandlerArg *)" at line 510 of file VBoxManageDisk.cpp
>

Please fix this customization and try again.
```
</li>
</ul>
<h3>What I've tried:</h3>
<p>Deleting the medium before creating it by adding:</p>
<pre class="lang-rb prettyprint-override"><code>vb.customize [ "closemedium", "disk", disk_name, "--delete" ]
</code>```

Nevertheless it doesn't work, also thought of checking if it exists and create if not.

答:
Just needed to check if the file exists using ruby syntax:</p>
```<code>if(!File.exists?(disk_name))
    vb.customize [ "createmedium", "disk", "--filename", disk_name, "--format", "VDI", "--size", 2048 ]
    vb.customize [ "storagectl", vm_name, "--name", controller_name, "--add", "sas" ]
    vb.customize [ "storageattach", vm_name, "--storagectl", controller_name, "--port", "1", "--device", "0", "--type", "hdd", "--medium", disk_name ]
end
</code>```

Body:
Introduction

I want to add a external medium to a vagrant box,and it works fine. However when I shutdown the VM and run it again it tries to create the medium again so it throws an error because it already exists.

Configuration

Here is the Vagrantfile:

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.hostmanager.enabled = true
  config.hostmanager.manage_host = true
  config.hostmanager.manage_guest = true
  config.vm.box = "ubuntu/focal64"
  config.vm.box_version = "20211026.0.0"
  config.vm.box_check_update = false
  config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
  config.vm.network "private_network", type: "dhcp"
  config.vm.network "private_network", ip: "192.168.56.10"
  config.vm.provider "virtualbox" do |vb|
    disk_name = "secondary.vdi"
    controller_name = "sas_controller"
    vm_name = "mybox"
    vb.name = vm_name
    vb.cpus = 2
    vb.memory = 2048
    vb.customize [ "createmedium", "disk", "--filename", disk_name, "--format", "VDI", "--size", 2048 ]
    vb.customize [ "storagectl", vm_name, "--name", controller_name, "--add", "sas" ]
    vb.customize [ "storageattach", vm_name, "--storagectl", controller_name, "--port", "1", "--device", "0", "--type", "hdd", "--medium", disk_name ]
  end
  config.vm.provision "shell", inline: <<-SHELL
    apt-get update
    apt-get install -y apache2
    systemctl enable apache2
    mkfs -t ext4 /dev/sda
    mkdir /mnt/jaas-aisi2122-disk
    mount /dev/sda  /mnt/jaas-aisi2122-disk
  SHELL
end

Steps to reproduce

Run box with vagrant up

Stop box with vagrant halt

Run box again:

A customization command failed:

["createmedium", "disk", "--filename", "secondary.vdi", "--format", "VDI", "--size", 2048]

The following error was experienced:

#<Vagrant::Errors::VBoxManageError: There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["createmedium", "disk", "--filename", "secondary.vdi", "--format", "VDI", "--size", "2048"]

Stderr: 0%...
Progress state: VBOX_E_FILE_ERROR
VBoxManage.exe: error: Failed to create medium
VBoxManage.exe: error: Could not create the medium storage unit 'C:\...\secondary.vdi'.
VBoxManage.exe: error: VDI: cannot create image 'C:\...\secondary.vdi' (VERR_ALREADY_EXISTS)
VBoxManage.exe: error: Details: code VBOX_E_FILE_ERROR (0x80bb0004), component MediumWrap, interface IMedium
VBoxManage.exe: error: Context: "enum RTEXITCODE __cdecl handleCreateMedium(struct HandlerArg *)" at line 510 of file VBoxManageDisk.cpp
>

Please fix this customization and try again.

What I've tried:

Deleting the medium before creating it by adding:

vb.customize [ "closemedium", "disk", disk_name, "--delete" ]

Nevertheless it doesn't work, also thought of checking if it exists and create if not.

Body:
Just needed to check if the file exists using ruby syntax:

if(!File.exists?(disk_name))
    vb.customize [ "createmedium", "disk", "--filename", disk_name, "--format", "VDI", "--size", 2048 ]
    vb.customize [ "storagectl", vm_name, "--name", controller_name, "--add", "sas" ]
    vb.customize [ "storageattach", vm_name, "--storagectl", controller_name, "--port", "1", "--device", "0", "--type", "hdd", "--medium", disk_name ]
end