问:
Click two elements at the same time by clicking one button with javascript
Is it possible to click one button and simultaneously click another element. Like I click a button to show an image and simultaneously let something else appear which would also appear when clicking on it</p>

答:
It's totally possible. You have to get the click event of the element, and you can do whatever you want.

Example:

  <button id="button">I am a button</button>

```

Body:
It's totally possible. You have to get the click event of the element, and you can do whatever you want.

Example:

  <button id="button">I am a button</button>
  <div id="anotherElement"></div>
  <script>
    const button = document.getElementById('button');
    const anotherElement = document.getElementById('anotherElement');
    button.addEventListener('click', () => {
      // do whatever you want here
      anotherElement.click();
    });
  </script>


来源: stackexchange

问:
How to contain diff between two local git branches
I have same working directory but often keeps switching between two branches whose git head is at different points and also different local changes. Without pushing the diff to remote repo is there a way to maintain/ restrict the changes and not overwrite it when switching from one branch to another branch. I am not sure if git would track locally in this way? Please help

Say i am on branch 1 made some changes i.e. diff1, didnot stash this. Now i want to switch to another branch 2, at this point git complains either to commit or stash changes (diff1)? I am asking if we can switch to branch 2 without having to stash/ discard/ commit diff1 changes? somehow switch to branch 2 and work on changes, now when issued git diff it should show diff2 but not diff1. Dont know if this is even possible.

答:
Say i am on branch 1 made some changes i.e. diff1, didnot stash this. Now i want to switch to another branch 2, at this point git complains either to commit or stash changes (diff1)?

@torek's answer is great and gives a lot of the detail. The one thing I'd like to emphasize is that if you made changes that you didn't commit, then git has no way to know how to resolve those changes with changes on another branch. This happens when two branches makes different changes to the same line of code and is one reason that git complains in the situation you describe.

I am asking if we can switch to branch 2 without having to stash/ discard/ commit diff1 changes?

So the answer here should not be clear: no, you cannot switch branches without stashing, discarding, or committing your local, uncommitted changes. The message from git should make this clear.

ContentLicense: CC BY-SA 4.0


问:
Android: draw using fb0 on eink device
I've been looking a lot around, and can't find much of anything clear. The context is I have a stylus-enabled e-ink tablet that I program on for fun, and I'd love to use a native library to read the pen events, and draw directly on the framebuffer. The vendor provides one, secret (a .so JNI lib that you can call with just a size parameter).

I suppose this is intended to activate a direct draw on the frame buffer, eventually with a refresh. But I can't grasp how it's supposed to compose with SurfaceFlinger and Android...

Anyone has experience with generic eink tricks to display from JNI via IOCTL that could explain me why I don't see the pixels changing unless I draw myself in java (I can change the update mode and draw quite fast, but... I want the fastest) ?

How could I verify writes on the FB ? Can an android app be "overlayed" by pixels written directly on the framebuffer ?

答: I suggest you write a basic pixel plotting program in C for framebuffer. Execute it normally and then create a JNI call for the same. The speed difference is negligible to notice.</p>

Title: Android: draw using fb0 on eink device


问:
How to host prisma application on cpanel?
I build a express app with prisma, and upload to cpanel hosting, then run this command:
npx prisma migrate dev
npx prisma migrate deploy
npx prisma generate

and get this same error

```<code>Error: Unable to require(`/home/u1254216/nodevenv/node_apps/cpanel_prisma/16/lib/node_modules/@prisma/engines/libquery_engine-debian-openssl-1.1.x.so.node`)
 /lib64/libc.so.6: version `GLIBC_2.18' not found (required by /home/u1254216/nodevenv/node_apps/cpanel_prisma/16/lib/node_modules/@prisma/engines/libquery_engine-debian-openssl-1.1.x.so.node)
</code>```

my schema.prisma file:

```<code>generator client {
  provider      = "prisma-client-js"
  binaryTargets = ["native", "debian-openssl-1.1.x"]
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}
</code>```

prisma version:

```<code>"prisma": "^3.9.1"
"@prisma/client": "^3.9.1"
</code>```

how to fix this?

答: If your hosting OS is centOS, You can't run prisma, Because it's need some libs (like GLIBC_2.18) that not install on centOs.</p>

Body:
I build a express app with prisma, and upload to cpanel hosting, then run this command:
npx prisma migrate dev
npx prisma migrate deploy
npx prisma generate

and get this same error

Error: Unable to require(`/home/u1254216/nodevenv/node_apps/cpanel_prisma/16/lib/node_modules/@prisma/engines/libquery_engine-debian-openssl-1.1.x.so.node`)
 /lib64/libc.so.6: version `GLIBC_2.18' not found (required by /home/u1254216/nodevenv/node_apps/cpanel_prisma/16/lib/node_modules/@prisma/engines/libquery_engine-debian-openssl-1.1.x.so.node)

my schema.prisma file:

generator client {
  provider      = "prisma-client-js"
  binaryTargets = ["native", "debian-openssl-1.1.x"]
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

prisma version:

"prisma": "^3.9.1"
"@prisma/client": "^3.9.1"

how to fix this?


问:
How to make an annotation layer relative to a geom_point layer
I would like the annotated text on this chart to be relative to the data points on the line chart because this report is parameterized so the points change with each iteration. How do I make the annotation layer relative to the geom_point layer?
This is what I've tried...

```<code>degree_line <- degree_summary %>%
  ggplot(mapping = aes(x = chrt_grad, y = proportion, group = 1)) +
  geom_line(size = 1) +
  geom_point(shape = 1, stroke = 1.5) +
  scale_y_continuous(expand = expansion(mult = c(0, .1)),
                     labels = scales::percent,
                     limits = c(0, .4)) +
  annotate(geom = "text", x = 2016.8, y = degree_summary$proportion + .05, label = "4-year rate",
           size = 3, hjust = 0, color = "#696969") +
  annotate(geom = "text", x = 2015.1, y = degree_summary$proportion + .05, label = "6-year rate",
           size = 3, hjust = 1, color = "#696969") +
  labs(x = NULL,
       y = NULL)
