问:
Flask and React CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request
I am trying to connect my react frontend to my flask api backend. Note that flask-cors is already installed.

I initiated CORS as CORS(app) . the login passes but I keep getting this error when I go to project route:

Access to fetch at 'http://192.168.101.4:5000/project' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

My init.py file:

```<code>from flask import Flask, request, make_response

from .extensions import db, migrate, jwt, mail, CORS

from .models import TokenBlocklist

from .routes.base import base
from .routes.auth import auth
from .routes.core import core
from .routes.admin import admin
from .routes.user import user
from .routes.project import project

def create_app(config_file='config.py'):
    app = Flask(__name__)

    app.config.from_pyfile(config_file)

    @jwt.token_in_blocklist_loader
    def check_if_token_revoked(jtw_header, jwt_payload: dict)->bool:
        jti = jwt_payload['jti']
        token = db.session.query(TokenBlocklist.id).filter_by(jti=jti).scalar()

        return token is not None

    # initiate
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    mail.init_app(app)
    CORS(app)

    app.register_blueprint(base)
    app.register_blueprint(auth, url_prefix='/auth')
    app.register_blueprint(core, url_prefix='/core')
    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(user, url_prefix='/user')
    app.register_blueprint(project, url_prefix='/project')

    return app
</code>```

my auth.py:

```<code>"""
Route: endpoints for authentication
"""

from flask import Blueprint, jsonify, request, current_app, url_for, make_response
import datetime
import uuid
import validators
from itsdangerous import URLSafeTimedSerializer

from flask_jwt_extended import create_access_token, create_refresh_token, get_jwt_identity, jwt_required, unset_jwt_cookies, get_jwt, set_access_cookies, set_refresh_cookies
from werkzeug.security import generate_password_hash

from flask_cors import CORS

from ..utils import send_mail
from ..extensions import db, status, jwt
from ..models import User, TokenBlocklist

auth = Blueprint('auth', __name__)

CORS(auth)

@auth.route('/confirm-email/<token>')
def confirm_email(token):
    s = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])
    try:
        email = s.loads(token, salt='email-confirm', max_age=200)

        # mark user mail as confirmed
        user = User.query.filter_by(email=email).first()

        if not user.is_confirmed:
            user.is_confirmed = True
            db.session.commit()
        return jsonify(msg='email confirmed'), status.ok
    except:
        return jsonify(msg = False), status.bad

@auth.route('/register', methods=['POST'])
def register():
    """
    recieve request->username, email, password
    check username & email exists or not, if not hash password and store.
    send email with confirmation link
    """
    data = request.get_json()
    username = data['username']
    email = data['email']
    password = data['password']

    # check existance of requirements in request json
    if not username or not email or not password:
        return jsonify(msg='missing json data'), status.bad

    # email validations
    if not validators.email(email):
        return jsonify(msg='invalid email address'),

    # check if username and email is taken
    user = User.query.filter_by(username=username).first()
    if user:
        return jsonify(msg='username already taken')

    user = User.query.filter_by(email=email).first()
    if user:
        return jsonify(msg='email already taken')

    # save new user in db
    new_user = User(
        username = username,
        email = email,
        password = generate_password_hash(password, 'sha256'), # probably not a good practice to use User
        public_id = uuid.uuid4()
    )
    try:
        db.session.add(new_user)
        db.session.commit()
    except:
        return jsonify(msg='could not save')

    # create email confirmation link
    token = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])
    token = token.dumps(email, salt='email-confirm')
    link = url_for('auth.confirm_email', token=token, _external=True)

    # send mail
    body = f'confirmation link: {link}'

    mail_sent = send_mail(recipient=email, body=body, subject='Linkage Email Confirmation')

    if not mail_sent:
        return jsonify(msg= 'email could not be sent')

    return jsonify(msg= 'mail sent' ,email=email, token=token), 201

@auth.route('/login', methods=['POST'])
def login():
    """
    recieve json data->email, password
    check if email exists,
        check user's hashed password and if email is confirmed.
        generate refresh and access token and return
    """
    data = request.get_json()
    email = data['email']
    password = data['password']

    user = User.query.filter_by(email=email).first()

    # email not found
    if not user:
        return make_response(
            'User not found',
            401,
            {'WWW-Authenticate' : 'Basic realm ="could not verify"'}
        )

    # email found
    verified = user.verify_password(password)
    if verified is False:
        return make_response(
            'password mismatch',
            401,
            {'WWW-Authenticate' : 'Basic realm ="could not verify"'}
        )

    # authenticated, now generate tokens
    user_public_id = user.public_id
    refresh_token = create_refresh_token(identity=user_public_id)
    access_token = create_access_token(identity=user_public_id)

    # i am totally not sure about the following, but the fe dev *insists*
    response = jsonify({"x-access-token": access_token})
    response.set_cookie("refresh_token_cookie", refresh_token)

    return response, 200
</code>```

And Finally my project.py:

```<code>from datetime import datetime

from flask import Blueprint, jsonify, request, make_response
from flask_jwt_extended import get_jwt_identity, jwt_required

from ..extensions import db
from ..models import Project

project = Blueprint('project', __name__)

# this route must be deleted before production
@project.route('/', methods=['GET'])
@jwt_required()
def all_projects():
    user_public_id = get_jwt_identity()
    projects = Project.query.filter_by(user_public_id=user_public_id).all()
    projects_data = []

    for project in projects:
        project_data = {}
        project_data['id'] = project.id
        project_data['domain'] = project.domain
        project_data['name'] = project.name
        project_data['user_public_id'] = project.user_public_id
        project_data['wp_password'] = project.wp_password
        project_data['wp_username'] = project.wp_username
        project_data['date_added'] = project.date_added
        projects_data.append(project_data)

    return jsonify(projects = projects_data), 20

</code>```

CORS related configs in my config.py file:

```<code>#CORS
CORS_ALLOW_HEADERS = ['Content-Type', 'Authorization']
CORS_SUPPORTS_CREDENTIALS = True
CORS_HEADERS = ['Content-Type', 'Authorization']
</code>```

I am totally lost here. I don't know where is the redirect is happening.
Thank you for your time.

Body:
I am trying to connect my react frontend to my flask api backend. Note that flask-cors is already installed.

I initiated CORS as CORS(app) . the login passes but I keep getting this error when I go to project route:

Access to fetch at 'http://192.168.101.4:5000/project' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

My init.py file:

from flask import Flask, request, make_response

from .extensions import db, migrate, jwt, mail, CORS

from .models import TokenBlocklist

from .routes.base import base
from .routes.auth import auth
from .routes.core import core
from .routes.admin import admin
from .routes.user import user
from .routes.project import project

def create_app(config_file='config.py'):
    app = Flask(__name__)

    app.config.from_pyfile(config_file)

    @jwt.token_in_blocklist_loader
    def check_if_token_revoked(jtw_header, jwt_payload: dict)->bool:
        jti = jwt_payload['jti']
        token = db.session.query(TokenBlocklist.id).filter_by(jti=jti).scalar()

        return token is not None

    # initiate
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
    mail.init_app(app)
    CORS(app)

    app.register_blueprint(base)
    app.register_blueprint(auth, url_prefix='/auth')
    app.register_blueprint(core, url_prefix='/core')
    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(user, url_prefix='/user')
    app.register_blueprint(project, url_prefix='/project')

    return app

my auth.py:

"""
Route: endpoints for authentication
"""

from flask import Blueprint, jsonify, request, current_app, url_for, make_response
import datetime
import uuid
import validators
from itsdangerous import URLSafeTimedSerializer

from flask_jwt_extended import create_access_token, create_refresh_token, get_jwt_identity, jwt_required, unset_jwt_cookies, get_jwt, set_access_cookies, set_refresh_cookies
from werkzeug.security import generate_password_hash

from flask_cors import CORS

from ..utils import send_mail
from ..extensions import db, status, jwt
from ..models import User, TokenBlocklist

auth = Blueprint('auth', __name__)

CORS(auth)

@auth.route('/confirm-email/<token>')
def confirm_email(token):
    s = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])
    try:
        email = s.loads(token, salt='email-confirm', max_age=200)

        # mark user mail as confirmed
        user = User.query.filter_by(email=email).first()

        if not user.is_confirmed:
            user.is_confirmed = True
            db.session.commit()
        return jsonify(msg='email confirmed'), status.ok
    except:
        return jsonify(msg = False), status.bad

@auth.route('/register', methods=['POST'])
def register():
    """
    recieve request->username, email, password
    check username & email exists or not, if not hash password and store.
    send email with confirmation link
    """
    data = request.get_json()
    username = data['username']
    email = data['email']
    password = data['password']

    # check existance of requirements in request json
    if not username or not email or not password:
        return jsonify(msg='missing json data'), status.bad

    # email validations
    if not validators.email(email):
        return jsonify(msg='invalid email address'),

    # check if username and email is taken
    user = User.query.filter_by(username=username).first()
    if user:
        return jsonify(msg='username already taken')

    user = User.query.filter_by(email=email).first()
    if user:
        return jsonify(msg='email already taken')

    # save new user in db
    new_user = User(
        username = username,
        email = email,
        password = generate_password_hash(password, 'sha256'), # probably not a good practice to use User
        public_id = uuid.uuid4()
    )
    try:
        db.session.add(new_user)
        db.session.commit()
    except:
        return jsonify(msg='could not save')

    # create email confirmation link
    token = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])
    token = token.dumps(email, salt='email-confirm')
    link = url_for('auth.confirm_email', token=token, _external=True)

    # send mail
    body = f'confirmation link: {link}'

    mail_sent = send_mail(recipient=email, body=body, subject='Linkage Email Confirmation')

    if not mail_sent:
        return jsonify(msg= 'email could not be sent')

    return jsonify(msg= 'mail sent' ,email=email, token=token), 201

@auth.route('/login', methods=['POST'])
def login():
    """
    recieve json data->email, password
    check if email exists,
        check user's hashed password and if email is confirmed.
        generate refresh and access token and return
    """
    data = request.get_json()
    email = data['email']
    password = data['password']

    user = User.query.filter_by(email=email).first()

    # email not found
    if not user:
        return make_response(
            'User not found',
            401,
            {'WWW-Authenticate' : 'Basic realm ="could not verify"'}
        )

    # email found
    verified = user.verify_password(password)
    if verified is False:
        return make_response(
            'password mismatch',
            401,
            {'WWW-Authenticate' : 'Basic realm ="could not verify"'}
        )

    # authenticated, now generate tokens
    user_public_id = user.public_id
    refresh_token = create_refresh_token(identity=user_public_id)
    access_token = create_access_token(identity=user_public_id)

    # i am totally not sure about the following, but the fe dev *insists*
    response = jsonify({"x-access-token": access_token})
    response.set_cookie("refresh_token_cookie", refresh_token)

    return response, 200

