问:
How do I make my script play sounds according to the keys that has been placed?
Consider:

```<code>import winsound
import string
import keyboard
listend = keyboard.read_key()
aloop = False
listed = [string.ascii_letters, string.digits]
while True:
    if listend in listed:
            continue
            aloop = True
    elif listend not in listed:
        listend = None
        pass
    elif NameError:
        pass                 # Checks if these are
        listend = None
    elif ValueError:
        pass
        listend = None
    elif listend == None:
        pass
        listend = None
    else:
        pass
while aloop == True:
    for listend in listed:
        winsound

x = listed + '.wav'
meanings = {
    listed: x
}
</code>```

I'm trying to make a keyboardfeedback program that plays a really hard-to-hear noise when one button has been pressed. listend asks for inputs here through the keyboard module, and if listend = something in listed, it starts the loop aloop. I couldn't do aloop just yet as I don’t know how to do it. The file names were supposed to be for instance !w.wav! !l.wav! !8.wav! and the portion of the code in the very bottom was used to control it.

Updated code

```<code>import winsound
import string
import keyboard
listend = keyboard.read_key()
aloop = False
listed = str(string.ascii_letters + string.digits)
x = listed + '.wav'
meanings = {
    listend: x
}
while True:
    if listend in listed:
            aloop = True
            continue
    elif listend not in listed:
        listend = ''
        pass
    elif NameError:
        pass                        #checks if these are
        listend = ''
    elif ValueError:
        pass
        listend = ''
    elif listend == '':
        pass
        listend = ''
    else:
        pass
while aloop == True:
    for listend in meanings:
        winsound.PlaySound(listend, winsound.SND_ASYNC)
</code>```

It doesn’t even give any errors by now. There are files named w.wav,  a.wav, and so on, but none plays.

答:
I've learned more as the days went on.

```<code>import winsound
import keyboard
alias = winsound.SND_ASYNC | winsound.SND_FILENAME | winsound.SND_NODEFAULT
while True:
    y = keyboard.read_key()
    x = "pykeyboardfeedback\\" + y + '.wav'
    winsound.PlaySound(x, alias)
</code>```

You have to replace pykeyboardfeedback with the folder your sound files are in.

I don’t know if it is possible, but if you somehow manage to play other sound files in winsound, change the .wav with .mp3. I guess - I don't know.

I'm actually pretty surprised I could finish this in seven lines.

Body:
Consider:

import winsound
import string
import keyboard
listend = keyboard.read_key()
aloop = False
listed = [string.ascii_letters, string.digits]
while True:
    if listend in listed:
            continue
            aloop = True
    elif listend not in listed:
        listend = None
        pass
    elif NameError:
        pass                 # Checks if these are
        listend = None
    elif ValueError:
        pass
        listend = None
    elif listend == None:
        pass
        listend = None
    else:
        pass
while aloop == True:
    for listend in listed:
        winsound

x = listed + '.wav'
meanings = {
    listed: x
}

I'm trying to make a keyboardfeedback program that plays a really hard-to-hear noise when one button has been pressed. listend asks for inputs here through the keyboard module, and if listend = something in listed, it starts the loop aloop. I couldn't do aloop just yet as I don’t know how to do it. The file names were supposed to be for instance !w.wav! !l.wav! !8.wav! and the portion of the code in the very bottom was used to control it.

Updated code

import winsound
import string
import keyboard
listend = keyboard.read_key()
aloop = False
listed = str(string.ascii_letters + string.digits)
x = listed + '.wav'
meanings = {
    listend: x
}
while True:
    if listend in listed:
            aloop = True
            continue
    elif listend not in listed:
        listend = ''
        pass
    elif NameError:
        pass                        #checks if these are
        listend = ''
    elif ValueError:
        pass
        listend = ''
    elif listend == '':
        pass
        listend = ''
    else:
        pass
while aloop == True:
    for listend in meanings:
        winsound.PlaySound(listend, winsound.SND_ASYNC)

It doesn’t even give any errors by now. There are files named w.wav,  a.wav, and so on, but none plays.

Body:
I've learned more as the days went on.

import winsound
import keyboard
alias = winsound.SND_ASYNC | winsound.SND_FILENAME | winsound.SND_NODEFAULT
while True:
    y = keyboard.read_key()
    x = "pykeyboardfeedback\\" + y + '.wav'
    winsound.PlaySound(x, alias)

You have to replace pykeyboardfeedback with the folder your sound files are in.

I don’t know if it is possible, but if you somehow manage to play other sound files in winsound, change the .wav with .mp3. I guess - I don't know.

I'm actually pretty surprised I could finish this in seven lines.


来源: stackexchange

答:
Instead of using x and y to move your SVG around, you could use a translation. That would allow you to get rid of the outer SVG-element and have the inner one start positioned at the top left.

For example the CSS-rule svg { transform: translate(10px, 10px); } would move it 10px to the right and 10px down. Just set this as you would x and y otherwise.

ContentLicense: CC BY-SA 4.0

Title: SVG Element is Vertically Centred and I don't want it to be

Body:
I'm trying to recreate the old DVD logo that would bounce around the tv screen using the SVG html element.

<svg className='canvas'>
  <svg ref={this.image} xmlns="http://www.w3.org/2000/svg" width="10%" viewBox="0 0 510 305" version="1.1">
    <g ref={this.g} id="g1" transform="matrix(6,0,0,6,48.16071,-418.59098)">
      <path id="path1" d="m 30.57323,69.90683 0,0.14991 0.14998,0.30006 0.15001,0.44999 0.14999,0.67505 0.37501,0.67497 0.22499,0.82497 0.22501,0.75005 0.29999,0.74996 0.22501,0.67505 0.14999,0.67497 0.15001,0.44998 0.6,1.57501 0.45,1.35003 0.29999,1.12496 0.375,0.90004 0.15001,0.74996 0.15,0.67505 0.075,0.37499 0.075,0.37498 0,0.29999 0.075,-0.075 0.075,-0.22499 0.15,-0.22507 0.22499,-0.37498 0.30001,-0.52498 0.52501,-0.59998 0.52498,-0.67497 0.67501,-0.90004 0.82499,-1.12495 0.97501,-1.20003 1.19999,-1.42502 0.30001,-0.29999 0.375,-0.44997 0.44999,-0.67505 0.67501,-0.67498 0.525,-0.74997 0.60001,-0.75004 0.67499,-0.74998 0.525,-0.59997 0.59999,-0.67505 0.37501,-0.37499 0.22499,-0.30006 0.075,-0.14991 17.24999,0 2.17501,0.14991 2.02499,0.22507 1.8,0.44998 1.72501,0.60005 1.49999,0.74997 1.35001,0.89997 1.12499,1.05003 0.975,1.05003 0.60002,1.19995 0.375,1.35002 0.075,1.35003 -0.22501,1.42494 -0.45,1.50001 -0.74999,1.35002 -0.97501,1.35003 -1.27499,1.19995 -1.425,1.12495 -1.57501,0.97504 -1.72499,0.89996 -1.875,0.82505 -2.02501,0.52505 -2.02498,0.44999 -2.10001,0.22498 -2.25,0.075 -11.55001,0 3.45001,-14.62502 8.175,0 -2.325,10.05005 1.8,0 1.425,-0.075 1.425,-0.15 1.425,-0.22499 1.19999,-0.37499 1.20002,-0.59997 1.12499,-0.60005 0.89999,-0.82498 0.75001,-0.82496 0.60001,-1.05004 0.44998,-1.20002 0.15001,-1.04995 -0.075,-0.97504 -0.29999,-0.89996 -0.6,-0.67505 -0.67501,-0.74998 -0.97499,-0.52497 -1.05,-0.44999 -1.20001,-0.30006 -1.34998,-0.14999 -1.57501,-0.075 -9.9,0 -18.75,21.30005 -7.425,-20.92506 0,-0.075 -0.075,-0.14999 0,-0.075 -0.15,-0.15 -0.075,0 -0.14999,0.15 0,0.075 0.075,0.075 0,0.15 0.075,0 0,0.075 0.22502,0.82504 0.14998,0.74997 0.075,0.90004 0.075,0.89996 0,0.75004 -0.075,0.74998 -0.075,0.52497 -0.45,1.50001 -0.825,1.35003 -0.975,1.35002 -1.20002,1.19988 -1.425,1.12495 -1.57501,0.97504 -1.79999,0.89996 -1.875,0.67505 -1.95001,0.67505 -2.09999,0.44999 -2.17501,0.22498 -2.09999,0.075 -11.625,0 3.525,-14.62502 8.175,0 -2.475,10.05005 1.95,0 1.425,-0.075 1.425,-0.15 1.275,-0.22499 1.35,-0.37499 1.19999,-0.59997 1.05002,-0.60005 0.89998,-0.82498 0.82501,-0.82496 0.52501,-1.05004 0.44998,-1.20002 0.15,-1.04995 -0.075,-0.97504 -0.375,-0.89996 -0.45,-0.67505 -0.74999,-0.74998 -0.9,-0.52497 -1.125,-0.44999 -1.2,-0.30006 -1.34999,-0.14999 -1.50001,-0.075 -10.12499,0 1.12499,-4.64996 31.12501,0" />
      <path id="path2" d="m 30.64821,103.58183 -1.5,0 -2.69998,-0.15007 -1.12501,-0.14992 -1.125,-0.22506 -0.9,-0.15 -0.75,-0.29999 -0.6,-0.29999 -0.30001,-0.29999 -0.14999,-0.29998 0.14999,-0.29999 0.30001,-0.22506 0.6,-0.37499 0.75,-0.22499 0.9,-0.225 1.125,-0.14999 1.12501,-0.15007 1.34998,-0.0749 1.35,-0.075 1.5,-0.075 1.5,0.075 1.42501,0.075 1.27499,0.0749 1.27501,0.15008 0.975,0.14999 0.97501,0.225 0.67499,0.22498 0.6,0.37499 0.29999,0.22507 0.15001,0.29999 -0.15001,0.29998 -0.29999,0.29999 -0.6,0.29999 -0.67499,0.29999 -0.97501,0.15 -0.975,0.22506 -1.27501,0.14992 -1.27499,0.0751 -1.42501,0.075 -1.5,0 z m 1.5,-7.65007 -3.67499,0 -3.6,0.0751 -3.375,0.15 -3.3,0.14992 -3.225,0.15007 -3.00001,0.29999 -2.925,0.22499 -2.7,0.29998 -2.475,0.30007 -2.325,0.37498 -2.09999,0.44993 -1.875,0.37497 -1.65001,0.375 -1.275,0.52498 -1.05,0.45005 -0.825,0.44999 -0.44999,0.52498 -0.15001,0.52505 0.15001,0.44998 0.44999,0.59998 0.825,0.44999 1.05,0.45005 1.275,0.52497 1.65001,0.37499 1.875,0.37499 2.09999,0.44998 2.325,0.37498 2.475,0.30006 2.7,0.29999 2.925,0.225 3.00001,0.29999 3.225,0.15006 3.3,0.15 3.375,0.14999 3.6,0 3.67499,0.075 3.67502,-0.075 3.52499,0 3.375,-0.14999 3.29999,-0.15 3.22501,-0.15006 2.99999,-0.29999 2.92501,-0.225 2.69999,-0.29999 2.55001,-0.30006 2.25,-0.37498 2.17499,-0.44998 1.8,-0.37499 1.65001,-0.37499 1.34999,-0.52497 0.975,-0.45005 0.82502,-0.44999 0.44998,-0.59998 0.15001,-0.44998 -0.15001,-0.52505 -0.44998,-0.52498 -0.82502,-0.44999 -0.975,-0.45005 -1.34999,-0.52498 -1.65001,-0.37499 -1.8,-0.37498 -2.17499,-0.44998 -2.25,-0.37499 -2.55001,-0.30006 -2.69999,-0.29999 -2.92501,-0.22499 -2.99999,-0.29999 -3.22501,-0.15007 -3.29999,-0.14991 -3.375,-0.15 -3.52499,-0.0751 -3.67502,0" />
      <path id="path3" d="m 71.59822,106.0568 -0.97501,0 -0.37499,2.92504 -0.45,0 0.375,-2.92504 -1.05001,0 0.075,-0.37506 2.475,0 -0.075,0.37506" />
      <path id="path4" d="m 75.04822,108.98184 -0.45,0 0,-2.55005 -1.35001,2.55005 -0.52499,-2.55005 -0.89999,2.55005 -0.375,0 1.12499,-3.3001 0.29999,0 0.525,2.17506 1.20001,-2.17506 0.45,0 0,3.3001" />
      <path id="path5" d="m 5.07322,117.53179 2.69999,-5.475 2.55001,0 -4.65,8.40004 -1.425,0 -4.57501,-8.40004 2.475,0 2.92501,5.475" />
      <path id="path6" d="m 16.02321,120.45683 2.25,0 0,-8.4 -2.25,0 0,8.4 z" />
      <path id="path7" d="m 28.39821,120.45683 -3.44998,0 0,-8.40004 3.44998,0 1.20001,0.075 1.12499,0.22499 1.05001,0.44998 0.82499,0.45005 0.67501,0.67498 0.525,0.67505 0.3,0.82496 0.075,0.82498 -0.075,0.90003 -0.3,0.74997 -0.525,0.75005 -0.75001,0.52497 -0.74999,0.59998 -1.05001,0.37506 -1.12499,0.22499 -1.20001,0.075 z m -0.67499,-6.97503 1.12499,0 0.9,0.225 0.67501,0.29999 0.59999,0.37499 0.45001,0.52505 0.225,0.59997 0.075,0.74998 -0.075,0.60005 -0.15001,0.52497 -0.22499,0.44999 -0.525,0.45005 -0.52501,0.29999 -0.67499,0.22491 -0.82501,0.15007 -1.04999,0.075 -0.37501,0 0,-5.55001 0.37501,0" />
      <path id="path8" d="m 42.72322,113.4818 0,1.875 3.675,0 0,1.42503 -3.675,0 0,2.24998 3.89999,0 0,1.42502 -6.225,0 0,-8.40004 6.225,0 0,1.42501 -3.89999,0" />
      <path id="path9" d="m 58.47322,120.45683 1.35,-0.075 1.125,-0.22499 1.04999,-0.37506 0.82501,-0.59998 0.75,-0.59997 0.525,-0.75004 0.29999,-0.74998 0.075,-0.82503 -0.075,-0.82498 -0.29999,-0.82496 -0.525,-0.60005 -0.75,-0.67498 -0.82501,-0.52505 -1.04999,-0.44998 -1.125,-0.22499 -1.35,-0.075 -1.20001,0.075 -1.12499,0.22499 -1.05001,0.44998 -0.82499,0.52505 -0.75001,0.67498 -0.52499,0.60005 -0.29999,0.82496 -0.075,0.82498 0.075,0.82503 0.29999,0.74998 0.52499,0.75004 0.75001,0.59997 0.82499,0.59998 1.05001,0.37506 1.12499,0.22499 1.20001,0.075 z m 0,-6.90003 0.89999,0.075 0.75,0.29999 0.67501,0.29999 0.525,0.37506 0.45,0.4499 0.22499,0.60005 0.075,0.52499 -0.075,0.60005 -0.22499,0.44997 -0.45,0.52499 -0.525,0.52505 -0.75,0.29999 -0.67501,0.22491 -0.89999,0.0751 -0.75,-0.0751 -0.82501,-0.22491 -0.59999,-0.29999 -0.525,-0.52505 -0.45,-0.52499 -0.22501,-0.44997 -0.075,-0.60005 0.075,-0.52499 0.22501,-0.60005 0.45,-0.4499 0.525,-0.37506 0.59999,-0.29999 0.82501,-0.29999 0.75,-0.075" />
    </g>
  </svg>