</code>```

But this is what I get...

dput(degree_summary)

```<code>structure(list(chrt_grad = 2014:2017, graduated = c("Y", "Y",
"Y", "Y"), school = c("Bonita Vista Senior High", "Bonita Vista Senior High",
"Bonita Vista Senior High", "Bonita Vista Senior High"), total = c(132L,
122L, 117L, 92L), proportion = c(0.0172639288516872, 0.0167859108420473,
0.0187259923175416, 0.0199522880069399)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), groups = structure(list(
    chrt_grad = 2014:2017, graduated = c("Y", "Y", "Y", "Y"),
    .rows = structure(list(1L, 2L, 3L, 4L), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))
</code>```

答:
I added a new column to your data containing the desired label. Then you can use geom_text for the annotations:

degree_summary %>%
  dplyr::mutate(
    label = dplyr::case_when(
      chrt_grad == 2015 ~ "6-year rate",
      chrt_grad == 2017 ~ "4-year rate",
      TRUE ~ ""
    )
  ) %>%
  ggplot(mapping = aes(x = chrt_grad, y = proportion, group = 1)) +
  geom_line(size = 1) +
  geom_point(shape = 1, stroke = 1.5) +
  geom_text(aes(label = label), nudge_y = 0.0005)
  scale_y_continuous(expand = expansion(mult = c(0, .1)),
                     labels = scales::percent,
                     limits = c(0, .4))
```

Body:
I would like the annotated text on this chart to be relative to the data points on the line chart because this report is parameterized so the points change with each iteration. How do I make the annotation layer relative to the geom_point layer?
This is what I've tried...

degree_line <- degree_summary %>%
  ggplot(mapping = aes(x = chrt_grad, y = proportion, group = 1)) +
  geom_line(size = 1) +
  geom_point(shape = 1, stroke = 1.5) +
  scale_y_continuous(expand = expansion(mult = c(0, .1)),
                     labels = scales::percent,
                     limits = c(0, .4)) +
  annotate(geom = "text", x = 2016.8, y = degree_summary$proportion + .05, label = "4-year rate",
           size = 3, hjust = 0, color = "#696969") +
  annotate(geom = "text", x = 2015.1, y = degree_summary$proportion + .05, label = "6-year rate",
           size = 3, hjust = 1, color = "#696969") +
  labs(x = NULL,
       y = NULL)

But this is what I get...

dput(degree_summary)

structure(list(chrt_grad = 2014:2017, graduated = c("Y", "Y",
"Y", "Y"), school = c("Bonita Vista Senior High", "Bonita Vista Senior High",
"Bonita Vista Senior High", "Bonita Vista Senior High"), total = c(132L,
122L, 117L, 92L), proportion = c(0.0172639288516872, 0.0167859108420473,
0.0187259923175416, 0.0199522880069399)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), groups = structure(list(
    chrt_grad = 2014:2017, graduated = c("Y", "Y", "Y", "Y"),
    .rows = structure(list(1L, 2L, 3L, 4L), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))


问:
Error with angular & angular/cli versions
I have this error on angular docker project:

```<code>industrialareas_angular_ctnr | This version of CLI is only compatible with Angular versions ^13.0.0-next || >=13.0.0 <14.0.0,
industrialareas_angular_ctnr | but Angular version 12.2.16 was found instead.
</code>```

My Dockerfile-angular file is:

```<code>FROM node:14
WORKDIR /usr/src/app
RUN npm uninstall -g @angular/cli
RUN npm uninstall @angular/cli
RUN npm i @angular/cli@12.2.8
RUN npm cache clean --force
COPY ./project/package*.json .
RUN npm install
RUN npm link @angular/cli
COPY ./project .
EXPOSE 4200
CMD npm start
</code>```

My docker-compose.yml file is:

```<code>version: '3.7'
services:
  angular:
    container_name: industrialareas_angular_ctnr
    build:
      context: .
      dockerfile: Dockerfile-angular
    restart: unless-stopped
    volumes:
      - ./project/src:/usr/src/app/src
    ports:
      - 4200:4200
</code>```

And the package.json file is:

```<code>...
"dependencies": {
  ...
  "@angular/core": "~12.2.0",
  ...
},
"devDependencies": {
  ...
  "@angular/cli": "~12.2.8",
  ...
</code>```

I have checked compatibility versions on this link

Anybody could help me please ? Thanks in advance.

答:
Angular CLI version that u declared in JSON isn't compatible with Angular core version u used: would be more clear if u post whole package.json file content.

To solve issue, you can either upgrade angular core version to 13.0.0 and next, or you can downgrade angular cli version: the link doesn't come from official documentation, so it's not viable

Body:
I have this error on angular docker project:

industrialareas_angular_ctnr | This version of CLI is only compatible with Angular versions ^13.0.0-next || >=13.0.0 <14.0.0,
industrialareas_angular_ctnr | but Angular version 12.2.16 was found instead.

My Dockerfile-angular file is:

FROM node:14
WORKDIR /usr/src/app
RUN npm uninstall -g @angular/cli
RUN npm uninstall @angular/cli
RUN npm i @angular/cli@12.2.8
RUN npm cache clean --force
COPY ./project/package*.json .
RUN npm install
RUN npm link @angular/cli
COPY ./project .
EXPOSE 4200
CMD npm start

My docker-compose.yml file is:

version: '3.7'
services:
  angular:
    container_name: industrialareas_angular_ctnr
    build:
      context: .
      dockerfile: Dockerfile-angular
    restart: unless-stopped
    volumes:
      - ./project/src:/usr/src/app/src
    ports:
      - 4200:4200

And the package.json file is:

...
"dependencies": {
  ...
  "@angular/core": "~12.2.0",
  ...
},
"devDependencies": {
  ...
  "@angular/cli": "~12.2.8",
  ...

I have checked compatibility versions on this link

Anybody could help me please ? Thanks in advance.


问:
Practical uses of git reset --soft?
I have been working with git for just over a month. Indeed I have used reset for the first time only yesterday, but the soft reset still doesn't make much sense to me.

I understand I can use the soft reset to edit a commit without altering the index or the working directory, as I would with git commit --amend.

Are these two commands really the same (reset --soft vs commit --amend)? Any reason to use one or the other in practical terms? And more importantly, are there any other uses for reset --soft apart from amending a commit?

答:
I usually use both git reset --soft and git commit --amend in order to combine commits.
For example if I have a commit history like:

```<code>master: A--B--C
</code>```

At this point I just want to keep commit A and delete commit B and C but still keep the changes. First:

```<code>git reset --soft <commit A's hash>
</code>```

because the option --soft just bring you back at a specific commit and still keep the changes. Now you can apply those change to your commit A:

```<code>git commit --amend
</code>```

Or you can rename that commit as well:

```<code>git commit --amend -m 'your new commit message'
</code>```

After that, if you want to push the to the remote repository, you will have to use:

```<code>git push -f origin master
</code>```

Please note that it seems like you 'went back' to your old commit but in fact, the amended commit is a new commit and has replaced that old commit A (you can check it's hash id by using git log), but in the end, you still have a nice commit history like you intended.

ContentLicense: CC BY-SA 3.0

Title: Practical uses of git reset --soft?

Body:
I usually use both git reset --soft and git commit --amend in order to combine commits.
For example if I have a commit history like:

master: A--B--C

At this point I just want to keep commit A and delete commit B and C but still keep the changes. First:

git reset --soft <commit A's hash>

because the option --soft just bring you back at a specific commit and still keep the changes. Now you can apply those change to your commit A:

git commit --amend

Or you can rename that commit as well:

git commit --amend -m 'your new commit message'

After that, if you want to push the to the remote repository, you will have to use:

git push -f origin master

Please note that it seems like you 'went back' to your old commit but in fact, the amended commit is a new commit and has replaced that old commit A (you can check it's hash id by using git log), but in the end, you still have a nice commit history like you intended.


问:
Update happens only on the last row, instead of first
```<code>function createTextFields(obj) {
    for (var i = 0; i < obj.length; i++) {
        var dataDump = {};
        for (var key in obj[i]) {
            var textField = Ti.UI.createTextField(pm.combine($$.labelBrown, {
            left: 200,
            height:35,
            value:obj[i][key],
            width:550,
            keyboardType:Ti.UI.KEYBOARD_NUMBER_PAD,
            layout:'horizontal',
            backgroundColor:'transparent',
            id:i
         }));

            dataDump[key] = textField.value;
            var callback = function (vbKey) {
                    return function (e) {
                        dataDump[vbKey] = e.source.value;
                    };
                }(key);
        }
        globalData.push(dataDump);
    }

}
</code>```

I am using the simlar code for Adding the data and it works fine. I posted the problem yesterday and it got resolved...

Last Object is always getting updated?

Now when i go to edit page, it shows me four text fields or number of text fields added... now when i edit something and click on save... the value get's updated on the fourth or the last TextFields Object...

答:
Don't define functions inside loops. Computationally expensive and leads to problems, like this one. Here's a fix that should solve it:</p>

```<code>function createTextFields(obj) {

     var callback = function (vbKey, localDump) {
                    return function (e) {
                        localDump[vbKey] = e.source.value;
                    };
                }
    var i;
    var max = obj.length;
    for (i = 0; i < max; i++) {
        var dataDump = {};
        for (var key in obj[i]) {
            dataDump[key] = textField.value;
            var callBackInstance = function(keyn, dataDump);
         }
        globalData.push(dataDump);
    }

}
</code>```

Body:
function createTextFields(obj) {
    for (var i = 0; i < obj.length; i++) {
        var dataDump = {};
        for (var key in obj[i]) {
            var textField = Ti.UI.createTextField(pm.combine($$.labelBrown, {
            left: 200,
            height:35,
            value:obj[i][key],
            width:550,
            keyboardType:Ti.UI.KEYBOARD_NUMBER_PAD,
            layout:'horizontal',
            backgroundColor:'transparent',
            id:i
         }));

            dataDump[key] = textField.value;
            var callback = function (vbKey) {
                    return function (e) {
                        dataDump[vbKey] = e.source.value;
                    };
                }(key);
        }
        globalData.push(dataDump);
    }

}

I am using the simlar code for Adding the data and it works fine. I posted the problem yesterday and it got resolved...

Last Object is always getting updated?

Now when i go to edit page, it shows me four text fields or number of text fields added... now when i edit something and click on save... the value get's updated on the fourth or the last TextFields Object...

Body:
Don't define functions inside loops. Computationally expensive and leads to problems, like this one. Here's a fix that should solve it:

function createTextFields(obj) {

     var callback = function (vbKey, localDump) {
                    return function (e) {
                        localDump[vbKey] = e.source.value;
                    };
                }
    var i;
    var max = obj.length;
    for (i = 0; i < max; i++) {
        var dataDump = {};
        for (var key in obj[i]) {
            dataDump[key] = textField.value;
            var callBackInstance = function(keyn, dataDump);
         }
        globalData.push(dataDump);
    }

}


问:
Tried to update field with a model instance, <SimpleLazyObject:<<>>. Use a value compatible with CharField
I am trying to over ride the save method in my model to store the currently loged in user. I am using the django-current user to get the authenticated user. I wrote this code

```<code>from django_currentuser.middleware import (
    get_current_user, get_current_authenticated_user)

from django_currentuser.db.models import CurrentUserField

 uploaded_by = models.CharField(max_length=255, blank=True, null=True, editable=False)

 def save(self, *args, **kwargs):

     user = get_current_authenticated_user()

     self.uploaded_by = user

     super(Citation, self).save(*args, **kwargs)

</code>```

But I am getting this error

```<code>Tried to update field professional.Citation.uploaded_by with a model instance, <SimpleLazyObject: <CustomUser: staff@gmail.com>>. Use a value compatible with CharField.
</code>```

What should I do? I want to store the currently logged in user in the model save method and also keep this field non editable.

I am getting this error only when the field is being updated. It is working fine wile saving for the first time

答:
This is how I overcame the error

```<code>def save(self, *args, **kwargs):

        current_user = get_current_authenticated_user()

        user =CustomUser.objects.get(email = current_user)

        self.uploaded_by = user.email

        super(Citation, self).save(*args, **kwargs)

</code>```

Here I am getting the user before directly saving it using get_current_authenticated_user() and then I am storing the user name (in my case email).

Body:
I am trying to over ride the save method in my model to store the currently loged in user. I am using the django-current user to get the authenticated user. I wrote this code

from django_currentuser.middleware import (
    get_current_user, get_current_authenticated_user)

from django_currentuser.db.models import CurrentUserField

 uploaded_by = models.CharField(max_length=255, blank=True, null=True, editable=False)

 def save(self, *args, **kwargs):

     user = get_current_authenticated_user()

     self.uploaded_by = user

     super(Citation, self).save(*args, **kwargs)

But I am getting this error

Tried to update field professional.Citation.uploaded_by with a model instance, <SimpleLazyObject: <CustomUser: staff@gmail.com>>. Use a value compatible with CharField.

What should I do? I want to store the currently logged in user in the model save method and also keep this field non editable.

I am getting this error only when the field is being updated. It is working fine wile saving for the first time

Body:
This is how I overcame the error

def save(self, *args, **kwargs):

        current_user = get_current_authenticated_user()

        user =CustomUser.objects.get(email = current_user)

        self.uploaded_by = user.email

        super(Citation, self).save(*args, **kwargs)

Here I am getting the user before directly saving it using get_current_authenticated_user() and then I am storing the user name (in my case email).


问:
How to call a specific function when the app is updated from Store or is First installed in Android?
I have an app with a Login functionality and also auto Login, and before login screen, a Splash Screen Activity is displayed. Inside Splash Screen activity I want to check if the user has just updated the app from the Google play to a newer version, and if so, to always show him the Login screen.
So my question is, how to check if current version app is different from the last version?
I tried solutions found in this topic: Detect if new install or updated version (Android app)

But in this function

```<code>public static boolean isInstallFromUpdate(Context context) {
    try {
        long firstInstallTime = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).firstInstallTime;
        long lastUpdateTime = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).lastUpdateTime;
        return firstInstallTime != lastUpdateTime;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}
</code>```

This line is always true: firstInstallTime != lastUpdateTime;, but after an update, if I close the app and then reopen it, this line should be false.
If you have any suggestions or need more details, please let me know! Thanks

答: You can simply set a SharedPreference, if you open the app after an update. After you closed the app and reopened it, you should check for your isInstallFromUpdate(...) and the just set SharedPreference

Body:
I have an app with a Login functionality and also auto Login, and before login screen, a Splash Screen Activity is displayed. Inside Splash Screen activity I want to check if the user has just updated the app from the Google play to a newer version, and if so, to always show him the Login screen.
So my question is, how to check if current version app is different from the last version?
I tried solutions found in this topic: Detect if new install or updated version (Android app)

But in this function

public static boolean isInstallFromUpdate(Context context) {
    try {
        long firstInstallTime = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).firstInstallTime;
        long lastUpdateTime = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).lastUpdateTime;
        return firstInstallTime != lastUpdateTime;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}

This line is always true: firstInstallTime != lastUpdateTime;, but after an update, if I close the app and then reopen it, this line should be false.
If you have any suggestions or need more details, please let me know! Thanks


问:
Calling a method of Runnable object doesn't affect objects outside of it JAVA
Given the code bellow, I Create two objects and ask the Swapper to swap between them.
Therefore the outcome should look like this:

```<code>1, 2
2, 1
</code>```

but it appears to not work, and the outcome is two lines of "1,2".

The example we were given did swap between them, with the only difference of using an object that has a "get, set" function for the data inside it.

Is this not working because of the "set, get" functions not present, or would this not work either way?

```<code> public static void main(String[] args) throws InterruptedException {
    StringBuffer _i1 , _i2;
    _i1 = new StringBuffer("1");
    _i2 = new StringBuffer("2");
    Thread t = new Thread(new Swapper(_i1, _i2));
    System.out.println(_i1 + ", " + _i2);
    System.out.println(_i1 + ", " + _i2);
    t.start();
    t.join();
    System.out.println(_i1 + ", " + _i2);
   }
}
class Swapper<Static> implements  Runnable {
StringBuffer _i1 , _i2;
Swapper(StringBuffer i1, StringBuffer i2) { _i1 = i1; _i2=i2;}
public void run(){
    synchronized (_i1){
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (_i2){
            StringBuffer tmp = _i1;
            _i1 = _i2;
            _i2 = tmp;
        }
    }
}
</code>```

答:
Firstly, I encourage you to get familiar with a naming convention, use only camel-case, no _i1 or anything along these lines.

The reason why your code isn't working is because you are confusing an object and a reference to the object.

You have two reference variables inside the main() method, and  two reference variables in the Swapper. Since in the method run() you are juggling with references but not changing the objects, the reference variables in main() stay unaffected because they still point to the same objects.

To change i1 and i2 you need to change the objects they are pointing to.

Side notes:

The generic parameter <Static> is unused in your code and its name doesn't make any sense (it the same as Swapper<T> where <T> is just a placeholder for a type);

don't synchronize your code against references that are being changed.

```<code>public static void main(String[] args) throws InterruptedException {
    StringBuffer i1 = new StringBuffer("1");
    StringBuffer i2 = new StringBuffer("2");

    Thread t = new Thread(new Swapper(i1, i2));
    System.out.println(i1 + ", " + i2);
    t.start();
    t.join();
    System.out.println(i1 + ", " + i2);
}

class Swapper implements  Runnable {
    private final StringBuffer i1;
    private final StringBuffer i2;

    Swapper(StringBuffer i1, StringBuffer i2) {
        this.i1 = i1;
        this.i2 = i2;
    }

    public void run(){
        synchronized (i1){
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (i2){
                StringBuffer tmp = new StringBuffer(i1);
                i1.replace(0, i1.length(), i2.toString());
                i2.replace(0, i2.length(), tmp.toString());
            }
        }
    }
}
</code>```

Output:

1, 2
2, 1
```

Body:
Given the code bellow, I Create two objects and ask the Swapper to swap between them.
Therefore the outcome should look like this:

1, 2
2, 1

but it appears to not work, and the outcome is two lines of "1,2".

The example we were given did swap between them, with the only difference of using an object that has a "get, set" function for the data inside it.

Is this not working because of the "set, get" functions not present, or would this not work either way?

 public static void main(String[] args) throws InterruptedException {
    StringBuffer _i1 , _i2;
    _i1 = new StringBuffer("1");
    _i2 = new StringBuffer("2");
    Thread t = new Thread(new Swapper(_i1, _i2));
    System.out.println(_i1 + ", " + _i2);
    System.out.println(_i1 + ", " + _i2);
    t.start();
    t.join();
    System.out.println(_i1 + ", " + _i2);
   }
}
class Swapper<Static> implements  Runnable {
StringBuffer _i1 , _i2;
Swapper(StringBuffer i1, StringBuffer i2) { _i1 = i1; _i2=i2;}
public void run(){
    synchronized (_i1){
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (_i2){
            StringBuffer tmp = _i1;
            _i1 = _i2;
            _i2 = tmp;
        }
    }
}

Body:
Firstly, I encourage you to get familiar with a naming convention, use only camel-case, no _i1 or anything along these lines.

The reason why your code isn't working is because you are confusing an object and a reference to the object.

You have two reference variables inside the main() method, and  two reference variables in the Swapper. Since in the method run() you are juggling with references but not changing the objects, the reference variables in main() stay unaffected because they still point to the same objects.

To change i1 and i2 you need to change the objects they are pointing to.

Side notes:

The generic parameter <Static> is unused in your code and its name doesn't make any sense (it the same as Swapper<T> where <T> is just a placeholder for a type);

don't synchronize your code against references that are being changed.

public static void main(String[] args) throws InterruptedException {
    StringBuffer i1 = new StringBuffer("1");
    StringBuffer i2 = new StringBuffer("2");

    Thread t = new Thread(new Swapper(i1, i2));
    System.out.println(i1 + ", " + i2);
    t.start();
    t.join();
    System.out.println(i1 + ", " + i2);
}

class Swapper implements  Runnable {
    private final StringBuffer i1;
    private final StringBuffer i2;

    Swapper(StringBuffer i1, StringBuffer i2) {
        this.i1 = i1;
        this.i2 = i2;
    }

    public void run(){
        synchronized (i1){
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (i2){
                StringBuffer tmp = new StringBuffer(i1);
                i1.replace(0, i1.length(), i2.toString());
                i2.replace(0, i2.length(), tmp.toString());
            }
        }
    }
}

Output:

1, 2
2, 1


问:
How to handle Sagemaker Batch Transform discarding a file with a failed model request
I have a large number of JSON requests for a model split across multiple files in an S3 bucket. I would like to use Sagemaker's Batch Transform feature to process all of these requests (I have done a couple of test runs using small amounts of data and the transform job succeeds). My main issue is here (https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform.html#batch-transform-errors), specifically:

If a batch transform job fails to process an input file because of a problem with the dataset, SageMaker marks the job as failed. If an input file contains a bad record, the transform job doesn't create an output file for that input file because doing so prevents it from maintaining the same order in the transformed data as in the input file. When your dataset has multiple input files, a transform job continues to process input files even if it fails to process one. The processed files still generate useable results.

This is not preferable mainly because if 1 request fails (whether its a transient error, a malformmated request, or something wrong with the model container) in a file with a large number of requests, all of those requests will get discarded (even if all of them succeeded and the last one failed). I would ideally prefer Sagemaker to just write the output of the failed response to the file and keep going, rather than discarding the entire file.

My question is, are there any suggestions to mitigating this issue? I was thinking about storing 1 request per file in S3, but this seems somewhat ridiculous? Even if I did this, is there a good way of seeing which requests specifically failed after the transform job finishes?

答:
You've got the right idea: the fewer datapoints are in each file, the less likely a given file is to fail. The issue is that while you can pass a prefix with many files to CreateTransformJob, partitioning one datapoint per file at least requires an S3 read per datapoint, plus a model invocation per datapoint, which is probably not great. Be aware also that apparently there are hidden rate limits.

Here are a couple options:

Partition into small-ish files, and plan on failures being rare. Hopefully, not many of your datapoints would actually fail. If you partition your dataset into e.g. 100 files, then a single failure only requires reprocessing 1% of your data. Note that Sagemaker has built-in retries, too, so most of the time failures should be caused by your data/logic, not randomness on Sagemaker's side.

Deal with failures directly in your model. The same doc you quoted in your question also says:

If you are using your own algorithms, you can use placeholder text, such as ERROR, when the algorithm finds a bad record in an input file. For example, if the last record in a dataset is bad, the algorithm places the placeholder text for that record in the output file.

Note that the reason Batch Transform does this whole-file failure is to maintain a 1-1 mapping between rows in the input and the output. If you can substitute the output for failed datapoints with an error message from inside your model, without actually causing the model itself to fail processing, Batch Transform will be happy.


问:
discord.js v13 bot uptime
I made some bot uptime code but got an error showing 52 years ago The code is below.

const style = 'R'
const starttime = `<t:${Math.floor(client.readyAt / 1000)}` + (style ? `:${style}` : '') + '>'

client.on('messageCreate' , message=>{
    if(message.content == "!uptime"){
        message.reply(`uptime!\n uptime : ${starttime}`)
    }
})
```

答:
You are setting that outside of the event, where client.readyAt is null. When you divide null by anything except for 0, you get 0. The result would then be <t:0:R>. You could either make this a function, or set it in the event

function generateReadyTimestamp() {
  return `<t:${Math.floor(client.readyAt / 1000)}` + (style ? `:${style}` : '') + '>'
}
// ...
message.reply(`uptime!\n uptime : ${generateReadyTimestamp()}`)
```
<p>Or, setting it inside the callback:</p>
<pre class="lang-js prettyprint-override"><code>client.on('messageCreate', message => {
    if(message.content == "!uptime"){
        const starttime = `<t:${Math.floor(client.readyAt / 1000)}` + (style ? `:${style}` : '') + '>'
        message.reply(`uptime!\n uptime : ${starttime}`)
    }
})
</code>```

Title: discord.js v13 bot uptime

Body:
You are setting that outside of the event, where client.readyAt is null. When you divide null by anything except for 0, you get 0. The result would then be <t:0:R>. You could either make this a function, or set it in the event

function generateReadyTimestamp() {
  return `<t:${Math.floor(client.readyAt / 1000)}` + (style ? `:${style}` : '') + '>'
}
// ...
message.reply(`uptime!\n uptime : ${generateReadyTimestamp()}`)

Or, setting it inside the callback:

client.on('messageCreate', message => {
    if(message.content == "!uptime"){
        const starttime = `<t:${Math.floor(client.readyAt / 1000)}` + (style ? `:${style}` : '') + '>'
        message.reply(`uptime!\n uptime : ${starttime}`)
    }
})


问:
flask-socketio emit message from backend to frontend
I am trying to emit a message using socket.io originating on a python backend to the frontend. I am able to register the initial connection between the front and the backend, to send a message from the frontend to the backend, and to reply from the backend to the frontend but not just send a message from the back to the front on its own. It seems rather simple but I am not seeing something.

main.py

```<code>from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'tmp-secret-key'
socketio = SocketIO(app)

@app.route('/')
def sessions():
    message = "test message"
    print(message)
    socketio.emit('message', message)
    return render_template('index.html')

@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
    print('received my event: ' + str(json))
    socketio.emit('my response', "hello")

if __name__ == '__main__':
    socketio.run(app, debug=True)
</code>```

index.html (in templates folder)

```<code><!DOCTYPE html>

<html lang="en">
<head>
  <title>Flask SocketIO Test</title>
</head>
<body>

 <script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>

 <script type="text/javascript">
   var socket = io();

   socket.on('connect', function() {
     console.log("connection found")
     socket.emit( 'my event', {
       data: 'User Connected'
     });
   });

   socket.on('message', function(data) {
     console.log("message data: ", data);
   });

   socket.on('my response', function(msg) {
     console.log("my response: ", msg)
   })

 </script>

</body>
</html>
</code>```

requirements.txt

```<code>flask==2.0.2
flask-socketio==5.1.1
simple-websocket==0.5.0
python-engineio==4.3.1
python-socketio==5.5.1
</code>```

when page loads this is printed to stdout:

1 : test message

2 : received my event: {'data': 'User Connected'}

when page loads this is printed to the browser console:

1 : connection found

2 : my response:  hello

The outputs show that communication is possible. Also if a second window is open then the browser console shows message data:  test message which is what I am looking for just with only one session open. This seems to indicate a session or namespace issue but I am not sure what is wrong.

答:
You are correct, the template is re-rendered every time the page is refreshed. This means that the old session is also ended and a new one is created.

The problem arises from these lines.

The message is emitted before the template is rendered. This leads to the mentioned timing problem.

```<code>@app.route('/')
def sessions():
    message = "test message"
    print(message)
    socketio.emit('message', message)    # The message is emitted.
    return render_template('index.html') # The template is rendered and sent.
</code>```

Unfortunately, I can't tell from your question which goal you are working towards.

There are different ways of working with websockets per se.

On the one hand, web sockets enable the reply to incoming messages or broadcast them to other clients. handle_my_custom_event shows this possibility.

Another possibility is to send messages to the client from the background.

I wrote a small example for this.

In this case, messages are periodically emitted from a background thread. As soon as a client is connected, it is checked whether the thread has already been started.

```<code>from threading import Lock
from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.secret_key = 'your secret here'
sio = SocketIO(app)

thread = None
thread_lock = Lock()

@app.route('/')
def index():
    return render_template('index.html')

def background_task():
    while True:
        sio.sleep(10)
        sio.emit('my_response', { 'data': 'a new message' })

@sio.on('connect')
def connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = sio.start_background_task(background_task)
    emit('my_response', { 'data': 'connected' })

if __name__ == '__main__':
    sio.run(app)
</code>```
```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>

    <script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
    <script type="text/javascript">
      (() => {
        const sock = io();
        sock.on('my_response', data => {
          console.log(data);
        });
      })();
    </script>
  </body>
</html>
</code>```

Body:
I am trying to emit a message using socket.io originating on a python backend to the frontend. I am able to register the initial connection between the front and the backend, to send a message from the frontend to the backend, and to reply from the backend to the frontend but not just send a message from the back to the front on its own. It seems rather simple but I am not seeing something.

main.py

from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'tmp-secret-key'
socketio = SocketIO(app)

@app.route('/')
def sessions():
    message = "test message"
    print(message)
    socketio.emit('message', message)
    return render_template('index.html')

@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
    print('received my event: ' + str(json))
    socketio.emit('my response', "hello")

if __name__ == '__main__':
    socketio.run(app, debug=True)

index.html (in templates folder)

<!DOCTYPE html>

  <title>Flask SocketIO Test</title>

requirements.txt

flask==2.0.2
flask-socketio==5.1.1
simple-websocket==0.5.0
python-engineio==4.3.1
python-socketio==5.5.1

when page loads this is printed to stdout:

1 : test message

2 : received my event: {'data': 'User Connected'}

when page loads this is printed to the browser console:

1 : connection found

2 : my response:  hello

The outputs show that communication is possible. Also if a second window is open then the browser console shows message data:  test message which is what I am looking for just with only one session open. This seems to indicate a session or namespace issue but I am not sure what is wrong.

Body:
You are correct, the template is re-rendered every time the page is refreshed. This means that the old session is also ended and a new one is created.

The problem arises from these lines.

The message is emitted before the template is rendered. This leads to the mentioned timing problem.

@app.route('/')
def sessions():
    message = "test message"
    print(message)
    socketio.emit('message', message)    # The message is emitted.
    return render_template('index.html') # The template is rendered and sent.

Unfortunately, I can't tell from your question which goal you are working towards.

There are different ways of working with websockets per se.

On the one hand, web sockets enable the reply to incoming messages or broadcast them to other clients. handle_my_custom_event shows this possibility.

Another possibility is to send messages to the client from the background.

I wrote a small example for this.

In this case, messages are periodically emitted from a background thread. As soon as a client is connected, it is checked whether the thread has already been started.

from threading import Lock
from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.secret_key = 'your secret here'
sio = SocketIO(app)

thread = None
thread_lock = Lock()

@app.route('/')
def index():
    return render_template('index.html')

def background_task():
    while True:
        sio.sleep(10)
        sio.emit('my_response', { 'data': 'a new message' })

@sio.on('connect')
def connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = sio.start_background_task(background_task)
    emit('my_response', { 'data': 'connected' })

if __name__ == '__main__':
    sio.run(app)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>

    <script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
    <script type="text/javascript">
      (() => {
        const sock = io();
        sock.on('my_response', data => {
          console.log(data);
        });
      })();
    </script>
  </body>
</html>


问:
Check if powerhshell was started using "run as administrator"
i found an old question on this topic. However, i am not clear.
I have a script that checks, if PS has been run using "run as administrator" and if yes it does the job, otherweise it prompts that the script must be run as administrator.

```<code>$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$CheckforAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
</code>```

it gives true or false. I have if-else statement that does the rest.

```<code>    If($CheckforAdmin -eq 'True'){
        $MSG = ""
        If(($EventLogCheck -ne $EventLog) -or ($EventLogsourceCheck -ne 'True')){
            New-EventLog -LogName $EventLog -Source $EventLogSource -ErrorAction Stop
            $MSG = "$env:USERNAME has successfully created a new eventlog named $EventLog with the source $EventLogSource."
            Write-EventLog -logname $PiEventLog -source  $PiEventLogSource -eventID 1021 -entrytype Information -message $MSG
        }
        else{
            $MSG = "$env:USERNAME tried to create an EventLog named $EventLog with the source $EventLogSource. `nSince the EventLog and the source already exist, this step was aborted."
            Write-EventLog -logname $EventLog -source  $EventLogSource -eventID 1021 -entrytype Information -message $MSG
        }

#           Wenn der Parameter Silent auf true gesetzt ist, wird das Skript nach der Erstellung des EventLogs unmittelbar beendet.
        if($install -eq $true){
            Write-Host $MSG
            Read-Host 'Press any key to continue...'
        }
        exit
    }
    else{
        Write-Host "The Script must be executed as admin"
     [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
        [System.Windows.Forms.MessageBox]::Show('Installation: The script must be run as administrator in order to create the event log', 'Run as admin')
        exit
    }
</code>```

It works well, if i am logged in with a normal user. But on my server where i want to run the script, i log in as domain administrator. Even if if run the script just double clicking on it, it runs instead of prompting that the script must be run using "run as administrator".

I red the articles about UAC (User Account control) and as far as i understood: running a script using "run as administor" is actually the same as logging in as domain administrator and double clicking on the script.

Is there any other way to check, if the script was run using "run as administrator" option that shows up if u right click on powershell (doesn't matter, whether you are logged in as admin or not) ?

答:
At the top of your script add the line:

```<code> #Requires -RunAsAdministrator
</code>```

then remove all your code to check for an administrator.

If the user running the script is not an elevated administrator, a message will be displayed and the execution of the scripts stops.

Body:
i found an old question on this topic. However, i am not clear.
I have a script that checks, if PS has been run using "run as administrator" and if yes it does the job, otherweise it prompts that the script must be run as administrator.

$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$CheckforAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

it gives true or false. I have if-else statement that does the rest.

    If($CheckforAdmin -eq 'True'){
        $MSG = ""
        If(($EventLogCheck -ne $EventLog) -or ($EventLogsourceCheck -ne 'True')){
            New-EventLog -LogName $EventLog -Source $EventLogSource -ErrorAction Stop
            $MSG = "$env:USERNAME has successfully created a new eventlog named $EventLog with the source $EventLogSource."
            Write-EventLog -logname $PiEventLog -source  $PiEventLogSource -eventID 1021 -entrytype Information -message $MSG
        }
        else{
            $MSG = "$env:USERNAME tried to create an EventLog named $EventLog with the source $EventLogSource. `nSince the EventLog and the source already exist, this step was aborted."
            Write-EventLog -logname $EventLog -source  $EventLogSource -eventID 1021 -entrytype Information -message $MSG
        }

#           Wenn der Parameter Silent auf true gesetzt ist, wird das Skript nach der Erstellung des EventLogs unmittelbar beendet.
        if($install -eq $true){
            Write-Host $MSG
            Read-Host 'Press any key to continue...'
        }
        exit
    }
    else{
        Write-Host "The Script must be executed as admin"
     [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
        [System.Windows.Forms.MessageBox]::Show('Installation: The script must be run as administrator in order to create the event log', 'Run as admin')
        exit
    }

It works well, if i am logged in with a normal user. But on my server where i want to run the script, i log in as domain administrator. Even if if run the script just double clicking on it, it runs instead of prompting that the script must be run using "run as administrator".

I red the articles about UAC (User Account control) and as far as i understood: running a script using "run as administor" is actually the same as logging in as domain administrator and double clicking on the script.

Is there any other way to check, if the script was run using "run as administrator" option that shows up if u right click on powershell (doesn't matter, whether you are logged in as admin or not) ?

Body:
At the top of your script add the line:

 #Requires -RunAsAdministrator

then remove all your code to check for an administrator.

If the user running the script is not an elevated administrator, a message will be displayed and the execution of the scripts stops.


问:
NodeJs Postgres + AWS Lambda timeout even after successful client connect
Lambda Function:

```<code>const client = new Client({
    user: 'postgres',
    host: 'rds_host',
    database: 'dbname',
    password: 'db_password',
    port: 5432
});

exports.handler = async (event, context, callback) => {
    try {
        await client.connect();
        callback(null, "Connected Successfully");
    } catch (e) {
        callback(null, "Error");
    }
};
</code>```

With this code my lambda always get a timeout error, if I get rid of the cliente.connect() line, it works fine.

The interesting part is that if I add a client.query with INSERT the command does work and the row is created at the DB, so why I get a timeout when the client.connect() is added and the connection works?

答:
I'm pretty sure that when your handler function is async, it's expecting a promise to be resolved, so, instead of using the callback, I would just return "Connected Successfully";

Link to relevant docs

There's an example at this link where there's an async handler without the callback.

Body:
Lambda Function:

const client = new Client({
    user: 'postgres',
    host: 'rds_host',
    database: 'dbname',
    password: 'db_password',
    port: 5432
});

exports.handler = async (event, context, callback) => {
    try {
        await client.connect();
        callback(null, "Connected Successfully");
    } catch (e) {
        callback(null, "Error");
    }
};

With this code my lambda always get a timeout error, if I get rid of the cliente.connect() line, it works fine.

The interesting part is that if I add a client.query with INSERT the command does work and the row is created at the DB, so why I get a timeout when the client.connect() is added and the connection works?


问:
in Azure DevOps, where are the stages of a pipeline actually run?
I'm coming to Azure DevOps from my experience with Jenkins, where it was clear that the code in the pipelines being run is actually run on the Jenkins server (whatever machine is hosting that).  So I assumed that Azure DevOps pipelines were running somehow somewhere on https://dev.azure.com/.  Maybe this is true, maybe it isn't.  Maybe it depends on how the "environment" is set up and what resources are in that environment.  My multi-stage pipeline looks like this:

# ASP.NET
# Build and test ASP.NET projects.
# Add steps that publish symbols, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4

trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

stages:
- stage: build
  displayName: Build
  jobs:
  - job: Build

    steps:

    - checkout: self

    #without this first one, bad things happen!!
    - task: NuGetCommand@2
      inputs:
        command: 'restore'
        restoreSolution: '**/*.sln'
        feedsToUse: 'config'
        nugetConfigPath: 'NuGet.config'

    - task: NuGetToolInstaller@1

    - task: VSBuild@1
      inputs:
        solution: '$(solution)'
        msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
        platform: '$(buildPlatform)'
        configuration: '$(buildConfiguration)'

    - task: VSTest@2
      inputs:
        platform: '$(buildPlatform)'
        configuration: '$(buildConfiguration)'

    - task: PublishBuildArtifacts@1
      inputs:
        PathtoPublish: '$(Build.ArtifactStagingDirectory)'
        ArtifactName: 'drop'
        publishLocation: 'Container'

- stage: Release
  displayName: Release
  condition: and(succeeded(), eq(variables['build.sourceBranch'], 'refs/heads/master'))
  jobs:

  - deployment:
    displayName: Release
    environment:
        name: QA
        resourceType: VirtualMachine
    strategy:
      runOnce:
        deploy:
          steps:
          - task: CopyFiles@2
            inputs:
              SourceFolder: '$(Agent.WorkFolder)\1\drop'
              Contents: '**\*.zip'
              OverWrite: true
              TargetFolder: 'C:\QA\XXX\YYY'```

I know that 'C:\QA\XXX\YYY' is on the server I am deploying to (a resource in the QA Azure DevOps environment).  But where are these locations?

$(Build.ArtifactStagingDirectory)

$(Agent.WorkFolder)

Some of these have "D:" in their path, and yet there is no D: on the server I am deploying to.  Microsoft's documentation never really seems to address this issue, and yet understanding it would seem to be essential to anyone trying to get up to speed with Azure DevOps.

答:
The pipeline runs on the agent, which can be located in one of two places:

Microsoft-Hosted Agents each run on a single-purpose VM which is freshly created by Microsoft, and destroyed after a single pipeline job is finished.

Self-Hosted Agents are run by you, on your infrastructure (either locally or in the cloud). It's normal for them to persist, and run multiple jobs. You can run them:

on a local physical server

on an Azure VM

on an Azure VMSS

Whatever kind of agent you use, those pre-defined variables ($(Build.ArtifactStagingDirectory) and $(Agent.WorkFolder)) correspond to local file locations on the server where the agent is running.

Your choice of the "windows-latest" pool means that your pipeline runs on a Microsoft-hosted agent, on a Windows VM.

Body:
I'm coming to Azure DevOps from my experience with Jenkins, where it was clear that the code in the pipelines being run is actually run on the Jenkins server (whatever machine is hosting that).  So I assumed that Azure DevOps pipelines were running somehow somewhere on https://dev.azure.com/.  Maybe this is true, maybe it isn't.  Maybe it depends on how the "environment" is set up and what resources are in that environment.  My multi-stage pipeline looks like this:

# ASP.NET
# Build and test ASP.NET projects.
# Add steps that publish symbols, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4

trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

stages:
- stage: build
  displayName: Build
  jobs:
  - job: Build

    steps:

    - checkout: self

    #without this first one, bad things happen!!
    - task: NuGetCommand@2
      inputs:
        command: 'restore'
        restoreSolution: '**/*.sln'
        feedsToUse: 'config'
        nugetConfigPath: 'NuGet.config'

    - task: NuGetToolInstaller@1

    - task: VSBuild@1
      inputs:
        solution: '$(solution)'
        msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
        platform: '$(buildPlatform)'
        configuration: '$(buildConfiguration)'

    - task: VSTest@2
      inputs:
        platform: '$(buildPlatform)'
        configuration: '$(buildConfiguration)'

    - task: PublishBuildArtifacts@1
      inputs:
        PathtoPublish: '$(Build.ArtifactStagingDirectory)'
        ArtifactName: 'drop'
        publishLocation: 'Container'

- stage: Release
  displayName: Release
  condition: and(succeeded(), eq(variables['build.sourceBranch'], 'refs/heads/master'))
  jobs:

  - deployment:
    displayName: Release
    environment:
        name: QA
        resourceType: VirtualMachine
    strategy:
      runOnce:
        deploy:
          steps:
          - task: CopyFiles@2
            inputs:
              SourceFolder: '$(Agent.WorkFolder)\1\drop'
              Contents: '**\*.zip'
              OverWrite: true
              TargetFolder: 'C:\QA\XXX\YYY'

I know that 'C:\QA\XXX\YYY' is on the server I am deploying to (a resource in the QA Azure DevOps environment).  But where are these locations?

$(Build.ArtifactStagingDirectory)

$(Agent.WorkFolder)

Some of these have "D:" in their path, and yet there is no D: on the server I am deploying to.  Microsoft's documentation never really seems to address this issue, and yet understanding it would seem to be essential to anyone trying to get up to speed with Azure DevOps.


问:
how to make the sqlalchemy async session(Async Session) generator as class-base?
I have the fast API application and run schedule task in a background thread as a startup event in fast API.
so when I use the SQlAlchemy async session in route scope like:
session: AsyncSession=Depends(instance_manger.db_instance.get_db_session) it's ok and runs as correct , but when it's run in the background thread I have the below error.
I use python module => SQLAlchemy[asyncio]  asyncmy pymysql fastapi

database.py

```<code>class DBManager:
    def __init__(self):
        self.SQLALCHEMY_DATABASE_URL = None
        self.config_reader_instance = None
        self.engine = None
        self._session_factory = None
        self.logger_handler_instance = None
        self.db = None

    def initialize(self, config_reader_instance, logger_handler_instance):
        self.logger_handler_instance = logger_handler_instance
        self.config_reader_instance = config_reader_instance
        self.SQLALCHEMY_DATABASE_URL = "mysql+asyncmy://{0}:{1}@{2}:{3}/{4}".format(
            self.config_reader_instance.DB_INFO['db_username'], self.config_reader_instance.DB_INFO['db_password'],
            self.config_reader_instance.DB_INFO['db_hostname'], self.config_reader_instance.DB_INFO['db_port'],
            self.config_reader_instance.DB_INFO['db_name'])
        self.engine = create_async_engine(self.SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
        # self.engine.begi/n()
        self._session_factory = async_scoped_session(sessionmaker(
            self.engine, class_=AsyncSession, expire_on_commit=False), scopefunc=current_task)
        # self._session_factory = orm.scoped_session(
        #     orm.sessionmaker(
        #         class_=AsyncSession,
        #         autoflush=False,
        #         bind=self.engine,
        #     ),
        # )

    async def get_db_session(self) -> AsyncSession:
        async with self._session_factory() as session:
            try:
                yield session
            except Exception as e:
                self.logger_handler_instance.write_log(__name__, logging.FATAL,
                                                       'Session rollback because of exception')
                self.logger_handler_instance.write_log(__name__, logging.FATAL, e)
                await session.rollback()
                raise
            finally:
                await session.close()
</code>```

background_thread.py

```<code>class BackgroundRunnable:
    def __init__(self):
        self.instance_manger = None
        self.core_process_instance = None
        self.conf_reader_instance = None
        self.process_id = None
        self.process_name = "BTC"

    def initialize(self, instance_manager: InstanceManager):
        self.instance_manger = instance_manager
        return self

    def set_process_info(self, process_name):
        self.process_id = os.getpid()
        self.process_name = process_name

    async def run_main(self):
        self.instance_manger.logger_handler_instance.write_log(__name__, logging.INFO,
                                                               "Background Thread is start")
        results = await CryptoCoinService(
            CryptoCoinRepository(AsyncSession(self.instance_manger.db_instance.engine))).get_coin()
        print(results)

</code>```

crypto_coin_repository.py

```<code>from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import class_mapper

from db.models.models import CryptoCoinModel

class CryptoCoinRepository:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session

    async def get_all(self) -> bool:
        results = await self.session.execute(
            select(CryptoCoinModel._id).where(CryptoCoinModel._symbol == 'BTC'))
        results_ = results.fetchone()
        if results_.__len__() == 0:
            return False
        else:
            return True
</code>```

main.py

```<code>from fastapi import APIRouter, Depends, Request, Response, FastAPI, status
from fastapi.responses import JSONResponse
from sqlalchemy.ext.asyncio import AsyncSession

from coin_server.background_thread import BackgroundRunnable
from coin_server.core_process import CoreProcess
from core.instance_manager import InstanceManager
from db.database import DBManager
from db.repository.crypto_coin_repository import CryptoCoinRepository
from db.services.crypto_coin_service import CryptoCoinService

deposit_Router = APIRouter()

instance_manager = InstanceManager()
instance_manager.initialize()
db_instance = DBManager()
db_instance.initialize(instance_manager.config_reader_instance, instance_manager.logger_handler_instance)

@deposit_Router.post('/')
async def index(request: Request, session: AsyncSession = Depends(db_instance.get_db_session)):
    results = await CryptoCoinService(CryptoCoinRepository(session)).get_coin()
    print(results)

deposit_app = FastAPI()

@deposit_app.on_event('startup')
async def app_startup():
    background_runnable = BackgroundRunnable()
    background_runnable.initialize(instance_manager)
    asyncio.create_task(background_runnable.run_main())
    # asyncio.create_task(BackgroundRunnable().initialize(instance_manager).run_main())

deposit_app.include_router(deposit_Router)

</code>```

when I run fast API app error like belong output.

```<code>INFO:     Uvicorn running on http://0.0.0.0:5000 (Press CTRL+C to quit)
INFO:     Started reloader process [176] using watchgod
INFO:     Started server process [179]
INFO:     Waiting for application startup.
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<BackgroundRunnable.run_main() done, defined at /mnt/c/Users/dr_r00t3r/Desktop/main/coin_server/background_thread.py:48> exception=At
tributeError("'async_generator' object has no attribute 'execute'")>
Traceback (most recent call last):
  File "/mnt/c/Users/dr_r00t3r/Desktop/main/coin_server/background_thread.py", line 51, in run_main
    results = await CryptoCoinService(
  File "/mnt/c/Users/dr_r00t3r/Desktop/main/db/repository/crypto_coin_repository.py", line 17, in get_all
    results = await self.session.execute(
AttributeError: 'async_generator' object has no attribute 'execute'
INFO:     Application startup complete.

</code>```

答:
It's all note: when you use function get_db_session in database.py like a generator, close function of session doesn't work as auto, so you should close them like manually.

database.py

```<code>import logging

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()

class DBManager:
    def __init__(self):
        self.SQLALCHEMY_DATABASE_URL = None
        self.config_reader_instance = None
        self.engine = None
        self.session_factory = None
        self.Base = declarative_base()
        self.logger_handler_instance = None

    def initialize(self, config_reader_instance, logger_handler_instance):
        self.logger_handler_instance = logger_handler_instance
        self.config_reader_instance = config_reader_instance
        self.SQLALCHEMY_DATABASE_URL = "mysql+asyncmy://{0}:{1}@{2}:{3}/{4}".format(
            self.config_reader_instance.DB_INFO['db_username'], self.config_reader_instance.DB_INFO['db_password'],
            self.config_reader_instance.DB_INFO['db_hostname'], self.config_reader_instance.DB_INFO['db_port'],
            self.config_reader_instance.DB_INFO['db_name'])
        self.engine = create_async_engine(self.SQLALCHEMY_DATABASE_URL, pool_pre_ping=True, pool_size=30,
                                          max_overflow=30, echo_pool=True, echo=False,
                                          pool_recycle=3600)  # recycle every hour
        DBManager.Base = declarative_base()
        self.session_factory = scoped_session(sessionmaker(
            self.engine, class_=AsyncSession, expire_on_commit=False
        ))

    def get_db_session(self):
        session = self.session_factory()
        try:
            yield session
        except Exception as e:
            self.logger_handler_instance.log(__name__, logging.FATAL,
                                             'Session rollback because of exception')
            self.logger_handler_instance.log(__name__, logging.FATAL, e)
            session.rollback()
            raise
        finally:
            session.close()

    async def init_models(self):
        async with self.engine.begin() as conn:
            await conn.run_sync(Base.metadata.drop_all)
            await conn.run_sync(Base.metadata.create_all)
</code>```

background_thread.py

```<code>class BackgroundRunnable:
    def __init__(self):
        self.instance_manger = None
        self.core_process_instance = None
        self.conf_reader_instance = None
        self.process_id = None
        self.process_name = "BTC"

    def initialize(self, instance_manager: InstanceManager):
        self.instance_manger = instance_manager
        return self

    def set_process_info(self, process_name):
        self.process_id = os.getpid()
        self.process_name = process_name

    async def run_main(self):
        self.instance_manger.logger_handler_instance.write_log(__name__, logging.INFO,
                                                               "Background Thread is start")
        self.session: AsyncSession = next(self.instance_manger.db_instance.get_db_session())
        results = await CryptoCoinService(CryptoCoinRepository(self.session)).get_coin(
            self.instance_manger.config_reader_instance.BTC_INFO['BTC_COIN'])
        print(results)
</code>```

crypto_coin_repository.py

```<code>"""Repositories module."""
from contextlib import AbstractContextManager
from typing import Callable

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import class_mapper, Session

from db.models.models import CryptoCoinModel

class CryptoCoinRepository:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session

    async def get_all(self, coin) -> bool:
        results = await self.session.execute(
            select(CryptoCoinModel._id).where(CryptoCoinModel._symbol == coin))
        results = results.fetchall()
        if len(results) == 0:
            return False
        else:
            return True

    def serialize(self, model):
        """Transforms a model into a dictionary which can be dumped to JSON."""
        # first we get the names of all the columns on your model
        columns = [c.key for c in class_mapper(model.__class__).columns]
        # then we return their values in a dict
        return dict((c, getattr(model, '_' + c)) for c in columns)

class NotFoundError(Exception):
    symbol: str

    def __init__(self):
        super().__init__(f'{self._symobl} not found,please add this coin to db')

class CryptoCoinNotFoundError(NotFoundError):
    # entity_name: str = 'User'
    pass
</code>```

main.py

```<code>from fastapi import APIRouter, Depends, Request, Response, FastAPI, status
from fastapi.responses import JSONResponse
from sqlalchemy.ext.asyncio import AsyncSession

from coin_server.background_thread import BackgroundRunnable
from coin_server.core_process import CoreProcess
from core.instance_manager import InstanceManager
from db.database import DBManager
from db.repository.crypto_coin_repository import CryptoCoinRepository
from db.services.crypto_coin_service import CryptoCoinService

deposit_Router = APIRouter()

instance_manager = InstanceManager()
instance_manager.initialize()
db_instance = DBManager()
db_instance.initialize(instance_manager.config_reader_instance, instance_manager.logger_handler_instance)

@deposit_Router.post('/')
async def index(request: Request, session: AsyncSession = Depends(db_instance.get_db_session)):
    results = await CryptoCoinService(CryptoCoinRepository(session)).get_coin()
    print(results)

deposit_app = FastAPI()

@deposit_app.on_event('startup')
async def app_startup():
    background_runnable = BackgroundRunnable()
    background_runnable.initialize(instance_manager)
    asyncio.create_task(background_runnable.run_main())
    # asyncio.create_task(BackgroundRunnable().initialize(instance_manager).run_main())

deposit_app.include_router(deposit_Router)
</code>```

Body:
I have the fast API application and run schedule task in a background thread as a startup event in fast API.
so when I use the SQlAlchemy async session in route scope like:
session: AsyncSession=Depends(instance_manger.db_instance.get_db_session) it's ok and runs as correct , but when it's run in the background thread I have the below error.
I use python module => SQLAlchemy[asyncio]  asyncmy pymysql fastapi

database.py

class DBManager:
    def __init__(self):
        self.SQLALCHEMY_DATABASE_URL = None
        self.config_reader_instance = None
        self.engine = None
        self._session_factory = None
        self.logger_handler_instance = None
        self.db = None

    def initialize(self, config_reader_instance, logger_handler_instance):
        self.logger_handler_instance = logger_handler_instance
        self.config_reader_instance = config_reader_instance
        self.SQLALCHEMY_DATABASE_URL = "mysql+asyncmy://{0}:{1}@{2}:{3}/{4}".format(
            self.config_reader_instance.DB_INFO['db_username'], self.config_reader_instance.DB_INFO['db_password'],
            self.config_reader_instance.DB_INFO['db_hostname'], self.config_reader_instance.DB_INFO['db_port'],
            self.config_reader_instance.DB_INFO['db_name'])
        self.engine = create_async_engine(self.SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
        # self.engine.begi/n()
        self._session_factory = async_scoped_session(sessionmaker(
            self.engine, class_=AsyncSession, expire_on_commit=False), scopefunc=current_task)
        # self._session_factory = orm.scoped_session(
        #     orm.sessionmaker(
        #         class_=AsyncSession,
        #         autoflush=False,
        #         bind=self.engine,
        #     ),
        # )

    async def get_db_session(self) -> AsyncSession:
        async with self._session_factory() as session:
            try:
                yield session
            except Exception as e:
                self.logger_handler_instance.write_log(__name__, logging.FATAL,
                                                       'Session rollback because of exception')
                self.logger_handler_instance.write_log(__name__, logging.FATAL, e)
                await session.rollback()
                raise
            finally:
                await session.close()

background_thread.py

class BackgroundRunnable:
    def __init__(self):
        self.instance_manger = None
        self.core_process_instance = None
        self.conf_reader_instance = None
        self.process_id = None
        self.process_name = "BTC"

    def initialize(self, instance_manager: InstanceManager):
        self.instance_manger = instance_manager
        return self

    def set_process_info(self, process_name):
        self.process_id = os.getpid()
        self.process_name = process_name

    async def run_main(self):
        self.instance_manger.logger_handler_instance.write_log(__name__, logging.INFO,
                                                               "Background Thread is start")
        results = await CryptoCoinService(
            CryptoCoinRepository(AsyncSession(self.instance_manger.db_instance.engine))).get_coin()
        print(results)

crypto_coin_repository.py

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import class_mapper

from db.models.models import CryptoCoinModel

class CryptoCoinRepository:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session

    async def get_all(self) -> bool:
        results = await self.session.execute(
            select(CryptoCoinModel._id).where(CryptoCoinModel._symbol == 'BTC'))
        results_ = results.fetchone()
        if results_.__len__() == 0:
            return False
        else:
            return True

main.py

from fastapi import APIRouter, Depends, Request, Response, FastAPI, status
from fastapi.responses import JSONResponse
from sqlalchemy.ext.asyncio import AsyncSession

from coin_server.background_thread import BackgroundRunnable
from coin_server.core_process import CoreProcess
from core.instance_manager import InstanceManager
from db.database import DBManager
from db.repository.crypto_coin_repository import CryptoCoinRepository
from db.services.crypto_coin_service import CryptoCoinService

deposit_Router = APIRouter()

instance_manager = InstanceManager()
instance_manager.initialize()
db_instance = DBManager()
db_instance.initialize(instance_manager.config_reader_instance, instance_manager.logger_handler_instance)

@deposit_Router.post('/')
async def index(request: Request, session: AsyncSession = Depends(db_instance.get_db_session)):
    results = await CryptoCoinService(CryptoCoinRepository(session)).get_coin()
    print(results)

deposit_app = FastAPI()

@deposit_app.on_event('startup')
async def app_startup():
    background_runnable = BackgroundRunnable()
    background_runnable.initialize(instance_manager)
    asyncio.create_task(background_runnable.run_main())
    # asyncio.create_task(BackgroundRunnable().initialize(instance_manager).run_main())

deposit_app.include_router(deposit_Router)

when I run fast API app error like belong output.

INFO:     Uvicorn running on http://0.0.0.0:5000 (Press CTRL+C to quit)
INFO:     Started reloader process [176] using watchgod
INFO:     Started server process [179]
INFO:     Waiting for application startup.
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<BackgroundRunnable.run_main() done, defined at /mnt/c/Users/dr_r00t3r/Desktop/main/coin_server/background_thread.py:48> exception=At
tributeError("'async_generator' object has no attribute 'execute'")>
Traceback (most recent call last):
  File "/mnt/c/Users/dr_r00t3r/Desktop/main/coin_server/background_thread.py", line 51, in run_main
    results = await CryptoCoinService(
  File "/mnt/c/Users/dr_r00t3r/Desktop/main/db/repository/crypto_coin_repository.py", line 17, in get_all
    results = await self.session.execute(
AttributeError: 'async_generator' object has no attribute 'execute'
INFO:     Application startup complete.

Body:
It's all note: when you use function get_db_session in database.py like a generator, close function of session doesn't work as auto, so you should close them like manually.

database.py

import logging

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()

class DBManager:
    def __init__(self):
        self.SQLALCHEMY_DATABASE_URL = None
        self.config_reader_instance = None
        self.engine = None
        self.session_factory = None
        self.Base = declarative_base()
        self.logger_handler_instance = None

    def initialize(self, config_reader_instance, logger_handler_instance):
        self.logger_handler_instance = logger_handler_instance
        self.config_reader_instance = config_reader_instance
        self.SQLALCHEMY_DATABASE_URL = "mysql+asyncmy://{0}:{1}@{2}:{3}/{4}".format(
            self.config_reader_instance.DB_INFO['db_username'], self.config_reader_instance.DB_INFO['db_password'],
            self.config_reader_instance.DB_INFO['db_hostname'], self.config_reader_instance.DB_INFO['db_port'],
            self.config_reader_instance.DB_INFO['db_name'])
        self.engine = create_async_engine(self.SQLALCHEMY_DATABASE_URL, pool_pre_ping=True, pool_size=30,
                                          max_overflow=30, echo_pool=True, echo=False,
                                          pool_recycle=3600)  # recycle every hour
        DBManager.Base = declarative_base()
        self.session_factory = scoped_session(sessionmaker(
            self.engine, class_=AsyncSession, expire_on_commit=False
        ))

    def get_db_session(self):
        session = self.session_factory()
        try:
            yield session
        except Exception as e:
            self.logger_handler_instance.log(__name__, logging.FATAL,
                                             'Session rollback because of exception')
            self.logger_handler_instance.log(__name__, logging.FATAL, e)
            session.rollback()
            raise
        finally:
            session.close()

    async def init_models(self):
        async with self.engine.begin() as conn:
            await conn.run_sync(Base.metadata.drop_all)
            await conn.run_sync(Base.metadata.create_all)

background_thread.py

class BackgroundRunnable:
    def __init__(self):
        self.instance_manger = None
        self.core_process_instance = None
        self.conf_reader_instance = None
        self.process_id = None
        self.process_name = "BTC"

    def initialize(self, instance_manager: InstanceManager):
        self.instance_manger = instance_manager
        return self

    def set_process_info(self, process_name):
        self.process_id = os.getpid()
        self.process_name = process_name

    async def run_main(self):
        self.instance_manger.logger_handler_instance.write_log(__name__, logging.INFO,
                                                               "Background Thread is start")
        self.session: AsyncSession = next(self.instance_manger.db_instance.get_db_session())
        results = await CryptoCoinService(CryptoCoinRepository(self.session)).get_coin(
            self.instance_manger.config_reader_instance.BTC_INFO['BTC_COIN'])
        print(results)

crypto_coin_repository.py

"""Repositories module."""
from contextlib import AbstractContextManager
from typing import Callable

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import class_mapper, Session

from db.models.models import CryptoCoinModel

class CryptoCoinRepository:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session

    async def get_all(self, coin) -> bool:
        results = await self.session.execute(
            select(CryptoCoinModel._id).where(CryptoCoinModel._symbol == coin))
        results = results.fetchall()
        if len(results) == 0:
            return False
        else:
            return True

    def serialize(self, model):
        """Transforms a model into a dictionary which can be dumped to JSON."""
        # first we get the names of all the columns on your model
        columns = [c.key for c in class_mapper(model.__class__).columns]
        # then we return their values in a dict
        return dict((c, getattr(model, '_' + c)) for c in columns)

class NotFoundError(Exception):
    symbol: str

    def __init__(self):
        super().__init__(f'{self._symobl} not found,please add this coin to db')

class CryptoCoinNotFoundError(NotFoundError):
    # entity_name: str = 'User'
    pass

main.py

from fastapi import APIRouter, Depends, Request, Response, FastAPI, status
from fastapi.responses import JSONResponse
from sqlalchemy.ext.asyncio import AsyncSession

from coin_server.background_thread import BackgroundRunnable
from coin_server.core_process import CoreProcess
from core.instance_manager import InstanceManager
from db.database import DBManager
from db.repository.crypto_coin_repository import CryptoCoinRepository
from db.services.crypto_coin_service import CryptoCoinService

deposit_Router = APIRouter()

instance_manager = InstanceManager()
instance_manager.initialize()
db_instance = DBManager()
db_instance.initialize(instance_manager.config_reader_instance, instance_manager.logger_handler_instance)

@deposit_Router.post('/')
async def index(request: Request, session: AsyncSession = Depends(db_instance.get_db_session)):
    results = await CryptoCoinService(CryptoCoinRepository(session)).get_coin()
    print(results)

deposit_app = FastAPI()

@deposit_app.on_event('startup')
async def app_startup():
    background_runnable = BackgroundRunnable()
    background_runnable.initialize(instance_manager)
    asyncio.create_task(background_runnable.run_main())
    # asyncio.create_task(BackgroundRunnable().initialize(instance_manager).run_main())

deposit_app.include_router(deposit_Router)


问:
yarn command not found after installing via npm
As per the yarn installation for yarn v2, they want you to install using npm install -g yarn.  So I ran sudo npm install -g yarn on Ubuntu 20.04.  But after I do that, it says command not found.

```<code>❯ sudo npm install -g yarn

> yarn@1.22.10 preinstall /usr/local/lib/node_modules/yarn
> :; (node ./preinstall.js > /dev/null 2>&1 || true)

❯ yarn --version
zsh: command not found: yarn
</code>```

答:
I installed yarn with npm install -g yarn on git bash and I tested it with yarn -v that show the version of the installed yarn, but when I used yarn start it gives me this error

C:\Users\{username}\AppData\Roaming\npm/node_modules/node/bin/node: line 1: This: command not found

These are simple steps that I used to fix my problem on Windows 10:

Uninstall node.js

Restart your computer

Delete your C:\Program Files\nodejs and C:\Users\{username}\AppData\Roaming\npm

Install node.js again and check it with node -v

Start your vs code as an admin and write npm install

Write yarn start

Body:
As per the yarn installation for yarn v2, they want you to install using npm install -g yarn.  So I ran sudo npm install -g yarn on Ubuntu 20.04.  But after I do that, it says command not found.

❯ sudo npm install -g yarn

> yarn@1.22.10 preinstall /usr/local/lib/node_modules/yarn
> :; (node ./preinstall.js > /dev/null 2>&1 || true)

❯ yarn --version
zsh: command not found: yarn


问:
How To Remove Github SSH Key Relics From Past User
I have received a loaner MacBook M1 Air, and have been running into issues trying to use my GitHub SSH key to push to company repositories. I deleted the past keys in the .ssh folder, created a new key, and added it to GitHub. I changed the .ssh/config file to reflect my information, and am the only user in the .ssh/known_hosts file. When trying to push a commit, I receive an error that states: ERROR: Write access to repository not granted. fatal: Could not read from remote repository.

If I run ssh -T, I get a welcome message to the GitHub username of the previous user of this laptop. I can't find any area where this past-user's information is still being stored, having cleared out the .ssh folder and replaced it's contents with my information. When I run ssh-add -l -E sha256, the output reflects the past user's account and key.

Inside my .ssh folder, the files are:

config

id_ed25519

id_ed25519.pub

known_hosts

The information in all these files reflects my GitHub token and account. I am struggling to figure out how to delete all relics of the previous user, or even to find out where they are hiding. Any help much appreciated!

答: torek nailed it in their comment. I already had IdentityFile in my ssh config, pointing to my key. Adding IdentitiesOnly yes allowed me to push again, as well as changing the ssh -T output to reflect my username. Thank you @torek!


问:
group an array into subarrays in a project stage
I want to split the following array according to the group-value. I know I can do this using $unwind and $group. Is there any way to this in a single $project-stage?

Input

```<code>{
    "_id": 1,
    "some_field": "some_value",
    "array": [
        {
            "group": "a",
            "subgroup": "aa",
            "value": 1
        },
        {
            "group": "b",
            "subgroup": "bb",
            "value": 2
        },
        {
            "group": "a",
            "subgroup": "ab",
            "value": 2
        }
    ]
}
</code>```

desired output:

```<code>{
    "_id": 1,
    "some_field": "some_value",
    "array": [
        {
            "group": "a",
            "values": [
                {
                    "subgroup": "aa",
                    "value": 1
                },
                {
                    "subgroup": "ab",
                    "value": 2
                }
            ]
        },
        {
            "group": "b",
            "values": [
                {
                    "subgroup": "bb",
                    "value": 2
                }
            ]
        }
    ]
}
</code>```

答:
It is doable, it's definitely not clean or sexy.
My approach is to use $reduce and $mergeObjects, we'll iterate over the array and keep reconstructing the result.

The main issue that plagues this approach is this feature that doesn't allow to $concatArrays expressions, so we have to use some very ugly workarounds.

Anyways here is how you can achieve this:

```<code>db.collection.aggregate([
  {
    $project: {
      _id: 1,
      some_field: 1,
      array: {
        $map: {
          input: {
            "$objectToArray": {
              $reduce: {
                input: "$array",
                initialValue: {},
                in: {
                  "$mergeObjects": [
                    "$$value",
                    {
                      "$arrayToObject": [
                        [
                          {
                            k: "$$this.group",
                            v: {
                              $map: {
                                input: {
                                  "$concatArrays": [
                                    [
                                      "$$this"
                                    ],
                                    {
                                      $map: {
                                        input: {
                                          $filter: {
                                            input: {
                                              "$objectToArray": "$$value"
                                            },
                                            as: "filterItem",
                                            cond: {
                                              $eq: [
                                                "$$filterItem.k",
                                                "$$this.group"
                                              ]
                                            }
                                          }
                                        },
                                        as: "mapItem",
                                        in: "$$mapItem.v"
                                      }
                                    },

                                  ]
                                },
                                as: "map2Item",
                                in: {
                                  $cond: [
                                    {
                                      "$isArray": "$$map2Item"
                                    },
                                    {
                                      $arrayElemAt: [
                                        "$$map2Item",
                                        0
                                      ]
                                    },
                                    "$$map2Item"
                                  ]
                                }
                              }
                            }
                          }
                        ]
                      ]
                    }
                  ]
                }
              }
            }
          },
          as: "item",
          in: {
            group: "$$item.k",
            values: "$$item.v"
          }
        }
      }
    }
  }
])
</code>```

Mongo Playground

Body:
I want to split the following array according to the group-value. I know I can do this using $unwind and $group. Is there any way to this in a single $project-stage?

Input

{
    "_id": 1,
    "some_field": "some_value",
    "array": [
        {
            "group": "a",
            "subgroup": "aa",
            "value": 1
        },
        {
            "group": "b",
            "subgroup": "bb",
            "value": 2
        },
        {
            "group": "a",
            "subgroup": "ab",
            "value": 2
        }
    ]
}

desired output:

{
    "_id": 1,
    "some_field": "some_value",
    "array": [
        {
            "group": "a",
            "values": [
                {
                    "subgroup": "aa",
                    "value": 1
                },
                {
                    "subgroup": "ab",
                    "value": 2
                }
            ]
        },
        {
            "group": "b",
            "values": [
                {
                    "subgroup": "bb",
                    "value": 2
                }
            ]
        }
    ]
}

Body:
It is doable, it's definitely not clean or sexy.
My approach is to use $reduce and $mergeObjects, we'll iterate over the array and keep reconstructing the result.

The main issue that plagues this approach is this feature that doesn't allow to $concatArrays expressions, so we have to use some very ugly workarounds.

Anyways here is how you can achieve this:

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      some_field: 1,
      array: {
        $map: {
          input: {
            "$objectToArray": {
              $reduce: {
                input: "$array",
                initialValue: {},
                in: {
                  "$mergeObjects": [
                    "$$value",
                    {
                      "$arrayToObject": [
                        [
                          {
                            k: "$$this.group",
                            v: {
                              $map: {
                                input: {
                                  "$concatArrays": [
                                    [
                                      "$$this"
                                    ],
                                    {
                                      $map: {
                                        input: {
                                          $filter: {
                                            input: {
                                              "$objectToArray": "$$value"
                                            },
                                            as: "filterItem",
                                            cond: {
                                              $eq: [
                                                "$$filterItem.k",
                                                "$$this.group"
                                              ]
                                            }
                                          }
                                        },
                                        as: "mapItem",
                                        in: "$$mapItem.v"
                                      }
                                    },

                                  ]
                                },
                                as: "map2Item",
                                in: {
                                  $cond: [
                                    {
                                      "$isArray": "$$map2Item"
                                    },
                                    {
                                      $arrayElemAt: [
                                        "$$map2Item",
                                        0
                                      ]
                                    },
                                    "$$map2Item"
                                  ]
                                }
                              }
                            }
                          }
                        ]
                      ]
                    }
                  ]
                }
              }
            }
          },
          as: "item",
          in: {
            group: "$$item.k",
            values: "$$item.v"
          }
        }
      }
    }
  }
])

Mongo Playground


问:
A RenderFlex overflowed bottom flutter
when I run the project it shows A RenderFlex overflowed on the bottom

A RenderFlex overflowed by 6.7 pixels on the bottom.

答:
When the kayboard appears, it may hide something.
To avoid this problem, you can wrap the entire screen widget in a SingleChildScrollView. This will mate the screen scrollable.

Title: A RenderFlex overflowed bottom flutter