问:
Mocking a request object to pass to ViewSet create() method
I'm learning unittest and unittest.mock, and struggling with the concepts and implementations primarily with mock.

For context, what I'm playing with is a Django / DRF API and Redis. I'm trying to write tests which require mocking the Redis calls.

Here is the test I'm working on:

```<code># tests.py

import unittest
from unittest.mock import patch

from core.views import KeysViewSet

class KeysViewSetTestCase(unittest.TestCase):

    def setUp(self):
        self.json_object = {'key': 'hello', 'value': 'world'}
        self.view = KeysViewSet()

    def test_create(self):
        with patch('core.views.RedisUtil.create') as mocked_create:
            mocked_create.return_value.data = True

            created = self.view.create(self.json_object)
</code>```

The views.py:

```<code># viefws.py

# Third party imports
from rest_framework import status, viewsets
from rest_framework.response import Response

# Croner imports
from .serializers import KeysSerializer

# Import Redis
from .utils import RedisUtil

class KeysViewSet(viewsets.ViewSet):
    """
    METHOD      URI                 DESCRIPTION
    GET         /api/keys/<:key>/   Returns specific value from key
    POST        /api/keys/          Creates a new key/value
    DELETE      /api/keys/<:key>/   Deletes a specific key
    """

    def __init__(self, *args, **kwargs):
        """
        Instantiate the RedisUtil object.
        """
        self.redis_util = RedisUtil()

    def create(self, request):
        """
        Creates a key/pair in the Redis store.
        """
        print(request)
        # Serialize the request body
        serializer = KeysSerializer(data=request.data)

        # If valid, create the key/value in Redis; if not send error message
        if serializer.is_valid():
            return Response(self.redis_util.create(serializer.data))
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
</code>```

And the utils.py that handles the Redis actions:

```<code># utils.py

# Django imports
from django.conf import settings

# Redis imports
import redis

class RedisUtil:
    """
    Instantiates the Redis object and sets the connection params.
    """
    def __init__(self):
        self.redis_instance = redis.StrictRedis(
            host=settings.REDIS_HOST,
            port=settings.REDIS_PORT
        )

    def create(self, data):
        """
        Creates the key/value pair from request body.
        """
        return self.redis_instance.set(data['key'], data['value'])
</code>```

The error I'm getting is the following:

```<code>Found 1 test(s).
System check identified no issues (0 silenced).
{'key': 'hello', 'value': 'world'}
E
======================================================================
ERROR: test_create (core.tests.KeysViewSetTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/cjones/Projects/test/kv-store/api/src/core/tests.py", line 19, in test_create
    created = self.view.create(self.json_object)
  File "/Users/cjones/Projects/test/kv-store/api/src/core/views.py", line 32, in create
    serializer = KeysSerializer(data=request.data)
AttributeError: 'dict' object has no attribute 'data'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)
</code>```

I know what I'm getting this error: the KeysViewSet().create() in views.py is expecting the object I'm passing to be at request.data = {} and it isn't.

Resolving it is what I'm trying to figure out.

I know there is the request library, but not sure I would need to import it just for this. DRF has several options including APIRequestFactory, but those will try to spin up a database and create an error as it will try to connect to Redis which it won't be able to.

How should I go about resolving this issue?

答:
What I ended up doing to resolve the issue was the following:

```<code># test.py

import unittest
from unittest.mock import patch

from core.views import KeysViewSet

class KeysViewSetTestCase(unittest.TestCase):

    def setUp(self):
        self.json_object = {'key': 'hello', 'value': 'world'}
        self.view = KeysViewSet()
        class Request:
            def __init__(self, data):
                self.data = data
        self.request = Request(self.json_object)

    def test_create(self):
        with patch('core.views.RedisUtil.create') as mocked_create:
            mocked_create.return_value.data = True

            created = self.view.create(self.request)
</code>```

That being said, I'm not sure that this is a desirable solution so I'm reluctant to accept it as the correct answer. Looking forward to feedback.

Body:
I'm learning unittest and unittest.mock, and struggling with the concepts and implementations primarily with mock.

For context, what I'm playing with is a Django / DRF API and Redis. I'm trying to write tests which require mocking the Redis calls.

Here is the test I'm working on:

# tests.py

import unittest
from unittest.mock import patch

from core.views import KeysViewSet

class KeysViewSetTestCase(unittest.TestCase):

    def setUp(self):
        self.json_object = {'key': 'hello', 'value': 'world'}
        self.view = KeysViewSet()

    def test_create(self):
        with patch('core.views.RedisUtil.create') as mocked_create:
            mocked_create.return_value.data = True

            created = self.view.create(self.json_object)

The views.py:

# viefws.py

# Third party imports
from rest_framework import status, viewsets
from rest_framework.response import Response

# Croner imports
from .serializers import KeysSerializer

# Import Redis
from .utils import RedisUtil

class KeysViewSet(viewsets.ViewSet):
    """
    METHOD      URI                 DESCRIPTION
    GET         /api/keys/<:key>/   Returns specific value from key
    POST        /api/keys/          Creates a new key/value
    DELETE      /api/keys/<:key>/   Deletes a specific key
    """

    def __init__(self, *args, **kwargs):
        """
        Instantiate the RedisUtil object.
        """
        self.redis_util = RedisUtil()

    def create(self, request):
        """
        Creates a key/pair in the Redis store.
        """
        print(request)
        # Serialize the request body
        serializer = KeysSerializer(data=request.data)

        # If valid, create the key/value in Redis; if not send error message
        if serializer.is_valid():
            return Response(self.redis_util.create(serializer.data))
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

And the utils.py that handles the Redis actions:

# utils.py

# Django imports
from django.conf import settings

# Redis imports
import redis

class RedisUtil:
    """
    Instantiates the Redis object and sets the connection params.
    """
    def __init__(self):
        self.redis_instance = redis.StrictRedis(
            host=settings.REDIS_HOST,
            port=settings.REDIS_PORT
        )

    def create(self, data):
        """
        Creates the key/value pair from request body.
        """
        return self.redis_instance.set(data['key'], data['value'])

The error I'm getting is the following:

Found 1 test(s).
System check identified no issues (0 silenced).
{'key': 'hello', 'value': 'world'}
E
======================================================================
ERROR: test_create (core.tests.KeysViewSetTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/cjones/Projects/test/kv-store/api/src/core/tests.py", line 19, in test_create
    created = self.view.create(self.json_object)
  File "/Users/cjones/Projects/test/kv-store/api/src/core/views.py", line 32, in create
    serializer = KeysSerializer(data=request.data)
AttributeError: 'dict' object has no attribute 'data'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

I know what I'm getting this error: the KeysViewSet().create() in views.py is expecting the object I'm passing to be at request.data = {} and it isn't.

Resolving it is what I'm trying to figure out.

I know there is the request library, but not sure I would need to import it just for this. DRF has several options including APIRequestFactory, but those will try to spin up a database and create an error as it will try to connect to Redis which it won't be able to.

How should I go about resolving this issue?

Body:
What I ended up doing to resolve the issue was the following:

# test.py

import unittest
from unittest.mock import patch

from core.views import KeysViewSet

class KeysViewSetTestCase(unittest.TestCase):

    def setUp(self):
        self.json_object = {'key': 'hello', 'value': 'world'}
        self.view = KeysViewSet()
        class Request:
            def __init__(self, data):
                self.data = data
        self.request = Request(self.json_object)

    def test_create(self):
        with patch('core.views.RedisUtil.create') as mocked_create:
            mocked_create.return_value.data = True

            created = self.view.create(self.request)

That being said, I'm not sure that this is a desirable solution so I'm reluctant to accept it as the correct answer. Looking forward to feedback.


来源: stackexchange

问:
Import "rest_framework" could not be resolved. But I have installed djangorestframework, I don't know what is going wrong
Here's my settings.py:</p>
```<code>INSTALLED_APPS = [
    'rest_framework',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api.apps.ApiConfig'
]
</code>```

答:
Control+ shift + p.

type 'Python: Select Interpreter' and select the same.

choose your virtual env from the list
if it is not listed please choose
Enter Interpreter path'

Give pathe like this 'c:\users\user\django\myvenv\scripts\python.ex'

ContentLicense: CC BY-SA 4.0

Body:
Here's my settings.py:

INSTALLED_APPS = [
    'rest_framework',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api.apps.ApiConfig'
]


问:
RelativeDateTimeFormatter says a date from 2 days ago is yesterday
I noticed a particular day that refers to two days ago was localised as Yesterday by the formatter. Is there a config to set to make this be 2 days ago instead? Here's code to replicate the issue:

```<code>func getDateFromString(_ dateTimeString: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
    return dateFormatter.date(from:dateTimeString)!
}

let targetDateStr = "2022-02-08T19:50:11.333017Z"
let nowStr = "2022-02-10T16:57:10.000017Z"

let targetDate = getDateFromString(targetDateStr)
let now = getDateFromString(nowStr)

let formatter = RelativeDateTimeFormatter()
formatter.dateTimeStyle = .named
formatter.unitsStyle = .short
let s = formatter.localizedString(for: targetDate, relativeTo: now) // "yesterday"
</code>```

I noticed that the formatter produces "2 days ago" only after 48 hours have passed, is there a way to change this behaviour so that any hour on 2022-02-08 gets considered 2 days ago?

Edit

Problem solved: need to remove the hours/minutes/etc. info from the date then the formatter behaves as expected. Thanks @Dev

```<code>func getDateFromString(_ dateTimeString: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
    let date = dateFormatter.date(from:dateTimeString)!
    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day], from: date)
    return calendar.date(from: components)!
}
</code>```

答:
I haven't used swift, but does the .date function return a date object that has only the date or both date & time? I imagine it would work if you just compared dates (the yyyy-MM-dd component) and not dates & times.

Link to thread on removing timestamp components
Convert string to date in Swift

Body:
I noticed a particular day that refers to two days ago was localised as Yesterday by the formatter. Is there a config to set to make this be 2 days ago instead? Here's code to replicate the issue:

func getDateFromString(_ dateTimeString: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
    return dateFormatter.date(from:dateTimeString)!
}

let targetDateStr = "2022-02-08T19:50:11.333017Z"
let nowStr = "2022-02-10T16:57:10.000017Z"

let targetDate = getDateFromString(targetDateStr)
let now = getDateFromString(nowStr)

let formatter = RelativeDateTimeFormatter()
formatter.dateTimeStyle = .named
formatter.unitsStyle = .short
let s = formatter.localizedString(for: targetDate, relativeTo: now) // "yesterday"

I noticed that the formatter produces "2 days ago" only after 48 hours have passed, is there a way to change this behaviour so that any hour on 2022-02-08 gets considered 2 days ago?

Edit

Problem solved: need to remove the hours/minutes/etc. info from the date then the formatter behaves as expected. Thanks @Dev

func getDateFromString(_ dateTimeString: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
    let date = dateFormatter.date(from:dateTimeString)!
    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day], from: date)
    return calendar.date(from: components)!
}


