问:
how to get docker-compose to use the latest image from repository
I don't know what I'm doing wrong, but I simply cannot get docker-compose up to use the latest image from our registry without first removing the old containers from the system completely. It looks like compose is using the previously started image even though docker-compose pull has fetched a newer image.

I looked at How to get docker-compose to always re-create containers from fresh images? which seemed to be similar to my issue, but none of the provided solutions there work for me, since I'm looking for a solution I can use on the production server and there I don't want to be removing all containers before starting them again (possible data loss?). I would like for compose only to detect the new version of the changed images, pull them and then restart the services with those new images.

I created a simple test project for this in which the only goal is to get a version nr to increase on each new build. The version nr is displayed if I browse to the nginx server that is created (this works as expected locally).

docker version: 1.11.2
docker-compose version: 1.7.1
OS: tested on both CentOS 7 and OS X 10.10 using docker-toolbox

My docker-compose.yml:

```<code>version: '2'
services:
  application:
    image: ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
    volumes:
      - /var/www/html
    tty: true

  nginx:
    build: nginx
    ports:
      - "80:80"
    volumes_from:
      - application
    volumes:
      - ./logs/nginx/:/var/log/nginx
  php:
    container_name: buildchaintest_php_1
    build: php-fpm
    expose:
      - "9000"
    volumes_from:
      - application
    volumes:
      - ./logs/php-fpm/:/var/www/logs
</code>```

on our jenkins server I run the following to build and tag the image

```<code>cd $WORKSPACE && PROJECT_VERSION=$(cat VERSION)-dev
/usr/local/bin/docker-compose rm -f
/usr/local/bin/docker-compose build
docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest ourprivate.docker.reg:5000/ourcompany/buildchaintest:$PROJECT_VERSION
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest
</code>```

this seems to be doing what it's supposed to be since I get a new version tag in our repository each time the build completes and the version nr has been bumped.

If I now run

```<code>docker-compose pull && docker-compose -f docker-compose.yml up -d
</code>```

in a folder on my computer, where the contents is only the docker-compose.yml and the necessary Dockerfiles to build the nginx and php services, the output I get is not the latest version number as has been tagged in the registry or is shown in the docker-compose.yml (0.1.8), but the version before that, which is 0.1.7. However the output of the pull command would suggest that a new version of the image was fetched:

```<code>Pulling application (ourprivate.docker.reg:5000/ourcompany/buildchaintest:latest)...
latest: Pulling from ourcompany/buildchaintest
Digest: sha256:8f7a06203005ff932799fe89e7756cd21719cccb9099b7898af2399414bfe62a
Status: Downloaded newer image for docker.locotech.fi:5000/locotech/buildchaintest:0.1.8-dev
</code>```

Only if I run

```<code>docker-compose stop && docker-compose rm -f
</code>```

and then run the docker-compose up command do I get the new version to show up on screen as expected.

Is this intended behaviour of docker-compose? i.e. should I always do a docker-compose rm -f before running up again, even on production servers? Or am I doing something against the grain here, which is why it's not working?

The goal is to have our build process build and create tagged versions of the images needed in a docker-compose.yml, push those to our private registry and then for the "release to production-step" to simply copy the docker-compose.yml to the production server and run a docker-compose pull && docker-compose -f docker-compose.yml up -d for the new image to start in production. If anyone has tips on this or can point to a best practices tutorial for this kind of setup that would be much appreciated also.

答:
Your docker-compose.yml uses image to refer to ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev. That means that running docker-compose build doesn’t take any action in regards to ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev. There must be commands like the following run somewhere:

```<code>docker build -t ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
</code>```

This would put the versioned build into your repository. But it would not update its latest tag. That would still point to the prior version (e.g., 0.1.7-dev).

Then, you ran the other commands on your jenkins:

```<code>cd $WORKSPACE && PROJECT_VERSION=$(cat VERSION)-dev
/usr/local/bin/docker-compose rm -f
/usr/local/bin/docker-compose build
docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest ourprivate.docker.reg:5000/ourcompany/buildchaintest:$PROJECT_VERSION
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest
</code>```

As part of docker-compose build, you are effectively running docker pull ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev on your server. However, that does not account for how the tag ourprivate.docker.reg:5000/ourcompany/buildchaintest:latest (which you refer to in the command docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest ourprivate.docker.reg:5000/ourcompany/buildchaintest:$PROJECT_VERSION) got onto your server. If the latest tag was not defined by something else beforehand, that docker tag command would give this error: No such image: ourprivate.docker.reg:5000/ourcompany/buildchaintest:latest. So, prior to running the commands you showed, your jenkins server must have run something like the following:

```<code>docker pull ourprivate.docker.reg:5000/ourcompany/buildchaintest
</code>```

This command would cause it to pull whatever is set to latest at that time in your repository. Because you gave no proof that you ever pushed your newly build buildchaintest:0.1.8-dev as buildchaintest:latest prior to running the above docker pull command, we have to assume that this is where the old version comes from. As a result, your tag command effectively does this:

```<code>docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest:latest ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
</code>```

Which, if latest is pointing to the same thing at 0.1.7-dev, is the same as doing:

```<code>docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.7-dev ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
</code>```

Then, later, when you run docker-compose pull && docker-compose up -d, of course it will pull what is set in the repository as ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev which should be the old version because you tagged 0.1.7-dev as 0.1.8-dev.

Notes

You seem to be assuming that docker-compose build does something related to building buildchaintest. However, it does not. You set image but not build in your docker-compose.yml. That means docker-compose build will not build the buildchaintest docker image—it will just directly pull and run the docker image tag. Since docker-compose build doesn’t attempt to build buildchaintest, there’s no point to trying to tag or push that image after invoking it.

Also, docker-compose push exists and would do all of the tagging and pushing of things if you specify both build and image (because then image is used to inform docker-compose that it should set a tag for the built thing). This would push the correct tags (and would correctly be a no-op for your docker-compose.yml file).

