问:
Mocking auth decorator with pytest and flask
I have a flask application that uses an auth decorator to validate JWT tokens to an external service (auth0). The application looks like this:

app/helpers/decorators.py

```<code>from functools import wraps

def check_auth(f):
    @wraps(f)
    def auth_check(*args, **kwargs):
        token = get_token_auth_header() # will get token from Bearer header
        jsonurl = urlopen("https://"+AUTH0_DOMAIN+"/.well-known/jwks.json")
        ...[ pass token to auth0 ]
    return auth_check
</code>```

app/api/annotation_api.py

```<code>from flask.views import MethodView
from app.helpers.decorators import check_auth

class AnnotationMetricAPI(MethodView):
    @check_auth
    def get(self, id):
        return {status: 200}

annotation_metric_view = AnnotationMetricAPI.as_view('annotation_metric_view')
</code>```

app/routes/routes.py

```<code>from flask import Blueprint
from flask_cors import CORS
from app.api.annotation_api import annotation_metric_view

routes_blueprint = Blueprint('routes', __name__)
CORS(routes_blueprint, max_age=30*86400)

routes_blueprint.add_url_rule(
    '/api/v1/annotation/metric/<id>',
    view_func=annotation_metric_view,
    methods=['GET']
)

</code>```

app/_ _init_ _.py

```<code>from flask import Flask
from flask_cors import CORS
from app.routes import routes_blueprint
import logging

logging.basicConfig(level=logging.DEBUG)

def create_app():
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object('config.Config')
    CORS(app)
    with app.app_context():
        app.register_blueprint(routes_blueprint)
        return app
</code>```

Now I'd like to use pytest to replace the @check_auth decorator with a mock decorator. After reading these articles:
https://medium.com/@hmajid2301/testing-with-pytest-mock-and-pytest-flask-13cd968e1f24

Mock authentication decorator in unittesting

I've tried the following methods:

Method 1: using pytest-flask and pytest-mock plugins:

tests/test_annotation_api1.py

```<code>import pytest

from app import create_app

@pytest.fixture
def app(mocker):
    mocker.patch("app.helpers.decorators.check_auth", return_value=True)
    app = create_app()
    return app

def test_get_metric_annotations(client):
    response = client.get(
        '/api/v1/annotation/metric/1',
        content_type='application/json'
    )
    data = response.json
    assert data['status'] == 200
</code>```

Method 2: using mock.patch:

tests/test_annotation_api2.py

```<code>from functools import wraps
from mock import patch

def mock_decorator(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        return f(*args, **kwargs)
    return decorated_function

patch('app.helpers.decorators.check_auth', mock_decorator).start()

from app import create_app

app = create_app()
app.testing = True

def test_get_metric_annotations():
    with app.test_client() as client:
        response = client.get(
            '/api/v1/annotation/metric/1',
            content_type='application/json'
        )
        data = response.json
        assert data['status'] == 200
</code>```

Method 3: using the @patch decorator:

tests/test_annotation_api3.py

```<code>from functools import wraps
from mock import patch

def mock_decorator(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print("IN HEREEE")
        return f(*args, **kwargs)
    return decorated_function

from app import create_app

app = create_app()
app.testing = True

@patch('app.helpers.decorators.check_auth')
def test_get_metric_annotations(mock_auth):
    mock_auth.return_value = True
    with app.test_client() as client:
        response = client.get(
            '/api/v1/annotation/metric/1',
            content_type='application/json'
        )
        data = response.json
        assert data['status'] == 200
</code>```

With each of these methods I get the same result, the check_auth decorator fires, ie it isn't being mocked properly:

```<code>============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: /container
plugins: cov-2.8.1, mock-3.1.0, flask-1.0.0
collected 1 item

tests/test_annotation_api.py F                                           [100%]

=================================== FAILURES ===================================
_________________ test_get_metric_annotations_multiple_results _________________

    def test_get_metric_annotations_multiple_results():
        with app.test_client() as client:
            response = client.get(
                '/api/v1/annotation/metric/1',
>               content_type='application/json'
            )

tests/test_annotation_api.py:24:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/local/lib/python3.6/dist-packages/werkzeug/test.py:1006: in get

...
/usr/local/lib/python3.6/dist-packages/flask/views.py:89: in view
    return self.dispatch_request(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/flask/views.py:163: in dispatch_request
    return meth(*args, **kwargs)
app/helpers/decorators.py:24: in auth_check
    token = get_token_auth_header()

def get_token_auth_header():
        """Obtains the Access Token from the Authorization Header
        """
        auth = request.headers.get("Authorization", None)
        if not auth:
            raise AuthError({"code": "authorization_header_missing",
                            "description":
>                               "Authorization header is expected"}, 401)
E           app.helpers.errorhandlers.AuthError: ({'code': 'authorization_header_missing', 'description': 'Authorization header is expected'}, 401)

app/helpers/jwt_handler.py:16: AuthError
</code>```

My guess is that I'm not targeting the check_auth decorator properly, but I'm at a loss for what to try next. Thoughts? Thanks.

答:
I figured it out. Following the advice posted here:

https://stackoverflow.com/a/61289000/1220172

I changed my decorator to:

app/helpers/decorators.py

```<code>from functools import wraps

def is_token_valid():
    ''' this will return true if valid, false or raise error otherwise '''
    token = get_token_auth_header() # will get token from Bearer header
    jsonurl = urlopen("https://"+AUTH0_DOMAIN+"/.well-known/jwks.json")
    ...[ pass token to auth0 ]

def check_auth(f):
    @wraps(f)
    def auth_check(*args, **kwargs):
        if is_token_valid() == True:
            return f(*args, **kwargs)
    return auth_check
</code>```

My test can now mock is_token_valid:

tests/conftest.py

```<code>import pytest
from app import create_app

@pytest.fixture
def app(mocker):
    mocker.patch("app.helpers.decorators.is_token_valid", return_value=True)
    app = create_app()
    return app
</code>```

Hope this helps you if you're having trouble mocking decorators.

Body:
I have a flask application that uses an auth decorator to validate JWT tokens to an external service (auth0). The application looks like this:

app/helpers/decorators.py

from functools import wraps

def check_auth(f):
    @wraps(f)
    def auth_check(*args, **kwargs):
        token = get_token_auth_header() # will get token from Bearer header
        jsonurl = urlopen("https://"+AUTH0_DOMAIN+"/.well-known/jwks.json")
        ...[ pass token to auth0 ]
    return auth_check

app/api/annotation_api.py

from flask.views import MethodView
from app.helpers.decorators import check_auth

class AnnotationMetricAPI(MethodView):
    @check_auth
    def get(self, id):
        return {status: 200}

annotation_metric_view = AnnotationMetricAPI.as_view('annotation_metric_view')

app/routes/routes.py

from flask import Blueprint
from flask_cors import CORS
from app.api.annotation_api import annotation_metric_view

routes_blueprint = Blueprint('routes', __name__)
CORS(routes_blueprint, max_age=30*86400)

routes_blueprint.add_url_rule(
    '/api/v1/annotation/metric/<id>',
    view_func=annotation_metric_view,
    methods=['GET']
)

app/_ _init_ _.py

from flask import Flask
from flask_cors import CORS
from app.routes import routes_blueprint
import logging

logging.basicConfig(level=logging.DEBUG)

def create_app():
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object('config.Config')
    CORS(app)
    with app.app_context():
        app.register_blueprint(routes_blueprint)
        return app

Now I'd like to use pytest to replace the @check_auth decorator with a mock decorator. After reading these articles:
https://medium.com/@hmajid2301/testing-with-pytest-mock-and-pytest-flask-13cd968e1f24

Mock authentication decorator in unittesting

I've tried the following methods:

Method 1: using pytest-flask and pytest-mock plugins:

tests/test_annotation_api1.py

import pytest

from app import create_app

@pytest.fixture
def app(mocker):
    mocker.patch("app.helpers.decorators.check_auth", return_value=True)
    app = create_app()
    return app

def test_get_metric_annotations(client):
    response = client.get(
        '/api/v1/annotation/metric/1',
        content_type='application/json'
    )
    data = response.json
    assert data['status'] == 200

Method 2: using mock.patch:

tests/test_annotation_api2.py

from functools import wraps
from mock import patch