And Finally my project.py:

from datetime import datetime

from flask import Blueprint, jsonify, request, make_response
from flask_jwt_extended import get_jwt_identity, jwt_required

from ..extensions import db
from ..models import Project

project = Blueprint('project', __name__)

# this route must be deleted before production
@project.route('/', methods=['GET'])
@jwt_required()
def all_projects():
    user_public_id = get_jwt_identity()
    projects = Project.query.filter_by(user_public_id=user_public_id).all()
    projects_data = []

    for project in projects:
        project_data = {}
        project_data['id'] = project.id
        project_data['domain'] = project.domain
        project_data['name'] = project.name
        project_data['user_public_id'] = project.user_public_id
        project_data['wp_password'] = project.wp_password
        project_data['wp_username'] = project.wp_username
        project_data['date_added'] = project.date_added
        projects_data.append(project_data)

    return jsonify(projects = projects_data), 20

CORS related configs in my config.py file:

#CORS
CORS_ALLOW_HEADERS = ['Content-Type', 'Authorization']
CORS_SUPPORTS_CREDENTIALS = True
CORS_HEADERS = ['Content-Type', 'Authorization']

I am totally lost here. I don't know where is the redirect is happening.
Thank you for your time.


来源: stackexchange

问:
Call a function when notification delivery succeeds - Firebase Messaging Android
Context: I'm building a chat app, and I want to let my users know if their recipient is successfully notified of the message that they sent.

Is there a way to check if the user was successfully notified of a notification on FCM Android?

I checked this article, which says that there is no way call a function when notification+data message is received in the background on Android. Is there at least a way to check if the notification delivery was successful?

I also found this article, which talks about how to measure notification success rate and run some statistic codes against it. If FCM collects notification success rate for Androids, I guess it is technically possible to also run our custom code when the notification is received. But idk how to.

ContentLicense: CC BY-SA 4.0


问:
How to write test for hooks by onclick method?
How do I write a test to activate the save button when I choose a date in the datepicker and the onclick function, which holds a state?here is a code snippet....</p>
```<code>
        if (selectedDate?.filter((e: any) => e.employeeId === employeeId).length > 0) {

            setSelectedDate(selectedDate.map((e: any) => {

                if (e.employeeId === employeeId) {

                    return { ...e, workAnniversary: value }

                }

                else {

                    return { ...e }

                }

            }))

        }

        else {

            setSelectedDate([...selectedDate, { employeeId: employeeId, workAnniversary: value }])

        }

        setIsDisabled(false);

    };
</code>```

Body:
How do I write a test to activate the save button when I choose a date in the datepicker and the onclick function, which holds a state?here is a code snippet....

        if (selectedDate?.filter((e: any) => e.employeeId === employeeId).length > 0) {

            setSelectedDate(selectedDate.map((e: any) => {

                if (e.employeeId === employeeId) {

                    return { ...e, workAnniversary: value }

                }

                else {

                    return { ...e }

                }

            }))

        }

        else {

            setSelectedDate([...selectedDate, { employeeId: employeeId, workAnniversary: value }])

        }

        setIsDisabled(false);

    };


问:
Invokehttp POST to public API fails
I am trying to ingest data from a public API using invoke HTTP processor on a secured Nifi cluster. I have imported the API's certificate to Nifi server cacerts but I am experiencing the error

```<code>Routing to failure due to exception: Failed to connect to sandbox-dxl.auth.eu-west1.amazon.com/52.51.xxx.xxx:443.
</code>```

I am able to ingest data from the same API when I run the pipeline from a local instance of Nifi in my laptop.

When I ping the API URL. I get the following error: says

```<code>Name or service not found
</code>```

Tried pinging the remote url. says Name or service not found

Title: Invokehttp POST to public API fails

Body:
I am trying to ingest data from a public API using invoke HTTP processor on a secured Nifi cluster. I have imported the API's certificate to Nifi server cacerts but I am experiencing the error

Routing to failure due to exception: Failed to connect to sandbox-dxl.auth.eu-west1.amazon.com/52.51.xxx.xxx:443.

I am able to ingest data from the same API when I run the pipeline from a local instance of Nifi in my laptop.

When I ping the API URL. I get the following error: says

Name or service not found

Tried pinging the remote url. says Name or service not found


问:
Windows Application Driver taking long time to detect UI
Windows Application driver is taking long time to detect UI even though it is present right in front of the screen. For the first few launches it works fine and then it gets rapidly slow to detect the UI. Any workaround to fix this issue even after using driver.quit?</p>


问:
use Scalene for FastAPI profiling
I'm currently trying to profile my FastAPI endpoints using Scalene. my code looks like this. I have a profiling middleware like this:

class ScaleneProfilerMiddleware(BaseHTTPMiddleware):

    def __init__(self, app):
        super().__init__(app)

    async def dispatch(self, request: Request, call_next):
        with _profiler() as profiler:
            response = await call_next(request)
            return _handle_response(profiler)
```
<p>and the <strong>_profiler()</strong> function should be something like this:</p>
<pre class="lang-py prettyprint-override"><code>@contextmanager
def _profiler():
    profiler = Scalene()
    try:
        profiler.start()
        yield profiler
    finally:
        profiler.stop()
</code>```

and I like to generate an HTML response right away using the _handle_response(response, profiler) which is something like this:

def _handle_response(
    profiler: Scalene
) -> Response:
    return HTMLResponse(profiler.generate_html())
```

I couldn't find any example like this so I'm wondering if this is possible at the moment

Title: use Scalene for FastAPI profiling

Body:
I'm currently trying to profile my FastAPI endpoints using Scalene. my code looks like this. I have a profiling middleware like this:

class ScaleneProfilerMiddleware(BaseHTTPMiddleware):

    def __init__(self, app):
        super().__init__(app)

    async def dispatch(self, request: Request, call_next):
        with _profiler() as profiler:
            response = await call_next(request)
            return _handle_response(profiler)

and the _profiler() function should be something like this:

@contextmanager
def _profiler():
    profiler = Scalene()
    try:
        profiler.start()
        yield profiler
    finally:
        profiler.stop()

and I like to generate an HTML response right away using the _handle_response(response, profiler) which is something like this:

def _handle_response(
    profiler: Scalene
) -> Response:
    return HTMLResponse(profiler.generate_html())

I couldn't find any example like this so I'm wondering if this is possible at the moment


问:
CUDA Runtime error when copying to element of jagged array
On the host I have a jagged array implemented with a vector of vector of ints.

To set up a jagged array on device, I started by allocating a pointer to a pointer of ints:

```<code>int **   adjlist;    // host pointer
int ** d_adjlist;    // device pointer
</code>```

Just to clarify some terminology, I am calling the array of pointers adjlist the "base", and the arrays that are pointed to adjlist[i] the "teeth".

```<code>// this is the width of the base
const int ens_size = 12;

// allocate the base on the device
cutilSafeCall( cudaMalloc( (void***)&d_adjlist, ens_size*sizeof(int*) ) );

// to store the contents of base on host (I can't cudaMalloc the teeth directly, as that would require dereferencing a pointer to device memory)
adjlist = static_cast<int**>( malloc( ens_size*sizeof(int*) ) );

// copy the contents of base from the device to the host
cutilSafeCall( cudaMemcpy( adjlist, d_adjlist, ens_size*sizeof(int*), cudaMemcpyDeviceToHost) );
</code>```

This all works fine, now the base is done. The original vector of vectors I mentioned at the beginning is stored at nets[i]->adjlist. Now I allocate the teeth with the following loop:

```<code>int N = 6;
int numNets = 2;

for(int i=0; i < numNets; ++i)
{
    for(int j=0; j < N; ++j)
    {
        k = nets[i]->adjlist[j].size();

        // allocate the "teeth" of the adjacency list
        cutilSafeCall( cudaMalloc( (void**)&(adjlist[N*i+j]), k ) );
    }
 }
</code>```

My problem arises when I go to copy the teeth from the vector of vectors to the teeth on the device, here is the code:

```<code>// this holds the tooth to be copied to the device
int h_adjlist[Kmax];    // k <= Kmax

for(int i=0; i < numNets; ++i)
{
    for(int j=0; j < N; ++j)
    {
        k = nets[i]->adjlist[j].size();

        // copy the adjacency list of the (Ni+j)-th node
        copy( nets[i]->adjlist[j].begin(), nets[i]->adjlist[j].end(), h_adjlist );

        cutilSafeCall( cudaMemcpy( adjlist[N*i+j],
                                   h_adjlist,
                                   sizeof(int)*k,
                                   cudaMemcpyHostToDevice ) );

    }
}
</code>```

When I try to run the code, I get a Runtime API error: invalid argument. error on the line:

```<code>                                   cudaMemcpyHostToDevice ) );
</code>```

At least that is the line where the cudaSafeCall function says the error occurs.

Why is this being flagged as an invalid argument? Or if it is some other argument, which one?

ContentLicense: CC BY-SA 3.0

Body:
On the host I have a jagged array implemented with a vector of vector of ints.

To set up a jagged array on device, I started by allocating a pointer to a pointer of ints:

int **   adjlist;    // host pointer
int ** d_adjlist;    // device pointer

Just to clarify some terminology, I am calling the array of pointers adjlist the "base", and the arrays that are pointed to adjlist[i] the "teeth".

// this is the width of the base
const int ens_size = 12;

// allocate the base on the device
cutilSafeCall( cudaMalloc( (void***)&d_adjlist, ens_size*sizeof(int*) ) );

// to store the contents of base on host (I can't cudaMalloc the teeth directly, as that would require dereferencing a pointer to device memory)
adjlist = static_cast<int**>( malloc( ens_size*sizeof(int*) ) );

// copy the contents of base from the device to the host
cutilSafeCall( cudaMemcpy( adjlist, d_adjlist, ens_size*sizeof(int*), cudaMemcpyDeviceToHost) );

This all works fine, now the base is done. The original vector of vectors I mentioned at the beginning is stored at nets[i]->adjlist. Now I allocate the teeth with the following loop:

int N = 6;
int numNets = 2;

for(int i=0; i < numNets; ++i)
{
    for(int j=0; j < N; ++j)
    {
        k = nets[i]->adjlist[j].size();

        // allocate the "teeth" of the adjacency list
        cutilSafeCall( cudaMalloc( (void**)&(adjlist[N*i+j]), k ) );
    }
 }

My problem arises when I go to copy the teeth from the vector of vectors to the teeth on the device, here is the code:

// this holds the tooth to be copied to the device
int h_adjlist[Kmax];    // k <= Kmax

for(int i=0; i < numNets; ++i)
{
    for(int j=0; j < N; ++j)
    {
        k = nets[i]->adjlist[j].size();

        // copy the adjacency list of the (Ni+j)-th node
        copy( nets[i]->adjlist[j].begin(), nets[i]->adjlist[j].end(), h_adjlist );

        cutilSafeCall( cudaMemcpy( adjlist[N*i+j],
                                   h_adjlist,
                                   sizeof(int)*k,
                                   cudaMemcpyHostToDevice ) );

    }
}

When I try to run the code, I get a Runtime API error: invalid argument. error on the line:

                                   cudaMemcpyHostToDevice ) );

At least that is the line where the cudaSafeCall function says the error occurs.

Why is this being flagged as an invalid argument? Or if it is some other argument, which one?


问:
Why is the ng-click inserted records twice sometimes in angularjs
I've got a Submit button that's used to insert item:

                              `
    <button type="button" id="subbtn" class="btn btn-success margin-t12" ng-click="Submit();">Submit</button> //button
    <button type="button" class="btn btn-default margin-t12" ng-click="back();">Cancel</button>