Your docker-compose has build in it without image. Those things will be built wherever you run docker-compose up. So there is no point (unless you add image to set tags and save those built images and use docker-compose push) in running docker-compose build on the build server (beyond testing that building runs to completion). You’re not saving yourself any time or reducing the work performed by servers during deployment. You’re increasing the number of times things are built and the variability between nodes in your system (as whatever is built on your build server will be different (e.g., file timestamps, updated image tags) than whatever is running on your server.

Unfortunately, your question is not trustworthy. You use commands as if they have different behaviors than they are supposed to have. I am sorry to attack your question, but I have learned some surprising (to me) things about how docker tag and docker-compose work as a result. Thanks!

tl;dr

Make sure that you actually tag and push the correct image into your repository!

Body:
I don't know what I'm doing wrong, but I simply cannot get docker-compose up to use the latest image from our registry without first removing the old containers from the system completely. It looks like compose is using the previously started image even though docker-compose pull has fetched a newer image.

I looked at How to get docker-compose to always re-create containers from fresh images? which seemed to be similar to my issue, but none of the provided solutions there work for me, since I'm looking for a solution I can use on the production server and there I don't want to be removing all containers before starting them again (possible data loss?). I would like for compose only to detect the new version of the changed images, pull them and then restart the services with those new images.

I created a simple test project for this in which the only goal is to get a version nr to increase on each new build. The version nr is displayed if I browse to the nginx server that is created (this works as expected locally).

docker version: 1.11.2
docker-compose version: 1.7.1
OS: tested on both CentOS 7 and OS X 10.10 using docker-toolbox

My docker-compose.yml:

version: '2'
services:
  application:
    image: ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
    volumes:
      - /var/www/html
    tty: true

  nginx:
    build: nginx
    ports:
      - "80:80"
    volumes_from:
      - application
    volumes:
      - ./logs/nginx/:/var/log/nginx
  php:
    container_name: buildchaintest_php_1
    build: php-fpm
    expose:
      - "9000"
    volumes_from:
      - application
    volumes:
      - ./logs/php-fpm/:/var/www/logs

on our jenkins server I run the following to build and tag the image

cd $WORKSPACE && PROJECT_VERSION=$(cat VERSION)-dev
/usr/local/bin/docker-compose rm -f
/usr/local/bin/docker-compose build
docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest ourprivate.docker.reg:5000/ourcompany/buildchaintest:$PROJECT_VERSION
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest

this seems to be doing what it's supposed to be since I get a new version tag in our repository each time the build completes and the version nr has been bumped.

If I now run

docker-compose pull && docker-compose -f docker-compose.yml up -d

in a folder on my computer, where the contents is only the docker-compose.yml and the necessary Dockerfiles to build the nginx and php services, the output I get is not the latest version number as has been tagged in the registry or is shown in the docker-compose.yml (0.1.8), but the version before that, which is 0.1.7. However the output of the pull command would suggest that a new version of the image was fetched:

Pulling application (ourprivate.docker.reg:5000/ourcompany/buildchaintest:latest)...
latest: Pulling from ourcompany/buildchaintest
Digest: sha256:8f7a06203005ff932799fe89e7756cd21719cccb9099b7898af2399414bfe62a
Status: Downloaded newer image for docker.locotech.fi:5000/locotech/buildchaintest:0.1.8-dev

Only if I run

docker-compose stop && docker-compose rm -f

and then run the docker-compose up command do I get the new version to show up on screen as expected.

Is this intended behaviour of docker-compose? i.e. should I always do a docker-compose rm -f before running up again, even on production servers? Or am I doing something against the grain here, which is why it's not working?

The goal is to have our build process build and create tagged versions of the images needed in a docker-compose.yml, push those to our private registry and then for the "release to production-step" to simply copy the docker-compose.yml to the production server and run a docker-compose pull && docker-compose -f docker-compose.yml up -d for the new image to start in production. If anyone has tips on this or can point to a best practices tutorial for this kind of setup that would be much appreciated also.

Body:
Your docker-compose.yml uses image to refer to ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev. That means that running docker-compose build doesn’t take any action in regards to ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev. There must be commands like the following run somewhere:

docker build -t ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev

This would put the versioned build into your repository. But it would not update its latest tag. That would still point to the prior version (e.g., 0.1.7-dev).

Then, you ran the other commands on your jenkins:

cd $WORKSPACE && PROJECT_VERSION=$(cat VERSION)-dev
/usr/local/bin/docker-compose rm -f
/usr/local/bin/docker-compose build
docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest ourprivate.docker.reg:5000/ourcompany/buildchaintest:$PROJECT_VERSION
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest

As part of docker-compose build, you are effectively running docker pull ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev on your server. However, that does not account for how the tag ourprivate.docker.reg:5000/ourcompany/buildchaintest:latest (which you refer to in the command docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest ourprivate.docker.reg:5000/ourcompany/buildchaintest:$PROJECT_VERSION) got onto your server. If the latest tag was not defined by something else beforehand, that docker tag command would give this error: No such image: ourprivate.docker.reg:5000/ourcompany/buildchaintest:latest. So, prior to running the commands you showed, your jenkins server must have run something like the following:

docker pull ourprivate.docker.reg:5000/ourcompany/buildchaintest

This command would cause it to pull whatever is set to latest at that time in your repository. Because you gave no proof that you ever pushed your newly build buildchaintest:0.1.8-dev as buildchaintest:latest prior to running the above docker pull command, we have to assume that this is where the old version comes from. As a result, your tag command effectively does this:

docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest:latest ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev

Which, if latest is pointing to the same thing at 0.1.7-dev, is the same as doing:

docker tag ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.7-dev ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev
docker push ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev

Then, later, when you run docker-compose pull && docker-compose up -d, of course it will pull what is set in the repository as ourprivate.docker.reg:5000/ourcompany/buildchaintest:0.1.8-dev which should be the old version because you tagged 0.1.7-dev as 0.1.8-dev.

Notes

You seem to be assuming that docker-compose build does something related to building buildchaintest. However, it does not. You set image but not build in your docker-compose.yml. That means docker-compose build will not build the buildchaintest docker image—it will just directly pull and run the docker image tag. Since docker-compose build doesn’t attempt to build buildchaintest, there’s no point to trying to tag or push that image after invoking it.

Also, docker-compose push exists and would do all of the tagging and pushing of things if you specify both build and image (because then image is used to inform docker-compose that it should set a tag for the built thing). This would push the correct tags (and would correctly be a no-op for your docker-compose.yml file).

Your docker-compose has build in it without image. Those things will be built wherever you run docker-compose up. So there is no point (unless you add image to set tags and save those built images and use docker-compose push) in running docker-compose build on the build server (beyond testing that building runs to completion). You’re not saving yourself any time or reducing the work performed by servers during deployment. You’re increasing the number of times things are built and the variability between nodes in your system (as whatever is built on your build server will be different (e.g., file timestamps, updated image tags) than whatever is running on your server.

Unfortunately, your question is not trustworthy. You use commands as if they have different behaviors than they are supposed to have. I am sorry to attack your question, but I have learned some surprising (to me) things about how docker tag and docker-compose work as a result. Thanks!

tl;dr

Make sure that you actually tag and push the correct image into your repository!


来源: stackexchange

问:
RSpec 2 use of assign for view specs
I feel like I'm missing something pretty basic, but I can't seem to figure it out, either.

When doing the following spec:

```<code>require 'spec_helper'

describe "/mymodel/show.html.erb" do
  before(:each) do
    @mymodel = Factory(:mymodel)
    @user = Factory(:user)
    assign(:web_tip, @mymodel)
    assign(:current_user, @user)
  end

  it "renders attributes in <p>" do
    render
    rendered.should have_text(/somevalue/)
  end
end
</code>```

I get an error that the local variable current_user is undefined (the view's layout wants to call it to show the current login status).

I'm on Rails 3, Rspec 2.6.4, and thought I was following the current docs correctly.

答:
what worked for me (with a similar problem) was something like:

@controller.stub(:current_user) { @user }

I think the problem is that current user is not an assignation (instance variable), is a value in the session.

Hope it helps

ContentLicense: CC BY-SA 3.0

Title: RSpec 2 use of assign for view specs

Body:
I feel like I'm missing something pretty basic, but I can't seem to figure it out, either.

When doing the following spec:

require 'spec_helper'

describe "/mymodel/show.html.erb" do
  before(:each) do
    @mymodel = Factory(:mymodel)
    @user = Factory(:user)
    assign(:web_tip, @mymodel)
    assign(:current_user, @user)
  end

  it "renders attributes in
" do
    render
    rendered.should have_text(/somevalue/)
  end
end

I get an error that the local variable current_user is undefined (the view's layout wants to call it to show the current login status).

I'm on Rails 3, Rspec 2.6.4, and thought I was following the current docs correctly.


问:
Enabling Service Broker in SQL Server 2008
I am integrating SqlCacheDependency to use in my LinqToSQL datacontext.

I am using an extension class for Linq querys found here - http://code.msdn.microsoft.com/linqtosqlcache

I have wired up the code and when I open the page I get this exception -

"The SQL Server Service Broker for the current database is not enabled, and as a result query notifications are not supported.  Please enable the Service Broker for this database if you wish to use notifications."

its coming from this event in the global.asax

```<code>        protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
        //In Application Start Event
        System.Data.SqlClient.SqlDependency.Start(new dataContextDataContext().Connection.ConnectionString);

    }
</code>```

my question is...

how do i enable Service Broker in my SQL server 2008 database? I have tried to run this query.. ALTER DATABASE tablename SET ENABLE_BROKER but it never ends and runs for ever, I have to manually stop it.

once I have this set in SQL server 2008, will it filter down to my DataContext, or do I need to configure something there too ?

thanks for any help

Truegilly

答:
Error Outputted by Service Broker. Image 1

To Fix, enable Service broker using SSMS, Image 2

After Setting to true Service Broker error should gone now, see my Image 3

ContentLicense: CC BY-SA 2.5

Body:
I am integrating SqlCacheDependency to use in my LinqToSQL datacontext.

I am using an extension class for Linq querys found here - http://code.msdn.microsoft.com/linqtosqlcache

I have wired up the code and when I open the page I get this exception -

"The SQL Server Service Broker for the current database is not enabled, and as a result query notifications are not supported.  Please enable the Service Broker for this database if you wish to use notifications."

its coming from this event in the global.asax

        protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
        //In Application Start Event
        System.Data.SqlClient.SqlDependency.Start(new dataContextDataContext().Connection.ConnectionString);

    }

my question is...

how do i enable Service Broker in my SQL server 2008 database? I have tried to run this query.. ALTER DATABASE tablename SET ENABLE_BROKER but it never ends and runs for ever, I have to manually stop it.

once I have this set in SQL server 2008, will it filter down to my DataContext, or do I need to configure something there too ?

thanks for any help

Truegilly

ContentLicense: CC BY-SA 4.0


问:
Join tables using multiple columns
I have 2 tables in Python. I want them to join using the first 3 columns (i.e. Level1, Level2, and YearMonth). I used the following code but it would omit those rows where there was no value for YearMonth in Table 2:

```<code>sqldf.run("SELECT t1.Level1,t1.Level2,t1.YearMonth,t1.MemberMonths,t2.TotalER FROM Table1 AS 't1' LEFT JOIN Table2 as t2 ON t1.Level1=t2.Level1 and t1.Level2=t2.Level2 and t1.YearMonth=t2.YearMonth")
</code>```

Please guide me a better way to achieve the desired table in Python.

答:
You can try using the merge method in pandas follwed by a fillna.

```<code>df_joined = pd.merge(t1, t2, on=['Level1', 'Level2', 'YearMonth'], how='left')
df_joined['TotalER'].fillna(0, inplace=True)
</code>```

When you perform left join, the non matching rows from the right table come as NaN. That's why you've to separately fill those NaN values as part of your post-processing step.

Title: Join tables using multiple columns

Body:
I have 2 tables in Python. I want them to join using the first 3 columns (i.e. Level1, Level2, and YearMonth). I used the following code but it would omit those rows where there was no value for YearMonth in Table 2:

sqldf.run("SELECT t1.Level1,t1.Level2,t1.YearMonth,t1.MemberMonths,t2.TotalER FROM Table1 AS 't1' LEFT JOIN Table2 as t2 ON t1.Level1=t2.Level1 and t1.Level2=t2.Level2 and t1.YearMonth=t2.YearMonth")

Please guide me a better way to achieve the desired table in Python.

Body:
You can try using the merge method in pandas follwed by a fillna.

df_joined = pd.merge(t1, t2, on=['Level1', 'Level2', 'YearMonth'], how='left')
df_joined['TotalER'].fillna(0, inplace=True)

When you perform left join, the non matching rows from the right table come as NaN. That's why you've to separately fill those NaN values as part of your post-processing step.


问:
Is there a way to have a default value inside a dictionary in Python?
I want to know if there is a way to have a default value in a dictionary (without using the get function), so that:

```<code>dict colors = {
"Black":(0, 0, 0),
"White":(255, 255, 255),
default:(100, 100, 100)
};

paint(colors["Blue"]);  # Paints the default value (Grey) onto the screen

</code>```

Of course, the code above wouldn't work in Python, and I have serious doubt it is even possible.

I Know that by using get I could do this easily, however I'm still curious if there is any other way (just for curiosity).

答:
You can use a defaultdict.

from collections import defaultdict

colors = defaultdict(lambda: (100, 100, 100))

colors["Black"] = (0, 0, 0),
colors["White"] = (255, 255, 255)

# Prints (0, 0, 0), because "Black" is mapped to (0, 0, 0) in the dictionary.
print(colors["Black"])

# Prints (100, 100, 100), because "Blue" is not a key in the dictionary.
print(colors["Blue"])
```

Body:
I want to know if there is a way to have a default value in a dictionary (without using the get function), so that:

dict colors = {
"Black":(0, 0, 0),
"White":(255, 255, 255),
default:(100, 100, 100)
};

paint(colors["Blue"]);  # Paints the default value (Grey) onto the screen

Of course, the code above wouldn't work in Python, and I have serious doubt it is even possible.

I Know that by using get I could do this easily, however I'm still curious if there is any other way (just for curiosity).


问:
JS - jQuery Remove all bands that contains a class but keep the one with the ID that is in the URL
I need your help. I am new to Javascript and jQuery. I have something to do.
I have a list of divs with the same class but each div has a specific ID.
Let say I have this:

```<code><div class="list" id="apples"></div>
<div class="list" id="bananas"></div>
<div class="list" id="pineapples"></div>
</code>```

I have the URL https://johndoe.com/apples, https://johndoe.com/bananas and https://johndoe.com/pineapples.

All divs are displayed on the 3 pages but I want to have only the div with id apples displayed on the Apples page and the others to be entirely removed not hidden. I want the same for each page (bananas displayed on bananas' page...). So what I wrote is this. I thought that changing apples div's class to something else would avoid it to be deleted.

```<code>var fruitId = val['id'];
function displayDiv()
{
    var selectedSection = document.getElementById(fruitId);
    if (window.location.href.indexOf(fruitId) > 0)
    {
        selectedSection.setAttribute('class', 'selectedfruit');
        $("div.list").remove();
    }
}
</code>```

Do not pay attention to fruitId it's 'apples', 'bananas' and 'pineapples' in the JSON file and I have the correct list.

答:
Use filter(function) and check the id in the function

```<code>$("div.list").filter(function(){
   return !window.location.href.includes(this.id)
}).remove();
</code>```

This will remove only the ones where the id value is not in the href

Body:
I need your help. I am new to Javascript and jQuery. I have something to do.
I have a list of divs with the same class but each div has a specific ID.
Let say I have this:

I have the URL https://johndoe.com/apples, https://johndoe.com/bananas and https://johndoe.com/pineapples.

All divs are displayed on the 3 pages but I want to have only the div with id apples displayed on the Apples page and the others to be entirely removed not hidden. I want the same for each page (bananas displayed on bananas' page...). So what I wrote is this. I thought that changing apples div's class to something else would avoid it to be deleted.

var fruitId = val['id'];
function displayDiv()
{
    var selectedSection = document.getElementById(fruitId);
    if (window.location.href.indexOf(fruitId) > 0)
    {
        selectedSection.setAttribute('class', 'selectedfruit');
        $("div.list").remove();
    }
}

Do not pay attention to fruitId it's 'apples', 'bananas' and 'pineapples' in the JSON file and I have the correct list.

Body:
Use filter(function) and check the id in the function

$("div.list").filter(function(){
   return !window.location.href.includes(this.id)
}).remove();

This will remove only the ones where the id value is not in the href


问:
Firebase Authentication Vue Router Guard Issue w/ Vuex
I am using firebase authentication with vue and in order to prevent initial flickering of "login" in the navigation bar on the dashboard, (instead of the logged in user's name on authentication), I initialize firebase in main.js and wrap the vue app in the onAuthStateChanged function.

main.js

```<code>initializeApp(firebaseConfig);

const auth = getAuth();
const app = new Vue({
  router,
  store,
  vuetify,
  render: h => h(App)
});
auth.onAuthStateChanged(user => {
  console.log('firedOnAuthStateChanged');
  store.dispatch("setUser", user).then(() => {
    app.$mount('#app');
  });
});
</code>```

This works great. I sign in, the page doesn't load until the user is authenticated to firebase and I update the vuex store with updated user information (some from firebase, some from the backend).

The problem I'm having now, is I want to use the beforeEach route guard in the router but the route guards run before the authStateChange fires in main.js. Because of this, the user isn't set in vuex and when I use the stored user state to determine if the user is logged in, it believes they are not logged in because the firebase method hasn't updated it yet.

authentication.js (module from store.js)

```<code>setUser({dispatch, commit}, user) {
return new Promise((resolve, reject) => {

  if(user)
  {
    user.getIdToken().then(token => {
      commit('SET_SESSION_TOKEN', token);
      console.log(token);
      this._vm.$axios.get('/api/user/login',{
          headers: {
              'Authorization': `Bearer ${token}`
          }
      })
      .then((response) => {
          commit('SET_SESSION_USER', response.data);
          resolve(response);

      })
    });
  }
  else
  {
    this._vm.$axios.post('/api/user/logout').then((response) => {
      console.log(response);
      commit('SET_SESSION_USER', null);
      commit('SET_SESSION_TOKEN', null);
    });
    resolve();
  }
})
</code>```

},

router.js

```<code>router.beforeEach(async (to, from, next) => {

  console.log('Is Authenticated:' +store.getters.isAuthenticated);
  console.log('Session User:' +store.getters.getSessionUser);
  if (to.matched.some(record => record.meta.authRequired) && !store.getters.isAuthenticated) {//!userAuth) {
    next({ path: '/login'})
    } else {
      next();
    }
});
</code>```

I've searched around and some solutions say to add your firebase onAuthStateChanged in the router. That does allow the route guards to work correctly but that recreated the problem I had before adding that method to main.js - the page flickers with pre-logged in information. I found other possibility that said you could add a promise around the onAuthStateChanged method and call that from the router. That may work but I'm not sure how to implement that with firebase in the main.js file wrapped around the vue app being initialized.

I would like to avoid setting cookies or using localstorage to make this work and I'm wondering if there is some way to get firebase, vuex state and vue route guards to function correctly together.

答:
I figured out a way to do this. Login and logout works correctly, notifications work at login and logout (not at all on refresh), the user is perpetually logged in (onAuthState and token updates should handle the 1 hour timeout), and the page loads only after the firebase login finishes so there is no flash of "Login" instead of the username.

main.js

```<code>initializeApp(firebaseConfig);

const auth = getAuth();

let app;
auth.onAuthStateChanged(user => {
  console.log('firedOnAuthStateChanged)')
  store.dispatch("setUser", user).then(() => {
    if (!app) {
      app = new Vue({
        router,
        store,
        vuetify,
        render: h => h(App)
      }).$mount('#app')
    }
  });
});
</code>```

authentication.js (module from store.js)

```<code>setUser({dispatch, commit}, user) {
    return new Promise((resolve, reject) => {
      if(user)
      {
        user.getIdToken().then(token => {
          commit('SET_SESSION_TOKEN', token);
          this._vm.$axios.get('/api/user/login',{
              headers: {
                  'Authorization': `Bearer ${token}`
              }
          })
          .then((response) => {
              commit('SET_SESSION_USER', response.data);
              resolve(response);

           })
          .catch(error => {
              dispatch('setSnackbar', {
                color: "error",
                timeout: 4000,
                text: 'Failed verifying token on login.'
              });
              reject();
          });

        });
      }
      else
      {
        this._vm.$axios.post('/api/user/logout').then((response) => {
          commit('SET_SESSION_USER', null);
          commit('SET_SESSION_TOKEN', null);
        });
        resolve();
      }
    })
  }
</code>```

router.js

```<code>router.beforeEach((to, from, next) => {
  const auth = getAuth();
  const user = auth.currentUser;
  if (to.matched.some(record => record.meta.authRequired) && !user) {
    next({ path: '/login'})
    } else {
      next();
    }
});
</code>```

If you know of a more efficient way of doing this, please let me know.

Body:
I am using firebase authentication with vue and in order to prevent initial flickering of "login" in the navigation bar on the dashboard, (instead of the logged in user's name on authentication), I initialize firebase in main.js and wrap the vue app in the onAuthStateChanged function.

main.js

initializeApp(firebaseConfig);

const auth = getAuth();
const app = new Vue({
  router,
  store,
  vuetify,
  render: h => h(App)
});
auth.onAuthStateChanged(user => {
  console.log('firedOnAuthStateChanged');
  store.dispatch("setUser", user).then(() => {
    app.$mount('#app');
  });
});

This works great. I sign in, the page doesn't load until the user is authenticated to firebase and I update the vuex store with updated user information (some from firebase, some from the backend).

The problem I'm having now, is I want to use the beforeEach route guard in the router but the route guards run before the authStateChange fires in main.js. Because of this, the user isn't set in vuex and when I use the stored user state to determine if the user is logged in, it believes they are not logged in because the firebase method hasn't updated it yet.

authentication.js (module from store.js)

setUser({dispatch, commit}, user) {
return new Promise((resolve, reject) => {

  if(user)
  {
    user.getIdToken().then(token => {
      commit('SET_SESSION_TOKEN', token);
      console.log(token);
      this._vm.$axios.get('/api/user/login',{
          headers: {
              'Authorization': `Bearer ${token}`
          }
      })
      .then((response) => {
          commit('SET_SESSION_USER', response.data);
          resolve(response);

      })
    });
  }
  else
  {
    this._vm.$axios.post('/api/user/logout').then((response) => {
      console.log(response);
      commit('SET_SESSION_USER', null);
      commit('SET_SESSION_TOKEN', null);
    });
    resolve();
  }
})

},

router.js

router.beforeEach(async (to, from, next) => {

  console.log('Is Authenticated:' +store.getters.isAuthenticated);
  console.log('Session User:' +store.getters.getSessionUser);
  if (to.matched.some(record => record.meta.authRequired) && !store.getters.isAuthenticated) {//!userAuth) {
    next({ path: '/login'})
    } else {
      next();
    }
});

I've searched around and some solutions say to add your firebase onAuthStateChanged in the router. That does allow the route guards to work correctly but that recreated the problem I had before adding that method to main.js - the page flickers with pre-logged in information. I found other possibility that said you could add a promise around the onAuthStateChanged method and call that from the router. That may work but I'm not sure how to implement that with firebase in the main.js file wrapped around the vue app being initialized.

I would like to avoid setting cookies or using localstorage to make this work and I'm wondering if there is some way to get firebase, vuex state and vue route guards to function correctly together.

Body:
I figured out a way to do this. Login and logout works correctly, notifications work at login and logout (not at all on refresh), the user is perpetually logged in (onAuthState and token updates should handle the 1 hour timeout), and the page loads only after the firebase login finishes so there is no flash of "Login" instead of the username.

main.js

initializeApp(firebaseConfig);

const auth = getAuth();

let app;
auth.onAuthStateChanged(user => {
  console.log('firedOnAuthStateChanged)')
  store.dispatch("setUser", user).then(() => {
    if (!app) {
      app = new Vue({
        router,
        store,
        vuetify,
        render: h => h(App)
      }).$mount('#app')
    }
  });
});

authentication.js (module from store.js)

setUser({dispatch, commit}, user) {
    return new Promise((resolve, reject) => {
      if(user)
      {
        user.getIdToken().then(token => {
          commit('SET_SESSION_TOKEN', token);
          this._vm.$axios.get('/api/user/login',{
              headers: {
                  'Authorization': `Bearer ${token}`
              }
          })
          .then((response) => {
              commit('SET_SESSION_USER', response.data);
              resolve(response);

           })
          .catch(error => {
              dispatch('setSnackbar', {
                color: "error",
                timeout: 4000,
                text: 'Failed verifying token on login.'
              });
              reject();
          });

        });
      }
      else
      {
        this._vm.$axios.post('/api/user/logout').then((response) => {
          commit('SET_SESSION_USER', null);
          commit('SET_SESSION_TOKEN', null);
        });
        resolve();
      }
    })
  }

router.js

router.beforeEach((to, from, next) => {
  const auth = getAuth();
  const user = auth.currentUser;
  if (to.matched.some(record => record.meta.authRequired) && !user) {
    next({ path: '/login'})
    } else {
      next();
    }
});

If you know of a more efficient way of doing this, please let me know.


问:
How to send an image in Java to a Python server that uses requests?
I have 2 python scripts, 1 is the server itself and the other for POST-ing and image.
Server.py ->

```<code>app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        file = request.files.get('file')
        if file is None or file.filename == "":
            return jsonify({"error": "nothing inside file"})

        try:
            image_bytes = file.read()
            pillow_img = imageio.imread(image_bytes, pilmode='RGB')
            start_time = time.time()
            result = tfnet.return_predict(pillow_img)[0]
            end_time = time.time()
            result['response_time'] = end_time - start_time
            return jsonify({'Output': str(result)})
        except Exception as e:
            return jsonify({"error": str(e)})

    return "OK"
</code>```

I'm trying to re-create the test.py into java, I'm able to POST to the server and get 200 response. But I'm having trouble sending and image to the server.py thats running.
I'm breaking this problem into 2 parts: 1) Try POST a json for my server.py to recognize it as some JSON instead of None. 2) Try encode an image and POST it to server.py to recognize and send a response back.
I'm not able to do both the steps.
Test.py ->

```<code>import requests

resp = requests.post("http://xxxxxxxxxxxxxx:8080/",
                    files={'file': open('D://Jupyter//GCP Deploy//darkflow-master//1.jpg', 'rb')})

print(resp.json())
</code>```

and the respective java file that doesnt send the image but a json.

```<code>public class HttpURLConnectionExample {
public static void main(String[] args) throws IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost("http://xxxxxxxxxxxxxx:8080/");
        String json = "{\r\n" +
            "  \"file\": \"string value\"\r\n" +
            "}";

        StringEntity stringEntity = new StringEntity(json);
        httpPost.setEntity(stringEntity);
        System.out.println("Executing request " + httpPost.getRequestLine());

        // Create a custom response handler
        ResponseHandler < String > responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };
        String responseBody = httpclient.execute(httpPost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
    }
}
</code>```

}

The only success I'm having from this is that the server recognizes the POST request, but doesnt go into the try block, the file in the Server.py is None.

答: try convert the image to base64 on client, put it in json, send it to server, then in the server you can convert base64 to image</p>

Body:
I have 2 python scripts, 1 is the server itself and the other for POST-ing and image.
Server.py ->

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        file = request.files.get('file')
        if file is None or file.filename == "":
            return jsonify({"error": "nothing inside file"})

        try:
            image_bytes = file.read()
            pillow_img = imageio.imread(image_bytes, pilmode='RGB')
            start_time = time.time()
            result = tfnet.return_predict(pillow_img)[0]
            end_time = time.time()
            result['response_time'] = end_time - start_time
            return jsonify({'Output': str(result)})
        except Exception as e:
            return jsonify({"error": str(e)})

    return "OK"

I'm trying to re-create the test.py into java, I'm able to POST to the server and get 200 response. But I'm having trouble sending and image to the server.py thats running.
I'm breaking this problem into 2 parts: 1) Try POST a json for my server.py to recognize it as some JSON instead of None. 2) Try encode an image and POST it to server.py to recognize and send a response back.
I'm not able to do both the steps.
Test.py ->

import requests

resp = requests.post("http://xxxxxxxxxxxxxx:8080/",
                    files={'file': open('D://Jupyter//GCP Deploy//darkflow-master//1.jpg', 'rb')})

print(resp.json())

and the respective java file that doesnt send the image but a json.

public class HttpURLConnectionExample {
public static void main(String[] args) throws IOException {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost("http://xxxxxxxxxxxxxx:8080/");
        String json = "{\r\n" +
            "  \"file\": \"string value\"\r\n" +
            "}";

        StringEntity stringEntity = new StringEntity(json);
        httpPost.setEntity(stringEntity);
        System.out.println("Executing request " + httpPost.getRequestLine());

        // Create a custom response handler
        ResponseHandler < String > responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };
        String responseBody = httpclient.execute(httpPost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
    }
}

}

The only success I'm having from this is that the server recognizes the POST request, but doesnt go into the try block, the file in the Server.py is None.


问:
Swift Table View Cell Value Failed to display vertically
I am new to swift . I am creating table view cell programatically with the sub title . I defined the two label and two function to get the value form API and display it into label control but the problem is the values of label are displayed into correct position . I want to display the title and then below the title is sub title values . Here is the screen shot .

Here is the code table view cell.

```<code>extension ViewController: UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.rovers.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: StoryCell.identifier , for: indexPath) as? StoryCell
        else{ return UITableViewCell()}

        let row = indexPath.row

        let title = viewModel.getTitle(by: row)
        cell.configureCell(title:title)

        let Id = viewModel.getId(by: row)
        cell.configureCell(Id: Id)
        return cell
    }

}
</code>```

Here is code for configure the label .

```<code>import UIKit