</svg>

This is what I've got so far. I have a parent SVG element which has some CSS styling to set its position to absolute and its width and height to 100%, so that it fills the whole window.

I then have the internal SVG element, which I've given a viewbox so that I can have the image be dynamically sized according to the size of the window.

This works but the SVG image ends up vertically centred in the window when x and y are set to 0, which is frustrating. I want the x=0 y=0 coordinate to be the top left of the window. If I am to remove the parent SVG element then the image successfully displays in the top left but I then can't use the coordinates to move it around the page, and if I don't specify a viewBox then I can use the coordinates and the origin is at the top left of the window but I have no control over the size of the image and it is rather larger than I would like.

What do I do?


问:
How to test sublinks on a page in Selenium
How to test sub links on a page in Selenium. I have an events page. Then from that events page i collect all the different events links. Then i want to recursively run tests on those links.

I have attached an image of the page. The green text are all links. So i collected the href values of all these. After that I have some tests to run on those pages. I have a test class called EventsPageTest for the main page. The test class for the sub pages is called SingleEventsPageTest. How do I transfer the href values from the main class to the other class. Or is there any other method I need to follow.
I searched the internet so much but was of no use.
Any help would be appreciated.
Thanks

EventsPageTest

```<code>package test;
import pages.EventsPageObjects;

@Listeners(listeners.TestListener.class)
public class EventsPageTest {

    private static ExtentHtmlReporter htmlReporter;
    private static ExtentReports extent;
    private static ExtentTest test;
    static WebDriver driver = null;
    private static EventsPageObjects eventsPage;
    public MutableCapabilities capabilities;
    static Set<String> eventsLinks = new HashSet<String>();
    String url;

    @BeforeSuite
    public void setUp() {

        // initialize the HtmlReporter
        htmlReporter = new ExtentHtmlReporter("extentReportsEventsPage.html");

        // initialize ExtentReports and attach the HtmlReporter
        extent = new ExtentReports();

        // attach only HtmlReporter
        extent.attachReporter(htmlReporter);
    }

     @BeforeTest
     public void setUpTest() throws IOException{
         WebDriverManager.chromedriver().setup();
            driver = new ChromeDriver();

            url = "abc.com";
            driver.get(url);

            System.out.println("Inside setUpTest");

            //Create eventsPageObject
            eventsPage = new EventsPageObjects(driver);

     }

    @Test(alwaysRun=true)
    public void collectEventsLinks() throws InterruptedException, IOException {

        test = extent.createTest("Collect all Events Links on a page","Test to Collect all Events Links on a page ");

        test.log(Status.INFO, "Starting Test Case");

        List<WebElement> links = driver.findElements(By.tagName("a"));

         for (int i = 0; i<links.size(); i++) {
           if(Pattern.matches("^https://"+ TestRunner.url +"/events/[^/]+[^\\s]$", links.get(i).getAttribute("href")))
               eventsLinks.add((links.get(i).getAttribute("href")));
         }

         test.log(Status.INFO, "Finished Test Case");

    }

    @AfterTest(alwaysRun = true)
    public void tearDownTest() {
        //close browser
        driver.close();
        driver.quit();
    }

    @DataProvider(name="getURLS")
    @AfterTest
    public Object[] getURLS() {

        System.out.println("Inside get Urls");
        System.out.println("getURLS : " + eventsLinks.size());

        Object[] objArray = eventsLinks.toArray();

        System.out.println(eventsLinks.size());

        return objArray;
    }

    @AfterSuite
    public void tearDown() {
        extent.flush();
    }
}
</code>```

SingleEventsPageTest

```<code>package test;

@Listeners(listeners.TestListener.class)
public class SingleEventsPageTest{

    private static ExtentHtmlReporter htmlReporter;

    private static ExtentReports extent;
    private static ExtentTest test;
    static WebDriver driver;
    private static SingleEventsPageObjects singleEventsPage;
    static List<Object> eventsURLS = new ArrayList<Object>();

    @BeforeSuite
    public void setUp() {
        PropertiesFile.getProperties();

        // initialize the HtmlReporter
        htmlReporter = new ExtentHtmlReporter("extentReportsSingleEventsPage.html");

        // initialize ExtentReports and attach the HtmlReporter
        extent = new ExtentReports();

        // attach only HtmlReporter
        extent.attachReporter(htmlReporter);
    }

     @BeforeTest
     public void setUpTest() throws IOException{
         WebDriverManager.chromedriver().setup();
            driver = new ChromeDriver();

            //Create eventsPageObject
            singleEventsPage = new SingleEventsPageObjects(driver);
     }

    @Test(dataProvider="getURLS",dataProviderClass=EventsPageTest.class,alwaysRun=true)
    public void findIfEventsTitleExists(String url) throws InterruptedException, IOException {

        driver.get(url);

        System.out.println("Inside findIfEventsTitleExists : " + driver.getCurrentUrl());

        test = extent.createTest("Events Title Exists","Test to verify if the Events Title exists after opening the page");

        test.log(Status.INFO, "Starting Test Case");

        test.log(Status.INFO, "Checking If the URL points to the events page else navigate to that");

        Assert.assertEquals(true,singleEventsPage.findIfEventsTitleExists());

        test.log(Status.INFO, "Finished Test Case");

    }

   @Test(dataProvider="getURLS",dataProviderClass=EventsPageTest.class,alwaysRun=true)
        public void verifyIfEventDescriptionExists(String url) throws InterruptedException, IOException {

            driver.get(url);

            test = extent.createTest("Events description Exists","Test to verify if the Events description exists");

            test.log(Status.INFO, "Starting Test Case");

            test.log(Status.INFO, "Checking If the URL points to the events page else navigate to that");
            if(singleEventsPage.getCurrentUrl() != url)
                singleEventsPage.navigateTo(url);

            test.log(Status.INFO, "Checking If the Page Sub Title Exists");
            Assert.assertEquals(true,singleEventsPage.checkIfElementExists(singleEventsPage.getEventDesc()));

            test.log(Status.INFO, "Finished Test Case");

        }

    @AfterTest(alwaysRun = true)
    public void tearDownTest() {
        //close browser
        driver.close();
        driver.quit();
    }

    @AfterSuite
    public void tearDown() {
        extent.flush();
    }

}
</code>```