```
<p>Now when I press the Submit button I noticed sometime the item inserted twice with same details.  I applied below solution already but the issue not resolved yet.</p>
<pre class="lang-js prettyprint-override"><code>    $('#subbtn').attr("disabled", 'disabled'); //button disable
    setTimeout(function () {
      $('#subbtn').removeAttr("disabled")
    }, 10000);
</code>```

I'm just wondering what I've overlooked...

Body:
I've got a Submit button that's used to insert item:

                              `
    <button type="button" id="subbtn" class="btn btn-success margin-t12" ng-click="Submit();">Submit</button> //button
    <button type="button" class="btn btn-default margin-t12" ng-click="back();">Cancel</button>

Now when I press the Submit button I noticed sometime the item inserted twice with same details.  I applied below solution already but the issue not resolved yet.

    $('#subbtn').attr("disabled", 'disabled'); //button disable
    setTimeout(function () {
      $('#subbtn').removeAttr("disabled")
    }, 10000);

I'm just wondering what I've overlooked...


问:
Binary Search Tree Algorithm (BST) currentNode = self
class BST:
def init(self, value):
self.value = value
self.left = None
self.right = None

```<code>def insert(self, value):
    currentNode = self
    print(currentNode)
    while True:
        if value < currentNode.value:
            if currentNode.left is None:
                currentNode.left = BST(value)
                break
            else:
                currentNode = currentNode.left
        else:
            if currentNode.right is None:
                currentNode.right = BST(value)
                break
            else:
                currentNode = currentNode.right
        return self
</code>```

I am confused about currentNode = self. What value is this referring to? I am assuming that the 'value' is referring to the value from the parameter but where would currentNode.value come from, the init constructor?

Body:
class BST:
def init(self, value):
self.value = value
self.left = None
self.right = None

def insert(self, value):
    currentNode = self
    print(currentNode)
    while True:
        if value < currentNode.value:
            if currentNode.left is None:
                currentNode.left = BST(value)
                break
            else:
                currentNode = currentNode.left
        else:
            if currentNode.right is None:
                currentNode.right = BST(value)
                break
            else:
                currentNode = currentNode.right
        return self

I am confused about currentNode = self. What value is this referring to? I am assuming that the 'value' is referring to the value from the parameter but where would currentNode.value come from, the init constructor?


问:
I'm trying to call one vehicle api from another service . But when calling that api from my service class it's giving error 405 Method Not Allowed
This is another code(This is for vehicle service)This is working fine

public ResponseEntity updateByVehicleId(Vehicle vehicle, BigInteger id) {
    if (id == null || id.compareTo(BigInteger.ZERO) < 0) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid id");
    }

    if (vehicle == null) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid vehicle object");
    }

    Vehicle mod = repository.findById(id).orElseThrow(() -> new NoSuchElementException("Vehicle not found with id " + id));

    vehicle.setModifiedDate(new Date());
    repository.save(vehicle);

    return ResponseEntity.status(HttpStatus.OK).body("vehicle details modified successfully");
}
```
<p>This is the code I'm using for Vehicle management service</p>
<pre class="lang-java prettyprint-override"><code>public Vehicle updateByVehicleId(Vehicle vehicle,BigInteger id) {
    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<Vehicle> request = new HttpEntity<>(vehicle);

    ResponseEntity<Vehicle> response = restTemplate.exchange(RESTTEMPLATE_GET_BY_VEHICLE_ID, HttpMethod.PUT, request, Vehicle.class, id);

    return response.getBody();
}
</code>```

Controller class from which vehicle is called.

public static final String GET_BY_VEHICLE_ID = "/vehicle/{id}";

@PutMapping(GET_BY_VEHICLE_ID)
public Vehicle updateByVehicleId(@PathVariable BigInteger id,@RequestBody Vehicle vehicle) {

    logger.info("Log level:updated vehicle details");

    return vmsService.updateByVehicleId(vehicle,id);
}
```

I have to make a call to vehicle from vehicle management service.

I'm trying to update all the vehicle details using vehicle id and there are two services: one is vehicle and another one is vehicle management service

When I'm trying to update the details in vehicle it's working fine. But, same thing when I'm trying to create a REST template for this api it's not updating the data instead it's giving error:

{Request processing failed; nested exception is
org.springframework.web.client.HttpClientErrorException$MethodNotAllowed:
405 Method Not Allowed: [no body]}.

This is the request I'm sending in the postman

This is error on console

Body:
This is another code(This is for vehicle service)This is working fine

public ResponseEntity updateByVehicleId(Vehicle vehicle, BigInteger id) {
    if (id == null || id.compareTo(BigInteger.ZERO) < 0) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid id");
    }

    if (vehicle == null) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid vehicle object");
    }

    Vehicle mod = repository.findById(id).orElseThrow(() -> new NoSuchElementException("Vehicle not found with id " + id));

    vehicle.setModifiedDate(new Date());
    repository.save(vehicle);

    return ResponseEntity.status(HttpStatus.OK).body("vehicle details modified successfully");
}

This is the code I'm using for Vehicle management service

public Vehicle updateByVehicleId(Vehicle vehicle,BigInteger id) {
    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<Vehicle> request = new HttpEntity<>(vehicle);

    ResponseEntity<Vehicle> response = restTemplate.exchange(RESTTEMPLATE_GET_BY_VEHICLE_ID, HttpMethod.PUT, request, Vehicle.class, id);

    return response.getBody();
}

Controller class from which vehicle is called.

public static final String GET_BY_VEHICLE_ID = "/vehicle/{id}";

@PutMapping(GET_BY_VEHICLE_ID)
public Vehicle updateByVehicleId(@PathVariable BigInteger id,@RequestBody Vehicle vehicle) {

    logger.info("Log level:updated vehicle details");

    return vmsService.updateByVehicleId(vehicle,id);
}

I have to make a call to vehicle from vehicle management service.

I'm trying to update all the vehicle details using vehicle id and there are two services: one is vehicle and another one is vehicle management service

When I'm trying to update the details in vehicle it's working fine. But, same thing when I'm trying to create a REST template for this api it's not updating the data instead it's giving error:

{Request processing failed; nested exception is
org.springframework.web.client.HttpClientErrorException$MethodNotAllowed:
405 Method Not Allowed: [no body]}.

This is the request I'm sending in the postman

This is error on console


问:
Why can't I run includes on values of an object in typescript?
Why do I get typescript errors on this?

```<code>const myObj = {
  a: "1",
  b: "2",
  c: "3"
} as const;

const hasFour = Object.values(myObj).includes("4");
// Argument of type '"4"' is not assignable to parameter of type '"1" | "2" | "3"'.ts(2345)
</code>```

I would expect typescript to know that the result is an array of strings. Why do I need to cast the Object.values to string[] first? Why isn't this inferred?

Body:
Why do I get typescript errors on this?

const myObj = {
  a: "1",
  b: "2",
  c: "3"
} as const;

const hasFour = Object.values(myObj).includes("4");
// Argument of type '"4"' is not assignable to parameter of type '"1" | "2" | "3"'.ts(2345)

I would expect typescript to know that the result is an array of strings. Why do I need to cast the Object.values to string[] first? Why isn't this inferred?


问:
Text to speech not working on iOS in the background
I am unable to play an audio that is generated in the background using text to speech plugin flutter_tts on iOS only.

I am getting the following error:

```<code>2023-01-11 09:52:04.095673+0400 Runner[12016:2350386] [AXTTSCommon] Failure starting audio queue alp!
2023-01-11 09:52:05.218595+0400 Runner[12016:2350386] [AXTTSCommon] _BeginSpeaking: couldn't begin playback
</code>```

Background Settings in info.plist

```<code><key>UIBackgroundModes</key>
    <array>
        <string>audio</string>
        <string>fetch</string>
        <string>location</string>
        <string>processing</string>
    </array>
</code>```

Speaker Configuration

```<code>Future<void> initializeSpeaker() async {
    speakerPlugin = FlutterTts();
    speakerPlugin.setQueueMode(0);

    /////////////////////////////
    //Selecting voices
    ////////////////////////////
    var voices = await speakerPlugin.getVoices;

    //example {name: ur-PK-language, locale: ur-PK}

    String deviceLanguage= Platform.localeName.substring(0,2);
    int defaultvoiceix = 0;
    String userlocale = "en-gb";

    try {
      String languageCode = Platform.localeName.split('_')[0];
      String countryCode = Platform.localeName.split('_')[1];
      userlocale = languageCode + "-"+countryCode;
    } catch (exception) {
      userlocale = "en-gb";
    }

    for (var i=0;i<voices.length;i++) {
      String currentLocale = voices[i]["locale"];
      if (currentLocale.toLowerCase() == userlocale.toLowerCase()){
        defaultvoiceix = i;
      }
    }

    await speakerPlugin.setSharedInstance(true);
    await speakerPlugin.setVoice(voices[defaultvoiceix]);
    await speakerPlugin.setVolume(1.0);
    await speakerPlugin.setSpeechRate(1.0);
    await speakerPlugin.setPitch(1.0);
    await speakerPlugin.setLanguage(userlocale);
    await speakerPlugin
        .setIosAudioCategory(IosTextToSpeechAudioCategory.playback, [
      IosTextToSpeechAudioCategoryOptions.mixWithOthers,
      IosTextToSpeechAudioCategoryOptions.duckOthers
    ]);

  }
</code>```