class StoryCell: UITableViewCell {

    static let identifier = "StoryCell"

    private lazy var storyTitleLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.textAlignment = .left
        return label
    }()

    private lazy var storyIdLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.textAlignment = .left
        return label
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setUpUI()
        setUpUIID()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configureCell(title: String) {
        storyTitleLabel.text = "Status :\(title)"
    }

    func configureCell(Id: Int) {
        storyIdLabel.text = "Id: \(String(Id))"
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    private func setUpUI() {
        contentView.addSubview(storyTitleLabel)

        // constraints
        let safeArea = contentView.safeAreaLayoutGuide
        storyTitleLabel.topAnchor.constraint(equalTo: safeArea.topAnchor).isActive = true
        storyTitleLabel.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor).isActive = true
        storyTitleLabel.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor).isActive = true
        storyTitleLabel.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor).isActive = true

    }

   private func setUpUIID() {
        contentView.addSubview(storyIdLabel)

        // constraints
        let safeArea = contentView.safeAreaLayoutGuide
        storyIdLabel.topAnchor.constraint(equalTo: safeArea.topAnchor).isActive = true
        storyIdLabel.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor).isActive = true
        storyIdLabel.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor).isActive = true
        storyIdLabel.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor).isActive = true
    }
}
</code>```

答:
I made some changes in your code check below. Now it should be fine.</p>
```<code>private func setUpUI() {
    contentView.addSubview(storyTitleLabel)

    // constraints
    let safeArea = contentView.safeAreaLayoutGuide
    storyTitleLabel.topAnchor.constraint(equalTo: safeArea.topAnchor).isActive = true
    storyTitleLabel.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor).isActive = true
    storyTitleLabel.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor).isActive = true

}

