问:
Why do I get an error which says, "unsupported method in my route" in Laravel?
I was trying to get the value of the form data by pressing the submit button from blade, to route having a route name patient/update. I'm trying to test the $request object on controller using die dump function dd(). However there was an error message

"The GET method is not supported for this route".

I tried switching from get to post. But still I cant figure out what's the error behind.

Here is my code on blade;

```<code><form class="" action="{{ route('patient/update') }}" metdod="post">
    @csrf
    <nav class="nav">
        <a href="{{ route('home') }}">
            <button class="btn btn-secondary mr-2 mb-2" type="button" name="button">Home</button>
        </a>
        <input type="submit" class="btn btn-primary mb-2" name="save" value="Save">
    </nav>
    <table class="table">
        <tr>
            <td>
                <label class="text-primary">Fullname</label>
                <input class="form-control" type="text" name="fullname" value="{{ $patient->fullname }}" />
            </td>
            <td>
                <label class="text-primary">Date of birth</label>
                <input class="form-control" type="date" name="date_of_birth" value="{{ $patient->date_of_birth }}" />
            </td>
            <td>
                <label class="text-primary">Sex</label>
                <input class="form-control" type="text" name="sex" value="{{ $patient->sex }}" />
            </td>
            <td>
                <label class="text-primary">Birth weight</label>
                <input class="form-control" type="text" name="birth_weight" value="{{ $patient->birth_weight }}" />
            </td>
            <td>
                <label class="text-primary">Birth length</label>
                <input class="form-control" type="text" name="birth_length" value="{{ $patient->birth_length }}" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <label class="text-primary">Birth History</label>
                <textarea class="form-control" name="birth_history" rows="3" cols="30">{{ $patient->history }}</textarea>
            </td>
            <td colspan="2">
                <label class="text-primary">Feeding: </label>
                <textarea class="form-control" name="feeding" rows="3" cols="30">{{ $patient->feeding }}</textarea>
            </td>
            <td colspan="2">
                <label class="text-primary">screening_date: </label>
                <input class="form-control" type="date" name="screening_date" value="{{ $patient->screening_date }}" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <label class="text-primary">Home Address</label>
                <textarea class="form-control" name="home_address" rows="3" cols="30">{{ $patient->home_address }}</textarea>
            </td>
        </tr>
        <tr>
            <td>
                <label class="text-primary">Mother's name</label>
                <input class="form-control" type="text" name="mother_name" value="{{ $patient->mother_name }}" />
            </td>
            <td>
                <label class="text-primary">Age</label>
                <input class="form-control" type="text" name="mother_age" value="{{ $patient->mother_age }}" />
            </td>
            <td>
                <label class="text-primary">Occupation</label>
                <input class="form-control" type="text" name="mother_occupation" value="{{ $patient->mother_occupation }}" />
            </td>
            <td>
                <label class="text-primary">Contact No.</label>
                <input class="form-control" type="text" name="mother_cp" value="{{ $patient->mother_cp }}" />
            </td>
            <td>
                <label class="text-primary">TT Status</label>
                <input class="form-control" type="text" name="mother_tt_status" value="{{ $patient->mother_tt_status }}" />
            </td>
        </tr>
        <tr>
            <td>
                <label class="text-primary">Father's Name</label>
                <input class="form-control" type="text" name="father_name" value="{{ $patient->father_name }}" />
            </td>
            <td>
                <label class="text-primary">Age</label>
                <input class="form-control" type="text" name="father_age" value="{{ $patient->father_age }}" />
            </td>
            <td>
                <label class="text-primary">Occupation</label>
                <input class="form-control" type="text" name="father_occupation" value="{{ $patient->father_occupation }}" />
            </td>
            <td>
                <label class="text-primary">Contact No.</label>
                <input class="form-control" type="text" name="father_cp" value="{{ $patient->father_cp }}" />
            </td>
        </tr>
    </table>
    <input type="submit" class="btn btn-primary m-2 " name="save" value="Save">
</form>
</code>```

Here is my route;

```<code>Route::post('/patient/update', 'PatientController@update')->name('patient/update');
</code>```

And here is my controller;

```<code>public function update(Request $request)
{
    dd($request);
}
</code>```

Can anybody explain me why this error is happening?
Thanks in advance!

答:
The issue is in the very first line of your Blade file, where you misspelled "method":

<form class="" action="{{ route('patient/update') }}" metdod="post">
                                                      ^^^^^^
```

Without a valid method attribute in the form tag, the request will default to a GET.

Body:
I was trying to get the value of the form data by pressing the submit button from blade, to route having a route name patient/update. I'm trying to test the $request object on controller using die dump function dd(). However there was an error message

"The GET method is not supported for this route".

I tried switching from get to post. But still I cant figure out what's the error behind.

Here is my code on blade;

<form class="" action="{{ route('patient/update') }}" metdod="post">
    @csrf

            <button class="btn btn-secondary mr-2 mb-2" type="button" name="button">Home</button>

        <input type="submit" class="btn btn-primary mb-2" name="save" value="Save">

                Fullname
                <input class="form-control" type="text" name="fullname" value="{{ $patient->fullname }}" />

                Date of birth
                <input class="form-control" type="date" name="date_of_birth" value="{{ $patient->date_of_birth }}" />

                Sex
                <input class="form-control" type="text" name="sex" value="{{ $patient->sex }}" />

                Birth weight
                <input class="form-control" type="text" name="birth_weight" value="{{ $patient->birth_weight }}" />

                Birth length
                <input class="form-control" type="text" name="birth_length" value="{{ $patient->birth_length }}" />

                Birth History
                <textarea class="form-control" name="birth_history" rows="3" cols="30">{{ $patient->history }}</textarea>

                Feeding:
                <textarea class="form-control" name="feeding" rows="3" cols="30">{{ $patient->feeding }}</textarea>

                screening_date:
                <input class="form-control" type="date" name="screening_date" value="{{ $patient->screening_date }}" />

                Home Address
                <textarea class="form-control" name="home_address" rows="3" cols="30">{{ $patient->home_address }}</textarea>

                Mother's name
                <input class="form-control" type="text" name="mother_name" value="{{ $patient->mother_name }}" />

                Age
                <input class="form-control" type="text" name="mother_age" value="{{ $patient->mother_age }}" />

                Occupation
                <input class="form-control" type="text" name="mother_occupation" value="{{ $patient->mother_occupation }}" />

                Contact No.
                <input class="form-control" type="text" name="mother_cp" value="{{ $patient->mother_cp }}" />

                TT Status
                <input class="form-control" type="text" name="mother_tt_status" value="{{ $patient->mother_tt_status }}" />

                Father's Name
                <input class="form-control" type="text" name="father_name" value="{{ $patient->father_name }}" />

                Age
                <input class="form-control" type="text" name="father_age" value="{{ $patient->father_age }}" />

                Occupation
                <input class="form-control" type="text" name="father_occupation" value="{{ $patient->father_occupation }}" />

                Contact No.
                <input class="form-control" type="text" name="father_cp" value="{{ $patient->father_cp }}" />

    <input type="submit" class="btn btn-primary m-2 " name="save" value="Save">
</form>

Here is my route;

Route::post('/patient/update', 'PatientController@update')->name('patient/update');

And here is my controller;

public function update(Request $request)
{
    dd($request);
}

Can anybody explain me why this error is happening?
Thanks in advance!

Body:
The issue is in the very first line of your Blade file, where you misspelled "method":

<form class="" action="{{ route('patient/update') }}" metdod="post">
                                                      ^^^^^^

Without a valid method attribute in the form tag, the request will default to a GET.


来源: stackexchange

问:
Four identical Selenium test gives different result
I have a test class with four identical test (because of this error). I dont understand why three of them pass well and one throws me an error. Can somebody tell me where is the problem? Here is the code of the class:

```<code>package tests;

import Pages.SinCityPage;
import Pages.SpartaPage;
import model.Sin;
import model.SinTagsEnum;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PageFactoryExampleTest extends Base
{
    protected String siteUrl = "/sincity.php";
    protected String spartaSiteUrl = "/sparta.php";

    protected SinCityPage sinCityPage;

    protected SpartaPage spartaPage;

    @Before
    public void setUp() throws IOException {
        driver.get(baseUrl + siteUrl);
        this.sinCityPage = new SinCityPage(driver);
        this.spartaPage = new SpartaPage(driver);
    }

    @Test
    public void test1() throws InterruptedException {
        Sin sin = this.createSin();
        sinCityPage.openSinDetail(sin);
        sinCityPage.fillForm(sin);
        sinCityPage.openSinDetail(sin);
        sinCityPage.checkSinDetail(sin);

        driver.get(baseUrl + spartaSiteUrl);
        spartaPage.checkSins();
        spartaPage.checkForgive();
    }

    @Test
    public void test2() throws InterruptedException {
        Sin sin = this.createSin();
        sinCityPage.openSinDetail(sin);
        sinCityPage.fillForm(sin);
        sinCityPage.openSinDetail(sin);
        sinCityPage.checkSinDetail(sin);

        driver.get(baseUrl + spartaSiteUrl);
        spartaPage.checkSins();
        spartaPage.checkForgive();
    }

    @Test
    public void test3() throws InterruptedException {
        Sin sin = this.createSin();
        sinCityPage.openSinDetail(sin);
        sinCityPage.fillForm(sin);
        sinCityPage.openSinDetail(sin);
        sinCityPage.checkSinDetail(sin);

        driver.get(baseUrl + spartaSiteUrl);
        spartaPage.checkSins();
        spartaPage.checkForgive();
    }

    @Test
    public void test4() throws InterruptedException {
        Sin sin = this.createSin();
        sinCityPage.openSinDetail(sin);
        sinCityPage.fillForm(sin);
        sinCityPage.openSinDetail(sin);
        sinCityPage.checkSinDetail(sin);

        driver.get(baseUrl + spartaSiteUrl);
        spartaPage.checkSins();
        spartaPage.checkForgive();
    }

    private Sin createSin() {
        List<SinTagsEnum> tags = new ArrayList<SinTagsEnum>();
        tags.add(SinTagsEnum.BLACK_MAIL);
        tags.add(SinTagsEnum.HIJACK);

        return new Sin("Vrazda", "Ja", "Vrazda spojena s lupeznzm prepadnutim muchy v zapadnutej ulicke", tags);
    }
}
</code>```

Here is the Base class

```<code>package tests;