答:
It would be good if you could post your code here. You can try to store them in one class as List, then pass them to another.

I am not sure how your framework is working now. I am thinking of something like this. Please post more code here.

```<code>class EventsPageTest {
  public List<T> getAllHref() {
    // return List
  }
}
</code>```

```<code>class SingleEventsPage {
  @Test
  public void someTest () {
    EventsPageTest eventsPageTest = new EventsPageTest();
    List<T> hrefs = eventsPageTest.getAllHref();
  }

}

</code>```

Hope this helps

Body:
How to test sub links on a page in Selenium. I have an events page. Then from that events page i collect all the different events links. Then i want to recursively run tests on those links.

I have attached an image of the page. The green text are all links. So i collected the href values of all these. After that I have some tests to run on those pages. I have a test class called EventsPageTest for the main page. The test class for the sub pages is called SingleEventsPageTest. How do I transfer the href values from the main class to the other class. Or is there any other method I need to follow.
I searched the internet so much but was of no use.
Any help would be appreciated.
Thanks

EventsPageTest

package test;
import pages.EventsPageObjects;

@Listeners(listeners.TestListener.class)
public class EventsPageTest {

    private static ExtentHtmlReporter htmlReporter;
    private static ExtentReports extent;
    private static ExtentTest test;
    static WebDriver driver = null;
    private static EventsPageObjects eventsPage;
    public MutableCapabilities capabilities;
    static Set<String> eventsLinks = new HashSet<String>();
    String url;

    @BeforeSuite
    public void setUp() {

        // initialize the HtmlReporter
        htmlReporter = new ExtentHtmlReporter("extentReportsEventsPage.html");

        // initialize ExtentReports and attach the HtmlReporter
        extent = new ExtentReports();

        // attach only HtmlReporter
        extent.attachReporter(htmlReporter);
    }

     @BeforeTest
     public void setUpTest() throws IOException{
         WebDriverManager.chromedriver().setup();
            driver = new ChromeDriver();

            url = "abc.com";
            driver.get(url);

            System.out.println("Inside setUpTest");

            //Create eventsPageObject
            eventsPage = new EventsPageObjects(driver);

     }

    @Test(alwaysRun=true)
    public void collectEventsLinks() throws InterruptedException, IOException {

        test = extent.createTest("Collect all Events Links on a page","Test to Collect all Events Links on a page ");

        test.log(Status.INFO, "Starting Test Case");

        List<WebElement> links = driver.findElements(By.tagName("a"));

         for (int i = 0; i<links.size(); i++) {
           if(Pattern.matches("^https://"+ TestRunner.url +"/events/[^/]+[^\\s]$", links.get(i).getAttribute("href")))
               eventsLinks.add((links.get(i).getAttribute("href")));
         }

         test.log(Status.INFO, "Finished Test Case");

    }

    @AfterTest(alwaysRun = true)
    public void tearDownTest() {
        //close browser
        driver.close();
        driver.quit();
    }

    @DataProvider(name="getURLS")
    @AfterTest
    public Object[] getURLS() {

        System.out.println("Inside get Urls");
        System.out.println("getURLS : " + eventsLinks.size());

        Object[] objArray = eventsLinks.toArray();

        System.out.println(eventsLinks.size());

        return objArray;
    }

    @AfterSuite
    public void tearDown() {
        extent.flush();
    }
}

SingleEventsPageTest

package test;

@Listeners(listeners.TestListener.class)
public class SingleEventsPageTest{

    private static ExtentHtmlReporter htmlReporter;

    private static ExtentReports extent;
    private static ExtentTest test;
    static WebDriver driver;
    private static SingleEventsPageObjects singleEventsPage;
    static List<Object> eventsURLS = new ArrayList<Object>();

    @BeforeSuite
    public void setUp() {
        PropertiesFile.getProperties();

        // initialize the HtmlReporter
        htmlReporter = new ExtentHtmlReporter("extentReportsSingleEventsPage.html");

        // initialize ExtentReports and attach the HtmlReporter
        extent = new ExtentReports();

        // attach only HtmlReporter
        extent.attachReporter(htmlReporter);
    }

     @BeforeTest
     public void setUpTest() throws IOException{
         WebDriverManager.chromedriver().setup();
            driver = new ChromeDriver();

            //Create eventsPageObject
            singleEventsPage = new SingleEventsPageObjects(driver);
     }

    @Test(dataProvider="getURLS",dataProviderClass=EventsPageTest.class,alwaysRun=true)
    public void findIfEventsTitleExists(String url) throws InterruptedException, IOException {

        driver.get(url);

        System.out.println("Inside findIfEventsTitleExists : " + driver.getCurrentUrl());

        test = extent.createTest("Events Title Exists","Test to verify if the Events Title exists after opening the page");

        test.log(Status.INFO, "Starting Test Case");

        test.log(Status.INFO, "Checking If the URL points to the events page else navigate to that");

        Assert.assertEquals(true,singleEventsPage.findIfEventsTitleExists());

        test.log(Status.INFO, "Finished Test Case");

    }

   @Test(dataProvider="getURLS",dataProviderClass=EventsPageTest.class,alwaysRun=true)
        public void verifyIfEventDescriptionExists(String url) throws InterruptedException, IOException {

            driver.get(url);

            test = extent.createTest("Events description Exists","Test to verify if the Events description exists");

            test.log(Status.INFO, "Starting Test Case");

            test.log(Status.INFO, "Checking If the URL points to the events page else navigate to that");
            if(singleEventsPage.getCurrentUrl() != url)
                singleEventsPage.navigateTo(url);

            test.log(Status.INFO, "Checking If the Page Sub Title Exists");
            Assert.assertEquals(true,singleEventsPage.checkIfElementExists(singleEventsPage.getEventDesc()));

            test.log(Status.INFO, "Finished Test Case");

        }

    @AfterTest(alwaysRun = true)
    public void tearDownTest() {
        //close browser
        driver.close();
        driver.quit();
    }

    @AfterSuite
    public void tearDown() {
        extent.flush();
    }

}

Body:
It would be good if you could post your code here. You can try to store them in one class as List, then pass them to another.

I am not sure how your framework is working now. I am thinking of something like this. Please post more code here.

class EventsPageTest {
  public List<T> getAllHref() {
    // return List
  }
}

class SingleEventsPage {
  @Test
  public void someTest () {
    EventsPageTest eventsPageTest = new EventsPageTest();
    List<T> hrefs = eventsPageTest.getAllHref();
  }

}

Hope this helps


问:
How to Download and SVG element as an SVG file
Over the past few months, I have been working on this code that deals with ellipsoidal earth and just recently I have finished it. My professor now wants me to send him pictures of the diagrams I made as an SVG file. I know in Python you can put a few lines of code into your project to have it download the image, but I am unsure how it works in JavaScript. How can I do this in JavaScript, or is there another easier way?

答:
Check out this demo: https://codepen.io/Alexander9111/pen/VwLaaPe?editors=1010

Code (modified from https://stackoverflow.com/a/19885344/9792594):

```<code>function downloadSVGasTextFile() {
  const base64doc = btoa(unescape(encodeURIComponent(document.querySelector('svg').outerHTML)));
  const a = document.createElement('a');
  const e = new MouseEvent('click');

  a.download = 'download.svg';
  a.href = 'data:text/html;base64,' + base64doc;
  a.dispatchEvent(e);
}

downloadSVGasTextFile();
</code>```

You encode your svg as a 64bit string and then use that as the href of an anchor tag and then dispatch a click event to download the svg text file as download.svg

If you want to save an image, such as .png then you can first draw svg image into a cnavas then download that as .png,

UPDATE

I modified the answer and the demo to now include both download as text file .svg or download as image file .png https://codepen.io/Alexander9111/pen/VwLaaPe:

HTML:

```<code><svg>
 ...
</svg>
<br/>
<button id="downloadPNG">Download .png</button>
<button id="downloadSVG">Download .svg</button>
</code>```

JS:

```<code>function downloadSVGAsText() {
  const svg = document.querySelector('svg');
  const base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML)));
  const a = document.createElement('a');
  const e = new MouseEvent('click');
  a.download = 'download.svg';
  a.href = 'data:image/svg+xml;base64,' + base64doc;
  a.dispatchEvent(e);
}

function downloadSVGAsPNG(e){
  const canvas = document.createElement("canvas");
  const svg = document.querySelector('svg');
  const base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML)));
  const w = parseInt(svg.getAttribute('width'));
  const h = parseInt(svg.getAttribute('height'));
  const img_to_download = document.createElement('img');
  img_to_download.src = 'data:image/svg+xml;base64,' + base64doc;
  console.log(w, h);
  img_to_download.onload = function () {
    canvas.setAttribute('width', w);
    canvas.setAttribute('height', h);
    const context = canvas.getContext("2d");
    //context.clearRect(0, 0, w, h);
    context.drawImage(img_to_download,0,0,w,h);
    const dataURL = canvas.toDataURL('image/png');
    if (window.navigator.msSaveBlob) {
      window.navigator.msSaveBlob(canvas.msToBlob(), "download.png");
      e.preventDefault();
    } else {
      const a = document.createElement('a');
      const my_evt = new MouseEvent('click');
      a.download = 'download.png';
      a.href = dataURL;
      a.dispatchEvent(my_evt);
    }
    //canvas.parentNode.removeChild(canvas);
  }
}

const downloadSVG = document.querySelector('#downloadSVG');
downloadSVG.addEventListener('click', downloadSVGAsText);
const downloadPNG = document.querySelector('#downloadPNG');
downloadPNG.addEventListener('click', downloadSVGAsPNG);
</code>```

Body:
Check out this demo: https://codepen.io/Alexander9111/pen/VwLaaPe?editors=1010

Code (modified from https://stackoverflow.com/a/19885344/9792594):

function downloadSVGasTextFile() {
  const base64doc = btoa(unescape(encodeURIComponent(document.querySelector('svg').outerHTML)));
  const a = document.createElement('a');
  const e = new MouseEvent('click');

  a.download = 'download.svg';
  a.href = 'data:text/html;base64,' + base64doc;
  a.dispatchEvent(e);
}

downloadSVGasTextFile();

You encode your svg as a 64bit string and then use that as the href of an anchor tag and then dispatch a click event to download the svg text file as download.svg

If you want to save an image, such as .png then you can first draw svg image into a cnavas then download that as .png,

UPDATE

I modified the answer and the demo to now include both download as text file .svg or download as image file .png https://codepen.io/Alexander9111/pen/VwLaaPe:

HTML:

<svg>
 ...
</svg>
<br/>
<button id="downloadPNG">Download .png</button>
<button id="downloadSVG">Download .svg</button>

JS:

function downloadSVGAsText() {
  const svg = document.querySelector('svg');
  const base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML)));
  const a = document.createElement('a');
  const e = new MouseEvent('click');
  a.download = 'download.svg';
  a.href = 'data:image/svg+xml;base64,' + base64doc;
  a.dispatchEvent(e);
}