Body:
I am unable to play an audio that is generated in the background using text to speech plugin flutter_tts on iOS only.

I am getting the following error:

2023-01-11 09:52:04.095673+0400 Runner[12016:2350386] [AXTTSCommon] Failure starting audio queue alp!
2023-01-11 09:52:05.218595+0400 Runner[12016:2350386] [AXTTSCommon] _BeginSpeaking: couldn't begin playback

Background Settings in info.plist

<key>UIBackgroundModes</key>
    <array>
        <string>audio</string>
        <string>fetch</string>
        <string>location</string>
        <string>processing</string>
    </array>

Speaker Configuration

Future<void> initializeSpeaker() async {
    speakerPlugin = FlutterTts();
    speakerPlugin.setQueueMode(0);

    /////////////////////////////
    //Selecting voices
    ////////////////////////////
    var voices = await speakerPlugin.getVoices;

    //example {name: ur-PK-language, locale: ur-PK}

    String deviceLanguage= Platform.localeName.substring(0,2);
    int defaultvoiceix = 0;
    String userlocale = "en-gb";

    try {
      String languageCode = Platform.localeName.split('_')[0];
      String countryCode = Platform.localeName.split('_')[1];
      userlocale = languageCode + "-"+countryCode;
    } catch (exception) {
      userlocale = "en-gb";
    }

    for (var i=0;i<voices.length;i++) {
      String currentLocale = voices[i]["locale"];
      if (currentLocale.toLowerCase() == userlocale.toLowerCase()){
        defaultvoiceix = i;
      }
    }

    await speakerPlugin.setSharedInstance(true);
    await speakerPlugin.setVoice(voices[defaultvoiceix]);
    await speakerPlugin.setVolume(1.0);
    await speakerPlugin.setSpeechRate(1.0);
    await speakerPlugin.setPitch(1.0);
    await speakerPlugin.setLanguage(userlocale);
    await speakerPlugin
        .setIosAudioCategory(IosTextToSpeechAudioCategory.playback, [
      IosTextToSpeechAudioCategoryOptions.mixWithOthers,
      IosTextToSpeechAudioCategoryOptions.duckOthers
    ]);

  }


问:
How to create an array with the number of elements that increases with conditions?
I want to create an array whose number of elements starts with one and is incremented by one when a certain condition is met, but when running I find that when the number of elements increases to 8, it no longer increases, why

```<code>#include<iostream>
int main()
{
    int a,e,re,n=1;
    int arr[n];
    scanf("%d%d",&a,&e);
    for(int i=0;i<n;i++)
    {
        if(a%e<0) re=a%e-e;
        else re=a%e;
        arr[i]=re;
        a=(a-re)/e;
        if(a!=0) n++;
        else break;
    }
    for(int i=n-1;i>=0;i--)
    {
        printf("%d",arr[i]);
    }
}
</code>```

This is a base-converted code, when I convert 3 to negative binary, the result is 111, but when I convert 30000 to negative binary, the result is 011110000, but the correct answer should be 11011010101110000, why

Body:
I want to create an array whose number of elements starts with one and is incremented by one when a certain condition is met, but when running I find that when the number of elements increases to 8, it no longer increases, why

#include<iostream>
int main()
{
    int a,e,re,n=1;
    int arr[n];
    scanf("%d%d",&a,&e);
    for(int i=0;i<n;i++)
    {
        if(a%e<0) re=a%e-e;
        else re=a%e;
        arr[i]=re;
        a=(a-re)/e;
        if(a!=0) n++;
        else break;
    }
    for(int i=n-1;i>=0;i--)
    {
        printf("%d",arr[i]);
    }
}

This is a base-converted code, when I convert 3 to negative binary, the result is 111, but when I convert 30000 to negative binary, the result is 011110000, but the correct answer should be 11011010101110000, why


问:
How to WHITELIST our CUSTOMER's domain to our internally deployed Google Sheets ADD-ON?
We have developed a small Google Sheets add-on. Due to some specific reasons and also because of the tedious verification process, we decided to deploy the add-on internally. For example, Company "Banana" (ours) wants to give an access to our add-on "FruitCutter" to our customer called "Pineapple".

The add-on works fine for our internal users. Everyone can install the add-on and use it. However, since we are planning to give an access to our customer, we want to whitelist the domain of our customer.

I have logged in with the admin profile and tried to add the domain to the whitelisted domains. But I don't think it is working as I expected.

Could anyone guide me on this domain whitelisting process? Even the documentation/support materials seem to contain this information, I could not find the relevant info to my case.

Thank you in advance!


问:
how to map *& in SWIG?
I have the below code in c++, p is a person array.

void GetPersonArrayRef(Person*& p)
{
    Person* plist = p;
    for (int i = 0; i < 5; i++)
    {
        std::cout << (plist[i].name) << std::endl;
    }
    Person p0, p1, p2;
    p0.name = "0name";
    p1.name = "1name";
    p2.name = "2name";
    Person* a = new Person[3]{ p0,p1,p2 };
    p = a;
}
```

the generated c# type is SWIGTYPE_p_p_Person of Person*&.

I want to call the method like this GetPersonArrayRef(ref Person[] list) in c# code. Can someone help?

If can't do like above, can give me any other tips?

Title: how to map *& in SWIG?

Body:
I have the below code in c++, p is a person array.

void GetPersonArrayRef(Person*& p)
{
    Person* plist = p;
    for (int i = 0; i < 5; i++)
    {
        std::cout << (plist[i].name) << std::endl;
    }
    Person p0, p1, p2;
    p0.name = "0name";
    p1.name = "1name";
    p2.name = "2name";
    Person* a = new Person[3]{ p0,p1,p2 };
    p = a;
}

the generated c# type is SWIGTYPE_p_p_Person of Person*&.

I want to call the method like this GetPersonArrayRef(ref Person[] list) in c# code. Can someone help?

If can't do like above, can give me any other tips?


问:
base64_decode is not working with php8.1 & magento 2.4.4
We are using Magento 2.4.4 on php8.1 and one of the magento core file is having a method which is using base64_decode() method.
Can you please suggest alternate of base64_decode();

$filterString = base64_decode($filterString);


问:
MUI Datatables expandable Row - Add a column before expandableRow icon
I want to add a column before expandable row Icon

In the Material-UI library's  component, the expandable rows feature can be implemented by setting the expandableRows property to "true". I Want to add a column before the expandable row icon.
(https://i.stack.imgur.com/D22ON.png)

expected : click

please find MUIDatatables demo code here
https://codesandbox.io/s/19r60?file=/src/ExpandableRowTable.js

import React from "react";
import MUIDataTable from "mui-datatables";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";

// const Card = () => (
//

//
//

//         lorem ipsum dorel em quol acee, vion, bloolw, wafeo, feiwjfoiew,
//         foiwejifowefjweoi, fewjoewjfowei, fwefwefewfewfewf
//

//
//

// );

const ExpandableRowTable = props => {
  const columns = [
    {
      name: "Name"
    },
    {
      name: "Title"
    },
    {
      name: "Location"
    },
    {
      name: "Age"
    },
    {
      name: "Salary"
    }
  ];
  const data = [
    ["Gabby George", "Business Analyst", "Minneapolis", 30, 100000],
    ["Business Analyst", "Business Consultant", "Dallas", 55, 200000],
    ["Jaden Collins", "Attorney", "Santa Ana", 27, 500000],
    ["Franky Rees", "Business Analyst", "St. Petersburg", 22, 50000],
    ["Aaren Rose", "Business Consultant", "Toledo", 28, 75000],
    ["Blake Duncan", "Business Management Analyst", "San Diego", 65, 94000],
    ["Frankie Parry", "Agency Legal Counsel", "Jacksonville", 71, 210000],
    ["Lane Wilson", "Commercial Specialist", "Omaha", 19, 65000],
    ["Robin Duncan", "Business Analyst", "Los Angeles", 20, 77000],
    ["Mel Brooks", "Business Consultant", "Oklahoma City", 37, 135000],
    ["Harper White", "Attorney", "Pittsburgh", 52, 420000],
    ["Kris Humphrey", "Agency Legal Counsel", "Laredo", 30, 150000],
    ["Frankie Long", "Industrial Analyst", "Austin", 31, 170000],
    ["Brynn Robbins", "Business Analyst", "Norfolk", 22, 90000],
    ["Justice Mann", "Business Consultant", "Chicago", 24, 133000],
    ["Addison Navarro", "Business Management Analyst", "New York", 50, 295000],
    ["Jesse Welch", "Agency Legal Counsel", "Seattle", 28, 200000],
    ["Eli Mejia", "Commercial Specialist", "Long Beach", 65, 400000],
    ["Gene Leblanc", "Industrial Analyst", "Hartford", 34, 110000],
    ["Danny Leon", "Computer Scientist", "Newark", 60, 220000],
    ["Lane Lee", "Corporate Counselor", "Cincinnati", 52, 180000],
    ["Jesse Hall", "Business Analyst", "Baltimore", 44, 99000],
    ["Danni Hudson", "Agency Legal Counsel", "Tampa", 37, 90000],
    ["Terry Macdonald", "Commercial Specialist", "Miami", 39, 140000],
    ["Justice Mccarthy", "Attorney", "Tucson", 26, 330000],
    ["Silver Carey", "Computer Scientist", "Memphis", 47, 250000],
    ["Franky Miles", "Industrial Analyst", "Buffalo", 49, 190000],
    ["Glen Nixon", "Corporate Counselor", "Arlington", 44, 80000],
    [
      "Gabby Strickland",
      "Business Process Consultant",
      "Scottsdale",
      26,
      45000
    ],
    ["Mason Ray", "Computer Scientist", "San Francisco", 39, 142000]
  ];

  function createData(name, calories, fat, carbs, protein) {
    return { name, calories, fat, carbs, protein };
  }

  const rows = [
    createData("Frozen yoghurt", 159, 6.0, 24, 4.0),
    createData("Ice cream sandwich", 237, 9.0, 37, 4.3),
    createData("Eclair", 262, 16.0, 24, 6.0),
    createData("Cupcake", 305, 3.7, 67, 4.3),
    createData("Gingerbread", 356, 16.0, 49, 3.9)
  ];

  const options = {
    filter: true,
    onFilterChange: (changedColumn, filterList) => {
      console.log(changedColumn, filterList);
    },
    selectableRows: "single",
    filterType: "dropdown",
    responsive: "scrollMaxHeight",
    rowsPerPage: 10,
    expandableRows: true,
    renderExpandableRow: (rowData, rowMeta) => {
      console.log(rowData, rowMeta);
      return (
        <React.Fragment>

              <TableContainer component={Paper}>

                  <TableHead>
                    <TableRow>
                      <TableCell>Dessert (100g serving)</TableCell>
                      <TableCell align="right">Calories</TableCell>
                      <TableCell align="right">Fat (g)</TableCell>
                      <TableCell align="right">Carbs (g)</TableCell>
                      <TableCell align="right">Calories</TableCell>
                      <TableCell align="right">Fat (g)</TableCell>
                      <TableCell align="right">Calories</TableCell>
                      <TableCell align="right">Fat (g)</TableCell>
                      <TableCell align="right">Protein (g)</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {rows.map(row => (
                      <TableRow key={row.name}>
                        <TableCell component="th" scope="row">
                          {row.name}
                        </TableCell>
                        <TableCell align="right">{row.calories}</TableCell>
                        <TableCell align="right">{row.fat}</TableCell>
                        <TableCell align="right">{row.carbs}</TableCell>
                        <TableCell align="right">{row.protein}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>

              </TableContainer>

              <TableContainer component={Paper}>

                  <TableHead>
                    <TableRow>
                      <TableCell>Dessert (100g serving)</TableCell>
                      <TableCell align="right">Calories</TableCell>
                      <TableCell align="right">Fat (g)</TableCell>
                      <TableCell align="right">Carbs (g)</TableCell>
                      <TableCell align="right">Protein (g)</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {rows.map(row => (
                      <TableRow key={row.name}>
                        <TableCell component="th" scope="row">
                          {row.name}
                        </TableCell>
                        <TableCell align="right">{row.calories}</TableCell>
                        <TableCell align="right">{row.fat}</TableCell>
                        <TableCell align="right">{row.carbs}</TableCell>
                        <TableCell align="right">{row.protein}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>

              </TableContainer>

        </React.Fragment>
      );
    },
    page: 1
  };

  return (
    <MUIDataTable
      title={"ACME Employee list"}
      data={data}
      columns={columns}
      options={options}
    />
  );
};

export default ExpandableRowTable;```


