问:
How to access current user/auth_state from notebook
I am using JupyterHub with custom authenticator.
It sets auth_state with access token, which then can be copied into environment inside pre_spawn_start method like in the example:

```<code>class MyAuthenticator(Authenticator):
    @gen.coroutine
    def authenticate(self, handler, data=None):
        username = yield identify_user(handler, data)
        upstream_token = yield token_for_user(username)
        return {
            'name': username,
            'auth_state': {
                'upstream_token': upstream_token,
            },
        }

@gen.coroutine
def pre_spawn_start(self, user, spawner):
    """Pass upstream_token to spawner via environment variable"""
    auth_state = yield user.get_auth_state()
    if not auth_state:
        # auth_state not enabled
        return
    spawner.environment['UPSTREAM_TOKEN'] = auth_state['upstream_token']
</code>```

However, it happens only once per user. If I logout and login again, the pre_spawn_start is not called again and old token is still present in the environment variable.

Is it possible to access user.get_auth_state() directly from the notebook so I can be sure to use the current token, rather then previously set and stored in the environment?

Otherwise, is it possible to force spawner stop on logout so the subsequent login will trigger the pre_spawn_start?

答:
you can force stop servers and ask for login when token gets expired, it can achieved by following steps,

Write refresh_user method to get new token(attached sample code)

Set time for refresh_user.

c.MyAuthenticator.auth_refresh_age = 30 #This could be the time of validity of token in seconds

import inspect, concurrent,asyncio

async def refresh_user(self, user,handler=None):
    """
    1. Check if token is valid and then call _shutdown_servers and then redirect to login page
    2. If time of refresh_user is set as token expiry, directly call _shutdown_servers and then redirect to login page
    This is shutdown single user servers and once redirected to login, auth flow gets run and new tokens are passed to spawner
    """
    auth_state = await user.get_auth_state()
    if self._is_invalid_sessionid(auth_state):
        await self._shutdown_servers(user, handler=None)
        handler.clear_login_cookie()
        handler.redirect('/login')
    return True

async def maybe_future(obj):
    """Return an asyncio Future
    Use instead of gen.maybe_future
    For our compatibility, this must accept:
    - asyncio coroutine (gen.maybe_future doesn't work in tornado < 5)
    - tornado coroutine (asyncio.ensure_future doesn't work)
    - scalar (asyncio.ensure_future doesn't work)
    - concurrent.futures.Future (asyncio.ensure_future doesn't work)
    - tornado Future (works both ways)
    - asyncio Future (works both ways)
    """
    if inspect.isawaitable(obj):
        # already awaitable, use ensure_future
        return asyncio.ensure_future(obj)
    elif isinstance(obj, concurrent.futures.Future):
        return asyncio.wrap_future(obj)
    else:
        # could also check for tornado.concurrent.Future
        # but with tornado >= 5.1 tornado.Future is asyncio.Future
        f = asyncio.Future()
        f.set_result(obj)
        return f

async def _shutdown_servers(self, user,handler):
    """Shutdown servers for logout
    Get all active servers for the provided user, stop them.
    """
    active_servers = [
        name
        for (name, spawner) in user.spawners.items()
        if spawner.active and not spawner.pending
    ]
    if active_servers:
        self.log.info("Shutting down %s's servers", user.name)
        futures = []
        for server_name in active_servers:
            futures.append(self.maybe_future(handler.stop_single_user(user, server_name)))
        await asyncio.gather(*futures)
```

https://jupyterhub.readthedocs.io/en/stable/api/auth.html#jupyterhub.auth.Authenticator.auth_refresh_age
https://jupyterhub.readthedocs.io/en/stable/api/auth.html#jupyterhub.auth.Authenticator.refresh_user

Body:
I am using JupyterHub with custom authenticator.
It sets auth_state with access token, which then can be copied into environment inside pre_spawn_start method like in the example:

class MyAuthenticator(Authenticator):
    @gen.coroutine
    def authenticate(self, handler, data=None):
        username = yield identify_user(handler, data)
        upstream_token = yield token_for_user(username)
        return {
            'name': username,
            'auth_state': {
                'upstream_token': upstream_token,
            },
        }

@gen.coroutine
def pre_spawn_start(self, user, spawner):
    """Pass upstream_token to spawner via environment variable"""
    auth_state = yield user.get_auth_state()
    if not auth_state:
        # auth_state not enabled
        return
    spawner.environment['UPSTREAM_TOKEN'] = auth_state['upstream_token']

However, it happens only once per user. If I logout and login again, the pre_spawn_start is not called again and old token is still present in the environment variable.

Is it possible to access user.get_auth_state() directly from the notebook so I can be sure to use the current token, rather then previously set and stored in the environment?

Otherwise, is it possible to force spawner stop on logout so the subsequent login will trigger the pre_spawn_start?

Body:
you can force stop servers and ask for login when token gets expired, it can achieved by following steps,

Write refresh_user method to get new token(attached sample code)

Set time for refresh_user.

c.MyAuthenticator.auth_refresh_age = 30 #This could be the time of validity of token in seconds

import inspect, concurrent,asyncio

async def refresh_user(self, user,handler=None):
    """
    1. Check if token is valid and then call _shutdown_servers and then redirect to login page
    2. If time of refresh_user is set as token expiry, directly call _shutdown_servers and then redirect to login page
    This is shutdown single user servers and once redirected to login, auth flow gets run and new tokens are passed to spawner
    """
    auth_state = await user.get_auth_state()
    if self._is_invalid_sessionid(auth_state):
        await self._shutdown_servers(user, handler=None)
        handler.clear_login_cookie()
        handler.redirect('/login')
    return True

async def maybe_future(obj):
    """Return an asyncio Future
    Use instead of gen.maybe_future
    For our compatibility, this must accept:
    - asyncio coroutine (gen.maybe_future doesn't work in tornado < 5)
    - tornado coroutine (asyncio.ensure_future doesn't work)
    - scalar (asyncio.ensure_future doesn't work)
    - concurrent.futures.Future (asyncio.ensure_future doesn't work)
    - tornado Future (works both ways)
    - asyncio Future (works both ways)
    """
    if inspect.isawaitable(obj):
        # already awaitable, use ensure_future
        return asyncio.ensure_future(obj)
    elif isinstance(obj, concurrent.futures.Future):
        return asyncio.wrap_future(obj)
    else:
        # could also check for tornado.concurrent.Future
        # but with tornado >= 5.1 tornado.Future is asyncio.Future
        f = asyncio.Future()
        f.set_result(obj)
        return f

async def _shutdown_servers(self, user,handler):
    """Shutdown servers for logout
    Get all active servers for the provided user, stop them.
    """
    active_servers = [
        name
        for (name, spawner) in user.spawners.items()
        if spawner.active and not spawner.pending
    ]
    if active_servers:
        self.log.info("Shutting down %s's servers", user.name)
        futures = []
        for server_name in active_servers:
            futures.append(self.maybe_future(handler.stop_single_user(user, server_name)))
        await asyncio.gather(*futures)

https://jupyterhub.readthedocs.io/en/stable/api/auth.html#jupyterhub.auth.Authenticator.auth_refresh_age
https://jupyterhub.readthedocs.io/en/stable/api/auth.html#jupyterhub.auth.Authenticator.refresh_user


来源: stackexchange

问:
How to truncate and load data in RDS (SQL Server) using Lambda function
I need to load data into RDS (SQL Server) after deleting the table contents which was previously loaded. That's because I don't want to append the table contents. I would like to achieve this using a Lambda function.

This is my sample Lambda function script:

```<code>import pyodbc
import pandas as pd
# insert data from csv file into dataframe(df).
server = 'yourservername'
database = 'AdventureWorks'
username = 'username'
password = 'yourpassword'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
# Insert Dataframe into SQL Server:
for index, row in df.iterrows():
     cursor.execute("INSERT INTO HumanResources.DepartmentTest (DepartmentID,Name,GroupName) values(?,?,?)", row.DepartmentID, row.Name, row.GroupName)
cnxn.commit()
cursor.close()
</code>```

I tried to execute the below before "insert" command

```<code>for index, row in df.iterrows():
cursor.execute("truncate table HumanResources.DepartmentTest")
</code>```

Unfortunately it didn't work properly. Although my table was truncated but inserted only one row. Not sure why!

Can someone tell me why just one row got loaded? I have more than 50k rows in my csv file which I am trying to load via S3 bucket. If I run my cursor.execute separately it works.

Any help would be appreciated.

答:
I found out the solution to achieve what I was trying earlier. To load data after truncate old table contents, I need to remove cursor.execute("truncate table HumanResources.DepartmentTest") from "for index, row in df.iterrows():" and place it under;

```<code>cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("truncate table HumanResources.DepartmentTest")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to load data into RDS (SQL Server) after deleting the table contents which was previously loaded. That's because I don't want to append the table contents. I would like to achieve this using a Lambda function.

This is my sample Lambda function script:

import pyodbc
import pandas as pd
# insert data from csv file into dataframe(df).
server = 'yourservername'
database = 'AdventureWorks'
username = 'username'
password = 'yourpassword'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
# Insert Dataframe into SQL Server:
for index, row in df.iterrows():
     cursor.execute("INSERT INTO HumanResources.DepartmentTest (DepartmentID,Name,GroupName) values(?,?,?)", row.DepartmentID, row.Name, row.GroupName)
cnxn.commit()
cursor.close()

I tried to execute the below before "insert" command

for index, row in df.iterrows():
cursor.execute("truncate table HumanResources.DepartmentTest")

Unfortunately it didn't work properly. Although my table was truncated but inserted only one row. Not sure why!

Can someone tell me why just one row got loaded? I have more than 50k rows in my csv file which I am trying to load via S3 bucket. If I run my cursor.execute separately it works.

Any help would be appreciated.

Body:
I found out the solution to achieve what I was trying earlier. To load data after truncate old table contents, I need to remove cursor.execute("truncate table HumanResources.DepartmentTest") from "for index, row in df.iterrows():" and place it under;

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("truncate table HumanResources.DepartmentTest")


问:
How to fill color inside a shape created using CustomPainter drawPath?
So, I've created a shape using drawPath and drawArc from CustomPainter, the PaintingStyle is stroke, but when I change it to fill, it only fills the arcs and not the whole shape.
I want to fill the shape I created with a color, so how can I fill the shape with a particular color?