function downloadSVGAsPNG(e){
  const canvas = document.createElement("canvas");
  const svg = document.querySelector('svg');
  const base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML)));
  const w = parseInt(svg.getAttribute('width'));
  const h = parseInt(svg.getAttribute('height'));
  const img_to_download = document.createElement('img');
  img_to_download.src = 'data:image/svg+xml;base64,' + base64doc;
  console.log(w, h);
  img_to_download.onload = function () {
    canvas.setAttribute('width', w);
    canvas.setAttribute('height', h);
    const context = canvas.getContext("2d");
    //context.clearRect(0, 0, w, h);
    context.drawImage(img_to_download,0,0,w,h);
    const dataURL = canvas.toDataURL('image/png');
    if (window.navigator.msSaveBlob) {
      window.navigator.msSaveBlob(canvas.msToBlob(), "download.png");
      e.preventDefault();
    } else {
      const a = document.createElement('a');
      const my_evt = new MouseEvent('click');
      a.download = 'download.png';
      a.href = dataURL;
      a.dispatchEvent(my_evt);
    }
    //canvas.parentNode.removeChild(canvas);
  }
}

const downloadSVG = document.querySelector('#downloadSVG');
downloadSVG.addEventListener('click', downloadSVGAsText);
const downloadPNG = document.querySelector('#downloadPNG');
downloadPNG.addEventListener('click', downloadSVGAsPNG);


问:
Dynamic name dataframe R for loop
I am trying to produce 16 dataframes each with the name of the 16 different proteins, the code I have tried doesn't work</p>

```<code>for (i in seq(1,len_TSPAN)){
  temp_TSPAN <- TSPANS$V1[i]
  print(temp_TSPAN)
  paste(temp_TSPAN) <- data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                            Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                            Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                            Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                            Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                            Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                            Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                            Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                            Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                            Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67))
}
</code>```

答:
Here is another solution, worked off from your loop. Note that I have made up a dataframe for illustration

```<code>TSPANS <- data.frame(V1 = letters[1:12])

myList <- list()

for (i in seq(1,12)){
  temp_TSPAN <- TSPANS$V1[i]
  print(temp_TSPAN)
  x <- data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                                  Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                                  Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                                  Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                                  Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                                  Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                                  Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                                  Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                                  Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                                  Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67), temp_TSPAN = temp_TSPAN)
  myList[[temp_TSPAN]] <- x
}
# I have added a column named, temp_TSPAN, with name of temp_TSPAN  in it. This is because converting the list to a dataframe, as below, will put everything into one.

library(tidyverse)

# You may use this dataframe to subset for your temp_TSPAN variable. Its better to have them in one, them lots of separate dataframes.
df <- bind_rows(myList)
</code>```

Title: Dynamic name dataframe R for loop

Body:
I am trying to produce 16 dataframes each with the name of the 16 different proteins, the code I have tried doesn't work

for (i in seq(1,len_TSPAN)){
  temp_TSPAN <- TSPANS$V1[i]
  print(temp_TSPAN)
  paste(temp_TSPAN) <- data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                            Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                            Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                            Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                            Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                            Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                            Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                            Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                            Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                            Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67))
}

Body:
Here is another solution, worked off from your loop. Note that I have made up a dataframe for illustration

TSPANS <- data.frame(V1 = letters[1:12])

myList <- list()

for (i in seq(1,12)){
  temp_TSPAN <- TSPANS$V1[i]
  print(temp_TSPAN)
  x <- data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                                  Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                                  Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                                  Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                                  Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                                  Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                                  Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                                  Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                                  Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                                  Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67), temp_TSPAN = temp_TSPAN)
  myList[[temp_TSPAN]] <- x
}
# I have added a column named, temp_TSPAN, with name of temp_TSPAN  in it. This is because converting the list to a dataframe, as below, will put everything into one.

library(tidyverse)

# You may use this dataframe to subset for your temp_TSPAN variable. Its better to have them in one, them lots of separate dataframes.
df <- bind_rows(myList)


问:
not able to figure out what sender to return from a leadingSwipeActions for a prepare for segue
Sorry, I am brand new swift and IOS development but I have a table view with each element in the table view I can tap on the item to go to my edit screen which determines the information in the table cell. I would like to also have a leadingSwipeActionsConfigurationForRowAt bring up an edit button that uses the same segue way to get to into edit screen as taping the cell. The issue is that my prepare(for segue:) statement for the handling of the tap segue keeps failing because of the sender of leadingSwipeAction. Now I am really confused about what I should put as my sender in my leadingSwipeAction. I have tried a UITableViewCell() which failed this guard statement:

guard let ViewController = segue.destination as? ViewController else {
                             fatalError("Unexpected destination: \(segue.destination)")
            }

for being a UIView() and then I tried sending a taskCellTableViewCell which is the object/class I called an individual cell but that returned a nil/empty cell which failed another guard statement in the prepare. So now I am confused about how to get and send the actual cell that leadingSwipeAction was performed on. I hope anyone can help me figure out the correct sender I need to return to pass the prepare. Thanks

Here is the code used for the leadingSwipeAction and prepare:

```<code>//leading swipe for editing code
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    let edit = UIContextualAction(style: .normal, title: "Edit") { (contextualAction, view, actionPerformed: (Bool) -> ()) in
        self.performSegue(withIdentifier: "showDetail", sender: UITableViewCell())
        actionPerformed(true)

    }

    return UISwipeActionsConfiguration(actions: [edit])
}

    // Get the new view controller using segue.destination.
    // Pass the selected object to the new view controller.
    super.prepare(for: segue, sender: sender)

    switch(segue.identifier ?? "") {

        case "addItem":
        os_log("Adding a new task.", log: OSLog.default, type: .debug)

        case "showDetail":
        guard let ViewController = segue.destination as? ViewController else {
            fatalError("Unexpected destination: \(segue.destination)")
        }

        guard let selectedTaskCell = sender as? taskCellTableViewCell else {
            fatalError("Unexpected sender: \(sender)")
        }

        guard let indexPath = tableView.indexPath(for: selectedTaskCell) else {
            fatalError("The selected cell is not being displayed by the table")
        }

        let selectedTask = tasks[indexPath.row]
        ViewController.Task = selectedTask

        default:
        fatalError("Unexpected Segue Identifier; \(segue.identifier)")

    }
}
</code>```

it fails trying to use the showDetail segue again.

Also here is a pastebin of the complete code of the project pastebin

答: Ok after searching around and changing my google search using every buzz word I can think of I finally found the answer. To make the sender be the current cell that the LeadingSwipeAction is performed on the sender needs to set to tableView.cellForRow(at: indexPath) which takes the tableView being passed into the LeadingSwipe func and gets cell form the indexPath.

Body:
Sorry, I am brand new swift and IOS development but I have a table view with each element in the table view I can tap on the item to go to my edit screen which determines the information in the table cell. I would like to also have a leadingSwipeActionsConfigurationForRowAt bring up an edit button that uses the same segue way to get to into edit screen as taping the cell. The issue is that my prepare(for segue:) statement for the handling of the tap segue keeps failing because of the sender of leadingSwipeAction. Now I am really confused about what I should put as my sender in my leadingSwipeAction. I have tried a UITableViewCell() which failed this guard statement:

guard let ViewController = segue.destination as? ViewController else {
                             fatalError("Unexpected destination: \(segue.destination)")
            }

for being a UIView() and then I tried sending a taskCellTableViewCell which is the object/class I called an individual cell but that returned a nil/empty cell which failed another guard statement in the prepare. So now I am confused about how to get and send the actual cell that leadingSwipeAction was performed on. I hope anyone can help me figure out the correct sender I need to return to pass the prepare. Thanks

Here is the code used for the leadingSwipeAction and prepare:

//leading swipe for editing code
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    let edit = UIContextualAction(style: .normal, title: "Edit") { (contextualAction, view, actionPerformed: (Bool) -> ()) in
        self.performSegue(withIdentifier: "showDetail", sender: UITableViewCell())
        actionPerformed(true)

    }

    return UISwipeActionsConfiguration(actions: [edit])
}

    // Get the new view controller using segue.destination.
    // Pass the selected object to the new view controller.
    super.prepare(for: segue, sender: sender)

    switch(segue.identifier ?? "") {

        case "addItem":
        os_log("Adding a new task.", log: OSLog.default, type: .debug)

        case "showDetail":
        guard let ViewController = segue.destination as? ViewController else {
            fatalError("Unexpected destination: \(segue.destination)")
        }

        guard let selectedTaskCell = sender as? taskCellTableViewCell else {
            fatalError("Unexpected sender: \(sender)")
        }

        guard let indexPath = tableView.indexPath(for: selectedTaskCell) else {
            fatalError("The selected cell is not being displayed by the table")
        }

        let selectedTask = tasks[indexPath.row]
        ViewController.Task = selectedTask

        default:
        fatalError("Unexpected Segue Identifier; \(segue.identifier)")

    }
}

it fails trying to use the showDetail segue again.

Also here is a pastebin of the complete code of the project pastebin


问:
Subtract time and show difference in mins:secs format
I want to accurately display the difference between two times. The different should be displayed in a format such as mm:ss

```<code>    methods: {
        calcuateTimeDifference: function (startTime, endTime) {
            let result = 0;
            if (startTime && endTime) {
                let start = startTime.split(":");
                let end = endTime.split(':');
                let startTimeInHrs = (parseFloat(start[0]/3600) + parseFloat(start[1]/60) + parseFloat(start[2]/3600));
                let endTimeInHrs = (parseFloat(end[0]/3600) + parseFloat(end[1]/60) + parseFloat(end[2] /3600));
                result = endTimeInHrs - startTimeInHrs;
            }
            return result.toFixed(2);

        },
</code>```

Using this function - the difference between the following times: 16:03:01 - 16:04:01 - I get the result as -32.00.

答:
split the strings on : to get the hours, minutes, and seconds

convert all to seconds and add them to get the total seconds from each time

subtract the two to get the difference in seconds

convert the difference seconds to hours, minutes and seconds using the modules operator(%)

format the result for appropriate display

let start = "16:03:01";
let end  = "16:04:05";

let time = calcuateTimeDifference(start, end);
console.log(time);

function calcuateTimeDifference(startTime, endTime) {

    let result = 0;
    if (startTime && endTime) {

        const start = startTime.split(':').map(Number);
        const end = endTime.split(':').map(Number);

        const startSeconds = (60*60) * start[0] + 60*start[1] + start[2];
        const endSeconds = (60*60) * end[0] + 60*end[1] + end[2];

        const diffSeconds = endSeconds - startSeconds;

        seconds = parseInt((diffSeconds) % 60);
        minutes = parseInt((diffSeconds/60) % 60);
        hours = parseInt((diffSeconds/(60*60)) % 24);

        //append `0` infront if a single digit
        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;

        return `${hours}:${minutes}:${seconds}`;

    }

     console.log("Invalid Input");

}```

Body:
I want to accurately display the difference between two times. The different should be displayed in a format such as mm:ss

    methods: {
        calcuateTimeDifference: function (startTime, endTime) {
            let result = 0;
            if (startTime && endTime) {
                let start = startTime.split(":");
                let end = endTime.split(':');
                let startTimeInHrs = (parseFloat(start[0]/3600) + parseFloat(start[1]/60) + parseFloat(start[2]/3600));
                let endTimeInHrs = (parseFloat(end[0]/3600) + parseFloat(end[1]/60) + parseFloat(end[2] /3600));
                result = endTimeInHrs - startTimeInHrs;
            }
            return result.toFixed(2);

        },

Using this function - the difference between the following times: 16:03:01 - 16:04:01 - I get the result as -32.00.


问:
Is it possible to configure create-react-app express.static options without ejecting?
By default, when an empty folder exists, express.static triggers a 301 redirect adding a forward slash.

This is how I disable this redirect for custom Express servers.

server.use(
  express.static(path.join(__dirname, "build"), {
    redirect: false,
  })
)
```