问:
width of sampler2D must be the multiple of 16
As the topic say, the sampler2D binding to a texture which is storage to 125x94, 125 is width, 94 is height,when I use texelFetch(sampler2D, ivec2(0, 1), 0),the 128th number is token, seems like width is 128 not 125,why?

Is there some docs to prove that,thanks.


问:
SQL Database promblem with ports and accessing
So i am trying to make a SQL database for my minecraft plugin

when i was making this database it said 3306 port was in use so i used 3307 , but afterward i thought its better to replace the 3306 port with this one , and deleted SQL in task manager
and after that this error keeps poping up

my goal is to make this database able to be reached from other places not only my localhost

i am new in this database this area
any comment will be very helpful

i tried deleting SQL in task manager
i tried going on the web to search how to solve this problem


问:
Dagger hilt missing binding issue. cannot be provided without an @Provides-annotated method
I have started using dagger hilt. I have seen many tutorials and implemented basic sample. But i have discovered a issue that i have not being able to resolve. Although i have seen many questions on stackoverflow, but with no success. My code below,

Error log:

```<code>/Users/Shared/Previously Relocated Items/Security/Bitbucket_android/NotesAppApplication/app/build/generated/hilt/component_sources/debug/com/abc/noteSample/api/NoteApplication_HiltComponents.java:132: error: [Dagger/MissingBinding] com.abc.noteSample.api.NoteAPI cannot be provided without an @Provides-annotated method.
  public abstract static class SingletonC implements NoteApplication_GeneratedInjector,
                         ^
      com.abc.noteSample.api.NoteAPI is injected at
          com.abc.noteSample.repository.NoteRepository(noteAPI)
      com.abc.noteSample.repository.NoteRepository is injected at
          com.abc.noteSample.ui.note.NoteViewModel(noteRepository)
      com.abc.noteSample.ui.note.NoteViewModel is injected at
          com.abc.noteSample.ui.note.NoteViewModel_HiltModules.BindsModule.binds(arg0)
      @dagger.hilt.android.internal.lifecycle.HiltViewModelMap java.util.Map<java.lang.String,javax.inject.Provider<androidx.lifecycle.ViewModel>> is requested at
          dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.ViewModelFactoriesEntryPoint.getHiltViewModelMap() [com.abc.noteSample.api.NoteApplication_HiltComponents.SingletonC → com.abc.noteSample.api.NoteApplication_HiltComponents.ActivityRetainedC → com.abc.noteSample.api.NoteApplication_HiltComponents.ViewModelC]
</code>```

Application class

```<code>@HiltAndroidApp
class NoteApplication : Application() {
}
</code>```

Interface

```<code>interface NoteAPI {

    @FormUrlEncoded
    @POST("GetPendingOrdersByManagerId")
    suspend fun getPendingOrders(@Field("AuthCode") AuthCode: String,
                                 @Field("ManagerId") ManagerLoginId: String,
                                 @Field("PageNumber") PageNumber: String) : Response<PendingResponse>
}
</code>```

Network class

```<code>@InstallIn(SingletonComponent::class)
@Module
class NetworkModule {

    @Provides
    @Singleton
    fun providesRetrofit() : Retrofit {
        return Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASE_URL)
            .build()
    }

    @Provides
    @Singleton
    fun providesUserApi(retrofit : Retrofit) : UserApi {
        return retrofit.create(UserApi::class.java)
    }
}
</code>```

Repository class

```<code>class NoteRepository @Inject constructor(private val noteAPI: NoteAPI) {

    private val _pendingLiveData = MutableLiveData<NetworkResult<PendingResponse>>()
    val pendingLiveData get() = _pendingLiveData

    suspend fun pendingOrders(pendingRequest: PendingRequest) {
        _pendingLiveData.postValue(NetworkResult.Loading())
        val response = noteAPI.getPendingOrders(pendingRequest.AuthCode,pendingRequest.ManagerId,pendingRequest.PageNumber)
        if (response.isSuccessful && response.body() != null) {
            _pendingLiveData.postValue(NetworkResult.Success(response.body()!!))
        }
        else if (response.errorBody() != null) {
            val errorObj = JSONObject(response.errorBody()!!.charStream().readText())
            _pendingLiveData.postValue(NetworkResult.Error(errorObj.getString("message")))
        }
        else {
            _pendingLiveData.postValue(NetworkResult.Error("Something went wrong"))
        }
    }
}
</code>```

View Model

```<code>@HiltViewModel
class NoteViewModel @Inject constructor(private val noteRepository: NoteRepository) : ViewModel(){

    val pendingLiveData get() = noteRepository.pendingLiveData

    fun getPendingOrders(pendingRequest: PendingRequest) {
        viewModelScope.launch {
            noteRepository.pendingOrders(pendingRequest)
        }
    }
}
</code>```

Calling Fragment

```<code>@AndroidEntryPoint
class MainFragment : Fragment() {

    private var _binding : FragmentMainBinding? = null
    private val binding get() = _binding!!
    private val noteViewModel by viewModels<NoteViewModel>()

    private lateinit var adapter: NoteAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        _binding = FragmentMainBinding.inflate(inflater,container,false)
        adapter = NoteAdapter()

        // Inflate the layout for this fragment
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        noteViewModel.getPendingOrders(PendingRequest("YWRtaW46MTIzNA==","19","1"))

       // binding.noteList.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
       // binding.noteList.adapter = adapter

        bindObserver()
    }
}
</code>```

Kindly point out issue

Body:
I have started using dagger hilt. I have seen many tutorials and implemented basic sample. But i have discovered a issue that i have not being able to resolve. Although i have seen many questions on stackoverflow, but with no success. My code below,

Error log:

/Users/Shared/Previously Relocated Items/Security/Bitbucket_android/NotesAppApplication/app/build/generated/hilt/component_sources/debug/com/abc/noteSample/api/NoteApplication_HiltComponents.java:132: error: [Dagger/MissingBinding] com.abc.noteSample.api.NoteAPI cannot be provided without an @Provides-annotated method.
  public abstract static class SingletonC implements NoteApplication_GeneratedInjector,
                         ^
      com.abc.noteSample.api.NoteAPI is injected at
          com.abc.noteSample.repository.NoteRepository(noteAPI)
      com.abc.noteSample.repository.NoteRepository is injected at
          com.abc.noteSample.ui.note.NoteViewModel(noteRepository)
      com.abc.noteSample.ui.note.NoteViewModel is injected at
          com.abc.noteSample.ui.note.NoteViewModel_HiltModules.BindsModule.binds(arg0)
      @dagger.hilt.android.internal.lifecycle.HiltViewModelMap java.util.Map<java.lang.String,javax.inject.Provider<androidx.lifecycle.ViewModel>> is requested at
          dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.ViewModelFactoriesEntryPoint.getHiltViewModelMap() [com.abc.noteSample.api.NoteApplication_HiltComponents.SingletonC → com.abc.noteSample.api.NoteApplication_HiltComponents.ActivityRetainedC → com.abc.noteSample.api.NoteApplication_HiltComponents.ViewModelC]

Application class

@HiltAndroidApp
class NoteApplication : Application() {
}

Interface

interface NoteAPI {

    @FormUrlEncoded
    @POST("GetPendingOrdersByManagerId")
    suspend fun getPendingOrders(@Field("AuthCode") AuthCode: String,
                                 @Field("ManagerId") ManagerLoginId: String,
                                 @Field("PageNumber") PageNumber: String) : Response<PendingResponse>
}

Network class

@InstallIn(SingletonComponent::class)
@Module
class NetworkModule {

    @Provides
    @Singleton
    fun providesRetrofit() : Retrofit {
        return Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASE_URL)
            .build()
    }

    @Provides
    @Singleton
    fun providesUserApi(retrofit : Retrofit) : UserApi {
        return retrofit.create(UserApi::class.java)
    }
}

Repository class

class NoteRepository @Inject constructor(private val noteAPI: NoteAPI) {

    private val _pendingLiveData = MutableLiveData<NetworkResult<PendingResponse>>()
    val pendingLiveData get() = _pendingLiveData

    suspend fun pendingOrders(pendingRequest: PendingRequest) {
        _pendingLiveData.postValue(NetworkResult.Loading())
        val response = noteAPI.getPendingOrders(pendingRequest.AuthCode,pendingRequest.ManagerId,pendingRequest.PageNumber)
        if (response.isSuccessful && response.body() != null) {
            _pendingLiveData.postValue(NetworkResult.Success(response.body()!!))
        }
        else if (response.errorBody() != null) {
            val errorObj = JSONObject(response.errorBody()!!.charStream().readText())
            _pendingLiveData.postValue(NetworkResult.Error(errorObj.getString("message")))
        }
        else {
            _pendingLiveData.postValue(NetworkResult.Error("Something went wrong"))
        }
    }
}