private func setUpUIID() {
    contentView.addSubview(storyIdLabel)
    let safeArea = contentView.safeAreaLayoutGuide
    storyIdLabel.topAnchor.constraint(equalTo: storyTitleLabel.topAnchor).constant = 5
    storyIdLabel.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor).isActive = true
    storyIdLabel.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor).isActive = true
    storyIdLabel.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor).isActive = true
}
</code>```

Body:
I am new to swift . I am creating table view cell programatically with the sub title . I defined the two label and two function to get the value form API and display it into label control but the problem is the values of label are displayed into correct position . I want to display the title and then below the title is sub title values . Here is the screen shot .

Here is the code table view cell.

extension ViewController: UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.rovers.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: StoryCell.identifier , for: indexPath) as? StoryCell
        else{ return UITableViewCell()}

        let row = indexPath.row

        let title = viewModel.getTitle(by: row)
        cell.configureCell(title:title)

        let Id = viewModel.getId(by: row)
        cell.configureCell(Id: Id)
        return cell
    }

}

Here is code for configure the label .

import UIKit

class StoryCell: UITableViewCell {

    static let identifier = "StoryCell"

    private lazy var storyTitleLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.textAlignment = .left
        return label
    }()

    private lazy var storyIdLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.textAlignment = .left
        return label
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setUpUI()
        setUpUIID()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configureCell(title: String) {
        storyTitleLabel.text = "Status :\(title)"
    }

    func configureCell(Id: Int) {
        storyIdLabel.text = "Id: \(String(Id))"
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    private func setUpUI() {
        contentView.addSubview(storyTitleLabel)

        // constraints
        let safeArea = contentView.safeAreaLayoutGuide
        storyTitleLabel.topAnchor.constraint(equalTo: safeArea.topAnchor).isActive = true
        storyTitleLabel.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor).isActive = true
        storyTitleLabel.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor).isActive = true
        storyTitleLabel.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor).isActive = true

    }

   private func setUpUIID() {
        contentView.addSubview(storyIdLabel)

        // constraints
        let safeArea = contentView.safeAreaLayoutGuide
        storyIdLabel.topAnchor.constraint(equalTo: safeArea.topAnchor).isActive = true
        storyIdLabel.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor).isActive = true
        storyIdLabel.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor).isActive = true
        storyIdLabel.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor).isActive = true
    }
}

Body:
I made some changes in your code check below. Now it should be fine.

private func setUpUI() {
    contentView.addSubview(storyTitleLabel)

    // constraints
    let safeArea = contentView.safeAreaLayoutGuide
    storyTitleLabel.topAnchor.constraint(equalTo: safeArea.topAnchor).isActive = true
    storyTitleLabel.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor).isActive = true
    storyTitleLabel.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor).isActive = true

}

private func setUpUIID() {
    contentView.addSubview(storyIdLabel)
    let safeArea = contentView.safeAreaLayoutGuide
    storyIdLabel.topAnchor.constraint(equalTo: storyTitleLabel.topAnchor).constant = 5
    storyIdLabel.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor).isActive = true
    storyIdLabel.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor).isActive = true
    storyIdLabel.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor).isActive = true
}


答:
Check out the collections.defaultdict type  (https://docs.python.org/3/library/collections.html#collections.defaultdict):

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

Your code would use it like this:

```<code>from collections import defaultdict