def mock_decorator(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        return f(*args, **kwargs)
    return decorated_function

patch('app.helpers.decorators.check_auth', mock_decorator).start()

from app import create_app

app = create_app()
app.testing = True

def test_get_metric_annotations():
    with app.test_client() as client:
        response = client.get(
            '/api/v1/annotation/metric/1',
            content_type='application/json'
        )
        data = response.json
        assert data['status'] == 200

Method 3: using the @patch decorator:

tests/test_annotation_api3.py

from functools import wraps
from mock import patch

def mock_decorator(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print("IN HEREEE")
        return f(*args, **kwargs)
    return decorated_function

from app import create_app

app = create_app()
app.testing = True

@patch('app.helpers.decorators.check_auth')
def test_get_metric_annotations(mock_auth):
    mock_auth.return_value = True
    with app.test_client() as client:
        response = client.get(
            '/api/v1/annotation/metric/1',
            content_type='application/json'
        )
        data = response.json
        assert data['status'] == 200

With each of these methods I get the same result, the check_auth decorator fires, ie it isn't being mocked properly:

============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: /container
plugins: cov-2.8.1, mock-3.1.0, flask-1.0.0
collected 1 item

tests/test_annotation_api.py F                                           [100%]

=================================== FAILURES ===================================
_________________ test_get_metric_annotations_multiple_results _________________

    def test_get_metric_annotations_multiple_results():
        with app.test_client() as client:
            response = client.get(
                '/api/v1/annotation/metric/1',
>               content_type='application/json'
            )

tests/test_annotation_api.py:24:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/local/lib/python3.6/dist-packages/werkzeug/test.py:1006: in get

...
/usr/local/lib/python3.6/dist-packages/flask/views.py:89: in view
    return self.dispatch_request(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/flask/views.py:163: in dispatch_request
    return meth(*args, **kwargs)
app/helpers/decorators.py:24: in auth_check
    token = get_token_auth_header()

def get_token_auth_header():
        """Obtains the Access Token from the Authorization Header
        """
        auth = request.headers.get("Authorization", None)
        if not auth:
            raise AuthError({"code": "authorization_header_missing",
                            "description":
>                               "Authorization header is expected"}, 401)
E           app.helpers.errorhandlers.AuthError: ({'code': 'authorization_header_missing', 'description': 'Authorization header is expected'}, 401)

app/helpers/jwt_handler.py:16: AuthError

My guess is that I'm not targeting the check_auth decorator properly, but I'm at a loss for what to try next. Thoughts? Thanks.

Body:
I figured it out. Following the advice posted here:

https://stackoverflow.com/a/61289000/1220172

I changed my decorator to:

app/helpers/decorators.py

from functools import wraps

def is_token_valid():
    ''' this will return true if valid, false or raise error otherwise '''
    token = get_token_auth_header() # will get token from Bearer header
    jsonurl = urlopen("https://"+AUTH0_DOMAIN+"/.well-known/jwks.json")
    ...[ pass token to auth0 ]

def check_auth(f):
    @wraps(f)
    def auth_check(*args, **kwargs):
        if is_token_valid() == True:
            return f(*args, **kwargs)
    return auth_check

My test can now mock is_token_valid:

tests/conftest.py

import pytest
from app import create_app

@pytest.fixture
def app(mocker):
    mocker.patch("app.helpers.decorators.is_token_valid", return_value=True)
    app = create_app()
    return app

Hope this helps you if you're having trouble mocking decorators.


来源: stackexchange

问:
Android Studio: How do I disable reformat code completion popup
I'm developing an app on my mac in Android Studio. When I reformat code an annoying popup appears telling me how many lines have been formatted, etc. Is there a way to disable this popup?</p>

答:
Preferences > Editor > General

The first option under the "Formatting" header is "Show notification after reformat code action"; disable it.

ContentLicense: CC BY-SA 4.0


问:
Pandas - Calculate row values based on prior row value, update the result to be the new row value (and so on)

Below is some dummy data that reflects the data I am working with.

```<code>import pandas as pd
import numpy as np
from numpy import random

random.seed(30)

# Dummy data that represents a percent change
datelist = pd.date_range(start='1983-01-01', end='1994-01-01', freq='Y')
df1 = pd.DataFrame({"P Change_1": np.random.uniform(low=-0.55528, high=0.0396181, size=(11,)),
                   "P Change_2": np.random.uniform(low=-0.55528, high=0.0396181, size=(11,))})
#This dataframe contains the rows we want to operate on
df2 = pd.DataFrame({
    'Loc1': [None, None, None, None, None, None, None, None, None, None, 2.5415],
    'Loc2': [None, None, None, None, None, None, None, None, None, None, 3.2126],})

#Set the datetime index
df1 = df1.set_index(datelist)
df2 = df2.set_index(datelist)
</code>```

df1:

```<code>            P Change_1  P Change_2
1984-12-31   -0.172080   -0.231574
1985-12-31   -0.328773   -0.247018
1986-12-31   -0.160834   -0.099079
1987-12-31   -0.457924    0.000266
1988-12-31    0.017374   -0.501916
1989-12-31   -0.349052   -0.438816
1990-12-31    0.034711    0.036164
1991-12-31   -0.415445   -0.415372
1992-12-31   -0.206852   -0.413107
1993-12-31   -0.313341   -0.181030
1994-12-31   -0.474234   -0.118058
</code>```

df2:

```<code>              Loc1    Loc2
1984-12-31     NaN     NaN
1985-12-31     NaN     NaN
1986-12-31     NaN     NaN
1987-12-31     NaN     NaN
1988-12-31     NaN     NaN
1989-12-31     NaN     NaN
1990-12-31     NaN     NaN
1991-12-31     NaN     NaN
1992-12-31     NaN     NaN
1993-12-31     NaN     NaN
1994-12-31  2.5415  3.2126
</code>```

DataFrame details:

First off, Loc1 will correspond with P Change_1 and Loc2 corresponds to P Change_2, etc. Looking at Loc1 first, I want to either fill up the DataFrame containing Loc1 and Loc2 with the relevant values or compute a new dataframe that has columns Calc1 and Calc2.

The calculation:

I want to start with the 1994 value of Loc1 and calculate a new value for 1993 by taking Loc1 1993 = Loc1 1994 + (Loc1 1994 * P Change_1 1993).  With the values filled in it would be 2.5415 +(-0.313341 * 2.5415) which equals about 1.74514.

This 1.74514 value will replace the NaN value in 1993, and then I want to use that calculated value to get a value for 1992.  This means we now compute Loc1 1992 = Loc1 1993 + (Loc1 1993 * P Change_1 1992).  I want to carry out this operation row-wise until it gets the earliest value in the timeseries.

What is the best way to go about implementing this row-wise equation?  I hope this makes some sense and any help is greatly appreciated!

答:
Just to be clear, what you need is Loc1[year]=Loc1[next_year] + PChange[year]*Loc1[next_year], right?
The below loop will do what you are looking for, but it just assumes that the number of rows in both df's is always equal, etc. (instead of matching the value in the index). From your description, I think this works for your data.

```<code>for i in range(df2.shape[0]-2,-1,-1):
    df2.Loc1[i]=df2.Loc1[i+1] + (df1.PChange_1[i]*df2.Loc1[i+1])
</code>```

Hope this helps :)

Body:
Below is some dummy data that reflects the data I am working with.

import pandas as pd
import numpy as np
from numpy import random

random.seed(30)

# Dummy data that represents a percent change
datelist = pd.date_range(start='1983-01-01', end='1994-01-01', freq='Y')
df1 = pd.DataFrame({"P Change_1": np.random.uniform(low=-0.55528, high=0.0396181, size=(11,)),
                   "P Change_2": np.random.uniform(low=-0.55528, high=0.0396181, size=(11,))})
#This dataframe contains the rows we want to operate on
df2 = pd.DataFrame({
    'Loc1': [None, None, None, None, None, None, None, None, None, None, 2.5415],
    'Loc2': [None, None, None, None, None, None, None, None, None, None, 3.2126],})

#Set the datetime index
df1 = df1.set_index(datelist)
df2 = df2.set_index(datelist)

df1:

            P Change_1  P Change_2
1984-12-31   -0.172080   -0.231574
1985-12-31   -0.328773   -0.247018
1986-12-31   -0.160834   -0.099079
1987-12-31   -0.457924    0.000266
1988-12-31    0.017374   -0.501916
1989-12-31   -0.349052   -0.438816
1990-12-31    0.034711    0.036164
1991-12-31   -0.415445   -0.415372
1992-12-31   -0.206852   -0.413107
1993-12-31   -0.313341   -0.181030
1994-12-31   -0.474234   -0.118058

df2:

              Loc1    Loc2
1984-12-31     NaN     NaN
1985-12-31     NaN     NaN
1986-12-31     NaN     NaN
1987-12-31     NaN     NaN
1988-12-31     NaN     NaN
1989-12-31     NaN     NaN
1990-12-31     NaN     NaN
1991-12-31     NaN     NaN
1992-12-31     NaN     NaN
1993-12-31     NaN     NaN
1994-12-31  2.5415  3.2126

DataFrame details:

First off, Loc1 will correspond with P Change_1 and Loc2 corresponds to P Change_2, etc. Looking at Loc1 first, I want to either fill up the DataFrame containing Loc1 and Loc2 with the relevant values or compute a new dataframe that has columns Calc1 and Calc2.

The calculation:

I want to start with the 1994 value of Loc1 and calculate a new value for 1993 by taking Loc1 1993 = Loc1 1994 + (Loc1 1994 * P Change_1 1993).  With the values filled in it would be 2.5415 +(-0.313341 * 2.5415) which equals about 1.74514.

This 1.74514 value will replace the NaN value in 1993, and then I want to use that calculated value to get a value for 1992.  This means we now compute Loc1 1992 = Loc1 1993 + (Loc1 1993 * P Change_1 1992).  I want to carry out this operation row-wise until it gets the earliest value in the timeseries.

What is the best way to go about implementing this row-wise equation?  I hope this makes some sense and any help is greatly appreciated!

Body:
Just to be clear, what you need is Loc1[year]=Loc1[next_year] + PChange[year]*Loc1[next_year], right?
The below loop will do what you are looking for, but it just assumes that the number of rows in both df's is always equal, etc. (instead of matching the value in the index). From your description, I think this works for your data.

for i in range(df2.shape[0]-2,-1,-1):
    df2.Loc1[i]=df2.Loc1[i+1] + (df1.PChange_1[i]*df2.Loc1[i+1])

Hope this helps :)


问:
Using VLOOKUP to look into 2 columns from 2 seperate spreadsheets, apply formatting if found in second column?
I am trying to use VLOOKUP on Google Sheets to look into different sheets, one having 'good' inventory, the other having 'damaged' inventory. If value found on the sheet with 'damaged' inventory, I want to highlight the 'LOT # SERIAL #" column for that row so the counters and analysts can identify these.

I have tried combining the VLOOKUPS, basically inserting into the argument another instant to look elsewhere. However, I am more interested in a fucntion that can look for the 'LOT & SERIAL #' in the 'Damaged' database sheet, and highlight it in red if a match is found, without affecting my other VLOOKUPS for 'DESCRIPTION', 'CLASS 1', etc.

My sheet works fine until I try to do a VLOOKUP on 'LOT & SERIAL #'. I know I must be doing it wrong and it's more of a data validation rule, but how can I acomplish this by looking into the 'LOT & SERIAL #' of those other two sheets, and if matched to a 'Damaged' product, highlight in red?

Anybody knows how to achieve this with User Defined Functions only? Any help would be much appreciated it.

Sample sheet (it already has everything else I needed to do set):

https://docs.google.com/spreadsheets/d/1Kd3-8I_isB6s4hHhx4GO-vOB3NkWAZwO2R8OeP3aAgA/edit?usp=sharing

答:
Nevermind, I found a way to do the data validation from another sheet, see below:

=match(G:G,indirect("CTRDW Damage Slabs DATABASE!H:H"),0)


问:
beautiful soup find function to scrape number off google
Ive just finished watching a tutorial on beautiful soup and thought I'd use it to try and scrape some data from google.

I've just googled coronavirus UK and wanted to scrape the current confirmed cases number.

On the upper right hand side of the web page is a box which shows the number of confirmed cases in the UK. Upon inspecting the element I found it to be located in this block:

```<code><td jsname="VBiLTe" class="dZdtsb QmWbpe ZDeom" data-absolute-value="276332" data-is-data-cell="true"
data-per-million-value="4258.258906030955" data-vfs="276332"><div class="amyZLb">Confirmed</div><div
class="m7B03"><div jsname="fUyIqc"><span>276K</span></div><div jsname="KBqmYc" style="display:none">
<span>4,258</span></div></div><div class="h5Hgwe"><div jsname="fUyIqc">+<span>1,570</span></div></div>
</td>
</code>```

The data-vfs key in the above code block holds the value I want to scrape. I thought this code would work to scrape the value.

```<code>from bs4 import BeautifulSoup
import requests

source = requests.get("https://www.google.com/search?q=coronavrius+uk&rlz=1C1CHBF_en-GBGB813GB813&oq=cor&aqs=chrome.0.69i59l2j0j69i57j35i39j69i64j69i60l2.1384j0j4&sourceid=chrome&ie=UTF-8").text
soup = BeautifulSoup(source,'lxml')

test=soup.find("td",class_="dZdtsb QmWbpe ZDeom")
print(test["data-vfs"])
</code>```

However, test is returned as none, (which gives an error upon running the code) implying nothing was found? I've been trying to figure out why for ages but nothing comes to mind. How do I modify the arguments in find to scrape the number?

答:
To obtain information from pages served by Google, you need to specify User-Agent header.

For example:

```<code>import requests
from bs4 import BeautifulSoup

url ='https://www.google.com/search?hl=en&q=corona+virus+uk'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}

soup = BeautifulSoup( requests.get(url, headers=headers).content, 'html.parser' )

table1 = soup.select_one('div:has(span:contains("United Kingdom")) + table')
table2 = soup.select_one('div:has(span:contains("Worldwide")) + table')

print('UK:')
print('-'*80)
for td in table1.select('td'):
    print(td.get_text(strip=True, separator=' '))

print()

print('World:')
print('-'*80)
for td in table2.select('td'):
    print(td.get_text(strip=True, separator=' '))
</code>```

Prints:

```<code>UK:
--------------------------------------------------------------------------------
Confirmed 276K 4,258 + 1,570
Recovered -
Deaths 39,045 602 + 0

World:
--------------------------------------------------------------------------------
Confirmed 6.06M 860 + 123K
Recovered -
Deaths 371K 53 + 4,000
</code>```

EDIT: Running the code as of 6th July 2020 prints:

```<code>UK:
--------------------------------------------------------------------------------
Confirmed 285K 4,398 + 624
Recovered -
Deaths 44,220 681 + 67

World:
--------------------------------------------------------------------------------
Confirmed 11.4M 1,621 + 203K
Recovered 6.16M 874
Deaths 534K 76 + 5,193
</code>```

Body:
Ive just finished watching a tutorial on beautiful soup and thought I'd use it to try and scrape some data from google.

I've just googled coronavirus UK and wanted to scrape the current confirmed cases number.

On the upper right hand side of the web page is a box which shows the number of confirmed cases in the UK. Upon inspecting the element I found it to be located in this block:

Confirmed

276K

4,258

+1,570

The data-vfs key in the above code block holds the value I want to scrape. I thought this code would work to scrape the value.

from bs4 import BeautifulSoup
import requests

source = requests.get("https://www.google.com/search?q=coronavrius+uk&rlz=1C1CHBF_en-GBGB813GB813&oq=cor&aqs=chrome.0.69i59l2j0j69i57j35i39j69i64j69i60l2.1384j0j4&sourceid=chrome&ie=UTF-8").text
soup = BeautifulSoup(source,'lxml')

test=soup.find("td",class_="dZdtsb QmWbpe ZDeom")
print(test["data-vfs"])

However, test is returned as none, (which gives an error upon running the code) implying nothing was found? I've been trying to figure out why for ages but nothing comes to mind. How do I modify the arguments in find to scrape the number?

Body:
To obtain information from pages served by Google, you need to specify User-Agent header.

For example:

import requests
from bs4 import BeautifulSoup

url ='https://www.google.com/search?hl=en&q=corona+virus+uk'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}