<p>Is it possible to configure <code>redirect: false</code> when using create-react-app in development mode (<code>npm start</code>?</p>

<p>Having a look at the following headers, I guess Express is what <code>create-react-app</code> uses to serve the SPA in development mode.</p>

<p><strong>Request headers when loading http://localhost:3001/privacy-guides</strong></p>

```HTTP/1.1 301 Moved Permanently
X-Powered-By: Express
Content-Type: text/html; charset=UTF-8
Content-Length: 195
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Location: /privacy-guides/
Vary: Accept-Encoding
```

答:
create-react-app is a build tool, not a server. Its output is a set of static html/js/css files which you are free to serve in any way you want. (npm run build)

The only thing that somehow served with create-react-app is a dev server, which intended to be used only on developer machine, not in production. (npm start)

If you still need to override create-react-app configurations, then take a look on specialized tools like:

https://github.com/timarney/react-app-rewired

https://github.com/harrysolovay/rescripts

https://github.com/gsoft-inc/craco

Body:
By default, when an empty folder exists, express.static triggers a 301 redirect adding a forward slash.

This is how I disable this redirect for custom Express servers.

server.use(
  express.static(path.join(__dirname, "build"), {
    redirect: false,
  })
)

Is it possible to configure redirect: false when using create-react-app in development mode (npm start?

Having a look at the following headers, I guess Express is what create-react-app uses to serve the SPA in development mode.

Request headers when loading http://localhost:3001/privacy-guides

HTTP/1.1 301 Moved Permanently
X-Powered-By: Express
Content-Type: text/html; charset=UTF-8
Content-Length: 195
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Location: /privacy-guides/
Vary: Accept-Encoding


问:
Handle dropdown on Webpage Dialog window using Selenium Webdriver and Java
I am working on automation of a website using Selenium WebDriver and Java, but I am stuck in a situation where on a button click a new webpage dialog opens and on that web page dialog I have perform Operations like entering values / selecting from Dropdowns.

Problem is I am unable to switch to that webpage dialog and even F12 window not working on that webpage dialog. This website is only working on IE. Please help me.

```<code>    driver.findElement(By.id("buttonOK")).click(); //operation on main browser
    Thread.sleep(3000);
    driver.switchTo().activeElement();  // This didn't switch to webpage dialog

     for(String winHandle : driver.getWindowHandles()){  // this code also didn't switchTo webpage dialog
            driver.switchTo().window(winHandle);
        }

    driver.findElement(By.name("textDataValue")).sendKeys("test"); //operation on webpage dialog
</code>```

Screenshot: enter image description here

答:
I think that the current for loop code just switches between all open windows, but you want to switch to a particular open window.

I'd recommend that each loop iteration look for the first By.tagName("title") element and extract the title element's text. That should hopefully correspond to the text in the top bar of the window.

Then, for each window that you switch to, compare that fetched 'title' text with the text which you know is in the top bar of the dialog window ("Add/Modify Address -- Webpage Dialog"). If they match, then you can break out of the for loop and hopefully Selenium will be focused on that dialog window.

Body:
I am working on automation of a website using Selenium WebDriver and Java, but I am stuck in a situation where on a button click a new webpage dialog opens and on that web page dialog I have perform Operations like entering values / selecting from Dropdowns.

Problem is I am unable to switch to that webpage dialog and even F12 window not working on that webpage dialog. This website is only working on IE. Please help me.

    driver.findElement(By.id("buttonOK")).click(); //operation on main browser
    Thread.sleep(3000);
    driver.switchTo().activeElement();  // This didn't switch to webpage dialog

     for(String winHandle : driver.getWindowHandles()){  // this code also didn't switchTo webpage dialog
            driver.switchTo().window(winHandle);
        }

    driver.findElement(By.name("textDataValue")).sendKeys("test"); //operation on webpage dialog

Screenshot: enter image description here


问:
Facing "Devtools was disconnected from the page. Once page is reloaded, Devtools will automatically reconnect."
I'm working on React-native js and Xcode 9.3 for iOS app development, but in between I get this error:

while debugging and becomes a road blocker for me to proceed in the debugging. Also referred few articles from here but didn't get anything for help.

I read this link but it didn't work.

答:
Install https://www.google.com/chrome/canary/ and run Visual Studio, on the debug-Run [Play] button open dropdown cl'ck on Browse and select new installed google chrome canary browser (C:\Users\username\AppData\Local\Google\Chrome SxS\Application\chrome.exe) as default debugger.

This worked for me.


问:
Python: Tkinter :Dynamically Create Label
I am trying to create Label Dynamically , I am getting invalid Syntax. Can you please help me what i am missing or any alternative</p>

```<code>      crsr = cnxn.execute(query)
        row_num=2
        column_num=0
        Variable_Number=1
        for row in crsr.fetchall():

            test='Column_Label'+str(Variable_Number)+' = tk.Label(frame,text="'+row[0]+'")'

#proper Indentation availabe in code        test1='Column_Label'+str(Variable_Number)+'.grid(row='+str(row_num)+',column='+str(column_num)+')'
            eval(test+';'+test1)
    #        eval(test1)
            row_num+=1
            column_num+=1
        root.update_idletasks()
</code>```

答:
You should not be using exec. If you want to associate a computed name with a widget in a loop, use a dictionary:

```<code>labels = {}
varnum = 0
for row in crsr.fetchall():
    name=f"label#{varnum}"
    labels[name] = tk.Label(frame, text=str(row[0]))
    labels[name].grid(row=row_num, column=column_num
    varnum += 1
    row_num+=1
    column_num+=1
</code>```

If you don't really care what the name is, you can store the widgets in a list rather than a dictionary, and then reference them using an integer index (eg: labels[0], labels[1], etc).

Body:
I am trying to create Label Dynamically , I am getting invalid Syntax. Can you please help me what i am missing or any alternative

      crsr = cnxn.execute(query)
        row_num=2
        column_num=0
        Variable_Number=1
        for row in crsr.fetchall():

            test='Column_Label'+str(Variable_Number)+' = tk.Label(frame,text="'+row[0]+'")'

#proper Indentation availabe in code        test1='Column_Label'+str(Variable_Number)+'.grid(row='+str(row_num)+',column='+str(column_num)+')'
            eval(test+';'+test1)
    #        eval(test1)
            row_num+=1
            column_num+=1
        root.update_idletasks()

Body:
You should not be using exec. If you want to associate a computed name with a widget in a loop, use a dictionary:

labels = {}
varnum = 0
for row in crsr.fetchall():
    name=f"label#{varnum}"
    labels[name] = tk.Label(frame, text=str(row[0]))
    labels[name].grid(row=row_num, column=column_num
    varnum += 1
    row_num+=1
    column_num+=1

If you don't really care what the name is, you can store the widgets in a list rather than a dictionary, and then reference them using an integer index (eg: labels[0], labels[1], etc).


问:
Generating smooth normals for terrains in OpenGL
I'm implementing a system to generate terrains using perlin noise. This is how I generate the vertices:

```<code>int arrayIdx = 0;

    for(float x = offset.x - CHUNK_WIDTH / 2.0f; x < float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f; x += TRIANGLE_WIDTH) {
        for(float y = offset.y - CHUNK_WIDTH / 2.0f; y < float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f; y += TRIANGLE_WIDTH) {
            float height0 = noise->octaveNoise(x + 0.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH),
            height1 = noise->octaveNoise(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH),
            height2 = noise->octaveNoise(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH),
            height3 = noise->octaveNoise(x + 1.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);

            mapVertices[arrayIdx + 0] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height0, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 1] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height1, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 2] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height2, y + 1.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 3] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height3, y + 1.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 4] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height1, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 5] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height2, y + 1.0f * TRIANGLE_WIDTH);

            mapUVs[arrayIdx + 0] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 1] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 2] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 3] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 4] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 5] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);

            glm::vec3 normal0 = -1.0f * glm::triangleNormal(mapVertices[arrayIdx + 0], mapVertices[arrayIdx + 1], mapVertices[arrayIdx + 2]),
            normal1 = +1.0f * glm::triangleNormal(mapVertices[arrayIdx + 3], mapVertices[arrayIdx + 4], mapVertices[arrayIdx + 5]);

            mapNormals[arrayIdx + 0] = normal0;
            mapNormals[arrayIdx + 1] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 2] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 3] = normal1;
            mapNormals[arrayIdx + 4] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 5] = (normal0 + normal1) / 2.0f;

            arrayIdx += 6;
        }
    }
</code>```

Not using lighting produces these quite smooth results,

The only thing left to do is to generate normals for the triangles, that will make the terrain look smooth.
Just using glm::triangleNormal yields this result,

As you can see, lighting really destroys the illusion of a smooth surface.

I tried using an average value of normals on the colliding vertices of the triangles like this:

```<code>arrayIdx = 0;

    for(float x = offset.x - CHUNK_WIDTH / 2.0f; x < float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f; x += TRIANGLE_WIDTH) {
        for(float y = offset.y - CHUNK_WIDTH / 2.0f; y < float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f; y += TRIANGLE_WIDTH) {

            if((x == offset.x - CHUNK_WIDTH / 2.0f && y == offset.y - CHUNK_WIDTH / 2.0f) ||
               (x == float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH && y == offset.y - CHUNK_WIDTH / 2.0f) ||
               (x == offset.x - CHUNK_WIDTH / 2.0f && y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH) ||
               (x == float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH && y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH)) {
                //Special case
            }
            else if(x ==  float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH ||
                    y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH) {
                 //Special case
            }
            else {
                glm::vec3 averageNormals = (mapNormals[arrayIdx + 3 + 0] + //This triangle
                                            mapNormals[arrayIdx + 0 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6 + 6] + //Triangle after and this one
                                            mapNormals[arrayIdx + 2 + 6] + //Triangle in the right
                                            mapNormals[arrayIdx + 5 + 6] + //Triangle in the right
                                            mapNormals[arrayIdx + 1 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] + //Triangle after this one
                                            mapNormals[arrayIdx + 4 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6])  //Triangle after this one
                                            / 6.0f;

                mapNormals[arrayIdx + 3 + 0] = averageNormals;
                mapNormals[arrayIdx + 2 + 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 5 + 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 1 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 4 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 0 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6 + 6] = mapNormals[arrayIdx + 3 + 0];
            }

            arrayIdx += 6;
        }
    }
</code>```

which yielded this result,

but this doesn't look much better.

Using the normals as fragment color give this result:

Rendering the normals as lines yields this, this is before the optimization and with larger triangles, to reduce the number of lines:

This is with my optimization:

Somehow, two normals dont get set.

The blue lines here are the average normals, the green lines are the individual normals before optimizing, they look good:

This is with wireframe:

Maybe some normals aren't set to the average value?

How can I generate normals that are smooth?

答:
The way to compute the per-vertex normal is as follows: You have to consider each polygon that the vertex also belongs to, for instance:

As you mentioned, the problem seems to be related to lighting. Having the proper per-vertex normal computed, you should be also using the correct shading technique, which in this case would be Phong or Gouraud shading instead of Flat shading, as it appears you are using.

Body:
I'm implementing a system to generate terrains using perlin noise. This is how I generate the vertices:

int arrayIdx = 0;

    for(float x = offset.x - CHUNK_WIDTH / 2.0f; x < float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f; x += TRIANGLE_WIDTH) {
        for(float y = offset.y - CHUNK_WIDTH / 2.0f; y < float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f; y += TRIANGLE_WIDTH) {
            float height0 = noise->octaveNoise(x + 0.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH),
            height1 = noise->octaveNoise(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH),
            height2 = noise->octaveNoise(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH),
            height3 = noise->octaveNoise(x + 1.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);

            mapVertices[arrayIdx + 0] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height0, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 1] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height1, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 2] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height2, y + 1.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 3] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height3, y + 1.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 4] = glm::vec3(x + 1.0f * TRIANGLE_WIDTH, height1, y + 0.0f * TRIANGLE_WIDTH);
            mapVertices[arrayIdx + 5] = glm::vec3(x + 0.0f * TRIANGLE_WIDTH, height2, y + 1.0f * TRIANGLE_WIDTH);

            mapUVs[arrayIdx + 0] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 1] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 2] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 3] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 4] = glm::vec2(x + 1.0f * TRIANGLE_WIDTH, y + 0.0f * TRIANGLE_WIDTH);
            mapUVs[arrayIdx + 5] = glm::vec2(x + 0.0f * TRIANGLE_WIDTH, y + 1.0f * TRIANGLE_WIDTH);

            glm::vec3 normal0 = -1.0f * glm::triangleNormal(mapVertices[arrayIdx + 0], mapVertices[arrayIdx + 1], mapVertices[arrayIdx + 2]),
            normal1 = +1.0f * glm::triangleNormal(mapVertices[arrayIdx + 3], mapVertices[arrayIdx + 4], mapVertices[arrayIdx + 5]);

            mapNormals[arrayIdx + 0] = normal0;
            mapNormals[arrayIdx + 1] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 2] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 3] = normal1;
            mapNormals[arrayIdx + 4] = (normal0 + normal1) / 2.0f;
            mapNormals[arrayIdx + 5] = (normal0 + normal1) / 2.0f;

            arrayIdx += 6;
        }
    }