colors = defaultdict(lambda: (100, 100, 100), {
    "Black":(0, 0, 0),
    "White":(255, 255, 255),
})

print(colors['Blue'])
</code>```

Title: Is there a way to have a default value inside a dictionary in Python?

Body:
Check out the collections.defaultdict type  (https://docs.python.org/3/library/collections.html#collections.defaultdict):

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

Your code would use it like this:

from collections import defaultdict

colors = defaultdict(lambda: (100, 100, 100), {
    "Black":(0, 0, 0),
    "White":(255, 255, 255),
})

print(colors['Blue'])


Title: Need to fill data frame with missing years and value in 2nd column

Body:
I have data frames with counts from a series of years, 1970-2020, generated by a subset command from a larger data set, i.e. resulting in two columns "Year" and "Count":

Year         Count
1987         8
1989         1
1991         1
1992         4
1995         11
1996         3
1997         7
.
.
.
2019         2
2020         5

There are missing years where Count=0, and I need a procedure to fill these df's with the missing years and Count=0. I have this script that I can't get to work:

library(tidyr)
aug <- subset(mainframe, month==8)
complete(aug, year = 1987:2020, fill = list(Count = 0))

Here's a sample dataframe 'aug':

dput(aug)
structure(list(month = structure(c(8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L), .Label = c("1", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "11", "12"), class = "factor"), year = structure(1:28, .Label = c("1987",
"1988", "1989", "1990", "1991", "1992", "1993", "1994", "1995",
"1996", "1998", "2000", "2001", "2002", "2003", "2004", "2005",
"2006", "2007", "2008", "2009", "2010", "2011", "2013", "2015",
"2016", "2018", "2020"), class = "factor"), Count = c(4L, 0L,
3L, 3L, 0L, 0L, 1L, 0L, 1L, 1L, 3L, 0L, 0L, 0L, 0L, 2L, 0L, 0L,
0L, 2L, 0L, 1L, 1L, 0L, 0L, 1L, 0L, 1L)), row.names = c(8L, 20L,
32L, 44L, 56L, 68L, 80L, 92L, 104L, 116L, 128L, 140L, 152L, 164L,
176L, 188L, 200L, 212L, 224L, 236L, 248L, 260L, 272L, 284L, 296L,
308L, 320L, 332L), class = "data.frame")

Body:
If I get your question correctly, you want to have a complete dataframe containing year 1987 to 2020, but there are some missing years in your aug dataframe, and you want to fill in the missing years with month = "8" and Count = 0.

Here's a tidyverse approach (in your original aug dataframe, your year is factor, so at the end of my solution I also transformed it into factor):

Your dataset

    month year Count
8       8 1987     4
20      8 1988     0
32      8 1989     3
44      8 1990     3
56      8 1991     0
68      8 1992     0
80      8 1993     1
92      8 1994     0
104     8 1995     1
116     8 1996     1
128     8 1998     3
140     8 2000     0
152     8 2001     0
164     8 2002     0
176     8 2003     0
188     8 2004     2
200     8 2005     0
212     8 2006     0
224     8 2007     0
236     8 2008     2
248     8 2009     0
260     8 2010     1
272     8 2011     1
284     8 2013     0
296     8 2015     0
308     8 2016     1
320     8 2018     0
332     8 2020     1

Solution

library(tidyverse)

aug %>% mutate(year = as.numeric(as.character(year))) %>%
  complete(year = first(year):max(year), # or year = 1987:2020
           fill = list(month = "8", Count = 0)) %>%
  mutate(year = as.factor(year))

Output

year    month   Count
1987    8   4
1988    8   0
1989    8   3
1990    8   3
1991    8   0
1992    8   0
1993    8   1
1994    8   0
1995    8   1
1996    8   1
1997    8   0
1998    8   3
1999    8   0
2000    8   0
2001    8   0
2002    8   0
2003    8   0
2004    8   2
2005    8   0
2006    8   0
2007    8   0
2008    8   2
2009    8   0
2010    8   1
2011    8   1
2012    8   0
2013    8   0
2014    8   0
2015    8   0
2016    8   1
2017    8   0
2018    8   0
2019    8   0
2020    8   1


问:
Docker stopped working: Failed to install symlinks in /usr/local/bin (stage 4)
All of a sudden today Docker on my Mac stopped working with a 'failed to install symlinks"

I tried to get back to a clean state by uninstalling Docker and trying to remove all symlinks in the /usr/local/bin. I'm left with two simlinks docker-compose and docker-machine that I cannot remove even with sudo.

Any suggestion on how to delete those files (that I suspect are the root of the problem) so I can do a clean install?

Not sure if helps but 'Macfee Endpoint security' is running on my Mac.

答: I had the same issue. I find bin some what messed in /usr/local/bin. I took a backup of /usr/local/bin and deleted it and recreate new directory /usr/local/bin with same permissions. Then it worked.</p>


问:
The point within the range of rectangle
In easy English can someone please explain to me this line of code.</p>
```<code>public bool IsAt(Point2D pt)
    {
        return (pt.X > Width && pt.X < Width + X && pt.Y > Height && pt.Y < Height + Y);
    }
</code>```

答:
Assuming Width and Height are actually the width and the height of a defined rectangle, then I'd go with the class System.Drawing.Rectangle and use the method Contains() to check if a point is in a rectangle.

Read: https://learn.microsoft.com/en-us/dotnet/api/system.drawing.rectangle.contains?view=net-6.0#system-drawing-rectangle-contains(system-drawing-point)

Title: The point within the range of rectangle

Body:
In easy English can someone please explain to me this line of code.

public bool IsAt(Point2D pt)
    {
        return (pt.X > Width && pt.X < Width + X && pt.Y > Height && pt.Y < Height + Y);
    }


问:
How do I uppercase an entire sheet in Office Scripts Excel (Typescript)?
I was able to do the below in VBA and need to transfer my script to Office Scripts in Excel 365. I can't figure out how to do the whole sheet and not just a string.

This is what I used in VBA:

```<code>Dim rng As Range
Set rng = Selection
For Each cell In rng
cell.Value = UCase(cell)
Next cell
</code>```

答:
This worked for me, could be a little cumbersome with a lot of cells but should still work.

```<code>function main(workbook: ExcelScript.Workbook, worksheetName: string)
{
  let worksheet = workbook.getWorksheet(worksheetName);

  // Ge tthe Used Range on the given worksheet and all values.
  let usedRange = worksheet.getUsedRange(false);
  var values = usedRange.getValues();

  // Now loop through each cell and upper case it.
  for (var row = 0; row < values.length; row++) {
    for (var col = 0; col < values[row].length; col++) {
      values[row][col] = values[row][col].toString().toUpperCase();
    }
  }

  usedRange.setValues(values);
}
</code>```

Note:  There is a parameter to the function so it is expected to be used via PowerAutomate/LogicApps but if you don't want that then you should be able to change it up to use the active sheet with relative ease.

e.g. ...

```<code>function main(workbook: ExcelScript.Workbook)
{
  let worksheet = workbook.getActiveWorksheet();

  ... continue the rest of the code here ...
}
</code>```

Body:
I was able to do the below in VBA and need to transfer my script to Office Scripts in Excel 365. I can't figure out how to do the whole sheet and not just a string.

This is what I used in VBA:

Dim rng As Range
Set rng = Selection
For Each cell In rng
cell.Value = UCase(cell)
Next cell

Body:
This worked for me, could be a little cumbersome with a lot of cells but should still work.

function main(workbook: ExcelScript.Workbook, worksheetName: string)
{
  let worksheet = workbook.getWorksheet(worksheetName);

  // Ge tthe Used Range on the given worksheet and all values.
  let usedRange = worksheet.getUsedRange(false);
  var values = usedRange.getValues();

  // Now loop through each cell and upper case it.
  for (var row = 0; row < values.length; row++) {
    for (var col = 0; col < values[row].length; col++) {
      values[row][col] = values[row][col].toString().toUpperCase();
    }
  }

  usedRange.setValues(values);
}

Note:  There is a parameter to the function so it is expected to be used via PowerAutomate/LogicApps but if you don't want that then you should be able to change it up to use the active sheet with relative ease.

e.g. ...

function main(workbook: ExcelScript.Workbook)
{
  let worksheet = workbook.getActiveWorksheet();

  ... continue the rest of the code here ...
}


问:
matplolib string: how to use a special character AND use a variable
I'm trying to put both a special character and a variable into a string in a matplotlib plot.  a lot of great info here {https://matplotlib.org/stable/tutorials/text/mathtext.html} about special characters, but doesn't address using a variable in the string.

```<code>plt.plot(crossShoreC, -runningP, label=r'$\bar{P}_{%s}$'.format(win))
win='10'
plt.text(0, 1, f"$\bar{P}")  # works