soup = BeautifulSoup( requests.get(url, headers=headers).content, 'html.parser' )

table1 = soup.select_one('div:has(span:contains("United Kingdom")) + table')
table2 = soup.select_one('div:has(span:contains("Worldwide")) + table')

print('UK:')
print('-'*80)
for td in table1.select('td'):
    print(td.get_text(strip=True, separator=' '))

print()

print('World:')
print('-'*80)
for td in table2.select('td'):
    print(td.get_text(strip=True, separator=' '))

Prints:

UK:
--------------------------------------------------------------------------------
Confirmed 276K 4,258 + 1,570
Recovered -
Deaths 39,045 602 + 0

World:
--------------------------------------------------------------------------------
Confirmed 6.06M 860 + 123K
Recovered -
Deaths 371K 53 + 4,000

EDIT: Running the code as of 6th July 2020 prints:

UK:
--------------------------------------------------------------------------------
Confirmed 285K 4,398 + 624
Recovered -
Deaths 44,220 681 + 67

World:
--------------------------------------------------------------------------------
Confirmed 11.4M 1,621 + 203K
Recovered 6.16M 874
Deaths 534K 76 + 5,193


问:
Find each element with attr type without element type
I'd like to find each element with an attr of name and replace part of the string.  The caveat is I don't wish to target them by element type.
The below doesn't work:

```<code>       var index = 0;
       $('.foil').each(function () {
            $(this).each(function () {
                attr = $(this).attr('name');
                if (typeof attr !== typeof undefined && attr !== false){
                    console.log(attr);
                    attr.replace(/\[(.+?)\]/g, '[' + index + ']');
                }
            });
           index++;
       });
</code>```

This was the solution that worked:

```<code>                $(this).find('[name]').each(function () {
                    $(this).attr('name', $(this).attr('name').replace(/\[(.+?)\]/g, '[' + index + ']'));
                });
</code>```

答:
Consider fthe following code.

```<code>$(".foil").each(function (i, el) {
  if($(el).attr("name") != undefined || $(el).attr("name") != ""){
    $(el).attr("name", $(el).attr("name").replace(/\[(.?)\]/, "[" + i + "]"));
  }
});
</code>```

So if you have:

```<code><input class="foil" type="text" name="txtfield[23]" />
<input class="foil" type="text" name="txtfield[60]" />
</code>```

Each would be iterated and and the name attribute would be updated with the new Indexes.

```<code><input class="foil" type="text" name="txtfield[0]" />
<input class="foil" type="text" name="txtfield[1]" />
</code>```

Body:
I'd like to find each element with an attr of name and replace part of the string.  The caveat is I don't wish to target them by element type.
The below doesn't work:

       var index = 0;
       $('.foil').each(function () {
            $(this).each(function () {
                attr = $(this).attr('name');
                if (typeof attr !== typeof undefined && attr !== false){
                    console.log(attr);
                    attr.replace(/\[(.+?)\]/g, '[' + index + ']');
                }
            });
           index++;
       });

This was the solution that worked:

                $(this).find('[name]').each(function () {
                    $(this).attr('name', $(this).attr('name').replace(/\[(.+?)\]/g, '[' + index + ']'));
                });

Body:
Consider fthe following code.

$(".foil").each(function (i, el) {
  if($(el).attr("name") != undefined || $(el).attr("name") != ""){
    $(el).attr("name", $(el).attr("name").replace(/\[(.?)\]/, "[" + i + "]"));
  }
});

So if you have:

<input class="foil" type="text" name="txtfield[23]" />
<input class="foil" type="text" name="txtfield[60]" />

Each would be iterated and and the name attribute would be updated with the new Indexes.

<input class="foil" type="text" name="txtfield[0]" />
<input class="foil" type="text" name="txtfield[1]" />


问:
react-autocomplete multiple suggestions
```<code>  const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().slice(0, inputLength) === inputValue
    );
  };
</code>```

The current algorithm of react-autocomplete only finds the first word of a phase.
For example I can only find "Coca Cola Zero Sugar Cola" when I write "coc" or"coca" but I cannot find it if I write "Cola", "Zero" or "Sugar". I asked in repo's issues but cannot get and answer. I tried myself without success.
How can I write algorithm that will work as I explained above?

答:
If you modify your filter to use .includes instead of === it will return multiple suggestions:

```<code>const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().includes(inputValue)
   );
 };
</code>```

Title: react-autocomplete multiple suggestions

Body:
  const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().slice(0, inputLength) === inputValue
    );
  };

The current algorithm of react-autocomplete only finds the first word of a phase.
For example I can only find "Coca Cola Zero Sugar Cola" when I write "coc" or"coca" but I cannot find it if I write "Cola", "Zero" or "Sugar". I asked in repo's issues but cannot get and answer. I tried myself without success.
How can I write algorithm that will work as I explained above?

Body:
If you modify your filter to use .includes instead of === it will return multiple suggestions:

const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().includes(inputValue)
   );
 };


问:
Fast grouping and aggregation of huge data set
I've got a huge amount of data (stored in file, but it is irrelevant - main part is that the data doesn't fit into memory) - let's say 109 lines of records.

The record consists of time, some set of keys, and data. The keys aren't unique.

for example

```<code>keys:          data:
A | B | C |
----------------------
1 | 2 | 3 |    10
1 | 1 | 3 |    150
1 | 1 | 2 |    140
1 | 2 | 5 |    130
5 | 3 | 2 |    120
...
</code>```