View Model

@HiltViewModel
class NoteViewModel @Inject constructor(private val noteRepository: NoteRepository) : ViewModel(){

    val pendingLiveData get() = noteRepository.pendingLiveData

    fun getPendingOrders(pendingRequest: PendingRequest) {
        viewModelScope.launch {
            noteRepository.pendingOrders(pendingRequest)
        }
    }
}

Calling Fragment

@AndroidEntryPoint
class MainFragment : Fragment() {

    private var _binding : FragmentMainBinding? = null
    private val binding get() = _binding!!
    private val noteViewModel by viewModels<NoteViewModel>()

    private lateinit var adapter: NoteAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        _binding = FragmentMainBinding.inflate(inflater,container,false)
        adapter = NoteAdapter()

        // Inflate the layout for this fragment
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        noteViewModel.getPendingOrders(PendingRequest("YWRtaW46MTIzNA==","19","1"))

       // binding.noteList.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
       // binding.noteList.adapter = adapter

        bindObserver()
    }
}

Kindly point out issue


问:
how can i change the time counter on a coming soon template in slider revolution
I tried to add coming soon slider revolution template on my site but i can't find where to set the time counter.

I checked the FAQ on their official site and found a solution to my problem but it didn't explain it well and couldn't solve my problem.


问:
Mcprotocol - Getting Error code - BAD 255
We're using nodejs mcprotocol library to pole periodic data from Mitsubishi Electric PLC-FX5U-64M after every 1 minute and saving it to mongodb collection.

We've added 1 tag named as Tag_1 with configuration as

{
      'tagname' : 'Tag_1',
      'type' : 'number',
      'address' : 'D10',
      'tagsize' : 2
}
```

But when we read the tag value we're getting error of something went wrong writing values with status code and actual data as BAD 255.MC protocol BAD 255
Please refer to attached image for the same.
Thank you.

We've so far tried by changing the address series to test for another Tag of D sereis, but still the BAD 255 code continues.

Body:
We're using nodejs mcprotocol library to pole periodic data from Mitsubishi Electric PLC-FX5U-64M after every 1 minute and saving it to mongodb collection.

We've added 1 tag named as Tag_1 with configuration as

{
      'tagname' : 'Tag_1',
      'type' : 'number',
      'address' : 'D10',
      'tagsize' : 2
}

But when we read the tag value we're getting error of something went wrong writing values with status code and actual data as BAD 255.MC protocol BAD 255
Please refer to attached image for the same.
Thank you.

We've so far tried by changing the address series to test for another Tag of D sereis, but still the BAD 255 code continues.


问:
edit multiple rows data from text and table using same button in jquery 3.5
I want to enable editing multiple data field after clicking the edit button. There are multiple data need to change. I want to click on a cell (col/row) and that cell value will change to a textbox (editable). After the user edit the value, it will save the each edited data.

Here is the code snippet...

```<code><div class="table-responsive">
          <table class="table table-bordered table-dark">
            <thead>
              <tr>
                <th scope="col">Personal Account</th>
                <th scope="col">Beginning</th>
                <th scope="col">End</th>
                <th scope="col">Returns*</th>
                <th scope="col">S&P 500***</th>
                <th scope="col">Nasdaq***</th>
              </tr>
            </thead>
            <tbody>
              <tr class="table-primary input-data">
                <td>Inception</td>
                <td class="start-date" readonly='readonly'>7/31/2008</td>
                <td class="end-date" readonly='readonly'>12/1/2022</td>
                <td>22.69%</td>
                <td>15.69%</td>
                <td>27.87%</td>
              </tr>
              <tr class="table-primary input-data">
                <td>Last 12 months</td>
                <td class="start-date">12/31/2021</td>
                <td class="end-date">12/1/2022</td>
                <td>-31.90%</td>
                <td>-15.99%</td>
                <td>-29.41%</td>
              </tr>
              <tr class="table-primary input-data">
                <td>Last 3 years</td>
                <td class="start-date">12/31/2019</td>
                <td class="end-date">12/1/2022</td>
                <td>15.39%</td>
                <td>9.10%</td>
                <td>9.72%</td>
              </tr>
              <tr class="table-primary input-data">
                <td>Last 5 years</td>
                <td class="start-date">12/31/2017</td>
                <td class="end-date">12/1/2022</td>
                <td>14.95%</td>
                <td>10.85%</td>
                <td>13.71%</td>
              </tr>
            </tbody>
          </table>
        </div>