plt.text(4, 0.5, r"$\bar{P}$") # works -- from example in link

plt.text(1, 0, f"$\bar{P}_{win}")  # doesn't work

plt.text(1, 0, r"$\bar{P}_{%s}".format(win))  #doesn't work

plt.text(1, 0, r"$\bar{P}_{0}".format(win))  # doesn't work
</code>```

this returns a NameError: name 'x' is not defined
I'd like the output to be a latex like solution where F_a=ma # where a has two dots over it and the _a is a subscript

答:
Edit: Thanks for clarifying your question, as suggested by @r-beginners, you can use expression % (<variable 1>, <variable 2>, ...) to format variable into string inside the format r"$<special characters>$", so in this case, you can do something like below

```<code>plt.text(1, 0, r"$F_{%s}=m\ddot{a} \beta$" % (x))
</code>```

Body:
I'm trying to put both a special character and a variable into a string in a matplotlib plot.  a lot of great info here {https://matplotlib.org/stable/tutorials/text/mathtext.html} about special characters, but doesn't address using a variable in the string.

plt.plot(crossShoreC, -runningP, label=r'$\bar{P}_{%s}$'.format(win))
win='10'
plt.text(0, 1, f"$\bar{P}")  # works

plt.text(4, 0.5, r"$\bar{P}$") # works -- from example in link

plt.text(1, 0, f"$\bar{P}_{win}")  # doesn't work

plt.text(1, 0, r"$\bar{P}_{%s}".format(win))  #doesn't work

plt.text(1, 0, r"$\bar{P}_{0}".format(win))  # doesn't work

this returns a NameError: name 'x' is not defined
I'd like the output to be a latex like solution where F_a=ma # where a has two dots over it and the _a is a subscript

Body:
Edit: Thanks for clarifying your question, as suggested by @r-beginners, you can use expression % (<variable 1>, <variable 2>, ...) to format variable into string inside the format r"$<special characters>$", so in this case, you can do something like below

plt.text(1, 0, r"$F_{%s}=m\ddot{a} \beta$" % (x))


问:
Is css translateZ not available in React? Unknown function 'translateZ'
I want to create a parallax effect for an image on my webpage built with react. At the moment, I am using javascript however this is not an ideal solution considering 3 lines of css can do the same thing. The problem is, I need to be able to use translateZ.

When I apply transform: translateZ(-10px); to my image, nothing happens, and IntelliJ gives me red squiggles saying Unknown function 'translateZ'. Everything else is set up correctly for sure, the image is inside a wrapper div with perspective: 10px; transform-style: preserve-3d;, and either way this would not affect whether the function translateZ itself is recognized. These CSS properties are in a dedicated CSS file and are being applied via className, in case that helps.

I cannot for the life of me find anything about this online, which to me seems to indicate that perhaps something is messed up locally? Because I don't understand why an entire CSS function would just be absent in react for no reason.

EDIT:
Forgot to mention, translate3d() also has the same issue, it is not recognized.

答: You can try translate3d(0, 0, VALUE)

Body: You can try translate3d(0, 0, VALUE)


问:
android pair command not found ( Wireless Debugging )
I am trying to connect to my phone wirelessly for USB Debugging using following :

adb pair 192.168.30.27:41424 .

But I am getting following error:

"Unknown command pair" error.

I have already updated Android SDK Platform tools to 31+ version, still this does not fix this issue.

答:
If you updated recently then even though the update is on your system, you might have an older version of the adb server running. So try:

adb kill-server

and then adb pair again. Found this here: ADB pair unknown command using r32 platform tools

For me, adb pair still didn't work but the "pair devices over wifi" option in Android Studio did, after running that kill-server command.


问:
how to pass variable from html to ajax/javascript
I have below HTML page which I land on after successful authentication. In its body, I get access_token value.

```<code><html>
<head>
    <title>Authorization successful</title>
</head>
<body>
    <p>Welcome. You are authorized to access the page.</p>
    <p>access_token: {{ access_token }}</p>
    <p>token_type:   {{ token_type }}</p>

    <form method="POST" action="/protected_hi" >
        <button type="submit" id="protectedApiButton">Protected API</button>
    </form>
    <script src="ajax.js"></script>
</body>
</html>
</code>```

The page has a button named "Protected API" on which ajax.js script it registers.
How can I get the access_token variable's value in my ajax.js script?

```<code>let protectedApiButton = document.getElementById('protectedApiButton');
protectedApiButton.addEventListener('click', buttonClickHandler)

function buttonClickHandler() {

    var myAttribute = <------------- how to assign access_token value from html template to here?
    console.log(myAttribute);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://dummy.restapiexample.com/api/v1/create', false);
    xhr.setRequestHeader('Content-type', 'application/json');

    xhr.onprogress = function(){
        console.log('On progress');
    }

    xhr.onload = function () {
        if(this.status === 200){

            console.log(this.responseText)
        }
        else{
            console.log("Some error occurred")
        }
    }
    params = `{"name":"ravi","age":"43"}`;
    xhr.send(params);
}
</code>```

答:
Add the input with the type of hidden to store the access token.

```<code><input type="hidden" id="access_token" value="token-goes-here" />
</code>```

Then retrieve the value from access_token in the buttonClickHandler():

```<code>function buttonClickHandler() {
  var myAttribute = document.getElementById('access_token').value;
  ...
}
</code>```

Body:
I have below HTML page which I land on after successful authentication. In its body, I get access_token value.

    <title>Authorization successful</title>

Welcome. You are authorized to access the page.

access_token: {{ access_token }}

token_type:   {{ token_type }}

    <form method="POST" action="/protected_hi" >
        <button type="submit" id="protectedApiButton">Protected API</button>
    </form>

The page has a button named "Protected API" on which ajax.js script it registers.
How can I get the access_token variable's value in my ajax.js script?

let protectedApiButton = document.getElementById('protectedApiButton');
protectedApiButton.addEventListener('click', buttonClickHandler)

function buttonClickHandler() {

    var myAttribute = <------------- how to assign access_token value from html template to here?
    console.log(myAttribute);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://dummy.restapiexample.com/api/v1/create', false);
    xhr.setRequestHeader('Content-type', 'application/json');

    xhr.onprogress = function(){
        console.log('On progress');
    }

    xhr.onload = function () {
        if(this.status === 200){

            console.log(this.responseText)
        }
        else{
            console.log("Some error occurred")
        }
    }
    params = `{"name":"ravi","age":"43"}`;
    xhr.send(params);
}

Body:
Add the input with the type of hidden to store the access token.

<input type="hidden" id="access_token" value="token-goes-here" />

Then retrieve the value from access_token in the buttonClickHandler():

function buttonClickHandler() {
  var myAttribute = document.getElementById('access_token').value;
  ...
}


问:
Jquery get to another page
I know that there is simple solution which i know but i couldn't remember now.

I want to use get method of jquery but not asynchronous or synchronous. I want to post whole page.
Below i go to 'myurladress'.

```<code>$('<a>').attr('href','myurladress').trigger('click');
/// :) i want to achieve same effect but shortly :))
</code>```

答:
I'm going to hazard a guess that you want to know how to redirect to another page using JavaScript, in which case you'd use window.location. For example:

```<code>window.location = 'http://www.example.com';
</code>```

Typically this is a bad idea, but there are a few niche cases where this can be useful. Especially when dealing with a different window handle (popouts etc.).

Title: Jquery get to another page

Body:
I know that there is simple solution which i know but i couldn't remember now.

I want to use get method of jquery but not asynchronous or synchronous. I want to post whole page.
Below i go to 'myurladress'.

$('').attr('href','myurladress').trigger('click');
/// :) i want to achieve same effect but shortly :))

Body:
I'm going to hazard a guess that you want to know how to redirect to another page using JavaScript, in which case you'd use window.location. For example:

window.location = 'http://www.example.com';

Typically this is a bad idea, but there are a few niche cases where this can be useful. Especially when dealing with a different window handle (popouts etc.).


问:
How do you reverse the direction of a ball if continuously going in one direction?

var velocity = 100;
var positionX = 0;
var ball = document.getElementById('ball');

function moveBall() {
  var Xmin = 0;
  var Xmax = 300;

  positionX = positionX + velocity;
  ball.style.left = positionX + 'px';
}

setInterval(moveBall, 100);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  position: absolute;
}</code>```