I need to go through all of the data, and filter them using user-defined filter (this isn't problem), and then aggregate, count sum, and return rows with highest data.

For example, in given data, I want to sum every data grouping by A and C.

expected result:

```<code>A | C | data
------------
1 | 3 | 160
1 | 2 | 140
1 | 5 | 130

------------ following (data isn't in 3 highest value) doesn't concern me.
5 | 2 | 120
</code>```

I implemented this using naive solution, I have Dictionary<tuple(A, C), long>, and sum there. But the problem is, that there can be more unique combinations of A,C than I can fit into memory.

I cannot pre-sum any of the data, as any filtering may appear, nor use SQL (relational DB doesn't fit well for me).

Are there any memory-efficient algorithms usable for grouping this way? How does SQL handle so much data? I'm able to do the grouping on SQL, but there are some reasons why I do not want to use it.

Or, what should I google? I haven't found any useful article on this issue.

(I'm using C#, the question is rather theoretical than 'use following code:')

答:
well, the comments for the question might be considered as an answer...

You can use mapreduce (hadoop is the framework implementation in java)

your map stage will parse each line and extract relevant key and value for each line.

 your reduce stage will summarize all the data for the given key.

ContentLicense: CC BY-SA 3.0

Body:
I've got a huge amount of data (stored in file, but it is irrelevant - main part is that the data doesn't fit into memory) - let's say 109 lines of records.

The record consists of time, some set of keys, and data. The keys aren't unique.

for example

keys:          data:
A | B | C |
----------------------
1 | 2 | 3 |    10
1 | 1 | 3 |    150
1 | 1 | 2 |    140
1 | 2 | 5 |    130
5 | 3 | 2 |    120
...

I need to go through all of the data, and filter them using user-defined filter (this isn't problem), and then aggregate, count sum, and return rows with highest data.

For example, in given data, I want to sum every data grouping by A and C.

expected result:

A | C | data
------------
1 | 3 | 160
1 | 2 | 140
1 | 5 | 130

------------ following (data isn't in 3 highest value) doesn't concern me.
5 | 2 | 120

I implemented this using naive solution, I have Dictionary<tuple(A, C), long>, and sum there. But the problem is, that there can be more unique combinations of A,C than I can fit into memory.

I cannot pre-sum any of the data, as any filtering may appear, nor use SQL (relational DB doesn't fit well for me).

Are there any memory-efficient algorithms usable for grouping this way? How does SQL handle so much data? I'm able to do the grouping on SQL, but there are some reasons why I do not want to use it.

Or, what should I google? I haven't found any useful article on this issue.

(I'm using C#, the question is rather theoretical than 'use following code:')


问:
How to connect two users in one room in React Native JSX
i am a newbie. Making my first app in react-native. I am stuck on one step.

In the app a user can create a room on regestration. The room is shared ONLY between 2 users. So the second user can connect to it using the name of  the room and the password. Both users won't share one screen. The connection between the users in the room will be used only at the end. When the "game" is finished, the second user will be notified and will get a list of tasks that the first user has completed.

How could i achieve it?

THanks for any help.

答:
I would advise you learn the fundamentals of SocketIO, Websockets, Node.JS.

Follow a tutorial on building a real time chat app. SocketIO has a rooms API you can use to join users to share data in real time.


问:
Out of Memory Exception at System.Drawing.Graphics.FromHdcInternal but no memory leak
Am getting a very occasional crash with the following trace:

```<code>System.OutOfMemoryException: Out of memory.
   at System.Drawing.Graphics.FromHdcInternal(IntPtr hdc)
   at System.Windows.Forms.PaintEventArgs.get_Graphics()
   at System.Windows.Forms.Control.PaintBackColor(PaintEventArgs e, Rectangle rectangle, Color backColor)
   at System.Windows.Forms.Control.PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backColor, Point scrollOffset)
   at System.Windows.Forms.Control.PaintBackground(PaintEventArgs e, Rectangle rectangle)
   at System.Windows.Forms.Control.OnPaintBackground(PaintEventArgs pevent)
   at System.Windows.Forms.ScrollableControl.OnPaintBackground(PaintEventArgs e)
   at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
   at System.Windows.Forms.Control.WmEraseBkgnd(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.ContainerControl.WndProc(Message& m)
   at System.Windows.Forms.UserControl.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code>```

As you can see theres none of my code in the trace so i'm finding it very hard to find the cause. Google searches seem inconclusive but generally point to a GC handle leak somewhere but following the most recent crash my memory usage was:

```<code>Handle count:16,283,
Private Bytes:995,440K,
Virtual Bytes:1,628,208K,
Working Set:866,892K,
GC Heap Size:158,841K,
GDI Objects:402,
User Objects:1,607
</code>```

Which does not seem out of the ordinary. Also, I regularly use .net memory profiler to manage leaks.

Unfortunately my app is quite large with many windows so my first question would be: How can I identify which window is causing all the pain?

and then of course my second question would be: If there is no handle leak, what is causing the exception!?

Edit:

Sorry I can't post any code: Its a massive codebase and the exceptions arent exactly giving me any clues as to which part may be the problem.

I read about there being a 10,000 limit on handles but this app has historically always run fine with 15,000 so I assumed the limit was on something else: GDI handles or user objects maybe?

Just to make sure, I checked and the handles are not being leaked as they are all assigned at startup and do not increase with usage.

Let me modify my question: Given this information, what should the next course of action be? I have process Explorer installed and have succeeded in getting a full memory dump from one of the crashes but really dont have experience in using either to diagnose this kind of problem (until now .net memory profiler has been enough)

答:
Late to the party, but in case someone else ends up here, but there's a Hotfix that got released:
https://support.microsoft.com/en-us/help/2650146/fix-outofmemoryexception-exception-when-you-use-a-graphics-object-to-p

FIX: OutOfMemoryException exception when you use a graphics object to
paint in a .NET Framework 3.5-based Windows Forms application Applies
to: .NET Framework 3.5 Service Pack 1

Symptoms
Consider the following scenario:

You create a Microsoft .NET
Framework 3.5-based graphics-intensive application on a computer that
is running Windows 7 or Windows Server 2008 R2.

The application uses
the graphics device interface (GDI).

You create a graphics object, and
then use it to paint. In this scenario, you may experience an
OutOfMemoryException exception. Additionally, you receive the
following error message:

Exception type: System.OutOfMemoryException Message: Out of memory.

When you debug this issue, you receive a stack trace that resembles
the following:

at System.Drawing.Graphics.FromHdcInternal(IntPtr hdc)

at System.Windows.Forms.PaintEventArgs.get_Graphics()

To resolve:

A supported hotfix is now available from Microsoft. However, it is
intended to correct only the problem that this article describes.
Apply it only to systems that are experiencing this specific problem.

To resolve this problem, contact Microsoft Customer Support Services
to obtain the hotfix. For a complete list of Microsoft Customer
Support Services telephone numbers and information about support
costs, visit the following Microsoft website:
http://support.microsoft.com/contactus/?ws=support

Body:
Am getting a very occasional crash with the following trace:

System.OutOfMemoryException: Out of memory.
   at System.Drawing.Graphics.FromHdcInternal(IntPtr hdc)
   at System.Windows.Forms.PaintEventArgs.get_Graphics()
   at System.Windows.Forms.Control.PaintBackColor(PaintEventArgs e, Rectangle rectangle, Color backColor)
   at System.Windows.Forms.Control.PaintBackground(PaintEventArgs e, Rectangle rectangle, Color backColor, Point scrollOffset)
   at System.Windows.Forms.Control.PaintBackground(PaintEventArgs e, Rectangle rectangle)
   at System.Windows.Forms.Control.OnPaintBackground(PaintEventArgs pevent)
   at System.Windows.Forms.ScrollableControl.OnPaintBackground(PaintEventArgs e)
   at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
   at System.Windows.Forms.Control.WmEraseBkgnd(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.ContainerControl.WndProc(Message& m)
   at System.Windows.Forms.UserControl.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

As you can see theres none of my code in the trace so i'm finding it very hard to find the cause. Google searches seem inconclusive but generally point to a GC handle leak somewhere but following the most recent crash my memory usage was:

Handle count:16,283,
Private Bytes:995,440K,
Virtual Bytes:1,628,208K,
Working Set:866,892K,
GC Heap Size:158,841K,
GDI Objects:402,
User Objects:1,607

Which does not seem out of the ordinary. Also, I regularly use .net memory profiler to manage leaks.

Unfortunately my app is quite large with many windows so my first question would be: How can I identify which window is causing all the pain?

and then of course my second question would be: If there is no handle leak, what is causing the exception!?

Edit:

Sorry I can't post any code: Its a massive codebase and the exceptions arent exactly giving me any clues as to which part may be the problem.

I read about there being a 10,000 limit on handles but this app has historically always run fine with 15,000 so I assumed the limit was on something else: GDI handles or user objects maybe?

Just to make sure, I checked and the handles are not being leaked as they are all assigned at startup and do not increase with usage.

Let me modify my question: Given this information, what should the next course of action be? I have process Explorer installed and have succeeded in getting a full memory dump from one of the crashes but really dont have experience in using either to diagnose this kind of problem (until now .net memory profiler has been enough)


问:
Adding a dimension to an array
If I have an array that I loaded from a nifti file with shape (112, 176, 112) and I want to add a fourth dimension but not be limited to shape (112, 176, 112, 3)

Why does this code allow me to add however many layers in the 4th dimension I want:

```<code>data = np.ones((112, 176, 112, 20), dtype=np.int16)
print(data.shape)
    >>>(112, 176, 112, 20)
</code>```

But when I try to add a higher layer number to the fourth dimension of my file I get an error. The code only works correctly if axis = 3. If axis = 2 the shape is (112, 176, 336, 1)

```<code>filepath = '3channel.nii'
img = nib.load(filepath)
img = img.get_fdata()
print(img.shape)
    >>>(112, 176, 112)
img2 = img.reshape((112, 176, 112, -1))
img2 = np.concatenate([img2, img2, img2], axis = 20)
</code>```

Error:

```<code>AxisError: axis 20 is out of bounds for array of dimension 4
</code>```

答:
@hpaulj got it, I was looking this up, and this shows the issue; note the shape of the arrays. I modified the original array so you can see what is being added...</p>

```<code>import numpy as np

data = np.ones((112, 176, 115, 20), dtype=np.int16)

data2=np.ones((112, 176, 115), dtype=np.int16)

data2a = data2.reshape((112, 176, 115, -1))
print(data2a.shape)

print("concatenate...")
img2 = np.concatenate([data2a, data2a, data2a],axis=0)
print(img2.shape)

img2 = np.concatenate([data2a, data2a, data2a],axis=1)
print(img2.shape)

img2 = np.concatenate([data2a, data2a, data2a],axis=2)
print(img2.shape)

img2 = np.concatenate([data2a, data2a, data2a],axis=3)
print(img2.shape)

# This throws the error
img2 = np.concatenate([data2a, data2a, data2a],axis=4)
print(img2.shape)
</code>```

Title: Adding a dimension to an array

Body:
If I have an array that I loaded from a nifti file with shape (112, 176, 112) and I want to add a fourth dimension but not be limited to shape (112, 176, 112, 3)

Why does this code allow me to add however many layers in the 4th dimension I want:

data = np.ones((112, 176, 112, 20), dtype=np.int16)
print(data.shape)
    >>>(112, 176, 112, 20)

But when I try to add a higher layer number to the fourth dimension of my file I get an error. The code only works correctly if axis = 3. If axis = 2 the shape is (112, 176, 336, 1)

filepath = '3channel.nii'
img = nib.load(filepath)
img = img.get_fdata()
print(img.shape)
    >>>(112, 176, 112)
img2 = img.reshape((112, 176, 112, -1))
img2 = np.concatenate([img2, img2, img2], axis = 20)

Error:

AxisError: axis 20 is out of bounds for array of dimension 4

Body:
@hpaulj got it, I was looking this up, and this shows the issue; note the shape of the arrays. I modified the original array so you can see what is being added...

import numpy as np

data = np.ones((112, 176, 115, 20), dtype=np.int16)

data2=np.ones((112, 176, 115), dtype=np.int16)

data2a = data2.reshape((112, 176, 115, -1))
print(data2a.shape)

print("concatenate...")
img2 = np.concatenate([data2a, data2a, data2a],axis=0)
print(img2.shape)

img2 = np.concatenate([data2a, data2a, data2a],axis=1)
print(img2.shape)

img2 = np.concatenate([data2a, data2a, data2a],axis=2)
print(img2.shape)

img2 = np.concatenate([data2a, data2a, data2a],axis=3)
print(img2.shape)

# This throws the error
img2 = np.concatenate([data2a, data2a, data2a],axis=4)
print(img2.shape)


问:
How to read cert files from Cloud Functions for Firebase Folder
I am trying to read a file under certs folder as shown below:

```<code>-functions
 |
--certs
  |
---idp-public-cert.perm
</code>```

Here is the code I am using to read the file:

fs.readFileSync(path.join(__dirname, 'certs/idp-public-cert.pem')).

When I run the function, I get the following errors:

```<code>Error: ENOENT: no such file or directory, open '/srv/lib/certs/idp-public-cert.pem'
</code>```

I would appreciate any crew on how to do this. Thanks in advance.

答:
I found that specifying path with "./" or "/" is iffy - because it takes a relative patch from somewhere, maybe OLDPWD or PWD, not sure how it messes up
But I found that the right way to do fix is to add
__dirname to the path. __dirname will give the path of the functions directory.
so if your function is in /home/username/firebase/functions/routes, then __dirname will show you that.
So if you have a file /home/username/firebase/abc/, then you would have to specify:
fs.readFileSync(__dirname+"../abc/"

Hope this saves the time of others!! I wasted so much time on this, it was quite frustrating, and was kicking myself for not reading the doc!

Body:
I am trying to read a file under certs folder as shown below:

-functions
 |
--certs
  |
---idp-public-cert.perm

Here is the code I am using to read the file:

fs.readFileSync(path.join(__dirname, 'certs/idp-public-cert.pem')).

When I run the function, I get the following errors:

Error: ENOENT: no such file or directory, open '/srv/lib/certs/idp-public-cert.pem'

I would appreciate any crew on how to do this. Thanks in advance.


问:
Symfony4 MakerBundle Own Crud Maker
I want to customize the boilerplate code of the new makerbundle crud maker. There is no simple overwriting the templates as it was in SensioGeneratorBundle. I tried to generate a custom MyMakeCrud based on the original code - but i struggle about the injected DoctrineEntityHelper $entityHelper.

```<code> Cannot autowire service "App\Maker\MakeMyCrud": argument "$entityHelper" of
 method "__construct()" references class "Symfony\Bundle\MakerBundle\Doctri
 ne\DoctrineEntityHelper" but no such service exists. You should maybe alias
 this class to the existing "maker.doctrine_entity_helper" service.
</code>```

The existing maker.doctrine_entity_helper is defined private in the maker bundle. How can i get the injection to run?

Could you help me? Has anyone an example for customizing the crud generation? New in sf4.

答:
Many thanks to both of you for this post. I had to customize the MakeCrud command too.
This is the configuration which worked for me for version 5.</p>

```<code>app.maker.make_crud:
    class: App\Maker\MakeCrudCommand
    arguments: ['@maker.doctrine_helper', '@maker.renderer.form_type_renderer']
    calls:
        - [configureCommand, ['@security.command.user_password_encoder', '@?']]
        - [interact, ['@?', '@?', '@security.command.user_password_encoder']]
    tags:
        - { name: maker.command }
</code>```

Title: Symfony4 MakerBundle Own Crud Maker

Body:
I want to customize the boilerplate code of the new makerbundle crud maker. There is no simple overwriting the templates as it was in SensioGeneratorBundle. I tried to generate a custom MyMakeCrud based on the original code - but i struggle about the injected DoctrineEntityHelper $entityHelper.

 Cannot autowire service "App\Maker\MakeMyCrud": argument "$entityHelper" of
 method "__construct()" references class "Symfony\Bundle\MakerBundle\Doctri
 ne\DoctrineEntityHelper" but no such service exists. You should maybe alias
 this class to the existing "maker.doctrine_entity_helper" service.

The existing maker.doctrine_entity_helper is defined private in the maker bundle. How can i get the injection to run?

Could you help me? Has anyone an example for customizing the crud generation? New in sf4.

Body:
Many thanks to both of you for this post. I had to customize the MakeCrud command too.
This is the configuration which worked for me for version 5.

app.maker.make_crud:
    class: App\Maker\MakeCrudCommand
    arguments: ['@maker.doctrine_helper', '@maker.renderer.form_type_renderer']
    calls:
        - [configureCommand, ['@security.command.user_password_encoder', '@?']]
        - [interact, ['@?', '@?', '@security.command.user_password_encoder']]
    tags:
        - { name: maker.command }


问:
What is the best comment in source code you have ever encountered?
What is the best comment in source code you have ever encountered?</p>

答:
This is a comment of mine which I found today while refactoring some code</p>

```<code>if( year < 100 ): year += 2000 #lol, Y2K
</code>```

OwnerDisplayName: endpoint

LastEditorDisplayName: Brian

Body:
This is a comment of mine which I found today while refactoring some code

if( year < 100 ): year += 2000 #lol, Y2K

OwnerDisplayName: hasen j

ContentLicense: CC BY-SA 2.5


问:
How can I change the play speed of google bubble chart in R Shiny?
I am currently working on my project by using Shiny and google bubble charts.
My project looks very similar to the one in the shiny gallery (https://shiny.rstudio.com/gallery/google-charts.html). However, my dataset has many more years of data than this demo. I am wondering what argument I can use to increase the play speed from year to year?
Thank you.</p>

答:
sliderInput has a animationOptions feature with default set to 1000ms, just change that.

```<code>sliderInput(inputId, label, min, max, value, step = NULL,
  round = FALSE, format = NULL, locale = NULL, ticks = TRUE,
  animate = FALSE, width = NULL, sep = ",", pre = NULL,
  post = NULL, timeFormat = NULL, timezone = NULL,
  dragRange = TRUE)

animationOptions(interval = 1000, loop = FALSE, playButton = NULL,
  pauseButton = NULL)
</code>```

Body:
sliderInput has a animationOptions feature with default set to 1000ms, just change that.

sliderInput(inputId, label, min, max, value, step = NULL,
  round = FALSE, format = NULL, locale = NULL, ticks = TRUE,
  animate = FALSE, width = NULL, sep = ",", pre = NULL,
  post = NULL, timeFormat = NULL, timezone = NULL,
  dragRange = TRUE)

animationOptions(interval = 1000, loop = FALSE, playButton = NULL,
  pauseButton = NULL)


问:
Getting POSIX PATH from finder selection
I am trying to build a quick action able to ls the selected folder in finder, using automator with an applescript in it. I can't make it working. It always come back to the error " Can't get the POSIX Path". Here is my code so far : </p>

```<code>on run {input, parameters}
            tell application "Finder" to set theFiles to POSIX path of input
            tell application "Terminal"
                do shell script "ls " & theFiles
                activate
            end tell
            return theFiles
        end run
</code>```

<p>Thanks. </p>

答:
Here is an Automator Service I use that you can adapt to your liking:

on run {input, parameters}
    set theseFinderItems to {}
    repeat with aItem in input
        copy quoted form of POSIX path of aItem to end of theseFinderItems
        copy space to end of theseFinderItems
    end repeat
    tell application "Terminal"
        do script "ls -aleO@ " & theseFinderItems
    end tell
end run
```

<p><img src="https://i.stack.imgur.com/Kr6fN.png" alt="enter image description here"></p>

<p>Here is a sample output in <strong>Terminal</strong> when selecting the <strong>Finder</strong> <em>item</em> and then the<br> <strong>ls -aleO@ Finder Items</strong> <em>Service</em>, which in <strong>macOS Mojave</strong> and later is referred to as a <em>Quick Action</em>.</p>

<pre class="lang-none prettyprint-override"><code>$ ls -aleO@ '/Volumes/RAMDisk/CAT RP6500/Service Manual - CM20160617-56278-18523.pdf'
-rw-r--r--@ 1 me  staff  - 7061976 Jun  1 21:08 /Volumes/RAMDisk/CAT RP6500/Service Manual - CM20160617-56278-18523.pdf
    com.apple.lastuseddate#PS        16
    com.apple.metadata:kMDItemDownloadedDate         53
    com.apple.metadata:kMDItemWhereFroms        116
    com.apple.quarantine         57
$
</code>```

Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

Body:
I am trying to build a quick action able to ls the selected folder in finder, using automator with an applescript in it. I can't make it working. It always come back to the error " Can't get the POSIX Path". Here is my code so far :

on run {input, parameters}
            tell application "Finder" to set theFiles to POSIX path of input
            tell application "Terminal"
                do shell script "ls " & theFiles
                activate
            end tell
            return theFiles
        end run

Thanks.

Body:
Here is an Automator Service I use that you can adapt to your liking:

on run {input, parameters}
    set theseFinderItems to {}
    repeat with aItem in input
        copy quoted form of POSIX path of aItem to end of theseFinderItems
        copy space to end of theseFinderItems
    end repeat
    tell application "Terminal"
        do script "ls -aleO@ " & theseFinderItems
    end tell
end run

Here is a sample output in Terminal when selecting the Finder item and then the
 ls -aleO@ Finder Items Service, which in macOS Mojave and later is referred to as a Quick Action.

$ ls -aleO@ '/Volumes/RAMDisk/CAT RP6500/Service Manual - CM20160617-56278-18523.pdf'
-rw-r--r--@ 1 me  staff  - 7061976 Jun  1 21:08 /Volumes/RAMDisk/CAT RP6500/Service Manual - CM20160617-56278-18523.pdf
    com.apple.lastuseddate#PS        16
    com.apple.metadata:kMDItemDownloadedDate         53
    com.apple.metadata:kMDItemWhereFroms        116
    com.apple.quarantine         57
$

Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.


Title: Pandas - Calculate row values based on prior row value, update the result to be the new row value (and so on)

Body:
Below is some dummy data that reflects the data I am working with.

import pandas as pd
import numpy as np
from numpy import random

random.seed(30)

# Dummy data that represents a percent change
datelist = pd.date_range(start='1983-01-01', end='1994-01-01', freq='Y')
df1 = pd.DataFrame({"P Change_1": np.random.uniform(low=-0.55528, high=0.0396181, size=(11,)),
                   "P Change_2": np.random.uniform(low=-0.55528, high=0.0396181, size=(11,))})
#This dataframe contains the rows we want to operate on
df2 = pd.DataFrame({
    'Loc1': [None, None, None, None, None, None, None, None, None, None, 2.5415],
    'Loc2': [None, None, None, None, None, None, None, None, None, None, 3.2126],})

#Set the datetime index
df1 = df1.set_index(datelist)
df2 = df2.set_index(datelist)

df1:

            P Change_1  P Change_2
1984-12-31   -0.172080   -0.231574
1985-12-31   -0.328773   -0.247018
1986-12-31   -0.160834   -0.099079
1987-12-31   -0.457924    0.000266
1988-12-31    0.017374   -0.501916
1989-12-31   -0.349052   -0.438816
1990-12-31    0.034711    0.036164
1991-12-31   -0.415445   -0.415372
1992-12-31   -0.206852   -0.413107
1993-12-31   -0.313341   -0.181030
1994-12-31   -0.474234   -0.118058

df2:

              Loc1    Loc2
1984-12-31     NaN     NaN
1985-12-31     NaN     NaN
1986-12-31     NaN     NaN
1987-12-31     NaN     NaN
1988-12-31     NaN     NaN
1989-12-31     NaN     NaN
1990-12-31     NaN     NaN
1991-12-31     NaN     NaN
1992-12-31     NaN     NaN
1993-12-31     NaN     NaN
1994-12-31  2.5415  3.2126

DataFrame details:

First off, Loc1 will correspond with P Change_1 and Loc2 corresponds to P Change_2, etc. Looking at Loc1 first, I want to either fill up the DataFrame containing Loc1 and Loc2 with the relevant values or compute a new dataframe that has columns Calc1 and Calc2.

The calculation:

I want to start with the 1994 value of Loc1 and calculate a new value for 1993 by taking Loc1 1993 = Loc1 1994 + (Loc1 1994 * P Change_1 1993).  With the values filled in it would be 2.5415 +(-0.313341 * 2.5415) which equals about 1.74514.

This 1.74514 value will replace the NaN value in 1993, and then I want to use that calculated value to get a value for 1992.  This means we now compute Loc1 1992 = Loc1 1993 + (Loc1 1993 * P Change_1 1992).  I want to carry out this operation row-wise until it gets the earliest value in the timeseries.

What is the best way to go about implementing this row-wise equation?  I hope this makes some sense and any help is greatly appreciated!

Body:
[EDITED] Perhaps there are better/more elegant ways to do this, but this worked fine for me:

def fill_values(df1, df2, cols1=None, cols2=None):
    if cols1 is None: cols1 = df1.columns
    if cols2 is None: cols2 = df2.columns

    for i in reversed(range(df2.shape[0]-1)):
        for col1, col2 in zip(cols1, cols2):
            if np.isnan(df2[col2].iloc[i]):
                val = df2[col2].iloc[i+1] + df2[col2].iloc[i+1] * df1[col1].iloc[i]
                df2[col2].iloc[i] = val

    return df1, df2

df1, df2 = fill_values(df1, df2)

print(df2)

    Loc1    Loc2
1983-12-31  0.140160    0.136329
1984-12-31  0.169291    0.177413
1985-12-31  0.252212    0.235614
1986-12-31  0.300550    0.261526
1987-12-31  0.554444    0.261457
1988-12-31  0.544976    0.524925
1989-12-31  0.837202    0.935388
1990-12-31  0.809117    0.902741
1991-12-31  1.384158    1.544128
1992-12-31  1.745144    2.631024
1993-12-31  2.541500    3.212600

This assumes that the rows in df1 and df2 corresponds perfectly (I'm not querying the index, but only the location). Hope it helps!


问:
How do have both count and percent on barcharts in ggplot2? R
this is my data

```<code>data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c("5","7", "3"),
                   "Percent" = c("33%", "47%", "20%"))
</code>```

This is my plot

```<code>ggplot(data, aes(x=Name, y=Freq)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=data$Freq, vjust=-1)

</code>```

How can I have both my percent label next to my freq label preferably in parenthesis or separated by a comma?

答:
I think it is important that if you want to plot numeric variables you make sure they are numbers, rather than factors as in your example, otherwise the proportions will be wrong:

```<code>data$Freq <- as.numeric(as.character(data$Freq))
labs <- paste0(format(100 * data$Freq/sum(data$Freq), digits = 4), "%")

ggplot(data, aes(x=Name, y=Freq)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label = labs, vjust=-1) + coord_cartesian(ylim = c(0, 8))
</code>```

Body:
this is my data

data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c("5","7", "3"),
                   "Percent" = c("33%", "47%", "20%"))

This is my plot

ggplot(data, aes(x=Name, y=Freq)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=data$Freq, vjust=-1)

How can I have both my percent label next to my freq label preferably in parenthesis or separated by a comma?

Body:
I think it is important that if you want to plot numeric variables you make sure they are numbers, rather than factors as in your example, otherwise the proportions will be wrong:

data$Freq <- as.numeric(as.character(data$Freq))
labs <- paste0(format(100 * data$Freq/sum(data$Freq), digits = 4), "%")

ggplot(data, aes(x=Name, y=Freq)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label = labs, vjust=-1) + coord_cartesian(ylim = c(0, 8))


问:
sqlite3 & PHP results empty: object(SQLite3Result)#3 (0) { }
Im starting to use sqlite3 but I'am unable to get some results.
My database is called database.sqlite3

Inside SQLite command prompt and doing 'SELECT * FROM table'; . works fine. But im having problems with php.

```<code>$db = new SQLite3('db/database.sqlite3');
$result = $db->query('SELECT * FROM table');
var_dump( $result );
</code>```

The result of this code is : object(SQLite3Result)#3 (0) { }

What is worng here?

Thank you.

PD: $result->fetchArray(SQLITE3_ASSOC) works but only gives me one record... why???

答:
from the php doc, the return value of query:

Return Values

Returns an SQLite3Result object, or FALSE on failure.

Have a look at the fetcharray method of the Result object to see how to get (fetch) the the row data.

Body:
Im starting to use sqlite3 but I'am unable to get some results.
My database is called database.sqlite3

Inside SQLite command prompt and doing 'SELECT * FROM table'; . works fine. But im having problems with php.

$db = new SQLite3('db/database.sqlite3');
$result = $db->query('SELECT * FROM table');
var_dump( $result );

The result of this code is : object(SQLite3Result)#3 (0) { }

What is worng here?

Thank you.

PD: $result->fetchArray(SQLITE3_ASSOC) works but only gives me one record... why???


问:
Correct way to execute a function when I have function name
I have a string "Car.run(true)" or "Car.find('window')", I want to execute the function run or find and also pass respective parameters passed. What is the correct way to do it without using eval?

I tried to split the string, extracted the function name and parameters using regex but issue is with boolean values(it will a string after extraction).

Can anyone guide me to resolve this blocker?

答:
Generally using eval is not a good idea, and this isn't great either but it's a start:

function Car() {
  this.run = function(args) {
    console.log('Running', args)
  }
}

const str = "Car.run(true)";

// Get the constructor name and the function with arguments as a string
const [ctor, fn] = str.split('.');

// The name of the function without parens
const fnName = fn.replace(/\((.+)\)/, '')

// Get the argument list of the function
const originalArgs = fn.match(/\((.+)\)/)

// Clean arguments
const args = originalArgs[1]
  .split(',')
  .map(str => str.trim())
  .filter(Boolean);

// Instantiate a new object based on the name
const f = new(Function.prototype.bind.apply(window[ctor]))();

// Invoke the function with the arguments
f[fnName].apply(f, args) // Running  true```

General idea comes from the AngularJS source and how it instantiates objects from strings.

Body:
Generally using eval is not a good idea, and this isn't great either but it's a start:

function Car() {
  this.run = function(args) {
    console.log('Running', args)
  }
}

const str = "Car.run(true)";

// Get the constructor name and the function with arguments as a string
const [ctor, fn] = str.split('.');

// The name of the function without parens
const fnName = fn.replace(/\((.+)\)/, '')

// Get the argument list of the function
const originalArgs = fn.match(/\((.+)\)/)

// Clean arguments
const args = originalArgs[1]
  .split(',')
  .map(str => str.trim())
  .filter(Boolean);

// Instantiate a new object based on the name
const f = new(Function.prototype.bind.apply(window[ctor]))();

// Invoke the function with the arguments
f[fnName].apply(f, args) // Running  true

General idea comes from the AngularJS source and how it instantiates objects from strings.


问:
Build condition comparison for if statement
Is this possible?

```<code>$var_1 = 1;
$var_2 = 10;
$comparison = '>';

if($var_1 $comparison $var_2) {
    // do something...
}
</code>```

The syntax right now is not valid but is there a way to do this?

答:
Not natively (except of course with eval). You will need to evaluate the various expressions yourself. Build a wrapper function and use a switch statement. Or for non-expression comparisons a simple map:

```<code>$var_1 = 1;
$var_2 = 10;
$comparison = '>';

$map = array(
    ">" => $var_1 > $var_2,
    "<" => $var_1 < $var_2,
    "==" => $var_1 == $var_2,
    "!=" => $var_1 != $var_2,
);

if($map[$comparison]) {
    // do something...
}
</code>```

Body:
Is this possible?

$var_1 = 1;
$var_2 = 10;
$comparison = '>';

if($var_1 $comparison $var_2) {
    // do something...
}

The syntax right now is not valid but is there a way to do this?

Body:
Not natively (except of course with eval). You will need to evaluate the various expressions yourself. Build a wrapper function and use a switch statement. Or for non-expression comparisons a simple map:

$var_1 = 1;
$var_2 = 10;
$comparison = '>';

$map = array(
    ">" => $var_1 > $var_2,
    "<" => $var_1 < $var_2,
    "==" => $var_1 == $var_2,
    "!=" => $var_1 != $var_2,
);

if($map[$comparison]) {
    // do something...
}


问:
conditionally remove row in left join or prioritize value that to show
im having trouble creating a sql script which prioritize value on a left join. so this is the scenario.

i have this query

```<code>SELECT a.calc_id, a.eff_post_tmst, a.event_id, a.error_flag,
b.BC_PersonId,  'Test' AS submitted_by,818674 AS transaction_id,  e.PersonType
from dbo.cnv_pen_calc a
LEFT join dbo.cnv_PpToBcPersonIdMap b on a.person_id = b.PP_PersonId
INNER JOIN dbo.cdm_person e ON e.PersonId = b.BC_PersonId
where a.event_id = 'estimate' and a.error_flag = 0 AND a.calc_id = 100019 ORDER BY a.calc_id
</code>```

as you can see there was a left join in "cnv_PpToBcPersonIdMap" and "cnv_pen_calc" this caused duplicate calc_id on my query with different e.PersonType

this what the cnv_PpToBcPersonIdMap  data looks like

you can see that there are two records for this PP_personId that caused the duplicate of the query.

my main goal is if calc_id has duplicate like this image below

if the result has duplicate calc_ids query should display only data that has PersonType = 'Employee'
and if is doesn't have any duplicate calc_id it should leave as is.

is there a way do do that? im not expert in sql. thanks.

答:
Please use below query,</p>

```<code>select * from
(SELECT a.calc_id, a.eff_post_tmst, a.event_id, a.error_flag,
b.BC_PersonId,  'Test' AS submitted_by,818674 AS transaction_id,  e.PersonType,
row_number() over(partition by a.calc_id order by e.PersonType) as rnk
from dbo.cnv_pen_calc a
LEFT join dbo.cnv_PpToBcPersonIdMap b on a.person_id = b.PP_PersonId
INNER JOIN dbo.cdm_person e ON e.PersonId = b.BC_PersonId
where a.event_id = 'estimate' and a.error_flag = 0 AND a.calc_id = 100019 ORDER BY
a.calc_id) qry
where rnk = 1;
</code>```

Body:
im having trouble creating a sql script which prioritize value on a left join. so this is the scenario.

i have this query

SELECT a.calc_id, a.eff_post_tmst, a.event_id, a.error_flag,
b.BC_PersonId,  'Test' AS submitted_by,818674 AS transaction_id,  e.PersonType
from dbo.cnv_pen_calc a
LEFT join dbo.cnv_PpToBcPersonIdMap b on a.person_id = b.PP_PersonId
INNER JOIN dbo.cdm_person e ON e.PersonId = b.BC_PersonId
where a.event_id = 'estimate' and a.error_flag = 0 AND a.calc_id = 100019 ORDER BY a.calc_id

as you can see there was a left join in "cnv_PpToBcPersonIdMap" and "cnv_pen_calc" this caused duplicate calc_id on my query with different e.PersonType

this what the cnv_PpToBcPersonIdMap  data looks like

you can see that there are two records for this PP_personId that caused the duplicate of the query.

my main goal is if calc_id has duplicate like this image below

if the result has duplicate calc_ids query should display only data that has PersonType = 'Employee'
and if is doesn't have any duplicate calc_id it should leave as is.

is there a way do do that? im not expert in sql. thanks.

Body:
Please use below query,

select * from
(SELECT a.calc_id, a.eff_post_tmst, a.event_id, a.error_flag,
b.BC_PersonId,  'Test' AS submitted_by,818674 AS transaction_id,  e.PersonType,
row_number() over(partition by a.calc_id order by e.PersonType) as rnk
from dbo.cnv_pen_calc a
LEFT join dbo.cnv_PpToBcPersonIdMap b on a.person_id = b.PP_PersonId
INNER JOIN dbo.cdm_person e ON e.PersonId = b.BC_PersonId
where a.event_id = 'estimate' and a.error_flag = 0 AND a.calc_id = 100019 ORDER BY
a.calc_id) qry
where rnk = 1;


问:
SQL: display newest entry
I'm not really much of a developer, I only started self-learning VBA for Excel this year and I only started working with SQL two days ago...

That said: I'm trying to write a query that only shows the newest entry for each INVBTICKETNO based on ITTRANDATE but I can't seem to figure it out.

```<code>SELECT
  WHSNAME.WHSNNAME AS [Warehouse Name]
 ,VALID_BIN.BIN_TYPE AS T
 ,INVENTORY_BIN.INVBBINNO AS [Bin Number]
 ,INVENTORY_BIN.INVBITEMNO AS [Item Number]
 ,INVENTORY_ITEM_TAB.DESCR AS [Item Description]
 ,PRODUCT_CODE.DESCR AS [Product Code & Description]
 ,CUSTOMER.CSNAME AS [Customer Name]
 ,ORDERS.ORDER_NO AS [Oder No]
 ,INVENTORY_BIN.DATE_OF_INVENTORY AS [Date of Inventory]
 ,INVENTORY_BIN.INVBTICKETNO AS [Ticket No]
 ,INVENTORY_BIN.INVBQTYONHAND AS [Qty on Hand]
 ,ORDERS.QTY_ORDERED AS [Qty Ordered]
 ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT AS MSF
 ,INVENTORY_BIN.EXTENDED_CST AS [Valuation?]
 ,INVENTORY_TRAN.ITSOURCE AS Source
 ,INVENTORY_TRAN.ITCOMMENT AS Comment
 ,MAX(INVENTORY_TRAN.ITTRANDATE) AS [Trans Date]
 ,ORDERS.FOR_INVT_FLG AS Flag
 ,SALESAGENT.SANAME AS [Sales Agent]
 ,ORDERS.CUST_PO_NO AS [Customer PO No]
FROM dbo.INVENTORY_BIN INVENTORY_BIN
INNER JOIN dbo.INVENTORY_ITEM_TAB INVENTORY_ITEM_TAB
  ON INVENTORY_BIN.INVBITEMNO = INVENTORY_ITEM_TAB.ITEM_NO
INNER JOIN dbo.WHSNAME WHSNAME
  ON INVENTORY_BIN.INVBWHSNCODE = WHSNAME.WHSNCODE
INNER JOIN dbo.VALID_BIN VALID_BIN
  ON INVENTORY_BIN.INVBBINNO = VALID_BIN.BIN_ID
    AND INVENTORY_BIN.INVBWHSNCODE = VALID_BIN.WHSNCODE
LEFT OUTER JOIN dbo.INVENTORY_TRAN INVENTORY_TRAN
  ON INVENTORY_BIN.INVBTICKETNO = INVENTORY_TRAN.ITTICKETNO
    AND INVENTORY_BIN.DATE_LST_ACTIVITY < INVENTORY_TRAN.ITTRANDATE
LEFT OUTER JOIN dbo.CUSTOMER CUSTOMER
  ON INVENTORY_BIN.CSCODE = CUSTOMER.CSCODE
LEFT OUTER JOIN dbo.ORDERS ORDERS
  ON INVENTORY_BIN.ORDER_NO = ORDERS.ORDER_NO
INNER JOIN dbo.PRODUCT_CODE PRODUCT_CODE
  ON INVENTORY_ITEM_TAB.PROD_CD = PRODUCT_CODE.PROD_CD
LEFT OUTER JOIN dbo.SALESAGENT SALESAGENT
  ON CUSTOMER.SACODE = SALESAGENT.SACODE
WHERE ORDERS.FOR_INVT_FLG = 'R'
GROUP BY INVENTORY_BIN.INVBITEMNO
        ,INVENTORY_BIN.INVBBINNO
        ,INVENTORY_BIN.INVBQTYONHAND
        ,INVENTORY_BIN.DATE_OF_INVENTORY
        ,INVENTORY_BIN.EXTENDED_CST
        ,INVENTORY_ITEM_TAB.DESCR
        ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT
        ,WHSNAME.WHSNNAME
        ,VALID_BIN.BIN_TYPE
        ,INVENTORY_TRAN.ITSOURCE
        ,CUSTOMER.CSNAME
        ,ORDERS.ORDER_NO
        ,ORDERS.CUST_PO_NO
        ,ORDERS.QTY_ORDERED
        ,PRODUCT_CODE.DESCR
        ,SALESAGENT.SANAME
        ,ORDERS.FOR_INVT_FLG
        ,INVENTORY_BIN.INVBTICKETNO
        ,INVENTORY_TRAN.ITCOMMENT
ORDER BY [Date of Inventory]
</code>```

答:
I found https://kristiannielsen.livejournal.com/6745.html and implemented their "fastest" solution.

Except it doesn't seem very fast... 1 min 12 seconds for 217 rows returned. Do queries run slower if you're working remotely?

```<code>SELECT
  WHSNAME.WHSNNAME AS [Warehouse Name]
 ,VALID_BIN.BIN_TYPE AS T
 ,INVENTORY_BIN.INVBBINNO AS [Bin Number]
 ,INVENTORY_BIN.INVBITEMNO AS [Item Number]
 ,INVENTORY_ITEM_TAB.DESCR AS [Item Description]
 ,PRODUCT_CODE.DESCR AS [Product Code & Description]
 ,CUSTOMER.CSNAME AS [Customer Name]
 ,ORDERS.ORDER_NO AS [Order Number]
 ,INVENTORY_BIN.DATE_OF_INVENTORY AS [Date of Inventory]
 ,tra1.ITTICKETNO AS [Ticket Number]
 ,INVENTORY_BIN.INVBQTYONHAND AS [Qty on Hand]
 ,ORDERS.QTY_ORDERED AS [Qty Ordered]
 ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT AS MSF
 ,INVENTORY_BIN.EXTENDED_CST AS [Valuation?]
 ,tra1.ITSOURCE AS Source
 ,tra1.ITCOMMENT AS Comment
 ,tra1.ITTRANDATE AS [Trans Date]
 ,ORDERS.FOR_INVT_FLG AS Flag
 ,SALESAGENT.SANAME AS [Sales Agent]
 ,ORDERS.CUST_PO_NO AS [Customer PO Number]
FROM dbo.INVENTORY_TRAN tra1
**INNER JOIN (SELECT
    INVENTORY_TRAN.ITTICKETNO
   ,MAX(INVENTORY_TRAN.ITTRANDATE) AS ITTRANDATE
  FROM dbo.INVENTORY_TRAN
  GROUP BY INVENTORY_TRAN.ITTICKETNO) tra2
  ON tra1.ITTICKETNO = tra2.ITTICKETNO
    AND tra1.ITTRANDATE = tra2.ITTRANDATE**
INNER JOIN dbo.INVENTORY_BIN
  ON tra1.ITTICKETNO = INVENTORY_BIN.INVBTICKETNO
INNER JOIN dbo.INVENTORY_ITEM_TAB
  ON INVENTORY_BIN.INVBITEMNO = INVENTORY_ITEM_TAB.ITEM_NO
INNER JOIN dbo.PRODUCT_CODE
  ON INVENTORY_ITEM_TAB.PROD_CD = PRODUCT_CODE.PROD_CD
INNER JOIN dbo.ORDERS
  ON INVENTORY_BIN.ORDER_NO = ORDERS.ORDER_NO
INNER JOIN dbo.WHSNAME
  ON INVENTORY_BIN.INVBWHSNCODE = WHSNAME.WHSNCODE
INNER JOIN dbo.CUSTOMER
  ON INVENTORY_BIN.CSCODE = CUSTOMER.CSCODE
INNER JOIN dbo.SALESAGENT
  ON CUSTOMER.SACODE = SALESAGENT.SACODE
INNER JOIN dbo.VALID_BIN
  ON INVENTORY_BIN.INVBWHSNCODE = VALID_BIN.WHSNCODE
    AND VALID_BIN.BIN_ID = INVENTORY_BIN.INVBBINNO
WHERE ORDERS.FOR_INVT_FLG = 'R'
ORDER BY [Date of Inventory]
</code>```

Title: SQL: display newest entry

Body:
I'm not really much of a developer, I only started self-learning VBA for Excel this year and I only started working with SQL two days ago...

That said: I'm trying to write a query that only shows the newest entry for each INVBTICKETNO based on ITTRANDATE but I can't seem to figure it out.

SELECT
  WHSNAME.WHSNNAME AS [Warehouse Name]
 ,VALID_BIN.BIN_TYPE AS T
 ,INVENTORY_BIN.INVBBINNO AS [Bin Number]
 ,INVENTORY_BIN.INVBITEMNO AS [Item Number]
 ,INVENTORY_ITEM_TAB.DESCR AS [Item Description]
 ,PRODUCT_CODE.DESCR AS [Product Code & Description]
 ,CUSTOMER.CSNAME AS [Customer Name]
 ,ORDERS.ORDER_NO AS [Oder No]
 ,INVENTORY_BIN.DATE_OF_INVENTORY AS [Date of Inventory]
 ,INVENTORY_BIN.INVBTICKETNO AS [Ticket No]
 ,INVENTORY_BIN.INVBQTYONHAND AS [Qty on Hand]
 ,ORDERS.QTY_ORDERED AS [Qty Ordered]
 ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT AS MSF
 ,INVENTORY_BIN.EXTENDED_CST AS [Valuation?]
 ,INVENTORY_TRAN.ITSOURCE AS Source
 ,INVENTORY_TRAN.ITCOMMENT AS Comment
 ,MAX(INVENTORY_TRAN.ITTRANDATE) AS [Trans Date]
 ,ORDERS.FOR_INVT_FLG AS Flag
 ,SALESAGENT.SANAME AS [Sales Agent]
 ,ORDERS.CUST_PO_NO AS [Customer PO No]
FROM dbo.INVENTORY_BIN INVENTORY_BIN
INNER JOIN dbo.INVENTORY_ITEM_TAB INVENTORY_ITEM_TAB
  ON INVENTORY_BIN.INVBITEMNO = INVENTORY_ITEM_TAB.ITEM_NO
INNER JOIN dbo.WHSNAME WHSNAME
  ON INVENTORY_BIN.INVBWHSNCODE = WHSNAME.WHSNCODE
INNER JOIN dbo.VALID_BIN VALID_BIN
  ON INVENTORY_BIN.INVBBINNO = VALID_BIN.BIN_ID
    AND INVENTORY_BIN.INVBWHSNCODE = VALID_BIN.WHSNCODE
LEFT OUTER JOIN dbo.INVENTORY_TRAN INVENTORY_TRAN
  ON INVENTORY_BIN.INVBTICKETNO = INVENTORY_TRAN.ITTICKETNO
    AND INVENTORY_BIN.DATE_LST_ACTIVITY < INVENTORY_TRAN.ITTRANDATE
LEFT OUTER JOIN dbo.CUSTOMER CUSTOMER
  ON INVENTORY_BIN.CSCODE = CUSTOMER.CSCODE
LEFT OUTER JOIN dbo.ORDERS ORDERS
  ON INVENTORY_BIN.ORDER_NO = ORDERS.ORDER_NO
INNER JOIN dbo.PRODUCT_CODE PRODUCT_CODE
  ON INVENTORY_ITEM_TAB.PROD_CD = PRODUCT_CODE.PROD_CD
LEFT OUTER JOIN dbo.SALESAGENT SALESAGENT
  ON CUSTOMER.SACODE = SALESAGENT.SACODE
WHERE ORDERS.FOR_INVT_FLG = 'R'
GROUP BY INVENTORY_BIN.INVBITEMNO
        ,INVENTORY_BIN.INVBBINNO
        ,INVENTORY_BIN.INVBQTYONHAND
        ,INVENTORY_BIN.DATE_OF_INVENTORY
        ,INVENTORY_BIN.EXTENDED_CST
        ,INVENTORY_ITEM_TAB.DESCR
        ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT
        ,WHSNAME.WHSNNAME
        ,VALID_BIN.BIN_TYPE
        ,INVENTORY_TRAN.ITSOURCE
        ,CUSTOMER.CSNAME
        ,ORDERS.ORDER_NO
        ,ORDERS.CUST_PO_NO
        ,ORDERS.QTY_ORDERED
        ,PRODUCT_CODE.DESCR
        ,SALESAGENT.SANAME
        ,ORDERS.FOR_INVT_FLG
        ,INVENTORY_BIN.INVBTICKETNO
        ,INVENTORY_TRAN.ITCOMMENT
ORDER BY [Date of Inventory]

Body:
I found https://kristiannielsen.livejournal.com/6745.html and implemented their "fastest" solution.

Except it doesn't seem very fast... 1 min 12 seconds for 217 rows returned. Do queries run slower if you're working remotely?

SELECT
  WHSNAME.WHSNNAME AS [Warehouse Name]
 ,VALID_BIN.BIN_TYPE AS T
 ,INVENTORY_BIN.INVBBINNO AS [Bin Number]
 ,INVENTORY_BIN.INVBITEMNO AS [Item Number]
 ,INVENTORY_ITEM_TAB.DESCR AS [Item Description]
 ,PRODUCT_CODE.DESCR AS [Product Code & Description]
 ,CUSTOMER.CSNAME AS [Customer Name]
 ,ORDERS.ORDER_NO AS [Order Number]
 ,INVENTORY_BIN.DATE_OF_INVENTORY AS [Date of Inventory]
 ,tra1.ITTICKETNO AS [Ticket Number]
 ,INVENTORY_BIN.INVBQTYONHAND AS [Qty on Hand]
 ,ORDERS.QTY_ORDERED AS [Qty Ordered]
 ,INVENTORY_ITEM_TAB.SQUARE_FEET_UNIT AS MSF
 ,INVENTORY_BIN.EXTENDED_CST AS [Valuation?]
 ,tra1.ITSOURCE AS Source
 ,tra1.ITCOMMENT AS Comment
 ,tra1.ITTRANDATE AS [Trans Date]
 ,ORDERS.FOR_INVT_FLG AS Flag
 ,SALESAGENT.SANAME AS [Sales Agent]
 ,ORDERS.CUST_PO_NO AS [Customer PO Number]
FROM dbo.INVENTORY_TRAN tra1
**INNER JOIN (SELECT
    INVENTORY_TRAN.ITTICKETNO
   ,MAX(INVENTORY_TRAN.ITTRANDATE) AS ITTRANDATE
  FROM dbo.INVENTORY_TRAN
  GROUP BY INVENTORY_TRAN.ITTICKETNO) tra2
  ON tra1.ITTICKETNO = tra2.ITTICKETNO
    AND tra1.ITTRANDATE = tra2.ITTRANDATE**
INNER JOIN dbo.INVENTORY_BIN
  ON tra1.ITTICKETNO = INVENTORY_BIN.INVBTICKETNO
INNER JOIN dbo.INVENTORY_ITEM_TAB
  ON INVENTORY_BIN.INVBITEMNO = INVENTORY_ITEM_TAB.ITEM_NO
INNER JOIN dbo.PRODUCT_CODE
  ON INVENTORY_ITEM_TAB.PROD_CD = PRODUCT_CODE.PROD_CD
INNER JOIN dbo.ORDERS
  ON INVENTORY_BIN.ORDER_NO = ORDERS.ORDER_NO
INNER JOIN dbo.WHSNAME
  ON INVENTORY_BIN.INVBWHSNCODE = WHSNAME.WHSNCODE
INNER JOIN dbo.CUSTOMER
  ON INVENTORY_BIN.CSCODE = CUSTOMER.CSCODE
INNER JOIN dbo.SALESAGENT
  ON CUSTOMER.SACODE = SALESAGENT.SACODE
INNER JOIN dbo.VALID_BIN
  ON INVENTORY_BIN.INVBWHSNCODE = VALID_BIN.WHSNCODE
    AND VALID_BIN.BIN_ID = INVENTORY_BIN.INVBBINNO
WHERE ORDERS.FOR_INVT_FLG = 'R'
ORDER BY [Date of Inventory]


问:
Javascript required attribute not working with e.preventDefault
I have a form with inputs that have the required attribute.However, I dont want the form to be submitted normally, but it uses ajax.Thus, I set the form action to javascript:void(0) .But doing so, renders the required attribute useless.It doesn't work

How can I fix that?

This is my form

```<code><form action="javascript:void(0)"> <input name="email" required> </form>`
</code>```

答:
If you're doing the submit yourself you can check the validity of the form with

```<code>if (form.checkValidity()) {
  // submit via XHR etc...
} else {
  // the form is not valid
}
</code>```

See this and this

Body:
I have a form with inputs that have the required attribute.However, I dont want the form to be submitted normally, but it uses ajax.Thus, I set the form action to javascript:void(0) .But doing so, renders the required attribute useless.It doesn't work

How can I fix that?

This is my form

<form action="javascript:void(0)"> <input name="email" required> </form>`

Body:
If you're doing the submit yourself you can check the validity of the form with

if (form.checkValidity()) {
  // submit via XHR etc...
} else {
  // the form is not valid
}

See this and this


问:
How to install Visual Studio Code on Linux?
I have just downloaded VSCode-linux-x64 from the Microsoft website. It's a zip file called VSCode-linux-x64.zip. How can I install it on my Linux system?</p>

答:
Simplest way to install Visual Studio Code in Linux
I hope it useful.
Installing Visual Studio Code in Kali Linux - 4 simple steps

Update your system and install the below package.
```<code>sudo apt update
sudo apt install curl gpg software-properties-common apt-transport-https
</code>```

Importing Microsoft GPG key to Kali Linux
```<code>curl -sSL https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
</code>```

Adding APT repository for VS Code to Kali Linux
```<code> echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" | sudo tee /etc/apt/sources.list.d/vscode.list
</code>```

Installing VS Code
```<code>sudo apt update
sudo apt install code
</code>```

For reference:
https://youtu.be/ycIjQf0rOJI

Body:
Simplest way to install Visual Studio Code in Linux
I hope it useful.
Installing Visual Studio Code in Kali Linux - 4 simple steps

Update your system and install the below package.

sudo apt update
sudo apt install curl gpg software-properties-common apt-transport-https

Importing Microsoft GPG key to Kali Linux

curl -sSL https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -

Adding APT repository for VS Code to Kali Linux

 echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" | sudo tee /etc/apt/sources.list.d/vscode.list

Installing VS Code

sudo apt update
sudo apt install code

For reference:
https://youtu.be/ycIjQf0rOJI


问:
Alternative to regular PHP Class
Generally when creating a PHP class I would do something as such

```<code>class Foo
{
    public function Foo(){}
    public function RandomFunction(){};
}
global $foo;
$foo = new Foo();
$foo->RandomFunction();
</code>```

I have noticed that on the web people are frowning upon the global vars for classes but without it I would not be able to access the class inside other functions.

Now an alternative to this would be using static classes as such:

```<code>class Foo
{
    static public function RandomFunction(){}
}
Foo::RandomFunction();
</code>```

My Question is this, is this the best alternative to global vars for classes? Or is there a better way to go about it all together?

答:
Think of your object like a bicycle. You own your bicycle, and can loan it to whomever you wish. They can use it and return it to you, and you will be able to keep track of who did what to your bike, and when.

If your bike is generally available to anyone in the world, however, your job of monitoring and controlling access to it will become exponentially more difficult. You will be hard-pressed to keep track of who is using your bike, when they are using it, and how they are (ab)using it.

Passing your objects (rather than declaring them globally) allows you to maintain stricter controls on your object and the data it contains.

Title: Alternative to regular PHP Class

Body:
Generally when creating a PHP class I would do something as such

class Foo
{
    public function Foo(){}
    public function RandomFunction(){};
}
global $foo;
$foo = new Foo();
$foo->RandomFunction();

I have noticed that on the web people are frowning upon the global vars for classes but without it I would not be able to access the class inside other functions.

Now an alternative to this would be using static classes as such:

class Foo
{
    static public function RandomFunction(){}
}
Foo::RandomFunction();

My Question is this, is this the best alternative to global vars for classes? Or is there a better way to go about it all together?


问:
SQL to returns the value before last value in an ordered partition of a result set
I want to get a data into a new column (previous year end head count) after doing partition on the year and taking latest headcount value from that partition and setting it in the subsequent year for the new column.

Create table and insert data script:

```<code>    CREATE TABLE #test1(
        [DateTime] [date] NULL,
        [HeadCount] [int] NULL
    )
    GO
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-06-02' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-05-02' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-02-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-01-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-06-05' AS Date), 7)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-05-01' AS Date), 7)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-04-20' AS Date), 5)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-01-02' AS Date), 5)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-12-15' AS Date), 8)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-10-02' AS Date), 9)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-09-12' AS Date), 6)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-08-06' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-07-10' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-06-05' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-03-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-02-10' AS Date), 7)
</code>```

Solution I have tried:

```<code>    SELECT
    datetime,headcount,
    LAST_VALUE(headcount) OVER(
                PARTITION BY year(datetime)
            ORDER BY datetime desc
            RANGE BETWEEN
                UNBOUNDED PRECEDING AND
                UNBOUNDED FOLLOWING
        ) PrevYearEndHeadCnt
    FROM
        #test1 order by datetime desc
</code>```

Result I am getting vs expectation:

```<code>    datetime    headcount   PrevYearEndHeadCnt  Expected
    02-06-2020  2           3                   7
    02-05-2020  2           3                   7
    20-02-2020  3           3                   7
    20-01-2020  3           3                   7
    05-06-2019  7           5                   8
    01-05-2019  7           5                   8
    20-04-2019  5           5                   8
    02-01-2019  5           5                   8
    15-12-2018  8           7                   0
    02-10-2018  9           7                   0
    12-09-2018  6           7                   0
    06-08-2018  3           7                   0
    10-07-2018  2           7                   0
    05-06-2018  3           7                   0
    20-03-2018  3           7                   0
    10-02-2018  7           7                   0
</code>```

答:
```<code>with x as (
    select *,
           cnt = count(*) over (partition by year([DateTime])),
           rownum = row_number() over (partition by year([DateTime])
                                       order by [DateTime] desc)
    from #test1
)
select [DateTime],
       HeadCount,
       PrevYearEndHeadCnt = isnull(lead(HeadCount, cnt - rownum + 1)
                                   over(order by [DateTime] desc), 0)
from x order by [DateTime] desc;
</code>```

Body:
I want to get a data into a new column (previous year end head count) after doing partition on the year and taking latest headcount value from that partition and setting it in the subsequent year for the new column.

Create table and insert data script:

    CREATE TABLE #test1(
        [DateTime] [date] NULL,
        [HeadCount] [int] NULL
    )
    GO
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-06-02' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-05-02' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-02-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2020-01-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-06-05' AS Date), 7)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-05-01' AS Date), 7)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-04-20' AS Date), 5)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2019-01-02' AS Date), 5)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-12-15' AS Date), 8)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-10-02' AS Date), 9)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-09-12' AS Date), 6)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-08-06' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-07-10' AS Date), 2)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-06-05' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-03-20' AS Date), 3)
    INSERT #test1 ([DateTime], [HeadCount]) VALUES (CAST(N'2018-02-10' AS Date), 7)

Solution I have tried:

    SELECT
    datetime,headcount,
    LAST_VALUE(headcount) OVER(
                PARTITION BY year(datetime)
            ORDER BY datetime desc
            RANGE BETWEEN
                UNBOUNDED PRECEDING AND
                UNBOUNDED FOLLOWING
        ) PrevYearEndHeadCnt
    FROM
        #test1 order by datetime desc

Result I am getting vs expectation:

    datetime    headcount   PrevYearEndHeadCnt  Expected
    02-06-2020  2           3                   7
    02-05-2020  2           3                   7
    20-02-2020  3           3                   7
    20-01-2020  3           3                   7
    05-06-2019  7           5                   8
    01-05-2019  7           5                   8
    20-04-2019  5           5                   8
    02-01-2019  5           5                   8
    15-12-2018  8           7                   0
    02-10-2018  9           7                   0
    12-09-2018  6           7                   0
    06-08-2018  3           7                   0
    10-07-2018  2           7                   0
    05-06-2018  3           7                   0
    20-03-2018  3           7                   0
    10-02-2018  7           7                   0


问:
Getting error during implementing unique user name
I was watching this video.
https://www.youtube.com/watch?v=NLWHEiH1FZY

I want my Angular Firebase app with the user in such a way that no similar username repeated. But I'm getting two errors

Argument of type '(auth: User) => any[] | AngularFireObject' is not assignable to parameter of type '(value: User, index: number) => ObservableInput'.

Type 'any[] | AngularFireObject' is not assignable to type 'ObservableInput'.

Type 'AngularFireObject' is not assignable to type 'ObservableInput'.

Property '[Symbol.iterator]' is missing in type 'AngularFireObject' but required in type 'Iterable'.

My code is

```<code>export class User {
      uid: string;
      username: string = "";

      constructor(auth) {
        this.uid = auth.uid
      }
}
</code>```

Error occurs at

```<code>    this.afAuth.authState.pipe(
      switchMap(auth => {
        if (auth) {
          this.currentUser = new User(auth)
          return this.db.object(`users/${auth.uid}`) // getting error here
        } else return [];
      })
    )
</code>```

答:
When you use switchMap operator you need to return an observable. Try to return the valueChanges() method.

this.afAuth.authState.pipe(
  switchMap(auth => {
    if (auth) {
      this.currentUser = new User(auth);
      return this.db.object(`users/${auth.uid}`).valueChanges();   // <-- return `valueChanges()` here
    } else return of([]);      // <-- `of` method to return an observable
  })
)
```

Body:
I was watching this video.
https://www.youtube.com/watch?v=NLWHEiH1FZY

I want my Angular Firebase app with the user in such a way that no similar username repeated. But I'm getting two errors

Argument of type '(auth: User) => any[] | AngularFireObject' is not assignable to parameter of type '(value: User, index: number) => ObservableInput'.

Type 'any[] | AngularFireObject' is not assignable to type 'ObservableInput'.

Type 'AngularFireObject' is not assignable to type 'ObservableInput'.

Property '[Symbol.iterator]' is missing in type 'AngularFireObject' but required in type 'Iterable'.

My code is

export class User {
      uid: string;
      username: string = "";

      constructor(auth) {
        this.uid = auth.uid
      }
}

Error occurs at

    this.afAuth.authState.pipe(
      switchMap(auth => {
        if (auth) {
          this.currentUser = new User(auth)
          return this.db.object(`users/${auth.uid}`) // getting error here
        } else return [];
      })
    )


问:
SQL - Removing Row Groups
I have a table with the following information:

Is there a way to remove all groups which have multiple IDs? For example group 3 would be removed because it consists of ID 1 and 2.

Thank you!

答:
Try to execute below query:</p>

```<code>select id,group from table where group in
(
select group from(
select group,count(distinct id) as cn from table group by 1 having cn=1) a
)
</code>```

Title: SQL - Removing Row Groups

Body:
Try to execute below query:

select id,group from table where group in
(
select group from(
select group,count(distinct id) as cn from table group by 1 having cn=1) a
)


问:
Mongoose find (findOne) from a reference subDocument property array
So, I'm trying to use the poulate and match property but without any success, I couldn't find any documentation of my problem (I struggled to find a documentation about it too, so maybe you can provide me some source other then this)?)

Btw, I have this two models:

1 - Pages

```<code>const PageSchema = new Schema({
    name: String,
    organization: {
        type: Schema.Types.ObjectId,
        ref: 'organizations',
    },
})
</code>```

1 - Organizations

```<code>const OrganizationSchema = new Schema({
    name: String,
    domains: [{
        type: String,
        unique: true
    }],
})
</code>```

I need to find the page that belongs to a specific domain, so I was doing this findOne Query:

```<code>const page = await  Page.findOne({
    'settings.slug':  req.params.slug
}).populate({
    path: 'organization',
    match: {domains:"foo.com"},
}).exec()
</code>```

It doesn't make the "filter" and returns the pages that have an organization without the domain "foo.com"

I tried an even more easy approach but it doesn't work neither:

```<code>const presentation = await  Page.findOne({
    'organization.domains': host,
    'settings.slug':  req.params.slug
}).populate('organization')
</code>```

It returns always null.

Can someone help me? Many thanks

答:
I think the problem is in this line </p>

```<code>.populate({
    path: 'organization',  <---  you forgot an s //organizations as declared in you ref
</code>```

Body:
So, I'm trying to use the poulate and match property but without any success, I couldn't find any documentation of my problem (I struggled to find a documentation about it too, so maybe you can provide me some source other then this)?)

Btw, I have this two models:

1 - Pages

const PageSchema = new Schema({
    name: String,
    organization: {
        type: Schema.Types.ObjectId,
        ref: 'organizations',
    },
})

1 - Organizations

const OrganizationSchema = new Schema({
    name: String,
    domains: [{
        type: String,
        unique: true
    }],
})

I need to find the page that belongs to a specific domain, so I was doing this findOne Query:

const page = await  Page.findOne({
    'settings.slug':  req.params.slug
}).populate({
    path: 'organization',
    match: {domains:"foo.com"},
}).exec()

It doesn't make the "filter" and returns the pages that have an organization without the domain "foo.com"

I tried an even more easy approach but it doesn't work neither:

const presentation = await  Page.findOne({
    'organization.domains': host,
    'settings.slug':  req.params.slug
}).populate('organization')

It returns always null.

Can someone help me? Many thanks

Body:
I think the problem is in this line

.populate({
    path: 'organization',  <---  you forgot an s //organizations as declared in you ref


问:
How to convert a boolean variable to unsigned char in c++?
I want to convert a variable of type bool to an unsigned char variable, I tried the following code, but it doesn´t work.

enter image description here

答:
how about something like this?

#include <iostream>
using namespace std;
main() {
   bool my_bool;
   my_bool = true;
   cout << "The int equivalent of my_bool is: " << (unsigned char)(my_bool) << endl;
   my_bool = false;
   cout << "The int equivalent of my_bool is: " << (unsigned char)(my_bool);
}```