Not using lighting produces these quite smooth results,

The only thing left to do is to generate normals for the triangles, that will make the terrain look smooth.
Just using glm::triangleNormal yields this result,

As you can see, lighting really destroys the illusion of a smooth surface.

I tried using an average value of normals on the colliding vertices of the triangles like this:

arrayIdx = 0;

    for(float x = offset.x - CHUNK_WIDTH / 2.0f; x < float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f; x += TRIANGLE_WIDTH) {
        for(float y = offset.y - CHUNK_WIDTH / 2.0f; y < float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f; y += TRIANGLE_WIDTH) {

            if((x == offset.x - CHUNK_WIDTH / 2.0f && y == offset.y - CHUNK_WIDTH / 2.0f) ||
               (x == float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH && y == offset.y - CHUNK_WIDTH / 2.0f) ||
               (x == offset.x - CHUNK_WIDTH / 2.0f && y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH) ||
               (x == float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH && y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH)) {
                //Special case
            }
            else if(x ==  float(CHUNK_WIDTH) + offset.x - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH ||
                    y ==  float(CHUNK_WIDTH) + offset.y - CHUNK_WIDTH / 2.0f - TRIANGLE_WIDTH) {
                 //Special case
            }
            else {
                glm::vec3 averageNormals = (mapNormals[arrayIdx + 3 + 0] + //This triangle
                                            mapNormals[arrayIdx + 0 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6 + 6] + //Triangle after and this one
                                            mapNormals[arrayIdx + 2 + 6] + //Triangle in the right
                                            mapNormals[arrayIdx + 5 + 6] + //Triangle in the right
                                            mapNormals[arrayIdx + 1 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] + //Triangle after this one
                                            mapNormals[arrayIdx + 4 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6])  //Triangle after this one
                                            / 6.0f;

                mapNormals[arrayIdx + 3 + 0] = averageNormals;
                mapNormals[arrayIdx + 2 + 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 5 + 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 1 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 4 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6] = mapNormals[arrayIdx + 3 + 0];
                mapNormals[arrayIdx + 0 + int(CHUNK_WIDTH * (1.0f / TRIANGLE_WIDTH)) * 6 + 6] = mapNormals[arrayIdx + 3 + 0];
            }

            arrayIdx += 6;
        }
    }

which yielded this result,

but this doesn't look much better.

Using the normals as fragment color give this result:

Rendering the normals as lines yields this, this is before the optimization and with larger triangles, to reduce the number of lines:

This is with my optimization:

Somehow, two normals dont get set.

The blue lines here are the average normals, the green lines are the individual normals before optimizing, they look good:

This is with wireframe:

Maybe some normals aren't set to the average value?

How can I generate normals that are smooth?


问:
Set MySQL timestamp to random time within past 24 hours
I have a timestamp column in my MySQL table.

I'm wanting to set this timestamp to a random time within the past 24 hours for all rows in the table.

I know I can update all the rows doing this:

```<code>UPDATE table SET timestamp =
</code>```

But I can't find if there's a way to set a random timestamp that's occurred within the past 24 hours so that each row has a different time.

答:
Check this might work for you.

```<code>update table name set timestamp = now() - interval floor(rand()*(60*60*24*2)) second;
</code>```

Output:
you will get the current timestamp- between 0 seconds and two days.

If you want to change 2 days to 3 days or any days just need to change(60*60*24***Days enter here**))

Body:
I have a timestamp column in my MySQL table.

I'm wanting to set this timestamp to a random time within the past 24 hours for all rows in the table.

I know I can update all the rows doing this:

UPDATE table SET timestamp =

But I can't find if there's a way to set a random timestamp that's occurred within the past 24 hours so that each row has a different time.

Body:
Check this might work for you.

update table name set timestamp = now() - interval floor(rand()*(60*60*24*2)) second;

Output:
you will get the current timestamp- between 0 seconds and two days.

If you want to change 2 days to 3 days or any days just need to change(60*60*24***Days enter here**))


问:
How to remove a current page from stack navigation Xamarin Forms
I'm trying so hard to do something but i wasnt able to solve this problem. I have three pages, One is the MainPage, LoginUpPage and SignUpPage, inside of LoginUpPage has a button who navigates to SignUpPage, what i want to do is when I finish my logic navigates to another page CreatedPage, whitch contains a Label with a Message - Success and then after 2 seconds GoBack to the LoginPage, the problem is if I press the backbutton from device it will return to the last page that has the label with a message and I don't want that. I have a toobar with a BackButton to return to each page that i navigates. So far I have this:

LoginPage to SignUpPage :

```<code>Navigation.PushAsync(new SignupPage());
</code>```

SignUpPage to CreatedPage :

```<code>await Navigation.PushModalAsync(new Created());
</code>```

And inside of CreatedPage in my Contructor, this Method :

```<code>    public async void Redirect()
    {
        await Task.Delay(TimeSpan.FromSeconds(2));
        await Navigation.PushAsync(new LoginPage());
    }
</code>```

I know by this question there's basically three ways to navigate to another page :

```<code>Navigation.PushAsync(new OtherPage()); // to show OtherPage and be able to go back
</code>```

Navigation.PushAsyncModal(new AnotherPage());// to show AnotherPage and not have a Back button

Navigation.PopAsync();// to go back one step on the navigation stack

At the same question has a example how to remove from a page from stack but it doesn't work.

```<code>item.Tapped += async (sender, e) => {
await Navigation.PushAsync (new SecondPage ());
Navigation.RemovePage(this);
</code>```

};

答:
The easiest way I found to clear a stack and open up a new page on a clear stack

```<code>await Navigation.PushAsync(new UserJourneysTabPage()); //Push the page you want to push
            var existingPages = Navigation.NavigationStack.ToList();
            //get all the pages in the stack
            foreach (var page in existingPages)
            {
                    //Check they type of the page if its not the
                    //same type as the newly created one remove it
                    if (page.GetType() == typeof(UserJourneysTabPage))

                    continue;

                Navigation.RemovePage(page);
            }
</code>```

Note: This doesn't clear a page from the navigation stack if its the same type, but you can always add a property to distinguish the newly created one from the old ones

ContentLicense: CC BY-SA 3.0

Body:
I'm trying so hard to do something but i wasnt able to solve this problem. I have three pages, One is the MainPage, LoginUpPage and SignUpPage, inside of LoginUpPage has a button who navigates to SignUpPage, what i want to do is when I finish my logic navigates to another page CreatedPage, whitch contains a Label with a Message - Success and then after 2 seconds GoBack to the LoginPage, the problem is if I press the backbutton from device it will return to the last page that has the label with a message and I don't want that. I have a toobar with a BackButton to return to each page that i navigates. So far I have this:

LoginPage to SignUpPage :

Navigation.PushAsync(new SignupPage());

SignUpPage to CreatedPage :

await Navigation.PushModalAsync(new Created());

And inside of CreatedPage in my Contructor, this Method :

    public async void Redirect()
    {
        await Task.Delay(TimeSpan.FromSeconds(2));
        await Navigation.PushAsync(new LoginPage());
    }

I know by this question there's basically three ways to navigate to another page :

Navigation.PushAsync(new OtherPage()); // to show OtherPage and be able to go back

Navigation.PushAsyncModal(new AnotherPage());// to show AnotherPage and not have a Back button

Navigation.PopAsync();// to go back one step on the navigation stack

At the same question has a example how to remove from a page from stack but it doesn't work.

item.Tapped += async (sender, e) => {
await Navigation.PushAsync (new SecondPage ());
Navigation.RemovePage(this);

};

Body:
The easiest way I found to clear a stack and open up a new page on a clear stack

await Navigation.PushAsync(new UserJourneysTabPage()); //Push the page you want to push
            var existingPages = Navigation.NavigationStack.ToList();
            //get all the pages in the stack
            foreach (var page in existingPages)
            {
                    //Check they type of the page if its not the
                    //same type as the newly created one remove it
                    if (page.GetType() == typeof(UserJourneysTabPage))

                    continue;

                Navigation.RemovePage(page);
            }