import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import services.WebDriverService;

import java.io.IOException;

public class Base
{
    protected WebDriver driver;

    protected String baseUrl = "http://seleniumweb2";

    @Before
    public void baseBefore() throws IOException {
        this.driver = (new WebDriverService()).getDriver();
        //this.driver = (new WebDriverService()).getDriver(WebDriverService.GECKO_EXE);
    }

    @After  // It can not be AfterClass because of closing browsers on remote server
    public void baseAfter()
    {
        try {
            //driver.close(); // Closes current active window with focus on. Other windows opened bz driver remain open.
            driver.quit();  // Closes all opened windows by this driver.
        } catch ( Exception e ) {
            System.out.println("Base::baseAfter() throws exception: " + e.getMessage());
        }
    }

}
</code>```

Here is driver class

```<code>package services;

import model.BrowsersEnum;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.MalformedURLException;
import java.net.URL;

public class WebDriverService
{

    public static String CHROME_EXE = "chromedriver.exe";
    public static String PHANTOM_EXE = "phantomjs.exe";
    public static String GECKO_EXE = "geckodriver.exe";
    public static String HUB_URL = "http://127.0.0.1:4444/wd/hub";

    private WebDriver driver = null;

    /**
     * This returns singleton driver
     * @return
     * @throws MalformedURLException
     */
    public WebDriver getDriver() throws MalformedURLException {
        String browser = System.getProperty("browser").toLowerCase();

        if (browser.equals(BrowsersEnum.CHROME.getValue())) {
            this.driver = new RemoteWebDriver(this.getRemoteUrl(), new ChromeOptions());
        } else if (browser.equals(BrowsersEnum.FIREFOX.getValue())) {
            this.driver = new RemoteWebDriver(this.getRemoteUrl(), new FirefoxOptions());
        } else {
            throw new IllegalArgumentException("Base::getDriver() invalid argument: " + browser);
        }

        return this.driver;
    }

    /**
     * Avoid using Selenium server GRID
     * @param which
     * @return
     */
    public WebDriver getDriver(String which) {
        if (which == PHANTOM_EXE) {
            System.setProperty("phantomjs.binary.path", PHANTOM_EXE);
            this.driver = new PhantomJSDriver();
        } else if (which == CHROME_EXE) {
            System.setProperty("webdriver.chrome.driver", CHROME_EXE);
            this.driver = new ChromeDriver();
        } else if (which == GECKO_EXE) {
            System.setProperty("webdriver.chrome.driver", GECKO_EXE);
            this.driver = new FirefoxDriver();
        }

        return this.driver;
    }

    /**
     * Remote selenium server (nodes) needs to have new instance for every test (not singleton).
     * Otherwise on the driver.quit() lose the session.
     * @return
     * @throws MalformedURLException
     */
    public URL getRemoteUrl() throws MalformedURLException {
        URL url = new URL( HUB_URL );
        return url;
    }
}
</code>```

And here is a screenshot of Jenkins error log

It drives me crazy. I dont really know what is going on.

答:
I fix the problem with maven surefire plugin settings for parallel test. This is the solution:

```<code><configuration>
    <forkCount>8</forkCount>
    <reuseForks>false</reuseForks>
</configuration>
</code>```

Before there was

```<code><configuration>
     <parallel>methods</parallel>
     <threadCount>10</threadCount>
</configuration>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a test class with four identical test (because of this error). I dont understand why three of them pass well and one throws me an error. Can somebody tell me where is the problem? Here is the code of the class:

package tests;

import Pages.SinCityPage;
import Pages.SpartaPage;
import model.Sin;
import model.SinTagsEnum;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PageFactoryExampleTest extends Base
{
    protected String siteUrl = "/sincity.php";
    protected String spartaSiteUrl = "/sparta.php";

    protected SinCityPage sinCityPage;

    protected SpartaPage spartaPage;

    @Before
    public void setUp() throws IOException {
        driver.get(baseUrl + siteUrl);
        this.sinCityPage = new SinCityPage(driver);
        this.spartaPage = new SpartaPage(driver);
    }

    @Test
    public void test1() throws InterruptedException {
        Sin sin = this.createSin();
        sinCityPage.openSinDetail(sin);
        sinCityPage.fillForm(sin);
        sinCityPage.openSinDetail(sin);
        sinCityPage.checkSinDetail(sin);

        driver.get(baseUrl + spartaSiteUrl);
        spartaPage.checkSins();
        spartaPage.checkForgive();
    }

    @Test
    public void test2() throws InterruptedException {
        Sin sin = this.createSin();
        sinCityPage.openSinDetail(sin);
        sinCityPage.fillForm(sin);
        sinCityPage.openSinDetail(sin);
        sinCityPage.checkSinDetail(sin);

        driver.get(baseUrl + spartaSiteUrl);
        spartaPage.checkSins();
        spartaPage.checkForgive();
    }

    @Test
    public void test3() throws InterruptedException {
        Sin sin = this.createSin();
        sinCityPage.openSinDetail(sin);
        sinCityPage.fillForm(sin);
        sinCityPage.openSinDetail(sin);
        sinCityPage.checkSinDetail(sin);

        driver.get(baseUrl + spartaSiteUrl);
        spartaPage.checkSins();
        spartaPage.checkForgive();
    }

    @Test
    public void test4() throws InterruptedException {
        Sin sin = this.createSin();
        sinCityPage.openSinDetail(sin);
        sinCityPage.fillForm(sin);
        sinCityPage.openSinDetail(sin);
        sinCityPage.checkSinDetail(sin);

        driver.get(baseUrl + spartaSiteUrl);
        spartaPage.checkSins();
        spartaPage.checkForgive();
    }

    private Sin createSin() {
        List<SinTagsEnum> tags = new ArrayList<SinTagsEnum>();
        tags.add(SinTagsEnum.BLACK_MAIL);
        tags.add(SinTagsEnum.HIJACK);

        return new Sin("Vrazda", "Ja", "Vrazda spojena s lupeznzm prepadnutim muchy v zapadnutej ulicke", tags);
    }
}

Here is the Base class

package tests;

import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import services.WebDriverService;

import java.io.IOException;

public class Base
{
    protected WebDriver driver;

    protected String baseUrl = "http://seleniumweb2";

    @Before
    public void baseBefore() throws IOException {
        this.driver = (new WebDriverService()).getDriver();
        //this.driver = (new WebDriverService()).getDriver(WebDriverService.GECKO_EXE);
    }

    @After  // It can not be AfterClass because of closing browsers on remote server
    public void baseAfter()
    {
        try {
            //driver.close(); // Closes current active window with focus on. Other windows opened bz driver remain open.
            driver.quit();  // Closes all opened windows by this driver.
        } catch ( Exception e ) {
            System.out.println("Base::baseAfter() throws exception: " + e.getMessage());
        }
    }

}

Here is driver class

package services;

import model.BrowsersEnum;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.MalformedURLException;
import java.net.URL;

public class WebDriverService
{

    public static String CHROME_EXE = "chromedriver.exe";
    public static String PHANTOM_EXE = "phantomjs.exe";
    public static String GECKO_EXE = "geckodriver.exe";
    public static String HUB_URL = "http://127.0.0.1:4444/wd/hub";

    private WebDriver driver = null;

    /**
     * This returns singleton driver
     * @return
     * @throws MalformedURLException
     */
    public WebDriver getDriver() throws MalformedURLException {
        String browser = System.getProperty("browser").toLowerCase();

        if (browser.equals(BrowsersEnum.CHROME.getValue())) {
            this.driver = new RemoteWebDriver(this.getRemoteUrl(), new ChromeOptions());
        } else if (browser.equals(BrowsersEnum.FIREFOX.getValue())) {
            this.driver = new RemoteWebDriver(this.getRemoteUrl(), new FirefoxOptions());
        } else {
            throw new IllegalArgumentException("Base::getDriver() invalid argument: " + browser);
        }

        return this.driver;
    }

    /**
     * Avoid using Selenium server GRID
     * @param which
     * @return
     */
    public WebDriver getDriver(String which) {
        if (which == PHANTOM_EXE) {
            System.setProperty("phantomjs.binary.path", PHANTOM_EXE);
            this.driver = new PhantomJSDriver();
        } else if (which == CHROME_EXE) {
            System.setProperty("webdriver.chrome.driver", CHROME_EXE);
            this.driver = new ChromeDriver();
        } else if (which == GECKO_EXE) {
            System.setProperty("webdriver.chrome.driver", GECKO_EXE);
            this.driver = new FirefoxDriver();
        }

        return this.driver;
    }

    /**
     * Remote selenium server (nodes) needs to have new instance for every test (not singleton).
     * Otherwise on the driver.quit() lose the session.
     * @return
     * @throws MalformedURLException
     */
    public URL getRemoteUrl() throws MalformedURLException {
        URL url = new URL( HUB_URL );
        return url;
    }
}

And here is a screenshot of Jenkins error log

It drives me crazy. I dont really know what is going on.

Body:
I fix the problem with maven surefire plugin settings for parallel test. This is the solution:

<configuration>
    <forkCount>8</forkCount>
    <reuseForks>false</reuseForks>
</configuration>

Before there was

<configuration>
     <parallel>methods</parallel>
     <threadCount>10</threadCount>
</configuration>


问:
How do I solve the staircase problem on Hacker rank
So, I'm trying to do the staircase problem in hacker rank, I'm trying to achieve it with C

The problem : https://www.hackerrank.com/challenges/staircase/problem

```<code>int i,j,k;
for(i=0;i<n;i++)
{
    for(j=i;j<n;j++)
    {
        printf(" ");
    }
    for(k=0;k<=i;k++)
    {
        printf("#");
    }
    printf("\n");
}
</code>```

}

But all the test cases are failing for the following code, any input would be really helpful :)

答:
```<code>void staircase(int n)
{
    for(int step = 1; step <= n; step++)
    {
        for(int spaces = n - step; spaces; spaces--)
        {
            putchar(' ');
        }
        for(int star = 0; star < step; star++)
        {
            putchar('#');
        }
        putchar('\n');
    }
}

</code>```

Body:
So, I'm trying to do the staircase problem in hacker rank, I'm trying to achieve it with C

The problem : https://www.hackerrank.com/challenges/staircase/problem

int i,j,k;
for(i=0;i<n;i++)
{
    for(j=i;j<n;j++)
    {
        printf(" ");
    }
    for(k=0;k<=i;k++)
    {
        printf("#");
    }
    printf("\n");
}

}

But all the test cases are failing for the following code, any input would be really helpful :)


问:
HERE Map Javascript Api gives InvalidArgumentError
I am using HERE Map Api to display Map. My application uses joomla CMS. I get "InvalidArgumentError" in my browser console.

Here is the error:

```<code>InvalidArgumentError: H.map.DomIcon (Argument #0 No element data) ............................ mapsjs-core.js:43:1074
zh https://js.api.here.com/v3/3.1/mapsjs-core.js:164
<anonymous> https://js.api.here.com/v3/3.1/mapsjs-core.js line 71 > eval:78
<anonymous> https://js.api.here.com/v3/3.1/mapsjs-core.js:71
<anonymous> https://js.api.here.com/v3/3.1/mapsjs-ui.js:7
</code>```

I just included below HERE map scripts and nothing else,

```<code><link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css?dp-version=1526040296" />
<script src="https://js.api.here.com/v3/3.1/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>
</code>```

This map is working fine when I use same code in separate HTML file. I doubt joomla js file may getting conflict with HERE Map js script.

Any help related to this is very much appreciated!

答: This Error is thrown only if you try to excecute H.map.DomIcon() without DOM element as a parameter. Are you sure you don't call H.map.DomIcon() somewhere else within your application?

Body:
I am using HERE Map Api to display Map. My application uses joomla CMS. I get "InvalidArgumentError" in my browser console.

Here is the error:

InvalidArgumentError: H.map.DomIcon (Argument #0 No element data) ............................ mapsjs-core.js:43:1074
zh https://js.api.here.com/v3/3.1/mapsjs-core.js:164
<anonymous> https://js.api.here.com/v3/3.1/mapsjs-core.js line 71 > eval:78
<anonymous> https://js.api.here.com/v3/3.1/mapsjs-core.js:71
<anonymous> https://js.api.here.com/v3/3.1/mapsjs-ui.js:7

I just included below HERE map scripts and nothing else,

<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css?dp-version=1526040296" />

This map is working fine when I use same code in separate HTML file. I doubt joomla js file may getting conflict with HERE Map js script.

Any help related to this is very much appreciated!


问:
Slider next / prev. button
I´d like to know, if it´s possible to add next and previous buttons to my homepage slider, which is made only with HTML and CSS code (without any Javascript).
If yes - how can i manage it?

https://codepen.io/michal-gambo/pen/zYGrMZo

My website is: autodielytatra.sk.
My code:

```<code><div class="content" id="slider">
<figure><a href="https://www.autodielytatra.sk/sk/kategoria/nahradne-diely"><img class="hp-img-print" src="https://www.autodielytatra.sk/files/upload/homepage/images/homepage-1.jpg" style="margin-bottom: 10px;" /></a> <a href="https://www.autodielytatra.sk/sk/search?q=plast+%C5%BElt%C3%BD+domie%C5%A1ava%C4%8D"> <img class="hp-img-print" src="https://www.autodielytatra.sk/files/upload/homepage/images/homepage-2.jpg" /></a> <a href="https://www.autodielytatra.sk/sk/kategoria/akciovy-tovar"> <img class="hp-img-print" src="https://www.autodielytatra.sk/files/upload/homepage/images/homepage-3.jpg" /></a> <a href="https://www.autodielytatra.sk/sk/kategoria/nahradne-diely"> <img class="hp-img-print" src="https://www.autodielytatra.sk/files/upload/homepage/images/homepage-1.jpg" /></a></figure>
</div>
</code>```

答:
A quick google for 'CSS only slider with prev and next buttons' brought up many things, including this:

https://codepen.io/AMKohn/pen/EKJHf

It is very, very difficult to be specific given the information you have provided.

The slider component:

```<code><ul class="slides">
    <input type="radio" name="radio-btn" id="img-1" checked />
    <li class="slide-container">
        <div class="slide">
            <img src="http://farm9.staticflickr.com/8072/8346734966_f9cd7d0941_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-6" class="prev">‹</label>
            <label for="img-2" class="next">›</label>
        </div>
    </li>

    <input type="radio" name="radio-btn" id="img-2" />
    <li class="slide-container">
        <div class="slide">
          <img src="http://farm9.staticflickr.com/8504/8365873811_d32571df3d_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-1" class="prev">‹</label>
            <label for="img-3" class="next">›</label>
        </div>
    </li>

    <input type="radio" name="radio-btn" id="img-3" />
    <li class="slide-container">
        <div class="slide">
          <img src="http://farm9.staticflickr.com/8068/8250438572_d1a5917072_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-2" class="prev">‹</label>
            <label for="img-4" class="next">›</label>
        </div>
    </li>

    <input type="radio" name="radio-btn" id="img-4" />
    <li class="slide-container">
        <div class="slide">
          <img src="http://farm9.staticflickr.com/8061/8237246833_54d8fa37f0_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-3" class="prev">‹</label>
            <label for="img-5" class="next">›</label>
        </div>
    </li>

    <input type="radio" name="radio-btn" id="img-5" />
    <li class="slide-container">
        <div class="slide">
          <img src="http://farm9.staticflickr.com/8055/8098750623_66292a35c0_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-4" class="prev">‹</label>
            <label for="img-6" class="next">›</label>
        </div>
    </li>

    <input type="radio" name="radio-btn" id="img-6" />
    <li class="slide-container">
        <div class="slide">
          <img src="http://farm9.staticflickr.com/8195/8098750703_797e102da2_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-5" class="prev">‹</label>
            <label for="img-1" class="next">›</label>
        </div>
    </li>

    <li class="nav-dots">
      <label for="img-1" class="nav-dot" id="img-dot-1"></label>
      <label for="img-2" class="nav-dot" id="img-dot-2"></label>
      <label for="img-3" class="nav-dot" id="img-dot-3"></label>
      <label for="img-4" class="nav-dot" id="img-dot-4"></label>
      <label for="img-5" class="nav-dot" id="img-dot-5"></label>
      <label for="img-6" class="nav-dot" id="img-dot-6"></label>
    </li>
</ul>
</code>```

And the CSS:

```<code>@import url(https://fonts.googleapis.com/css?family=Varela+Round);

html, body { background: #333 url("https://codepen.io/images/classy_fabric.png"); }

.slides {
    padding: 0;
    width: 609px;
    height: 420px;
    display: block;
    margin: 0 auto;
    position: relative;
}

.slides * {
    user-select: none;
    -ms-user-select: none;
    -moz-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -webkit-touch-callout: none;
}

.slides input { display: none; }

.slide-container { display: block; }

.slide {
    top: 0;
    opacity: 0;
    width: 609px;
    height: 420px;
    display: block;
    position: absolute;

    transform: scale(0);

    transition: all .7s ease-in-out;
}

.slide img {
    width: 100%;
    height: 100%;
}

.nav label {
    width: 200px;
    height: 100%;
    display: none;
    position: absolute;

      opacity: 0;
    z-index: 9;
    cursor: pointer;

    transition: opacity .2s;

    color: #FFF;
    font-size: 156pt;
    text-align: center;
    line-height: 380px;
    font-family: "Varela Round", sans-serif;
    background-color: rgba(255, 255, 255, .3);
    text-shadow: 0px 0px 15px rgb(119, 119, 119);
}

.slide:hover + .nav label { opacity: 0.5; }

.nav label:hover { opacity: 1; }

.nav .next { right: 0; }

input:checked + .slide-container  .slide {
    opacity: 1;

    transform: scale(1);

    transition: opacity 1s ease-in-out;
}

input:checked + .slide-container .nav label { display: block; }

.nav-dots {
    width: 100%;
    bottom: 9px;
    height: 11px;
    display: block;
    position: absolute;
    text-align: center;
}

.nav-dots .nav-dot {
    top: -5px;
    width: 11px;
    height: 11px;
    margin: 0 4px;
    position: relative;
    border-radius: 100%;
    display: inline-block;
    background-color: rgba(0, 0, 0, 0.6);
}

.nav-dots .nav-dot:hover {
    cursor: pointer;
    background-color: rgba(0, 0, 0, 0.8);
}

input#img-1:checked ~ .nav-dots label#img-dot-1,
input#img-2:checked ~ .nav-dots label#img-dot-2,
input#img-3:checked ~ .nav-dots label#img-dot-3,
input#img-4:checked ~ .nav-dots label#img-dot-4,
input#img-5:checked ~ .nav-dots label#img-dot-5,
input#img-6:checked ~ .nav-dots label#img-dot-6 {
    background: rgba(0, 0, 0, 0.8);
}
</code>```

Title: Slider next / prev. button

Body:
A quick google for 'CSS only slider with prev and next buttons' brought up many things, including this:

https://codepen.io/AMKohn/pen/EKJHf

It is very, very difficult to be specific given the information you have provided.

The slider component:

<ul class="slides">
    <input type="radio" name="radio-btn" id="img-1" checked />
    <li class="slide-container">
        <div class="slide">
            <img src="http://farm9.staticflickr.com/8072/8346734966_f9cd7d0941_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-6" class="prev">&#x2039;</label>
            <label for="img-2" class="next">&#x203a;</label>
        </div>
    </li>

    <input type="radio" name="radio-btn" id="img-2" />
    <li class="slide-container">
        <div class="slide">
          <img src="http://farm9.staticflickr.com/8504/8365873811_d32571df3d_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-1" class="prev">&#x2039;</label>
            <label for="img-3" class="next">&#x203a;</label>
        </div>
    </li>

    <input type="radio" name="radio-btn" id="img-3" />
    <li class="slide-container">
        <div class="slide">
          <img src="http://farm9.staticflickr.com/8068/8250438572_d1a5917072_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-2" class="prev">&#x2039;</label>
            <label for="img-4" class="next">&#x203a;</label>
        </div>
    </li>

    <input type="radio" name="radio-btn" id="img-4" />
    <li class="slide-container">
        <div class="slide">
          <img src="http://farm9.staticflickr.com/8061/8237246833_54d8fa37f0_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-3" class="prev">&#x2039;</label>
            <label for="img-5" class="next">&#x203a;</label>
        </div>
    </li>

    <input type="radio" name="radio-btn" id="img-5" />
    <li class="slide-container">
        <div class="slide">
          <img src="http://farm9.staticflickr.com/8055/8098750623_66292a35c0_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-4" class="prev">&#x2039;</label>
            <label for="img-6" class="next">&#x203a;</label>
        </div>
    </li>

    <input type="radio" name="radio-btn" id="img-6" />
    <li class="slide-container">
        <div class="slide">
          <img src="http://farm9.staticflickr.com/8195/8098750703_797e102da2_z.jpg" />
        </div>
        <div class="nav">
            <label for="img-5" class="prev">&#x2039;</label>
            <label for="img-1" class="next">&#x203a;</label>
        </div>
    </li>

    <li class="nav-dots">
      <label for="img-1" class="nav-dot" id="img-dot-1"></label>
      <label for="img-2" class="nav-dot" id="img-dot-2"></label>
      <label for="img-3" class="nav-dot" id="img-dot-3"></label>
      <label for="img-4" class="nav-dot" id="img-dot-4"></label>
      <label for="img-5" class="nav-dot" id="img-dot-5"></label>
      <label for="img-6" class="nav-dot" id="img-dot-6"></label>
    </li>
</ul>

And the CSS:

@import url(https://fonts.googleapis.com/css?family=Varela+Round);

html, body { background: #333 url("https://codepen.io/images/classy_fabric.png"); }

.slides {
    padding: 0;
    width: 609px;
    height: 420px;
    display: block;
    margin: 0 auto;
    position: relative;
}

.slides * {
    user-select: none;
    -ms-user-select: none;
    -moz-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -webkit-touch-callout: none;
}

.slides input { display: none; }

.slide-container { display: block; }

.slide {
    top: 0;
    opacity: 0;
    width: 609px;
    height: 420px;
    display: block;
    position: absolute;

    transform: scale(0);

    transition: all .7s ease-in-out;
}

.slide img {
    width: 100%;
    height: 100%;
}

.nav label {
    width: 200px;
    height: 100%;
    display: none;
    position: absolute;

      opacity: 0;
    z-index: 9;
    cursor: pointer;

    transition: opacity .2s;

    color: #FFF;
    font-size: 156pt;
    text-align: center;
    line-height: 380px;
    font-family: "Varela Round", sans-serif;
    background-color: rgba(255, 255, 255, .3);
    text-shadow: 0px 0px 15px rgb(119, 119, 119);
}

.slide:hover + .nav label { opacity: 0.5; }

.nav label:hover { opacity: 1; }

.nav .next { right: 0; }

input:checked + .slide-container  .slide {
    opacity: 1;

    transform: scale(1);

    transition: opacity 1s ease-in-out;
}

input:checked + .slide-container .nav label { display: block; }

.nav-dots {
    width: 100%;
    bottom: 9px;
    height: 11px;
    display: block;
    position: absolute;
    text-align: center;
}

.nav-dots .nav-dot {
    top: -5px;
    width: 11px;
    height: 11px;
    margin: 0 4px;
    position: relative;
    border-radius: 100%;
    display: inline-block;
    background-color: rgba(0, 0, 0, 0.6);
}

.nav-dots .nav-dot:hover {
    cursor: pointer;
    background-color: rgba(0, 0, 0, 0.8);
}

input#img-1:checked ~ .nav-dots label#img-dot-1,
input#img-2:checked ~ .nav-dots label#img-dot-2,
input#img-3:checked ~ .nav-dots label#img-dot-3,
input#img-4:checked ~ .nav-dots label#img-dot-4,
input#img-5:checked ~ .nav-dots label#img-dot-5,
input#img-6:checked ~ .nav-dots label#img-dot-6 {
    background: rgba(0, 0, 0, 0.8);
}


问:
initialize array that is within a object, use in localStorage
Isolated Question:

```<code>user[username] = {
  cool: true,
  stuff: false,
  arrData: []
};
</code>```

I am trying to globally initialize my arrData array in order to populate in different scope; the below does not work.

```<code>let user.arrData = [],
</code>```

later I want to do the following, for context:

```<code>...........
  inputs.forEach(function(input){
      user = JSON.parse(localStorage.getItem(username)); // tried moving this here
      user.arrData.push({ id: input.id, checked: input.checked });
      // the above errors on .arrData cannot push undefined, I have tried also including the key here, how is this done?
  });
  localStorage.setItem(user, JSON.stringify(user.arrData));
  console.log({ arrData: user.arrData }); // returns undefined
............
</code>```

Sub question: can I set and retrieve a object.array with localStorage like this. Meaning my reference to (user.arrData)?

Context/actual code:

Below is the complete relevant code for context: I am trying to save a series of checkbox states per user with local storage, then reload them when a button is clicked.

```<code>let user = {};
var savebtnBM = document.getElementById("savebtnBM");
const username = document.querySelector("span.name").textContent;

user[username] = {
   cool: true,
   stuff: false,
   arrData: []
};

var layersMod =  document.querySelectorAll(".layers #savebtnBM")[0];
layersMod.addEventListener('click', ()=>{
setTimeout(
  function() {
    Saver();
  }, 2000);
});

function Saver() {
  var inputs = document.querySelectorAll('input[type="checkbox"]');
  // var arrData = [];
  inputs.forEach(function(input){
    user[username].arrData.push({ id: input.id, checked: input.checked });
  });
  localStorage.setItem(user, JSON.stringify(user.arrData));
  console.log(JSON.stringify(user.arrData));
}

var etHOME= document.getElementById("et-phone-home");
etHOME.addEventListener('click', ()=>{
    user = JSON.parse(localStorage.getItem(username));
    console.log(user);
    document.getElementsByClassName("big-button")[0].click();
    setTimeout(load_, 2000);

    function load_() {
      var inputs = JSON.parse(localStorage.getItem(user));
      inputs.forEach(function(input){
        document.getElementById(input.id).checked = input.checked;
        load__();
      });
    function load__() {
        var elems = document.querySelectorAll('input:checked');
        for(var i = 0; i<elems.length; i++) {
          elems[i].click();
        }
      }
    }
});
</code>```

答:
Sub question response:

The localStorage and sessionStorage can only handle strings.

So first we must convert our object to string with JSON.stringify() as in the following example:

```<code>localStorage.setItem('user', JSON.stringify(user));
</code>```

When it comes to obtaining the previously saved we do the opposite, using JSON.parse():

```<code>//...
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log({ arrData: storedUser.arrData });
</code>```

Body:
Isolated Question:

user[username] = {
  cool: true,
  stuff: false,
  arrData: []
};

I am trying to globally initialize my arrData array in order to populate in different scope; the below does not work.

let user.arrData = [],

later I want to do the following, for context:

...........
  inputs.forEach(function(input){
      user = JSON.parse(localStorage.getItem(username)); // tried moving this here
      user.arrData.push({ id: input.id, checked: input.checked });
      // the above errors on .arrData cannot push undefined, I have tried also including the key here, how is this done?
  });
  localStorage.setItem(user, JSON.stringify(user.arrData));
  console.log({ arrData: user.arrData }); // returns undefined
............

Sub question: can I set and retrieve a object.array with localStorage like this. Meaning my reference to (user.arrData)?

Context/actual code:

Below is the complete relevant code for context: I am trying to save a series of checkbox states per user with local storage, then reload them when a button is clicked.

let user = {};
var savebtnBM = document.getElementById("savebtnBM");
const username = document.querySelector("span.name").textContent;

user[username] = {
   cool: true,
   stuff: false,
   arrData: []
};

var layersMod =  document.querySelectorAll(".layers #savebtnBM")[0];
layersMod.addEventListener('click', ()=>{
setTimeout(
  function() {
    Saver();
  }, 2000);
});

function Saver() {
  var inputs = document.querySelectorAll('input[type="checkbox"]');
  // var arrData = [];
  inputs.forEach(function(input){
    user[username].arrData.push({ id: input.id, checked: input.checked });
  });
  localStorage.setItem(user, JSON.stringify(user.arrData));
  console.log(JSON.stringify(user.arrData));
}

var etHOME= document.getElementById("et-phone-home");
etHOME.addEventListener('click', ()=>{
    user = JSON.parse(localStorage.getItem(username));
    console.log(user);
    document.getElementsByClassName("big-button")[0].click();
    setTimeout(load_, 2000);

    function load_() {
      var inputs = JSON.parse(localStorage.getItem(user));
      inputs.forEach(function(input){
        document.getElementById(input.id).checked = input.checked;
        load__();
      });
    function load__() {
        var elems = document.querySelectorAll('input:checked');
        for(var i = 0; i<elems.length; i++) {
          elems[i].click();
        }
      }
    }
});

Body:
Sub question response:

The localStorage and sessionStorage can only handle strings.

So first we must convert our object to string with JSON.stringify() as in the following example:

localStorage.setItem('user', JSON.stringify(user));

When it comes to obtaining the previously saved we do the opposite, using JSON.parse():

//...
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log({ arrData: storedUser.arrData });


问:
firing a jQuery change function at document ready
My change function allows users to switch from country to country and get different text and features. It works when changing country selections. But at initial page load, it does not fire jQuery change to set the hide and show text divs for the default / initial country.

Both divs display at initial page load. When I change away and then back to the default/initial country, change fires, hide and show fire, and shows the proper information and features.

I have tried document.ready with a change function both inside the switch selections and outside the change function. Neither work - they don't fire the hide, show and other jQuery in the switch cases at doc ready.  Its not clear to me whether 'ready' is a valid trigger event.

I have also tried:

```<code>$('input[name=country]').value('US').trigger('click');
</code>```

but it broke the change function. Here's the code.  The country selection below is just 2 countries to keep it simple, but actually, there are many.

```<code>$(document).ready(function()
{
//1st tier - select country via radio buttons:
//Initialize country
$('input[name=country]:first').attr('checked', true);   //Set first radio button (United States)
//$('input[name=country]:first').attr('checked', true).trigger('ready');  //sets 1st button, but does not fire change
//$('input[name=country]:first').trigger('click'); //sets 1st button, but does not fire change

$('input[name=country]').change(function ()
{
// change user instructions to be country specific
    switch ($('input[name=country]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps
        break;
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
});
});
</code>```

答: Before the final });, add in $('input').change();</p>

