问:
How to handle the error 'Page reload detected during async script' using Selenium
How to handle the error  Page reload detected during async script using Selenium and InternetExplorerDriver?

Error stack trace:

```<code>org.openqa.selenium.JavascriptException: Page reload detected during async script
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_221'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities {acceptInsecureCerts: false, browserName: internet explorer, browserVersion: 11, javascriptEnabled: true, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), se:ieOptions: {browserAttachTimeout: 0, elementScrollBehavior: 0, enablePersistentHover: true, ie.browserCommandLineSwitches: , ie.edgechromium: false, ie.edgepath: , ie.ensureCleanSession: false, ie.fileUploadDialogTimeout: 3000, ie.forceCreateProcessApi: false, ignoreProtectedModeSettings: false, ignoreZoomSetting: false, initialBrowserUrl: http://localhost:24135/, nativeEvents: true, requireWindowFocus: false}, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: f8538187-14df-4144-8bd0-605ce398395e
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.executeAsyncScript(RemoteWebDriver.java:506)
    at stepdefinition.Steps.I_selected_the_Client(Steps.java:60)
</code>```

答:
Could you please provide a minimal sample to reproduce the issue? With which code snippet you're running and in which line the error occurs? You could follow the below sample to automate IE using Selenium webdriver in Java:</p>

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebElement;

public class new_java_class {
public static void main(String[] args) {
  //add the IE web driver path here..
  System.setProperty("webdriver.ie.driver","your\\path\\to\\IEwebdriver\\IEDriverServer.exe");
       WebDriver browser = new InternetExplorerDriver();
       //replace the URL of the web page here..
       browser.get("http://testsite.login/");
       WebElement username = browser.findElement(By.name("uname"));
       username.sendKeys("test_user");
       WebElement password = browser.findElement(By.name("psw"));
       password.sendKeys("abcd@1234");
       WebElement btn = browser.findElement(By.name("signIn"));
       btn.click();
}
}
</code>```

Body:
How to handle the error  Page reload detected during async script using Selenium and InternetExplorerDriver?

Error stack trace:

org.openqa.selenium.JavascriptException: Page reload detected during async script
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_221'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities {acceptInsecureCerts: false, browserName: internet explorer, browserVersion: 11, javascriptEnabled: true, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), se:ieOptions: {browserAttachTimeout: 0, elementScrollBehavior: 0, enablePersistentHover: true, ie.browserCommandLineSwitches: , ie.edgechromium: false, ie.edgepath: , ie.ensureCleanSession: false, ie.fileUploadDialogTimeout: 3000, ie.forceCreateProcessApi: false, ignoreProtectedModeSettings: false, ignoreZoomSetting: false, initialBrowserUrl: http://localhost:24135/, nativeEvents: true, requireWindowFocus: false}, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: f8538187-14df-4144-8bd0-605ce398395e
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.executeAsyncScript(RemoteWebDriver.java:506)
    at stepdefinition.Steps.I_selected_the_Client(Steps.java:60)

Body:
Could you please provide a minimal sample to reproduce the issue? With which code snippet you're running and in which line the error occurs? You could follow the below sample to automate IE using Selenium webdriver in Java:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebElement;

public class new_java_class {
public static void main(String[] args) {
  //add the IE web driver path here..
  System.setProperty("webdriver.ie.driver","your\\path\\to\\IEwebdriver\\IEDriverServer.exe");
       WebDriver browser = new InternetExplorerDriver();
       //replace the URL of the web page here..
       browser.get("http://testsite.login/");
       WebElement username = browser.findElement(By.name("uname"));
       username.sendKeys("test_user");
       WebElement password = browser.findElement(By.name("psw"));
       password.sendKeys("abcd@1234");
       WebElement btn = browser.findElement(By.name("signIn"));
       btn.click();
}
}


来源: stackexchange

问:
External controllers for iPhone
Are there any external buttons/controls that can be plugged into the iPhone that can be used within an app. If so, does anyone have any links to any code to use with these controls.

I was thinking of some kind of iPod controller that I could hack that could be plugged into the slot on the bottom of the phone.

Cheers.

答:
There are many solutions to this, most involve jailbreaking the iphone.

The most famous/popular is the iControlPad.

ContentLicense: CC BY-SA 3.0

Title: External controllers for iPhone


问:
How do I create a base test class in Xunit to test interface implementations?
I am writing a test suite for a class library using C# and XUnit. In the library are a number of classes that implement an interface. I could simply copy-paste the same tests for the interface implementation into each test class but I was wondering if there is a neater solution using some test base class which can be inherited from and run automatically without calling each method in turn in each test class.

This article on codeproject demonstrates how it would be done in mstest using an abstract base class marked with TestClass. A summary is given below. However I cannot figure out if there is an equivalent using xunit. Does anyone know how to approach this? The xunit docs say there is no equivalent to TestClass in mstest.

Interface

```<code>public interface IDoSomething
{
  int SearchString(string stringToSearch, string pattern);
}
</code>```

One of many classes implementing interface

```<code>public class ThisDoesSomething : IDoSomething
{
  public int SearchString(string stringToSearch, string pattern);
  {
    // implementation
  }
}
</code>```

Interface Test base class

```<code>[TestClass]
public abstract class IDoSomethingTestBase
{
  public abstract IDoSomething GetDoSomethingInstance();