```<code>
class CustomShapeCard extends CustomPainter {
  CustomShapeCard({@required this.strokeWidth, @required this.color});

  final double strokeWidth;
  final Color color;

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth
      ..color = color;

    var path = Path();

    path.moveTo(size.width * 0.1, size.height * 0.2);
    path.lineTo(size.width * 0.1, size.height * 0.9);
    canvas.drawPath(path, paint);

    canvas.drawArc(
      Rect.fromCenter(
        center: Offset((size.width * 0.2) - 14, size.height * 0.9),
        height: 50,
        width: 50,
      ),
      math.pi / 2,
      math.pi / 2,
      false,
      paint,
    );

    path.moveTo((size.width * 0.2) - 14, (size.height * 0.9) + 25);
    path.lineTo((size.width * 0.9) - 25, size.height * 0.9 + 25);
    canvas.drawPath(path, paint);

    canvas.drawArc(
      Rect.fromCenter(
        center: Offset((size.width * 0.9) - 25, size.height * 0.9),
        height: 50,
        width: 50,
      ),
      math.pi / 2,
      -math.pi / 2,
      false,
      paint,
    );

    path.moveTo((size.width * 0.9), (size.height * 0.9));
    path.lineTo(size.width * 0.9, size.height * 0.35);
    canvas.drawPath(path, paint);

    canvas.drawArc(
      Rect.fromCenter(
        center: Offset((size.width * 0.9) - 25, size.height * 0.35),
        height: 50,
        width: 50,
      ),
      -math.pi / 2,
      math.pi / 2,
      false,
      paint,
    );

    path.moveTo((size.width * 0.9) - 25, (size.height * 0.35) - 25);
    path.lineTo(size.width * 0.25, (size.height * 0.35) - 25);
    canvas.drawPath(path, paint);

    canvas.drawArc(
      Rect.fromCenter(
        center: Offset((size.width * 0.25), (size.height * 0.35) - 50),
        height: 50,
        width: 50,
      ),
      math.pi / 2,
      math.pi / 3,
      false,
      paint,
    );

    path.moveTo((size.width * 0.25) - 20, (size.height * 0.35) - 35);
    path.lineTo(size.width * 0.1, size.height * 0.2);
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
</code>```

When the PaintingStyle is stroke, I get this,

When I change PaintingStyle to fill, I get,

答:
To fill a shape like this with a color,
the arcToPoint() should be used instead of drawArc().</p>

Body:
So, I've created a shape using drawPath and drawArc from CustomPainter, the PaintingStyle is stroke, but when I change it to fill, it only fills the arcs and not the whole shape.
I want to fill the shape I created with a color, so how can I fill the shape with a particular color?

class CustomShapeCard extends CustomPainter {
  CustomShapeCard({@required this.strokeWidth, @required this.color});

  final double strokeWidth;
  final Color color;

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth
      ..color = color;

    var path = Path();

    path.moveTo(size.width * 0.1, size.height * 0.2);
    path.lineTo(size.width * 0.1, size.height * 0.9);
    canvas.drawPath(path, paint);

    canvas.drawArc(
      Rect.fromCenter(
        center: Offset((size.width * 0.2) - 14, size.height * 0.9),
        height: 50,
        width: 50,
      ),
      math.pi / 2,
      math.pi / 2,
      false,
      paint,
    );

    path.moveTo((size.width * 0.2) - 14, (size.height * 0.9) + 25);
    path.lineTo((size.width * 0.9) - 25, size.height * 0.9 + 25);
    canvas.drawPath(path, paint);

    canvas.drawArc(
      Rect.fromCenter(
        center: Offset((size.width * 0.9) - 25, size.height * 0.9),
        height: 50,
        width: 50,
      ),
      math.pi / 2,
      -math.pi / 2,
      false,
      paint,
    );

    path.moveTo((size.width * 0.9), (size.height * 0.9));
    path.lineTo(size.width * 0.9, size.height * 0.35);
    canvas.drawPath(path, paint);

    canvas.drawArc(
      Rect.fromCenter(
        center: Offset((size.width * 0.9) - 25, size.height * 0.35),
        height: 50,
        width: 50,
      ),
      -math.pi / 2,
      math.pi / 2,
      false,
      paint,
    );

    path.moveTo((size.width * 0.9) - 25, (size.height * 0.35) - 25);
    path.lineTo(size.width * 0.25, (size.height * 0.35) - 25);
    canvas.drawPath(path, paint);

    canvas.drawArc(
      Rect.fromCenter(
        center: Offset((size.width * 0.25), (size.height * 0.35) - 50),
        height: 50,
        width: 50,
      ),
      math.pi / 2,
      math.pi / 3,
      false,
      paint,
    );