Note: This doesn't clear a page from the navigation stack if its the same type, but you can always add a property to distinguish the newly created one from the old ones


问:
How to Register Font which was pick up from UIDocument
I'm trying to Register Font which was pick up from UIDocument, everything works fine

I enabled Install Fonts capability under the Signing & Capabilities and I accessed the UIDocument file and I pick the font. but I don't know how to register it.

This is my code

```<code>@objc func didPressButton(_ sender: UIButton) {
    let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.truetype-ttf-font", "public.opentype-font"], in: UIDocumentPickerMode.import)
     documentPicker.delegate = self
    self.present(documentPicker, animated: true, completion: nil)
}

// MARK: - UIDocumentPickerDelegate Methods
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {

    let fontUrl = Bundle(for: type(of : self)).path(forResource: "\(urls[0].path)", ofType: nil)
   CTFontManagerRegisterFontURLs([fontUrl] as CFArray, .persistent, true) { (errors, done) -> Bool in
       if(done) {
           print("Done")
       }
       print(errors as Array)
    for family in UIFont.familyNames.sorted() {
        let names = UIFont.fontNames(forFamilyName: family)
        print("Family: \(family) Font names: \(names)")
    }

       return true
   }
}

 func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    controller.dismiss(animated: true, completion: nil)
}
</code>```

答:
I figured it out at last and this is the answer for other people looking for a solution.</p>

```<code> @objc func didPressButton(_ sender: UIButton) {
        let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.truetype-ttf-font", "public.opentype-font"], in: UIDocumentPickerMode.import)
         documentPicker.delegate = self
        self.present(documentPicker, animated: true, completion: nil)
    }

    // MARK: - UIDocumentPickerDelegate Methods
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {

       self.handleFileSelection(inUrl: urls.first!)

    }

     func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        controller.dismiss(animated: true, completion: nil)
    }

    private func handleFileSelection(inUrl:URL) -> Void {
        do {
         // inUrl is the document's URL
            let fontData = try Data(contentsOf: inUrl) // Getting file data here
            let dataProvider = CGDataProvider(data: fontData as CFData)
            let cgFont = CGFont(dataProvider!)

                var error: Unmanaged<CFError>?
            if !CTFontManagerRegisterGraphicsFont(cgFont!, &error)
                {
                    print("Error loading Font!")
                } else {

                let fontName = cgFont!.postScriptName

                self.lab.font = UIFont(name: String(fontName!), size: 30)
                for family in UIFont.familyNames.sorted() {
                    let names = UIFont.fontNames(forFamilyName: family)
                    print("Family: \(family) Font names: \(names)")
                }
            }

        } catch {
            print("document loading error")
        }
    }
</code>```

Body:
I'm trying to Register Font which was pick up from UIDocument, everything works fine

I enabled Install Fonts capability under the Signing & Capabilities and I accessed the UIDocument file and I pick the font. but I don't know how to register it.

This is my code

@objc func didPressButton(_ sender: UIButton) {
    let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.truetype-ttf-font", "public.opentype-font"], in: UIDocumentPickerMode.import)
     documentPicker.delegate = self
    self.present(documentPicker, animated: true, completion: nil)
}

// MARK: - UIDocumentPickerDelegate Methods
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {

    let fontUrl = Bundle(for: type(of : self)).path(forResource: "\(urls[0].path)", ofType: nil)
   CTFontManagerRegisterFontURLs([fontUrl] as CFArray, .persistent, true) { (errors, done) -> Bool in
       if(done) {
           print("Done")
       }
       print(errors as Array)
    for family in UIFont.familyNames.sorted() {
        let names = UIFont.fontNames(forFamilyName: family)
        print("Family: \(family) Font names: \(names)")
    }

       return true
   }
}

 func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    controller.dismiss(animated: true, completion: nil)
}

Body:
I figured it out at last and this is the answer for other people looking for a solution.

 @objc func didPressButton(_ sender: UIButton) {
        let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.truetype-ttf-font", "public.opentype-font"], in: UIDocumentPickerMode.import)
         documentPicker.delegate = self
        self.present(documentPicker, animated: true, completion: nil)
    }

    // MARK: - UIDocumentPickerDelegate Methods
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {

       self.handleFileSelection(inUrl: urls.first!)

    }

     func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        controller.dismiss(animated: true, completion: nil)
    }

    private func handleFileSelection(inUrl:URL) -> Void {
        do {
         // inUrl is the document's URL
            let fontData = try Data(contentsOf: inUrl) // Getting file data here
            let dataProvider = CGDataProvider(data: fontData as CFData)
            let cgFont = CGFont(dataProvider!)

                var error: Unmanaged<CFError>?
            if !CTFontManagerRegisterGraphicsFont(cgFont!, &error)
                {
                    print("Error loading Font!")
                } else {

                let fontName = cgFont!.postScriptName

                self.lab.font = UIFont(name: String(fontName!), size: 30)
                for family in UIFont.familyNames.sorted() {
                    let names = UIFont.fontNames(forFamilyName: family)
                    print("Family: \(family) Font names: \(names)")
                }
            }

        } catch {
            print("document loading error")
        }
    }


问:
Lateral Flatten Snowpipe data with mixture of arrays and dict
I have two different structured json files being piped in from a snowpipe. The only difference is that instead of a nested dict it has many nested arrays. I am trying to figure out how to transform structure 1 into one finalized table. I've successfully transformed structure 2 into a table and included the code below.

I know I need to be making use of lateral flatten but have not been successful.

```<code>**Structure 1: Nested Arrays (Need help on)**
This json lives within a table and in column **JSONTEXT**
[
  {
    "ID": "xxx-xxxx-xxxx xxx-xxx",
    "caseTypeID": "xx-xxxx-xxxx-xxxxx",
    "content": {
      "AccountID": "xx-xxxxx-xxxx-xxxx xxxx-xxxxx",
      "AccountName": "XXXX",
      "Address": {
        "pxObjClass": "Data-Address-Postal"
      },
      "Addresses": [],
      "AllKickoffsComplete": "true",
      "BillingContactList": [],
      "ClientCurrency": "USD",
      "ClientID": "XXXXXX",
      "ClientNSID": "XXXXXXXX-00",
      "ClientName": "XXXXX XXXX Inc.",
      "CompanyPhoneNumber": "XXX-XXX-XXXX",
      "CrmSearchOrg": "XXXX",
      "EEList": [
        {
          "AccountID": "xxx-xxxxx-xxxx-xxxxx xxxx-xxxxx",
          "AccountName": "XXXX",
          "AllowanceList": [
            {
              "AllowanceAmount": "327",
              "AllowanceName": "Car Allowance",
              "pxObjClass": "xxxxx-xxxxx-xxxxx"
]
</code>```

Structure 2: Nested Dict
This json lives within a table and in column JSONTEXT

```<code>[
  {
    "OppID": "xxxx-xxxxx",
    "pxObjClass": "xx-xxxxx-xxxx-xxxxxx",
    "pxPages": {
      "EEList": {
        "Country": "xxx",
        "CountryName": "xxx",
        "Currency": "xxx",
        "EstimatedICPCost": "xxxxxxxxxxx",
        "ICPCurrency": "xxxxx",
        "ICPID": "xxxxxxxxx.",
        "ICPNSID": "xxxx-xx",
        "ICPName": "xxx xx xx.",
        "LocalMonthlySalary": "xxxxxx",
        "MinFee": "xxxx",
        "MonthlyGrossCost": "xxxxx",
        "NewOrRepeatCustomer": "xxxxx",
        "OppCloseDate": "xxx-xxx-xx",
        "OppID": "xxx-xxxx",
        "OpportunityName": "xxx - xxx xxx - xxx - xxxx",
        "ReferralSource": "xxxxxx",
        "pxObjClass": "Index-xx-xxxx-xxxx-xxxxxx",
        "pxSubscript": "EEList"
      }
    },
    "pyID": "xxxxxx",
    "pzInsKey": "xxxx-xxxx-xxxx xxxxx-xxx"
  },
]
</code>```

Here is my code for the second structure that works.

```<code>create or replace table xxxx
    as select
    value:ID::varchar as ID,
    value:caseTypeID::varchar as caseTypeID,
    value:content:AccountID::varchar as AccountID,
    value:content:AccountName::varchar as AccountName,
    value:content:AllKickoffsComplete::boolean as AllKickoffsComplete,
    value:content:ClientCurrency::varchar as ClientCurrency,
    value:content:ClientID::varchar as ClientID,
    value:content:ClientNSID::varchar as ClientNSID,
    value:content:ClientName::varchar as ClientName,
    value:content:CompanyAddressCountryName::varchar as CompanyAddressCountryName,
    value:content:CompanyPhoneNumber::varchar as CompanyPhoneNumber,
    value:content:CreateNew::boolean as CreateNew,
    value:content:CrmSearchOrg::varchar as CrmSearchOrg,
    value:content:EEList:AccountID::varchar as EE_AccountID,
    value:content:EEList:AccountName::varchar as EE_AccountName
from new_raw_json,
    lateral flatten (input =>jsontext);
</code>```

Here is code I've tried it only works when you put jsontext[Nth].

```<code>select
    value:ID::varchar as ID,
    value:EEListID::varchar as EEListID,
    value:caseTypeID::varchar as caseTypeID
    from new_raw_json,

    lateral flatten (input => jsontext[0]:content:EEList);
</code>```

Appreciate any help!

答:
You can chain multiple lateral views using FLATTEN to continue exploding into nested structures (arrays within arrays).

An explicitly defined approach may appear this way (only some columns are projected here, to illustrate levels):

SELECT
  outer_object.value:caseTypeID AS caseTypeID,
  outer_object.value:content.AccountID AS parentAccountID,
  eelist_object.value:AccountID AS eeListAccountID,
  allowance_object.value:AllowanceName
FROM
  new_raw_json,
  LATERAL FLATTEN (input => jsontext) outer_object,
  LATERAL FLATTEN (input => outer_object.value:content.EEList) eelist_object,
  LATERAL FLATTEN (input => eelist_object.value:AllowanceList) allowance_object;