```

I have declared my global variables, followed by a function to move the ball, then followed by a setInterval. However, I can't seem to figure the right way to reverse the ball that continuously moves to the right of my screen until no longer visible. Is it a matter of a type of reverse method or setting up conditions?

答:
In the solution below the velocity variable is used to change the moving speed. The updateDirection() method is used to change the new direction information by checking the positionX value.

var ball = document.getElementById('ball');

/* This variable is used to change the movement speed. */
const velocity = 50;
/* This variable is used to change the amount of movement per unit time. */
const step = 10;
/* This variable stores the current or target position of the  element. */
var positionX = 0;
/* This variable stores the minimum position value. */
const xMin = 0;
/* This variable stores the maximum  position value. */
const xMax = 300;
/* true: right move, false: left move */
var direction = true;

/* This method is used to change the direction of movement. */
function updateDirection() {
  if(positionX == xMax)
    direction = false;
  else if(positionX == xMin)
    direction = true;
}

function moveBall() {
  updateDirection();

  if(direction)
    positionX += step;
  else
    positionX -= step;

  ball.style.left = `${positionX}px`;

  console.clear();
  console.log(`Direction: ${direction ? "right" : "left"} Position: ${positionX} `);
}

/* Update the velocity value to change the movement speed. */
setInterval(moveBall, velocity);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  position: absolute;
}</code>```

```

Body:
var velocity = 100;
var positionX = 0;
var ball = document.getElementById('ball');

function moveBall() {
  var Xmin = 0;
  var Xmax = 300;

  positionX = positionX + velocity;
  ball.style.left = positionX + 'px';
}

setInterval(moveBall, 100);

img {
  position: absolute;
}

I have declared my global variables, followed by a function to move the ball, then followed by a setInterval. However, I can't seem to figure the right way to reverse the ball that continuously moves to the right of my screen until no longer visible. Is it a matter of a type of reverse method or setting up conditions?

Body:
In the solution below the velocity variable is used to change the moving speed. The updateDirection() method is used to change the new direction information by checking the positionX value.

var ball = document.getElementById('ball');

/* This variable is used to change the movement speed. */
const velocity = 50;
/* This variable is used to change the amount of movement per unit time. */
const step = 10;
/* This variable stores the current or target position of the <img> element. */
var positionX = 0;
/* This variable stores the minimum position value. */
const xMin = 0;
/* This variable stores the maximum  position value. */
const xMax = 300;
/* true: right move, false: left move */
var direction = true;

/* This method is used to change the direction of movement. */
function updateDirection() {
  if(positionX == xMax)
    direction = false;
  else if(positionX == xMin)
    direction = true;
}

function moveBall() {
  updateDirection();

  if(direction)
    positionX += step;
  else
    positionX -= step;

  ball.style.left = `${positionX}px`;

  console.clear();
  console.log(`Direction: ${direction ? "right" : "left"} Position: ${positionX} `);
}

/* Update the velocity value to change the movement speed. */
setInterval(moveBall, velocity);

img {
  position: absolute;
}

<img id="ball" width="150" height="150" src="https://tr.seaicons.com/wp-content/uploads/2016/11/Volleyball-Ball-icon.png"/>


问:
Apps Script Google Calendar API Integration String Class Error
I'm super new to JavaScript, am a marketing executive by trade, but need to create a Google Calendar view from a Google Sheet for our content calendar for myself. After following some YT tutorials and finally running the code itself, I received the following error message:

Exception: The parameters (String,String,(class)) don't match the method signature for CalendarApp.Calendar.createAllDayEvent.

The following is my code:

```<code>function addEvents(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var cal = CalendarApp.getCalendarById("CalendarID");

  var data = ss.getRange("A3:C" + lr).getValues();

  for(var i = 0; i<data.length; i++){
    cal.createAllDayEvent(data[i][1], data[i][0], {description: data[i][2]});

  }

}
</code>```

In my Google Spreadsheet, the order of the data is as follows (data only appears in A3:C3 and downwards to the bottom rows): column A: Date, B: Event Title, C: Description

Hope to get some help, would appreciate it :'D

答:
I just tested your script and I noticed that after changing the date column information to String format it returned the specified error. I changed it back to Date format in the Sheet and it created the events as expected.

Make sure your dates are in the proper format in your Sheet and then try again. After that it should run just fine.

For reference the expected parameters type are specified here

Body:
I'm super new to JavaScript, am a marketing executive by trade, but need to create a Google Calendar view from a Google Sheet for our content calendar for myself. After following some YT tutorials and finally running the code itself, I received the following error message:

Exception: The parameters (String,String,(class)) don't match the method signature for CalendarApp.Calendar.createAllDayEvent.

The following is my code:

function addEvents(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var cal = CalendarApp.getCalendarById("CalendarID");

  var data = ss.getRange("A3:C" + lr).getValues();

  for(var i = 0; i<data.length; i++){
    cal.createAllDayEvent(data[i][1], data[i][0], {description: data[i][2]});

  }

}

In my Google Spreadsheet, the order of the data is as follows (data only appears in A3:C3 and downwards to the bottom rows): column A: Date, B: Event Title, C: Description

Hope to get some help, would appreciate it :'D


问:
No module named 'absl' error when I import tensorflow
I have anaconda installed on my Win 7 machine with a GTX1070.

I have been trying to install tensorflow gpu version for the past hour with no luck. I followed the tutorials on the tensorflow website to no success. They ask for you to install CUDA 8.0 and Cudll 6.0 which I do. I then add the location of cudnn64_6.dll, cudart64_80.dll and the libnvvp folder to my path variables. I then set up a virtual environment in conda and run the following command:

```<code>(tensorflow)C:> pip install --ignore-installed --upgrade tensorflow-gpu
</code>```

I believe when I do this, it installs tensorflow 1.5 which seems to require CUDA tools 9.0 because I get an error saying that cudart64_80.dll cannot be found. So I update my CUDA tools to 9.0 and download the corresponding Cuda library. I then change my path variables. Now I dont get any missing dll errors however, I am now faced with the following error

```<code>ModuleNotFoundError: No module named 'absl'
</code>```

Does anyone have any suggestions as to what I can do from here on?

答:
I got the No module named absl error when I tried to install tf-nightly 2.9.0.dev20220203 on my Ubuntu 20.04.3 machine.

Reinstalling absl-py did not directly worked.
While reinstalling absl, I got this error: ERROR: tf-nightly 2.9.0.dev20220203 has requirement gast<=0.4.0,>=0.2.1, but you'll have gast 0.5.3 which is incompatible.

So I uninstalled absl-py:

pip uninstall absl-py

Then downgraded gast:

pip uninstall gast

pip install gast==0.4.0

Finally,
pip install absl-py

Body:
I have anaconda installed on my Win 7 machine with a GTX1070.

I have been trying to install tensorflow gpu version for the past hour with no luck. I followed the tutorials on the tensorflow website to no success. They ask for you to install CUDA 8.0 and Cudll 6.0 which I do. I then add the location of cudnn64_6.dll, cudart64_80.dll and the libnvvp folder to my path variables. I then set up a virtual environment in conda and run the following command:

(tensorflow)C:> pip install --ignore-installed --upgrade tensorflow-gpu

I believe when I do this, it installs tensorflow 1.5 which seems to require CUDA tools 9.0 because I get an error saying that cudart64_80.dll cannot be found. So I update my CUDA tools to 9.0 and download the corresponding Cuda library. I then change my path variables. Now I dont get any missing dll errors however, I am now faced with the following error

ModuleNotFoundError: No module named 'absl'

Does anyone have any suggestions as to what I can do from here on?


问:
List ALL Files on iPhone
in Objective C how would I get a list of ALL files on the iPhone?

is this even possible or can I only get files from a certain directory or known path?

答:
No you can just get files within your sandbox. And to display your current directory use the following code : </p>

```<code>- (NSString *) returnFilePath {
    NSArray *pathArray =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    return [pathArray objectAtIndex:0];
}
</code>```

Title: List ALL Files on iPhone

Body:
No you can just get files within your sandbox. And to display your current directory use the following code :

- (NSString *) returnFilePath {
    NSArray *pathArray =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    return [pathArray objectAtIndex:0];
}


问:
Enable Partial Compilation in IntelliJ IDEA
How do I enable partial compiles in IntelliJ?

The same feature in NetBeans where by one can run a main method in a class without having non-dependecies in the same project be required to also compile.

EDIT:

After performing what CrazyCoder suggested, with some success, now I get ClassNotFoundException when trying to run a file not associated with those that were not compiling.  After fixing the non-compiling files, it runs just fine.

I actually made in error in the same non-compiling file to test and it still works.

Could it be a bug?

EDIT:

Followed instructions still not working.

答:
Step 1: Setting as follow:

Step2: Build Project Automatically

Step 3: Modify Run configuration

Step 4: close all app console-view tabs in Run View, then run app again Ctrl+Shift+F10


问:
How to reach outside of a div in an HTMLDivElement object with Javascript
I have several HTML elements that represent tiles to be flipped on click. Each element has a container div, which holds two divs, one for the front and back of the tile.

```<code><div class="flip-container" data-tile>
    <div class="flipper">
      <div class="front white">
        <!-- front content -->
      </div>
      <div class="back blue">
        <!-- back content -->
      </div>
    </div>
  </div>