ContentLicense: CC BY-SA 3.0

Body:
My change function allows users to switch from country to country and get different text and features. It works when changing country selections. But at initial page load, it does not fire jQuery change to set the hide and show text divs for the default / initial country.

Both divs display at initial page load. When I change away and then back to the default/initial country, change fires, hide and show fire, and shows the proper information and features.

I have tried document.ready with a change function both inside the switch selections and outside the change function. Neither work - they don't fire the hide, show and other jQuery in the switch cases at doc ready.  Its not clear to me whether 'ready' is a valid trigger event.

I have also tried:

$('input[name=country]').value('US').trigger('click');

but it broke the change function. Here's the code.  The country selection below is just 2 countries to keep it simple, but actually, there are many.

$(document).ready(function()
{
//1st tier - select country via radio buttons:
//Initialize country
$('input[name=country]:first').attr('checked', true);   //Set first radio button (United States)
//$('input[name=country]:first').attr('checked', true).trigger('ready');  //sets 1st button, but does not fire change
//$('input[name=country]:first').trigger('click'); //sets 1st button, but does not fire change

$('input[name=country]').change(function ()
{
// change user instructions to be country specific
    switch ($('input[name=country]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps
        break;
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
});
});


问:
Setting a value to a cell in a pandas dataframe
I have the following pandas dataframe:

```<code>K = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]})
</code>```

Then I set the cell in the first row and first column to 11:

```<code>K.iloc[0]["A"] = 11
</code>```

And when I check the dataframe again, I see that the value assignment is done and K.iloc[0]["A"] is equal to 11. However when I add a column to this data frame and do the same operation for a cell in the new column, the value assignment is not successful:

```<code>K["C"] = 0
K.iloc[0]["C"] = 11
</code>```

So, when I check the dataframe again, the value of K.iloc[0]["C"] is still zero. I appreciate if somebody can tell me what is going on here and how I can resolve this issue.

答:
For simplicity, I would do the operations in a different order and use loc:

```<code>K.loc[0, 'C'] = 0
K.loc[0, ['A', 'C']] = 11
</code>```

Body:
I have the following pandas dataframe:

K = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]})

Then I set the cell in the first row and first column to 11:

K.iloc[0]["A"] = 11

And when I check the dataframe again, I see that the value assignment is done and K.iloc[0]["A"] is equal to 11. However when I add a column to this data frame and do the same operation for a cell in the new column, the value assignment is not successful:

K["C"] = 0
K.iloc[0]["C"] = 11

So, when I check the dataframe again, the value of K.iloc[0]["C"] is still zero. I appreciate if somebody can tell me what is going on here and how I can resolve this issue.

Body:
For simplicity, I would do the operations in a different order and use loc:

K.loc[0, 'C'] = 0
K.loc[0, ['A', 'C']] = 11


问:
AngularFire and Firestore - Querying collection once whilst navigating components
I'm trying reduce the reads performed against my firestore database. In a small demo, I have two components.

Component 1

Component 1 is a list of artists stored in the firestore collection company/artists

Component 2

Component 2 is a list of albums from any artist stored in the firestore collection company/albums

I connect an artist to an album by having the artist_id listed in each album document.

I have a service that’s referenced in a component. The service contains an angularfire collection query which i initiate within the service constructor. I put a console log inside the query function to log when the function is called. I essentially want the albums query to only happen once, even when I navigate back a to the artists component and return, I don’t want it to fire again. If I new item is added to the list, I'd like that to sync, which it does.

However, right now even though the console.log('get all items called'); is only fired once as i navigate through the components, the console.log('data = ', data) is fired every time I go to the albums component, which makes me think that I am indeed querying the database everytime.

Questions

How do i make sure that this query is only run once?

How do I achieve question 1, but also sync any new changes to the list from the database?

Or have I actually done it correctly?

Albums Component

```<code>import { Component, OnInit } from '@angular/core';
import { AlbumItemsService } from '../services/category-items.service';

@Component({
   selector: 'app-album-items',
   templateUrl: './album-items.component.html',
   styleUrls: ['./album-items.component.css']
 })

export class AlbumItemsComponent implements OnInit {
  constructor(public albumItemsService: AlbumItemsService) { }
  ngOnInit(): void {}
}
</code>```

Service

```<code>import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AlbumItemsService {

   private itemsCollection: AngularFirestoreCollection<any>;
   items: Observable<any[]>;

   constructor(private afs: AngularFirestore) {
     console.log('Album Item Service Called')
     this.getAllItems();
   }

   getAllItems(){
      console.log('get all items called');
      this.itemsCollection = this.afs.collection<any>('url');
      this.items = this.itemsCollection.snapshotChanges().pipe(
         map(actions => actions.map(a => {
         const data = a.payload.doc.data();
         const id = a.payload.doc.id;
         console.log('data = ', data)
         return { id, ...data };
      }))
  );
 }
}
</code>```

HTML

```<code><ul>
  <li *ngFor="let item of AlbumItemsService.items | async">
    {{ item.item_title }}
  </li>
</ul>
</code>```

UPDATE

I messed around with the native firestore code instead of angularfire.

```<code>this.db.collection("collection").onSnapshot((querySnapshot) => {
    var cities = [];
    querySnapshot.forEach((doc) => {
        cities.push(doc.data());
    });
    console.log("cities = ", cities);
});
</code>```

This seems like it doesn't query the database everytime. Can anyone confirm?

答: I am looking mainly in your "UPDATE". If you want to query collection you should use .get instead of .onSnapshot the reference can be found here.

Body:
I'm trying reduce the reads performed against my firestore database. In a small demo, I have two components.

Component 1

Component 1 is a list of artists stored in the firestore collection company/artists

Component 2

Component 2 is a list of albums from any artist stored in the firestore collection company/albums

I connect an artist to an album by having the artist_id listed in each album document.

I have a service that’s referenced in a component. The service contains an angularfire collection query which i initiate within the service constructor. I put a console log inside the query function to log when the function is called. I essentially want the albums query to only happen once, even when I navigate back a to the artists component and return, I don’t want it to fire again. If I new item is added to the list, I'd like that to sync, which it does.

However, right now even though the console.log('get all items called'); is only fired once as i navigate through the components, the console.log('data = ', data) is fired every time I go to the albums component, which makes me think that I am indeed querying the database everytime.

Questions

How do i make sure that this query is only run once?

How do I achieve question 1, but also sync any new changes to the list from the database?

Or have I actually done it correctly?

Albums Component

import { Component, OnInit } from '@angular/core';
import { AlbumItemsService } from '../services/category-items.service';

@Component({
   selector: 'app-album-items',
   templateUrl: './album-items.component.html',
   styleUrls: ['./album-items.component.css']
 })

export class AlbumItemsComponent implements OnInit {
  constructor(public albumItemsService: AlbumItemsService) { }
  ngOnInit(): void {}
}

Service

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AlbumItemsService {

   private itemsCollection: AngularFirestoreCollection<any>;
   items: Observable<any[]>;

   constructor(private afs: AngularFirestore) {
     console.log('Album Item Service Called')
     this.getAllItems();
   }

   getAllItems(){
      console.log('get all items called');
      this.itemsCollection = this.afs.collection<any>('url');
      this.items = this.itemsCollection.snapshotChanges().pipe(
         map(actions => actions.map(a => {
         const data = a.payload.doc.data();
         const id = a.payload.doc.id;
         console.log('data = ', data)
         return { id, ...data };
      }))
  );
 }
}