```

Note that this only explodes one identified multi-value path (List -> EEList -> AllowanceList). It is unclear from the question if all the paths have to be exploded (such as List -> EEList -> Addresses AND AllowanceList) or if it is acceptable to store some of them as VARIANT (or other complex) type in the final result.

For example, if there is a need to to duplicate AllowanceList values for every listed address in Addresses under EEList, this could be achieved by performing a JOIN from two exploding query results (one that chains List -> Addresses and another that chains List -> EEList -> AllowanceList).

Body:
I have two different structured json files being piped in from a snowpipe. The only difference is that instead of a nested dict it has many nested arrays. I am trying to figure out how to transform structure 1 into one finalized table. I've successfully transformed structure 2 into a table and included the code below.

I know I need to be making use of lateral flatten but have not been successful.

**Structure 1: Nested Arrays (Need help on)**
This json lives within a table and in column **JSONTEXT**
[
  {
    "ID": "xxx-xxxx-xxxx xxx-xxx",
    "caseTypeID": "xx-xxxx-xxxx-xxxxx",
    "content": {
      "AccountID": "xx-xxxxx-xxxx-xxxx xxxx-xxxxx",
      "AccountName": "XXXX",
      "Address": {
        "pxObjClass": "Data-Address-Postal"
      },
      "Addresses": [],
      "AllKickoffsComplete": "true",
      "BillingContactList": [],
      "ClientCurrency": "USD",
      "ClientID": "XXXXXX",
      "ClientNSID": "XXXXXXXX-00",
      "ClientName": "XXXXX XXXX Inc.",
      "CompanyPhoneNumber": "XXX-XXX-XXXX",
      "CrmSearchOrg": "XXXX",
      "EEList": [
        {
          "AccountID": "xxx-xxxxx-xxxx-xxxxx xxxx-xxxxx",
          "AccountName": "XXXX",
          "AllowanceList": [
            {
              "AllowanceAmount": "327",
              "AllowanceName": "Car Allowance",
              "pxObjClass": "xxxxx-xxxxx-xxxxx"
]

Structure 2: Nested Dict
This json lives within a table and in column JSONTEXT

[
  {
    "OppID": "xxxx-xxxxx",
    "pxObjClass": "xx-xxxxx-xxxx-xxxxxx",
    "pxPages": {
      "EEList": {
        "Country": "xxx",
        "CountryName": "xxx",
        "Currency": "xxx",
        "EstimatedICPCost": "xxxxxxxxxxx",
        "ICPCurrency": "xxxxx",
        "ICPID": "xxxxxxxxx.",
        "ICPNSID": "xxxx-xx",
        "ICPName": "xxx xx xx.",
        "LocalMonthlySalary": "xxxxxx",
        "MinFee": "xxxx",
        "MonthlyGrossCost": "xxxxx",
        "NewOrRepeatCustomer": "xxxxx",
        "OppCloseDate": "xxx-xxx-xx",
        "OppID": "xxx-xxxx",
        "OpportunityName": "xxx - xxx xxx - xxx - xxxx",
        "ReferralSource": "xxxxxx",
        "pxObjClass": "Index-xx-xxxx-xxxx-xxxxxx",
        "pxSubscript": "EEList"
      }
    },
    "pyID": "xxxxxx",
    "pzInsKey": "xxxx-xxxx-xxxx xxxxx-xxx"
  },
]

Here is my code for the second structure that works.

create or replace table xxxx
    as select
    value:ID::varchar as ID,
    value:caseTypeID::varchar as caseTypeID,
    value:content:AccountID::varchar as AccountID,
    value:content:AccountName::varchar as AccountName,
    value:content:AllKickoffsComplete::boolean as AllKickoffsComplete,
    value:content:ClientCurrency::varchar as ClientCurrency,
    value:content:ClientID::varchar as ClientID,
    value:content:ClientNSID::varchar as ClientNSID,
    value:content:ClientName::varchar as ClientName,
    value:content:CompanyAddressCountryName::varchar as CompanyAddressCountryName,
    value:content:CompanyPhoneNumber::varchar as CompanyPhoneNumber,
    value:content:CreateNew::boolean as CreateNew,
    value:content:CrmSearchOrg::varchar as CrmSearchOrg,
    value:content:EEList:AccountID::varchar as EE_AccountID,
    value:content:EEList:AccountName::varchar as EE_AccountName
from new_raw_json,
    lateral flatten (input =>jsontext);

Here is code I've tried it only works when you put jsontext[Nth].

select
    value:ID::varchar as ID,
    value:EEListID::varchar as EEListID,
    value:caseTypeID::varchar as caseTypeID
    from new_raw_json,

    lateral flatten (input => jsontext[0]:content:EEList);

Appreciate any help!

Body:
You can chain multiple lateral views using FLATTEN to continue exploding into nested structures (arrays within arrays).

An explicitly defined approach may appear this way (only some columns are projected here, to illustrate levels):

SELECT
  outer_object.value:caseTypeID AS caseTypeID,
  outer_object.value:content.AccountID AS parentAccountID,
  eelist_object.value:AccountID AS eeListAccountID,
  allowance_object.value:AllowanceName
FROM
  new_raw_json,
  LATERAL FLATTEN (input => jsontext) outer_object,
  LATERAL FLATTEN (input => outer_object.value:content.EEList) eelist_object,
  LATERAL FLATTEN (input => eelist_object.value:AllowanceList) allowance_object;

Note that this only explodes one identified multi-value path (List -> EEList -> AllowanceList). It is unclear from the question if all the paths have to be exploded (such as List -> EEList -> Addresses AND AllowanceList) or if it is acceptable to store some of them as VARIANT (or other complex) type in the final result.

For example, if there is a need to to duplicate AllowanceList values for every listed address in Addresses under EEList, this could be achieved by performing a JOIN from two exploding query results (one that chains List -> Addresses and another that chains List -> EEList -> AllowanceList).


问:
Failed to save data in mongoDB
when trying to save in my Mongo database, I can't record the data, to the point of connection with the DB is fine but then it doesn't save the data.
Today is my first day with Mongo, it may be that something is wrongly configured.

My controller

```<code>exports.nuevoCliente = async (req, res, next) => {
    // console.log(req.body);

    const paciente = new Paciente(req.body);
    try {
        await paciente.save();
        res.json({ mensaje : 'El cliente se agregó correctamente'});
        console.log(paciente);

    } catch (error) {
        console.log(error);
        next();
    }
}
</code>```

When I run:

```<code>console.log(paciente);
</code>```

Result = __v: 0

Model:

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const pacientesSchema = new Schema({
    nombre: {
        type: String,
        trim: true,
    },
    propietario: {
        type: String,
        trim: true
    },
    fecha: {
        type: String,
        trim: true
    },
    telefono: {
        type: String,
        trim: true
    },
    hora: {
        type: String,
        trim: true
    },
    sintomas: {
        type: String,
        trim: true
    }
});

module.exports = mongoose.model('Paciente', pacientesSchema);
</code>```

Routes

```<code>const express = require('express');
const router = express.Router();
// Importar el controlador
const pacienteController = require('../controllers/pacienteControllers');

module.exports = function() {

    // router.get('/', () => {
    //     console.log('en home');

    // });

    // Agrega nuevos pacientes via POST
    router.post('/pacientes',
        pacienteController.nuevoCliente
    );

    return router;
}
</code>```

And the index:

```<code>const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');
const bodyParser = require('body-parser');

// Crear el servidor
const app = express();

// Conectar con MongoDB
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/veterinaria', {
    useNewUrlParser: true,
    useUnifiedTopology:true,
    useFindAndModify:false
});

// Habilitar el body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// Habilitar Routing
app.use('/', routes())

// Puerto y Arrancar
app.listen(4000, () => {
    console.log('Servidor funcionando')
})
</code>```

A screenshot of the configuration in atlas

Thanks friends.

答:
I think that the problem is in the AWAIT used at saving point.
Try to use:

```<code>paciente.save(function (err, saved) {
    if (err) {
      console.log(err);
    }
    else {
       console.log(saved);
       res.json({ mensaje : 'El cliente se agregó correctamente'});
    }
}
</code>```

Anyway to check if it's really saved, you can connect to mongo trough shell
   https://docs.mongodb.com/manual/reference/mongo-shell/ and query manually the collection.

Title: Failed to save data in mongoDB

Body:
when trying to save in my Mongo database, I can't record the data, to the point of connection with the DB is fine but then it doesn't save the data.
Today is my first day with Mongo, it may be that something is wrongly configured.

My controller

exports.nuevoCliente = async (req, res, next) => {
    // console.log(req.body);

    const paciente = new Paciente(req.body);
    try {
        await paciente.save();
        res.json({ mensaje : 'El cliente se agregó correctamente'});
        console.log(paciente);

    } catch (error) {
        console.log(error);
        next();
    }
}

When I run:

console.log(paciente);

Result = __v: 0

Model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const pacientesSchema = new Schema({
    nombre: {
        type: String,
        trim: true,
    },
    propietario: {
        type: String,
        trim: true
    },
    fecha: {
        type: String,
        trim: true
    },
    telefono: {
        type: String,
        trim: true
    },
    hora: {
        type: String,
        trim: true
    },
    sintomas: {
        type: String,
        trim: true
    }
});

module.exports = mongoose.model('Paciente', pacientesSchema);

Routes

const express = require('express');
const router = express.Router();
// Importar el controlador
const pacienteController = require('../controllers/pacienteControllers');

module.exports = function() {

    // router.get('/', () => {
    //     console.log('en home');

    // });

    // Agrega nuevos pacientes via POST
    router.post('/pacientes',
        pacienteController.nuevoCliente
    );

    return router;
}

And the index:

const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');
const bodyParser = require('body-parser');

// Crear el servidor
const app = express();

// Conectar con MongoDB
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/veterinaria', {
    useNewUrlParser: true,
    useUnifiedTopology:true,
    useFindAndModify:false
});

// Habilitar el body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// Habilitar Routing
app.use('/', routes())

// Puerto y Arrancar
app.listen(4000, () => {
    console.log('Servidor funcionando')
})

A screenshot of the configuration in atlas

Thanks friends.

Body:
I think that the problem is in the AWAIT used at saving point.
Try to use:

paciente.save(function (err, saved) {
    if (err) {
      console.log(err);
    }
    else {
       console.log(saved);
       res.json({ mensaje : 'El cliente se agregó correctamente'});
    }
}

Anyway to check if it's really saved, you can connect to mongo trough shell
   https://docs.mongodb.com/manual/reference/mongo-shell/ and query manually the collection.


问:
how to solve this div overlay problem in css
How to solve div overlay problem here I've one div in this div I've added two class col-sm-6. But when I am checking responsive it will going over of the div. I don't know how to solve. can anyone please help me.

I've attch the image of the output you can see :)

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

Showing 1 to 6 of 6 entries

        <button class="btn btn-link previous">Previous</button>
        <button class="btn btn-info number">1</button>
        <button class="btn btn-link next">Next</button>

```

答:
have found mobile grid class (col-xs-12) missing. Please try below snippet.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

Showing 1 to 6 of 6 entries

                    <button class="btn btn-link previous">Previous</button>
                    <button class="btn btn-info number">1</button>
                    <button class="btn btn-link next">Next</button>

   ```

Body:
have found mobile grid class (col-xs-12) missing. Please try below snippet.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<div class="block">
        <div class="row">
            <div class="col-xs-12 col-sm-6">
                <p><strong>Showing 1 to 6 of 6 entries</strong></p>
            </div>

            <div class="col-xs-12 col-sm-6">
                <div class="pagination">
                    <button class="btn btn-link previous">Previous</button>
                    <button class="btn btn-info number">1</button>
                    <button class="btn btn-link next">Next</button>
                </div>
            </div>
        </div>
    </div>