问:
Unable to launch chrome via chrome webdriver on jenkins where as it works fine on my local machine
Unable to launch chrome via chrome webdriver on jenkins where as it works fine on my local machine. I have tried everything that is on there on the internet to solve this problem but unable to get out of this loop hole. Though it's very much irritating I have wasted a lot of time kindly help if anyone out there is familiar of this problem. As I am new to selenium testing this is very frustrating issue.

```<code>Running as SYSTEM
Building in workspace /var/lib/jenkins/workspace/Test
`using credential 9917dab9-de45-43b7-8ff2-0c2b530a0ecf
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url https://bitbucket.org/admitkard/akd_e2e.git # timeout=10
Fetching upstream changes from https://bitbucket.org/admitkard/akd_e2e.git
 > git --version # timeout=10
using GIT_ASKPASS to set credentials
 > git fetch --tags --progress -- https://bitbucket.org/admitkard/akd_e2e.git +refs/heads/*:refs/remotes/origin/* # timeout=10
 > git rev-parse refs/remotes/origin/pawan^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/pawan^{commit} # timeout=10
Checking out Revision 10f6281f501136b9ffcd504f4d8f3a54568d1162 (refs/remotes/origin/pawan)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 10f6281f501136b9ffcd504f4d8f3a54568d1162 # timeout=10
Commit message: "Hi"
 > git rev-list --no-walk 10f6281f501136b9ffcd504f4d8f3a54568d1162 # timeout=10