    path.moveTo((size.width * 0.25) - 20, (size.height * 0.35) - 35);
    path.lineTo(size.width * 0.1, size.height * 0.2);
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

When the PaintingStyle is stroke, I get this,

When I change PaintingStyle to fill, I get,


问:
docker not found inside jenkins pipeline
I have a jenkins installed on my linux machine and connected it to my kubernetes cluster.

I've installed docker and docker-pipeline plugin inside jenkins and they can be found under /var/lib/jenkins/plugins:

```<code>docker-build-step
docker-build-step.jpi
docker-commons
docker-commons.jpi
docker-java-api
docker-java-api.jpi
docker-plugin
docker-plugin.jpi
docker-workflow
docker-workflow.jpi
</code>```

and configured in Global Tool Configuration:

However when I run docker.build or even sh 'docker ps' inside my pipeline it throws:

```<code>/home/jenkins/agent/workspace/nodejs@tmp/durable-492ddc4c/script.sh: 1: docker: not found
</code>```

EDIT:

I've built my own image with docker and when I exec into it I can run docker command but pipeline still throws docker not found command and found out it is because jnlp doesn't have docker installed. Any ideas how to fix it inside jenkins-inbound-agent?

答:
You should customize the jenkins/inbound-agent to add docker command, a minimal example as next:

Dockerfile:

```<code>FROM jenkins/inbound-agent
USER root
RUN apt-get update; \
apt-get install -y wget; \
wget https://download.docker.com/linux/static/stable/x86_64/docker-20.10.9.tgz; \
tar zxvf docker-20.10.9.tgz; \
cp -f docker/docker /usr/local/bin; \
rm -fr docker-20.10.0.tgz docker; \
apt-get purge -y wget
</code>```

Build:

```<code>docker build -t my-inbound-agent .
</code>```

Above will install a docker client binary in customized image to let you have docker command in inbound-agent. But still, you need mount docker unix socket to inbound-agent when start it, also you need to use your customized agent image, like next:

Start agent:

```<code>docker run --init -v /var/run/docker.sock:/var/run/docker.sock my-inbound-agent -url ......
</code>```

Then, we could verify it's ok in agent with next:

```<code>$ docker ps
CONTAINER ID   IMAGE              COMMAND                  CREATED         STATUS         PORTS     NAMES
6ad70ee079f5   my-inbound-agent   "/usr/local/bin/jenk…"   7 minutes ago   Up 7 minutes             jolly_fermat
$ docker exec -it 6ad70ee079f5 docker version
Client:
 Version:           20.10.9
 API version:       1.41
 Go version:        go1.16.8
 Git commit:        c2ea9bc
 Built:             Mon Oct  4 16:03:22 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.1
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       f001486
  Built:            Tue Dec 15 04:32:45 2020
  OS/Arch:          linux/amd64
  Experimental:     true
 containerd:
  Version:          1.4.3
  GitCommit:        269548fa27e0089a8b8278fc4fc781d7f65a939b
 runc:
  Version:          1.0.0-rc92
  GitCommit:        ff819c7e9184c13b7c2607fe6c30ae19403a7aff
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0
</code>```

Body:
I have a jenkins installed on my linux machine and connected it to my kubernetes cluster.

I've installed docker and docker-pipeline plugin inside jenkins and they can be found under /var/lib/jenkins/plugins:

docker-build-step
docker-build-step.jpi
docker-commons
docker-commons.jpi
docker-java-api
docker-java-api.jpi
docker-plugin
docker-plugin.jpi
docker-workflow
docker-workflow.jpi

and configured in Global Tool Configuration:

However when I run docker.build or even sh 'docker ps' inside my pipeline it throws:

/home/jenkins/agent/workspace/nodejs@tmp/durable-492ddc4c/script.sh: 1: docker: not found

EDIT:

I've built my own image with docker and when I exec into it I can run docker command but pipeline still throws docker not found command and found out it is because jnlp doesn't have docker installed. Any ideas how to fix it inside jenkins-inbound-agent?

Body:
You should customize the jenkins/inbound-agent to add docker command, a minimal example as next:

Dockerfile:

FROM jenkins/inbound-agent
USER root
RUN apt-get update; \
apt-get install -y wget; \
wget https://download.docker.com/linux/static/stable/x86_64/docker-20.10.9.tgz; \
tar zxvf docker-20.10.9.tgz; \
cp -f docker/docker /usr/local/bin; \
rm -fr docker-20.10.0.tgz docker; \
apt-get purge -y wget

Build:

docker build -t my-inbound-agent .

Above will install a docker client binary in customized image to let you have docker command in inbound-agent. But still, you need mount docker unix socket to inbound-agent when start it, also you need to use your customized agent image, like next:

Start agent:

docker run --init -v /var/run/docker.sock:/var/run/docker.sock my-inbound-agent -url ......

Then, we could verify it's ok in agent with next:

$ docker ps
CONTAINER ID   IMAGE              COMMAND                  CREATED         STATUS         PORTS     NAMES
6ad70ee079f5   my-inbound-agent   "/usr/local/bin/jenk…"   7 minutes ago   Up 7 minutes             jolly_fermat
$ docker exec -it 6ad70ee079f5 docker version
Client:
 Version:           20.10.9
 API version:       1.41
 Go version:        go1.16.8
 Git commit:        c2ea9bc
 Built:             Mon Oct  4 16:03:22 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.1
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       f001486
  Built:            Tue Dec 15 04:32:45 2020
  OS/Arch:          linux/amd64
  Experimental:     true
 containerd:
  Version:          1.4.3
  GitCommit:        269548fa27e0089a8b8278fc4fc781d7f65a939b
 runc:
  Version:          1.0.0-rc92
  GitCommit:        ff819c7e9184c13b7c2607fe6c30ae19403a7aff
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0


问:
How can I select distinct rows when a text field is part of the returned fields in MS SQL Server 2000?
I have a database-driven FAQ that is organised into sections and I am trying to get the section data for only those sections who have a question/answer associated with them.

Here is the schema:

```<code>|---------------------|      |----------------------|
|       Section       |      |       Quest-Ans      |
|---------------------|      |----------------------|
| PK | id(int)        |<--|  | PK     | id(int)     |
|    | title(varchar) |   |--| FK     | Sec_id(int) |
|    | desc(text)     |      |        | body(text)  |
|---------------------|      |----------------------|
</code>```

When I try this query:

```<code>SELECT DISTINCT s.id, s.title, s.desc
FROM Section as s INNER JOIN Quest-Ans as q ON s.id = q.Sec_id
</code>```

I get an error saying that DISCRETE cannot be applied to a text field. How can I get the data I want?

If it matters, this is an SQL2000 database.

EDIT:

Ok, so it seems like there are two ways to go about this. Either with EXISTS and a subquery in the where clause, or with the subquery in the inner join. Which is faster?

答:
```<code>select s.id, s.title, s.desc
from Section s
inner join (select distinct sec_id from Quest-Ans) dqa on s.id = dqa.sec_id
</code>```

OwnerDisplayName: cdeszaq

ContentLicense: CC BY-SA 2.5

Body:
I have a database-driven FAQ that is organised into sections and I am trying to get the section data for only those sections who have a question/answer associated with them.

Here is the schema:

|---------------------|      |----------------------|
|       Section       |      |       Quest-Ans      |
|---------------------|      |----------------------|
| PK | id(int)        |<--|  | PK     | id(int)     |
|    | title(varchar) |   |--| FK     | Sec_id(int) |
|    | desc(text)     |      |        | body(text)  |
|---------------------|      |----------------------|

When I try this query:

SELECT DISTINCT s.id, s.title, s.desc
FROM Section as s INNER JOIN Quest-Ans as q ON s.id = q.Sec_id

I get an error saying that DISCRETE cannot be applied to a text field. How can I get the data I want?

If it matters, this is an SQL2000 database.

EDIT:

Ok, so it seems like there are two ways to go about this. Either with EXISTS and a subquery in the where clause, or with the subquery in the inner join. Which is faster?

OwnerDisplayName: kristof


问:
Open source XMPP library with BOSH support
Is there any open source XMPP library (written in c#) with BOSH support? I checkout AgsXMPP. AgsXMPP doesn't seem to have bosh support. But Matrix supports bosh. Matrix is a commercial one. </p>

答:
We can bind the bosh (using AgsXMPP library) as follows,                </p>

```<code>        XmppClientConnection xmpp;
        xmpp = new XmppClientConnection();
        xmpp.Port = 5280;
        xmpp.Server = jidSender.Server;
        xmpp.SocketConnectionType = agsXMPP.net.SocketConnectionType.Bosh;
        xmpp.ConnectServer = "http://localhost:5280/http-bind";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We can bind the bosh (using AgsXMPP library) as follows,

        XmppClientConnection xmpp;
        xmpp = new XmppClientConnection();
        xmpp.Port = 5280;
        xmpp.Server = jidSender.Server;
        xmpp.SocketConnectionType = agsXMPP.net.SocketConnectionType.Bosh;
        xmpp.ConnectServer = "http://localhost:5280/http-bind";


问:
Terraform - Azure Service Principal deployment - insufficient permissions
I am trying to create azure service principal. I am connection to azure from my laptop using service principal, I have added required permissions, service principal (which I am using to connect to azure) is a member of global administrators, sp is a member of an application developer and application administrator role in azure AD. In order to connect to Azure I am using following PowerShell commands.

```<code>$ApplicationId = "aaa"
$AppPassword = "bbb"
$TenantId = "ccc"
$SecuredPassword = ConvertTo-SecureString -String $AppPassword -AsPlainText -Force

$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList
$ApplicationId, $SecuredPassword
Connect-AzAccount -ServicePrincipal -TenantId $TenantId -Credential $Credential
</code>```

When I try run -  terraform apply -var-file="variables.tfvars" I am getting an error:

```<code>with azuread_application.azuread_app,
│   on service-principal.tf line 3, in resource "azuread_application" "azuread_app":
│    3: resource "azuread_application" "azuread_app" {
│
│ ApplicationsClient.BaseClient.Post(): unexpected status 403 with OData error: Authorization_RequestDenied: Insufficient privileges to complete the operation.
</code>```

I was able to deploy other resources without any problems. I am using remote backend state file, located on Azure Container.

terraform code below:

```<code>data "azuread_client_config" "client_config" {}

resource "azuread_application" "azuread_app" {
  display_name = "sp_name"
  owners       = [data.azuread_client_config.client_config.object_id]
}

resource "azuread_service_principal" "azuread_sp" {
  application_id               = azuread_application.azuread_app.application_id
  app_role_assignment_required = false
  owners                       = [data.azuread_client_config.client_config.object_id]
}

resource "azuread_service_principal_password" "azuread_sp_password" {
  service_principal_id = azuread_service_principal.azuread_sp.object_id
}
</code>```

答:
I tested the same scenario in my environment using the below code and the Service Principal was successfully created from terraform.

```<code>terraform {
  backend "azurerm" {
    storage_account_name = "cloudshellansuman123" # replace with your storage account name
    container_name       = "test" #replace with your container name
    key                  = "terraform.tfstate"
    access_key = "ukyaH/Jxxxxxxxxxxxxxxxxx="#replace with your storage account access key
  }
}

provider "azurerm" {
    features{}
  client_id="de398e56-xxxxxxxxxxxxxxxxxx-20d07416ecb0"#replace with your service principal client ID which you are using to connect with Azure
  client_secret= "-IP7Q~uDLoxxxxxxxxxxxxRGtHMMXj7-.-lA"#replace with your service principal client Secret which you are using to connect with Azure
  tenant_id = "ab07xxxxxxxxxxxxxxx--xxx-620b694ded30"#replace with your AzureAD tenant ID which the subscription is a part of
  subscription_id="8xxxxxxxxxxx-xxxxxxx-xxxxxxxxx-xxae"#replace with your Subscription ID on Which the Service Principal has Owner/Contributor access
}

provider "azuread" {
  client_id="de398e-xx-x-x-x-x-x-x-x416ecb0"#replace with your service principal client ID which you are using to connect with Azure AD
  client_secret= "-IP7Q~uDLoxxxxxxxxxxxxxxGtHMMXj7-.-lA"#replace with your service principal client Secret which you are using to connect with Azure AD
  tenant_id = "ab0xxxxxxxxxxxxxxx-xxxxxxxxx-xxxxxxxx30"#replace with your AzureAD tenant ID which the subscription is a part of
}

data "azuread_client_config" "current" {}

resource "azuread_application" "terraform" {
  display_name = "Ansumantest"
  owners       = [data.azuread_client_config.current.object_id]
}

resource "azuread_application_password" "terraform" {
  application_object_id = azuread_application.terraform.object_id
}

 resource "azuread_service_principal" "terraform" {
   application_id = azuread_application.terraform.application_id
   owners         = [data.azuread_client_config.current.object_id]
 }
</code>```

For Testing I created a Service Principal which I am using to connect with Azure and granted all the same permissions that you have granted and also added  a Owner access on the subscription like below :

Output:

Note: Using the above code , you don't need again to connect to Azure using PowerShell. It will get authenticated directly using the .tf configuration. Also make sure to use Latest AzureRM and AzureAD provider Versions in terraform i.e. 2.95.0 & 2.17.0 respectively.

Body:
I am trying to create azure service principal. I am connection to azure from my laptop using service principal, I have added required permissions, service principal (which I am using to connect to azure) is a member of global administrators, sp is a member of an application developer and application administrator role in azure AD. In order to connect to Azure I am using following PowerShell commands.

$ApplicationId = "aaa"
$AppPassword = "bbb"
$TenantId = "ccc"
$SecuredPassword = ConvertTo-SecureString -String $AppPassword -AsPlainText -Force

$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList
$ApplicationId, $SecuredPassword
Connect-AzAccount -ServicePrincipal -TenantId $TenantId -Credential $Credential

When I try run -  terraform apply -var-file="variables.tfvars" I am getting an error:

with azuread_application.azuread_app,
│   on service-principal.tf line 3, in resource "azuread_application" "azuread_app":
│    3: resource "azuread_application" "azuread_app" {
│
│ ApplicationsClient.BaseClient.Post(): unexpected status 403 with OData error: Authorization_RequestDenied: Insufficient privileges to complete the operation.

I was able to deploy other resources without any problems. I am using remote backend state file, located on Azure Container.

terraform code below:

data "azuread_client_config" "client_config" {}

resource "azuread_application" "azuread_app" {
  display_name = "sp_name"
  owners       = [data.azuread_client_config.client_config.object_id]
}

resource "azuread_service_principal" "azuread_sp" {
  application_id               = azuread_application.azuread_app.application_id
  app_role_assignment_required = false
  owners                       = [data.azuread_client_config.client_config.object_id]
}

resource "azuread_service_principal_password" "azuread_sp_password" {
  service_principal_id = azuread_service_principal.azuread_sp.object_id
}

Body:
I tested the same scenario in my environment using the below code and the Service Principal was successfully created from terraform.

terraform {
  backend "azurerm" {
    storage_account_name = "cloudshellansuman123" # replace with your storage account name
    container_name       = "test" #replace with your container name
    key                  = "terraform.tfstate"
    access_key = "ukyaH/Jxxxxxxxxxxxxxxxxx="#replace with your storage account access key
  }
}

provider "azurerm" {
    features{}
  client_id="de398e56-xxxxxxxxxxxxxxxxxx-20d07416ecb0"#replace with your service principal client ID which you are using to connect with Azure
  client_secret= "-IP7Q~uDLoxxxxxxxxxxxxRGtHMMXj7-.-lA"#replace with your service principal client Secret which you are using to connect with Azure
  tenant_id = "ab07xxxxxxxxxxxxxxx--xxx-620b694ded30"#replace with your AzureAD tenant ID which the subscription is a part of
  subscription_id="8xxxxxxxxxxx-xxxxxxx-xxxxxxxxx-xxae"#replace with your Subscription ID on Which the Service Principal has Owner/Contributor access
}

provider "azuread" {
  client_id="de398e-xx-x-x-x-x-x-x-x416ecb0"#replace with your service principal client ID which you are using to connect with Azure AD
  client_secret= "-IP7Q~uDLoxxxxxxxxxxxxxxGtHMMXj7-.-lA"#replace with your service principal client Secret which you are using to connect with Azure AD
  tenant_id = "ab0xxxxxxxxxxxxxxx-xxxxxxxxx-xxxxxxxx30"#replace with your AzureAD tenant ID which the subscription is a part of
}

data "azuread_client_config" "current" {}

resource "azuread_application" "terraform" {
  display_name = "Ansumantest"
  owners       = [data.azuread_client_config.current.object_id]
}

resource "azuread_application_password" "terraform" {
  application_object_id = azuread_application.terraform.object_id
}

 resource "azuread_service_principal" "terraform" {
   application_id = azuread_application.terraform.application_id
   owners         = [data.azuread_client_config.current.object_id]
 }

For Testing I created a Service Principal which I am using to connect with Azure and granted all the same permissions that you have granted and also added  a Owner access on the subscription like below :

Output:

Note: Using the above code , you don't need again to connect to Azure using PowerShell. It will get authenticated directly using the .tf configuration. Also make sure to use Latest AzureRM and AzureAD provider Versions in terraform i.e. 2.95.0 & 2.17.0 respectively.


问:
I have lost my JKS file and I cannot restore it
I am an Android Amateur developer. I have recently developed an app for business purposes. I have lost my keystore .jks file and i cannot restore it for updating my android app. Is there anyone here to help me how to restore the jks file from a signed APK?? NOTICE: I have not published my app in Google Play store.

Thanks.

答:
You can generate a new jks file. While building apk from android studio, you can set key store path, in that folder you can see your jks file.

But once you upload the app to the play store make sure that you do not lose the JKS file. If you lose then you cannot further update the android app on the play store. JKS file is a unique key for a particular apk so that only those who have the key can update the application. It is for security.

You have not published the app on the play store so no worries. Just generate a new. One more thing, you cannot generate key from a signed apk. You can generate and signed apk and key both at same time. The key will always be same for a particular apk.

It changes only when you change the package name.


问:
Is it safe to accept url from user to show in our website?
I wanna show users websites in their profiles but I don't know after I validate the user's input format to be the valid URL (https://userwebsite.com), is it safe to use that input in a tag () to redirect other users to that website? if it's not safe is there any way to check the URL??

how facebook and others handle this situation like example below

href="https://www.facebook.com/pages/Restaurant-El-Reda-libanesische-und-iranische-Spezialit%C3%A4ten/169985763015422" rel="nofollow noreferrer">https://www.facebook.com/pages/Restaurant-El-Reda-libanesische-und-iranische-Spezialit%C3%A4ten/169985763015422

答:
It is absolutely not.

Keep this in mind that accepting anything from user means danger, this is you that should handle the danger in a safe way.

You can get a URL from a user but it might be harmful for others ...

Body:
I wanna show users websites in their profiles but I don't know after I validate the user's input format to be the valid URL (https://userwebsite.com), is it safe to use that input in a tag () to redirect other users to that website? if it's not safe is there any way to check the URL??

how facebook and others handle this situation like example below

https://www.facebook.com/pages/Restaurant-El-Reda-libanesische-und-iranische-Spezialit%C3%A4ten/169985763015422


问:
How to extend the range of stratification beyond the maximum value in a data frame?
Suppose we start with the following data frame, with the generating code beneath it:

```<code>> stratData
  ID  Period Values
1  1 2020-03     -5
2  1 2020-04     25
3  2 2020-01     35
4  2 2020-02     45
5  2 2020-03     55
6  2 2020-04     87
7  3 2020-02     10
8  3 2020-03     20
9  3 2020-04     30

stratData <-
   data.frame(
     ID = c(1,1,2,2,2,2,3,3,3),
     Period = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-02", "2020-03", "2020-04"),
     Values = c(-5, 25, 35, 45, 55, 87, 10, 20, 30)
     )
</code>```

I have a Shiny app that allows the user to stratify certain values in the data frame by different criteria, including the size of stratification bands. At the bottom is the stratification MWE code. The problem I'm having is the stratification range not properly labeling the maximum value in the range. As shown below, the maximum range shows NA, instead of the correct (85,90] to encompass the maximum from the stratData data frame. How can this be solved?

```<code># A tibble: 7 x 5
  Range   Count Values Count_pct Values_pct
  <fct>   <dbl>  <dbl>     <dbl>      <dbl>
1 [25,35]     2     55      66.7       38.7
2 (35,45]     0      0       0          0
3 (45,55]     0      0       0          0
4 (55,65]     0      0       0          0
5 (65,75]     0      0       0          0
6 (75,85]     0      0       0          0
7 NA          1     87      33.3       61.3
</code>```

Here is the MWE code to generate the above table (there are vestiges from the more complete App; I thought about making the max = round(value, -1) or something like that but a difficulty is the user has the ability to input different ranges in order to customize the stratification):

```<code>custom_min <- function(x) {if (length(x)>0) min(x, na.rm=TRUE) else Inf}
custom_max <- function(x) {if (length(x)>0) max(x, na.rm=TRUE) else Inf}

filter_exp1 <- parse(text=paste0("Period",  "==", "'","2020-04", "'"))
stratData_1 <- stratData %>% filter(eval(filter_exp1))

min <- custom_min(stratData_1[[3]])
max <- custom_max(stratData_1[[3]])
breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else seq(min, max, by = 10) # < in full code, the 10 is a variable the user can change via Shiny

tmp <- stratData %>%
  filter(eval(filter_exp1)) %>%
  mutate(Range = cut(!!sym("Values"), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
  group_by(Range) %>%
  summarise(Count = n(),Values = sum(!!sym("Values"))) %>%
  complete(Range, fill = list(Count = 0,Values = 0)) %>%
  ungroup %>%
  mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
  dplyr::select(everything(), Count, Count_pct, Values, Values_pct)
tmp
</code>```

答:
The above danlooo solution will be used in the larger App for now. Danlooo solution allows the user to specify the number of bands in the stratification using length.out = in the seq() function, instead of by =. However, as the App evolves I may change it to allow the user to specify the minimum band value, maximum band value, and the band thicknesses. (Will need to evaluate whether this added complexity is worthwhile). To allow the user to specify band thickness and add another band to encompass the maximum data frame value per the OP, you can add/change the following in the OP MWE:

```<code># New line:
tmpSeq <- seq(min, max, by = 10)

# Replace "breaks" in OP with the following using the append() function:
breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else append(tmpSeq,tmpSeq[length(tmpSeq)]+10)
</code>```

Body:
Suppose we start with the following data frame, with the generating code beneath it:

> stratData
  ID  Period Values
1  1 2020-03     -5
2  1 2020-04     25
3  2 2020-01     35
4  2 2020-02     45
5  2 2020-03     55
6  2 2020-04     87
7  3 2020-02     10
8  3 2020-03     20
9  3 2020-04     30

stratData <-
   data.frame(
     ID = c(1,1,2,2,2,2,3,3,3),
     Period = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-02", "2020-03", "2020-04"),
     Values = c(-5, 25, 35, 45, 55, 87, 10, 20, 30)
     )

I have a Shiny app that allows the user to stratify certain values in the data frame by different criteria, including the size of stratification bands. At the bottom is the stratification MWE code. The problem I'm having is the stratification range not properly labeling the maximum value in the range. As shown below, the maximum range shows NA, instead of the correct (85,90] to encompass the maximum from the stratData data frame. How can this be solved?

# A tibble: 7 x 5
  Range   Count Values Count_pct Values_pct
  <fct>   <dbl>  <dbl>     <dbl>      <dbl>
1 [25,35]     2     55      66.7       38.7
2 (35,45]     0      0       0          0
3 (45,55]     0      0       0          0
4 (55,65]     0      0       0          0
5 (65,75]     0      0       0          0
6 (75,85]     0      0       0          0
7 NA          1     87      33.3       61.3

Here is the MWE code to generate the above table (there are vestiges from the more complete App; I thought about making the max = round(value, -1) or something like that but a difficulty is the user has the ability to input different ranges in order to customize the stratification):

custom_min <- function(x) {if (length(x)>0) min(x, na.rm=TRUE) else Inf}
custom_max <- function(x) {if (length(x)>0) max(x, na.rm=TRUE) else Inf}

filter_exp1 <- parse(text=paste0("Period",  "==", "'","2020-04", "'"))
stratData_1 <- stratData %>% filter(eval(filter_exp1))

min <- custom_min(stratData_1[[3]])
max <- custom_max(stratData_1[[3]])
breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else seq(min, max, by = 10) # < in full code, the 10 is a variable the user can change via Shiny

tmp <- stratData %>%
  filter(eval(filter_exp1)) %>%
  mutate(Range = cut(!!sym("Values"), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
  group_by(Range) %>%
  summarise(Count = n(),Values = sum(!!sym("Values"))) %>%
  complete(Range, fill = list(Count = 0,Values = 0)) %>%
  ungroup %>%
  mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
  dplyr::select(everything(), Count, Count_pct, Values, Values_pct)
tmp

Body:
The above danlooo solution will be used in the larger App for now. Danlooo solution allows the user to specify the number of bands in the stratification using length.out = in the seq() function, instead of by =. However, as the App evolves I may change it to allow the user to specify the minimum band value, maximum band value, and the band thicknesses. (Will need to evaluate whether this added complexity is worthwhile). To allow the user to specify band thickness and add another band to encompass the maximum data frame value per the OP, you can add/change the following in the OP MWE:

# New line:
tmpSeq <- seq(min, max, by = 10)

# Replace "breaks" in OP with the following using the append() function:
breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else append(tmpSeq,tmpSeq[length(tmpSeq)]+10)


问:
no sql profiling for Entity Framework Code First
I've been struggling with this for a while now, and I see that I'm not the only one with the problem (see this and that).

I've managed to debug for a bit, and found a solution, though I'm pretty sure that this is not the 'right' way.

The first debug session (before the dev server was enabled) showed that the ProfiledDbConnectionFactory and ProfiledDbConnection classes provide the required data, but then AFTER the connection is created, the static Instance property on ProfiledDbProviderFactory is initialized (by calling the default constructor) and apparently CreateConnection() is run on that instance resulting with a null reference exception (tail is null).

I've managed to solve this by running

```<code>ProfiledDbProviderFactory.Instance.InitProfiledDbProviderFactory(_profiler, ripInnerProvider(_conn));
</code>```

at the end of ProfiledDbConnection(DbConnection connection, IDbProfiler profiler).

This allows me to view the sql profiling, but as I wrote, I have a feeling that this isn't the correct fix.

Here's the sample code I used.
Not sure if there is something wrong with my environment, or my code, as I have a feeling that this should work out of the box. Any comments/suggestions?
Sam?

答:
there is nothing wrong with using ProfiledDbConnectionFactory entity framework is designed to support ignorance i generally just use the debugger tools and create a breakpoint to view my generated sql statements as the code first framework provides the sql statement readily there </p>

<p>i would stick to using profiled connections the way you described in your unit testing as opposed to using it in production code as the profiling may be a performance hit you way also want to consider using the sql profiler included in sql server and there is also an sql profiler available as a visual studio extension however i am not sure if it supports code first as of yet </p>

Body:
I've been struggling with this for a while now, and I see that I'm not the only one with the problem (see this and that).

I've managed to debug for a bit, and found a solution, though I'm pretty sure that this is not the 'right' way.

The first debug session (before the dev server was enabled) showed that the ProfiledDbConnectionFactory and ProfiledDbConnection classes provide the required data, but then AFTER the connection is created, the static Instance property on ProfiledDbProviderFactory is initialized (by calling the default constructor) and apparently CreateConnection() is run on that instance resulting with a null reference exception (tail is null).

I've managed to solve this by running

ProfiledDbProviderFactory.Instance.InitProfiledDbProviderFactory(_profiler, ripInnerProvider(_conn));

at the end of ProfiledDbConnection(DbConnection connection, IDbProfiler profiler).

This allows me to view the sql profiling, but as I wrote, I have a feeling that this isn't the correct fix.

Here's the sample code I used.
Not sure if there is something wrong with my environment, or my code, as I have a feeling that this should work out of the box. Any comments/suggestions?
Sam?

Body:
there is nothing wrong with using ProfiledDbConnectionFactory entity framework is designed to support ignorance i generally just use the debugger tools and create a breakpoint to view my generated sql statements as the code first framework provides the sql statement readily there

i would stick to using profiled connections the way you described in your unit testing as opposed to using it in production code as the profiling may be a performance hit you way also want to consider using the sql profiler included in sql server and there is also an sql profiler available as a visual studio extension however i am not sure if it supports code first as of yet


问:
SwiftUI webview not updating with @State variable
For some reason the @State variable that I am using to update the url of my WebView is not updating. Both buttons result in the 'www.target.com' url.

```<code>import SwiftUI

struct ContentView: View {
    var siteArray = ["http://www.google.com","http://www.yahoo.com","http://www.amazon.com"]
    @State private var siteUrl = "http://www.target.com"
    @State private var showWebView = false

    var body: some View {
        ScrollView{
            Text("Websites")
            Button("Target") {
                showWebView.toggle()
            }
            Button("Google") {
                siteUrl = siteArray[0]
                showWebView.toggle()
            }
        }
        .sheet(isPresented: $showWebView) {

        WebView(url: URL(string: "\(siteUrl)")!)
                                            }
}
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

Any help would be appreciated. Thanks!

答:
try to use @Binding
for exemple:

```<code>struct WebView: View {
@Binding var siteUrl :String
var body: some View {
    Text(siteUrl)
}
}

struct ContentView: View {
var siteArray =    ["http://www.google.com","http://www.yahoo.com","http://www.amazon.com"]
@State private var siteUrl = "http://www.target.com"
@State private var showWebView = false

var body: some View {
    ScrollView{
        Text("Websites")
        Button("Target") {
            showWebView.toggle()
        }
        Button("Google") {
            siteUrl = siteArray[1]
            showWebView.toggle()
        }
    }
    .sheet(isPresented: $showWebView) {
        WebView(siteUrl: $siteUrl)

    }
}
}
</code>```

Body:
For some reason the @State variable that I am using to update the url of my WebView is not updating. Both buttons result in the 'www.target.com' url.

import SwiftUI

struct ContentView: View {
    var siteArray = ["http://www.google.com","http://www.yahoo.com","http://www.amazon.com"]
    @State private var siteUrl = "http://www.target.com"
    @State private var showWebView = false

    var body: some View {
        ScrollView{
            Text("Websites")
            Button("Target") {
                showWebView.toggle()
            }
            Button("Google") {
                siteUrl = siteArray[0]
                showWebView.toggle()
            }
        }
        .sheet(isPresented: $showWebView) {

        WebView(url: URL(string: "\(siteUrl)")!)
                                            }
}
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Any help would be appreciated. Thanks!

Body:
try to use @Binding
for exemple:

struct WebView: View {
@Binding var siteUrl :String
var body: some View {
    Text(siteUrl)
}
}

struct ContentView: View {
var siteArray =    ["http://www.google.com","http://www.yahoo.com","http://www.amazon.com"]
@State private var siteUrl = "http://www.target.com"
@State private var showWebView = false

var body: some View {
    ScrollView{
        Text("Websites")
        Button("Target") {
            showWebView.toggle()
        }
        Button("Google") {
            siteUrl = siteArray[1]
            showWebView.toggle()
        }
    }
    .sheet(isPresented: $showWebView) {
        WebView(siteUrl: $siteUrl)

    }
}
}


问:
alpine aarch64 can not install and run aws-cli v2
I have an EC2 instance with arch arm64: aarch64

I want to install aws-cli v2 on this instance, and I do following the official document of AWS: https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-linux.html#cliv2-linux-install

But after install like above document, I met below problem:

```<code>bash-5.1# aws
bash: /usr/local/bin/aws: No such file or directory

bash-5.1# ls /usr/local/bin/aws
/usr/local/bin/aws

</code>```

As you can see, I have that file but can not executed.
After find exactle where the bin located, I execute it but it show like this:

```<code>bash-5.1# ls -la aws
-rwxr-xr-x    1 root     root       4496072 Jun 11 11:41 aws

bash-5.1# ./aws
bash: ./aws: No such file or directory

bash-5.1# /bin/sh aws
aws: line 1: syntax error: unexpected word (expecting ")")

</code>```

I have doing exactly the document said for installing aws-cli v2 for arm64 Linux.

```<code>curl "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
./aws/install
</code>```

答:
I can not install aws-cli v2 directly, but I have an useful workaround like this:

```<code>pip install --no-cache-dir awscli
</code>```

Above solution work for me, but first of all, you need to install pip before, also its requirement packages.

Body:
I have an EC2 instance with arch arm64: aarch64

I want to install aws-cli v2 on this instance, and I do following the official document of AWS: https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-linux.html#cliv2-linux-install

But after install like above document, I met below problem:

bash-5.1# aws
bash: /usr/local/bin/aws: No such file or directory

bash-5.1# ls /usr/local/bin/aws
/usr/local/bin/aws

As you can see, I have that file but can not executed.
After find exactle where the bin located, I execute it but it show like this:

bash-5.1# ls -la aws
-rwxr-xr-x    1 root     root       4496072 Jun 11 11:41 aws

bash-5.1# ./aws
bash: ./aws: No such file or directory

bash-5.1# /bin/sh aws
aws: line 1: syntax error: unexpected word (expecting ")")

I have doing exactly the document said for installing aws-cli v2 for arm64 Linux.

curl "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
./aws/install

Body:
I can not install aws-cli v2 directly, but I have an useful workaround like this:

pip install --no-cache-dir awscli

Above solution work for me, but first of all, you need to install pip before, also its requirement packages.


答:
The exact grouping rules are unclear (thus the slightly different output), but the general idea is to to use groupby+cumsum:

```<code>                              # month+year        # other groups
df1['AuM_YTD'] = df1.groupby([df1['Month'].str[2:] ,'P1', 'P2'])['AuM'].cumsum()
</code>```

output:

```<code>   YEAR     Month P1  P2  AuM  AuM_YTD
0  2021  01012021  A  AA    2        2
1  2021  01012021  B  BB    4        4
2  2021  01022021  A  AA    6        6
3  2021  01032021  B  BB    8        8
4  2021  01032021  B  BB   10       18
5  2022  01012022  A  AA    3        3
6  2022  01012022  C  CC    6        6
7  2022  01022022  A  AA    9        9
8  2022  01022022  C  CC   12       12
</code>```

Title: Pandas groupby with unique values and cumulative sum

Body:
I have got the following dataframe:

lst=[['2021','01012021','A','AA',2],['2021','01012021','B','BB',4],['2021','01022021','A','AA',6],['2021','01032021','B','BB',8],['2021','01032021','B','BB',10],['2022','01012022','A','AA',3],['2022','01012022','C','CC',6],['2022','01022022','A','AA',9],['2022','01022022','C','CC',12]]
df1=pd.DataFrame(lst,columns=['YEAR','Month','P1','P2','AuM'])

For each year and each month it should accumulate the AuM of all unique P1 and P2. The result should look like this:

lst=[['2021','01012021','A','AA',2],['2021','01012021','B','BB',4],['2021','01022021','A','AA',8],['2021','01022021','B','BB',4],['2021','01032021','A','AA',16],['2021','01032021','B','BB',14],['2022','01012022','A','AA',3],['2022','01012022','C','CC',6],['2022','01022022','A','AA',12],['2022','01022022','C','CC',18]]
df2=pd.DataFrame(lst,columns=['YEAR','Month','P1','P2','AuM_YTD'])`

Even if in the the year 2021, 01.02.2021 there wasn't any AuM for P1=b and P2=bb the AuM was still shown from other months.
Thank you for your help.

Body:
The exact grouping rules are unclear (thus the slightly different output), but the general idea is to to use groupby+cumsum:

                              # month+year        # other groups
df1['AuM_YTD'] = df1.groupby([df1['Month'].str[2:] ,'P1', 'P2'])['AuM'].cumsum()

output:

   YEAR     Month P1  P2  AuM  AuM_YTD
0  2021  01012021  A  AA    2        2
1  2021  01012021  B  BB    4        4
2  2021  01022021  A  AA    6        6
3  2021  01032021  B  BB    8        8
4  2021  01032021  B  BB   10       18
5  2022  01012022  A  AA    3        3
6  2022  01012022  C  CC    6        6
7  2022  01022022  A  AA    9        9
8  2022  01022022  C  CC   12       12


问:
Invariant Violation: View config getter callback for component `input` must be a function (received `undefined`)
```<code>    This is my InputItems.js

    import React, { useState } from "react";
    import { Text, View, StyleSheet, TextInput, Button } from "react-native-web";

    function InputItems(props) {
      const [inputGoal, setinputGoal] = useState("");
      return (
        <View style={style.wholeInputcontainer}>
          <TextInput
            placeholder="Enter the Text"
            style={style.textInput}
            onChangeText={(enteredtext) => {
              setinputGoal(enteredtext);
            }}
            value={inputGoal}
          />
          <Button title="Submit" onPress={props.onpressprop.bind(this,inputGoal)} />
        </View>
      );
    }
    const style = StyleSheet.create({
      wholeInputcontainer: {
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      },
      textInput: {
        borderBottomColor: "blue",
        borderBottomWidth: 4,
        marginBottom: 10,
        width: 300,
      },
    });

    export default InputItems;

and this is my App.js
import React, { useState } from "react";

import { StatusBar } from "expo-status-bar";
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  Button,
  ScrollView,
  FlatList,
} from "react-native";
import Listitems from "./Components/ListItems";
import InputItems from "./Components/InputItems";
// import { Button, TextInput } from 'react-native-web';

export default function App() {
  const [outputGoal, setoutputGoal] = useState([]);
  const Onpress = (InputGoalProp) => {
    setoutputGoal((Currentgoal) => [...Currentgoal, InputGoalProp]);
  };
  return (
    <View style={style.root}>
      <InputItems onpressprop={Onpress} />
      {/* We can use mapping from outputGoal but using FlatList instead of ScrollView is more efficient */}
      <FlatList
        data={outputGoal}
        renderItem={(listitems) => <Listitems anything={listitems.item} />}
      />
      <StatusBar style="auto" />
    </View>
  );
}
const style = StyleSheet.create({
  //StyleSheet is a class of react-native, we can always use inline styleing
  root: {
    marginTop: 100,
  },
});
</code>```

Stuck into this problem. Please help me if you can.
This is the error...

Invariant Violation: View config getter callback for component input must be a function (received undefined). Make sure to start component names with a capital letter.

This error is located at:
in input (created by TextInput)
in TextInput (created by InputItems)

答:
You have a typo in this line:

<Button title="Submit" onPress={props.onpressprop.bind(this,inputGoal)} />

There's a comma instead of a period after this. It should be

<Button title="Submit" onPress={props.onpressprop.bind(this.inputGoal)} />

Body:
    This is my InputItems.js

    import React, { useState } from "react";
    import { Text, View, StyleSheet, TextInput, Button } from "react-native-web";

    function InputItems(props) {
      const [inputGoal, setinputGoal] = useState("");
      return (
        <View style={style.wholeInputcontainer}>
          <TextInput
            placeholder="Enter the Text"
            style={style.textInput}
            onChangeText={(enteredtext) => {
              setinputGoal(enteredtext);
            }}
            value={inputGoal}
          />
          <Button title="Submit" onPress={props.onpressprop.bind(this,inputGoal)} />
        </View>
      );
    }
    const style = StyleSheet.create({
      wholeInputcontainer: {
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      },
      textInput: {
        borderBottomColor: "blue",
        borderBottomWidth: 4,
        marginBottom: 10,
        width: 300,
      },
    });

    export default InputItems;

and this is my App.js
import React, { useState } from "react";

import { StatusBar } from "expo-status-bar";
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  Button,
  ScrollView,
  FlatList,
} from "react-native";
import Listitems from "./Components/ListItems";
import InputItems from "./Components/InputItems";
// import { Button, TextInput } from 'react-native-web';

export default function App() {
  const [outputGoal, setoutputGoal] = useState([]);
  const Onpress = (InputGoalProp) => {
    setoutputGoal((Currentgoal) => [...Currentgoal, InputGoalProp]);
  };
  return (
    <View style={style.root}>
      <InputItems onpressprop={Onpress} />
      {/* We can use mapping from outputGoal but using FlatList instead of ScrollView is more efficient */}
      <FlatList
        data={outputGoal}
        renderItem={(listitems) => <Listitems anything={listitems.item} />}
      />
      <StatusBar style="auto" />
    </View>
  );
}
const style = StyleSheet.create({
  //StyleSheet is a class of react-native, we can always use inline styleing
  root: {
    marginTop: 100,
  },
});

Stuck into this problem. Please help me if you can.
This is the error...

Invariant Violation: View config getter callback for component input must be a function (received undefined). Make sure to start component names with a capital letter.

This error is located at:
in input (created by TextInput)
in TextInput (created by InputItems)


问:
Instantiate class from name in MATLAB
I'm trying to list classes I created in some folder in my Matlab folder - using only their name (class name)

as an example, I have a class called 'SimpleString' - and I'm aiming to instantiate an object from that class, if all I know is that its name is 'SimpleString'

So in realtime, I'd like to find out what classes are in a folder (done), then be able to instantiate any of those classes (my question)
Thanks

答:
You can use eval to instantiate the class using just the class name.

```<code>instance = eval('SimpleString');
</code>```

However, if you're simply iterating through all the m-files in a folder containing class definitions and grabbing the file names, you'll only be able to invoke the default constructor using this method.

Title: Instantiate class from name in MATLAB

Body:
You can use eval to instantiate the class using just the class name.

instance = eval('SimpleString');

However, if you're simply iterating through all the m-files in a folder containing class definitions and grabbing the file names, you'll only be able to invoke the default constructor using this method.


问:
Why is this recursive solution faster than the iterative solution?
I wrote a recursive solution for something today, and as it goes, curiosity led me down a weird path. I wanted to see how an optimized recursive solution compares to an iterative solution so I chose a classic, the Nth Fibonacci to test with.

I was surprised to find that the recursive solution with memoization is much faster than the iterative solution and I would like to know why.

Here is the code (using python3):

import time
import sys
sys.setrecursionlimit(10000)

## recursive:
def fibr(n, memo = {}):
    if n <= 1:
        return n

    if n in memo:
        return memo[n]

    memo[n] = fibr(n-1, memo) + fibr(n-2, memo)

    return memo[n]

## iterative:
def fibi(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

rstart = time.time()
for n in range(10000):
    fibr(n)
rend = time.time()

istart = time.time()
for n in range(10000):
    fibi(n)
iend = time.time()

print(f"recursive: {rend-rstart}")
print(f"iterative: {iend-istart}")
```
<p>My results:</p>
```recursive: 0.010010004043579102
iterative: 6.274333238601685
```
<p>Unless I'm mistaken, both the recursive solution and the iterative solution are about as optimized as they can get?  If I'm wrong about that, I'd like to know why.</p>
<p>If not, what would cause the iterative solution to be so much slower?  It seems to be slower for all values of <code>n</code>, but harder to notice when <code>n</code> is something more reasonable, like <code><1000</code>. (I'm using <code>10000</code> as you can see above)</p>
<p><strong>Some things I've tried:</strong></p>
<ol>
<li>I thought it might be the magic swapping in the iterative solution <code>a, b = b, a + b</code>, so I tried replacing it with a more traditional "swap" pattern:</li>
</ol>
<pre class="lang-py prettyprint-override"><code>tmp = a + b
a = b
b = tmp
#a, b = b, a + b
</code>```

But the results are basically the same, so that's not the problem there.

Re-arrange the code so that the iterative solution runs first, just to see if there was some weird cache issue at the OS level? It doesn't change the results so that's not it, probably?

My understanding here (and it might be wrong) is that the recursive solution with memoization is O(n). And the iterative solution is also O(n) simply because it iterates from 0..n.

Am I missing something really obvious?  I feel like I must be missing something here.

答:
They are not the same.

The recursive version uses the Memoization pattern, calculating only once the result of fibr(n) and storing/caching the result for insta-return if needed again. It's an O(n) algorithm.

The iterative version calculates everything from scratch. It's an O(n2) algorithm (I think).

Body:
I wrote a recursive solution for something today, and as it goes, curiosity led me down a weird path. I wanted to see how an optimized recursive solution compares to an iterative solution so I chose a classic, the Nth Fibonacci to test with.

I was surprised to find that the recursive solution with memoization is much faster than the iterative solution and I would like to know why.

Here is the code (using python3):

import time
import sys
sys.setrecursionlimit(10000)

## recursive:
def fibr(n, memo = {}):
    if n <= 1:
        return n

    if n in memo:
        return memo[n]

    memo[n] = fibr(n-1, memo) + fibr(n-2, memo)

    return memo[n]

## iterative:
def fibi(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

rstart = time.time()
for n in range(10000):
    fibr(n)
rend = time.time()

istart = time.time()
for n in range(10000):
    fibi(n)
iend = time.time()

print(f"recursive: {rend-rstart}")
print(f"iterative: {iend-istart}")

My results:

recursive: 0.010010004043579102
iterative: 6.274333238601685

Unless I'm mistaken, both the recursive solution and the iterative solution are about as optimized as they can get?  If I'm wrong about that, I'd like to know why.

If not, what would cause the iterative solution to be so much slower?  It seems to be slower for all values of n, but harder to notice when n is something more reasonable, like <1000. (I'm using 10000 as you can see above)

Some things I've tried:

I thought it might be the magic swapping in the iterative solution a, b = b, a + b, so I tried replacing it with a more traditional "swap" pattern:

tmp = a + b
a = b
b = tmp
#a, b = b, a + b

But the results are basically the same, so that's not the problem there.

Re-arrange the code so that the iterative solution runs first, just to see if there was some weird cache issue at the OS level? It doesn't change the results so that's not it, probably?

My understanding here (and it might be wrong) is that the recursive solution with memoization is O(n). And the iterative solution is also O(n) simply because it iterates from 0..n.

Am I missing something really obvious?  I feel like I must be missing something here.


问:
Matplotlib: space categorical x axis ticks by numerical value
I have data that I want to plot in a vertically-grouped scatter plot like this:

```<code>q = pd.DataFrame({'time': ['1', '1', '1'], 'velocity': [2, 3, 4]})
q2 = pd.DataFrame({'time': ['3', '3', '3'], 'velocity': [1, 2, 3]})
q3 = pd.DataFrame({'time': ['10', '10', '10'], 'velocity': [2, 1, 4]})

fig, ax = plt.subplots()
ax.scatter(q['time'], q['velocity'], c='green')
ax.scatter(q2['time'], q2['velocity'], c='blue')
ax.scatter(q3['time'], q3['velocity'], c='red')
ax.set_xticks([1, 3, 10])
ax.legend()
</code>```

However, I want the categories on the x-axis to be spaced according to the name of the category. In this case, 'time' from data, data_2 and data_3 are, let's say, vectors populated with repeats of '1', '3', '10'.

I want the distance between category '1' and '3' to be 2 ticks, and the distance from '3' to '10' to be 7 ticks.

Tried to do:

```<code>ax.set_xticks(np.arange(0, 11, 1))
ax.set_xticklabels( [i if str(i) in ['1', '3', '10'] else 0 for i in range(11) ] )
</code>```

But this only creates empty values and still sets the category positions to 0, 1, 2.

Do I need to re-structure my data to incorporate empty values in the interstitial categories, or is there another way?

答:
I think this is what you are trying to do:

In which case, the only thing you really need to do is change your time values from strings to numbers.

```<code>q = pd.DataFrame({'time': [1, 1, 1], 'velocity': [2, 3, 4]})
q2 = pd.DataFrame({'time': [3, 3, 3], 'velocity': [1, 2, 3]})
q3 = pd.DataFrame({'time': [10, 10, 10], 'velocity': [2, 1, 4]})
</code>```

If you did that, and changed your xticklabels command to

```<code>ax.set_xticklabels( [i if i in [1, 3, 10] else 0 for i in range(11) ] )
</code>```

then I think your image would come out the way you wanted.

Alternatively, if you want to keep your dataframe with string values, you can write a function that returns the values as numbers for plotting:

```<code>import pandas as pd
import matplotlib.pyplot as plt

def str2num(mylist):
    return([float(i) for i in mylist])

q = pd.DataFrame({'time': ['1', '1', '1'], 'velocity': [2, 3, 4]})
q2 = pd.DataFrame({'time': ['3', '3', '3'], 'velocity': [1, 2, 3]})
q3 = pd.DataFrame({'time': ['10', '10', '10'], 'velocity': [2, 1, 4]})

fig, ax = plt.subplots()

ax.scatter(str2num(q['time']), q['velocity'], c='green')
ax.scatter(str2num(q2['time']), q2['velocity'], c='blue')
ax.scatter(str2num(q3['time']), q3['velocity'], c='red')
ax.set_xticks(range(11))
ax.set_xticklabels( [i if i in [1, 3, 10] else 0 for i in range(11) ] )
</code>```

Body:
I have data that I want to plot in a vertically-grouped scatter plot like this:

q = pd.DataFrame({'time': ['1', '1', '1'], 'velocity': [2, 3, 4]})
q2 = pd.DataFrame({'time': ['3', '3', '3'], 'velocity': [1, 2, 3]})
q3 = pd.DataFrame({'time': ['10', '10', '10'], 'velocity': [2, 1, 4]})

fig, ax = plt.subplots()
ax.scatter(q['time'], q['velocity'], c='green')
ax.scatter(q2['time'], q2['velocity'], c='blue')
ax.scatter(q3['time'], q3['velocity'], c='red')
ax.set_xticks([1, 3, 10])
ax.legend()

However, I want the categories on the x-axis to be spaced according to the name of the category. In this case, 'time' from data, data_2 and data_3 are, let's say, vectors populated with repeats of '1', '3', '10'.

I want the distance between category '1' and '3' to be 2 ticks, and the distance from '3' to '10' to be 7 ticks.

Tried to do:

ax.set_xticks(np.arange(0, 11, 1))
ax.set_xticklabels( [i if str(i) in ['1', '3', '10'] else 0 for i in range(11) ] )

But this only creates empty values and still sets the category positions to 0, 1, 2.

Do I need to re-structure my data to incorporate empty values in the interstitial categories, or is there another way?

Body:
I think this is what you are trying to do:

In which case, the only thing you really need to do is change your time values from strings to numbers.

q = pd.DataFrame({'time': [1, 1, 1], 'velocity': [2, 3, 4]})
q2 = pd.DataFrame({'time': [3, 3, 3], 'velocity': [1, 2, 3]})
q3 = pd.DataFrame({'time': [10, 10, 10], 'velocity': [2, 1, 4]})

If you did that, and changed your xticklabels command to

ax.set_xticklabels( [i if i in [1, 3, 10] else 0 for i in range(11) ] )

then I think your image would come out the way you wanted.

Alternatively, if you want to keep your dataframe with string values, you can write a function that returns the values as numbers for plotting:

import pandas as pd
import matplotlib.pyplot as plt

def str2num(mylist):
    return([float(i) for i in mylist])

q = pd.DataFrame({'time': ['1', '1', '1'], 'velocity': [2, 3, 4]})
q2 = pd.DataFrame({'time': ['3', '3', '3'], 'velocity': [1, 2, 3]})
q3 = pd.DataFrame({'time': ['10', '10', '10'], 'velocity': [2, 1, 4]})

fig, ax = plt.subplots()

ax.scatter(str2num(q['time']), q['velocity'], c='green')
ax.scatter(str2num(q2['time']), q2['velocity'], c='blue')
ax.scatter(str2num(q3['time']), q3['velocity'], c='red')
ax.set_xticks(range(11))
ax.set_xticklabels( [i if i in [1, 3, 10] else 0 for i in range(11) ] )


问:
Flask migrate error - foreign key associated with column could not find table with which to generate a foreign key to target column
I have two models as following in different files. When I run flask db migrate I get this error.

```<code>raise exc.NoReferencedTableError(
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'datasets.user_id' could not find table 'user' with which to generate a foreign key to target column 'id'
</code>```

What am i doing wrong? Please help me out, thanks.

```<code>class User(Model):
    __tablename__ = "users"
    id = Column(db.Integer, primary_key=True)
    email = Column(db.String(64), unique=True, index=True)
    username = Column(db.String(15), unique=True, index=True)
    role_id = Column(db.Integer, db.ForeignKey("roles.id"))
    userdataset = db.relationship("Dataset", backref="user")

class Dataset(db.Model):
    __tablename__ = 'datasets'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True, unique=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
</code>```

答: If you set the value of the foreign key in the dataset table to users.id, it will work.</p>

Body:
I have two models as following in different files. When I run flask db migrate I get this error.

raise exc.NoReferencedTableError(
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'datasets.user_id' could not find table 'user' with which to generate a foreign key to target column 'id'

What am i doing wrong? Please help me out, thanks.

class User(Model):
    __tablename__ = "users"
    id = Column(db.Integer, primary_key=True)
    email = Column(db.String(64), unique=True, index=True)
    username = Column(db.String(15), unique=True, index=True)
    role_id = Column(db.Integer, db.ForeignKey("roles.id"))
    userdataset = db.relationship("Dataset", backref="user")

class Dataset(db.Model):
    __tablename__ = 'datasets'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True, unique=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))


问:
What is the most efficient way to calculate the least common multiple of two integers?
What is the most efficient way to calculate the least common multiple of two integers?

I just came up with this, but it definitely leaves something to be desired.

int n=7, m=4, n1=n, m1=m;

while( m1 != n1 ){
    if( m1 > n1 )
        n1 += n;
    else
        m1 += m;
}

System.out.println( "lcm is " + m1 );
```

答:
Since we know the mathematic property which states that "product of LCM and HCF of any two numbers is equal to the product of the two numbers".

lets say X and Y are two integers,
then
X * Y = HCF(X, Y) * LCM(X, Y)

Now we can find LCM by knowing the HCF, which we can find through Euclidean Algorithm.

```<code>  LCM(X, Y) = (X * Y) / HCF(X, Y)
</code>```

Hope this will be efficient.

```<code>import java.util.*;
public class Hello {
    public static int HCF(int X, int Y){
        if(X == 0)return Y;
        return HCF(Y%X, X);
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int X = scanner.nextInt(), Y = scanner.nextInt();
        System.out.print((X * Y) / HCF(X, Y));
    }
}
</code>```

Body:
Since we know the mathematic property which states that "product of LCM and HCF of any two numbers is equal to the product of the two numbers".

lets say X and Y are two integers,
then
X * Y = HCF(X, Y) * LCM(X, Y)

Now we can find LCM by knowing the HCF, which we can find through Euclidean Algorithm.

  LCM(X, Y) = (X * Y) / HCF(X, Y)

Hope this will be efficient.

import java.util.*;
public class Hello {
    public static int HCF(int X, int Y){
        if(X == 0)return Y;
        return HCF(Y%X, X);
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int X = scanner.nextInt(), Y = scanner.nextInt();
        System.out.print((X * Y) / HCF(X, Y));
    }
}


问:
Pushing to one element in a nested array is adding to all elements in javascript
I am creating a prefilled nested array and want to push elements to specific indexes, but the elements are being added to all indexes.

```<code>let arr = new Array(4).fill([])
arr => Array(4) [ [], [], [], [] ] //this is what I want
arr[0].push(3)
arr => Array(4) [ [3], [3], [3], [3] ] //I only wanted to push 3 to first index,
//why do all indexes have this element?
</code>```

Any help on how to just update one index would be appreciated.

答:
This initialization method gives an array of length 4 with an empty array in each element:

[...Array(4)].map(() => []); // [[], [], [], []]

or for example you can use

[...Array(4)].map((_, i) => i); // and get [0, 1, 2, 3]

Body:
I am creating a prefilled nested array and want to push elements to specific indexes, but the elements are being added to all indexes.

let arr = new Array(4).fill([])
arr => Array(4) [ [], [], [], [] ] //this is what I want
arr[0].push(3)
arr => Array(4) [ [3], [3], [3], [3] ] //I only wanted to push 3 to first index,
//why do all indexes have this element?

Any help on how to just update one index would be appreciated.


问:
How do I make my Dockerfile use base images from ECR registry instead of Dockerhub?
I have a Codebuild project that is building an docker image and pushing it to ECR registry. I got hit with dockerhub rate limits, so I've been trying to pull the same image from AWS ECR Gallery instead of Dockerhub. How do I force docker build to use the pulled image instead of redownloading the same image with tags from docker hub registry?

Codebuild buildspec.yaml

version: 0.2
phases:
  install:
    runtime-versions:
        docker: 19
    commands:
      - nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://127.0.0.1:2375 --storage-driver=overlay2&
      - timeout 15 sh -c "until docker info; do echo .; sleep 1; done"
  pre_build:
    commands:
    - echo Logging in to Amazon ECR....
    - aws --version
    # update the following line with your own region
    - $(aws ecr get-login --no-include-email --region us-east-1)
    - IMAGE_TAG=$Environment
    - REPOSITORY_URI=<removing-this-part-was-my-private-repository-uri>
    - echo Pushing to $REPOSITORY_URI:$IMAGE_TAG
    - docker pull public.ecr.aws/docker/library/node:14.19.0-alpine3.14
    - docker pull public.ecr.aws/nginx/nginx:alpine
  build:
    commands:
    - echo Build started on `date`
    - echo Building the Docker image...
    # update the following line with the name of your own ECR repository
    - docker build -t local_build:latest .
    # update the following line with the URI of your own ECR repository (view the Push Commands in the console)
    - docker tag local_build:latest $REPOSITORY_URI:$IMAGE_TAG
  post_build:
    commands:
    - echo Build completed on `date`
    - echo pushing to repo
    # update the following line with the URI of your own ECR repository
    - docker push $REPOSITORY_URI:$IMAGE_TAG
```
<p>As you can see, I'm pulling the <code>node:14.19.0-alpine3.14</code> and <code>nginx:alpine</code> images from ECR public gallery.</p>
<p>This is my Dockerfile:</p>
<pre class="lang-docker prettyprint-override"><code># Multi-stage
# 1) Node image for building frontend assets
# 2) nginx stage to serve frontend assets

# Name the node stage "builder"
FROM node:14.19.0-alpine3.14 AS builder
# Some build tools here https://stackoverflow.com/questions/54428608/docker-node-alpine-image-build-fails-on-node-gyp
RUN apk add g++ make py3-pip
# Set working directory
WORKDIR /app
# Copy all files from current directory to working dir in image
COPY . .
# install node modules and build assets
RUN npm ci && npm run build

# nginx state for serving content
FROM nginx:alpine
# Set working directory to nginx asset directory
WORKDIR /usr/share/nginx/html
# Remove default nginx static assets
RUN rm -rf ./*
# Copy static assets from builder stage
COPY --from=builder /app/build .
# Containers run nginx with global directives and daemon off
ENTRYPOINT ["nginx", "-g", "daemon off;"]
</code>```

Codebuild logs:

```<code>[Container] 2022/02/08 04:49:19 Running command docker pull public.ecr.aws/docker/library/node:14.19.0-alpine3.14
113 14.19.0-alpine3.14: Pulling from docker/library/node
114 97518928ae5f: Pulling fs layer
115 94ae0bc29be1: Pulling fs layer
116 d5329011e23a: Pulling fs layer
117 b0eb5127ee8f: Pulling fs layer
118 b0eb5127ee8f: Waiting
119 d5329011e23a: Download complete
120 97518928ae5f: Verifying Checksum
121 97518928ae5f: Download complete
122 b0eb5127ee8f: Verifying Checksum
123 b0eb5127ee8f: Download complete
124 97518928ae5f: Pull complete
125 94ae0bc29be1: Download complete
126 94ae0bc29be1: Pull complete
127 d5329011e23a: Pull complete
128 b0eb5127ee8f: Pull complete
129 Digest: sha256:8c93166ecea91d8384d9f1768ceaca1cd8bc22c1eb13005cecfb491588bd8169
130 Status: Downloaded newer image for public.ecr.aws/docker/library/node:14.19.0-alpine3.14
131 public.ecr.aws/docker/library/node:14.19.0-alpine3.14
132
133 [Container] 2022/02/08 04:49:24 Running command docker pull public.ecr.aws/nginx/nginx:alpine
134 alpine: Pulling from nginx/nginx
135 59bf1c3509f3: Pulling fs layer
136 8d6ba530f648: Pulling fs layer
137 5288d7ad7a7f: Pulling fs layer
138 39e51c61c033: Pulling fs layer
139 ee6f71c6f4a8: Pulling fs layer
140 f2303c6c8865: Pulling fs layer
141 39e51c61c033: Waiting
142 ee6f71c6f4a8: Waiting
143 f2303c6c8865: Waiting
144 5288d7ad7a7f: Download complete
145 39e51c61c033: Verifying Checksum
146 39e51c61c033: Download complete
147 59bf1c3509f3: Verifying Checksum
148 59bf1c3509f3: Download complete
149 ee6f71c6f4a8: Verifying Checksum
150 ee6f71c6f4a8: Download complete
151 f2303c6c8865: Verifying Checksum
152 f2303c6c8865: Download complete
153 8d6ba530f648: Verifying Checksum
154 8d6ba530f648: Download complete
155 59bf1c3509f3: Pull complete
156 8d6ba530f648: Pull complete
157 5288d7ad7a7f: Pull complete
158 39e51c61c033: Pull complete
159 ee6f71c6f4a8: Pull complete
160 f2303c6c8865: Pull complete
161 Digest: sha256:3f033ffbe255618d38a47a4909f257c66620e08ce7b50f4081f16ca09c2cb74f
162 Status: Downloaded newer image for public.ecr.aws/nginx/nginx:alpine
163 public.ecr.aws/nginx/nginx:alpine
164
165 [Container] 2022/02/08 04:49:26 Phase complete: PRE_BUILD State: SUCCEEDED
166 [Container] 2022/02/08 04:49:26 Phase context status code:  Message:
167 [Container] 2022/02/08 04:49:26 Entering phase BUILD
168 [Container] 2022/02/08 04:49:26 Running command echo Build started on `date`
169 Build started on Tue Feb 8 04:49:26 UTC 2022
170
171 [Container] 2022/02/08 04:49:26 Running command echo Building the Docker image...
172 Building the Docker image...
173
174 [Container] 2022/02/08 04:49:26 Running command docker build -t depaint:latest .
175 Sending build context to Docker daemon  2.353MB
176
177 Step 1/10 : FROM node:14.19.0-alpine3.14 AS builder
178 14.19.0-alpine3.14: Pulling from library/node
179 Digest: sha256:8c93166ecea91d8384d9f1768ceaca1cd8bc22c1eb13005cecfb491588bd8169
180 Status: Downloaded newer image for node:14.19.0-alpine3.14
181  ---> 442800913bae
</code>```

Line 179-181 here seems to prove that it's redownloading it again anyway.

I also tried changing the docker build command inside buildspec.yaml to:

```<code>docker build -t <name-removed>:latest --cache-from public.ecr.aws/docker/library/node:14.19.0-alpine3.14 --cache-from public.ecr.aws/nginx/nginx:alpine .
</code>```

This didn't work either

答:
The problem lies here:

```<code>FROM node:14.19.0-alpine3.14 AS builder
</code>```

You haven't specified a registry in this FROM statement. Since you haven't specified a registry, it pulls hub.docker.com/docker/library/node. This is a different tag than public.ecr.aws/docker/library/node:14.19.0-alpine3.14, because all registries have different namespaces.

If you want the version from ECR, you need to specify that in your Dockerfile:

```<code>FROM public.ecr.aws/docker/library/node:14.19.0-alpine3.14
</code>```

This also makes it unnecessary to pull the base image before building - it will automatically fetch the base image if it's not present.

Body:
I have a Codebuild project that is building an docker image and pushing it to ECR registry. I got hit with dockerhub rate limits, so I've been trying to pull the same image from AWS ECR Gallery instead of Dockerhub. How do I force docker build to use the pulled image instead of redownloading the same image with tags from docker hub registry?

Codebuild buildspec.yaml

version: 0.2
phases:
  install:
    runtime-versions:
        docker: 19
    commands:
      - nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://127.0.0.1:2375 --storage-driver=overlay2&
      - timeout 15 sh -c "until docker info; do echo .; sleep 1; done"
  pre_build:
    commands:
    - echo Logging in to Amazon ECR....
    - aws --version
    # update the following line with your own region
    - $(aws ecr get-login --no-include-email --region us-east-1)
    - IMAGE_TAG=$Environment
    - REPOSITORY_URI=<removing-this-part-was-my-private-repository-uri>
    - echo Pushing to $REPOSITORY_URI:$IMAGE_TAG
    - docker pull public.ecr.aws/docker/library/node:14.19.0-alpine3.14
    - docker pull public.ecr.aws/nginx/nginx:alpine
  build:
    commands:
    - echo Build started on `date`
    - echo Building the Docker image...
    # update the following line with the name of your own ECR repository
    - docker build -t local_build:latest .
    # update the following line with the URI of your own ECR repository (view the Push Commands in the console)
    - docker tag local_build:latest $REPOSITORY_URI:$IMAGE_TAG
  post_build:
    commands:
    - echo Build completed on `date`
    - echo pushing to repo
    # update the following line with the URI of your own ECR repository
    - docker push $REPOSITORY_URI:$IMAGE_TAG

As you can see, I'm pulling the node:14.19.0-alpine3.14 and nginx:alpine images from ECR public gallery.

This is my Dockerfile:

# Multi-stage
# 1) Node image for building frontend assets
# 2) nginx stage to serve frontend assets

# Name the node stage "builder"
FROM node:14.19.0-alpine3.14 AS builder
# Some build tools here https://stackoverflow.com/questions/54428608/docker-node-alpine-image-build-fails-on-node-gyp
RUN apk add g++ make py3-pip
# Set working directory
WORKDIR /app
# Copy all files from current directory to working dir in image
COPY . .
# install node modules and build assets
RUN npm ci && npm run build

# nginx state for serving content
FROM nginx:alpine
# Set working directory to nginx asset directory
WORKDIR /usr/share/nginx/html
# Remove default nginx static assets
RUN rm -rf ./*
# Copy static assets from builder stage
COPY --from=builder /app/build .
# Containers run nginx with global directives and daemon off
ENTRYPOINT ["nginx", "-g", "daemon off;"]

Codebuild logs:

[Container] 2022/02/08 04:49:19 Running command docker pull public.ecr.aws/docker/library/node:14.19.0-alpine3.14
113 14.19.0-alpine3.14: Pulling from docker/library/node
114 97518928ae5f: Pulling fs layer
115 94ae0bc29be1: Pulling fs layer
116 d5329011e23a: Pulling fs layer
117 b0eb5127ee8f: Pulling fs layer
118 b0eb5127ee8f: Waiting
119 d5329011e23a: Download complete
120 97518928ae5f: Verifying Checksum
121 97518928ae5f: Download complete
122 b0eb5127ee8f: Verifying Checksum
123 b0eb5127ee8f: Download complete
124 97518928ae5f: Pull complete
125 94ae0bc29be1: Download complete
126 94ae0bc29be1: Pull complete
127 d5329011e23a: Pull complete
128 b0eb5127ee8f: Pull complete
129 Digest: sha256:8c93166ecea91d8384d9f1768ceaca1cd8bc22c1eb13005cecfb491588bd8169
130 Status: Downloaded newer image for public.ecr.aws/docker/library/node:14.19.0-alpine3.14
131 public.ecr.aws/docker/library/node:14.19.0-alpine3.14
132
133 [Container] 2022/02/08 04:49:24 Running command docker pull public.ecr.aws/nginx/nginx:alpine
134 alpine: Pulling from nginx/nginx
135 59bf1c3509f3: Pulling fs layer
136 8d6ba530f648: Pulling fs layer
137 5288d7ad7a7f: Pulling fs layer
138 39e51c61c033: Pulling fs layer
139 ee6f71c6f4a8: Pulling fs layer
140 f2303c6c8865: Pulling fs layer
141 39e51c61c033: Waiting
142 ee6f71c6f4a8: Waiting
143 f2303c6c8865: Waiting
144 5288d7ad7a7f: Download complete
145 39e51c61c033: Verifying Checksum
146 39e51c61c033: Download complete
147 59bf1c3509f3: Verifying Checksum
148 59bf1c3509f3: Download complete
149 ee6f71c6f4a8: Verifying Checksum
150 ee6f71c6f4a8: Download complete
151 f2303c6c8865: Verifying Checksum
152 f2303c6c8865: Download complete
153 8d6ba530f648: Verifying Checksum
154 8d6ba530f648: Download complete
155 59bf1c3509f3: Pull complete
156 8d6ba530f648: Pull complete
157 5288d7ad7a7f: Pull complete
158 39e51c61c033: Pull complete
159 ee6f71c6f4a8: Pull complete
160 f2303c6c8865: Pull complete
161 Digest: sha256:3f033ffbe255618d38a47a4909f257c66620e08ce7b50f4081f16ca09c2cb74f
162 Status: Downloaded newer image for public.ecr.aws/nginx/nginx:alpine
163 public.ecr.aws/nginx/nginx:alpine
164
165 [Container] 2022/02/08 04:49:26 Phase complete: PRE_BUILD State: SUCCEEDED
166 [Container] 2022/02/08 04:49:26 Phase context status code:  Message:
167 [Container] 2022/02/08 04:49:26 Entering phase BUILD
168 [Container] 2022/02/08 04:49:26 Running command echo Build started on `date`
169 Build started on Tue Feb 8 04:49:26 UTC 2022
170
171 [Container] 2022/02/08 04:49:26 Running command echo Building the Docker image...
172 Building the Docker image...
173
174 [Container] 2022/02/08 04:49:26 Running command docker build -t depaint:latest .
175 Sending build context to Docker daemon  2.353MB
176
177 Step 1/10 : FROM node:14.19.0-alpine3.14 AS builder
178 14.19.0-alpine3.14: Pulling from library/node
179 Digest: sha256:8c93166ecea91d8384d9f1768ceaca1cd8bc22c1eb13005cecfb491588bd8169
180 Status: Downloaded newer image for node:14.19.0-alpine3.14
181  ---> 442800913bae

Line 179-181 here seems to prove that it's redownloading it again anyway.

I also tried changing the docker build command inside buildspec.yaml to:

docker build -t <name-removed>:latest --cache-from public.ecr.aws/docker/library/node:14.19.0-alpine3.14 --cache-from public.ecr.aws/nginx/nginx:alpine .

This didn't work either

Body:
The problem lies here:

FROM node:14.19.0-alpine3.14 AS builder

You haven't specified a registry in this FROM statement. Since you haven't specified a registry, it pulls hub.docker.com/docker/library/node. This is a different tag than public.ecr.aws/docker/library/node:14.19.0-alpine3.14, because all registries have different namespaces.

If you want the version from ECR, you need to specify that in your Dockerfile:

FROM public.ecr.aws/docker/library/node:14.19.0-alpine3.14

This also makes it unnecessary to pull the base image before building - it will automatically fetch the base image if it's not present.


问:
How to Execute SQL Server Stored Procedure in SQL Developer?
I've been given a user account to a SQL Server database that only has privileges to execute a stored procedure. I added the JTDS SQL Server JDBC jar file to SQL Developer and added it as a Third Party JDBC driver. I can successfully log in to the SQL Server database.  I was given this syntax for running the procedure:

```<code>EXEC proc_name 'paramValue1' 'paramValue2'
</code>```

When I run this as either a statement or a script, I get this error:

```<code>Error starting at line 1 in command:
EXEC proc_name 'paramValue1' 'paramValue2'
Error report:
Incorrect syntax near the keyword 'BEGIN'.
</code>```

I tried wrapping the statement in BEGIN/END, but get the same error.  Is it possible to call the procedure from SQL Developer?  If so, what syntax do I need to use?

答:
There are two ways we can call stored procedure

CALL database name'. 'stored procedure name(parameter values);
example:- CALL dbs_nexopay_sisd1_dec_23.spr_v2_invoice_details_for_invoice_receipt_sub_swiss(1, 1, 1, 1);

From your MySQL workbench also you can do that.
i. Right-click on stored procedure.
ii. Send to SQL editor
iii. Procedure call.

Body:
I've been given a user account to a SQL Server database that only has privileges to execute a stored procedure. I added the JTDS SQL Server JDBC jar file to SQL Developer and added it as a Third Party JDBC driver. I can successfully log in to the SQL Server database.  I was given this syntax for running the procedure:

EXEC proc_name 'paramValue1' 'paramValue2'

When I run this as either a statement or a script, I get this error:

Error starting at line 1 in command:
EXEC proc_name 'paramValue1' 'paramValue2'
Error report:
Incorrect syntax near the keyword 'BEGIN'.

I tried wrapping the statement in BEGIN/END, but get the same error.  Is it possible to call the procedure from SQL Developer?  If so, what syntax do I need to use?