HTML

    {{ item.item_title }}

UPDATE

I messed around with the native firestore code instead of angularfire.

this.db.collection("collection").onSnapshot((querySnapshot) => {
    var cities = [];
    querySnapshot.forEach((doc) => {
        cities.push(doc.data());
    });
    console.log("cities = ", cities);
});

This seems like it doesn't query the database everytime. Can anyone confirm?


答: Looks like you misspelled the word method, you have metdod="post" which should be method="post".

Title: Why do I get an error which says, "unsupported method in my route" in Laravel?


问:
How to use date-picker in a react component using hooks
I have a component with a form that should display a date picker

```<code>const MyComponent = () => {
  const [formData, setFormData] = useState({
    dateFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
    dateTo: new Date()
  });

  const handleOnChange = e => {
    setFormData({...formData, [e.target.name]: e.target.value});
  };

  return (
    <DatePicker
      selected={formData.dateFrom}
      name="dateFrom"
      dateFormat="MMMM d, yyyy"
      onChange={e => handleOnChange(e)}
      />
  );
};
</code>```

What I need to do is to save the new date in the state, and get it back to update the component useing its selected property.

the handleOnChange method works for other form controls, not for the date picker, the error I am getting says :

Cannot read property 'name' of undefined

Any suggestion?

答:
the callback of onChange on the <DatePicker /> will have the value as first param, not the event, you can pass a similar Object to handleOnChange to keep it generic :

```<code><DatePicker
  selected={formData.dateFrom}
  name="dateFrom"
  dateFormat="MMMM d, yyyy"
  onChange={value => handleOnChange({target : { name: "dateForm", value}})}
/>
</code>```

Body:
I have a component with a form that should display a date picker

const MyComponent = () => {
  const [formData, setFormData] = useState({
    dateFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
    dateTo: new Date()
  });

  const handleOnChange = e => {
    setFormData({...formData, [e.target.name]: e.target.value});
  };

  return (
    <DatePicker
      selected={formData.dateFrom}
      name="dateFrom"
      dateFormat="MMMM d, yyyy"
      onChange={e => handleOnChange(e)}
      />
  );
};

What I need to do is to save the new date in the state, and get it back to update the component useing its selected property.

the handleOnChange method works for other form controls, not for the date picker, the error I am getting says :

Cannot read property 'name' of undefined

Any suggestion?

Body:
the callback of onChange on the <DatePicker /> will have the value as first param, not the event, you can pass a similar Object to handleOnChange to keep it generic :

<DatePicker
  selected={formData.dateFrom}
  name="dateFrom"
  dateFormat="MMMM d, yyyy"
  onChange={value => handleOnChange({target : { name: "dateForm", value}})}
/>


问:
AWS DynamoDB DAX "NoRouteException"
i tried to connect to my DAX cluster from my node js app per the steps given in the example. I get the following error while connecting to the client.

```<code>{
      "time": 1581671435720,
      "code": "NoRouteException",
      "retryable": true,
      "requestId": null,
      "statusCode": -1,
      "_tubeInvalid": false,
      "waitForRecoveryBeforeRetrying": false
    }
</code>```

I have roles and access permissions as suggested here but still i get the same error.

Please suggest.

thanks.

答:
It appears that DAX cannot be connected from Local Dev Environment. It gets connected only from VPC.

here's the SO link.

Using AWS DynamoDB DAX from local development machine

Title: AWS DynamoDB DAX "NoRouteException"

Body:
i tried to connect to my DAX cluster from my node js app per the steps given in the example. I get the following error while connecting to the client.

{
      "time": 1581671435720,
      "code": "NoRouteException",
      "retryable": true,
      "requestId": null,
      "statusCode": -1,
      "_tubeInvalid": false,
      "waitForRecoveryBeforeRetrying": false
    }

I have roles and access permissions as suggested here but still i get the same error.

Please suggest.

thanks.


问:
Fetch all columns into one column oracle
How do i achieve to fetch all columns into one column.

I have below sample query

```<code>WITH da AS(
SELECT 'a' col1, 'b' col2, 'c' col3 FROM dual UNION ALL
SELECT '1' col1, '2' col1, '3' col1 FROM dual UNION ALL
SELECT 'x' col1, 'y' col1, 'z' col1 FROM dual
)
SELECT * FROM da;

//RESULTS

COL1|COL2|COL3|
----|----|----|
a   |b   |c   |
1   |2   |3   |
x   |y   |z   |
</code>```

But what i want is the result to be as below with | as the delimiter.

```<code>ONE_COL|
-------|
a|b|c  |
1|2|3  |
x|y|z  |
</code>```

My biggest problem is i don't know the column names, therefore i cant do as:

```<code>SELECT  col1||'|'||col2||'|'||col3 AS ONE_COL  FROM da;
</code>```

how can i do this.