[Test] $ /bin/sh -xe /tmp/jenkins5524615085827631447.sh
+ echo /var/lib/jenkins/workspace/Test
/var/lib/jenkins/workspace/Test
+ cd /var/lib/jenkins/workspace/Test/
+ mvn clean test -DtestngFile=testng/signupTestng.xml -Durl=https://dev.admitkard.net/ -Dbrowser=chrome
[[1;34mINFO[m] Scanning for projects...
[[1;33mWARNING[m]
[[1;33mWARNING[m] Some problems were encountered while building the effective model for com.example.admitKard:admitKard:jar:1.0-SNAPSHOT
[[1;33mWARNING[m] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 27, column 21
[[1;33mWARNING[m]
[[1;33mWARNING[m] It is highly recommended to fix these problems because they threaten the stability of your build.
[[1;33mWARNING[m]
[[1;33mWARNING[m] For this reason, future Maven versions might no longer support building such malformed projects.
[[1;33mWARNING[m]
[[1;34mINFO[m]
[[1;34mINFO[m] [1m------------------< [0;36mcom.example.admitKard:admitKard[0;1m >-------------------[m
[[1;34mINFO[m] [1mBuilding admitKard 1.0-SNAPSHOT[m
[[1;34mINFO[m] [1m--------------------------------[ jar ]---------------------------------[m
[[1;33mWARNING[m] The artifact org.apache.commons:commons-io:jar:1.3.2 has been relocated to commons-io:commons-io:jar:1.3.2
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-clean-plugin:2.5:clean[m [1m(default-clean)[m @ [36madmitKard[0;1m ---[m
[[1;34mINFO[m] Deleting /var/lib/jenkins/workspace/Test/target
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-resources-plugin:2.6:resources[m [1m(default-resources)[m @ [36madmitKard[0;1m ---[m
[[1;33mWARNING[m] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[[1;34mINFO[m] skip non existing resourceDirectory /var/lib/jenkins/workspace/Test/src/main/resources
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-compiler-plugin:3.1:compile[m [1m(default-compile)[m @ [36madmitKard[0;1m ---[m
[[1;34mINFO[m] No sources to compile
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-resources-plugin:2.6:testResources[m [1m(default-testResources)[m @ [36madmitKard[0;1m ---[m
[[1;33mWARNING[m] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[[1;34mINFO[m] Copying 16 resources
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-compiler-plugin:3.1:testCompile[m [1m(default-testCompile)[m @ [36madmitKard[0;1m ---[m
[[1;34mINFO[m] Changes detected - recompiling the module!
[[1;33mWARNING[m] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[[1;34mINFO[m] Compiling 53 source files to /var/lib/jenkins/workspace/Test/target/test-classes
[[1;33mWARNING[m] /var/lib/jenkins/workspace/Test/src/test/java/admitKard/testcases/StudentProfileTest.java: /var/lib/jenkins/workspace/Test/src/test/java/admitKard/testcases/StudentProfileTest.java uses unchecked or unsafe operations.
[[1;33mWARNING[m] /var/lib/jenkins/workspace/Test/src/test/java/admitKard/testcases/StudentProfileTest.java: Recompile with -Xlint:unchecked for details.
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-surefire-plugin:3.0.0-M3:test[m [1m(default-test)[m @ [36madmitKard[0;1m ---[m
[[1;34mINFO[m]
[[1;34mINFO[m] -------------------------------------------------------
[[1;34mINFO[m]  T E S T S
[[1;34mINFO[m] -------------------------------------------------------
[[1;34mINFO[m] Running [1mTestSuite[m
Feb 19, 2020 11:39:25 AM org.openqa.selenium.remote.DesiredCapabilities chrome
INFO: Using `new ChromeOptions()` is preferred to `DesiredCapabilities.chrome()`
Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 24340
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
FAILED CONFIGURATION: @BeforeSuite setDriver
org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'latitude-e7450', ip: '192.168.0.72', os.name: 'Linux', os.arch: 'amd64', os.version: '5.3.0-28-generic', java.version: '1.8.0_242'
Driver info: driver.version: Set_Driver
remote stacktrace: #0 0x561a34250d29 <unknown>

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:122)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
    at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:499)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:486)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:531)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:125)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:212)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:157)
    at admitKard.base.BaseUIPage.initWebsiteDriver(BaseUIPage.java:72)
    at admitKard.base.Set_Driver.setDriver(Set_Driver.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:62)
    at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:340)
    at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:294)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:345)
    at org.testng.SuiteRunner.run(SuiteRunner.java:304)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
    at org.testng.TestNG.runSuites(TestNG.java:1032)
    at org.testng.TestNG.run(TestNG.java:1000)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:283)
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:120)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)

SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED: verifyClickRegisterTab
org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'latitude-e7450', ip: '192.168.0.72', os.name: 'Linux', os.arch: 'amd64', os.version: '5.3.0-28-generic', java.version: '1.8.0_242'
Driver info: driver.version: Set_Driver
remote stacktrace: #0 0x561a34250d29 <unknown>

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:122)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
    at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:499)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:486)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:531)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:125)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:212)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:157)
    at admitKard.base.BaseUIPage.initWebsiteDriver(BaseUIPage.java:72)
    at admitKard.base.Set_Driver.setDriver(Set_Driver.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:62)
    at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:340)
    at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:294)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:345)
    at org.testng.SuiteRunner.run(SuiteRunner.java:304)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
    at org.testng.TestNG.runSuites(TestNG.java:1032)
    at org.testng.TestNG.run(TestNG.java:1000)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:283)
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:120)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)
</code>```

This is before suite :-

```<code>`@BeforeSuite
    public void setDriver() throws Exception {

            BaseUIPage bp = new BaseUIPage();

            //Generate HTML Report
            htmlReporter = new ExtentHtmlReporter(new File(System.getProperty("user.dir") + "/AutomationReports.html"));
            htmlReporter.loadXMLConfig(
                    String.valueOf(new File(System.getProperty("user.dir") + "/src/test/resources/runner/extent-config.xml")));
            reports = new ExtentReports();
            reports.setSystemInfo("Environment", "Local");
            reports.setSystemInfo("Website Name", "AdmitKard");
            reports.attachReporter(htmlReporter);

            //Read Data from data properties file
            dataFileProperties = new Properties();
            FileInputStream fis = new FileInputStream(
                    System.getProperty("user.dir") + "/src/test/resources/properties/datafile.properties");
            dataFileProperties.load(fis);

        if (wDriver == null) {
            //Initialize web driver and Launch Website
            WEB_URL = System.getProperty("url");
            BROWSER = System.getProperty("browser");
            if(WEB_URL == null)
            {
                WEB_URL = dataFileProperties.getProperty("URL");
                BROWSER = dataFileProperties.getProperty("browser");
            }
            wDriver = bp.initWebsiteDriver(wDriver, WEB_URL, BROWSER);
        }
            //Set web driver in base UI page
            bp.setWebDriver(wDriver);

        //driver set for multiple browser
        multipleBrowser = System.getProperty("secondBrowser");
//        if(multipleBrowser == null){
//        multipleBrowser = dataFileProperties.getProperty("secondBrowser");}
        if(multipleBrowser!= null && multipleBrowser.equals("true")){
            secondDriver = bp.initWebsiteDriver(secondDriver, WEB_URL, BROWSER);
            bp.setSecondWebDriver(secondDriver);
        }
        //MyScreenRecorder.startRecording("AutomationTest");
     }`
</code>```

This is webdriver initalization code :-

```<code> `public WebDriver initWebsiteDriver(WebDriver cDriver, String WEB_URL, String Browser) throws NullPointerException
    {

        if(Browser.equalsIgnoreCase("Chrome"))
        {
            System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"/browserDriver/chromedriver");

            System.setProperty("webdriver.chrome.logfile", System.getProperty("user.dir")+"/browserDriver/chromedriver.log");
            System.setProperty("webdriver.chrome.verboseLogging", "true");

            //Set path for download file
            String downloadFilepath = System.getProperty("user.dir")+"/src/test/resources/download";
            HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
            chromePrefs.put("profile.default_content_settings.popups", 0);
            chromePrefs.put("download.default_directory", downloadFilepath);
            ChromeOptions options = new ChromeOptions();
            options.setExperimentalOption("prefs", chromePrefs);
            DesiredCapabilities cap = DesiredCapabilities.chrome();
            cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
            cap.setCapability(ChromeOptions.CAPABILITY, options);
            options.setBinary("/usr/bin/google-chrome");
            options.addArguments("--no-sandbox"); //https://stackoverflow.com/a/50725918/1689770
            options.addArguments("disable-features=NetworkService");
            options.addArguments("--disable-dev-shm-usage");
            options.addArguments("--no-sandbox");
            options.addArguments("--remote-debugging-port=9222");
           // ChromeOptions chromeOptions = new ChromeOptions();
            options.addArguments("--disable-notifications");
           // options.addArguments("--headless");
           // options.setHeadless(true);
            options.addArguments("--no-sandbox");
            options.addArguments("--disable-dev-shm-usage");
            cDriver = new ChromeDriver(options);
            //cDriver=new RemoteWebDriver(cap);
        }
        else if(Browser.equalsIgnoreCase("Firefox"))
        {
            System.setProperty("webdriver.gecko.driver",System.getProperty("user.dir")+"/browserDriver/geckodriver");
            FirefoxProfile profile = new FirefoxProfile();
            profile.setPreference("browser.download.dir", System.getProperty("user.dir") + "/src/test/resources/download"
                     + File.separator);

            FirefoxOptions firefoxOptions = new FirefoxOptions();
            firefoxOptions.setProfile(profile);

            //firefoxOptions.addPreference("dom.webnotifications.enabled",false);
            cDriver = new FirefoxDriver(firefoxOptions);
        }
        else if(Browser.equalsIgnoreCase("safari"))
        {
            cDriver = new SafariDriver();
        }
        cDriver.manage().window().setSize(new Dimension(1680, 900));
        cDriver.get(WEB_URL);
        cDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        return cDriver;
    }`
</code>```

答:
Add

```<code>--remote-debugging-port=9222
</code>```

to your chrome driver options

Body:
Unable to launch chrome via chrome webdriver on jenkins where as it works fine on my local machine. I have tried everything that is on there on the internet to solve this problem but unable to get out of this loop hole. Though it's very much irritating I have wasted a lot of time kindly help if anyone out there is familiar of this problem. As I am new to selenium testing this is very frustrating issue.

Running as SYSTEM
Building in workspace /var/lib/jenkins/workspace/Test
`using credential 9917dab9-de45-43b7-8ff2-0c2b530a0ecf
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url https://bitbucket.org/admitkard/akd_e2e.git # timeout=10
Fetching upstream changes from https://bitbucket.org/admitkard/akd_e2e.git
 > git --version # timeout=10
using GIT_ASKPASS to set credentials
 > git fetch --tags --progress -- https://bitbucket.org/admitkard/akd_e2e.git +refs/heads/*:refs/remotes/origin/* # timeout=10
 > git rev-parse refs/remotes/origin/pawan^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/pawan^{commit} # timeout=10
Checking out Revision 10f6281f501136b9ffcd504f4d8f3a54568d1162 (refs/remotes/origin/pawan)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 10f6281f501136b9ffcd504f4d8f3a54568d1162 # timeout=10
Commit message: "Hi"
 > git rev-list --no-walk 10f6281f501136b9ffcd504f4d8f3a54568d1162 # timeout=10
[Test] $ /bin/sh -xe /tmp/jenkins5524615085827631447.sh
+ echo /var/lib/jenkins/workspace/Test
/var/lib/jenkins/workspace/Test
+ cd /var/lib/jenkins/workspace/Test/
+ mvn clean test -DtestngFile=testng/signupTestng.xml -Durl=https://dev.admitkard.net/ -Dbrowser=chrome
[[1;34mINFO[m] Scanning for projects...
[[1;33mWARNING[m]
[[1;33mWARNING[m] Some problems were encountered while building the effective model for com.example.admitKard:admitKard:jar:1.0-SNAPSHOT
[[1;33mWARNING[m] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 27, column 21
[[1;33mWARNING[m]
[[1;33mWARNING[m] It is highly recommended to fix these problems because they threaten the stability of your build.
[[1;33mWARNING[m]
[[1;33mWARNING[m] For this reason, future Maven versions might no longer support building such malformed projects.
[[1;33mWARNING[m]
[[1;34mINFO[m]
[[1;34mINFO[m] [1m------------------< [0;36mcom.example.admitKard:admitKard[0;1m >-------------------[m
[[1;34mINFO[m] [1mBuilding admitKard 1.0-SNAPSHOT[m
[[1;34mINFO[m] [1m--------------------------------[ jar ]---------------------------------[m
[[1;33mWARNING[m] The artifact org.apache.commons:commons-io:jar:1.3.2 has been relocated to commons-io:commons-io:jar:1.3.2
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-clean-plugin:2.5:clean[m [1m(default-clean)[m @ [36madmitKard[0;1m ---[m
[[1;34mINFO[m] Deleting /var/lib/jenkins/workspace/Test/target
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-resources-plugin:2.6:resources[m [1m(default-resources)[m @ [36madmitKard[0;1m ---[m
[[1;33mWARNING[m] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[[1;34mINFO[m] skip non existing resourceDirectory /var/lib/jenkins/workspace/Test/src/main/resources
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-compiler-plugin:3.1:compile[m [1m(default-compile)[m @ [36madmitKard[0;1m ---[m
[[1;34mINFO[m] No sources to compile
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-resources-plugin:2.6:testResources[m [1m(default-testResources)[m @ [36madmitKard[0;1m ---[m
[[1;33mWARNING[m] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[[1;34mINFO[m] Copying 16 resources
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-compiler-plugin:3.1:testCompile[m [1m(default-testCompile)[m @ [36madmitKard[0;1m ---[m
[[1;34mINFO[m] Changes detected - recompiling the module!
[[1;33mWARNING[m] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[[1;34mINFO[m] Compiling 53 source files to /var/lib/jenkins/workspace/Test/target/test-classes
[[1;33mWARNING[m] /var/lib/jenkins/workspace/Test/src/test/java/admitKard/testcases/StudentProfileTest.java: /var/lib/jenkins/workspace/Test/src/test/java/admitKard/testcases/StudentProfileTest.java uses unchecked or unsafe operations.
[[1;33mWARNING[m] /var/lib/jenkins/workspace/Test/src/test/java/admitKard/testcases/StudentProfileTest.java: Recompile with -Xlint:unchecked for details.
[[1;34mINFO[m]
[[1;34mINFO[m] [1m--- [0;32mmaven-surefire-plugin:3.0.0-M3:test[m [1m(default-test)[m @ [36madmitKard[0;1m ---[m
[[1;34mINFO[m]
[[1;34mINFO[m] -------------------------------------------------------
[[1;34mINFO[m]  T E S T S
[[1;34mINFO[m] -------------------------------------------------------
[[1;34mINFO[m] Running [1mTestSuite[m
Feb 19, 2020 11:39:25 AM org.openqa.selenium.remote.DesiredCapabilities chrome
INFO: Using `new ChromeOptions()` is preferred to `DesiredCapabilities.chrome()`
Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 24340
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
FAILED CONFIGURATION: @BeforeSuite setDriver
org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'latitude-e7450', ip: '192.168.0.72', os.name: 'Linux', os.arch: 'amd64', os.version: '5.3.0-28-generic', java.version: '1.8.0_242'
Driver info: driver.version: Set_Driver
remote stacktrace: #0 0x561a34250d29 <unknown>

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:122)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
    at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:499)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:486)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:531)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:125)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:212)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:157)
    at admitKard.base.BaseUIPage.initWebsiteDriver(BaseUIPage.java:72)
    at admitKard.base.Set_Driver.setDriver(Set_Driver.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:62)
    at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:340)
    at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:294)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:345)
    at org.testng.SuiteRunner.run(SuiteRunner.java:304)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
    at org.testng.TestNG.runSuites(TestNG.java:1032)
    at org.testng.TestNG.run(TestNG.java:1000)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:283)
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:120)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)

SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED CONFIGURATION: @BeforeMethod register
SKIPPED CONFIGURATION: @AfterMethod afterMethod
SKIPPED: verifyClickRegisterTab
org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'latitude-e7450', ip: '192.168.0.72', os.name: 'Linux', os.arch: 'amd64', os.version: '5.3.0-28-generic', java.version: '1.8.0_242'
Driver info: driver.version: Set_Driver
remote stacktrace: #0 0x561a34250d29 <unknown>

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:122)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
    at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:499)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:486)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:531)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:125)
    at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:212)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:157)
    at admitKard.base.BaseUIPage.initWebsiteDriver(BaseUIPage.java:72)
    at admitKard.base.Set_Driver.setDriver(Set_Driver.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:62)
    at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:340)
    at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:294)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:345)
    at org.testng.SuiteRunner.run(SuiteRunner.java:304)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
    at org.testng.TestNG.runSuites(TestNG.java:1032)
    at org.testng.TestNG.run(TestNG.java:1000)
    at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:283)
    at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
    at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:120)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)

This is before suite :-

`@BeforeSuite
    public void setDriver() throws Exception {

            BaseUIPage bp = new BaseUIPage();

            //Generate HTML Report
            htmlReporter = new ExtentHtmlReporter(new File(System.getProperty("user.dir") + "/AutomationReports.html"));
            htmlReporter.loadXMLConfig(
                    String.valueOf(new File(System.getProperty("user.dir") + "/src/test/resources/runner/extent-config.xml")));
            reports = new ExtentReports();
            reports.setSystemInfo("Environment", "Local");
            reports.setSystemInfo("Website Name", "AdmitKard");
            reports.attachReporter(htmlReporter);

            //Read Data from data properties file
            dataFileProperties = new Properties();
            FileInputStream fis = new FileInputStream(
                    System.getProperty("user.dir") + "/src/test/resources/properties/datafile.properties");
            dataFileProperties.load(fis);

        if (wDriver == null) {
            //Initialize web driver and Launch Website
            WEB_URL = System.getProperty("url");
            BROWSER = System.getProperty("browser");
            if(WEB_URL == null)
            {
                WEB_URL = dataFileProperties.getProperty("URL");
                BROWSER = dataFileProperties.getProperty("browser");
            }
            wDriver = bp.initWebsiteDriver(wDriver, WEB_URL, BROWSER);
        }
            //Set web driver in base UI page
            bp.setWebDriver(wDriver);

        //driver set for multiple browser
        multipleBrowser = System.getProperty("secondBrowser");
//        if(multipleBrowser == null){
//        multipleBrowser = dataFileProperties.getProperty("secondBrowser");}
        if(multipleBrowser!= null && multipleBrowser.equals("true")){
            secondDriver = bp.initWebsiteDriver(secondDriver, WEB_URL, BROWSER);
            bp.setSecondWebDriver(secondDriver);
        }
        //MyScreenRecorder.startRecording("AutomationTest");
     }`

This is webdriver initalization code :-

 `public WebDriver initWebsiteDriver(WebDriver cDriver, String WEB_URL, String Browser) throws NullPointerException
    {

        if(Browser.equalsIgnoreCase("Chrome"))
        {
            System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"/browserDriver/chromedriver");

            System.setProperty("webdriver.chrome.logfile", System.getProperty("user.dir")+"/browserDriver/chromedriver.log");
            System.setProperty("webdriver.chrome.verboseLogging", "true");

            //Set path for download file
            String downloadFilepath = System.getProperty("user.dir")+"/src/test/resources/download";
            HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
            chromePrefs.put("profile.default_content_settings.popups", 0);
            chromePrefs.put("download.default_directory", downloadFilepath);
            ChromeOptions options = new ChromeOptions();
            options.setExperimentalOption("prefs", chromePrefs);
            DesiredCapabilities cap = DesiredCapabilities.chrome();
            cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
            cap.setCapability(ChromeOptions.CAPABILITY, options);
            options.setBinary("/usr/bin/google-chrome");
            options.addArguments("--no-sandbox"); //https://stackoverflow.com/a/50725918/1689770
            options.addArguments("disable-features=NetworkService");
            options.addArguments("--disable-dev-shm-usage");
            options.addArguments("--no-sandbox");
            options.addArguments("--remote-debugging-port=9222");
           // ChromeOptions chromeOptions = new ChromeOptions();
            options.addArguments("--disable-notifications");
           // options.addArguments("--headless");
           // options.setHeadless(true);
            options.addArguments("--no-sandbox");
            options.addArguments("--disable-dev-shm-usage");
            cDriver = new ChromeDriver(options);
            //cDriver=new RemoteWebDriver(cap);
        }
        else if(Browser.equalsIgnoreCase("Firefox"))
        {
            System.setProperty("webdriver.gecko.driver",System.getProperty("user.dir")+"/browserDriver/geckodriver");
            FirefoxProfile profile = new FirefoxProfile();
            profile.setPreference("browser.download.dir", System.getProperty("user.dir") + "/src/test/resources/download"
                     + File.separator);

            FirefoxOptions firefoxOptions = new FirefoxOptions();
            firefoxOptions.setProfile(profile);

            //firefoxOptions.addPreference("dom.webnotifications.enabled",false);
            cDriver = new FirefoxDriver(firefoxOptions);
        }
        else if(Browser.equalsIgnoreCase("safari"))
        {
            cDriver = new SafariDriver();
        }
        cDriver.manage().window().setSize(new Dimension(1680, 900));
        cDriver.get(WEB_URL);
        cDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        return cDriver;
    }`

Body:
Add

--remote-debugging-port=9222

to your chrome driver options


来源: stackexchange

问:
Not able to filter elements using an enum
```<code>protected static double averagePrice( List<ComputerComponent> list ) {
    return  list.stream()
            //  .filter( line-> EnumUtils.isValidEnum(ComputerComponentCategory.class, line.getCategory()) )

            //  .filter( line-> isInEnum( line.getCategory(), ComputerComponentCategory.class) )
            //   .filter( line->  inEnum(line.getCategory(),EnumUtils.getEnumMap(ComputerComponentCategory.class ).keySet() ))
                .filter(    line ->
                        line.getCategory().contains("CPU")
                        || line.getCategory().contains("GPU")
                        || line.getCategory().contains("Monitor")
                        || line.getCategory().contains("Keyboard")
                        || line.getCategory().contains("Mouse")
                        || line.getCategory().contains("Storage")
                        || line.getCategory().contains("Memory"))
               .mapToDouble(ComputerComponent::getPrice)
               .average()
               .orElseThrow(NoSuchElementException:: new);
    }
</code>```

I have an enum as

public enum ComputerComponentCategory {

    CPU("CPU"),
    MONITOR("Monitor"),
    KEYBOARD("Keyboard"),
    MOUSE("Mouse"),
    GPU("GPU"),
    MEMORY("Memory"),
    STORAGE("Storage"),
    NULL("NOT DEFINED");

    private String label;

    ComputerComponentCategory(String label) {
        this.label = label;
    }

    public String getLabel() {
        return this.label;
    }

    public static ComputerComponentCategory getValue(String label) {

        switch(label) {
            case "CPU":
                return CPU;
            case "Monitor":
                return MONITOR;
            case "Keyboard":
                return KEYBOARD;
            case "Mouse":
                return MOUSE;
            case "GPU":
                return GPU;
            case "Memory":
                return MEMORY;
            case "Storage":
                return STORAGE;
            default:
                return NULL ;
        }

    }
}
```

<p>I pass a list of ComputerComponent class to the averagePrice() function which has two fields of price
    which is of type double and
    category which is of type String. </p>

<p>My list has 4 elements with categories as "CPU", "Mouse",
    "Keyboard" and "Storage" with their respective prices as 34.0, 155.0, 23.0 and 75.0.   </p>

<p>When I try to use inEnum(), isInEnum() or EnumUtils.isValidEnum() functions, I get the average price
    as 34.0 which I think that they just return the price of the first element rather than the average. </p>

```But when I do filtering using

                            .filter(    line ->
                        line.getCategory().contains("CPU")
                        || line.getCategory().contains("GPU")
                        || line.getCategory().contains("Monitor")
                        || line.getCategory().contains("Keyboard")
                        || line.getCategory().contains("Mouse")
                        || line.getCategory().contains("Storage")
                        || line.getCategory().contains("Memory"))
```

<p>I get the correct average value of 71.75. </p>

<p>The implementations that I have used for isInEnum() and inEnum() functions are the following: </p>

```public static <E extends Enum<E>> boolean isInEnum(String value, Class<E> enumClass) {
      for (E e : enumClass.getEnumConstants()) {
        if(e.name().contains(value)) { return true; }
      }
      return false;
    }

public static boolean inEnum ( String category, Set<String> value ) {
    for(String s: value ) {
    if ( category.contains(s) ) {
        return true ;
    }
    }
    return false ;
}
```

How can I use enums correctly with java streams to filter by valid category names and get the correct
    average value of price?

What mistake I am making when using streams and its functions ?

答:
You could simply use your ComputerCategoryValue.getValue method and check for null, given the category of line:

```<code>public class EnumTest {

    @Test
    public void testBothMethods() {
        final ComputerComponent c1 = new ComputerComponent(ComputerComponentCategory.CPU.getLabel(), 12.21);
        final ComputerComponent c2 = new ComputerComponent(ComputerComponentCategory.MEMORY.getLabel(), 23.45);
        final List<ComputerComponent> list = Arrays.asList(c1, c2);

        assertEquals(averagePriceWithFilter(list), averagePriceWithInEnum(list), 0.01);
    }

    protected static double averagePriceWithFilter(final List<ComputerComponent> list) {
        return list.stream()
                .filter(line -> line.getCategory().contains("CPU")
                        || line.getCategory().contains("GPU")
                        || line.getCategory().contains("Monitor")
                        || line.getCategory().contains("Keyboard")
                        || line.getCategory().contains("Mouse")
                        || line.getCategory().contains("Storage")
                        || line.getCategory().contains("Memory"))
                .mapToDouble(ComputerComponent::getPrice)
                .average()
                .orElseThrow(NoSuchElementException::new);
    }

    protected static double averagePriceWithInEnum(final List<ComputerComponent> list) {
        return list.stream()
                .filter(line -> ComputerComponentCategory.getValue(line.getCategory()) != null)
                .mapToDouble(ComputerComponent::getPrice)
                .average()
                .orElseThrow(NoSuchElementException::new);
    }
}
</code>```

EDIT: explaining your mistakes:

EnumUtils.getEnumMap(ComputerComponentCategory.class).keySet()) returns a map of the enum name (not its label), so that the check will only work for CPU as there name and label are the same.

Same for the other method!

You need to use getLabel() instead of name() or use equalsIgnoreCase instead of contains.

ContentLicense: CC BY-SA 4.0

Body:
protected static double averagePrice( List<ComputerComponent> list ) {
    return  list.stream()
            //  .filter( line-> EnumUtils.isValidEnum(ComputerComponentCategory.class, line.getCategory()) )

            //  .filter( line-> isInEnum( line.getCategory(), ComputerComponentCategory.class) )
            //   .filter( line->  inEnum(line.getCategory(),EnumUtils.getEnumMap(ComputerComponentCategory.class ).keySet() ))
                .filter(    line ->
                        line.getCategory().contains("CPU")
                        || line.getCategory().contains("GPU")
                        || line.getCategory().contains("Monitor")
                        || line.getCategory().contains("Keyboard")
                        || line.getCategory().contains("Mouse")
                        || line.getCategory().contains("Storage")
                        || line.getCategory().contains("Memory"))
               .mapToDouble(ComputerComponent::getPrice)
               .average()
               .orElseThrow(NoSuchElementException:: new);
    }

I have an enum as

public enum ComputerComponentCategory {

    CPU("CPU"),
    MONITOR("Monitor"),
    KEYBOARD("Keyboard"),
    MOUSE("Mouse"),
    GPU("GPU"),
    MEMORY("Memory"),
    STORAGE("Storage"),
    NULL("NOT DEFINED");

    private String label;

    ComputerComponentCategory(String label) {
        this.label = label;
    }

    public String getLabel() {
        return this.label;
    }

    public static ComputerComponentCategory getValue(String label) {

        switch(label) {
            case "CPU":
                return CPU;
            case "Monitor":
                return MONITOR;
            case "Keyboard":
                return KEYBOARD;
            case "Mouse":
                return MOUSE;
            case "GPU":
                return GPU;
            case "Memory":
                return MEMORY;
            case "Storage":
                return STORAGE;
            default:
                return NULL ;
        }

    }
}

I pass a list of ComputerComponent class to the averagePrice() function which has two fields of price
    which is of type double and
    category which is of type String.

My list has 4 elements with categories as "CPU", "Mouse",
    "Keyboard" and "Storage" with their respective prices as 34.0, 155.0, 23.0 and 75.0.

When I try to use inEnum(), isInEnum() or EnumUtils.isValidEnum() functions, I get the average price
    as 34.0 which I think that they just return the price of the first element rather than the average.

But when I do filtering using

                            .filter(    line ->
                        line.getCategory().contains("CPU")
                        || line.getCategory().contains("GPU")
                        || line.getCategory().contains("Monitor")
                        || line.getCategory().contains("Keyboard")
                        || line.getCategory().contains("Mouse")
                        || line.getCategory().contains("Storage")
                        || line.getCategory().contains("Memory"))

I get the correct average value of 71.75.

The implementations that I have used for isInEnum() and inEnum() functions are the following:

public static <E extends Enum<E>> boolean isInEnum(String value, Class<E> enumClass) {
      for (E e : enumClass.getEnumConstants()) {
        if(e.name().contains(value)) { return true; }
      }
      return false;
    }

public static boolean inEnum ( String category, Set<String> value ) {
    for(String s: value ) {
    if ( category.contains(s) ) {
        return true ;
    }
    }
    return false ;
}

How can I use enums correctly with java streams to filter by valid category names and get the correct
    average value of price?

What mistake I am making when using streams and its functions ?

Body:
You could simply use your ComputerCategoryValue.getValue method and check for null, given the category of line:

public class EnumTest {

    @Test
    public void testBothMethods() {
        final ComputerComponent c1 = new ComputerComponent(ComputerComponentCategory.CPU.getLabel(), 12.21);
        final ComputerComponent c2 = new ComputerComponent(ComputerComponentCategory.MEMORY.getLabel(), 23.45);
        final List<ComputerComponent> list = Arrays.asList(c1, c2);

        assertEquals(averagePriceWithFilter(list), averagePriceWithInEnum(list), 0.01);
    }

    protected static double averagePriceWithFilter(final List<ComputerComponent> list) {
        return list.stream()
                .filter(line -> line.getCategory().contains("CPU")
                        || line.getCategory().contains("GPU")
                        || line.getCategory().contains("Monitor")
                        || line.getCategory().contains("Keyboard")
                        || line.getCategory().contains("Mouse")
                        || line.getCategory().contains("Storage")
                        || line.getCategory().contains("Memory"))
                .mapToDouble(ComputerComponent::getPrice)
                .average()
                .orElseThrow(NoSuchElementException::new);
    }

    protected static double averagePriceWithInEnum(final List<ComputerComponent> list) {
        return list.stream()
                .filter(line -> ComputerComponentCategory.getValue(line.getCategory()) != null)
                .mapToDouble(ComputerComponent::getPrice)
                .average()
                .orElseThrow(NoSuchElementException::new);
    }
}

EDIT: explaining your mistakes:

EnumUtils.getEnumMap(ComputerComponentCategory.class).keySet()) returns a map of the enum name (not its label), so that the check will only work for CPU as there name and label are the same.

Same for the other method!

You need to use getLabel() instead of name() or use equalsIgnoreCase instead of contains.


问:
How to choose the data structure for finding sentences with only known words
I am working on a language learning program. The program tracks the words it thinks a user knows, and I want to add a feature where I show the user sentences that they should be able to read.

I have a large data set of tokenized sentences, but I'm struggling to come up with the right data structure to make filtering this list fast enough. My first pass was just iterating through it all every time a user learns a new word, but this is proving to be too slow, especially since a user often learns several words during a session. Furthermore, the list of sentences changes over time, either as the user adds sentences of their own or my global database of sentences has sentences added/removed/updated.

What is a good data structure for making this search fast while supporting the dynamic nature of the data? That is, given the set of words the user knows, and a whole ton of tokenized and perhaps further pre-processed sentences, I want to quickly find the sentences that the user should be able to read all of the words in.

答:
You could use a tree of letters. A node would consist of the following members:

the letter

whether it is the end of a word

For example, on root level you would have a node 'a' which is a word of its own. One of its children would be 's', which is a word of its own as well, because reading it together with its parent you get 'as' and so on. Finding a word in this tree would take maximum 26 + length-of-the-word - 1.


问:
How do I return to previous state in reactjs?
I have created a sidebar component and set its state to false to hide the block until a user clicks on the hanmburger icon, then the state is shown. However I am trying to return(or close the sidebar menu) when the user clicks on the close 'X' icon. I have written a hideMenu method to return the state to false however it doesnt work, and there are no errors.
 Here is what I have written</p>

```<code>class SubMainNavbar extends React.Component{
  constructor(){
    super();
    this.state = {isShown:false}
    this.showMenu = this.showMenu.bind(this)
    this.hideMenu = this.hideMenu.bind(this)
  }

  showMenu(){
    this.setState({isShown: true})
  }

  hideMenu(){
   this.setState({isShown: false})
  }
  render() {
    return (
      <div className="sub-flex-container">
        <div className="co pt-4">
      <ul className="flex-container sub-list">
        <li>women</li>
        <li>mens</li>
        <li>health & beauty</li>
      </ul>
      <span onClick={this.showMenu} className="pl-3 hamburger hide-big pb-4"><Icon type="menu" />
      <div className="mobile-menu-display" id="mySidebar" style={{display: this.state.isShown ? 'block' : 'none' }}>
        <span onClick={this.hideMenu} className="float-right font-weight-bold hide-big close">X</span>
      </div>
      </span>

    </div>

    <div className="co">
    {/* <a href=""><Logo className="logo" /></a> */}
    <a href=""><img className="img-fluid logo" src={Logo} alt="losode logo"/></a>
    </div>

    <div className="co pt-4">
    <span className="hide-small"><SearchInput /></span>
    <div className="icon-mobile hide-big">
      <ul className="flex-icon sub-flex-container">
        <li><ion-icon name="search-outline"></ion-icon></li>
        <li><ion-icon name="person-outline"></ion-icon></li>
      <li><ion-icon name="basket-outline"></ion-icon></li>
      </ul>
    </div>
    </div>

    </div>
    );
  }
};

export default SubMainNavbar
</code>```

答:
really weird but could you try imitating what I did in this code sandbox?
https://codesandbox.io/s/heuristic-fire-2jp8n?fontsize=14&hidenavigation=1&theme=dark

that should be as simple as it gets

Body:
I have created a sidebar component and set its state to false to hide the block until a user clicks on the hanmburger icon, then the state is shown. However I am trying to return(or close the sidebar menu) when the user clicks on the close 'X' icon. I have written a hideMenu method to return the state to false however it doesnt work, and there are no errors.
 Here is what I have written

class SubMainNavbar extends React.Component{
  constructor(){
    super();
    this.state = {isShown:false}
    this.showMenu = this.showMenu.bind(this)
    this.hideMenu = this.hideMenu.bind(this)
  }

  showMenu(){
    this.setState({isShown: true})
  }

  hideMenu(){
   this.setState({isShown: false})
  }
  render() {
    return (

women

mens

health & beauty

      <Icon type="menu" />

        X

    {/* <Logo className="logo" /> */}

    <SearchInput />

<ion-icon name="search-outline"></ion-icon>

<ion-icon name="person-outline"></ion-icon>

<ion-icon name="basket-outline"></ion-icon>

    );
  }
};

export default SubMainNavbar


答:
Your span, which you click to hide the menu, is inside the span, which triggers the showMenu function. You need to call the hideMenu function with the event parameter and use the stopPropagation function in your hideMenu function before setting the state. So the click of the span outside is not triggert and just the inner span will receive the click.

```<code>class SubMainNavbar extends React.Component{
  constructor(){
    super();
    this.state = {isShown:false}
    this.showMenu = this.showMenu.bind(this)
    this.hideMenu = this.hideMenu.bind(this)
  }

  showMenu(){
    this.setState({isShown: true})
  }

  hideMenu(event){
   event.stopPropagation()
   this.setState({isShown: false})
  }
  render() {
    return (
      <div className="sub-flex-container">
        <div className="co pt-4">
      <ul className="flex-container sub-list">
        <li>women</li>
        <li>mens</li>
        <li>health & beauty</li>
      </ul>
      <span onClick={this.showMenu} className="pl-3 hamburger hide-big pb-4"><Icon type="menu" />
        <div className="mobile-menu-display" id="mySidebar" style={{display: this.state.isShown ? 'block' : 'none' }}>
          <span onClick={event => this.hideMenu(event)} className="float-right font-weight-bold hide-big close">X</span>
        </div>
      </span>

    </div>

    <div className="co">
    {/* <a href=""><Logo className="logo" /></a> */}
    <a href=""><img className="img-fluid logo" src={Logo} alt="losode logo"/></a>
    </div>

    <div className="co pt-4">
    <span className="hide-small"><SearchInput /></span>
    <div className="icon-mobile hide-big">
      <ul className="flex-icon sub-flex-container">
        <li><ion-icon name="search-outline"></ion-icon></li>
        <li><ion-icon name="person-outline"></ion-icon></li>
      <li><ion-icon name="basket-outline"></ion-icon></li>
      </ul>
    </div>
    </div>

    </div>
    );
  }
};

export default SubMainNavbar
</code>```

ps: You can use arrow functions so you don't need to use a constructor.

For example:

```<code>  this.state = { isShown: false }

  showMenu = () => {
    this.setState({isShown: true})
  }

  hideMenu = event => {
   event.stopPropagation()
   this.setState({isShown: false})
  }

</code>```

Title: How do I return to previous state in reactjs?

Body:
Your span, which you click to hide the menu, is inside the span, which triggers the showMenu function. You need to call the hideMenu function with the event parameter and use the stopPropagation function in your hideMenu function before setting the state. So the click of the span outside is not triggert and just the inner span will receive the click.

class SubMainNavbar extends React.Component{
  constructor(){
    super();
    this.state = {isShown:false}
    this.showMenu = this.showMenu.bind(this)
    this.hideMenu = this.hideMenu.bind(this)
  }

  showMenu(){
    this.setState({isShown: true})
  }

  hideMenu(event){
   event.stopPropagation()
   this.setState({isShown: false})
  }
  render() {
    return (
      <div className="sub-flex-container">
        <div className="co pt-4">
      <ul className="flex-container sub-list">
        <li>women</li>
        <li>mens</li>
        <li>health & beauty</li>
      </ul>
      <span onClick={this.showMenu} className="pl-3 hamburger hide-big pb-4"><Icon type="menu" />
        <div className="mobile-menu-display" id="mySidebar" style={{display: this.state.isShown ? 'block' : 'none' }}>
          <span onClick={event => this.hideMenu(event)} className="float-right font-weight-bold hide-big close">X</span>
        </div>
      </span>

    </div>

    <div className="co">
    {/* <a href=""><Logo className="logo" /></a> */}
    <a href=""><img className="img-fluid logo" src={Logo} alt="losode logo"/></a>
    </div>

    <div className="co pt-4">
    <span className="hide-small"><SearchInput /></span>
    <div className="icon-mobile hide-big">
      <ul className="flex-icon sub-flex-container">
        <li><ion-icon name="search-outline"></ion-icon></li>
        <li><ion-icon name="person-outline"></ion-icon></li>
      <li><ion-icon name="basket-outline"></ion-icon></li>
      </ul>
    </div>
    </div>

    </div>
    );
  }
};

export default SubMainNavbar

ps: You can use arrow functions so you don't need to use a constructor.

For example:

  this.state = { isShown: false }

  showMenu = () => {
    this.setState({isShown: true})
  }

  hideMenu = event => {
   event.stopPropagation()
   this.setState({isShown: false})
  }


问:
Get duration between two dates (Moment JS)
I have 2 dates. And need to find duration between them in this format ${y}year ${w}weeks ${d}d

For this I created function. Here is code

```<code> setTotalDuration(): void {
    const formattedFrom = moment(this.startDate).format('YYYY-MM-DD HH:mm:ss');
    const formattedTo = moment(this.endDate).format('YYYY-MM-DD HH:mm:ss');
    const duration = moment.duration(moment(formattedTo).diff(moment(formattedFrom)));
    const y = Math.floor(duration.asYears());
    const w = Math.floor(duration.asWeeks() - y * moment().weeksInYear());
    const d = Math.floor(duration.asDays() - w * 7);
    this.totalDuration = ` ${y}year ${w}weeks ${d}d`;
}
</code>```

it works not correctly,  now if I pass for example startDate - 19/02/2020 and endDate - 19/02/2021, I get duration  - 1year -1weeks 373d. But I need to get 1year 0weeks 0d

Where is my problem?

答:
I hope this is what you wanted.
You could get the difference in years and add that to the initial date; then get the difference in weeks and add that to the initial date again.

```<code>
var moment = require("moment");

var a = moment(["2021", "02", "20"]);
var b = moment(["2020", "02", "19"]);

var years = a.diff(b, "year");
b.add(years, "years");

var weeks = a.diff(b, "week");
b.add(weeks, "weeks");

var days = a.diff(b, "days");

console.log(years + " years " + weeks + " weeks " + days + " days");

</code>```

Sandbox: https://codesandbox.io/s/compassionate-bas-fg1c2

Body:
I have 2 dates. And need to find duration between them in this format ${y}year ${w}weeks ${d}d

For this I created function. Here is code

 setTotalDuration(): void {
    const formattedFrom = moment(this.startDate).format('YYYY-MM-DD HH:mm:ss');
    const formattedTo = moment(this.endDate).format('YYYY-MM-DD HH:mm:ss');
    const duration = moment.duration(moment(formattedTo).diff(moment(formattedFrom)));
    const y = Math.floor(duration.asYears());
    const w = Math.floor(duration.asWeeks() - y * moment().weeksInYear());
    const d = Math.floor(duration.asDays() - w * 7);
    this.totalDuration = ` ${y}year ${w}weeks ${d}d`;
}

it works not correctly,  now if I pass for example startDate - 19/02/2020 and endDate - 19/02/2021, I get duration  - 1year -1weeks 373d. But I need to get 1year 0weeks 0d

Where is my problem?

Body:
I hope this is what you wanted.
You could get the difference in years and add that to the initial date; then get the difference in weeks and add that to the initial date again.

var moment = require("moment");

var a = moment(["2021", "02", "20"]);
var b = moment(["2020", "02", "19"]);

var years = a.diff(b, "year");
b.add(years, "years");

var weeks = a.diff(b, "week");
b.add(weeks, "weeks");

var days = a.diff(b, "days");

console.log(years + " years " + weeks + " weeks " + days + " days");

Sandbox: https://codesandbox.io/s/compassionate-bas-fg1c2


问:
How to pass value given by javascript variables to PHP variables?
I want the variables like screen width screen height color depth and pixel depth to be used in a PHP function. Basically what I want to do is when user come in my webpage eg:localhost/try.php I want to know all above mentioned details of client without setting cookies or session properties or get parameters. Yeah and of course without reloading the page. I know php but not AJAX so can anyone help me with that?

答:
if i understood it right, your question is When user comes to your page(e.g try.php)how to pass javascript variable(e.g screen.width screen.height) to PHP section so that you can make it as a PHP variable.

Here is a working solution.

try.php

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
    <form action="" method="POST" name="myForm" id="myForm">
        <input type="hidden" id="screenWidth" name="screenWidth">
        <input type="hidden" id="screenHeight" name="screenHeight">
    </form>

    <script type="text/javascript">
        document.getElementById("screenWidth").value = screen.width;
        document.getElementById("screenHeight").value = screen.height;

        function autoSubmit ()
        {
            let form = document.getElementById("myForm");
            form.submit();
        }
        window.onload = autoSubmit;
    </script>
</body>
</html>

<?php
    if($_SERVER["REQUEST_METHOD"] === 'POST')
    {
        if(!empty($_POST["screenWidth"]))
        {
            $screenWidth = $_POST["screenWidth"];
            echo $screenWidth; // see if it gets the screen.width
        }
        if(!empty($_POST["screenHeight"]))
        {
            $screenHeight = $_POST["screenHeight"];
            echo $screenHeight; // see if it gets the screen.height
        }
    }
?>
</code>```

It basically manipulate the DOM and change the value of input value to be the screen.width and screen.height and then submit the form automatically when the window is onload.

If the the server received an HTTP POST method input then it checks the name of the POST inputs and save it into each PHP variables.

Body:
if i understood it right, your question is When user comes to your page(e.g try.php)how to pass javascript variable(e.g screen.width screen.height) to PHP section so that you can make it as a PHP variable.

Here is a working solution.

try.php

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <form action="" method="POST" name="myForm" id="myForm">
        <input type="hidden" id="screenWidth" name="screenWidth">
        <input type="hidden" id="screenHeight" name="screenHeight">
    </form>

    <script type="text/javascript">
        document.getElementById("screenWidth").value = screen.width;
        document.getElementById("screenHeight").value = screen.height;

        function autoSubmit ()
        {
            let form = document.getElementById("myForm");
            form.submit();
        }
        window.onload = autoSubmit;
    </script>
</body>
</html>

<?php
    if($_SERVER["REQUEST_METHOD"] === 'POST')
    {
        if(!empty($_POST["screenWidth"]))
        {
            $screenWidth = $_POST["screenWidth"];
            echo $screenWidth; // see if it gets the screen.width
        }
        if(!empty($_POST["screenHeight"]))
        {
            $screenHeight = $_POST["screenHeight"];
            echo $screenHeight; // see if it gets the screen.height
        }
    }
?>

It basically manipulate the DOM and change the value of input value to be the screen.width and screen.height and then submit the form automatically when the window is onload.

If the the server received an HTTP POST method input then it checks the name of the POST inputs and save it into each PHP variables.


问:
Two-way binding with Vuex
I have a state variable in store Vuex like this:

```<code>let state = {
    order: {
        payment_method: 'Credit card',
    }
};

export default state;
</code>```

Then, my template:

```<code><select id="payment_method" class="w-full form-control form-select"
        v-model="order.payment_method">
    <option value="Credit Card">Credit Card</option>
    <option value="COD">COD</option>
</select>
</code>```

When I change my select option, my state order will be updated. However, should I do that, because when I read the Vuex store principle, it said I shouldn't update the state value directly? Is that the way I am doing in the above code?

If I shouldn't do that, how will I get the value from the selection option?

答:
Exactly you shouldn't manipulate your vuex state directly. You can use Vuex Actions , Vuex Mutations and Vuex Getters to work with the state. Also in your component you could use computed Properties to get/set Vuex State data safely.

Use a computed property

In your template you could use a computed property and specificially define get and set methods for to wrap the store logic within.

```<code><select v-model="paymentMethod">
    <option value="Credit Card">Credit Card</option>
    <option value="COD">COD</option>
</select>

{
  computed : {
    paymentMethod : {
      get() { return this.$store.getters.orderPaymentMethod },
      set(value) { return this.$store.commit('SET_ORDER_PAYMENT_METHOD', value)
    }
}
</code>```

And then use this computed property as v-model for your selection v-model="paymentMethod"

Adding Mutations and Getters to your store

export const SET_ORDER_PAYMENT_METHOD = 'SET_ORDER_PAYMENT_METHOD'
const store = new Vuex.Store({
  state: {
    order: {
      payment_method: 'Credit Card'
    }
  },
  mutations : {
    [SET_ORDER_PAYMENT_METHOD] (state, method) {
       /* optional value validation here */
       state.order.payment_method = method;
    }
  },
  getters: {
    orderPaymentMethod: state => {
      /* optional filtering or else, ... */
      return state.order.payment_method
    }
  }
})
```

Read more about Mutations here https://vuex.vuejs.org/guide/mutations.html

Read more about Getters here https://vuex.vuejs.org/guide/getters.html

Title: Two-way binding with Vuex

Body:
I have a state variable in store Vuex like this:

let state = {
    order: {
        payment_method: 'Credit card',
    }
};

export default state;

Then, my template:

<select id="payment_method" class="w-full form-control form-select"
        v-model="order.payment_method">
    <option value="Credit Card">Credit Card</option>
    <option value="COD">COD</option>
</select>

When I change my select option, my state order will be updated. However, should I do that, because when I read the Vuex store principle, it said I shouldn't update the state value directly? Is that the way I am doing in the above code?

If I shouldn't do that, how will I get the value from the selection option?

Body:
Exactly you shouldn't manipulate your vuex state directly. You can use Vuex Actions , Vuex Mutations and Vuex Getters to work with the state. Also in your component you could use computed Properties to get/set Vuex State data safely.

Use a computed property

In your template you could use a computed property and specificially define get and set methods for to wrap the store logic within.

<select v-model="paymentMethod">
    <option value="Credit Card">Credit Card</option>
    <option value="COD">COD</option>
</select>

{
  computed : {
    paymentMethod : {
      get() { return this.$store.getters.orderPaymentMethod },
      set(value) { return this.$store.commit('SET_ORDER_PAYMENT_METHOD', value)
    }
}

And then use this computed property as v-model for your selection v-model="paymentMethod"

Adding Mutations and Getters to your store

export const SET_ORDER_PAYMENT_METHOD = 'SET_ORDER_PAYMENT_METHOD'
const store = new Vuex.Store({
  state: {
    order: {
      payment_method: 'Credit Card'
    }
  },
  mutations : {
    [SET_ORDER_PAYMENT_METHOD] (state, method) {
       /* optional value validation here */
       state.order.payment_method = method;
    }
  },
  getters: {
    orderPaymentMethod: state => {
      /* optional filtering or else, ... */
      return state.order.payment_method
    }
  }
})

Read more about Mutations here https://vuex.vuejs.org/guide/mutations.html

Read more about Getters here https://vuex.vuejs.org/guide/getters.html


问:
remove inline style properties and add html attributes using php
1) convert

```<code><table style="width: 700px; height: 300px; background-color: #ff0000;" border="0">
</code>```

to

```<code><table width="700" height="300" bgcolor="#ff0000" border="0">
</code>```

2) convert

```<code><table style="width: 700px; background-color: #ff0000;" border="0">
</code>```

to

```<code><table width="700" bgcolor="#ff0000" border="0">
</code>```

I'm using Joomla 1.5.x where in content client can add table or nested tables. Tinymce using inline styles for table dimensions, background properties. But when we try to generate pdf from front end inline styles for table are ignored. Joomla is using TCPDF to generate I've updated the version but same problem. When I've converted the css properties into html attributes, it is generating the table in formated way. So thought to replace all inline styles for table, td, th to html attributes. Tried with many thread from this website but unable to make use of them as I'm poor at regular expressions.

Please any help me in doing so.

Thanks in advance.

答:
I think you can use PHP DOM for this.

1) Use DOMElement::getAttribute() to get the value of attribute style=

2) Use $split = explode(";", $style) to separate those css values

3) With each entry $i of $split, $attributes = explode(":", $split[$i]), in get attribute's name and its value.

4) Now you got $attributes holding 2 values: attribute and value of that attribute.

5) Use DOMElement::setAttribute() to add those values of $attributes.

So, put everything into codes:

```<code>$dom = new DOMDocument();

$dom->loadHTML($html);

$atrvalue= $dom->getAttribute("style");

$split = explode(";", $atrvalue);

for ($i=0; $i<=count($split); $i++) {
    $attribute = explode(":", $split[$i]);
    $node = $doc->createElement("table");
    $newnode = $doc->appendChild($node);
    $newnode->setAttribute($attribute[0], $attribute[1]);
}
</code>```

This way doesn't involve regex :) But you need to modify it in order to fit your context.

ContentLicense: CC BY-SA 3.0

Body:
1) convert

to

2) convert

to

I'm using Joomla 1.5.x where in content client can add table or nested tables. Tinymce using inline styles for table dimensions, background properties. But when we try to generate pdf from front end inline styles for table are ignored. Joomla is using TCPDF to generate I've updated the version but same problem. When I've converted the css properties into html attributes, it is generating the table in formated way. So thought to replace all inline styles for table, td, th to html attributes. Tried with many thread from this website but unable to make use of them as I'm poor at regular expressions.

Please any help me in doing so.

Thanks in advance.

Body:
I think you can use PHP DOM for this.

1) Use DOMElement::getAttribute() to get the value of attribute style=

2) Use $split = explode(";", $style) to separate those css values

3) With each entry $i of $split, $attributes = explode(":", $split[$i]), in get attribute's name and its value.

4) Now you got $attributes holding 2 values: attribute and value of that attribute.

5) Use DOMElement::setAttribute() to add those values of $attributes.

So, put everything into codes:

$dom = new DOMDocument();

$dom->loadHTML($html);

$atrvalue= $dom->getAttribute("style");

$split = explode(";", $atrvalue);

for ($i=0; $i<=count($split); $i++) {
    $attribute = explode(":", $split[$i]);
    $node = $doc->createElement("table");
    $newnode = $doc->appendChild($node);
    $newnode->setAttribute($attribute[0], $attribute[1]);
}

This way doesn't involve regex :) But you need to modify it in order to fit your context.


问:
IllegalStateException with naming parameters in tomcat
I've been using tomcat and spring for a long time (more than a year). Everything worked out great.
Today, all of a sudden I get a weird error when starting tomcat:

Caused by: java.lang.IllegalStateException: Using named parameters for method public abstract java.util.List com.securegion.monitorcenter.dao.IncidentsViewRepository.getFixedIncidents(java.lang.String,java.util.List,java.lang.String,java.lang.String,int,int) but parameter 'text' not found in annotated query 'select * from siemincidents where fixed = 1 and descriptioninfo like %?1% and incidentseverity in ?2 and starttimestamp >= ?3 and endtimestamp <= ?4 order by starttimestamp desc limit ?5, ?6'!

I didn't knew what to do, but no one used the method so I deleted it. Then I restarted tomcat, and got

Using named parameters for method public abstract java.util.List com.securegion.monitorce
    nter.dao.IncidentsViewRepository.getFixedIncidents(int,int) but parameter 'start' not found in annotated query 'select * from siemincidents where fixed = 1 order by starttimestamp desc limit ?1, ?2'!

Again I didn't know what is this, so I deleted the tomcat server entirely from eclipse and created it again. This worked for half an hour, and then I got the same problem! Than, deleting tomcat doesn't help.
What is weird is the the service in the DAO starts with "get" and not "find". I thought that maybe tomcat is confused, so I changed "get" to "fetch". Didn't help. I read here that instead of writing "?1" I should write ":text". But understand that writing with "?" worked for over a year, so I have MANY parameters with "?" - too much work for an annoying bug (it worked for over a year). I've checked all my files, and nothing important is changed today, so I don't know what file caused it.

At the begging it only happened to me, but now it happens to a colleague. We use JENKINS to deploy our server, and JENKINS crashes in

```<code>ERROR: Build step failed with exception
org.codehaus.cargo.container.ContainerException: Failed to deploy [/etc/jenkins/jobs/mcg_DeployToDev/workspace/mcg/target/mcg.war]
    at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.deploy(AbstractTomcatManagerDeployer.java:107)
    at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.redeploy(AbstractTomcatManagerDeployer.java:185)
    at hudson.plugins.deploy.CargoContainerAdapter.deploy(CargoContainerAdapter.java:73)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:116)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:103)
    at hudson.FilePath.act(FilePath.java:989)
    at hudson.FilePath.act(FilePath.java:967)
    at hudson.plugins.deploy.CargoContainerAdapter.redeploy(CargoContainerAdapter.java:103)
    at hudson.plugins.deploy.DeployPublisher.perform(DeployPublisher.java:61)
    at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:761)
    at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:721)
    at hudson.model.Build$BuildExecution.post2(Build.java:183)
    at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:670)
    at hudson.model.Run.execute(Run.java:1766)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:374)
Caused by: org.codehaus.cargo.container.tomcat.internal.TomcatManagerException: FAIL - Deployed application at context path /mcg but context failed to start

    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.invoke(TomcatManager.java:566)
    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.deployImpl(TomcatManager.java:611)
    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.deploy(TomcatManager.java:291)
    at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.deploy(AbstractTomcatManagerDeployer.java:102)
    ... 17 more
org.codehaus.cargo.container.tomcat.internal.TomcatManagerException: FAIL - Deployed application at context path /mcg but context failed to start

    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.invoke(TomcatManager.java:566)
    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.deployImpl(TomcatManager.java:611)
    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.deploy(TomcatManager.java:291)
    at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.deploy(AbstractTomcatManagerDeployer.java:102)
    at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.redeploy(AbstractTomcatManagerDeployer.java:185)
    at hudson.plugins.deploy.CargoContainerAdapter.deploy(CargoContainerAdapter.java:73)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:116)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:103)
    at hudson.FilePath.act(FilePath.java:989)
    at hudson.FilePath.act(FilePath.java:967)
    at hudson.plugins.deploy.CargoContainerAdapter.redeploy(CargoContainerAdapter.java:103)
    at hudson.plugins.deploy.DeployPublisher.perform(DeployPublisher.java:61)
    at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:761)
    at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:721)
    at hudson.model.Build$BuildExecution.post2(Build.java:183)
    at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:670)
    at hudson.model.Run.execute(Run.java:1766)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:374)
Build step 'Deploy war/ear to a container' marked build as failure
Finished: FAILURE
</code>```

If it matters, I'm using tomcat 8.

What can I do? It is such a huge problem that perhaps I'm just missing a minor glitch... What is it?

答:
The question is too old but I faced the same issue. My issue was due to the tomcat version. I switched back to tomcat 7 from tomcat 8 and code starts working as expected.
Seems like Tomcat 8 is not supporting ? in Native Query.

Body:
I've been using tomcat and spring for a long time (more than a year). Everything worked out great.
Today, all of a sudden I get a weird error when starting tomcat:

Caused by: java.lang.IllegalStateException: Using named parameters for method public abstract java.util.List com.securegion.monitorcenter.dao.IncidentsViewRepository.getFixedIncidents(java.lang.String,java.util.List,java.lang.String,java.lang.String,int,int) but parameter 'text' not found in annotated query 'select * from siemincidents where fixed = 1 and descriptioninfo like %?1% and incidentseverity in ?2 and starttimestamp >= ?3 and endtimestamp <= ?4 order by starttimestamp desc limit ?5, ?6'!

I didn't knew what to do, but no one used the method so I deleted it. Then I restarted tomcat, and got

Using named parameters for method public abstract java.util.List com.securegion.monitorce
    nter.dao.IncidentsViewRepository.getFixedIncidents(int,int) but parameter 'start' not found in annotated query 'select * from siemincidents where fixed = 1 order by starttimestamp desc limit ?1, ?2'!

Again I didn't know what is this, so I deleted the tomcat server entirely from eclipse and created it again. This worked for half an hour, and then I got the same problem! Than, deleting tomcat doesn't help.
What is weird is the the service in the DAO starts with "get" and not "find". I thought that maybe tomcat is confused, so I changed "get" to "fetch". Didn't help. I read here that instead of writing "?1" I should write ":text". But understand that writing with "?" worked for over a year, so I have MANY parameters with "?" - too much work for an annoying bug (it worked for over a year). I've checked all my files, and nothing important is changed today, so I don't know what file caused it.

At the begging it only happened to me, but now it happens to a colleague. We use JENKINS to deploy our server, and JENKINS crashes in

ERROR: Build step failed with exception
org.codehaus.cargo.container.ContainerException: Failed to deploy [/etc/jenkins/jobs/mcg_DeployToDev/workspace/mcg/target/mcg.war]
    at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.deploy(AbstractTomcatManagerDeployer.java:107)
    at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.redeploy(AbstractTomcatManagerDeployer.java:185)
    at hudson.plugins.deploy.CargoContainerAdapter.deploy(CargoContainerAdapter.java:73)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:116)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:103)
    at hudson.FilePath.act(FilePath.java:989)
    at hudson.FilePath.act(FilePath.java:967)
    at hudson.plugins.deploy.CargoContainerAdapter.redeploy(CargoContainerAdapter.java:103)
    at hudson.plugins.deploy.DeployPublisher.perform(DeployPublisher.java:61)
    at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:761)
    at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:721)
    at hudson.model.Build$BuildExecution.post2(Build.java:183)
    at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:670)
    at hudson.model.Run.execute(Run.java:1766)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:374)
Caused by: org.codehaus.cargo.container.tomcat.internal.TomcatManagerException: FAIL - Deployed application at context path /mcg but context failed to start

    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.invoke(TomcatManager.java:566)
    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.deployImpl(TomcatManager.java:611)
    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.deploy(TomcatManager.java:291)
    at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.deploy(AbstractTomcatManagerDeployer.java:102)
    ... 17 more
org.codehaus.cargo.container.tomcat.internal.TomcatManagerException: FAIL - Deployed application at context path /mcg but context failed to start

    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.invoke(TomcatManager.java:566)
    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.deployImpl(TomcatManager.java:611)
    at org.codehaus.cargo.container.tomcat.internal.TomcatManager.deploy(TomcatManager.java:291)
    at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.deploy(AbstractTomcatManagerDeployer.java:102)
    at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.redeploy(AbstractTomcatManagerDeployer.java:185)
    at hudson.plugins.deploy.CargoContainerAdapter.deploy(CargoContainerAdapter.java:73)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:116)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:103)
    at hudson.FilePath.act(FilePath.java:989)
    at hudson.FilePath.act(FilePath.java:967)
    at hudson.plugins.deploy.CargoContainerAdapter.redeploy(CargoContainerAdapter.java:103)
    at hudson.plugins.deploy.DeployPublisher.perform(DeployPublisher.java:61)
    at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:761)
    at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:721)
    at hudson.model.Build$BuildExecution.post2(Build.java:183)
    at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:670)
    at hudson.model.Run.execute(Run.java:1766)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:374)
Build step 'Deploy war/ear to a container' marked build as failure
Finished: FAILURE

If it matters, I'm using tomcat 8.

What can I do? It is such a huge problem that perhaps I'm just missing a minor glitch... What is it?


问:
Android Biometric Prompt is not dismissed when device home button is pressed
When Biometric prompt is shown in App with setDeviceCredentialAllowed(true), It is not dismissed when device home button is pressed. It throws BiometricPrompt.ERROR_USER_CANCELED error and keeps the System UI as is.

Did any one face this issue ? Is there any workaround kind of thing ?

Note :
I am using androidx.biometric:biometric:1.0.1

Note: Its Android bug. https://issuetracker.google.com/issues/149770989

答:
I found this bug when I tried this library.
The problem is they implemented it as a fragment, and it's not responding well to this thing.

I opted out of using this library all together and just implemented it myself.


问:
How to print only first element from JSON Array in ReactJs?
I have the following JSON Array data from which I want to print Charlie. How to do it?</p>

```<code>[ [ {
"ID": 1,
"Name" :"David"
},{
"ID": 2,
"Name" :"Antony"
}],[{
"ID": 1,
"Name" :"Bob"
},{
"ID": 2,
"Name" :"Charlie"
} ] ]
</code>```

答:
you are using {PostData.map((group, index)=>{ return
{group.Name}
, since you are using map here PostData[0].Name will throw error inside map(), because you are iterating array with map().

Since you only need first item, you can simply use
PostData[0].Name

var data = [{
"ID": 1,
"Name" :"David",
},  {
"ID": 2,
"Name" :"Antony",
}];

console.log(data[0].Name)```

Body:
I have the following JSON Array data from which I want to print Charlie. How to do it?

[ [ {
"ID": 1,
"Name" :"David"
},{
"ID": 2,
"Name" :"Antony"
}],[{
"ID": 1,
"Name" :"Bob"
},{
"ID": 2,
"Name" :"Charlie"
} ] ]

Body:
you are using {PostData.map((group, index)=>{ return <p>{group.Name}</p>, since you are using map here PostData[0].Name will throw error inside map(), because you are iterating array with map().

Since you only need first item, you can simply use <p>PostData[0].Name</p>

var data = [{
"ID": 1,
"Name" :"David",
},  {
"ID": 2,
"Name" :"Antony",
}];

console.log(data[0].Name)


问:
Can one filter retrieved activities of a notification feed based on group properties (i.e. is seen or is read)?
I'm in the process of setting up an integration with GetStream where I've set up a notification feed for our users to follow flat feeds (products, other users, etc). I'm grouping activities by {id} as suggested in How to filter out previously seen and read activities while retrieving notifications? so that once a user has read an activity, it should never show up again in their feed.

I'd like to be able to filter the retrieval of activities to exclude read activities. I can't find anything in the API docs that suggest this is possible. If it truly is not, how best to reasonably retrieve feed activities without many calls to the API once there is a significant number of activities in some of the followed feeds?

Thanks in advance for the help!

答:
As we explained it in How to filter out previously seen and read activities while retrieving notifications?, read state "is_read" and seen state "is_seen" are kept at the activity group level ('activities' field in the API response) and its resets from read/seen (is_read=true)  to unread/unseen (is_seen=false) each time the group is updated (when a new activity is added or updated).

However, it's not possible to only retrieve the unread/unseen activities in a group as the get() method to retrieve activities from a notification feed does not support filtering activities by "is_read" or "is_seen" field.

It's yet possible for you to retrieve every activity group and filter those activities yourself by implementing your own method to exclude previous read/seen activities from the notification feed.

Let us know if you have other questions.

Best regards,