</code>```

I have the animation worked out in CSS so the tiles "flip" on hover. So far so good. Now I am trying to change the classList of the "flip-container" on click, so that a different className will be called from my style sheet.

My problem is that my handleClick function is targeting only the inner-div "back-blue", and not the "flip-container" that is holding both divs.

```<code>const tileData = document.querySelectorAll('[data-tile]')
const flipContainers = Array.from(
  document.getElementsByClassName('flip-container')
)

flipContainers.forEach((container) => {
  container.addEventListener('click', handleClick, { once: true })
})

function handleClick(e) {
  console.log('clicked')
  const container = e.target
  const currentClassColor = 'blue'
  fixColor(container, currentClassColor)
}

function fixColor(container, currentClassColor) {
  container.classList.add(currentClass)
}
</code>```

I have tried querying the "flip-container" both by selecting the data tag and also by grabbing an array from the specific className. In both cases, the entire element is still grabbed, and the target of the click applies only to the inner div. I guess it makes sense why this happening, but is there a way I can access the container even if the click target is one of the inner divs?

答:
What you want is probably e.currentTarget.

The currentTarget read-only property of the Event interface identifies
the current target for the event, as the event traverses the DOM. It
always refers to the element to which the event handler has been
attached, as opposed to Event.target, which identifies the element on
which the event occurred and which may be its descendant.

https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

If that doesn't work for your case, you will want to try e.currentTarget.parentNode

Body:
I have several HTML elements that represent tiles to be flipped on click. Each element has a container div, which holds two divs, one for the front and back of the tile.

I have the animation worked out in CSS so the tiles "flip" on hover. So far so good. Now I am trying to change the classList of the "flip-container" on click, so that a different className will be called from my style sheet.

My problem is that my handleClick function is targeting only the inner-div "back-blue", and not the "flip-container" that is holding both divs.

const tileData = document.querySelectorAll('[data-tile]')
const flipContainers = Array.from(
  document.getElementsByClassName('flip-container')
)

flipContainers.forEach((container) => {
  container.addEventListener('click', handleClick, { once: true })
})

function handleClick(e) {
  console.log('clicked')
  const container = e.target
  const currentClassColor = 'blue'
  fixColor(container, currentClassColor)
}

function fixColor(container, currentClassColor) {
  container.classList.add(currentClass)
}

I have tried querying the "flip-container" both by selecting the data tag and also by grabbing an array from the specific className. In both cases, the entire element is still grabbed, and the target of the click applies only to the inner div. I guess it makes sense why this happening, but is there a way I can access the container even if the click target is one of the inner divs?


问:
If there is no mutual exclusion then how volatile ensures happens-before relationship?
I read over here that volatile doesn't entail mutual exclusion locking, then how volatile ensures happens-before relationship or how volatile ensures that other thread reads updated value?

Please note that I have read this and this but it doesn't answer my question which is specifically about volatile and these answers in these questions really doesn't explain the point I am curious about.

答:
I'll hope to provide some insights in how a lock and volatile variable fit into the happens-before relation.

Imagine the following program with plain loads/stores

```<code>int a=0
int b=0

CPU1:
    a=1 (1)
    b=1 (2)

CPU2:
    while(b==0); (3)
    print(a) (4)
</code>```

When b==1, is a guaranteed to be 1? No, because there is no happens-before edge between the write and read of a; they are in a data race. If you are lucky, a==1 is seen, but there is no guarantee.

Let's make b volatile and see what happens:

```<code>int a=0
volatile int b=0

CPU1:
    a=1 (1)
    b=1 (2)

CPU2:
    while(b==0); (3)
    print(a) (4)
</code>```

If a volatile read of b sees 1 (3) then there is a happens-before edge between the write (2) and the read (3). This is because a volatile write synchronizes with its subsequent read, and hence they are ordered in the 'synchronizes-with' order and hence in the happens-before order.

We also have a happens-before edge between the (1) and (2) due to program order. And we have a happens-before edge between (3) and (4). Because happens before is transitive, we have a happens-before edge between (1) and (4). And hence there is no data race. So this means that when 'b==1' that 'a==1' as well.

Check the following explanation on how this translates to loads/stores on the CPU in combination with fences.

And now for the monitor:

```<code>int a=0
lock = new Object();
int b=0

CPU1:
    a=1 (1)
    lock(monitor) (2)
    b=1 (3)
    unlock(monitor); (4)
CPU2:
    done=false
    while(!done){
       lock(monitor); (5)
       if(b==1) done=true; (6)
       unlock(monitor); (7)
    }
    print(a) (8)
</code>```

When the unlock (4) synchronizes with a lock (5), then there is a happens-before edge. Synchronizes in this case means that they are ordered in the synchronizes-with order and hence they are part of the happens-before order.

And this means that there is a happens-before edge between (1) and (8) due to a sequence of program order rule edges and a single monitor lock rule edge between (4) and (5).

It is up to the JVM to ensure that the happens-before model is implemented correctly.

Some specific notes:

You will frequently hear that volatile causes a load or store to go through main memory. This is a fallacy; it isn't how modern CPUs work. Caches are always coherent. They typically make use of some MESI-based cache coherence protocol. So what typically happens is that when a write is made to a cache line, the cache line is first invalidated on all other CPUs. Once it has been invalidated, the CPU can apply the write to the cache line. CPUs typically use store-buffer to prevent the CPU from stalling waiting on that cache line. And this is also one of the causes why loads/stores can be reordered (so we get a violation of consistency).

The JMM is an axiomatic model and not an operational model. The focus of an axiomatic model is to tell which executions are allowed and which ones are forbidden. In the JMM this is done using the happens-before order (and the causal order). On purpose, it isn't expressed in terms of caches, store buffers, out-of-order execution, speculative execution, etc. It can be stress relieving to think in terms of fences, but it is a flawed model.

A lock can be implemented using volatiles only. E.g. Dekkers algorithm or Petersons algorithm. Not that anyone will do that on modern CPUs, but in theory, it is allowed. And when done using volatile, they will provide a happens-before edge. The point is, for the JMM it isn't relevant how a lock is implemented. Contended locks are typically implemented using some CAS operation. If threads need to be suspended or notified, interaction with the OS scheduler is needed as well.

Please have a look at the following orders:

synchronization order

synchronizes with order

program order

happens-before (order)

They are key to understanding the JMM.

Body:
I'll hope to provide some insights in how a lock and volatile variable fit into the happens-before relation.

Imagine the following program with plain loads/stores

int a=0
int b=0

CPU1:
    a=1 (1)
    b=1 (2)

CPU2:
    while(b==0); (3)
    print(a) (4)

When b==1, is a guaranteed to be 1? No, because there is no happens-before edge between the write and read of a; they are in a data race. If you are lucky, a==1 is seen, but there is no guarantee.

Let's make b volatile and see what happens:

int a=0
volatile int b=0

CPU1:
    a=1 (1)
    b=1 (2)

CPU2:
    while(b==0); (3)
    print(a) (4)

If a volatile read of b sees 1 (3) then there is a happens-before edge between the write (2) and the read (3). This is because a volatile write synchronizes with its subsequent read, and hence they are ordered in the 'synchronizes-with' order and hence in the happens-before order.

We also have a happens-before edge between the (1) and (2) due to program order. And we have a happens-before edge between (3) and (4). Because happens before is transitive, we have a happens-before edge between (1) and (4). And hence there is no data race. So this means that when 'b==1' that 'a==1' as well.

Check the following explanation on how this translates to loads/stores on the CPU in combination with fences.

And now for the monitor:

int a=0
lock = new Object();
int b=0

CPU1:
    a=1 (1)
    lock(monitor) (2)
    b=1 (3)
    unlock(monitor); (4)
CPU2:
    done=false
    while(!done){
       lock(monitor); (5)
       if(b==1) done=true; (6)
       unlock(monitor); (7)
    }
    print(a) (8)

When the unlock (4) synchronizes with a lock (5), then there is a happens-before edge. Synchronizes in this case means that they are ordered in the synchronizes-with order and hence they are part of the happens-before order.

And this means that there is a happens-before edge between (1) and (8) due to a sequence of program order rule edges and a single monitor lock rule edge between (4) and (5).

It is up to the JVM to ensure that the happens-before model is implemented correctly.

Some specific notes:

You will frequently hear that volatile causes a load or store to go through main memory. This is a fallacy; it isn't how modern CPUs work. Caches are always coherent. They typically make use of some MESI-based cache coherence protocol. So what typically happens is that when a write is made to a cache line, the cache line is first invalidated on all other CPUs. Once it has been invalidated, the CPU can apply the write to the cache line. CPUs typically use store-buffer to prevent the CPU from stalling waiting on that cache line. And this is also one of the causes why loads/stores can be reordered (so we get a violation of consistency).

The JMM is an axiomatic model and not an operational model. The focus of an axiomatic model is to tell which executions are allowed and which ones are forbidden. In the JMM this is done using the happens-before order (and the causal order). On purpose, it isn't expressed in terms of caches, store buffers, out-of-order execution, speculative execution, etc. It can be stress relieving to think in terms of fences, but it is a flawed model.

A lock can be implemented using volatiles only. E.g. Dekkers algorithm or Petersons algorithm. Not that anyone will do that on modern CPUs, but in theory, it is allowed. And when done using volatile, they will provide a happens-before edge. The point is, for the JMM it isn't relevant how a lock is implemented. Contended locks are typically implemented using some CAS operation. If threads need to be suspended or notified, interaction with the OS scheduler is needed as well.

Please have a look at the following orders:

synchronization order

synchronizes with order

program order

happens-before (order)

They are key to understanding the JMM.