答:
The following is just to demonstrate a way to achieve what you asked for. (Assuming I didn't misunderstand what you asked for.)

First some preparation.

Create the DA table (according to the sample data in your question).

create table DA (COL1 char(1), COL2 char(1), COL3 char(1));
```

<ol start="2">
<li>Add rows to the table (again, according to the sample data in your question).</li>
</ol>

<pre class="lang-sql prettyprint-override"><code>insert into DA values ('a','b','c');
insert into DA values ('1','2','3');
insert into DA values ('x','y','z');
</code>```

I understand that you want to insert the data from table DA into another table, so I created a second database table according to what I understood from your question.

create table RESULT (ONE_COL char(5));
```

<ol start="4">
<li>PL/SQL code that retrieves the names of the columns (assuming you know the table name) from the data dictionary, then creates a dynamic cursor to retrieve the values from that table (again in the format described in your question) and inserts the rows fetched by the dynamic cursor into a second database table (since this is your requirement as I understood it from your question).</li>
</ol>

<pre class="lang-sql prettyprint-override"><code>declare
  L_COL  varchar2(128);
  L_CUR  sys_refcursor;
  L_ONE  char(5);
  L_SQL  varchar2(2000);
--
  cursor C_COLS is
    select COLUMN_NAME
      from USER_TAB_COLUMNS
     where TABLE_NAME = 'DA';
begin
  L_SQL := 'select ';
  open C_COLS;
  fetch C_COLS into L_COL;
  L_SQL := L_SQL || L_COL;
  while C_COLS%found
  loop
    fetch C_COLS into L_COL;
    if C_COLS%found then
      L_SQL := L_SQL || '||';
      L_SQL := L_SQL || '''|''||';
      L_SQL := L_SQL || L_COL;
    end if;
  end loop;
  close C_COLS;
  L_SQL := L_SQL || ' from DA';
  open L_CUR for L_SQL;
  loop
    fetch L_CUR into L_ONE;
    exit when L_CUR%notfound;
    insert into RESULT values (L_ONE);
  end loop;
  close L_CUR;
end;
</code>```

Finally, after running the above PL/SQL code...

select * from RESULT;
```

<p>which returns</p>

```ONE_C
-----
abc
123
xyz
```

Body:
How do i achieve to fetch all columns into one column.

I have below sample query

WITH da AS(
SELECT 'a' col1, 'b' col2, 'c' col3 FROM dual UNION ALL
SELECT '1' col1, '2' col1, '3' col1 FROM dual UNION ALL
SELECT 'x' col1, 'y' col1, 'z' col1 FROM dual
)
SELECT * FROM da;

//RESULTS

COL1|COL2|COL3|
----|----|----|
a   |b   |c   |
1   |2   |3   |
x   |y   |z   |

But what i want is the result to be as below with | as the delimiter.

ONE_COL|
-------|
a|b|c  |
1|2|3  |
x|y|z  |

My biggest problem is i don't know the column names, therefore i cant do as:

SELECT  col1||'|'||col2||'|'||col3 AS ONE_COL  FROM da;

how can i do this.

Body:
The following is just to demonstrate a way to achieve what you asked for. (Assuming I didn't misunderstand what you asked for.)

First some preparation.

Create the DA table (according to the sample data in your question).

create table DA (COL1 char(1), COL2 char(1), COL3 char(1));

Add rows to the table (again, according to the sample data in your question).

insert into DA values ('a','b','c');
insert into DA values ('1','2','3');
insert into DA values ('x','y','z');

I understand that you want to insert the data from table DA into another table, so I created a second database table according to what I understood from your question.

create table RESULT (ONE_COL char(5));

PL/SQL code that retrieves the names of the columns (assuming you know the table name) from the data dictionary, then creates a dynamic cursor to retrieve the values from that table (again in the format described in your question) and inserts the rows fetched by the dynamic cursor into a second database table (since this is your requirement as I understood it from your question).

declare
  L_COL  varchar2(128);
  L_CUR  sys_refcursor;
  L_ONE  char(5);
  L_SQL  varchar2(2000);
--
  cursor C_COLS is
    select COLUMN_NAME
      from USER_TAB_COLUMNS
     where TABLE_NAME = 'DA';
begin
  L_SQL := 'select ';
  open C_COLS;
  fetch C_COLS into L_COL;
  L_SQL := L_SQL || L_COL;
  while C_COLS%found
  loop
    fetch C_COLS into L_COL;
    if C_COLS%found then
      L_SQL := L_SQL || '||';
      L_SQL := L_SQL || '''|''||';
      L_SQL := L_SQL || L_COL;
    end if;
  end loop;
  close C_COLS;
  L_SQL := L_SQL || ' from DA';
  open L_CUR for L_SQL;
  loop
    fetch L_CUR into L_ONE;
    exit when L_CUR%notfound;
    insert into RESULT values (L_ONE);
  end loop;
  close L_CUR;
end;

Finally, after running the above PL/SQL code...

select * from RESULT;

which returns

ONE_C
-----
abc
123
xyz


问:
Bar chart not starting at 0
I am looking to achieve the following with ChartJS but not sure if its actually possible? I need the graph to start at 0 but in effect my bars won't always start at the bottom of the chart (they may but in effect I need a BarStart and a BarEnd). Is it possible to offset them to achieve the below?

答:
This can be accomplished since Chart.js v2.9.0, which supports floating bars. Individual bars can since be specified with the syntax [min, max].

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: [1, 2, 3, 4, 5, 6, 7],
    datasets: [{
      type: 'bar',
      label: 'Green Bars',
      backgroundColor: 'green',
      data: [[3, 9.5],[2, 8.5],[4, 7],[1.5, 5.5],[3, 6.5],[3, 8.5],[4, 9]],
    }]
  },
  options: {
    responsive: true,
    legend: {
       display: false
    },
    scales: {
      yAxes: [{
        type: 'linear',
        ticks: {
          min: 0,
          max: 10,
          stepSize: 1
        }
      }],
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  max-width: 260px;
}</code>```

<canvas id="myChart" width="10" height="10"></canvas>```

Title: Bar chart not starting at 0

Body:
This can be accomplished since Chart.js v2.9.0, which supports floating bars. Individual bars can since be specified with the syntax [min, max].

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: [1, 2, 3, 4, 5, 6, 7],
    datasets: [{
      type: 'bar',
      label: 'Green Bars',
      backgroundColor: 'green',
      data: [[3, 9.5],[2, 8.5],[4, 7],[1.5, 5.5],[3, 6.5],[3, 8.5],[4, 9]],
    }]
  },
  options: {
    responsive: true,
    legend: {
       display: false
    },
    scales: {
      yAxes: [{
        type: 'linear',
        ticks: {
          min: 0,
          max: 10,
          stepSize: 1
        }
      }],
    }
  }
});

canvas {
  max-width: 260px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="10" height="10"></canvas>


问:
Paperclip shows missing files after a while in production only
On development, everything is working fine. i can upload an avatar, images and docs to posts and they stay there.

on production, in heroku. i can upload an avatar, image and docs. and they work and appear. however after a while, they do not show anymore and it says that the url does not exist.
however, when i check the database i can see that they are stored properly.

here is my heroku log on the error:

```<code>2020-02-03T10:31:37.916790+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] ActionController::RoutingError (No route matches [GET] "/system/users/avatars/000/000/004/medium/Screenshot_2020-02-01_at_16.06.41.png"):
2020-02-03T10:31:37.916792+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a]
2020-02-03T10:31:37.916795+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:36:in `call'
2020-02-03T10:31:37.916797+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
2020-02-03T10:31:37.916800+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] railties (6.0.2.1) lib/rails/rack/logger.rb:38:in `call_app'
2020-02-03T10:31:37.916802+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `block in call'
2020-02-03T10:31:37.916804+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `block in tagged'
2020-02-03T10:31:37.916806+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
2020-02-03T10:31:37.916808+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `tagged'
2020-02-03T10:31:37.916811+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `call'
2020-02-03T10:31:37.916813+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
2020-02-03T10:31:37.916815+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/request_id.rb:27:in `call'
2020-02-03T10:31:37.916817+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] rack (2.1.2) lib/rack/method_override.rb:24:in `call'
2020-02-03T10:31:37.916819+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] rack (2.1.2) lib/rack/runtime.rb:24:in `call'
2020-02-03T10:31:37.916821+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] activesupport (6.0.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
2020-02-03T10:31:37.916823+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
2020-02-03T10:31:37.916826+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/static.rb:126:in `call'
2020-02-03T10:31:37.916828+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] rack (2.1.2) lib/rack/sendfile.rb:113:in `call'
2020-02-03T10:31:37.916830+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/host_authorization.rb:77:in `call'
2020-02-03T10:31:37.916832+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] railties (6.0.2.1) lib/rails/engine.rb:526:in `call'
2020-02-03T10:31:37.916834+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] puma (4.3.1) lib/puma/configuration.rb:228:in `call'
2020-02-03T10:31:37.916837+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] puma (4.3.1) lib/puma/server.rb:681:in `handle_request'
2020-02-03T10:31:37.916839+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] puma (4.3.1) lib/puma/server.rb:472:in `process_client'
2020-02-03T10:31:37.916841+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] puma (4.3.1) lib/puma/server.rb:328:in `block in run'
2020-02-03T10:31:37.916844+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] puma (4.3.1) lib/puma/thread_pool.rb:134:in `block in spawn_thread'
2020-02-03T10:31:37.919025+00:00 heroku[router]: at=info method=GET path="/system/users/avatars/000/000/004/medium/Screenshot_2020-02-01_at_16.06.41.png?1580721331" host=fierce-spire-88971.herokuapp.com request_id=5972883e-916f-43d5-842f-fb4a3898d57a fwd="90.169.115.213" dyno=web.1 connect=1ms service=3ms status=404 bytes=1902 protocol=https
</code>```

答: The issue was simply coming from the fact that i was storing the images on heroku. i hadn't set up aws. Once done everything worked perfectly.</p>

Body:
On development, everything is working fine. i can upload an avatar, images and docs to posts and they stay there.

on production, in heroku. i can upload an avatar, image and docs. and they work and appear. however after a while, they do not show anymore and it says that the url does not exist.
however, when i check the database i can see that they are stored properly.

here is my heroku log on the error:

2020-02-03T10:31:37.916790+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] ActionController::RoutingError (No route matches [GET] "/system/users/avatars/000/000/004/medium/Screenshot_2020-02-01_at_16.06.41.png"):
2020-02-03T10:31:37.916792+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a]
2020-02-03T10:31:37.916795+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:36:in `call'
2020-02-03T10:31:37.916797+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
2020-02-03T10:31:37.916800+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] railties (6.0.2.1) lib/rails/rack/logger.rb:38:in `call_app'
2020-02-03T10:31:37.916802+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `block in call'
2020-02-03T10:31:37.916804+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `block in tagged'
2020-02-03T10:31:37.916806+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
2020-02-03T10:31:37.916808+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `tagged'
2020-02-03T10:31:37.916811+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `call'
2020-02-03T10:31:37.916813+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
2020-02-03T10:31:37.916815+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/request_id.rb:27:in `call'
2020-02-03T10:31:37.916817+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] rack (2.1.2) lib/rack/method_override.rb:24:in `call'
2020-02-03T10:31:37.916819+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] rack (2.1.2) lib/rack/runtime.rb:24:in `call'
2020-02-03T10:31:37.916821+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] activesupport (6.0.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
2020-02-03T10:31:37.916823+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
2020-02-03T10:31:37.916826+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/static.rb:126:in `call'
2020-02-03T10:31:37.916828+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] rack (2.1.2) lib/rack/sendfile.rb:113:in `call'
2020-02-03T10:31:37.916830+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] actionpack (6.0.2.1) lib/action_dispatch/middleware/host_authorization.rb:77:in `call'
2020-02-03T10:31:37.916832+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] railties (6.0.2.1) lib/rails/engine.rb:526:in `call'
2020-02-03T10:31:37.916834+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] puma (4.3.1) lib/puma/configuration.rb:228:in `call'
2020-02-03T10:31:37.916837+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] puma (4.3.1) lib/puma/server.rb:681:in `handle_request'
2020-02-03T10:31:37.916839+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] puma (4.3.1) lib/puma/server.rb:472:in `process_client'
2020-02-03T10:31:37.916841+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] puma (4.3.1) lib/puma/server.rb:328:in `block in run'
2020-02-03T10:31:37.916844+00:00 app[web.1]: [5972883e-916f-43d5-842f-fb4a3898d57a] puma (4.3.1) lib/puma/thread_pool.rb:134:in `block in spawn_thread'
2020-02-03T10:31:37.919025+00:00 heroku[router]: at=info method=GET path="/system/users/avatars/000/000/004/medium/Screenshot_2020-02-01_at_16.06.41.png?1580721331" host=fierce-spire-88971.herokuapp.com request_id=5972883e-916f-43d5-842f-fb4a3898d57a fwd="90.169.115.213" dyno=web.1 connect=1ms service=3ms status=404 bytes=1902 protocol=https


问:
Imitate SVProgressHUD behavior
I`ve implemented a UIView that display a CustomLottie in the center of the screen, it has show() and hide() methods.

How can I give it the ability of hide() it from another place than where show() was called??
This is the code:

```<code>class LottieProgressHUD: UIView {

    static let shared = LottieProgressHUD()
    let hudView: UIView
    var animationView: AnimationView

    //options
    var hudWidth:CGFloat    = 200
    var hudHeight:CGFloat   = 200
    var animationFileName   = "coinLoading"

    override init(frame: CGRect) {
        self.hudView = UIView()
        self.animationView = AnimationView()
        super.init(frame: frame)
        self.setup()
    }

    required init?(coder aDecoder: NSCoder) {
        self.hudView = UIView()
        self.animationView = AnimationView()
        super.init(coder: aDecoder)
        self.setup()
    }

    func setup() {
        self.addSubview(hudView)
        show()
    }

    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        if let superview = self.superview {
            self.animationView.removeFromSuperview()

            let screenRect = UIScreen.main.bounds
            let screenWidth = screenRect.size.width
            let screenHeight = screenRect.size.height

            let width: CGFloat  = self.hudWidth
            let height: CGFloat = self.hudHeight
            self.frame = CGRect(x: (screenWidth / 2) - (width / 2) ,y: (screenHeight / 2) - (height / 2), width: width, height: height)
            hudView.frame = self.bounds
            layer.masksToBounds = true

            self.animationView = AnimationView(name: self.animationFileName)
            self.animationView.frame = CGRect(x: 0, y: 0, width: self.hudView.frame.width, height: self.hudView.frame.size.height)
            self.animationView.contentMode = .scaleAspectFill

            self.hudView.addSubview(animationView)
            self.animationView.loopMode = .loop
            self.animationView.play()

            self.hide()
        }
    }

    func show() {
        self.isHidden = false
    }

    func hide() {
        self.isHidden = true
    }
}
</code>```