  [TestMethod]
  public void BasicTest()
  {
    IDoSomething ids = GetDoSomethingInstance();
    Assert.AreEqual("a_string", ids.SearchString("a_string", ".*");
  }
}
</code>```

Test class that tests the class implementing interface

```<code>[TestClass]
public class ThisDoesSomething_Tests : IDoSomethingTestBase
{
  public override IDoSomething GetDoSomethingInstance()
  {
    return new ThisDoesSomething();
  }
}
</code>```

答:
Works exactly the same way...

public abstract class IDoSomethingTestBase
{
  protected readonly IDoSomething InstanceUnderTest;

  protected IDoSomethingTestBase(IDoSomething instanceUnderTest){
    InstanceUnderTest = instanceUnderTest;
  }

  [Fact]
  public void BasicTest()
  {
    Assert.AreEqual("a_string", InstanceUnderTest.SearchString("a_string", ".*");
  }
}
```

<p>Actual test class:</p>

<pre class="lang-cs prettyprint-override"><code>public class ThisDoesSomething_Tests : IDoSomethingTestBase
{
  public ThisDoesSomething_Tests(): base(new ThisDoesSomething()) { }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing a test suite for a class library using C# and XUnit. In the library are a number of classes that implement an interface. I could simply copy-paste the same tests for the interface implementation into each test class but I was wondering if there is a neater solution using some test base class which can be inherited from and run automatically without calling each method in turn in each test class.

This article on codeproject demonstrates how it would be done in mstest using an abstract base class marked with TestClass. A summary is given below. However I cannot figure out if there is an equivalent using xunit. Does anyone know how to approach this? The xunit docs say there is no equivalent to TestClass in mstest.

Interface

public interface IDoSomething
{
  int SearchString(string stringToSearch, string pattern);
}

One of many classes implementing interface

public class ThisDoesSomething : IDoSomething
{
  public int SearchString(string stringToSearch, string pattern);
  {
    // implementation
  }
}

Interface Test base class

[TestClass]
public abstract class IDoSomethingTestBase
{
  public abstract IDoSomething GetDoSomethingInstance();

  [TestMethod]
  public void BasicTest()
  {
    IDoSomething ids = GetDoSomethingInstance();
    Assert.AreEqual("a_string", ids.SearchString("a_string", ".*");
  }
}

Test class that tests the class implementing interface

[TestClass]
public class ThisDoesSomething_Tests : IDoSomethingTestBase
{
  public override IDoSomething GetDoSomethingInstance()
  {
    return new ThisDoesSomething();
  }
}

Body:
Works exactly the same way...

public abstract class IDoSomethingTestBase
{
  protected readonly IDoSomething InstanceUnderTest;

  protected IDoSomethingTestBase(IDoSomething instanceUnderTest){
    InstanceUnderTest = instanceUnderTest;
  }

  [Fact]
  public void BasicTest()
  {
    Assert.AreEqual("a_string", InstanceUnderTest.SearchString("a_string", ".*");
  }
}

Actual test class:

public class ThisDoesSomething_Tests : IDoSomethingTestBase
{
  public ThisDoesSomething_Tests(): base(new ThisDoesSomething()) { }
}


问:
Is there a way to detect in javascript that the Backspace is long pressed in ios/android?
I'm working on a web application built in Vue.js. I can only detect if the Backspace is long pressed using keydown on desktop's keyboard (specifically Windows PC). In desktop, the event is fired many times as long as you keep holding the Backspace key. But in mobile, it seems that it only fired once even if you hold the Backspace key longer.

What I'm trying to achieve is that, when I'm on the last field and clear the text, if all text are cleared, then closest previous field will be focused until all text are cleared and the cursor will point on the first field.

I already managed to sort the desktop, the only problem I have is on the mobile(android/ios).

HTML:

```<code><input
    @keydown="onKeydown(key, $event)"
    @paste="onPasteEvent(key, $event)"
    @keyup="onKeyup(key, $event)"
    @click="onInputClick(key, $event)"
    type="text"
    :name="'input' + key"
    v-model="code[key]"
    :maxlength="(key === 0 ? 6 : 5)"
>
</code>```

Keydown handler:

```<code> onKeydown(key, event) {
        let input = document.querySelector('input[name="input'+ key +'"]');

        switch (event.key) {
            case 'Backspace':
                // If not in first field and no text before the cursor
                // position; focus the previous field.
                if (key > 0 && !this.getPrevWord(input)) {
                    this.moveCursorLeft(key);
                }
                break;

            case 'Delete':
                // If not in last field and no text after the cursor position;
                // focus the next field.
                if (key < (this.inputs - 1) && !this.getNextWord(input)) {
                    this.moveCursorRight(key);
                }
                break;
        }
 },
</code>```

答:
Try the following:</p>

```<code>onKeydown(key, event) {
        let input = document.querySelector('input[name="input'+ key +'"]');

        switch (event.keyCode) {
            case 8:

                // If not in first field and no text before the cursor position; focus the previous field
                if (key > 0 && !this.getPrevWord(input)) {
                    this.moveCursorLeft(key);
                }
                break;

            case 46:
                // If not in last field and no text after the cursor position; focus the next field
                if (key < (this.inputs - 1) && !this.getNextWord(input)) {
                    this.moveCursorRight(key);
                }
                break;
        }
 },
</code>```

Body:
I'm working on a web application built in Vue.js. I can only detect if the Backspace is long pressed using keydown on desktop's keyboard (specifically Windows PC). In desktop, the event is fired many times as long as you keep holding the Backspace key. But in mobile, it seems that it only fired once even if you hold the Backspace key longer.

What I'm trying to achieve is that, when I'm on the last field and clear the text, if all text are cleared, then closest previous field will be focused until all text are cleared and the cursor will point on the first field.

I already managed to sort the desktop, the only problem I have is on the mobile(android/ios).

HTML:

<input
    @keydown="onKeydown(key, $event)"
    @paste="onPasteEvent(key, $event)"
    @keyup="onKeyup(key, $event)"
    @click="onInputClick(key, $event)"
    type="text"
    :name="'input' + key"
    v-model="code[key]"
    :maxlength="(key === 0 ? 6 : 5)"
>

Keydown handler:

 onKeydown(key, event) {
        let input = document.querySelector('input[name="input'+ key +'"]');

        switch (event.key) {
            case 'Backspace':
                // If not in first field and no text before the cursor
                // position; focus the previous field.
                if (key > 0 && !this.getPrevWord(input)) {
                    this.moveCursorLeft(key);
                }
                break;

            case 'Delete':
                // If not in last field and no text after the cursor position;
                // focus the next field.
                if (key < (this.inputs - 1) && !this.getNextWord(input)) {
                    this.moveCursorRight(key);
                }
                break;
        }
 },

Body:
Try the following:

onKeydown(key, event) {
        let input = document.querySelector('input[name="input'+ key +'"]');

        switch (event.keyCode) {
            case 8:

                // If not in first field and no text before the cursor position; focus the previous field
                if (key > 0 && !this.getPrevWord(input)) {
                    this.moveCursorLeft(key);
                }
                break;

            case 46:
                // If not in last field and no text after the cursor position; focus the next field
                if (key < (this.inputs - 1) && !this.getNextWord(input)) {
                    this.moveCursorRight(key);
                }
                break;
        }
 },


问:
How to scroll the area like drop down and list box in Winapp driver with c#?
I am automating desktop application where i have list box in which many items are listed and i want to click on the item which is hidden and that item will shows after scrolling the list. Which code will work for this? I am working with WinAppdriver, appium , c# and MSTest.
I need such lines of code with which list will scroll till the element finds.

答:
Someone guide me this solution and it is working for me now. So, i am posting answer here.

The List Box has accessibility item "lbStates".
We want to click the item "NC" in it which has the text "NC".
In this case the "Displayed" property of most of the list items will be false.
We can click the down button in the ListBox to scroll down or We can press the keys buttons and test if the value which we want to click is displayed or not.
It is possible that the value we want to click is not present in the listbox, in such case our code will go in a deadlock and for that purpose I've introduced the integer maxClicks.

```<code> [TestMethod]
        public void ListBoxTest()
        {
            //lbStates
            var lbStates = sessionWinForm.FindElementByAccessibilityId("lbStates");
            var allListItems = lbStates.FindElementsByTagName("ListItem");
            var valueToClick = "NC";
            var maxClicks = 10;
            foreach(var ali in allListItems)
            {
                Debug.WriteLine($"{ali.Displayed} - {ali.Text}");
                if(ali.Text.Equals(valueToClick) && !ali.Displayed)
                {
                    var downButton = lbStates.FindElementByAccessibilityId("DownButton");
                    var listItemToClick = lbStates.FindElementByName(valueToClick);

                    while(!listItemToClick.Displayed && (maxClicks-- > 0))
                    {
                        downButton.Click();
                        listItemToClick = lbStates.FindElementByName(valueToClick);

                        if (listItemToClick.Displayed)
                        {
                            listItemToClick.Click();
                        }
                    }
                }
            }
        }
</code>```

Body:
Someone guide me this solution and it is working for me now. So, i am posting answer here.

The List Box has accessibility item "lbStates".
We want to click the item "NC" in it which has the text "NC".
In this case the "Displayed" property of most of the list items will be false.
We can click the down button in the ListBox to scroll down or We can press the keys buttons and test if the value which we want to click is displayed or not.
It is possible that the value we want to click is not present in the listbox, in such case our code will go in a deadlock and for that purpose I've introduced the integer maxClicks.

 [TestMethod]
        public void ListBoxTest()
        {
            //lbStates
            var lbStates = sessionWinForm.FindElementByAccessibilityId("lbStates");
            var allListItems = lbStates.FindElementsByTagName("ListItem");
            var valueToClick = "NC";
            var maxClicks = 10;
            foreach(var ali in allListItems)
            {
                Debug.WriteLine($"{ali.Displayed} - {ali.Text}");
                if(ali.Text.Equals(valueToClick) && !ali.Displayed)
                {
                    var downButton = lbStates.FindElementByAccessibilityId("DownButton");
                    var listItemToClick = lbStates.FindElementByName(valueToClick);

                    while(!listItemToClick.Displayed && (maxClicks-- > 0))
                    {
                        downButton.Click();
                        listItemToClick = lbStates.FindElementByName(valueToClick);

                        if (listItemToClick.Displayed)
                        {
                            listItemToClick.Click();
                        }
                    }
                }
            }
        }


问:
Python: Fastest way to take and save screenshots
I've been struggling to come up with a script that allows me to take screenshots of my desktop more than once per every second. I'm using Win10.

PIL:

```<code>from PIL import ImageGrab
import time

while True:
    im = ImageGrab.grab()
    fname = "dropfolder/%s.png" %int(time.time())
    im.save(fname,'PNG')
</code>```

Results 1.01 seconds per image.

PyScreeze (https://github.com/asweigart/pyscreeze):

```<code>import pyscreeze
import time

while True:
    fname = "dropfolder/%s.png" %int(time.time())
    x = pyscreeze.screenshot(fname)
</code>```

Results 1.00 seconds per image.

Win32:

```<code>import win32gui
import win32ui
import win32con
import time

w=1920 #res
h=1080 #res

while True:
    wDC = win32gui.GetWindowDC(0)
    dcObj=win32ui.CreateDCFromHandle(wDC)
    cDC=dcObj.CreateCompatibleDC()
    dataBitMap = win32ui.CreateBitmap()
    dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0,0),(w, h) , dcObj, (0,0), win32con.SRCCOPY)
    fname = "dropfolder/%s.png" %int(time.time())
    dataBitMap.SaveBitmapFile(cDC, fname)
    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(0, wDC)
    win32gui.DeleteObject(dataBitMap.GetHandle())
</code>```

Results 1.01 seconds per image.

Then I stumbled into thread (Fastest way to take a screenshot with python on windows) where it was suggested that gtk would yield phenomenal results.

However using gtk:

```<code>import gtk
import time

img_width = gtk.gdk.screen_width()
img_height = gtk.gdk.screen_height()

while True:
    screengrab = gtk.gdk.Pixbuf(
        gtk.gdk.COLORSPACE_RGB,
        False,
        8,
        img_width,
        img_height
    )

    fname = "dropfolder/%s.png" %int(time.time())
    screengrab.get_from_drawable(
        gtk.gdk.get_default_root_window(),
        gtk.gdk.colormap_get_system(),
        0, 0, 0, 0,
        img_width,
        img_height
        ).save(fname, 'png')
</code>```

Results 2.34 seconds per image.

It seems to me like I'm doing something wrong, because people have been getting great results with gtk.

Any advices how to speed up the process?

Thanks!

答:
This solution uses d3dshot.

```<code>def d3dgrab(rect=(0, 0, 0, 0), spath=r".\\pictures\\cache\\", sname="", title=""):
    """ take a screenshot by rect. """

    sname = sname if sname else time.strftime("%Y%m%d%H%M%S000.jpg", time.localtime())
    while os.path.isfile("%s%s" % (spath, sname)):
        sname = "%s%03d%s" % (sname[:-7], int(sname[-7:-4]) + 1, sname[-4:])

    xlen = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    ylen = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

    assert 0 <= rect[0] <= xlen and 0 <= rect[2] <= xlen, ValueError("Illegal value of X coordination in rect: %s" % rect)
    assert 0 <= rect[1] <= ylen and 0 <= rect[3] <= ylen, ValueError("Illegal value of Y coordinatoin in rect: %s" % rect)

    if title:
        hdl = win32gui.FindWindow(None, title)
        if hdl != win32gui.GetForegroundWindow():
            win32gui.SetForegroundWindow(hdl)
        rect = win32gui.GetWindowRect(hdl)
    elif not sum(rect):
        rect = (0, 0, xlen, ylen)

    d = d3dshot.create(capture_output="numpy")
    return d.screenshot_to_disk(directory=spath, file_name=sname, region=rect)
</code>```

I think it can be helped

```<code>sname = sname if sname else time.strftime("%Y%m%d%H%M%S000.jpg", time.localtime())
while os.path.isfile("%s%s" % (spath, sname)):
    sname = "%s%03d%s" % (sname[:-7], int(sname[-7:-4]) + 1, sname[-4:])
</code>```

And it's fastest way to take screenshot I found.

Body:
I've been struggling to come up with a script that allows me to take screenshots of my desktop more than once per every second. I'm using Win10.

PIL:

from PIL import ImageGrab
import time

while True:
    im = ImageGrab.grab()
    fname = "dropfolder/%s.png" %int(time.time())
    im.save(fname,'PNG')

Results 1.01 seconds per image.

PyScreeze (https://github.com/asweigart/pyscreeze):

import pyscreeze
import time

while True:
    fname = "dropfolder/%s.png" %int(time.time())
    x = pyscreeze.screenshot(fname)

Results 1.00 seconds per image.

Win32:

import win32gui
import win32ui
import win32con
import time

w=1920 #res
h=1080 #res

while True:
    wDC = win32gui.GetWindowDC(0)
    dcObj=win32ui.CreateDCFromHandle(wDC)
    cDC=dcObj.CreateCompatibleDC()
    dataBitMap = win32ui.CreateBitmap()
    dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
    cDC.SelectObject(dataBitMap)
    cDC.BitBlt((0,0),(w, h) , dcObj, (0,0), win32con.SRCCOPY)
    fname = "dropfolder/%s.png" %int(time.time())
    dataBitMap.SaveBitmapFile(cDC, fname)
    dcObj.DeleteDC()
    cDC.DeleteDC()
    win32gui.ReleaseDC(0, wDC)
    win32gui.DeleteObject(dataBitMap.GetHandle())

Results 1.01 seconds per image.

Then I stumbled into thread (Fastest way to take a screenshot with python on windows) where it was suggested that gtk would yield phenomenal results.

However using gtk:

import gtk
import time

img_width = gtk.gdk.screen_width()
img_height = gtk.gdk.screen_height()

while True:
    screengrab = gtk.gdk.Pixbuf(
        gtk.gdk.COLORSPACE_RGB,
        False,
        8,
        img_width,
        img_height
    )

    fname = "dropfolder/%s.png" %int(time.time())
    screengrab.get_from_drawable(
        gtk.gdk.get_default_root_window(),
        gtk.gdk.colormap_get_system(),
        0, 0, 0, 0,
        img_width,
        img_height
        ).save(fname, 'png')

Results 2.34 seconds per image.

It seems to me like I'm doing something wrong, because people have been getting great results with gtk.

Any advices how to speed up the process?

Thanks!

Body:
This solution uses d3dshot.

def d3dgrab(rect=(0, 0, 0, 0), spath=r".\\pictures\\cache\\", sname="", title=""):
    """ take a screenshot by rect. """

    sname = sname if sname else time.strftime("%Y%m%d%H%M%S000.jpg", time.localtime())
    while os.path.isfile("%s%s" % (spath, sname)):
        sname = "%s%03d%s" % (sname[:-7], int(sname[-7:-4]) + 1, sname[-4:])

    xlen = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    ylen = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

    assert 0 <= rect[0] <= xlen and 0 <= rect[2] <= xlen, ValueError("Illegal value of X coordination in rect: %s" % rect)
    assert 0 <= rect[1] <= ylen and 0 <= rect[3] <= ylen, ValueError("Illegal value of Y coordinatoin in rect: %s" % rect)

    if title:
        hdl = win32gui.FindWindow(None, title)
        if hdl != win32gui.GetForegroundWindow():
            win32gui.SetForegroundWindow(hdl)
        rect = win32gui.GetWindowRect(hdl)
    elif not sum(rect):
        rect = (0, 0, xlen, ylen)

    d = d3dshot.create(capture_output="numpy")
    return d.screenshot_to_disk(directory=spath, file_name=sname, region=rect)

I think it can be helped

sname = sname if sname else time.strftime("%Y%m%d%H%M%S000.jpg", time.localtime())
while os.path.isfile("%s%s" % (spath, sname)):
    sname = "%s%03d%s" % (sname[:-7], int(sname[-7:-4]) + 1, sname[-4:])

And it's fastest way to take screenshot I found.


问:
Get user's location for Flutter Web
I'm currently using the Flutter Geolocator Plugin to access user's location (latitude/longitude), but it seems like it does not work for the web yet. I tried to find something to retrieve the user's location in Flutter for web, but I couldn't find it.

Has anyone already tried/found something to do the job?

答:
To be able to retrieve the position for the web part I had to use
https://pub.dev/packages/js to expose the JavaScript API and combine it with https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API.

So here how it looks like :

First create a file (ex: locationJs.dart) to expose the JS function :

```<code> @JS('navigator.geolocation') // navigator.geolocation namespace
 library jslocation; // library name can be whatever you want

 import "package:js/js.dart";

@JS('getCurrentPosition') // Accessing method getCurrentPosition
from       Geolocation API
external void getCurrentPosition(Function success(GeolocationPosition pos));

@JS()
@anonymous
class GeolocationCoordinates {
  external double get latitude;
  external double get longitude;
  external double get altitude;
  external double get accuracy;
  external double get altitudeAccuracy;
  external double get heading;
  external double get speed;

external factory GeolocationCoordinates(
  {double latitude,
  double longitude,
  double altitude,
  double accuracy,
  double altitudeAccuracy,
  double heading,
  double speed});
  }

@JS()
@anonymous
class GeolocationPosition {
external GeolocationCoordinates get coords;

external factory GeolocationPosition({GeolocationCoordinates
coords});
}
</code>```

Call the newly created file

```<code> import 'package:Shared/locationJs.dart';

  success(pos) {
     try {
       print(pos.coords.latitude);
       print(pos.coords.longitude);
       } catch (ex) {
        print("Exception thrown : " + ex.toString());
         }
     }

  _getCurrentLocation() {
      if (kIsWeb) {
        getCurrentPosition(allowInterop((pos) => success(pos)));
                }
      }
</code>```

Title: Get user's location for Flutter Web

Body:
To be able to retrieve the position for the web part I had to use
https://pub.dev/packages/js to expose the JavaScript API and combine it with https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API.

So here how it looks like :

First create a file (ex: locationJs.dart) to expose the JS function :

 @JS('navigator.geolocation') // navigator.geolocation namespace
 library jslocation; // library name can be whatever you want

 import "package:js/js.dart";

@JS('getCurrentPosition') // Accessing method getCurrentPosition
from       Geolocation API
external void getCurrentPosition(Function success(GeolocationPosition pos));

@JS()
@anonymous
class GeolocationCoordinates {
  external double get latitude;
  external double get longitude;
  external double get altitude;
  external double get accuracy;
  external double get altitudeAccuracy;
  external double get heading;
  external double get speed;

external factory GeolocationCoordinates(
  {double latitude,
  double longitude,
  double altitude,
  double accuracy,
  double altitudeAccuracy,
  double heading,
  double speed});
  }

@JS()
@anonymous
class GeolocationPosition {
external GeolocationCoordinates get coords;

external factory GeolocationPosition({GeolocationCoordinates
coords});
}

Call the newly created file

 import 'package:Shared/locationJs.dart';

  success(pos) {
     try {
       print(pos.coords.latitude);
       print(pos.coords.longitude);
       } catch (ex) {
        print("Exception thrown : " + ex.toString());
         }
     }

  _getCurrentLocation() {
      if (kIsWeb) {
        getCurrentPosition(allowInterop((pos) => success(pos)));
                }
      }


问:
Composer and PSR-4
I readed much topics, but no noone resolved my problem.

In main directory i have composer.json, vendor dir and coredir which has Router.php file

Router.php

```<code>namespace Core;

class Router{}
</code>```

composer.sjon

```<code> "autoload": {
    "psr-0": {
      "Core\\": "core/"
    },
</code>```

Update of autoload generate 0 include classes and when I try to use Router, there is error Class 'Core\Router' not found

I try

"Core\\": "core"

"Core\\Router": "core/"

"Core\\Router": "core"

Nothing work

Title: Composer and PSR-4

Body:
I readed much topics, but no noone resolved my problem.

In main directory i have composer.json, vendor dir and coredir which has Router.php file

Router.php

namespace Core;

class Router{}

composer.sjon

 "autoload": {
    "psr-0": {
      "Core\\": "core/"
    },

Update of autoload generate 0 include classes and when I try to use Router, there is error Class 'Core\Router' not found

I try

"Core\\": "core"

"Core\\Router": "core/"

"Core\\Router": "core"

Nothing work

Body:
Use This :

"autoload": {
    "psr-4": {
        "Core\\": "core/",
    }
},


问:
How to import local json file data to my JavaScript variable?
I have data inside employees.json how can I get this data and assign it to the variable inside main.js?</p>

答:
If you use Babel, you can use this:

```<code>import * as data from './employees.json';
const employees = data;
</code>```

You can use another method using js file.

employees.js

```<code>export default
{
  // your json here...
}
</code>```

And then:

```<code>import data from '../employees.js'
</code>```

Body:
If you use Babel, you can use this:

import * as data from './employees.json';
const employees = data;

You can use another method using js file.

employees.js

export default
{
  // your json here...
}

And then:

import data from '../employees.js'


问:
V8 function execution interruption
Hi. I want to implement terminateThread function in JavaScript (same clearTimeout).

I implemented startThread function which starts new win32 thread, which calls function. Function can execute infinitely and I need opportunity to stop the function execution, but don't stop execution main thread (don't use isolate->TerminateExecution).

I tried to find source code of clearInterval and clearTimeout functions in WebApi, but it was unsuccessfull.

How can I interrupt V8 function execution from another thread?

Thanks in advance!

答:
Given that only one thread can be active in an isolate at a time, isolate->TerminateExecution() would appear to be the right way to interrupt the currently executing thread. You can discard the termination request afterwards, so that other threads can resume their execution.

Remember: it is your responsibility as an embedder of V8 to make sure that there is never more than one thread running in a given Isolate. You will get weird crashes otherwise. You can use v8::Locker to achieve this, or your own locking/mutex solution.

Title: V8 function execution interruption


问:
Issues with a mex mxGetDoubles() function when compiling
Whenever I try to compile my very simple testing mex function, I get an error

"undefined reference to `mxGetDoubles'

  collect2.exe: error: ld returned 1 exit status

I'm using Matlab R2019a, mingw-w64 6.3.0. The example c file they give (explore.c) compiles just fine and also uses mxGetDoubles().

I've tried using mxGetPr() and even though they say they don't recommend it and that it shouldn't work after matlab R2018a in the documentation, that works just fine.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mex.h"
#include "matrix.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
    mxDouble *vertices;

    vertices = mxGetDoubles(prhs[1]);//mxGetPr(prhs[1]);

}
```

答:
To clarify the answers (assuming you only use real, double variables):

Either use

```<code>vertices = mxGetDoubles(prhs[1]);
</code>```

with the command

```<code>mex -R2018a my_system_function.c
</code>```

(as you proposed)

Or you can also use

```<code>#if MX_HAS_INTERLEAVED_COMPLEX
    vertices = mxGetDoubles(prhs[1]);
#else
    vertices = mxGetPr(prhs[1]); // pointer to real part
#endif
</code>```

with the command

```<code>mex my_system_function.c
</code>```

(as mpre hinted - see code in "C:\Program Files\MATLAB\R2019b\extern\examples\mex\explore.c").

In my case, I used it do retrieve the function parameters in the update function:

```<code>static void mdlUpdate(SimStruct *S, int_T tid)
{
    const real_T   *u    = (const real_T*) ssGetInputPortSignal(S,0);
    real_T         *x    = ssGetRealDiscStates(S);
    const mxArray  *p_mx = (const mxArray *) ssGetSFcnParam(S, 0);

#if MX_HAS_INTERLEAVED_COMPLEX
    const mxDouble *p    = mxGetDoubles(p_mx);
#else
    const double   *p    = mxGetPr(p_mx); // pointer to real part
#endif

   //...

}
</code>```

Body:
To clarify the answers (assuming you only use real, double variables):

Either use

vertices = mxGetDoubles(prhs[1]);

with the command

mex -R2018a my_system_function.c

(as you proposed)

Or you can also use

#if MX_HAS_INTERLEAVED_COMPLEX
    vertices = mxGetDoubles(prhs[1]);
#else
    vertices = mxGetPr(prhs[1]); // pointer to real part
#endif

with the command

mex my_system_function.c

(as mpre hinted - see code in "C:\Program Files\MATLAB\R2019b\extern\examples\mex\explore.c").

In my case, I used it do retrieve the function parameters in the update function:

static void mdlUpdate(SimStruct *S, int_T tid)
{
    const real_T   *u    = (const real_T*) ssGetInputPortSignal(S,0);
    real_T         *x    = ssGetRealDiscStates(S);
    const mxArray  *p_mx = (const mxArray *) ssGetSFcnParam(S, 0);

#if MX_HAS_INTERLEAVED_COMPLEX
    const mxDouble *p    = mxGetDoubles(p_mx);
#else
    const double   *p    = mxGetPr(p_mx); // pointer to real part
#endif

   //...

}


问:
Javascript array search filter
I have the scenario, with provided example JSON data:

```<code>[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]
</code>```

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).

For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

```<code>filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});
</code>```

which is:

personList is list of array from JSON above;

filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

Choose 23-26 only will show Beck and Candace

Choose >27 only will show Joe

Choose both will show Beck, Candace and Joe

Thank you for any answer.

答:
For search person by its age, you can make an array of a selected age like this.

let ages = ['23','24','25'];

code like this

```<code>persons.filter(item=> {return ages.indexOf(item.age)!== -1 })
</code>```

this return person array which are matches in ages array

output:

```<code>[
  { name: 'Beck', age: '25', hobby: [ 'Drinking', 'Cycling' ] },
  { name: 'Candace', age: '24', hobby: [ 'Reading', 'Singing' ] }
]
</code>```

Title: Javascript array search filter

Body:
I have the scenario, with provided example JSON data:

[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).

For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});

which is:

personList is list of array from JSON above;

filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

Choose 23-26 only will show Beck and Candace

Choose >27 only will show Joe

Choose both will show Beck, Candace and Joe

Thank you for any answer.

Body:
For search person by its age, you can make an array of a selected age like this.

let ages = ['23','24','25'];

code like this

persons.filter(item=> {return ages.indexOf(item.age)!== -1 })

this return person array which are matches in ages array

output:

[
  { name: 'Beck', age: '25', hobby: [ 'Drinking', 'Cycling' ] },
  { name: 'Candace', age: '24', hobby: [ 'Reading', 'Singing' ] }
]


问:
Draw text with custom font using ImageMagick and PHP
I want to dynamically render text to an image with a custom font, preferably with the option to output directly or save to a file. And to automatically set the image size according to the font/size combination.

I can already do this with GD, but it doesn't handle fonts where characters overlay each other.

So now I'm looking to ImageMagick. I've found an example in the docs that seem to do what I want. Is this possible with php_magick? Especially the part where no image size is defined :) If it is not, can I make command-line magick output the raw image, so I can pass it directly to the client with PHP?

Thanks!

The real question probably is: How do I convert the IM command below to PHP code using php_magick?

```<code>convert -background lightblue -fill blue -font Arial -pointsize 72 label:Anthony
</code>```

答:
You should be able to use the annotateImage function of the Imagick class to duplicate that functionality.

Here's a straight up copy-paste from that documentation:

```<code><?php
/* Create some objects */
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(800, 75, $pixel);

/* Black text */
$draw->setFillColor('black');

/* Font properties */
$draw->setFont('Bookman-DemiItalic');
$draw->setFontSize( 30 );

/* Create text */
$image->annotateImage($draw, 10, 45, 0,
    'The quick brown fox jumps over the lazy dog');

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;
</code>```

Body:
I want to dynamically render text to an image with a custom font, preferably with the option to output directly or save to a file. And to automatically set the image size according to the font/size combination.

I can already do this with GD, but it doesn't handle fonts where characters overlay each other.

So now I'm looking to ImageMagick. I've found an example in the docs that seem to do what I want. Is this possible with php_magick? Especially the part where no image size is defined :) If it is not, can I make command-line magick output the raw image, so I can pass it directly to the client with PHP?

Thanks!

The real question probably is: How do I convert the IM command below to PHP code using php_magick?

convert -background lightblue -fill blue -font Arial -pointsize 72 label:Anthony

Body:
You should be able to use the annotateImage function of the Imagick class to duplicate that functionality.

Here's a straight up copy-paste from that documentation:

<?php
/* Create some objects */
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(800, 75, $pixel);

/* Black text */
$draw->setFillColor('black');

/* Font properties */
$draw->setFont('Bookman-DemiItalic');
$draw->setFontSize( 30 );

/* Create text */
$image->annotateImage($draw, 10, 45, 0,
    'The quick brown fox jumps over the lazy dog');

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;


问:
Why create an abstract super type in Julia?
I am looking at someone code and it uses <: when creating a struct. I looked in the docs and found out that this means they are creating an abstract supertype. Can anyone explain what this is and why one would want to use it?

答:
A much more practical use case is to create strongly typed, potentially mutually recursive structs.  E.g., you could not write the following:

```<code>struct Node
    edges::Vector{Edge}
end

struct Edge
    from::Node
    to::Node
end
</code>```

One way to write this is the rather artificial

```<code>abstract type AbstractNode end
abstract type AbstractEdge end

struct Node{E<:AbstractEdge}
    edges::Vector{E}
end

struct Edge{N<:AbstractNode}
    from::N
    to::N
end
</code>```

Often, with enough experience, this problem will be solved naturally already during the design of a data structure, as in the following:

```<code>abstract type Program end
abstract type Expression <: Program end
abstract type Statement <: Program

struct Literal <: Expression
    value::Int
end

struct Var <: Expression
    name::Symbol
end

struct Plus <: Expression
    x::Expression
    y::Expression
end

struct Assign <: Statement
    var::Var
    expr::Expression
end

struct Block <: Expression
    side_effects::Vector{<:Program}
    result::Expression
end
</code>```

This makes sure that Expressions (things that evaluate to numbers) and Statements (things that are only side-effects) are properly separated -- you never can create invalid programs like 1 + (x = 2).  And it could not be written without abstract types (or mutually recursive types, but they currently do not exist).

Body:
A much more practical use case is to create strongly typed, potentially mutually recursive structs.  E.g., you could not write the following:

struct Node
    edges::Vector{Edge}
end

struct Edge
    from::Node
    to::Node
end

One way to write this is the rather artificial

abstract type AbstractNode end
abstract type AbstractEdge end

struct Node{E<:AbstractEdge}
    edges::Vector{E}
end

struct Edge{N<:AbstractNode}
    from::N
    to::N
end

Often, with enough experience, this problem will be solved naturally already during the design of a data structure, as in the following:

abstract type Program end
abstract type Expression <: Program end
abstract type Statement <: Program

struct Literal <: Expression
    value::Int
end

struct Var <: Expression
    name::Symbol
end

struct Plus <: Expression
    x::Expression
    y::Expression
end

struct Assign <: Statement
    var::Var
    expr::Expression
end

struct Block <: Expression
    side_effects::Vector{<:Program}
    result::Expression
end

This makes sure that Expressions (things that evaluate to numbers) and Statements (things that are only side-effects) are properly separated -- you never can create invalid programs like 1 + (x = 2).  And it could not be written without abstract types (or mutually recursive types, but they currently do not exist).


问:
Must each Knex command in a transaction be submitted only after the previous command's promise has been fulfilled if their order is important?
I'm using the second form of knex transactions (e.g., with 'transacting'). However, this question is probably valid for the first form as well.

The documentation sample shows this:

```<code>// Using trx as a transaction object:
knex.transaction(function(trx) {

  const books = [
    {title: 'Canterbury Tales'},
    {title: 'Moby Dick'},
    {title: 'Hamlet'}
  ];

  knex.insert({name: 'Old Books'}, 'id')
    .into('catalogues')
    .transacting(trx)
    .then(function(ids) {
      books.forEach((book) => book.catalogue_id = ids[0]);
      return knex('books').insert(books).transacting(trx);
    })
    .then(trx.commit)
    .catch(trx.rollback);
})
</code>```

Two "insert" commands are being executed in the transaction. The second one is submitted only after the first one's promise has been fulfilled (i.e., in the promise's 'then' callback).

In the above example this is necessary, since the second command can only be formulated after the result of the first command has come back.

However, there are cases where multiple commands can be formulated in advance. As such, one might execute code like this:

```<code>promise1 = knex('table1').insert(...).transacting(trx).then(...)
promise2 = knex('table2').insert(...).transacting(trx).then(...)

Use Promise.all to wait for completion and eventually commit or rollback.
</code>```

In fact, this code will execute. Knex will queue the commands and send them out over the connection assigned to the transaction one at a time.

However, and this is the gist of my question, empirical evidence while using knex with PostgreSQL seems to show that the order in which the commands are sent to the database is not maintained. In other words, the order in which the commands were submitted to knex is not necessarily the order in which they are sent to the database. It seems that the only way to guarantee that commands are sent in a specific order is to create a promise chain whereby each command is submitted only after the previous command has been fulfilled.

Can anyone comment on this? Is this by design? Might this be a bug?

答:
However, and this is the gist of my question, empirical evidence while using knex with PostgreSQL seems to show that the order in which the commands are sent to the database is not maintained. In other words, the order in which the commands were submitted to knex is not necessarily the order in which they are sent to the database. It seems that the only way to guarantee that commands are sent in a specific order is to create a promise chain whereby each command is submitted only after the previous command has been fulfilled.

Sounds like your code doesn't do what you think it does.

Knex sends queries to the database driver in that order, how you tell it to execute them (by awaiting query builder or by executing .then() method).

If you execute more than 1 query to the same transaction, before earlier has finished node-pg driver buffers the second query and sends it only after the first query has first returned its response.

Use Promise.all to wait for completion and eventually commit or rollback.

If there is no error thrown, this should work.

Promise.all([p1,p2fails,p3,p4,p5])

However if there is exception thrown for example from p2fails promise, then Promise.all will reject instantly and rollback will be executed. After that p3,p4 and p5 are still tried to be executed, since they were already buffered in node-pg to be sent.

Would be safer, more memory efficient (query is stored twice, once in knex builder and once as buffered raw query inside pg driver with large inserts this might be significant) and easier to just wait each query to return before sending the next one. Using Promise.all here doesn't even give any additional concurrency benefits, since queries are still executed sequentially through the same connection.

Body:
I'm using the second form of knex transactions (e.g., with 'transacting'). However, this question is probably valid for the first form as well.

The documentation sample shows this:

// Using trx as a transaction object:
knex.transaction(function(trx) {

  const books = [
    {title: 'Canterbury Tales'},
    {title: 'Moby Dick'},
    {title: 'Hamlet'}
  ];

  knex.insert({name: 'Old Books'}, 'id')
    .into('catalogues')
    .transacting(trx)
    .then(function(ids) {
      books.forEach((book) => book.catalogue_id = ids[0]);
      return knex('books').insert(books).transacting(trx);
    })
    .then(trx.commit)
    .catch(trx.rollback);
})

Two "insert" commands are being executed in the transaction. The second one is submitted only after the first one's promise has been fulfilled (i.e., in the promise's 'then' callback).

In the above example this is necessary, since the second command can only be formulated after the result of the first command has come back.

However, there are cases where multiple commands can be formulated in advance. As such, one might execute code like this:

promise1 = knex('table1').insert(...).transacting(trx).then(...)
promise2 = knex('table2').insert(...).transacting(trx).then(...)

Use Promise.all to wait for completion and eventually commit or rollback.

In fact, this code will execute. Knex will queue the commands and send them out over the connection assigned to the transaction one at a time.

However, and this is the gist of my question, empirical evidence while using knex with PostgreSQL seems to show that the order in which the commands are sent to the database is not maintained. In other words, the order in which the commands were submitted to knex is not necessarily the order in which they are sent to the database. It seems that the only way to guarantee that commands are sent in a specific order is to create a promise chain whereby each command is submitted only after the previous command has been fulfilled.

Can anyone comment on this? Is this by design? Might this be a bug?


问:
Could not determine java version from '13.0.1'
I have gradle 6.0.1 and JDK 13.0.1 installed and tried gradlew setupDecompWorkspace, but it tells me "Could not determine java version from '13.0.1' ". I've tried to find an answer for a week now and I can't find a solution.

edit: the result of gradlew setupDecompWorkspace --stacktrace: https://pastebin.com/NFqZpBkG

edit 2: i manually changed the wrapper.properties file and updated my gradle wrapper. Now gradlew setupDecompWorkspace --stacktrace gives me this:
https://pastebin.com/ubYj4Zq0

答:
I was having the same issue. 1.7.10 forge does not support gradle 6. In the \gradle\wrapper\gradle-wrapper.properties revert the gradle version to what it was before it is something like 4.x. (This is for 1.8.9 not 1.7.10 if it is 3.x maybe try JDK 7 instead of 8 if the same error occurs)

Gradle 4 does not support JDK 13. I am not sure what versions work for gradle 4 as I cannot find the documentation for the supported versions. After some trial and error, I found JDK 8 works. Download and install here.

After the installer is complete, it won't just work. You will need to set "JAVA_HOME". Go to your environment variabes (Control Panel\System and Security\System\Advanced system settings\Advanced\Environment Variables...) If "JAVA_HOME" doesn't exist in the system variables, create it. Call it "JAVA_HOME" and set the value to "C:\Program Files\Java\jdk1.8.0_241" if you used the installer I linked. After you have done this, click ok, ok, ok and close the control panel.

You are almost done! Now all you have to do is restart your computer and it should work. If it doesn't comment on this answer and @ me. Hope it works.

Note: I recommend to use IntelliJ for modding and once you have decompiled, open the build.gradle with IntelliJ. Wait for it to load and then go back to your command prompt and type "gradlew genIntellijRuns" (as seen in github guide for modding)and now you are ready to start coding!


问:
CSS Label background Color setting - Only apply background color to Label Length
Need help with Label background setting. Below is my code which I am using . Please help me to get expected output as below mentioned image.

$header=@"

"@

ConvertTo-Html -body "

 Database Consolidated Health Check Report
" |`
 Out-File  C:\Temp\ConsolidatedReport.html ```

Current Output:

Expecting Output:

答:
Please add "display: inline-block;" property in h1. Try below code: </p>

```<code>ConvertTo-Html -body "<H1 style=color:snow;font-weight:normal;background-color:DarkslateGray;font-size:1.5em; display: inline-block; font-family:Arial;text-align:left;background-repeat:no-repeat;background-size:100%>
</code>```

<p>Database Consolidated Health Check Report " |`
 Out-File  C:\Temp\ConsolidatedReport.html </p>

Body:
Need help with Label background setting. Below is my code which I am using . Please help me to get expected output as below mentioned image.

$header=@"

"@

ConvertTo-Html -body "

 Database Consolidated Health Check Report
" |`
 Out-File  C:\Temp\ConsolidatedReport.html

Current Output:

Expecting Output:

Body:
Please add "display: inline-block;" property in h1. Try below code:

ConvertTo-Html -body "<H1 style=color:snow;font-weight:normal;background-color:DarkslateGray;font-size:1.5em; display: inline-block; font-family:Arial;text-align:left;background-repeat:no-repeat;background-size:100%>

Database Consolidated Health Check Report " |`
 Out-File  C:\Temp\ConsolidatedReport.html


问:
Why the service does not get an ClusterIP assigned?
I am trying to deploy MinIO on K8s cluster and have followed the guide on https://github.com/minio/minio-operator/blob/master/README.md.

After the installation the MinIO services does not get a ClusterIP:

What am I doing wrong?

答:
ClusterIp is "None" when you want to create a headless service. In your service template (yaml file) if clusterIp is set to "None" then cluster-ip is not assigned for your service.

If you need cluster-ip for your service then change your template and remove "clusterIP: None" field.


问:
A basic question regarding or operator in python
I get confused why the message always pops up like 'Welcome xxx' no matter what a user types.

```<code>username = input('Please enter your username: ')

if username == 'admin' or 'Admin' or 'ADMIN':
    print(f'Welcome {username}')
</code>```

Sorry I know it seems a silly question but hopefully it helps beginners like me understand or operator in python better.

Thank you for your help.

答:
What is going on here is treating Python like it's a spoken language.

What you intend with:

```<code>if username == 'admin' or 'Admin' or 'ADMIN':
    # stuff
</code>```

Is to mean:

```<code>if <condition>:
</code>```

The "condition" being if username is 'admin', 'Admin', or 'ADMIN'.

But that's not how python works. Python reads

```<code>if username == 'admin' or 'Admin' or 'ADMIN':
    # code
</code>```

as

```<code>if <condition 1> or <condition 2> or <condition 3>:
    # code
</code>```

--

Condition 1: username == 'admin' is FALSE.

--

Condition 2: 'Admin' is TRUE. This is because 'Admin' is a string literal object, which exists, and is non-zero, not null, and not empty, and therefore true.

This is like going

```<code>myString = "any string"

if myString:
    # code is executed because myString is not empty.
</code>```

But instead you're doing

```<code>if 'my string':
    # this code would run.
</code>```

--

Condition 3: 'ADMIN' is TRUE, for the same reason Condition 2 is TRUE.

--

What you have going on here is that the if condition is always true, no matter was is typed. Because

```<code>if username == 'admin' or 'Admin' or 'ADMIN':
    # code
</code>```

Evaluates to

```<code>if FALSE or TRUE or TRUE:
    # code
</code>```

And, therefore, will always evaluate to true and print whatever is in the username variable, even if it's not 'admin'.

Body:
I get confused why the message always pops up like 'Welcome xxx' no matter what a user types.

username = input('Please enter your username: ')

if username == 'admin' or 'Admin' or 'ADMIN':
    print(f'Welcome {username}')

Sorry I know it seems a silly question but hopefully it helps beginners like me understand or operator in python better.

Thank you for your help.

Body:
What is going on here is treating Python like it's a spoken language.

What you intend with:

if username == 'admin' or 'Admin' or 'ADMIN':
    # stuff

Is to mean:

if <condition>:

The "condition" being if username is 'admin', 'Admin', or 'ADMIN'.

But that's not how python works. Python reads

if username == 'admin' or 'Admin' or 'ADMIN':
    # code

as

if <condition 1> or <condition 2> or <condition 3>:
    # code

--

Condition 1: username == 'admin' is FALSE.

--

Condition 2: 'Admin' is TRUE. This is because 'Admin' is a string literal object, which exists, and is non-zero, not null, and not empty, and therefore true.

This is like going

myString = "any string"

if myString:
    # code is executed because myString is not empty.

But instead you're doing

if 'my string':
    # this code would run.

--

Condition 3: 'ADMIN' is TRUE, for the same reason Condition 2 is TRUE.

--

What you have going on here is that the if condition is always true, no matter was is typed. Because

if username == 'admin' or 'Admin' or 'ADMIN':
    # code

Evaluates to

if FALSE or TRUE or TRUE:
    # code

And, therefore, will always evaluate to true and print whatever is in the username variable, even if it's not 'admin'.


问:
Return index value from filter method javascript
I have an array of objects in my angular controller.

I want to return the value of the index of the field within the array which has a matching ID to my parameter.

There will only be one object in the array with a matching fieldId..

```<code>$scope.indexOfField = function(fieldId) {
  return $scope.model.fieldData.filter(function(x) {
    if (x.Id === fieldId) return // ???????
  });
}
</code>```

答:
Use the findIndex method - Array.prototype.findIndex().

When the condition is met first, the index is returned.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

Body:
I have an array of objects in my angular controller.

I want to return the value of the index of the field within the array which has a matching ID to my parameter.

There will only be one object in the array with a matching fieldId..

$scope.indexOfField = function(fieldId) {
  return $scope.model.fieldData.filter(function(x) {
    if (x.Id === fieldId) return // ???????
  });
}


问:
Break array of words in chunks based on the maximum number of character
I need to break the array of words into chunks based on maximum number of character:

const maxChar = 50
const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,','with','a','comfortable','home','and','happy','disposition,','seemed','to','unite','some','of','the','best','blessings','of','existence;','and','had','lived','nearly','twenty-one','years','in','the','world','with','very','little','to','distress','or','vex','her.']
```

<p>The desire result is to count the char of each word and break the array when the count of char reach maxChar.</p>

```const resultArr = [['Emma','Woodhouse,','handsome,','clever,','and','rich,','with','a'],['comfortable','home','and',..]....]
```

The problem is that I am using 2 for loops and want to know if there is a better way to reach the same result

答:
I figured out one better way:

const arrOfWords = ['Emma', 'Woodhouse,', 'handsome,', 'clever,', 'and', 'rich,', 'with', 'a', 'comfortable', 'home', 'and', 'happy', 'disposition,', 'seemed', 'to', 'unite', 'some', 'of', 'the', 'best', 'blessings', 'of', 'existence;', 'and', 'had', 'lived', 'nearly', 'twenty-one', 'years', 'in', 'the', 'world', 'with', 'very', 'little', 'to', 'distress', 'or', 'vex', 'her.']

const result = arrOfWords.join(' ').match(/.{1,50}\W/g).map(line => line.split(" ").filter(word => word.length > 0)) // 50 is the num of chars

 console.log('result: ', result)```

Body:
I need to break the array of words into chunks based on maximum number of character:

const maxChar = 50
const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,','with','a','comfortable','home','and','happy','disposition,','seemed','to','unite','some','of','the','best','blessings','of','existence;','and','had','lived','nearly','twenty-one','years','in','the','world','with','very','little','to','distress','or','vex','her.']

The desire result is to count the char of each word and break the array when the count of char reach maxChar.

const resultArr = [['Emma','Woodhouse,','handsome,','clever,','and','rich,','with','a'],['comfortable','home','and',..]....]

The problem is that I am using 2 for loops and want to know if there is a better way to reach the same result


问:
Using React's Hooks useReducer, the state is not "single source of truth"? How does the App or Sibling get the state of other components?
I tried the sample code of useReducer:

```<code>const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

export default function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  // ...
</code>```

and instantiated 3 Counters in the App.
Sample on: https://codesandbox.io/s/serene-morse-c017r

So it seems the state is local to each Counter component, and is not the "single source of truth" like on Redux?  If the App wants to get the value of all counters, or one Counter wants to get the value of another Counter, how would that be done?

答:
I made changes in your codesandbox and used context to make your counter as single source of truth like redux.

```<code>import React from "react";
const CountStateContext = React.createContext();
const CountDispatchContext = React.createContext();
function countReducer(state, action) {
  switch (action.type) {
    case "increment": {
      return { count: state.count + 1 };
    }
    case "decrement": {
      return { count: state.count - 1 };
    }
    default: {
      throw new Error(`Unhandled action type: ${action.type}`);
    }
  }
}
function CountProvider({ children }) {
  const [state, dispatch] = React.useReducer(countReducer, { count: 0 });
  return (
    <CountStateContext.Provider value={state}>
      <CountDispatchContext.Provider value={dispatch}>
        {children}
      </CountDispatchContext.Provider>
    </CountStateContext.Provider>
  );
}
function useCountState() {
  const context = React.useContext(CountStateContext);
  if (context === undefined) {
    throw new Error("useCountState must be used within a CountProvider");
  }
  return context;
}
function useCountDispatch() {
  const context = React.useContext(CountDispatchContext);
  if (context === undefined) {
    throw new Error("useCountDispatch must be used within a CountProvider");
  }
  return context;
}
export { CountProvider, useCountState, useCountDispatch };
</code>```

https://codesandbox.io/s/modern-wildflower-ihvjj

Body:
I tried the sample code of useReducer:

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

export default function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  // ...

and instantiated 3 Counters in the App.
Sample on: https://codesandbox.io/s/serene-morse-c017r

So it seems the state is local to each Counter component, and is not the "single source of truth" like on Redux?  If the App wants to get the value of all counters, or one Counter wants to get the value of another Counter, how would that be done?

Body:
I made changes in your codesandbox and used context to make your counter as single source of truth like redux.

import React from "react";
const CountStateContext = React.createContext();
const CountDispatchContext = React.createContext();
function countReducer(state, action) {
  switch (action.type) {
    case "increment": {
      return { count: state.count + 1 };
    }
    case "decrement": {
      return { count: state.count - 1 };
    }
    default: {
      throw new Error(`Unhandled action type: ${action.type}`);
    }
  }
}
function CountProvider({ children }) {
  const [state, dispatch] = React.useReducer(countReducer, { count: 0 });
  return (
    <CountStateContext.Provider value={state}>
      <CountDispatchContext.Provider value={dispatch}>
        {children}
      </CountDispatchContext.Provider>
    </CountStateContext.Provider>
  );
}
function useCountState() {
  const context = React.useContext(CountStateContext);
  if (context === undefined) {
    throw new Error("useCountState must be used within a CountProvider");
  }
  return context;
}
function useCountDispatch() {
  const context = React.useContext(CountDispatchContext);
  if (context === undefined) {
    throw new Error("useCountDispatch must be used within a CountProvider");
  }
  return context;
}
export { CountProvider, useCountState, useCountDispatch };

https://codesandbox.io/s/modern-wildflower-ihvjj


问:
How can I make the height of an element cover more than the visible area of the window?
I try to make the complete height of an element with absolute position and relative to body extend to the top of the whole page including the space that is not seen. only when scrolling

In the example, the sidebar extends along the visible view of the window, if the user scrolls the space that is not covered is noted

How can I make the height of an element cover more than the visible area of the window?

Thanks in advance

body {
    font-family: sans-serif;
    margin: 0;
}

.container {
  width: 300px;
  margin: 0 auto;
  border: 1px dashed grey;
  padding: 10px;
}

ul.items {
  list-style: none;
  margin: 0;
  border: 1px dotted orange;
  padding: 10px;
}

ul.items li {
  margin: 10px;
  padding: 10px;
  border: 1px solid darkturquoise;
}

nav.menu {
    background-color: deeppink;
    padding: 10px;
    position: absolute;
    width: 80px;
    top: 0;
    height: 100vh;
}

nav.menu ul {
    list-style: none;
    padding-left: 0;
}

nav.menu ul {
    margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <ul class="items">
      <li>item-1</li>
      <li>item-2</li>
      <li>item-3</li>
      <li>item-4</li>
      <li>item-5</li>
      <li>item-6</li>
      <li>item-7</li>
      <li>item-8</li>
      <li>item-9</li>
      <li>item-10</li>
      <li>item-11</li>
      <li>item-12</li>
      <li>item-13</li>
      <li>item-14</li>
      <li>item-15</li>
      <li>item-16</li>
      <li>item-17</li>
      <li>item-18</li>
      <li>item-19</li>
      <li>item-20</li>
      <li>item-21</li>
      <li>item-22</li>
      <li>item-23</li>
      <li>item-24</li>
      <li>item-25</li>
      <li>item-26</li>
      <li>item-27</li>
      <li>item-28</li>
      <li>item-29</li>
      <li>item-30</li>
      <li>item-31</li>
      <li>item-32</li>
      <li>item-33</li>
      <li>item-34</li>
      <li>item-35</li>
      <li>item-36</li>
      <li>item-37</li>
      <li>item-38</li>
      <li>item-39</li>
      <li>item-40</li>
      <li>item-41</li>
      <li>item-42</li>
      <li>item-43</li>
      <li>item-44</li>
      <li>item-45</li>
      <li>item-46</li>
      <li>item-47</li>
      <li>item-48</li>
      <li>item-49</li>
      <li>item-50</li>
    </ul>
  </div>
  <nav class="menu">
      <ul>
          <li>Link 1</li>
          <li>Link 2</li>
          <li>Link 3</li>
          <li>Link 4</li>
      </ul>
  </nav></code>```

答:
I found 4 solutions with a slight different behavior and approachs.

First Solution

make your nav container (body in your case) position: relative, it will make sense of nav position: absolute and now you can choose to make nav's height: 100% or bottom: 0.

Disadvantage - menu scrolls with items.

body {
    font-family: sans-serif;
    margin: 0;
    position: relative;
}

.container {
  width: 300px;
  margin: 0 auto;
  border: 1px dashed grey;
  padding: 10px;
}

ul.items {
  list-style: none;
  margin: 0;
  border: 1px dotted orange;
  padding: 10px;
}

ul.items li {
  margin: 10px;
  padding: 10px;
  border: 1px solid darkturquoise;
}

nav.menu {
    background-color: deeppink;
    padding: 10px;
    position: absolute;
    width: 80px;
    top: 0;
    bottom: 0;
}

nav.menu ul {
    list-style: none;
    padding-left: 0;
}

nav.menu ul {
    margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <ul class="items">
      <li>item-1</li>
      <li>item-2</li>
      <li>item-3</li>
      <li>item-4</li>
      <li>item-5</li>
      <li>item-6</li>
      <li>item-7</li>
      <li>item-8</li>
      <li>item-9</li>
      <li>item-10</li>
      <li>item-11</li>
      <li>item-12</li>
      <li>item-13</li>
      <li>item-14</li>
      <li>item-15</li>
      <li>item-16</li>
      <li>item-17</li>
      <li>item-18</li>
      <li>item-19</li>
      <li>item-20</li>
      <li>item-21</li>
      <li>item-22</li>
      <li>item-23</li>
      <li>item-24</li>
      <li>item-25</li>
      <li>item-26</li>
      <li>item-27</li>
      <li>item-28</li>
      <li>item-29</li>
      <li>item-30</li>
      <li>item-31</li>
      <li>item-32</li>
      <li>item-33</li>
      <li>item-34</li>
      <li>item-35</li>
      <li>item-36</li>
      <li>item-37</li>
      <li>item-38</li>
      <li>item-39</li>
      <li>item-40</li>
      <li>item-41</li>
      <li>item-42</li>
      <li>item-43</li>
      <li>item-44</li>
      <li>item-45</li>
      <li>item-46</li>
      <li>item-47</li>
      <li>item-48</li>
      <li>item-49</li>
      <li>item-50</li>
    </ul>
  </div>
  <nav class="menu">
      <ul>
          <li>Link 1</li>
          <li>Link 2</li>
          <li>Link 3</li>
          <li>Link 4</li>
      </ul>
  </nav></code>```

Second Solution

make nav position: fixed and bottom: 0 or height: 100% or height: 100vh.

In this case menu is always visible when items are scrolling.

body {
    font-family: sans-serif;
    margin: 0;
}

.container {
  width: 300px;
  margin: 0 auto;
  border: 1px dashed grey;
  padding: 10px;
}

ul.items {
  list-style: none;
  margin: 0;
  border: 1px dotted orange;
  padding: 10px;
}

ul.items li {
  margin: 10px;
  padding: 10px;
  border: 1px solid darkturquoise;
}

nav.menu {
    background-color: deeppink;
    padding: 10px;
    position: fixed;
    width: 80px;
    top: 0;
    bottom: 0;
}

nav.menu ul {
    list-style: none;
    padding-left: 0;
}

nav.menu ul {
    margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <ul class="items">
      <li>item-1</li>
      <li>item-2</li>
      <li>item-3</li>
      <li>item-4</li>
      <li>item-5</li>
      <li>item-6</li>
      <li>item-7</li>
      <li>item-8</li>
      <li>item-9</li>
      <li>item-10</li>
      <li>item-11</li>
      <li>item-12</li>
      <li>item-13</li>
      <li>item-14</li>
      <li>item-15</li>
      <li>item-16</li>
      <li>item-17</li>
      <li>item-18</li>
      <li>item-19</li>
      <li>item-20</li>
      <li>item-21</li>
      <li>item-22</li>
      <li>item-23</li>
      <li>item-24</li>
      <li>item-25</li>
      <li>item-26</li>
      <li>item-27</li>
      <li>item-28</li>
      <li>item-29</li>
      <li>item-30</li>
      <li>item-31</li>
      <li>item-32</li>
      <li>item-33</li>
      <li>item-34</li>
      <li>item-35</li>
      <li>item-36</li>
      <li>item-37</li>
      <li>item-38</li>
      <li>item-39</li>
      <li>item-40</li>
      <li>item-41</li>
      <li>item-42</li>
      <li>item-43</li>
      <li>item-44</li>
      <li>item-45</li>
      <li>item-46</li>
      <li>item-47</li>
      <li>item-48</li>
      <li>item-49</li>
      <li>item-50</li>
    </ul>
  </div>
  <nav class="menu">
      <ul>
          <li>Link 1</li>
          <li>Link 2</li>
          <li>Link 3</li>
          <li>Link 4</li>
      </ul>
  </nav></code>```

Third Solution

you can change structure.

Make some wrapper of menu and container. Move menu above container. Make wrapper display: flex. You can remove position: absolute and top: 0 from menu.

As in first solution - menu scrolls with items.

body {
  font-family: sans-serif;
  margin: 0;
}

.container {
  width: 300px;
  margin: 0 auto;
  border: 1px dashed grey;
  padding: 10px;
}

ul.items {
  list-style: none;
  margin: 0;
  border: 1px dotted orange;
  padding: 10px;
}

ul.items li {
  margin: 10px;
  padding: 10px;
  border: 1px solid darkturquoise;
}

nav.menu {
  background-color: deeppink;
  padding: 10px;
  width: 80px;
}

nav.menu ul {
  list-style: none;
  padding-left: 0;
}

nav.menu ul {
  margin: 0;
}

.wrapper {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <nav class="menu">
    <ul>
      <li>Link 1</li>
      <li>Link 2</li>
      <li>Link 3</li>
      <li>Link 4</li>
    </ul>
  </nav>
  <div class="container">
    <ul class="items">
      <li>item-1</li>
      <li>item-2</li>
      <li>item-3</li>
      <li>item-4</li>
      <li>item-5</li>
      <li>item-6</li>
      <li>item-7</li>
      <li>item-8</li>
      <li>item-9</li>
      <li>item-10</li>
      <li>item-11</li>
      <li>item-12</li>
      <li>item-13</li>
      <li>item-14</li>
      <li>item-15</li>
      <li>item-16</li>
      <li>item-17</li>
      <li>item-18</li>
      <li>item-19</li>
      <li>item-20</li>
      <li>item-21</li>
      <li>item-22</li>
      <li>item-23</li>
      <li>item-24</li>
      <li>item-25</li>
      <li>item-26</li>
      <li>item-27</li>
      <li>item-28</li>
      <li>item-29</li>
      <li>item-30</li>
      <li>item-31</li>
      <li>item-32</li>
      <li>item-33</li>
      <li>item-34</li>
      <li>item-35</li>
      <li>item-36</li>
      <li>item-37</li>
      <li>item-38</li>
      <li>item-39</li>
      <li>item-40</li>
      <li>item-41</li>
      <li>item-42</li>
      <li>item-43</li>
      <li>item-44</li>
      <li>item-45</li>
      <li>item-46</li>
      <li>item-47</li>
      <li>item-48</li>
      <li>item-49</li>
      <li>item-50</li>
    </ul>
  </div>
</div></code>```

Fourth Solution

structure as in the third solution.

But we make menu with position: sticky, top: 0 and height: calc(100vh - 10px * 2); (10px top and bottom padding value, if not subtract menu scrolls a little bit at the bottom of items scroll)

Menu is always visible.

body {
  font-family: sans-serif;
  margin: 0;
}

.container {
  width: 300px;
  margin: 0 auto;
  border: 1px dashed grey;
  padding: 10px;
}

ul.items {
  list-style: none;
  margin: 0;
  border: 1px dotted orange;
  padding: 10px;
}

ul.items li {
  margin: 10px;
  padding: 10px;
  border: 1px solid darkturquoise;
}

nav.menu {
  background-color: deeppink;
  padding: 10px;
  width: 80px;
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 0;
  height: calc(100vh - 10px * 2); /*top + bottom padding value*/
}

nav.menu ul {
  list-style: none;
  padding-left: 0;
}

nav.menu ul {
  margin: 0;
}

.wrapper {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <nav class="menu">
    <ul>
      <li>Link 1</li>
      <li>Link 2</li>
      <li>Link 3</li>
      <li>Link 4</li>
    </ul>
  </nav>
  <div class="container">
    <ul class="items">
      <li>item-1</li>
      <li>item-2</li>
      <li>item-3</li>
      <li>item-4</li>
      <li>item-5</li>
      <li>item-6</li>
      <li>item-7</li>
      <li>item-8</li>
      <li>item-9</li>
      <li>item-10</li>
      <li>item-11</li>
      <li>item-12</li>
      <li>item-13</li>
      <li>item-14</li>
      <li>item-15</li>
      <li>item-16</li>
      <li>item-17</li>
      <li>item-18</li>
      <li>item-19</li>
      <li>item-20</li>
      <li>item-21</li>
      <li>item-22</li>
      <li>item-23</li>
      <li>item-24</li>
      <li>item-25</li>
      <li>item-26</li>
      <li>item-27</li>
      <li>item-28</li>
      <li>item-29</li>
      <li>item-30</li>
      <li>item-31</li>
      <li>item-32</li>
      <li>item-33</li>
      <li>item-34</li>
      <li>item-35</li>
      <li>item-36</li>
      <li>item-37</li>
      <li>item-38</li>
      <li>item-39</li>
      <li>item-40</li>
      <li>item-41</li>
      <li>item-42</li>
      <li>item-43</li>
      <li>item-44</li>
      <li>item-45</li>
      <li>item-46</li>
      <li>item-47</li>
      <li>item-48</li>
      <li>item-49</li>
      <li>item-50</li>
    </ul>
  </div>
</div></code>```

Body:
I try to make the complete height of an element with absolute position and relative to body extend to the top of the whole page including the space that is not seen. only when scrolling

In the example, the sidebar extends along the visible view of the window, if the user scrolls the space that is not covered is noted

How can I make the height of an element cover more than the visible area of the window?

Thanks in advance

body {
    font-family: sans-serif;
    margin: 0;
}

.container {
  width: 300px;
  margin: 0 auto;
  border: 1px dashed grey;
  padding: 10px;
}

ul.items {
  list-style: none;
  margin: 0;
  border: 1px dotted orange;
  padding: 10px;
}

ul.items li {
  margin: 10px;
  padding: 10px;
  border: 1px solid darkturquoise;
}

nav.menu {
    background-color: deeppink;
    padding: 10px;
    position: absolute;
    width: 80px;
    top: 0;
    height: 100vh;
}

nav.menu ul {
    list-style: none;
    padding-left: 0;
}

nav.menu ul {
    margin: 0;
}

item-1

item-2

item-3

item-4

item-5

item-6

item-7

item-8

item-9

item-10

item-11

item-12

item-13

item-14

item-15

item-16

item-17

item-18

item-19

item-20

item-21

item-22

item-23

item-24

item-25

item-26

item-27

item-28

item-29

item-30

item-31

item-32

item-33

item-34

item-35

item-36

item-37

item-38

item-39

item-40

item-41

item-42

item-43

item-44

item-45

item-46

item-47

item-48

item-49

item-50

Link 1

Link 2

Link 3

Link 4

Body:
I found 4 solutions with a slight different behavior and approachs.

First Solution

make your nav container (body in your case) position: relative, it will make sense of nav position: absolute and now you can choose to make nav's height: 100% or bottom: 0.

Disadvantage - menu scrolls with items.

body {
    font-family: sans-serif;
    margin: 0;
    position: relative;
}

.container {
  width: 300px;
  margin: 0 auto;
  border: 1px dashed grey;
  padding: 10px;
}

ul.items {
  list-style: none;
  margin: 0;
  border: 1px dotted orange;
  padding: 10px;
}

ul.items li {
  margin: 10px;
  padding: 10px;
  border: 1px solid darkturquoise;
}

nav.menu {
    background-color: deeppink;
    padding: 10px;
    position: absolute;
    width: 80px;
    top: 0;
    bottom: 0;
}

nav.menu ul {
    list-style: none;
    padding-left: 0;
}

nav.menu ul {
    margin: 0;
}

<div class="container">
    <ul class="items">
      <li>item-1</li>
      <li>item-2</li>
      <li>item-3</li>
      <li>item-4</li>
      <li>item-5</li>
      <li>item-6</li>
      <li>item-7</li>
      <li>item-8</li>
      <li>item-9</li>
      <li>item-10</li>
      <li>item-11</li>
      <li>item-12</li>
      <li>item-13</li>
      <li>item-14</li>
      <li>item-15</li>
      <li>item-16</li>
      <li>item-17</li>
      <li>item-18</li>
      <li>item-19</li>
      <li>item-20</li>
      <li>item-21</li>
      <li>item-22</li>
      <li>item-23</li>
      <li>item-24</li>
      <li>item-25</li>
      <li>item-26</li>
      <li>item-27</li>
      <li>item-28</li>
      <li>item-29</li>
      <li>item-30</li>
      <li>item-31</li>
      <li>item-32</li>
      <li>item-33</li>
      <li>item-34</li>
      <li>item-35</li>
      <li>item-36</li>
      <li>item-37</li>
      <li>item-38</li>
      <li>item-39</li>
      <li>item-40</li>
      <li>item-41</li>
      <li>item-42</li>
      <li>item-43</li>
      <li>item-44</li>
      <li>item-45</li>
      <li>item-46</li>
      <li>item-47</li>
      <li>item-48</li>
      <li>item-49</li>
      <li>item-50</li>
    </ul>
  </div>
  <nav class="menu">
      <ul>
          <li><a href="#">Link 1</a></li>
          <li><a href="#">Link 2</a></li>
          <li><a href="#">Link 3</a></li>
          <li><a href="#">Link 4</a></li>
      </ul>
  </nav>

Second Solution

make nav position: fixed and bottom: 0 or height: 100% or height: 100vh.

In this case menu is always visible when items are scrolling.

body {
    font-family: sans-serif;
    margin: 0;
}

.container {
  width: 300px;
  margin: 0 auto;
  border: 1px dashed grey;
  padding: 10px;
}

ul.items {
  list-style: none;
  margin: 0;
  border: 1px dotted orange;
  padding: 10px;
}

ul.items li {
  margin: 10px;
  padding: 10px;
  border: 1px solid darkturquoise;
}

nav.menu {
    background-color: deeppink;
    padding: 10px;
    position: fixed;
    width: 80px;
    top: 0;
    bottom: 0;
}

nav.menu ul {
    list-style: none;
    padding-left: 0;
}

nav.menu ul {
    margin: 0;
}

<div class="container">
    <ul class="items">
      <li>item-1</li>
      <li>item-2</li>
      <li>item-3</li>
      <li>item-4</li>
      <li>item-5</li>
      <li>item-6</li>
      <li>item-7</li>
      <li>item-8</li>
      <li>item-9</li>
      <li>item-10</li>
      <li>item-11</li>
      <li>item-12</li>
      <li>item-13</li>
      <li>item-14</li>
      <li>item-15</li>
      <li>item-16</li>
      <li>item-17</li>
      <li>item-18</li>
      <li>item-19</li>
      <li>item-20</li>
      <li>item-21</li>
      <li>item-22</li>
      <li>item-23</li>
      <li>item-24</li>
      <li>item-25</li>
      <li>item-26</li>
      <li>item-27</li>
      <li>item-28</li>
      <li>item-29</li>
      <li>item-30</li>
      <li>item-31</li>
      <li>item-32</li>
      <li>item-33</li>
      <li>item-34</li>
      <li>item-35</li>
      <li>item-36</li>
      <li>item-37</li>
      <li>item-38</li>
      <li>item-39</li>
      <li>item-40</li>
      <li>item-41</li>
      <li>item-42</li>
      <li>item-43</li>
      <li>item-44</li>
      <li>item-45</li>
      <li>item-46</li>
      <li>item-47</li>
      <li>item-48</li>
      <li>item-49</li>
      <li>item-50</li>
    </ul>
  </div>
  <nav class="menu">
      <ul>
          <li><a href="#">Link 1</a></li>
          <li><a href="#">Link 2</a></li>
          <li><a href="#">Link 3</a></li>
          <li><a href="#">Link 4</a></li>
      </ul>
  </nav>

Third Solution

you can change structure.

Make some wrapper of menu and container. Move menu above container. Make wrapper display: flex. You can remove position: absolute and top: 0 from menu.

As in first solution - menu scrolls with items.

body {
  font-family: sans-serif;
  margin: 0;
}

.container {
  width: 300px;
  margin: 0 auto;
  border: 1px dashed grey;
  padding: 10px;
}

ul.items {
  list-style: none;
  margin: 0;
  border: 1px dotted orange;
  padding: 10px;
}

ul.items li {
  margin: 10px;
  padding: 10px;
  border: 1px solid darkturquoise;
}

nav.menu {
  background-color: deeppink;
  padding: 10px;
  width: 80px;
}

nav.menu ul {
  list-style: none;
  padding-left: 0;
}

nav.menu ul {
  margin: 0;
}

.wrapper {
  display: flex;
}

<div class="wrapper">
  <nav class="menu">
    <ul>
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
      <li><a href="#">Link 3</a></li>
      <li><a href="#">Link 4</a></li>
    </ul>
  </nav>
  <div class="container">
    <ul class="items">
      <li>item-1</li>
      <li>item-2</li>
      <li>item-3</li>
      <li>item-4</li>
      <li>item-5</li>
      <li>item-6</li>
      <li>item-7</li>
      <li>item-8</li>
      <li>item-9</li>
      <li>item-10</li>
      <li>item-11</li>
      <li>item-12</li>
      <li>item-13</li>
      <li>item-14</li>
      <li>item-15</li>
      <li>item-16</li>
      <li>item-17</li>
      <li>item-18</li>
      <li>item-19</li>
      <li>item-20</li>
      <li>item-21</li>
      <li>item-22</li>
      <li>item-23</li>
      <li>item-24</li>
      <li>item-25</li>
      <li>item-26</li>
      <li>item-27</li>
      <li>item-28</li>
      <li>item-29</li>
      <li>item-30</li>
      <li>item-31</li>
      <li>item-32</li>
      <li>item-33</li>
      <li>item-34</li>
      <li>item-35</li>
      <li>item-36</li>
      <li>item-37</li>
      <li>item-38</li>
      <li>item-39</li>
      <li>item-40</li>
      <li>item-41</li>
      <li>item-42</li>
      <li>item-43</li>
      <li>item-44</li>
      <li>item-45</li>
      <li>item-46</li>
      <li>item-47</li>
      <li>item-48</li>
      <li>item-49</li>
      <li>item-50</li>
    </ul>
  </div>
</div>

Fourth Solution

structure as in the third solution.

But we make menu with position: sticky, top: 0 and height: calc(100vh - 10px * 2); (10px top and bottom padding value, if not subtract menu scrolls a little bit at the bottom of items scroll)

Menu is always visible.

body {
  font-family: sans-serif;
  margin: 0;
}

.container {
  width: 300px;
  margin: 0 auto;
  border: 1px dashed grey;
  padding: 10px;
}

ul.items {
  list-style: none;
  margin: 0;
  border: 1px dotted orange;
  padding: 10px;
}

ul.items li {
  margin: 10px;
  padding: 10px;
  border: 1px solid darkturquoise;
}

nav.menu {
  background-color: deeppink;
  padding: 10px;
  width: 80px;
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 0;
  height: calc(100vh - 10px * 2); /*top + bottom padding value*/
}

nav.menu ul {
  list-style: none;
  padding-left: 0;
}

nav.menu ul {
  margin: 0;
}

.wrapper {
  display: flex;
}

<div class="wrapper">
  <nav class="menu">
    <ul>
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
      <li><a href="#">Link 3</a></li>
      <li><a href="#">Link 4</a></li>
    </ul>
  </nav>
  <div class="container">
    <ul class="items">
      <li>item-1</li>
      <li>item-2</li>
      <li>item-3</li>
      <li>item-4</li>
      <li>item-5</li>
      <li>item-6</li>
      <li>item-7</li>
      <li>item-8</li>
      <li>item-9</li>
      <li>item-10</li>
      <li>item-11</li>
      <li>item-12</li>
      <li>item-13</li>
      <li>item-14</li>
      <li>item-15</li>
      <li>item-16</li>
      <li>item-17</li>
      <li>item-18</li>
      <li>item-19</li>
      <li>item-20</li>
      <li>item-21</li>
      <li>item-22</li>
      <li>item-23</li>
      <li>item-24</li>
      <li>item-25</li>
      <li>item-26</li>
      <li>item-27</li>
      <li>item-28</li>
      <li>item-29</li>
      <li>item-30</li>
      <li>item-31</li>
      <li>item-32</li>
      <li>item-33</li>
      <li>item-34</li>
      <li>item-35</li>
      <li>item-36</li>
      <li>item-37</li>
      <li>item-38</li>
      <li>item-39</li>
      <li>item-40</li>
      <li>item-41</li>
      <li>item-42</li>
      <li>item-43</li>
      <li>item-44</li>
      <li>item-45</li>
      <li>item-46</li>
      <li>item-47</li>
      <li>item-48</li>
      <li>item-49</li>
      <li>item-50</li>
    </ul>
  </div>
</div>


问:
What is the use case of using @Qualifier in @Bean definition?
I know meaning of @Qualifier and @Bean annotations but what is the point of using it in a code like this? Is this for overriding "loadBalancedRestTemplate" bean or what?</p>

```<code>@Bean
@Qualifier("loadBalancedRestTemplate")
public RestTemplate restTemplate(RestTemplateCustomizer customizer) {
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    customizer.customize(restTemplate);
    return restTemplate;
}
</code>```

答:
I think this simple and concise answer found in Spring Docs would answer your question best:

@Primary is an effective way to use autowiring by type with several
  instances when one primary candidate can be determined. When you need
  more control over the selection process, you can use Spring’s
  @Qualifier annotation. You can associate qualifier values with
  specific arguments, narrowing the set of type matches so that a
  specific bean is chosen for each argument.

Body:
I know meaning of @Qualifier and @Bean annotations but what is the point of using it in a code like this? Is this for overriding "loadBalancedRestTemplate" bean or what?

@Bean
@Qualifier("loadBalancedRestTemplate")
public RestTemplate restTemplate(RestTemplateCustomizer customizer) {
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    customizer.customize(restTemplate);
    return restTemplate;
}


问:
What Unsupported docker v2 repository request for 'artifactory' means
My docker client/server version is:

```<code>$ docker version
Client:
Version:           18.09.0
API version:       1.39
Go version:        go1.10.4
Git commit:        4d60db4
Built:             Wed Nov  7 00:49:01 2018
OS/Arch:           linux/amd64
Experimental:      false

Server: Docker Engine - Community
Engine:
Version:          18.09.0
API version:      1.39 (minimum version 1.12)
Go version:       go1.10.4
Git commit:       4d60db4
Built:            Wed Nov  7 00:16:44 2018
OS/Arch:          linux/amd64
Experimental:     false
</code>```

Would like to use artifactory to host dockers.
When running

```<code>docker login
</code>```

getting:

Unsupported docker v2 repository request for 'artifactory'

What does this error mean?

What V2 part is artifactory complaining on?

答:
In addition to the error with reverse proxy, this message also appears when you try to push an image into a non-existent repository.

Look for HTTP 404 in Artifactory request.log

Body:
My docker client/server version is:

$ docker version
Client:
Version:           18.09.0
API version:       1.39
Go version:        go1.10.4
Git commit:        4d60db4
Built:             Wed Nov  7 00:49:01 2018
OS/Arch:           linux/amd64
Experimental:      false

Server: Docker Engine - Community
Engine:
Version:          18.09.0
API version:      1.39 (minimum version 1.12)
Go version:       go1.10.4
Git commit:       4d60db4
Built:            Wed Nov  7 00:16:44 2018
OS/Arch:          linux/amd64
Experimental:     false

Would like to use artifactory to host dockers.
When running

docker login

getting:

Unsupported docker v2 repository request for 'artifactory'

What does this error mean?

What V2 part is artifactory complaining on?