</code>```

I want to use the latest version of jquery and ajax.

```<code> $('#edit-record').click(function() {
  $(this).hide();
  $('#save-data, #cancel').show();
    if (edit-record {
      $(this).prop('contenteditable', true).css({
        'background': '#fff',
        'color': '#000'
      })
    } else {
      $(this).prop('contenteditable', false).removeAttr("style");
    }
  });

  $('#cancel').click(function() {
    $('#edit-record').show();
    $('#save-data, #cancel').hide();
  });

  $('#save-data').click(function() {
    $(this).hide();
    $('#cancel').hide();
    $('#edit-record').show();
  });
</code>```

Body:
I want to enable editing multiple data field after clicking the edit button. There are multiple data need to change. I want to click on a cell (col/row) and that cell value will change to a textbox (editable). After the user edit the value, it will save the each edited data.

Here is the code snippet...

                Personal Account
                Beginning
                End
                Returns*
                S&P 500***
                Nasdaq***

                Inception
                7/31/2008
                12/1/2022
                22.69%
                15.69%
                27.87%

                Last 12 months
                12/31/2021
                12/1/2022
                -31.90%
                -15.99%
                -29.41%

                Last 3 years
                12/31/2019
                12/1/2022
                15.39%
                9.10%
                9.72%

                Last 5 years
                12/31/2017
                12/1/2022
                14.95%
                10.85%
                13.71%

I want to use the latest version of jquery and ajax.

 $('#edit-record').click(function() {
  $(this).hide();
  $('#save-data, #cancel').show();
    if (edit-record {
      $(this).prop('contenteditable', true).css({
        'background': '#fff',
        'color': '#000'
      })
    } else {
      $(this).prop('contenteditable', false).removeAttr("style");
    }
  });

  $('#cancel').click(function() {
    $('#edit-record').show();
    $('#save-data, #cancel').hide();
  });

  $('#save-data').click(function() {
    $(this).hide();
    $('#cancel').hide();
    $('#edit-record').show();
  });


问:
mongodb join array of result to single document
i have used this schema

```<code>    conversation_id: 12345,
    time: time,
    members: ['user1', 'user2'],
    messages: [
      {
         sender: 'user1',
         message: 'Hello World',
         timestamp: time
      },
      {
         sender: 'user1',
         message: 'Hello World',
         timestamp: time
      }],
   total_messages: 2
}
</code>```

but i need to know how to get all the results by sorted

```<code>
db.chats.aggregate(
    {
        /**
         * query: The query in MQL.
         */
        $match: {
          "members": {
            "$all": [
                ObjectId('63ad8631e0d6cfe452b80677'),
                ObjectId('63adadf287e482e6f128ec0e'),
            ]
          }
        },
    },
    {
        /**
         * Provide any number of field/order pairs.
         */
        $sort: {
          "created_at": -1
        }
    },
    {
        /**
         * specifications: The fields to
         *   include or exclude.
         */
        $project: {
            "_id": 0,
            // "members": 1,
            "result": {
                $sortArray: {input: "$message", sortBy: {created_at: -1}}
            }
        }
    },
)
</code>```

I have used this.. but thing is every things are in result block and I want it to in one array so I can fetch previous messages with $limit and $skip so I can send back to API of user message..
here is my sample data

```<code>[
  {
    "result": [
      {
        "uuid": "df359053-5b69-4fc3-ac42-57aaf70ec9d9",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00011",
        "created_at": {
          "$date": "2023-01-10T19:52:26Z"
        }
      },
      {
        "uuid": "0cfe04ab-ccf2-4eb9-8760-d3471f033ea6",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00010",
        "created_at": {
          "$date": "2023-01-10T19:52:15Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "fe54bf97-5dad-4d3f-ada8-ea1f1ab31039",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00010",
        "created_at": {
          "$date": "2023-01-10T19:52:14Z"
        }
      },
      {
        "uuid": "9face81d-b989-4662-a090-2f8f498b1a7b",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00010",
        "created_at": {
          "$date": "2023-01-10T19:52:12Z"
        }
      },
      {
        "uuid": "8578ce16-f3ac-4ceb-b779-0c1f3e8fec2f",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00010",
        "created_at": {
          "$date": "2023-01-10T19:51:02Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "ef6f12e0-b601-4377-8ff9-28921799985b",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00009",
        "created_at": {
          "$date": "2023-01-10T19:51:00Z"
        }
      },
      {
        "uuid": "6fcbcc3b-ff09-4e1c-9ce5-d73790911592",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00008",
        "created_at": {
          "$date": "2023-01-10T19:50:47Z"
        }
      },
      {
        "uuid": "fdde26cd-6688-466a-be61-37ac8e312a70",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00007",
        "created_at": {
          "$date": "2023-01-10T19:49:33Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "fdde26cd-6688-466a-be61-37ac8e312a70",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00007",
        "created_at": {
          "$date": "2023-01-10T19:49:33Z"
        }
      },
      {
        "uuid": "fb72bef2-ceff-4e22-80cd-b54da6ba6f01",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00006",
        "created_at": {
          "$date": "2023-01-10T19:48:51Z"
        }
      },
      {
        "uuid": "3ffee1e6-8eb4-4a93-99a2-329576dc7754",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00005",
        "created_at": {
          "$date": "2023-01-10T19:48:34Z"
        }
      },
      {
        "uuid": "927726bd-acc9-461b-98db-9ce07cca5ff0",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00004",
        "created_at": {
          "$date": "2023-01-10T19:48:31Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "927726bd-acc9-461b-98db-9ce07cca5ff0",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00004",
        "created_at": {
          "$date": "2023-01-10T19:48:31Z"
        }
      },
      {
        "uuid": "664cb8fb-0284-4ad2-af1f-d9458fb09c24",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00003",
        "created_at": {
          "$date": "2023-01-10T19:48:25Z"
        }
      },
      {
        "uuid": "460e8a5a-327f-47c9-a8c3-76772cca4cc7",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      },
      {
        "uuid": "ed4e5060-45f9-4f4a-a6a0-e45eddbd64bc",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "a45e6738-afb4-47aa-a8f4-fdf1d70eeb5f",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      },
      {
        "uuid": "466b8569-12c4-4d06-8572-eb5999f0e4ae",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      },
      {
        "uuid": "314b60eb-1eaf-4a72-a7a6-528ab474a0d9",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      },
      {
        "uuid": "460e8a5a-327f-47c9-a8c3-76772cca4cc7",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "a45e6738-afb4-47aa-a8f4-fdf1d70eeb5f",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      },
      {
        "uuid": "4f56f58d-1b0c-48f9-b3b6-c63020068760",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:21:55Z"
        }
      },
      {
        "uuid": "4fb86042-93ef-4209-88ca-8c287f16a2f6",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00001",
        "created_at": {
          "$date": "2023-01-10T19:20:30Z"
        }
      },
      {
        "uuid": "3a6dc43d-bdb5-41b9-be93-15ab389380a9",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "New Docu ",
        "created_at": {
          "$date": "2023-01-10T18:44:01Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "69b1dd00-8ecf-4ba3-8df4-2cbba3887505",
        "sender": {
          "$oid": "63adadf287e482e6f128ec0e"
        },
        "message": "88888888888888888888",
        "created_at": {
          "$date": "2023-01-10T16:01:22Z"
        }
      },
      {
        "uuid": "3ea03321-3c99-48b6-a7fd-2cc5fa514fb3",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "0000000000000",
        "created_at": {
          "$date": "2023-01-10T15:51:20Z"
        }
      },
      {
        "uuid": "c8e35012-1106-4e3f-b678-6040002d54b8",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "pppppp",
        "created_at": {
          "$date": "2023-01-10T15:40:24Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "b78f1288-5363-4b0f-9bbe-ddf73f60fac1",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "Kio nn sass,,,",
        "created_at": {
          "$date": "2023-01-10T18:46:39Z"
        }
      },
      {
        "uuid": "94e3ae3a-eb2c-4ceb-b580-e97f4ec49aba",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "Kio nn sass,,,",
        "created_at": {
          "$date": "2023-01-10T18:44:57Z"
        }
      },
      {
        "uuid": "80c86174-9836-477b-b0d3-e4cb968b015a",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "Another messgee 2",
        "created_at": {
          "$date": "2023-01-10T18:44:45Z"
        }
      },
      {
        "uuid": "3a6dc43d-bdb5-41b9-be93-15ab389380a9",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "New Docu ",
        "created_at": {
          "$date": "2023-01-10T18:44:01Z"
        }
      },
      {
        "uuid": "69b1dd00-8ecf-4ba3-8df4-2cbba3887505",
        "sender": {
          "$oid": "63adadf287e482e6f128ec0e"
        },
        "message": "i am fine thanks",
        "created_at": {
          "$date": "2023-01-10T16:01:22Z"
        }
      },
      {
        "uuid": "3ea03321-3c99-48b6-a7fd-2cc5fa514fb3",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "Buddy hhh.. ",
        "created_at": {
          "$date": "2023-01-10T15:51:20Z"
        }
      },
      {
        "uuid": "c8e35012-1106-4e3f-b678-6040002d54b8",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "LOL How are you ",
        "created_at": {
          "$date": "2023-01-10T15:36:24Z"
        }
      }
    ]
  }
]
</code>```

I have made 3 messages collection document after 3 new document is created.. i will make it 1000 in production..
and I have use another thing called $concatArray but its adding only fields which I explicitly give example

```<code>// MongoDB Playground
// Use Ctrl+Space inside a snippet or a string literal to trigger completions.

const database = 'test3';

// The current database to use.
use(database);

// db.chats.find({
//   "members": {
//     "$eq": [
//       ObjectId('63ad8631e0d6cfe452b80677'),
//       ObjectId('63adadf287e482e6f128ec0e')
//       ]
//     }
//   }
// )

// db.chats.aggregate(
// {
//   $match: {
//   "members": {
//     "$all": [
//       ObjectId('63ad8631e0d6cfe452b80677'),
//       // ObjectId('63adadf287e482e6f128ec0e'),
//       ObjectId('63b3c2b8ce51cf1fca0325ad')
//       ]
//     },
//   }
// },
// {
//   $sort: {
//     "created_at": -1
//   }
// },
// // {
// //   $project: {
// //     "total": 1,
// //     "_id": 0
// //   }
// // },

// {
//   $limit: 1
// },
// )
// .sort({"created_at": -1})

// db.chats.find(
//   {
//     "members": {
//       "$all": [
//       ObjectId('63ad8631e0d6cfe452b80677'),
//       ObjectId('63adadf287e482e6f128ec0e'),
//       // ObjectId('63b3c2b8ce51cf1fca0325ad')
//       ]
//     }
//   },
// )

// db.chats.find({
//   "members": {
//     "$eq": [
//       ObjectId('63ad8631e0d6cfe452b80677'),
//       ObjectId('63adadf287e482e6f128ec0e')
//       ]
//     }
//   }
// )

db.chats.aggregate(
    {
        /**
         * query: The query in MQL.
         */
        $match: {
          "members": {
            "$all": [
                ObjectId('63ad8631e0d6cfe452b80677'),
                ObjectId('63adadf287e482e6f128ec0e'),
            ]
          }
        },
    },
    {
        /**
         * Provide any number of field/order pairs.
         */
        $sort: {
          "created_at": -1
        }
    },
    {
        /**
         * specifications: The fields to
         *   include or exclude.
         */
        $project: {
            "_id": 0,
            // "members": 1,
            "result": {
                $sortArray: {input: "$message", sortBy: {created_at: -1}},
            }
        }
    },
    {
        /**
         * specifications: The fields to
         *   include or exclude.
         */
        $project: {
          "messages": {
            '$concatArrays': [
                "$result", "$result"
                ]
            }
        }
    }
)
</code>```

it will add two result to messages  but not to all of that result
here my demo MongoDB collections https://pastebin.com/mt4i3HXr

Body:
i have used this schema

    conversation_id: 12345,
    time: time,
    members: ['user1', 'user2'],
    messages: [
      {
         sender: 'user1',
         message: 'Hello World',
         timestamp: time
      },
      {
         sender: 'user1',
         message: 'Hello World',
         timestamp: time
      }],
   total_messages: 2
}

but i need to know how to get all the results by sorted

db.chats.aggregate(
    {
        /**
         * query: The query in MQL.
         */
        $match: {
          "members": {
            "$all": [
                ObjectId('63ad8631e0d6cfe452b80677'),
                ObjectId('63adadf287e482e6f128ec0e'),
            ]
          }
        },
    },
    {
        /**
         * Provide any number of field/order pairs.
         */
        $sort: {
          "created_at": -1
        }
    },
    {
        /**
         * specifications: The fields to
         *   include or exclude.
         */
        $project: {
            "_id": 0,
            // "members": 1,
            "result": {
                $sortArray: {input: "$message", sortBy: {created_at: -1}}
            }
        }
    },
)

I have used this.. but thing is every things are in result block and I want it to in one array so I can fetch previous messages with $limit and $skip so I can send back to API of user message..
here is my sample data

[
  {
    "result": [
      {
        "uuid": "df359053-5b69-4fc3-ac42-57aaf70ec9d9",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00011",
        "created_at": {
          "$date": "2023-01-10T19:52:26Z"
        }
      },
      {
        "uuid": "0cfe04ab-ccf2-4eb9-8760-d3471f033ea6",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00010",
        "created_at": {
          "$date": "2023-01-10T19:52:15Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "fe54bf97-5dad-4d3f-ada8-ea1f1ab31039",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00010",
        "created_at": {
          "$date": "2023-01-10T19:52:14Z"
        }
      },
      {
        "uuid": "9face81d-b989-4662-a090-2f8f498b1a7b",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00010",
        "created_at": {
          "$date": "2023-01-10T19:52:12Z"
        }
      },
      {
        "uuid": "8578ce16-f3ac-4ceb-b779-0c1f3e8fec2f",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00010",
        "created_at": {
          "$date": "2023-01-10T19:51:02Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "ef6f12e0-b601-4377-8ff9-28921799985b",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00009",
        "created_at": {
          "$date": "2023-01-10T19:51:00Z"
        }
      },
      {
        "uuid": "6fcbcc3b-ff09-4e1c-9ce5-d73790911592",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00008",
        "created_at": {
          "$date": "2023-01-10T19:50:47Z"
        }
      },
      {
        "uuid": "fdde26cd-6688-466a-be61-37ac8e312a70",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00007",
        "created_at": {
          "$date": "2023-01-10T19:49:33Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "fdde26cd-6688-466a-be61-37ac8e312a70",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00007",
        "created_at": {
          "$date": "2023-01-10T19:49:33Z"
        }
      },
      {
        "uuid": "fb72bef2-ceff-4e22-80cd-b54da6ba6f01",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00006",
        "created_at": {
          "$date": "2023-01-10T19:48:51Z"
        }
      },
      {
        "uuid": "3ffee1e6-8eb4-4a93-99a2-329576dc7754",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00005",
        "created_at": {
          "$date": "2023-01-10T19:48:34Z"
        }
      },
      {
        "uuid": "927726bd-acc9-461b-98db-9ce07cca5ff0",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00004",
        "created_at": {
          "$date": "2023-01-10T19:48:31Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "927726bd-acc9-461b-98db-9ce07cca5ff0",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00004",
        "created_at": {
          "$date": "2023-01-10T19:48:31Z"
        }
      },
      {
        "uuid": "664cb8fb-0284-4ad2-af1f-d9458fb09c24",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00003",
        "created_at": {
          "$date": "2023-01-10T19:48:25Z"
        }
      },
      {
        "uuid": "460e8a5a-327f-47c9-a8c3-76772cca4cc7",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      },
      {
        "uuid": "ed4e5060-45f9-4f4a-a6a0-e45eddbd64bc",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "a45e6738-afb4-47aa-a8f4-fdf1d70eeb5f",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      },
      {
        "uuid": "466b8569-12c4-4d06-8572-eb5999f0e4ae",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      },
      {
        "uuid": "314b60eb-1eaf-4a72-a7a6-528ab474a0d9",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      },
      {
        "uuid": "460e8a5a-327f-47c9-a8c3-76772cca4cc7",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "a45e6738-afb4-47aa-a8f4-fdf1d70eeb5f",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:22:03Z"
        }
      },
      {
        "uuid": "4f56f58d-1b0c-48f9-b3b6-c63020068760",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00002",
        "created_at": {
          "$date": "2023-01-10T19:21:55Z"
        }
      },
      {
        "uuid": "4fb86042-93ef-4209-88ca-8c287f16a2f6",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "00001",
        "created_at": {
          "$date": "2023-01-10T19:20:30Z"
        }
      },
      {
        "uuid": "3a6dc43d-bdb5-41b9-be93-15ab389380a9",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "New Docu ",
        "created_at": {
          "$date": "2023-01-10T18:44:01Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "69b1dd00-8ecf-4ba3-8df4-2cbba3887505",
        "sender": {
          "$oid": "63adadf287e482e6f128ec0e"
        },
        "message": "88888888888888888888",
        "created_at": {
          "$date": "2023-01-10T16:01:22Z"
        }
      },
      {
        "uuid": "3ea03321-3c99-48b6-a7fd-2cc5fa514fb3",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "0000000000000",
        "created_at": {
          "$date": "2023-01-10T15:51:20Z"
        }
      },
      {
        "uuid": "c8e35012-1106-4e3f-b678-6040002d54b8",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "pppppp",
        "created_at": {
          "$date": "2023-01-10T15:40:24Z"
        }
      }
    ]
  },
  {
    "result": [
      {
        "uuid": "b78f1288-5363-4b0f-9bbe-ddf73f60fac1",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "Kio nn sass,,,",
        "created_at": {
          "$date": "2023-01-10T18:46:39Z"
        }
      },
      {
        "uuid": "94e3ae3a-eb2c-4ceb-b580-e97f4ec49aba",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "Kio nn sass,,,",
        "created_at": {
          "$date": "2023-01-10T18:44:57Z"
        }
      },
      {
        "uuid": "80c86174-9836-477b-b0d3-e4cb968b015a",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "Another messgee 2",
        "created_at": {
          "$date": "2023-01-10T18:44:45Z"
        }
      },
      {
        "uuid": "3a6dc43d-bdb5-41b9-be93-15ab389380a9",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "New Docu ",
        "created_at": {
          "$date": "2023-01-10T18:44:01Z"
        }
      },
      {
        "uuid": "69b1dd00-8ecf-4ba3-8df4-2cbba3887505",
        "sender": {
          "$oid": "63adadf287e482e6f128ec0e"
        },
        "message": "i am fine thanks",
        "created_at": {
          "$date": "2023-01-10T16:01:22Z"
        }
      },
      {
        "uuid": "3ea03321-3c99-48b6-a7fd-2cc5fa514fb3",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "Buddy hhh.. ",
        "created_at": {
          "$date": "2023-01-10T15:51:20Z"
        }
      },
      {
        "uuid": "c8e35012-1106-4e3f-b678-6040002d54b8",
        "sender": {
          "$oid": "63ad8631e0d6cfe452b80677"
        },
        "message": "LOL How are you ",
        "created_at": {
          "$date": "2023-01-10T15:36:24Z"
        }
      }
    ]
  }
]

I have made 3 messages collection document after 3 new document is created.. i will make it 1000 in production..
and I have use another thing called $concatArray but its adding only fields which I explicitly give example

// MongoDB Playground
// Use Ctrl+Space inside a snippet or a string literal to trigger completions.

const database = 'test3';

// The current database to use.
use(database);

// db.chats.find({
//   "members": {
//     "$eq": [
//       ObjectId('63ad8631e0d6cfe452b80677'),
//       ObjectId('63adadf287e482e6f128ec0e')
//       ]
//     }
//   }
// )

// db.chats.aggregate(
// {
//   $match: {
//   "members": {
//     "$all": [
//       ObjectId('63ad8631e0d6cfe452b80677'),
//       // ObjectId('63adadf287e482e6f128ec0e'),
//       ObjectId('63b3c2b8ce51cf1fca0325ad')
//       ]
//     },
//   }
// },
// {
//   $sort: {
//     "created_at": -1
//   }
// },
// // {
// //   $project: {
// //     "total": 1,
// //     "_id": 0
// //   }
// // },

// {
//   $limit: 1
// },
// )
// .sort({"created_at": -1})

// db.chats.find(
//   {
//     "members": {
//       "$all": [
//       ObjectId('63ad8631e0d6cfe452b80677'),
//       ObjectId('63adadf287e482e6f128ec0e'),
//       // ObjectId('63b3c2b8ce51cf1fca0325ad')
//       ]
//     }
//   },
// )

// db.chats.find({
//   "members": {
//     "$eq": [
//       ObjectId('63ad8631e0d6cfe452b80677'),
//       ObjectId('63adadf287e482e6f128ec0e')
//       ]
//     }
//   }
// )

db.chats.aggregate(
    {
        /**
         * query: The query in MQL.
         */
        $match: {
          "members": {
            "$all": [
                ObjectId('63ad8631e0d6cfe452b80677'),
                ObjectId('63adadf287e482e6f128ec0e'),
            ]
          }
        },
    },
    {
        /**
         * Provide any number of field/order pairs.
         */
        $sort: {
          "created_at": -1
        }
    },
    {
        /**
         * specifications: The fields to
         *   include or exclude.
         */
        $project: {
            "_id": 0,
            // "members": 1,
            "result": {
                $sortArray: {input: "$message", sortBy: {created_at: -1}},
            }
        }
    },
    {
        /**
         * specifications: The fields to
         *   include or exclude.
         */
        $project: {
          "messages": {
            '$concatArrays': [
                "$result", "$result"
                ]
            }
        }
    }
)

it will add two result to messages  but not to all of that result
here my demo MongoDB collections https://pastebin.com/mt4i3HXr


问:
Chart.js - How to move x axis tick marks position to above the x axis
I drew a line chart and want to move x axis tick marks position, but I can not find related configuration. Please see the picture below.

AS-IS/TO-BE

Here is my code

```<code><script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js">
</code>```
```<code><canvas id="myChart" style="height:500px"></canvas>
</code>```
```<code>chart = new Chart(document.getElementById("myChart"), {
        type: 'line',
        data: {
            datasets: [{
                label: "Count",
                pointStyle: 'circle',
                showLine: true,
                fill: false,
                lineTension: 0,
                borderColor: '#7265ce',
                pointRadius: 4,
                pointBorderWidth: 1,
                pointBackgroundColor: '#7265ce',
                data: data
            }]
        },
        options: {
            parsing: {
                xAxisKey: 'timestamp',
                yAxisKey: 'value'
            },
            spanGaps: false,
            responsive: false,
            scales: {
                x: {
                    bounds: 'ticks',
                    type: 'time',
                    time: {
                        parser: 'yyyyMMddHHmmss',
                        unit: 'minute',
                        stepSize: 5,
                        displayFormats: {
                            minute: 'HH:mm',
                            second: 'mm:ss'
                        }
                    },
                    title: {
                        display: false,
                        text: 'Timestamp'
                    },
                    grid: {
                        drawOnChartArea: false,
                        lineWidth: 1
                    },
                    ticks: {
                        display: true,
                        color: '#cecece'
                    }
                },
                y: {
                    type: 'linear',
                    display: true,
                    ticks: {
                        padding: 10,
                        autoSkip: true,
                        maxTicksLimit:2,
                        color: '#cecece'
                    },
                    title: {
                        display: false,
                        text: 'Count',
                        align: 'end'
                    },
                    grid: {
                        drawOnChartArea: false
                    },
                }
            }
        }
    });
});
</code>```
```<code>    let data = [
    { "timestamp": "20230109150000", "value": 10 },
    { "timestamp": "20230109150100", "value": 17 },
    { "timestamp": "20230109150200", "value": 92 },
    { "timestamp": "20230109150300", "value": 60 },
    { "timestamp": "20230109150400", "value": 50 },
    { "timestamp": "20230109150500", "value": 91 }
    ];
</code>```

Is it possible?
Is there any configuration in chartjs?
I'm using v3.9.1

Sorry for my poor english.


问:
Use multiple rows as column header for danfo
My excel table looks like this: Excel file Snip

I exported it as CSV file. and it looks like this: CSV file snip

I read this csv file using below method:

```<code>const dfd = require("danfojs");
var df;
df = dfd.readCSV("assets/temp-files/sample.csv");
df.print();
</code>```

The above code prints the df in browser console like this: df print in browser console

As in the above console snip, it is missing ID, Name, Payment columns as well as it is only including the first sub-header column under headers "Contact Info" & "Food Preferences".

I want all the columns in the danfo dataframe and print should show all the sub-headers under each header as it is in the excel.

Body:
My excel table looks like this: Excel file Snip

I exported it as CSV file. and it looks like this: CSV file snip

I read this csv file using below method:

const dfd = require("danfojs");
var df;
df = dfd.readCSV("assets/temp-files/sample.csv");
df.print();

The above code prints the df in browser console like this: df print in browser console

As in the above console snip, it is missing ID, Name, Payment columns as well as it is only including the first sub-header column under headers "Contact Info" & "Food Preferences".

I want all the columns in the danfo dataframe and print should show all the sub-headers under each header as it is in the excel.


问:
Change Label Background Color with VBScript
I have a HTA form where input type labels are set to background-color: LightGray; in the head CSS, and I would like to change the background color to another color during runtime based on a condition with VBScript. Condition code is fine (If... Then... End If)

Let's say the control's ID is "controlid".

I have tried stuff like

controlid.style.BackColor = RGB(0,0,0)

controlid.style.bgColor = RGB(0,0,0)

controlid.style.BackColor = "0,0,0"

controlid.style.bgColor = "0,0,0"

controlid.BackColor = RGB(0,0,0)

controlid.bgColor = RGB(0,0,0)

controlid.BackColor = "0,0,0"

controlid.bgColor = "0,0,0"

etcetera.

Google is not playing nice. Is there a way to do this?


问:
Google Analytics logs not appearing on Dashboard when sent from Android
I am trying to send custom google analytics log events in android, but on Google Analytics Dashboard Real-time view these logs do not show. I have to reinstall app to see the logs showing there.
I searched on google but couldn't find any relevant issues (for android). Docs mentions that it should happen within few seconds.

This is the code that I am using. I am using Jetpack compose.

```<code> ...
       analytics.logEvent(event.name) {
            event.params?.forEach { param ->
                param(param.key, param.value)
            }
 ...
</code>```

I could see that logs are sent to the server but not sure why they aren't showing in real-time view. Is my understanding correct or does it takes some time for Mobile?

Body:
I am trying to send custom google analytics log events in android, but on Google Analytics Dashboard Real-time view these logs do not show. I have to reinstall app to see the logs showing there.
I searched on google but couldn't find any relevant issues (for android). Docs mentions that it should happen within few seconds.

This is the code that I am using. I am using Jetpack compose.

 ...
       analytics.logEvent(event.name) {
            event.params?.forEach { param ->
                param(param.key, param.value)
            }
 ...

I could see that logs are sent to the server but not sure why they aren't showing in real-time view. Is my understanding correct or does it takes some time for Mobile?