This is how I call it inside the VC:

```<code>let progressHUD = LottieProgressHUD.shared
self.view.addSubview(progressHUD)
progressHUD.show()
</code>```

I would like to call progressHUD.hide() inside the VM

答:
You already have a static property that you can reference the same instance from anywhere.  Should be able to call your show and hide methods from any class.</p>

```<code>LottieProgressHUD.shared.show()

LottieProgressHUD.shared.hide()
</code>```

Title: Imitate SVProgressHUD behavior

Body:
I`ve implemented a UIView that display a CustomLottie in the center of the screen, it has show() and hide() methods.

How can I give it the ability of hide() it from another place than where show() was called??
This is the code:

class LottieProgressHUD: UIView {

    static let shared = LottieProgressHUD()
    let hudView: UIView
    var animationView: AnimationView

    //options
    var hudWidth:CGFloat    = 200
    var hudHeight:CGFloat   = 200
    var animationFileName   = "coinLoading"

    override init(frame: CGRect) {
        self.hudView = UIView()
        self.animationView = AnimationView()
        super.init(frame: frame)
        self.setup()
    }

    required init?(coder aDecoder: NSCoder) {
        self.hudView = UIView()
        self.animationView = AnimationView()
        super.init(coder: aDecoder)
        self.setup()
    }

    func setup() {
        self.addSubview(hudView)
        show()
    }

    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        if let superview = self.superview {
            self.animationView.removeFromSuperview()

            let screenRect = UIScreen.main.bounds
            let screenWidth = screenRect.size.width
            let screenHeight = screenRect.size.height

            let width: CGFloat  = self.hudWidth
            let height: CGFloat = self.hudHeight
            self.frame = CGRect(x: (screenWidth / 2) - (width / 2) ,y: (screenHeight / 2) - (height / 2), width: width, height: height)
            hudView.frame = self.bounds
            layer.masksToBounds = true

            self.animationView = AnimationView(name: self.animationFileName)
            self.animationView.frame = CGRect(x: 0, y: 0, width: self.hudView.frame.width, height: self.hudView.frame.size.height)
            self.animationView.contentMode = .scaleAspectFill

            self.hudView.addSubview(animationView)
            self.animationView.loopMode = .loop
            self.animationView.play()

            self.hide()
        }
    }

    func show() {
        self.isHidden = false
    }

    func hide() {
        self.isHidden = true
    }
}

This is how I call it inside the VC:

let progressHUD = LottieProgressHUD.shared
self.view.addSubview(progressHUD)
progressHUD.show()

I would like to call progressHUD.hide() inside the VM

Body:
You already have a static property that you can reference the same instance from anywhere.  Should be able to call your show and hide methods from any class.

LottieProgressHUD.shared.show()

LottieProgressHUD.shared.hide()


问:
How to change the package name in AndroidFindBy annotation
Problem : I want to run an Appium script on the same application, but different builds.

All resource-Id in the application is appended with the package name

Eg: For build A , username text field is - alpha.beta.charlie.delta:id/user_name and

For build B username field  alpha.beta.charlie/user_name , delta is removed from the package name.

I use AndroidFindBy from the page factory to locate the elements

```<code>    private static final PACKAGE = "alpha.beta.charlie.delta"

    @AndroidFindBy(id = PACKAGE + "/user_name")
    private MobileElement username;
</code>```

Where PACKAGE is declared as constant .

Now if I want to run the script on build B, I have to change the package name every time before I trigger the execution. Which is not efficient.

I know we can't add variables to pagefactory annotations.

The only workaround I see is using https://developer.android.com/reference/android/support/test/uiautomator/UiSelector.html#resourceidmatches

Is there any other workaround where I can add the package name at compile time to bypass changing package name manually.

答:
You don't need package name as Appium can find element without package name in resource id so you can use value after ":id/". I went through this problem when I get package name change for QA build and Prod build. so try below code :

```<code>@AndroidFindBy(id = "user_name")
private MobileElement username;
</code>```

Now it is independent from package name and can be run on any build if id is user_name in all builds.

Body:
Problem : I want to run an Appium script on the same application, but different builds.

All resource-Id in the application is appended with the package name

Eg: For build A , username text field is - alpha.beta.charlie.delta:id/user_name and

For build B username field  alpha.beta.charlie/user_name , delta is removed from the package name.

I use AndroidFindBy from the page factory to locate the elements

    private static final PACKAGE = "alpha.beta.charlie.delta"

    @AndroidFindBy(id = PACKAGE + "/user_name")
    private MobileElement username;

Where PACKAGE is declared as constant .

Now if I want to run the script on build B, I have to change the package name every time before I trigger the execution. Which is not efficient.

I know we can't add variables to pagefactory annotations.

The only workaround I see is using https://developer.android.com/reference/android/support/test/uiautomator/UiSelector.html#resourceidmatches

Is there any other workaround where I can add the package name at compile time to bypass changing package name manually.

Body:
You don't need package name as Appium can find element without package name in resource id so you can use value after ":id/". I went through this problem when I get package name change for QA build and Prod build. so try below code :

@AndroidFindBy(id = "user_name")
private MobileElement username;

Now it is independent from package name and can be run on any build if id is user_name in all builds.


问:
Replacing multiple words in a string sentence C#
Hello guys, I don't need the answer but I would look to know and find out what I'm doing wrong. As a beginner I got a very "easy" assignment in my studies. I need to create a string and inside this string I need to replace some words by other words without using the for loop as so: ( also I want to print it but I got no clue where to put Console.WriteLine and google searching for 1 hour didn't work or asking a colleage.

/* Excersice: use with stringbuilder
             * cat becomes littlecat
             * dog becomes littledog
             * mouse becomes littlemouse
             * words the must be replace by a
             * do not use a loop*/

```<code>
using System;
using System.Collections.Generic;
using System.Text;

namespace Opgavens_leerpad_3_oefening
{
    class Program
    {
        static string Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();

            string dogCat = new string("Can the cat find the mouse without waking the dog.");

            static string replacethisstring(string dogCat);
            {
                hondKat = dogCat.Replace("cat", "littlecat");
                hondKat = dogCat.Replace("dog", "littldog");
                hondKat = dogCat.Replace("mouse", "littlemouse");
                hondKat = dogCat.Replace("the", "a");
                return dogCat;
            }
        }
    }
}

</code>```

Error CS5001: Program does not contain a static "Main" method suitable for an entry point ( I don't get this doesn't almost any program starts with this static Main args? )

Error CS8112: replacethisstring(string)' is a local function and must therefore always have a body. ( I just gave it a body right? I opened the { and close it } and put a replace with return. )

答:
Having several issues like typos, syntax error etc.
Additionally, the excercise having a condition that needs to use with stringbuilder.

So, try this.

```<code>    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Can the cat find the mouse without waking the dog?");
        sb = replacethisstring(sb);

        Console.WriteLine(sb.ToString());
        Console.ReadLine();
    }

    static StringBuilder replacethisstring(StringBuilder dogCat)
    {
        StringBuilder hondKat = dogCat.Replace("cat", "littlecat");
        hondKat = dogCat.Replace("the", "a");
        hondKat = dogCat.Replace("dog", "littledog");
        hondKat = dogCat.Replace("mouse", "littlemouse");
        return hondKat;
    }
</code>```

Body:
Hello guys, I don't need the answer but I would look to know and find out what I'm doing wrong. As a beginner I got a very "easy" assignment in my studies. I need to create a string and inside this string I need to replace some words by other words without using the for loop as so: ( also I want to print it but I got no clue where to put Console.WriteLine and google searching for 1 hour didn't work or asking a colleage.

/* Excersice: use with stringbuilder
             * cat becomes littlecat
             * dog becomes littledog
             * mouse becomes littlemouse
             * words the must be replace by a
             * do not use a loop*/

using System;
using System.Collections.Generic;
using System.Text;

namespace Opgavens_leerpad_3_oefening
{
    class Program
    {
        static string Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();

            string dogCat = new string("Can the cat find the mouse without waking the dog.");

            static string replacethisstring(string dogCat);
            {
                hondKat = dogCat.Replace("cat", "littlecat");
                hondKat = dogCat.Replace("dog", "littldog");
                hondKat = dogCat.Replace("mouse", "littlemouse");
                hondKat = dogCat.Replace("the", "a");
                return dogCat;
            }
        }
    }
}

Error CS5001: Program does not contain a static "Main" method suitable for an entry point ( I don't get this doesn't almost any program starts with this static Main args? )

Error CS8112: replacethisstring(string)' is a local function and must therefore always have a body. ( I just gave it a body right? I opened the { and close it } and put a replace with return. )

Body:
Having several issues like typos, syntax error etc.
Additionally, the excercise having a condition that needs to use with stringbuilder.

So, try this.

    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("Can the cat find the mouse without waking the dog?");
        sb = replacethisstring(sb);

        Console.WriteLine(sb.ToString());
        Console.ReadLine();
    }

    static StringBuilder replacethisstring(StringBuilder dogCat)
    {
        StringBuilder hondKat = dogCat.Replace("cat", "littlecat");
        hondKat = dogCat.Replace("the", "a");
        hondKat = dogCat.Replace("dog", "littledog");
        hondKat = dogCat.Replace("mouse", "littlemouse");
        return hondKat;
    }