问:
VB.NET Class Shared Function or Instance function
Just wondering what is the best practice when using functions or properties.
I have a class

```<code>Class Person
    Property FirstName as String
    Property LastName as String

    'code to use
    Return $"{LastName.ToUpper}, {FirstName}"
End Class
</code>```

What's the best way?

ReadOnly Property FullName as String

Function FullName as String

Shared Function FullName(p as Person) as String

My understanding is 3 would be better as 1 or 2 would be part of the object, but there is nothing unique in what they do to an object, so the same code would be duplicated for every Person object.

答:
My understanding is 3 would be better as 1 or 2 would be part of the object, but there is nothing unique in what they do to an object, so the same code would be duplicated for every Person object.

No, code is not duplicated. All object instances of a class contain their own copy of their fields, but there is only one copy of the code in memory.

An instance method can be considered syntactic sugar for a shared method which takes the object instance as its first parameter, so there is no difference between 2 and 3 with respect to memory usage. Option 2 has a few advantages over option 3, though:

It's more idiomatic: myPerson.GetFullName() is easier to read than Person.GetFullName(myPerson).

It allows you to add polymorphism, if needed: An instance method can be overridden in a subclass, and instance methods can be used to implement interfaces.

A read-only property can be considered syntactic sugar for an instance method, so there's not much difference between 1 and 2 either. Microsoft published a guideline to choose between those two:

Choosing Between Properties and Methods

In particular, it advises to choose a property if "the member represents a logical attribute of the type", which is the case here. It also lists a number of criteria for choosing a method (expensive operation, conversion, different result on subsequent calls, side effects, state copy), none of which apply here. Thus, I'd say that option 1 is a clear winner here.

Body:
Just wondering what is the best practice when using functions or properties.
I have a class

Class Person
    Property FirstName as String
    Property LastName as String

    'code to use
    Return $"{LastName.ToUpper}, {FirstName}"
End Class

What's the best way?

ReadOnly Property FullName as String

Function FullName as String

Shared Function FullName(p as Person) as String

My understanding is 3 would be better as 1 or 2 would be part of the object, but there is nothing unique in what they do to an object, so the same code would be duplicated for every Person object.


问:
Can't make function return value wait for fetched result - Now multithreaded
Previously I asked this question in a single threaded situation, and was given an answer that worked in that situation here.  But now I'm trying to answer the same question in a multithreaded environment.

I'm using OpenLayers to draw a UK Ordnance Survey map. I have working examples, but they use a less secure method of accessing the UKOS servers by giving a key in the URL, whereas I'd like to use the more secure OAuth2 arrangement instead. To this end, I already have a CGI script querying the servers to get a session token, and returning this as JSON. The problem can be solved in a single-threaded environment by making the map drawing page wait for its return, as follows:

```<code>UKOS.getToken = async function () {
  if (
    !UKOS.token ||
    new Date().getTime() >
      UKOS.token.issued_at + 1000 * (UKOS.token.expires_in - 15)
  )
    UKOS.token = await fetch(/* CGI Script */).then((response) =>
      response.json()
    );
  console.log(UKOS.token.access_token);
  return UKOS.token.access_token;
};
// ...
UKOS.getToken()
  .then(token => fetch(UKOS.WMTS + "&request=GetCapabilities&version=2.0.0", { headers: {Authorization: "Bearer " + token} }) )
  .then( /* etc */ )
</code>```

However, now that I'm using a multi-threaded environment the above no longer works, because after the first call to getToken() launches the fetching of the token, subsequent calls come crashing through before it can be returned, and, depending on exactly how I try to code getToken(), either launch multiple fetches of tokens when one will do (until it expires), or else don't wait for the token to be returned, and fail because it is still null.  This is my current attempted adaptation of getToken() ...

```<code>UKOS = {
    token:      null,
    tokStat:    0,
    tokProm:    null
    }
UKOS.getToken = async function() {
    var result;
    console.log( "UKOS.tokStat: " + UKOS.tokStat );
    switch( UKOS.tokStat ) {
        case 1: await UKOS.tokProm;
                await UKOS.token;
                // Deliberate fall through
                console.log( "UKOS.token: " + UKOS.token );
                console.log( "Falling through from 1 to 2 ..." );
        case 2: if( new Date().getTime() < UKOS.token.issued_at + 1000*(UKOS.token.expires_in - 15) ) {
                    result = UKOS.token.access_token;
                    break;
                    }
                // Deliberate fall through
                console.log( "Falling through from 2 to 0 ..." );
        case 0: UKOS.tokStat    = 1;
                UKOS.tokProm    = fetch( location.protocol + '//' + location.host + "/cgi-bin/OSDataOAuth.py" );
                UKOS.token      = await UKOS.tokProm.then( response => response.json() );
                UKOS.tokStat    = 2;
                result = UKOS.token.access_token;
        }
    return result;
    };
</code>```

Without the two 'await' qualifiers, of course subsequent calls just crash through into 'case 2' and fail because the token is still null, with them, this is the result [irrelevant detail edited out] ...

```<code>// Debugging console log message from routine calling getToken()
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=1&FORMAT=image%2Fpng
// Debugging console log message from getToken()
UKOS.tokStat: 0
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=5&TILECOL=1&FORMAT=image%2Fpng
UKOS.tokStat: 1
[Repeated multiple times]
url: undefined
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=1&FORMAT=image%2Fpng
[Repeated multiple times]
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=2&FORMAT=image%2Fpng
UKOS.tokStat: 1

// Token fetched successfully
// (see end, the only map tile fetch that succeeds is almost certainly the first to call getToken())
XHRGET http://local.localhost/cgi-bin/OSDataOAuth.py
[HTTP/1.1 200 OK 1590ms]

url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=5&TILECOL=2&FORMAT=image%2Fpng
UKOS.tokStat: 1
[Repeated multiple times]
UKOS.token: null
Falling through from 1 to 2 ...
[Repeated multiple times]
Falling through from 1 to 2 ...
Uncaught (in promise) TypeError: UKOS.token is null
    getToken http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:206
    setImgSrc http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:301
    initImage https://openlayers.org/api/2.13/OpenLayers.debug.js:29733
    renderTile https://openlayers.org/api/2.13/OpenLayers.debug.js:29608
    draw https://openlayers.org/api/2.13/OpenLayers.debug.js:29581
    initGriddedTiles https://openlayers.org/api/2.13/OpenLayers.debug.js:30951
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:30422
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:83261
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:9273
    setCenter https://openlayers.org/api/2.13/OpenLayers.debug.js:9035
    setBaseLayer http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:442
    addLayer https://openlayers.org/api/2.13/OpenLayers.debug.js:8354
    initOSMap http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:457
    onload http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:1
UKOSOpenLayers2.shtml:206:34
[Repeated multiple times]
// I think this one, the only one to successfully fetch a map tile is probably the first attempt to do so, which correctly waited for the returned token
XHRGET https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=Leisure_27700&STYLE=default&TILEMATRIXSET=EPSG:27700&TILEMATRIX=EPSG:27700:0&TILEROW=6&TILECOL=1&FORMAT=image/png
[HTTP/1.1 200 OK 1417ms]
dataUrl: blob:http://local.localhost/2f7fa455-3385-4d10-ab0e-b70999658137
</code>```

What is interesting about the above is that the two 'await's do appear to be accomplishing something, but not enough, because without them each ...

```<code>UKOS.tokStat: 1
</code>```

... is immediately followed by ...

```<code>UKOS.token: null
Falling through from 1 to 2 ...
</code>```

... yet they're obviously not waiting for the token to be returned, as evidenced by the fact that they all fail before the first call ultimately succeeds.  Can anyone suggest how to make the second and subsequent calls wait for the token requested by the first call?

答:
In your original code there are two paths through the function.

You have a token already

return it

You don't have a token already

make an asynchronous request to get one

when the request resolves store the token

return it

When you call the function twice in rapid succession,  you fall through the gap between 2.1 and 2.2.

Stop storing the token. Store the promise returned by 2.1 instead.

That way, if a request is in-flight you can reuse it.

```<code>UKOS.getToken = async function () {
  if (UKOS.tokenPromise) {
    const token = await UKOS.tokenPromise;
    const now = new Date().getTime();
    if (now <= token.issued_at + 1000 * (token.expires_in - 15)) {
        // Token still good
        return token.access_token;
    }
    // If we get here, the token has expired
  }
  // If we get here, the token has expired or we didn't have a promise in the first place
  // Create or update token promise
  UKOS.tokenPromise = fetch(/* CGI Script */).then((response) => response.json());
  // Wait for it to resolve
  const token = UKOS.tokenPromise;
  // Assume the new token is good
  return UKOS.token.access_token;
};
</code>```

Body:
Previously I asked this question in a single threaded situation, and was given an answer that worked in that situation here.  But now I'm trying to answer the same question in a multithreaded environment.

I'm using OpenLayers to draw a UK Ordnance Survey map. I have working examples, but they use a less secure method of accessing the UKOS servers by giving a key in the URL, whereas I'd like to use the more secure OAuth2 arrangement instead. To this end, I already have a CGI script querying the servers to get a session token, and returning this as JSON. The problem can be solved in a single-threaded environment by making the map drawing page wait for its return, as follows:

UKOS.getToken = async function () {
  if (
    !UKOS.token ||
    new Date().getTime() >
      UKOS.token.issued_at + 1000 * (UKOS.token.expires_in - 15)
  )
    UKOS.token = await fetch(/* CGI Script */).then((response) =>
      response.json()
    );
  console.log(UKOS.token.access_token);
  return UKOS.token.access_token;
};
// ...
UKOS.getToken()
  .then(token => fetch(UKOS.WMTS + "&request=GetCapabilities&version=2.0.0", { headers: {Authorization: "Bearer " + token} }) )
  .then( /* etc */ )

However, now that I'm using a multi-threaded environment the above no longer works, because after the first call to getToken() launches the fetching of the token, subsequent calls come crashing through before it can be returned, and, depending on exactly how I try to code getToken(), either launch multiple fetches of tokens when one will do (until it expires), or else don't wait for the token to be returned, and fail because it is still null.  This is my current attempted adaptation of getToken() ...

UKOS = {
    token:      null,
    tokStat:    0,
    tokProm:    null
    }
UKOS.getToken = async function() {
    var result;
    console.log( "UKOS.tokStat: " + UKOS.tokStat );
    switch( UKOS.tokStat ) {
        case 1: await UKOS.tokProm;
                await UKOS.token;
                // Deliberate fall through
                console.log( "UKOS.token: " + UKOS.token );
                console.log( "Falling through from 1 to 2 ..." );
        case 2: if( new Date().getTime() < UKOS.token.issued_at + 1000*(UKOS.token.expires_in - 15) ) {
                    result = UKOS.token.access_token;
                    break;
                    }
                // Deliberate fall through
                console.log( "Falling through from 2 to 0 ..." );
        case 0: UKOS.tokStat    = 1;
                UKOS.tokProm    = fetch( location.protocol + '//' + location.host + "/cgi-bin/OSDataOAuth.py" );
                UKOS.token      = await UKOS.tokProm.then( response => response.json() );
                UKOS.tokStat    = 2;
                result = UKOS.token.access_token;
        }
    return result;
    };

Without the two 'await' qualifiers, of course subsequent calls just crash through into 'case 2' and fail because the token is still null, with them, this is the result [irrelevant detail edited out] ...

// Debugging console log message from routine calling getToken()
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=1&FORMAT=image%2Fpng
// Debugging console log message from getToken()
UKOS.tokStat: 0
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=5&TILECOL=1&FORMAT=image%2Fpng
UKOS.tokStat: 1
[Repeated multiple times]
url: undefined
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=1&FORMAT=image%2Fpng
[Repeated multiple times]
url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=6&TILECOL=2&FORMAT=image%2Fpng
UKOS.tokStat: 1

// Token fetched successfully
// (see end, the only map tile fetch that succeeds is almost certainly the first to call getToken())
XHRGET http://local.localhost/cgi-bin/OSDataOAuth.py
[HTTP/1.1 200 OK 1590ms]

url: https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=G…TRIX=EPSG%3A27700%3A0&TILEROW=5&TILECOL=2&FORMAT=image%2Fpng
UKOS.tokStat: 1
[Repeated multiple times]
UKOS.token: null
Falling through from 1 to 2 ...
[Repeated multiple times]
Falling through from 1 to 2 ...
Uncaught (in promise) TypeError: UKOS.token is null
    getToken http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:206
    setImgSrc http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:301
    initImage https://openlayers.org/api/2.13/OpenLayers.debug.js:29733
    renderTile https://openlayers.org/api/2.13/OpenLayers.debug.js:29608
    draw https://openlayers.org/api/2.13/OpenLayers.debug.js:29581
    initGriddedTiles https://openlayers.org/api/2.13/OpenLayers.debug.js:30951
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:30422
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:83261
    moveTo https://openlayers.org/api/2.13/OpenLayers.debug.js:9273
    setCenter https://openlayers.org/api/2.13/OpenLayers.debug.js:9035
    setBaseLayer http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:442
    addLayer https://openlayers.org/api/2.13/OpenLayers.debug.js:8354
    initOSMap http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:457
    onload http://local.localhost/JavaJive/ProgScriptWeb/UKOSOpenLayers2.shtml:1
UKOSOpenLayers2.shtml:206:34
[Repeated multiple times]
// I think this one, the only one to successfully fetch a map tile is probably the first attempt to do so, which correctly waited for the returned token
XHRGET https://api.os.uk/maps/raster/v1/wmts?service=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=Leisure_27700&STYLE=default&TILEMATRIXSET=EPSG:27700&TILEMATRIX=EPSG:27700:0&TILEROW=6&TILECOL=1&FORMAT=image/png
[HTTP/1.1 200 OK 1417ms]
dataUrl: blob:http://local.localhost/2f7fa455-3385-4d10-ab0e-b70999658137

What is interesting about the above is that the two 'await's do appear to be accomplishing something, but not enough, because without them each ...

UKOS.tokStat: 1

... is immediately followed by ...

UKOS.token: null
Falling through from 1 to 2 ...

... yet they're obviously not waiting for the token to be returned, as evidenced by the fact that they all fail before the first call ultimately succeeds.  Can anyone suggest how to make the second and subsequent calls wait for the token requested by the first call?

Body:
In your original code there are two paths through the function.

You have a token already

return it

You don't have a token already

make an asynchronous request to get one

when the request resolves store the token

return it

When you call the function twice in rapid succession,  you fall through the gap between 2.1 and 2.2.

Stop storing the token. Store the promise returned by 2.1 instead.

That way, if a request is in-flight you can reuse it.

UKOS.getToken = async function () {
  if (UKOS.tokenPromise) {
    const token = await UKOS.tokenPromise;
    const now = new Date().getTime();
    if (now <= token.issued_at + 1000 * (token.expires_in - 15)) {
        // Token still good
        return token.access_token;
    }
    // If we get here, the token has expired
  }
  // If we get here, the token has expired or we didn't have a promise in the first place
  // Create or update token promise
  UKOS.tokenPromise = fetch(/* CGI Script */).then((response) => response.json());
  // Wait for it to resolve
  const token = UKOS.tokenPromise;
  // Assume the new token is good
  return UKOS.token.access_token;
};


问:
How to bind to document events with Blazor
I am writing a simple snake game with Blazor, but I can't figure out how to bind to document events. I know that it is possible to bind events on different elements such as div or input. Example: <input onkeypress="@KeyPressInDiv"/>, where the handler is public void KeyPressInDiv(UIKeyboardEventArgs ev) {...}.

I suppose that there should be some equivalent to the JavaScript method document.onkeydown = function (evt) {}. I have found two approaches for working around this problem:

Use JavaScript for binding and invoke Blazor code (taken from https://github.com/aesalazar/AsteroidsWasm):

```<code>document.onkeydown = function (evt) {
    evt = evt || window.event;
    DotNet.invokeMethodAsync('Test.ClientSide', 'JsKeyDown', evt.keyCode);

    //Prevent all but F5 and F12
    if (evt.keyCode !== 116 && evt.keyCode !== 123)
        evt.preventDefault();
};

document.onkeyup = function (evt) {
    evt = evt || window.event;
    DotNet.invokeMethodAsync('Test.ClientSide', 'JsKeyUp', evt.keyCode);

    //Prevent all but F5 and F12
    if (evt.keyCode !== 116 && evt.keyCode !== 123)
        evt.preventDefault();
};
</code>```

... and in C# implement a static class with methods marked by [JSInvokable] and events. This works, but leads to an extreme delay on every key press.

It is possible to add an input tag and bind to its events. This works much faster than the previous approach, but it seems like a hack rather then a solution. Also, we are not able to listen for some actions, such as Up/Down Arrow.

Is there a direct way to bind to document events from Blazor?

Update 1: I created a simple project to better explain what I want to achieve: https://github.com/XelMed/BlazorSnake
There are 3 implementations of Snake:

Pure JS - this has the expected behavior

Using JS with Blazor - invoke a Blazor function from JS code with a JsInterop

Using input tag - bind to events on an input tag to control the snake

答:
I encountered similar situation and use the following approach as a workaround. You add event listener to a div tag, then set focus to that div such that your key presses can be captured.

```<code><div tabindex="0" @ref="container" @onkeydown="onKeyDown" id="container">
//your snake game markup
</div>
@code {
    ElementReference container;
    protected override async Task OnAfterRenderAsync(bool firstRender) {
        await container.FocusAsync();
    }
    private void onKeyPress(KeyboardEventArgs obj) { //your code here. }
}
</code>```

You may need to remove the focus border of the div tag:

```<code>#container:focus-visible {
    outline: none;
}
#container:focus {
    outline: none;
}
</code>```

Body:
I am writing a simple snake game with Blazor, but I can't figure out how to bind to document events. I know that it is possible to bind events on different elements such as div or input. Example: <input onkeypress="@KeyPressInDiv"/>, where the handler is public void KeyPressInDiv(UIKeyboardEventArgs ev) {...}.

I suppose that there should be some equivalent to the JavaScript method document.onkeydown = function (evt) {}. I have found two approaches for working around this problem:

Use JavaScript for binding and invoke Blazor code (taken from https://github.com/aesalazar/AsteroidsWasm):

document.onkeydown = function (evt) {
    evt = evt || window.event;
    DotNet.invokeMethodAsync('Test.ClientSide', 'JsKeyDown', evt.keyCode);

    //Prevent all but F5 and F12
    if (evt.keyCode !== 116 && evt.keyCode !== 123)
        evt.preventDefault();
};

document.onkeyup = function (evt) {
    evt = evt || window.event;
    DotNet.invokeMethodAsync('Test.ClientSide', 'JsKeyUp', evt.keyCode);

    //Prevent all but F5 and F12
    if (evt.keyCode !== 116 && evt.keyCode !== 123)
        evt.preventDefault();
};

... and in C# implement a static class with methods marked by [JSInvokable] and events. This works, but leads to an extreme delay on every key press.

It is possible to add an input tag and bind to its events. This works much faster than the previous approach, but it seems like a hack rather then a solution. Also, we are not able to listen for some actions, such as Up/Down Arrow.

Is there a direct way to bind to document events from Blazor?

Update 1: I created a simple project to better explain what I want to achieve: https://github.com/XelMed/BlazorSnake
There are 3 implementations of Snake:

Pure JS - this has the expected behavior

Using JS with Blazor - invoke a Blazor function from JS code with a JsInterop

Using input tag - bind to events on an input tag to control the snake

Body:
I encountered similar situation and use the following approach as a workaround. You add event listener to a div tag, then set focus to that div such that your key presses can be captured.

<div tabindex="0" @ref="container" @onkeydown="onKeyDown" id="container">
//your snake game markup
</div>
@code {
    ElementReference container;
    protected override async Task OnAfterRenderAsync(bool firstRender) {
        await container.FocusAsync();
    }
    private void onKeyPress(KeyboardEventArgs obj) { //your code here. }
}

You may need to remove the focus border of the div tag:

#container:focus-visible {
    outline: none;
}
#container:focus {
    outline: none;
}


问:
How to pass the url dynamically in the data-sly-resource?
I have 404.html page which has below:

```<code><div data-sly-resource="/content/emc/en-us/errorhandler/404" data-sly-unwrap></div>
</code>```

Also have a java class as below:

```<code>package apps.sling.servlet.errorhandler;

import com.adobe.cq.sightly.WCMUse;

public class ResponseStatus extends WCMUse {

    @Override
    public void activate() throws Exception {
        getResponse().setStatus(404);
    }
}
</code>```

On status 404, it takes to 404 page (/content/emc/en-us/errorhandler/404). My requirement here is when the user is on en-us url, it should take to /content/emc/en-us/errorhandler/404. And if the user is on zh-cn url, it should take to /content/emc/zh-cn/errorhandler/404. I need to pass the urls dynamically in the data-sly-resource by reading the locale on the url. Can anyone help me with the script?

答:
Let me share the way, it may help you.

Write a helper class:

```<code>import com.adobe.cq.sightly.WCMUsePojo;
import com.day.cq.wcm.api.Page;

public class PageNavigationHelper extends WCMUsePojo {
    private String locale;
    @Override
    public void activate() throws Exception {
        this.locale = get("locale", String.class);
    }
    public String getNotFoundUrl(){
        Page currentPage = getCurrentPage();
        String currentLocale = currentPage.getLanguage(true).getLanguage();

        // you can built more language specific url here.
        if(currentLocale.equalIgnoreCase("en")){
            return "/content/emc/en-us/errorhandler/404";
        }else{
            return "/content/emc/zh-cn/errorhandler/404";
        }
    }
}
</code>```

Then into your HTML:

```<code><div data-sly-use.langHelper="${'com.service.helper.PageNavigationHelper'}" data-sly-unwrap>
    <div data-sly-resource="${langHelper.getNotFoundUrl}" data-sly-unwrap></div>
</div>
</code>```

Body:
I have 404.html page which has below:

Also have a java class as below:

package apps.sling.servlet.errorhandler;

import com.adobe.cq.sightly.WCMUse;

public class ResponseStatus extends WCMUse {

    @Override
    public void activate() throws Exception {
        getResponse().setStatus(404);
    }
}

On status 404, it takes to 404 page (/content/emc/en-us/errorhandler/404). My requirement here is when the user is on en-us url, it should take to /content/emc/en-us/errorhandler/404. And if the user is on zh-cn url, it should take to /content/emc/zh-cn/errorhandler/404. I need to pass the urls dynamically in the data-sly-resource by reading the locale on the url. Can anyone help me with the script?

Body:
Let me share the way, it may help you.

Write a helper class:

import com.adobe.cq.sightly.WCMUsePojo;
import com.day.cq.wcm.api.Page;

public class PageNavigationHelper extends WCMUsePojo {
    private String locale;
    @Override
    public void activate() throws Exception {
        this.locale = get("locale", String.class);
    }
    public String getNotFoundUrl(){
        Page currentPage = getCurrentPage();
        String currentLocale = currentPage.getLanguage(true).getLanguage();

        // you can built more language specific url here.
        if(currentLocale.equalIgnoreCase("en")){
            return "/content/emc/en-us/errorhandler/404";
        }else{
            return "/content/emc/zh-cn/errorhandler/404";
        }
    }
}

Then into your HTML:

<div data-sly-use.langHelper="${'com.service.helper.PageNavigationHelper'}" data-sly-unwrap>
    <div data-sly-resource="${langHelper.getNotFoundUrl}" data-sly-unwrap></div>
</div>


问:
Inner rounded shadows inside div
I have a div which looks something like this:

.box{
 box-sizing: border-box;
 border: solid 0.01rem #2e2e2e;
 border-radius: 3px;
 width:100px;
 height:100px;
 background:red;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"/></code>```

And I'm trying to achieve this effect. How can I make this box look with such shadows from the inside of the div?

答:
linear gradient

blur filter

absolute positioning

pseudo-elements

flexbox

.box {
  box-sizing: border-box;
  border-radius: 10%;
  width: 100px;
  height: 100px;
  background: linear-gradient(270deg, red, #c10606);
  position: relative;
}

.box:before {
  position: absolute;
  content: '';
  top: 10%;
  right: 10%;
  bottom: 10%;
  left: 10%;
  background: linear-gradient(90deg, red, #c10606);
  border-radius: 12%;
  filter: blur(1px);  /* optional for a softer effect */
}

/* optional layout and styling for box contents */
.box {
  display: flex;
  align-items: center;
  text-align: center;
  font-family: arial;
  color: #ddd;
  font-weight: bold;
}

.box * {
  position: relative;  /* puts interior content over the pseudo-element */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <span>Interior content</span>
</div></code>```

Title: Inner rounded shadows inside div

Body:
I have a div which looks something like this:

.box{
 box-sizing: border-box;
 border: solid 0.01rem #2e2e2e;
 border-radius: 3px;
 width:100px;
 height:100px;
 background:red;
 }

And I'm trying to achieve this effect. How can I make this box look with such shadows from the inside of the div?

Body:
linear gradient

blur filter

absolute positioning

pseudo-elements

flexbox

.box {
  box-sizing: border-box;
  border-radius: 10%;
  width: 100px;
  height: 100px;
  background: linear-gradient(270deg, red, #c10606);
  position: relative;
}

.box:before {
  position: absolute;
  content: '';
  top: 10%;
  right: 10%;
  bottom: 10%;
  left: 10%;
  background: linear-gradient(90deg, red, #c10606);
  border-radius: 12%;
  filter: blur(1px);  /* optional for a softer effect */
}

/* optional layout and styling for box contents */
.box {
  display: flex;
  align-items: center;
  text-align: center;
  font-family: arial;
  color: #ddd;
  font-weight: bold;
}

.box * {
  position: relative;  /* puts interior content over the pseudo-element */
}

<div class="box">
  <span>Interior content</span>
</div>


问:
MEF and WCF
I'd like to use MEF for instantiating the dependencies in an application that has several WCF services hosted in IIS. The different services depend on shared components and I'd like MEF to manage the instantiation and injection of these.

Where should I perform composition? Initially I thought of having a CompositionContainer in an IInstanceProvider but then I realized that that container would only serve a single endpoint and the instances it manages will not be shared with other endpoints. Likewise with having the CompositionContainer in a ServiceHost - That would not be shared across different services.

Am I correct in this analysis? Is the only solution to have the CompositionContainer as a singleton at the application level?

A second question is - When a Service is instantiated by WCF (like when a new user session is started), how can I supply its dependencies? Do I make the CompositionContainer recompose? Wouldn't that affect other already running Service instances?

Might anyone share a code sample for this concept? Many thanks!

答:
I've encountered the requirement to make WCF service composeable many times, and the approach you identified where you use a custom IInstanceProvider is the way to solve it. Aswell as writing a custom instance provider, you also need a service behaviour, and a custom service host.

In terms of code-samples, I've documented my approach on my blog:
http://www.timjroberts.com/2011/08/wcf-services-with-mef/

Hope this helps.

ContentLicense: CC BY-SA 2.5

Title: MEF and WCF

ContentLicense: CC BY-SA 3.0


问:
How to pass Headers in rest assured test in java
I am new to rest assured,I am trying to do a very basic test of checking the response body and status.I am passing the headers as required in this API call
but when I run the test I am getting 401 unauthorized message instead of showing me the result in response body.when I am running the same API using Postman then its working fine

Below is the code that I have tried but its not working
I am including the sample url and headers value as cant share real ones

```<code>package test;

import org.testng.Assert;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class SimpleGetTest {

    @Test
    public void GetWeatherDetails() {

        RestAssured.baseURI = "https://test.com";

        RequestSpecification httpRequest = RestAssured.given();

        Response response = httpRequest.given().header("Content-Type", "application/json").given()
                .header("x-api-key", "123456").
                request(Method.GET, "/hello");

        System.out.println("Response sent =>  " + response);

        String responseBody = response.getBody().asString();
        System.out.println("Response Body is =>  " + responseBody);

        int statusCode = response.getStatusCode();
        System.out.println("Actual Status Code is : " + statusCode);

        Assert.assertEquals(statusCode, 200,
                "BUG : Status code is coming as different");
        System.out.println("Expected : Status code coming correct");

    }
}
</code>```

below is the console message that I am getting,in which its showing 401

Response sent =>  io.restassured.internal.RestAssuredResponseImpl@18cebaa5
Response Body is =>  "message":"UNAUTHORIZED_ACCESS","code":"401","data":null}
Actual Status Code is : 200
Expected : Status code coming correct
PASSED: GetWeatherDetails

答:
With io.rest-assured:rest-assured:4.2.1 dependency below code can be acheived.

```<code>RequestSpecification httpRequest = RestAssured.given();
Response response = httpRequest
                   .contentType("application/json")
                   .header("x-api-key", "123456")
                   .request(Method.GET, "/hello");
</code>```

(OR)
Incase if you need to pass other custom headers below code will help

EG:

```<code>Header languageHeader = new Header("Accept-Language", en);
Header keytHeader = new Header("x-api-key", "123456");
Header secretHeader = new Header("x-api-secret", "123456");
Headers headers = new Headers(languageHeader, keytHeader, secretHeader);

Response response = RestAssured.given()
                   .contentType("application/json")
                   .headers(headers)
                   .request(Method.GET, "/hello");
</code>```

Body:
I am new to rest assured,I am trying to do a very basic test of checking the response body and status.I am passing the headers as required in this API call
but when I run the test I am getting 401 unauthorized message instead of showing me the result in response body.when I am running the same API using Postman then its working fine

Below is the code that I have tried but its not working
I am including the sample url and headers value as cant share real ones

package test;

import org.testng.Assert;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class SimpleGetTest {

    @Test
    public void GetWeatherDetails() {

        RestAssured.baseURI = "https://test.com";

        RequestSpecification httpRequest = RestAssured.given();

        Response response = httpRequest.given().header("Content-Type", "application/json").given()
                .header("x-api-key", "123456").
                request(Method.GET, "/hello");

        System.out.println("Response sent =>  " + response);

        String responseBody = response.getBody().asString();
        System.out.println("Response Body is =>  " + responseBody);

        int statusCode = response.getStatusCode();
        System.out.println("Actual Status Code is : " + statusCode);

        Assert.assertEquals(statusCode, 200,
                "BUG : Status code is coming as different");
        System.out.println("Expected : Status code coming correct");

    }
}

below is the console message that I am getting,in which its showing 401

Response sent =>  io.restassured.internal.RestAssuredResponseImpl@18cebaa5
Response Body is =>  "message":"UNAUTHORIZED_ACCESS","code":"401","data":null}
Actual Status Code is : 200
Expected : Status code coming correct
PASSED: GetWeatherDetails

Body:
With io.rest-assured:rest-assured:4.2.1 dependency below code can be acheived.

RequestSpecification httpRequest = RestAssured.given();
Response response = httpRequest
                   .contentType("application/json")
                   .header("x-api-key", "123456")
                   .request(Method.GET, "/hello");

(OR)
Incase if you need to pass other custom headers below code will help

EG:

Header languageHeader = new Header("Accept-Language", en);
Header keytHeader = new Header("x-api-key", "123456");
Header secretHeader = new Header("x-api-secret", "123456");
Headers headers = new Headers(languageHeader, keytHeader, secretHeader);

Response response = RestAssured.given()
                   .contentType("application/json")
                   .headers(headers)
                   .request(Method.GET, "/hello");


问:
Fail test in VSC using Robot Framework
Learning RobotFramework using VSC.

Got downloaded chromedriver_win32.zip for Chrome 98 from here::
https://chromedriver.storage.googleapis.com/index.html?path=98.0.4758.80/

When I run my 1st test in VSC I get fail and the message shows:
This version of ChromeDriver only supports Chrome version 93
Current browser version is 98.0.4758.82 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe

Why it says Chrome version 93 when it's 98?

Thanks.

答:
You have to replace that chromedriver.exe by the one you have downloaded and extracted.

You need to know where that executable is (being found from the PATH environment variable).

Title: Fail test in VSC using Robot Framework


问:
When should I use semicolons in SQL Server?
While checking some code on the web and scripts generated by SQL Server Management Studio I have noticed that some statements are ended with a semicolon.

So when should I use it?

答:
From a SQLServerCentral.Com article by Ken Powers:

The Semicolon

The semicolon character is a statement terminator. It is a part of the ANSI SQL-92 standard, but was never used within Transact-SQL. Indeed, it was possible to code T-SQL for years without ever encountering a semicolon.

Usage

There are two situations in which you must use the semicolon. The first situation is where you use a Common Table Expression (CTE), and the CTE is not the first statement in the batch. The second is where you issue a Service Broker statement and the Service Broker statement is not the first statement in the batch.

OwnerDisplayName: apinto

LastEditorDisplayName: Rich B

OwnerDisplayName: TheTXI


问:
NGINX Ingress - Redis Module add on
Hi there I'm having some trouble adding in a 3rd party module into the Kubernetes NGINX-Ingress custom image, and haven't been successful in figuring out how to do it.

I have seen one other has had this problem, and they seemed to of compiled it from scratch but dont seem to provide details as to how they added the file.

I'm installing the ingress controller via Helm, with a simple values.yaml file to make the alterations shown below:

values.yaml

controller:
  image:
    registry: [registry]
    repository: [repo]
    image: [image]
    tag: 1.0.2
    pullPolicy: Always
  config:
    entries:
      main-snippets: "load_module /etc/nginx/modules/ngx_http_redis2_module.so"
prometheus:
  create: true
```
<p>Which was accepted when doing a helm install, in pulling a custom image into the pod/container for the ingress controller.  I have been able to dynamically compile the module into a <code>.so</code> file that I'm keeping locally at this time to add into the custom image. But the issue that I'm having it seems that when building a Docker file for this custom image I seem to be unable to add the module file.</p>
<h2>Dockerfile</h2>
<pre class="lang-yaml prettyprint-override"><code>FROM nginx/nginx-ingress:2.1.0

#Adds nginx redis2 module
USER root

COPY ngx_http_redis2_module.so /etc/nginx/modules/ngx_http_redis2_module.so

USER www-data
</code>```

The dockerfile is what I'm using above to attempt to add the file into the proper place, which should be under the /etc/nginx/modules folder like the others. But after running the pod, and bashing into it I'm only seeing the following:

```<code>-rwxr-xr-x    1 www-data www-data    164256 Sep 26 17:40 ngx_http_auth_digest_module.so
-rwxr-xr-x    1 www-data www-data   5388256 Sep 26 17:40 ngx_http_brotli_filter_module.so
-rwxr-xr-x    1 www-data www-data     78152 Sep 26 17:40 ngx_http_brotli_static_module.so
-rwxr-xr-x    1 www-data www-data    100704 Sep 26 17:40 ngx_http_geoip2_module.so
-rwxr-xr-x    1 www-data www-data    113056 Sep 26 17:40 ngx_http_influxdb_module.so
-rwxr-xr-x    1 www-data www-data    267080 Sep 26 17:40 ngx_http_modsecurity_module.so
-rwxr-xr-x    1 www-data www-data   2468184 Sep 26 17:40 ngx_http_opentracing_module.so
-rwxr-xr-x    1 www-data www-data     74856 Sep 26 17:40 ngx_stream_geoip2_module.so
</code>```

It seems that I'm making the image incorrectly or something else entirely and any help would be appreciated.

答:
So I found that I was doing a few things wrong partially, but thanks to @jordanm for helping me out here.

I was able to run it using the docker run -it --entrypoint=/bin/sh command pointing to my image. I saw that my commands, of adding the file on there was correct but I was doing a few things incorrectly. First off I was using the wrong image, should of been using the controller, so here is the proper dockerfile:

Dockerfile

FROM k8s.gcr.io/ingress-nginx/controller:v1.1.1

#Adds nginx redis2 module
USER root

COPY --chmod=744 ngx_http_redis2_module.so /etc/nginx/modules/ngx_http_redis2_module.so

USER www-data
```
<p>Also I had to tweak my values.yml file for helm to be a bit different also:</p>
<h2>values.yml</h2>
<pre class="lang-yaml prettyprint-override"><code>controller:
  image:
    registry: [registry]
    image: [image]
    tag: "1.0.5"
    digest: "sha256:[sha value]"
    pullPolicy: Always
  config:
    main-snippets: "load_module /etc/nginx/modules/ngx_http_redis2_module.so;"
prometheus:
  create: true
</code>```

I had to add in the digest value which didnt seem to be stated in the helm instructions. In order to get the SHA256 value use this command docker inspect --format='{{index .RepoDigests 0}}' [IMAGE]:[TAG] and use that output in the digest value.

What was happening which I didnt take notice, was the container was failing so fast and a different one was being spun up before I even noticed it. So what I did was I went onto my test control plane / node and uninstalled NGINX first, then I did a sudo docker system prune -af which removed unused images. This way I was being guaranteed my image was being pulled through and deployed, and not reverting back to a different image.

I dont know why but the description of the pod would state that it was deploying my image, but I believe under the hood it would use another image.

Title: NGINX Ingress - Redis Module add on

Body:
Hi there I'm having some trouble adding in a 3rd party module into the Kubernetes NGINX-Ingress custom image, and haven't been successful in figuring out how to do it.

I have seen one other has had this problem, and they seemed to of compiled it from scratch but dont seem to provide details as to how they added the file.

I'm installing the ingress controller via Helm, with a simple values.yaml file to make the alterations shown below:

values.yaml

controller:
  image:
    registry: [registry]
    repository: [repo]
    image: [image]
    tag: 1.0.2
    pullPolicy: Always
  config:
    entries:
      main-snippets: "load_module /etc/nginx/modules/ngx_http_redis2_module.so"
prometheus:
  create: true

Which was accepted when doing a helm install, in pulling a custom image into the pod/container for the ingress controller.  I have been able to dynamically compile the module into a .so file that I'm keeping locally at this time to add into the custom image. But the issue that I'm having it seems that when building a Docker file for this custom image I seem to be unable to add the module file.

Dockerfile

FROM nginx/nginx-ingress:2.1.0

#Adds nginx redis2 module
USER root

COPY ngx_http_redis2_module.so /etc/nginx/modules/ngx_http_redis2_module.so

USER www-data

The dockerfile is what I'm using above to attempt to add the file into the proper place, which should be under the /etc/nginx/modules folder like the others. But after running the pod, and bashing into it I'm only seeing the following:

-rwxr-xr-x    1 www-data www-data    164256 Sep 26 17:40 ngx_http_auth_digest_module.so
-rwxr-xr-x    1 www-data www-data   5388256 Sep 26 17:40 ngx_http_brotli_filter_module.so
-rwxr-xr-x    1 www-data www-data     78152 Sep 26 17:40 ngx_http_brotli_static_module.so
-rwxr-xr-x    1 www-data www-data    100704 Sep 26 17:40 ngx_http_geoip2_module.so
-rwxr-xr-x    1 www-data www-data    113056 Sep 26 17:40 ngx_http_influxdb_module.so
-rwxr-xr-x    1 www-data www-data    267080 Sep 26 17:40 ngx_http_modsecurity_module.so
-rwxr-xr-x    1 www-data www-data   2468184 Sep 26 17:40 ngx_http_opentracing_module.so
-rwxr-xr-x    1 www-data www-data     74856 Sep 26 17:40 ngx_stream_geoip2_module.so

It seems that I'm making the image incorrectly or something else entirely and any help would be appreciated.

Body:
So I found that I was doing a few things wrong partially, but thanks to @jordanm for helping me out here.

I was able to run it using the docker run -it --entrypoint=/bin/sh command pointing to my image. I saw that my commands, of adding the file on there was correct but I was doing a few things incorrectly. First off I was using the wrong image, should of been using the controller, so here is the proper dockerfile:

Dockerfile

FROM k8s.gcr.io/ingress-nginx/controller:v1.1.1

#Adds nginx redis2 module
USER root

COPY --chmod=744 ngx_http_redis2_module.so /etc/nginx/modules/ngx_http_redis2_module.so

USER www-data

Also I had to tweak my values.yml file for helm to be a bit different also:

values.yml

controller:
  image:
    registry: [registry]
    image: [image]
    tag: "1.0.5"
    digest: "sha256:[sha value]"
    pullPolicy: Always
  config:
    main-snippets: "load_module /etc/nginx/modules/ngx_http_redis2_module.so;"
prometheus:
  create: true

I had to add in the digest value which didnt seem to be stated in the helm instructions. In order to get the SHA256 value use this command docker inspect --format='{{index .RepoDigests 0}}' [IMAGE]:[TAG] and use that output in the digest value.

What was happening which I didnt take notice, was the container was failing so fast and a different one was being spun up before I even noticed it. So what I did was I went onto my test control plane / node and uninstalled NGINX first, then I did a sudo docker system prune -af which removed unused images. This way I was being guaranteed my image was being pulled through and deployed, and not reverting back to a different image.

I dont know why but the description of the pod would state that it was deploying my image, but I believe under the hood it would use another image.


问:
Unrecognized field during deserialization despite @SerializedName annotation
I am fetching some data via a REST service, but I am getting this error when deserializing the response :

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ResultSet Output" (class com.HolderCollectionWrapper), not marked as ignorable (one known property: "holders"]) at [Source: java.io.ByteArrayInputStream@74efa7bd; line: 1, column: 22] (through reference chain: com.HolderCollectionWrapper["ResultSet Output"])

This is my code :

```<code>response = restTemplate.exchange(requestUrl, HttpMethod.GET, request, HolderCollectionWrapper.class);

public class HolderCollectionWrapper {

    @SerializedName("ResultSet Output")
    private List<Holder> holders;

    public List<Holder> getHolders() {
        return holders;
    }

    public void setHolders(List<Holder> holders) {
        this.holders = holders;
    }
}
</code>```

This is the JSON I am getting :

```<code>{
    "ResultSet Output": [
        {...}, {...}, {...}
    ]
}
</code>```

Despite the @SerializedName("ResultSet Output"), it's not working, why ?

答:
@SerializedName is a gson annotation and you are using jackson library for serialization.

The jackson annotation for field name is @JsonProperty

Try:

```<code>@JsonProperty("ResultSet Output")
private List<Holder> holders;

</code>```

Body:
I am fetching some data via a REST service, but I am getting this error when deserializing the response :

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ResultSet Output" (class com.HolderCollectionWrapper), not marked as ignorable (one known property: "holders"]) at [Source: java.io.ByteArrayInputStream@74efa7bd; line: 1, column: 22] (through reference chain: com.HolderCollectionWrapper["ResultSet Output"])

This is my code :

response = restTemplate.exchange(requestUrl, HttpMethod.GET, request, HolderCollectionWrapper.class);

public class HolderCollectionWrapper {

    @SerializedName("ResultSet Output")
    private List<Holder> holders;

    public List<Holder> getHolders() {
        return holders;
    }

    public void setHolders(List<Holder> holders) {
        this.holders = holders;
    }
}

This is the JSON I am getting :

{
    "ResultSet Output": [
        {...}, {...}, {...}
    ]
}

Despite the @SerializedName("ResultSet Output"), it's not working, why ?

Body:
@SerializedName is a gson annotation and you are using jackson library for serialization.

The jackson annotation for field name is @JsonProperty

Try:

@JsonProperty("ResultSet Output")
private List<Holder> holders;


问:
IntelliJ IDEA: How do I verify and/or change my BitBucket git credentials?
As per this blog post, BitBucket is disabling account password usage for HTTPS access in March.

I've created one of these "app password" credentials - but how do I make IDEA to start using it?

I'm pretty sure I originally set my IDEA up to access via HTTPS and just put my BitBucket account username/password when prompted.

In my IDEA Git settings, Use credential helper is not enabled (so Windows credential manager is not relevant, pretty sure IDEA is saving into its Keepass file in the settings directory).

In other scenarios with changed account details, I've generally just tried to access the repo, waited for IDEA to fail and prompt for details, then entered the new credentials.

How do I tell IDEA to use the new password, given that the old password still works?

Things I don't want to do:

I don't want to reset all my credentials, just this one BitBucket password.

I don't want to change over to using the Windows credential manager.

I don't want to change over to SSH.

答:
Just in case someone still needs this info, here's how I did it. I'm not an expert - far from it, but I got it working...

How to check credentials in IntelliJ

Menu Git > Manage Remotes...
Git_ManageRemotes

Check remote URL in "Define Remote" screen and press OK.

When you press OK it will re-authenticate, in my case this gave me a window where I had to enter my app password.

If you don't get the credential popup (that means your current credentials are still valid), maybe remove your current remote URL and re-add it, to force a username/password popup.
Git_Remotes

How to configure your App Password in BitBucket

Follow the instructions on the blog post you linked (copied below for archiving)

To create an app password:

From your profile and settings avatar, select Personal settings.

Select App passwords under Access management.

Select Create app password.

Give the app password a name related to the application that will use the password.

Select the specific access and permissions you want to assign to this application password.

Copy the generated password and either record or paste it into the application you want to give access. The password is only displayed this one time.

Which permissions does your App Password need?
In my case, all I needed was pull/push of the code, so the below permissions were enough (Pull Requests-write, the rest is automatically enabled)
AppPassword_Permissions


问:
Moving a rectangle up down left and right
I wanted to make a rectangle move in 4 directions with a click of a button on JavaScript. Only the Right and Down works and the other two does not work. I tried finding it on internet and so far had not have any luck.

var currentXpos = 0;

function moveRectRight() {
  var rect = document.getElementById('rectangle');
  currentXpos += 100; // move by 100 px to the right
  rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}

function moveRectLeft() {
  var rect = document.getElementById('rectangle');
  currentXpos += 100; // move by 100 px to the right
  rect.style.marginRight = currentXpos + 'px'; // re-draw rectangle
}

function moveRectUp() {
  var rect = document.getElementById('rectangle');
  currentXpos += 100; // move by 100 px to the right
  rect.style.marginBottom = currentXpos + 'px'; // re-draw rectangle
}

function moveRectDown() {
  var rect = document.getElementById('rectangle');
  currentXpos += 100; // move by 100 px to the right
  rect.style.marginTop = currentXpos + 'px'; // re-draw rectangle
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#rectangle {
  background-color: red;
  width: 200px;
  height: 100px;
  margin-left: 0px;
}</code>```

<input type="button" value="Right" onclick="moveRectRight()" />
<input type="button" value="Left" onclick="moveRectLeft()" />
<input type="button" value="Up" onclick="moveRectUp()" />
<input type="button" value="Down" onclick="moveRectDown()" />```

答:
Your problem lies on this code

```<code>
function moveRectLeft() {
 var rect = document.getElementById('rectangle');
 currentXpos += 100; // move by 100 px to the right
 rect.style.marginRight = currentXpos + 'px'; // re-draw rectangle
}

function moveRectUp() {
 var rect = document.getElementById('rectangle');
 currentXpos += 100; // move by 100 px to the right
 rect.style.marginBottom = currentXpos + 'px'; // re-draw rectangle
}
</code>```

when you move left you tried to add the margin right and when you move up you add margin bottom. This is a wrong concept, you shouldn't imagine it like the box is being pushed from 4 side like this image

When you code in HTML & CSS, try to imagine that in coordinate, the 0,0 (x and y) is on your upper left corner of browser, and to move them you can only move them away or closer to the 0,0, like below

I suggest you to learn/debug using the developer tools you can see where it goes wrong,

So the answer is just changing the code to marginLeft and marginTop

That aside, I made my own version maybe you want to check it out

  <input type="button" value="Right" onclick="moveRect(this)" />
  <input type="button" value="Left" onclick="moveRect(this)" />
  <input type="button" value="Up" onclick="moveRect(this)" />
  <input type="button" value="Down" onclick="moveRect(this)" />

```

Body:
I wanted to make a rectangle move in 4 directions with a click of a button on JavaScript. Only the Right and Down works and the other two does not work. I tried finding it on internet and so far had not have any luck.

var currentXpos = 0;

function moveRectRight() {
  var rect = document.getElementById('rectangle');
  currentXpos += 100; // move by 100 px to the right
  rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}

function moveRectLeft() {
  var rect = document.getElementById('rectangle');
  currentXpos += 100; // move by 100 px to the right
  rect.style.marginRight = currentXpos + 'px'; // re-draw rectangle
}

function moveRectUp() {
  var rect = document.getElementById('rectangle');
  currentXpos += 100; // move by 100 px to the right
  rect.style.marginBottom = currentXpos + 'px'; // re-draw rectangle
}

function moveRectDown() {
  var rect = document.getElementById('rectangle');
  currentXpos += 100; // move by 100 px to the right
  rect.style.marginTop = currentXpos + 'px'; // re-draw rectangle
}

#rectangle {
  background-color: red;
  width: 200px;
  height: 100px;
  margin-left: 0px;
}

<input type="button" value="Right" onclick="moveRectRight()" />
<input type="button" value="Left" onclick="moveRectLeft()" />
<input type="button" value="Up" onclick="moveRectUp()" />
<input type="button" value="Down" onclick="moveRectDown()" />

Body:
Your problem lies on this code

function moveRectLeft() {
 var rect = document.getElementById('rectangle');
 currentXpos += 100; // move by 100 px to the right
 rect.style.marginRight = currentXpos + 'px'; // re-draw rectangle
}

function moveRectUp() {
 var rect = document.getElementById('rectangle');
 currentXpos += 100; // move by 100 px to the right
 rect.style.marginBottom = currentXpos + 'px'; // re-draw rectangle
}

when you move left you tried to add the margin right and when you move up you add margin bottom. This is a wrong concept, you shouldn't imagine it like the box is being pushed from 4 side like this image

When you code in HTML & CSS, try to imagine that in coordinate, the 0,0 (x and y) is on your upper left corner of browser, and to move them you can only move them away or closer to the 0,0, like below

I suggest you to learn/debug using the developer tools you can see where it goes wrong,

So the answer is just changing the code to marginLeft and marginTop

That aside, I made my own version maybe you want to check it out

<html>

<head>
  <style>
    #rectangle {
      background-color: red;
      width: 200px;
      height: 100px;
      position: fixed;
    }
  </style>
</head>

<body>
  <div id='rectangle' style="top:100px;left:100px;"></div>
  <input type="button" value="Right" onclick="moveRect(this)" />
  <input type="button" value="Left" onclick="moveRect(this)" />
  <input type="button" value="Up" onclick="moveRect(this)" />
  <input type="button" value="Down" onclick="moveRect(this)" />
  <script>
    const distance = 10;
    const directionMap = {
      'Up': {
        'prop': 'top',
        'value': -1
      },
      'Down': {
        'prop': 'top',
        'value': 1
      },
      'Left': {
        'prop': 'left',
        'value': -1
      },
      'Right': {
        'prop': 'left',
        'value': 1
      },
    }

    const parsePosition = (prop) => parseFloat(rectangle.style[prop]) || 0;

    const moveRect = (element) => {
      let {
        prop,
        value
      } = directionMap[element.value];
      rectangle.style[prop] = (parsePosition(prop) + (value * distance)) + "px";
    }
  </script>
</body>

</html>


问:
Deploying react apps to custom domain name (Ubuntu)
My react app is installed on a ubuntu server. I want to add a custom domain to it. When I pointed the domain to the server. It points to xx.xx.xx.xx but the react app is installed on xx.xx.xx.xx:3000

How can I install the react app on xx:xx:xx:xx:80 ?

答:
React App doesn't run in port 80. So we need to redirect requests hitting port 80 to port 3000.

For this, You need Nginx server which helps you with this.

Follow these Steps and Your react app will work on Port 80.

Link https://www.digitalocean.com/community/tutorials/how-to-deploy-a-react-application-with-nginx-on-ubuntu-20-04


问:
How to check Google Mobile Services enable in device or not?
I have to check if google services are active on the device. How can I check it? Looking just play services is enough? </p>

<p>I need this check for Huawei services. </p>

答:
The latest solution for 2022 is GoogleApiAvailabilityLight from package com.google.android.gms.common which is contained in dependency

com.google.android.gms:play-services-basement:18.0.0@aar

```<code>public static boolean isGooglePlayServicesAvailable(final Context context) {
  return GoogleApiAvailabilityLight.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS;
</code>```

}

Body:
I have to check if google services are active on the device. How can I check it? Looking just play services is enough?

I need this check for Huawei services.

Body:
The latest solution for 2022 is GoogleApiAvailabilityLight from package com.google.android.gms.common which is contained in dependency

com.google.android.gms:play-services-basement:18.0.0@aar

public static boolean isGooglePlayServicesAvailable(final Context context) {
  return GoogleApiAvailabilityLight.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS;

}


问:
How use Observable.ToAsync with IEnumerable
I have run into some problem with Rx. I need that after processing each item in a new thread send result to main thread. I did it with other way. How can i solve this task with Rx? Here is code:</p>

```<code> Observable.ToAsync<string, IEnumerable<UserState>>(Run)(path)
 .ObserveOnDispatcher<IEnumerable<UserState>>()
 .Subscribe(
(o) =>
{   // need to run in Main Thread
    foreach (var item in o)
    {
     WriteLog(item.StatusCode, item.Url);
    }
},
(ex) =>{        },
() =>{      } );

   // need to run in New Thread
   private IEnumerable<UserState> Run(string sitemap)
   {
 ....
 foreach (var url in urls)
 {
    var result = new UserState
    {
        Url = url.Value,
        TotalItems = urls.Count
    };
    ....
    yield return result;
 }
   }
</code>```

答:
You want to generate the IEnumerable on some other background thread and then Process each users object in this enumerable on Main UI thread, if this understanding is correct then you can do something like this:</p>

```<code>var users = Run(path); //NOTE: This doesn't execute your run method yet, Run will only execute when you start enumerating the users values
users.ToObservable(System.Concurrency.Scheduler.ThreadPool) //The enumerator will be scheduled on separate thread
.ObserveOn(frm) //Observe on UI thread of win form
.Subscribe(s => {}) //This will run in UI thread for each user object
</code>```

Body:
I have run into some problem with Rx. I need that after processing each item in a new thread send result to main thread. I did it with other way. How can i solve this task with Rx? Here is code:

 Observable.ToAsync<string, IEnumerable<UserState>>(Run)(path)
 .ObserveOnDispatcher<IEnumerable<UserState>>()
 .Subscribe(
(o) =>
{   // need to run in Main Thread
    foreach (var item in o)
    {
     WriteLog(item.StatusCode, item.Url);
    }
},
(ex) =>{        },
() =>{      } );

   // need to run in New Thread
   private IEnumerable<UserState> Run(string sitemap)
   {
 ....
 foreach (var url in urls)
 {
    var result = new UserState
    {
        Url = url.Value,
        TotalItems = urls.Count
    };
    ....
    yield return result;
 }
   }

Body:
You want to generate the IEnumerable on some other background thread and then Process each users object in this enumerable on Main UI thread, if this understanding is correct then you can do something like this:

var users = Run(path); //NOTE: This doesn't execute your run method yet, Run will only execute when you start enumerating the users values
users.ToObservable(System.Concurrency.Scheduler.ThreadPool) //The enumerator will be scheduled on separate thread
.ObserveOn(frm) //Observe on UI thread of win form
.Subscribe(s => {}) //This will run in UI thread for each user object


问:
Why my code is not showing the answer when i click button "Show Answer"
EDIT: Add a new 'Show answer' button to display the correct answer to the question. The answer is not visible when the question is retrieved but is only displayed when the 'Show answer' button is pressed. Make only one fetch request / question and you can display the answer using conditional rendering, for example. HELP NEEDED

const Trivia = () => {

```<code> const [question, setQuestion] = React.useState();
 const [showAnswer, setShowAnswer] = React.useState(false);

 const fetchQuestion = () => {
     fetch("https://opentdb.com/api.php?amount=1")
     .then((response) => response.json())
     .then((data) => {
      setQuestion(data.results[0].question);

     });
   };

    const answerToggler = () => setShowAnswer(prevAns => !prevAns)
     React.useEffect(() => {
         fetchQuestion();
     }, []);

 return(

 <div>
 <p> {question}</p>
 <button onClick={fetchQuestion}>New Question</button>
 {showAnswer && <h3>Correct Answer</h3>} **<= This is just an example because i don't know what i put there**
<button onClick={answerToggler}>Show Answer </button>

</div>
     );
</code>```

};

The idea is that the code retrieves the answer to the question by pressing the "show answer" button using only one fetch request. It should look like this:

答:
Your fetch returns something like this:

```<code>
{
  "response_code": 0,
  "results": [
    {
      "category": "Entertainment: Film",
      "type": "multiple",
      "difficulty": "medium",
      "question": "Which former Star Trek actor directed Three Men and a Baby (1987)?",
      "correct_answer": "Leonard Nimoy",
      "incorrect_answers": [
        "William Shatner",
        "George Takei",
        "James Doohan"
      ]
    }
  ]
}
</code>```

The correct answer is right there. When you do the fetch in your code you are saving just the question in your state. You could try to save the whole response and then filter it.

like this: setQuestion(data.results[0]) and then you can access the question and the answer from that state. like this:

{question.question}

{question.correct_answer}

Body:
EDIT: Add a new 'Show answer' button to display the correct answer to the question. The answer is not visible when the question is retrieved but is only displayed when the 'Show answer' button is pressed. Make only one fetch request / question and you can display the answer using conditional rendering, for example. HELP NEEDED

const Trivia = () => {

 const [question, setQuestion] = React.useState();
 const [showAnswer, setShowAnswer] = React.useState(false);

 const fetchQuestion = () => {
     fetch("https://opentdb.com/api.php?amount=1")
     .then((response) => response.json())
     .then((data) => {
      setQuestion(data.results[0].question);

     });
   };

    const answerToggler = () => setShowAnswer(prevAns => !prevAns)
     React.useEffect(() => {
         fetchQuestion();
     }, []);

 return(

 {question}

 <button onClick={fetchQuestion}>New Question</button>
 {showAnswer &&
Correct Answer
} **<= This is just an example because i don't know what i put there**
<button onClick={answerToggler}>Show Answer </button>

     );

};

The idea is that the code retrieves the answer to the question by pressing the "show answer" button using only one fetch request. It should look like this:

Body:
Your fetch returns something like this:

{
  "response_code": 0,
  "results": [
    {
      "category": "Entertainment: Film",
      "type": "multiple",
      "difficulty": "medium",
      "question": "Which former Star Trek actor directed Three Men and a Baby (1987)?",
      "correct_answer": "Leonard Nimoy",
      "incorrect_answers": [
        "William Shatner",
        "George Takei",
        "James Doohan"
      ]
    }
  ]
}

The correct answer is right there. When you do the fetch in your code you are saving just the question in your state. You could try to save the whole response and then filter it.

like this: setQuestion(data.results[0]) and then you can access the question and the answer from that state. like this:

<p>{question.question}</p>

<p>{question.correct_answer}</p>


问:
How to limit a full join by date
Our database is on SQL Server 2014. I had the exact same issue as SQL join table to itself to get data for previous year, and was so happy to find the answer. So I setup my query:

```<code>select distinct
    coalesce (a.year, b.year+1) [Year]
  , coalesce(a.Month, b.Month) [Month]
  , coalesce(a.account, b.account) [Account]
  , case when a.sales > 0
        then a.sales
        else 0 end [Sales MTD]
  , case when b.sales > 0
        then b.sales
        else 0 end [Sales Previous Year]
  , (case when b.sales!= 0
        then cast((case when a.sales > 0
                then a.sales
                else 0 end-b.sales)/b.sales*100 as decimal(10,1))
        else 0 end) [% Difference]
  , sum(a.sales) over (Partition by a.account, a.year order by a.month) [Account Sales YTD]
from yourtable a
      full join yourtable b
            on  a.account = b.account
            and a.month = b.month
            and a.year = b.year+1
</code>```

The output is giving me results for months in 2022 that haven't happened yet (and starting 2023 too). https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=9a2c29f1af08f525a1acee16b0efa2fd

I tried adding and b.[year]+1<=year(getdate()) to my join filters, but that doesn't seem to affect output at all. I also tried writing a where clause, that ended up with a case that made my head spin.

How can I prevent future dates from showing up in the end result?
Bonus question: Can I make my YTD calculation accept a 0 as a value for any lines added due to sales history?

答:
Add a WHERE clause

```<code>...
where datefromparts(coalesce(a.year, b.year+1), coalesce(a.Month, b.Month), 1) <= cast(getdate() as date)
</code>```

Title: How to limit a full join by date

Body:
Our database is on SQL Server 2014. I had the exact same issue as SQL join table to itself to get data for previous year, and was so happy to find the answer. So I setup my query:

select distinct
    coalesce (a.year, b.year+1) [Year]
  , coalesce(a.Month, b.Month) [Month]
  , coalesce(a.account, b.account) [Account]
  , case when a.sales > 0
        then a.sales
        else 0 end [Sales MTD]
  , case when b.sales > 0
        then b.sales
        else 0 end [Sales Previous Year]
  , (case when b.sales!= 0
        then cast((case when a.sales > 0
                then a.sales
                else 0 end-b.sales)/b.sales*100 as decimal(10,1))
        else 0 end) [% Difference]
  , sum(a.sales) over (Partition by a.account, a.year order by a.month) [Account Sales YTD]
from yourtable a
      full join yourtable b
            on  a.account = b.account
            and a.month = b.month
            and a.year = b.year+1

The output is giving me results for months in 2022 that haven't happened yet (and starting 2023 too). https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=9a2c29f1af08f525a1acee16b0efa2fd

I tried adding and b.[year]+1<=year(getdate()) to my join filters, but that doesn't seem to affect output at all. I also tried writing a where clause, that ended up with a case that made my head spin.

How can I prevent future dates from showing up in the end result?
Bonus question: Can I make my YTD calculation accept a 0 as a value for any lines added due to sales history?

Body:
Add a WHERE clause

...
where datefromparts(coalesce(a.year, b.year+1), coalesce(a.Month, b.Month), 1) <= cast(getdate() as date)


问:
Can I have two different input fields and one column in the database?
I want to have two input fields, but only one column in the database.
The first input is stored data in numbers and the other one is stored data in numbers divided by 24.
You can put data only in one field.
Is there any possible way to do this?

UPD:
Migration:

def change
  add_column :employees, :hourly_payment , :integer
end
```
<p>View:
employees/_form.html.erb</p>
```<%= simple_form_for @employee do |form| %>
  <%= form.input :name %>
  <%= form.input :hourly_payment %>
  <%= form.input :monthly_payment %>
  <%= form.button :submit, class: "btn btn-success" %>
<% end %>
```

答:
You'll need to create a view for that. Here is an example of migration:

def up
  sql = %(CREATE OR REPLACE VIEW my_view_models AS
  SELECT m.*,m.int_field*12 as my_new_value from my_models m
  )
  self.connection.execute(sql)
end

def down
  self.connection.execute('DROP VIEW IF EXISTS my_view_models')
end
```
<p>Then, you can access your value with method <code>my_new_value</code> on your model. You'll need to change the name of the default table matching your model.</p>
<pre class="lang-rb prettyprint-override"><code>class MyModel
  self.table_name = 'my_view_models'
end
</code>```

And access it via

```<code>MyModel.first.my_new_value
</code>```

Body:
I want to have two input fields, but only one column in the database.
The first input is stored data in numbers and the other one is stored data in numbers divided by 24.
You can put data only in one field.
Is there any possible way to do this?

UPD:
Migration:

def change
  add_column :employees, :hourly_payment , :integer
end

View:
employees/_form.html.erb

<%= simple_form_for @employee do |form| %>
  <%= form.input :name %>
  <%= form.input :hourly_payment %>
  <%= form.input :monthly_payment %>
  <%= form.button :submit, class: "btn btn-success" %>
<% end %>

Body:
You'll need to create a view for that. Here is an example of migration:

def up
  sql = %(CREATE OR REPLACE VIEW my_view_models AS
  SELECT m.*,m.int_field*12 as my_new_value from my_models m
  )
  self.connection.execute(sql)
end

def down
  self.connection.execute('DROP VIEW IF EXISTS my_view_models')
end

Then, you can access your value with method my_new_value on your model. You'll need to change the name of the default table matching your model.

class MyModel
  self.table_name = 'my_view_models'
end

And access it via

MyModel.first.my_new_value


问:
How to in React Component constructor set this state
I still learn much React JavaScript and now I can't understand how to create this initial state.

In the constructor here in the code I want to add to state by running this line:

```<code>    this.state = CsvViewer.parse(props.data);
</code>```

And direct after I want to add more state variables like this:

```<code>    this.state = {
        filters: {},
        sortColumn: null,
        sortDirection: null,
    };
</code>```

The problem now is that state does not contain the first call to CsvViewer. How can I add to state both the call to CsvViewer and the other state variables?

Code:

```<code>    class CsvViewer extends Component {
        static parse(data) {
            const rows = [];
            const columns = [];

            new CSV(data).forEach(array => {
                if (columns.length < 1) {
                    array.forEach((cell, idx) => {
                        columns.push({
                            key: `key-${idx}`,
                            name: cell,
                            resizable: true,
                            sortable: true,
                            filterable: true,
                        });
                    });
                } else {
                    const row = {};
                    array.forEach((cell, idx) => {
                        row[`key-${idx}`] = cell;
                    });
                    rows.push(row);
                }
            });
            return { rows, columns };
        }

        constructor(props) {
            super();
            this.state = CsvViewer.parse(props.data);
            this.state = {
                filters: {},
                sortColumn: null,
                sortDirection: null,
            };
        }

    UNSAFE_componentWillReceiveProps(nextProps) {
        // TODO
        this.setState(CsvViewer.parse(nextProps.data));
    }

    handleGridSort = (sortColumn, sortDirection) => {
        // this.setState({ sortColumn, sortDirection });
    };

    render() {
        const { rows, columns } = this.state;
        const { height } = this.props;
        return (
            <ReactDataGrid
                enableCellAutoFocus={false}
                columns={columns}
                rowsCount={rows ? rows.length: 0}
                rowGetter={i => rows[i]}
                minHeight={height || 650}
                onGridSort={this.handleGridSort}
            />
        );
    }
}

export default CsvViewer;
</code>```

答:
You can set csvViewer, filters, sortColumn, and sortDirection under one state like so.

```<code>    constructor(props) {
        super();
        this.state = {
            csvViewer: CsvViewer.parse(props.data),
            filters: {},
            sortColumn: null,
            sortDirection: null,
        };
    }
</code>```

The second this.state will overwrite your first this.state, you can have everything under one state.

Body:
I still learn much React JavaScript and now I can't understand how to create this initial state.

In the constructor here in the code I want to add to state by running this line:

    this.state = CsvViewer.parse(props.data);

And direct after I want to add more state variables like this:

    this.state = {
        filters: {},
        sortColumn: null,
        sortDirection: null,
    };

The problem now is that state does not contain the first call to CsvViewer. How can I add to state both the call to CsvViewer and the other state variables?

Code:

    class CsvViewer extends Component {
        static parse(data) {
            const rows = [];
            const columns = [];

            new CSV(data).forEach(array => {
                if (columns.length < 1) {
                    array.forEach((cell, idx) => {
                        columns.push({
                            key: `key-${idx}`,
                            name: cell,
                            resizable: true,
                            sortable: true,
                            filterable: true,
                        });
                    });
                } else {
                    const row = {};
                    array.forEach((cell, idx) => {
                        row[`key-${idx}`] = cell;
                    });
                    rows.push(row);
                }
            });
            return { rows, columns };
        }

        constructor(props) {
            super();
            this.state = CsvViewer.parse(props.data);
            this.state = {
                filters: {},
                sortColumn: null,
                sortDirection: null,
            };
        }

    UNSAFE_componentWillReceiveProps(nextProps) {
        // TODO
        this.setState(CsvViewer.parse(nextProps.data));
    }

    handleGridSort = (sortColumn, sortDirection) => {
        // this.setState({ sortColumn, sortDirection });
    };

    render() {
        const { rows, columns } = this.state;
        const { height } = this.props;
        return (
            <ReactDataGrid
                enableCellAutoFocus={false}
                columns={columns}
                rowsCount={rows ? rows.length: 0}
                rowGetter={i => rows[i]}
                minHeight={height || 650}
                onGridSort={this.handleGridSort}
            />
        );
    }
}

export default CsvViewer;

Body:
You can set csvViewer, filters, sortColumn, and sortDirection under one state like so.

    constructor(props) {
        super();
        this.state = {
            csvViewer: CsvViewer.parse(props.data),
            filters: {},
            sortColumn: null,
            sortDirection: null,
        };
    }

The second this.state will overwrite your first this.state, you can have everything under one state.


问:
Fetching WordPress.org reviews via API
I want to fetch a plugin review from wordpress.org via API, is it possible? I tried using https://api.wordpress.org/plugins/info/1.0/{slug}.json but no luck? Is there anyone available for help?</p>

答:
To fetch reviews of a WordPress plugin from the WordPress plugin directory, you can use the WordPress.org Plugin API. The API allows you to retrieve information about a plugin, including its reviews, by sending a GET request to a specific endpoint.

Here's an example of how you can use the API to retrieve reviews for a plugin with the slug "akismet":

https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&request[slug]=akismet

This will return JSON data containing information about the plugin, including an array of reviews. You can then parse the JSON data and extract the reviews as needed. At this moment it only returns 10 reviews.

Title: Fetching WordPress.org reviews via API