问:
Rails 4, how to correctly configure smtp settings (gmail)
I am trying to create a contact form in Rails 4. I did some digging around here and was able to get most of the stuff to work. (followed @sethfri's work here Contact Form Mailer in Rails 4)

Right now I am able to fill out my form box and hit send. In my rails server it says the mail was outbound to my email address, but I don't receive anything in my gmail box, so I think my smtp settings aren't right. My smtp settings are:

...config/environments/development.rb

```<code>config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_deliveries = true

  config.action_mailer.default_url_options = { :host => 'localhost:3000' }

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address => "smtp.gmail.com",
    :port => "587",
    :domain => "mydomain.net",
    :user_name => "mygmailusername@gmail.com",
    :password => "myGmailPassword",
    :authentication => "plain",
    :enable_starttls_auto => true
  }
</code>```

Also I added in
.../config/initializers/smtp_settings.rb

```<code>ActionMailer::Base.smtp_settings = {
    :address => "smtp.gmail.com",
    :port => "587",
    :domain => "mydomain.net",
    :user_name => "gmailuser@gmail.com",
    :password => "gmailPassword",
    :authentication => "plain",
    :enable_starttls_auto => true
}
</code>```

What am I missing/doing wrong? I've played around with a couple things (changed default_url to port 1025, changed :port => "587" to :port => 587) with no success.

Thanks for the help!

答:
2020, Rails 6 updated answer:</p>

```<code>  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_caching = false
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    authentication: "plain",
    enable_starttls_auto: true,
    user_name: "blabla@gmail.com",
    password: "blabla",
    domain: "smtp.gmail.com",
    openssl_verify_mode: "none",
  }
</code>```

Body:
I am trying to create a contact form in Rails 4. I did some digging around here and was able to get most of the stuff to work. (followed @sethfri's work here Contact Form Mailer in Rails 4)

Right now I am able to fill out my form box and hit send. In my rails server it says the mail was outbound to my email address, but I don't receive anything in my gmail box, so I think my smtp settings aren't right. My smtp settings are:

...config/environments/development.rb

config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_deliveries = true

  config.action_mailer.default_url_options = { :host => 'localhost:3000' }

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address => "smtp.gmail.com",
    :port => "587",
    :domain => "mydomain.net",
    :user_name => "mygmailusername@gmail.com",
    :password => "myGmailPassword",
    :authentication => "plain",
    :enable_starttls_auto => true
  }

Also I added in
.../config/initializers/smtp_settings.rb

ActionMailer::Base.smtp_settings = {
    :address => "smtp.gmail.com",
    :port => "587",
    :domain => "mydomain.net",
    :user_name => "gmailuser@gmail.com",
    :password => "gmailPassword",
    :authentication => "plain",
    :enable_starttls_auto => true
}

What am I missing/doing wrong? I've played around with a couple things (changed default_url to port 1025, changed :port => "587" to :port => 587) with no success.

Thanks for the help!

Body:
2020, Rails 6 updated answer:

  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_caching = false
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    authentication: "plain",
    enable_starttls_auto: true,
    user_name: "blabla@gmail.com",
    password: "blabla",
    domain: "smtp.gmail.com",
    openssl_verify_mode: "none",
  }


来源: stackexchange

问:
Find invalid numbers - Oracle SQL
I have a table:

table1

```<code>column_name    value
Test1          80933Y355220
Test1          8093363X5220
Test1          809336355220
Test1          80.98
Test1          -80.98

Test2          1234
Test2          abc
Test2          12-23-09
</code>```

I need to identify all the invalid number values present in the column value

Output should be:

```<code>column_name    value
Test1          80933Y355220
Test1          8093363X5220

Test2          abc
Test2          12-23-09
</code>```

Is there a way to get this list?

答:
I would use regexp_like() with this pattern:

```<code>SELECT column_name, value
FROM table1
WHERE  NOT REGEXP_LIKE(value, '^[-]?[0-9]*[.]?[0-9]*$')
</code>```

ContentLicense: CC BY-SA 4.0

Title: Find invalid numbers - Oracle SQL

Body:
I have a table:

table1

column_name    value
Test1          80933Y355220
Test1          8093363X5220
Test1          809336355220
Test1          80.98
Test1          -80.98

Test2          1234
Test2          abc
Test2          12-23-09

I need to identify all the invalid number values present in the column value

Output should be:

column_name    value
Test1          80933Y355220
Test1          8093363X5220

Test2          abc
Test2          12-23-09

Is there a way to get this list?

Body:
I would use regexp_like() with this pattern:

SELECT column_name, value
FROM table1
WHERE  NOT REGEXP_LIKE(value, '^[-]?[0-9]*[.]?[0-9]*$')


问:
Changing "src" attribute of an image to another image file?
This portion of my assignment is instructing me to change the src attribute of a collection of star images to another image file.

I've tried numerous combinations of removeAttribute() and setAttribute(), but no luck.  I'm probably thinking down the wrong path here.

```<code>function lightStars () {
   var starNumber = e.target.alt;
   var stars = document.querySelectorAll("span#stars img");
for (var i = 0; i < starNumber; i++) {
   stars.setAttribute("src", "bw_star2.png");
}
}
</code>```

HTML Code:

```<code><label id="ratingLabel" for="rating">Rate this title
           <span id="stars">
           <img src="bw_star.png" alt="1" />
           <img src="bw_star.png" alt="2" />
           <img src="bw_star.png" alt="3" />
           <img src="bw_star.png" alt="4" />
           <img src="bw_star.png" alt="5" /></span>
           <input type="text" name="rating" id="rating" readonly value="" />
</label>
</code>```

The purpose of this function is to color a star when the user moves the mouse pointer over a star image in order to reflect the user’s rating of the book.

I hope I explained this properly.

答:
If I'm understanding your code correctly, I think you just missed to access to each stars array position:</p>

```<code>function lightStars () {
    var starNumber = e.target.alt;
    var stars = document.querySelectorAll("span#stars img");
    for (var i = 0; i < starNumber; i++) {
        stars[i].setAttribute("src", "bw_star2.png");
    }
}
</code>```

Body:
This portion of my assignment is instructing me to change the src attribute of a collection of star images to another image file.

I've tried numerous combinations of removeAttribute() and setAttribute(), but no luck.  I'm probably thinking down the wrong path here.

function lightStars () {
   var starNumber = e.target.alt;
   var stars = document.querySelectorAll("span#stars img");
for (var i = 0; i < starNumber; i++) {
   stars.setAttribute("src", "bw_star2.png");
}
}

HTML Code:

Rate this title

           <input type="text" name="rating" id="rating" readonly value="" />

The purpose of this function is to color a star when the user moves the mouse pointer over a star image in order to reflect the user’s rating of the book.

I hope I explained this properly.

Body:
If I'm understanding your code correctly, I think you just missed to access to each stars array position:

function lightStars () {
    var starNumber = e.target.alt;
    var stars = document.querySelectorAll("span#stars img");
    for (var i = 0; i < starNumber; i++) {
        stars[i].setAttribute("src", "bw_star2.png");
    }
}


问:
GeoGebra Simulations -- output to file
Given some composition of objects, I would like to modify some input parameters and see how the output changes. The relation of input and resulting output parameters shall be written to a file.

EXAMPLE: Area of rectangle depending on position of point A.

```<code>       A *-----------------.
         |                 |
         |                 |
         |                 |
         '-----------------* B
</code>```

Point A is determined by its x and y coordinates. The edges of the rectangle are aligned with the edges of the coordinate system. Together with another point B, A spans the rectangle. The resulting rectangle has an area 'F'. Now, I would like to do something like the following

```<code>for x in range(0,5)
    for y in range(0,5)
        A = (x,y)
        # Assume GeoGebra does all the adaptations.
        myFile.write(x, y, F.area)
</code>```

答:
You can get the areas into a sequence:

Join(Sequence(Sequence({i,j,Polygon(B,(i,y(B)),(i,j),(x(B),j))},i,0,5),j,0,5))

but there is no way to pro programmatically save it into a file. You can use CopyFreeObject to convert it into a free object and copy the new matrix to a text editor of your choosing.

Maybe using GeoGebra's spreadsheet instead of sequence could make the copying easier.

Title: GeoGebra Simulations -- output to file

Body:
Given some composition of objects, I would like to modify some input parameters and see how the output changes. The relation of input and resulting output parameters shall be written to a file.

EXAMPLE: Area of rectangle depending on position of point A.

       A *-----------------.
         |                 |
         |                 |
         |                 |
         '-----------------* B

Point A is determined by its x and y coordinates. The edges of the rectangle are aligned with the edges of the coordinate system. Together with another point B, A spans the rectangle. The resulting rectangle has an area 'F'. Now, I would like to do something like the following

for x in range(0,5)
    for y in range(0,5)
        A = (x,y)
        # Assume GeoGebra does all the adaptations.
        myFile.write(x, y, F.area)


答:
```<code>function lightStars () {
   var starNumber = parseint(e.target.alt);
   var stars = document.querySelectorAll("span#stars img");
   for (var i = 0; i < starNumber; i++) {
       stars.setAttribute("src", "bw_star2.png");
   }
}
</code>```

Title: Changing "src" attribute of an image to another image file?


问:
React passing new props
So I update my state in a component and then pass the new props into the child but the child isn't updating correctly and the defaultValue of the input is not changing. At first I thought it might be because I am using this.props so begun using this.states and applying the new props there first but doesn't seem to be working.

Parent Component

```<code>this.state.newDetails == null ? '' :
    <NewDetailsView details={this.state.newDetails} />
</code>```

Child component:

```<code>import React, { Component } from 'react';

class NewDetailsView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      details: (this.props.details!= null) ? this.props.details: null
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ details: nextProps });
    this.forceUpdate();
  }

  render() {
    return (
      <div>
        <input type="text" defaultValue={this.state.details.id} />
      </div>
    );
  }
}

export default NewDetailsView ;
</code>```

Solution Code:

Pending...

答: Use getDerivedStateFromProps instead of using deprecated componentWillReceiveProps. An example of it can be found here

ContentLicense: CC BY-SA 3.0

Title: React passing new props

Body:
So I update my state in a component and then pass the new props into the child but the child isn't updating correctly and the defaultValue of the input is not changing. At first I thought it might be because I am using this.props so begun using this.states and applying the new props there first but doesn't seem to be working.

Parent Component

this.state.newDetails == null ? '' :
    <NewDetailsView details={this.state.newDetails} />

Child component:

import React, { Component } from 'react';

class NewDetailsView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      details: (this.props.details!= null) ? this.props.details: null
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ details: nextProps });
    this.forceUpdate();
  }

  render() {
    return (

        <input type="text" defaultValue={this.state.details.id} />

    );
  }
}

export default NewDetailsView ;

Solution Code:

Pending...


问:
Get record from particular department which is satisfying the condition?
```<code>create table tab1 (dep varchar2(10), val number);

begin
  insert into tab1 values ('a',10)
  insert into tab1 values ('a',20)
  insert into tab1 values ('a',30)
  insert into tab1 values ('b',10)
  insert into tab1 values ('b',20)
  insert into tab1 values ('c',10)
end;
</code>```

i need DEP and value matched only with 10,20,30

output:

```<code>DEP VAL
--- ---
a   10
a   20
a   30
</code>```

答:
If you want the departments with val having valid values 10 and 20 and 30 and no other value, then:

```<code>select dep
from tab1
group by dep
having
  count(distinct val) = 3
  and
  sum(case when val not in (10, 20, 30) then 1 else 0 end) = 0
</code>```

See the demo.

Body:
create table tab1 (dep varchar2(10), val number);

begin
  insert into tab1 values ('a',10)
  insert into tab1 values ('a',20)
  insert into tab1 values ('a',30)
  insert into tab1 values ('b',10)
  insert into tab1 values ('b',20)
  insert into tab1 values ('c',10)
end;

i need DEP and value matched only with 10,20,30

output:

DEP VAL
--- ---
a   10
a   20
a   30

Body:
If you want the departments with val having valid values 10 and 20 and 30 and no other value, then:

select dep
from tab1
group by dep
having
  count(distinct val) = 3
  and
  sum(case when val not in (10, 20, 30) then 1 else 0 end) = 0

See the demo.


问:
Create a URI pattern matcher to allow/disallow for decoding JWT
I am new to Spring Boot and Spring Security, and I am building a RESTful API service for allowing the user to sign-up, sign-in, and do other stuff on the application.

I am using JWT for claims verifications and I will be passing the token each time my user uses APIs other than sign-in and sign-up. Therefore I would to allow access to these APIs without passing in the JWT, but for the rest, I want to reject the request outright if the JWT isn't passed.

I have only one controller which is the UserController and it maps to the path /api/user. It would service for the below APIs -

/sign-up. This is a POST method. I want it to allow access to it without requiring JWT to be passed.

/verify/{verificationCode} This is a GET method. I want it to be allowed access to it without requiring JWT to be passed.

/set-password/ This is a POST method, and would return a JWT.

/set-profile. This is a PUT method and will use the JWT.

I tried some examples on configuring the WebSecurity and HttpSecurity by using antMatchers and I also configured a GenericFilterBean.

I don't know the correct approach to and help would be very much appreciated. I am using version 2.1.3.RELEASE of Spring.

答:
You could configure the security per URL by configuring  HttpSecurity :

```<code>@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //Ignore other configuration stuff for simplicity
        http.authorizeRequests()
                .antMatchers("/sign-up" ,"/verify/**" ).permitAll()
                .anyRequest().authenticated()
    }

}
</code>```

Then all requests to URL except /sign-up and /verify/** requires authentication (which means JWT in you case).

You can even do the following if you want to further control /sign-up and /verify/** can only be accessed without authentication for the correct HTTP methods only:

```<code>http.authorizeRequests()
  .antMatchers(HttpMethod.POST, "/sign-up").permitAll()
  .antMatchers(HttpMethod.GET, "/verify/**").permitAll()
  .anyRequest().authenticated()
</code>```

Body:
You could configure the security per URL by configuring  HttpSecurity :

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //Ignore other configuration stuff for simplicity
        http.authorizeRequests()
                .antMatchers("/sign-up" ,"/verify/**" ).permitAll()
                .anyRequest().authenticated()
    }

}

Then all requests to URL except /sign-up and /verify/** requires authentication (which means JWT in you case).

You can even do the following if you want to further control /sign-up and /verify/** can only be accessed without authentication for the correct HTTP methods only:

http.authorizeRequests()
  .antMatchers(HttpMethod.POST, "/sign-up").permitAll()
  .antMatchers(HttpMethod.GET, "/verify/**").permitAll()
  .anyRequest().authenticated()


问:
How to provide selective access for lambda execution to a federated user in AWS IAM policy?
I am trying to give lambda execution access to select members within a group. Users are authenticated via PingFederate. I am having issue granting this selective access to federated user.

I have a custom IAM policy (allow-lambda-invocation-selective) attached to this role. Although the policy seems to pass validation and policy simulation shows access is allowed, when I try to execute the lambda function I get message

```<code>Calling the invoke API action failed with this message: User:arn:aws:sts::123456789012:assumed-role/role-for-grp-l2/myuser1234 is not authorized to perform: lambda:InvokeFunction on resource: arn:aws:lambda:us-east-1:123456789012:function:my-lambda-function
</code>```

Here is my policy: allow-lambda-invocation-selective

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction",
                "lambda:InvokeAsync",
                "lambda:ListVersionsByFunction",
                "lambda:GetFunction",
                "lambda:ListAliases"
            ],
            "Resource": "arn:aws:lambda:*:123456789012:function:my-lambda-function",
            "Condition": {
                "StringEquals": {
                    "aws:userid": "arn:aws:sts::123456789012:assumed-role/role-for-grp-l2/myuser1234"
                }
            }
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "lambda:ListFunctions",
                "lambda:ListEventSourceMappings",
                "lambda:ListLayers",
                "lambda:ListLayerVersions"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "aws:userid": "arn:aws:sts::123456789012:assumed-role/role-for-grp-l2/myuser1234"
                }
            }
        }
    ]
}
</code>```

Am i missing something?

答:
I'm trying to understand your problem. Correct me if I made a wrong supposition.

Every group/user already have its own role.

When you authenticate your users, they have their assumed role. myuser1234, when authenticated, will receive arn:aws:sts::123456789012:assumed-role/role-for-grp-l2/myuser1234 role, right? Is it possible to create one role for each group and remove the conditions property (check item 2 explaining why)?

```<code>// role-for-grp-l2
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction",
                "lambda:InvokeAsync",
                "lambda:ListVersionsByFunction",
                "lambda:GetFunction",
                "lambda:ListAliases"
            ],
            "Resource": "arn:aws:lambda:*:123456789012:function:my-lambda-function"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "lambda:ListFunctions",
                "lambda:ListEventSourceMappings",
                "lambda:ListLayers",
                "lambda:ListLayerVersions"
            ],
            "Resource": "*"
        }
    ]
}
</code>```

The problem with aws:userid

Reading the docs about the key aws:userid we can find this key has the value given by role id:caller-specified-role-name,

where role id is the unique id of the role and the caller-specified-role-name is specified by the RoleSessionName parameter passed to the AssumeRole request.

So aws:userid has value like AIDAJQABLZS4A3QDU576Q:SomeNameYouGive. Because this, your condition never match arn:aws:sts::123456789012:assumed-role/role-for-grp-l2/myuser1234 and then user cannot assume that actions.

Using conditions another way

Assuming RoleSessionName is the user name, you can use conditions this way:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction",
                "lambda:InvokeAsync",
                "lambda:ListVersionsByFunction",
                "lambda:GetFunction",
                "lambda:ListAliases"
            ],
            "Resource": "arn:aws:lambda:*:123456789012:function:my-lambda-function",
            "Condition": {
                "StringLike": {
                    "aws:userid": "*:myuser1234"
                }
            }
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "lambda:ListFunctions",
                "lambda:ListEventSourceMappings",
                "lambda:ListLayers",
                "lambda:ListLayerVersions"
            ],
            "Resource": "*",
            "Condition": {
                "StringLike": {
                    "aws:userid": "*:myuser1234"
                }
            }
        }
    ]
}
</code>```

if you prefer, you may remove * wildcard getting role id using AWS CLI with the command:

```<code>aws iam get-role --role-name ROLE_NAME
</code>```

and changing condition as follows:

```<code>"Condition": {
   "StringEquals": {
       "aws:userid": "ROLE_ID:myuser1234"
   }
}

</code>```

Body:
I am trying to give lambda execution access to select members within a group. Users are authenticated via PingFederate. I am having issue granting this selective access to federated user.

I have a custom IAM policy (allow-lambda-invocation-selective) attached to this role. Although the policy seems to pass validation and policy simulation shows access is allowed, when I try to execute the lambda function I get message

Calling the invoke API action failed with this message: User:arn:aws:sts::123456789012:assumed-role/role-for-grp-l2/myuser1234 is not authorized to perform: lambda:InvokeFunction on resource: arn:aws:lambda:us-east-1:123456789012:function:my-lambda-function

Here is my policy: allow-lambda-invocation-selective

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction",
                "lambda:InvokeAsync",
                "lambda:ListVersionsByFunction",
                "lambda:GetFunction",
                "lambda:ListAliases"
            ],
            "Resource": "arn:aws:lambda:*:123456789012:function:my-lambda-function",
            "Condition": {
                "StringEquals": {
                    "aws:userid": "arn:aws:sts::123456789012:assumed-role/role-for-grp-l2/myuser1234"
                }
            }
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "lambda:ListFunctions",
                "lambda:ListEventSourceMappings",
                "lambda:ListLayers",
                "lambda:ListLayerVersions"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "aws:userid": "arn:aws:sts::123456789012:assumed-role/role-for-grp-l2/myuser1234"
                }
            }
        }
    ]
}

Am i missing something?

Body:
I'm trying to understand your problem. Correct me if I made a wrong supposition.

Every group/user already have its own role.

When you authenticate your users, they have their assumed role. myuser1234, when authenticated, will receive arn:aws:sts::123456789012:assumed-role/role-for-grp-l2/myuser1234 role, right? Is it possible to create one role for each group and remove the conditions property (check item 2 explaining why)?

// role-for-grp-l2
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction",
                "lambda:InvokeAsync",
                "lambda:ListVersionsByFunction",
                "lambda:GetFunction",
                "lambda:ListAliases"
            ],
            "Resource": "arn:aws:lambda:*:123456789012:function:my-lambda-function"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "lambda:ListFunctions",
                "lambda:ListEventSourceMappings",
                "lambda:ListLayers",
                "lambda:ListLayerVersions"
            ],
            "Resource": "*"
        }
    ]
}

The problem with aws:userid

Reading the docs about the key aws:userid we can find this key has the value given by role id:caller-specified-role-name,

where role id is the unique id of the role and the caller-specified-role-name is specified by the RoleSessionName parameter passed to the AssumeRole request.

So aws:userid has value like AIDAJQABLZS4A3QDU576Q:SomeNameYouGive. Because this, your condition never match arn:aws:sts::123456789012:assumed-role/role-for-grp-l2/myuser1234 and then user cannot assume that actions.

Using conditions another way

Assuming RoleSessionName is the user name, you can use conditions this way:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction",
                "lambda:InvokeAsync",
                "lambda:ListVersionsByFunction",
                "lambda:GetFunction",
                "lambda:ListAliases"
            ],
            "Resource": "arn:aws:lambda:*:123456789012:function:my-lambda-function",
            "Condition": {
                "StringLike": {
                    "aws:userid": "*:myuser1234"
                }
            }
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "lambda:ListFunctions",
                "lambda:ListEventSourceMappings",
                "lambda:ListLayers",
                "lambda:ListLayerVersions"
            ],
            "Resource": "*",
            "Condition": {
                "StringLike": {
                    "aws:userid": "*:myuser1234"
                }
            }
        }
    ]
}

if you prefer, you may remove * wildcard getting role id using AWS CLI with the command:

aws iam get-role --role-name ROLE_NAME

and changing condition as follows:

"Condition": {
   "StringEquals": {
       "aws:userid": "ROLE_ID:myuser1234"
   }
}


问:
How to load fxml file to full size in borderpane
My goal is get the size of user monitor and show FXML file accordingly.
However, the window appears to fit the size but the FXML file does not.
How do I fit the file into the BorderPane?

In addition, I hope it can be automatically resize when I change the screen size.

I wrote the code by referring to the following YouTube for window control.
https://www.youtube.com/watch?v=UzlXUlTD1Lo

Main.java

```<code>public class Main extends Application {
FXMLLoader loader = new FXMLLoader();
StackPane pane = new StackPane();
BorderPane mainPane = new BorderPane();
String main="test.fxml";
Scene scene = new Scene(pane, Screen.getPrimary().getVisualBounds().getWidth(), Screen.getPrimary().getVisualBounds().getHeight());

@Override
public void start(Stage primaryStage) {
    try {
        primaryStage.setX(Screen.getPrimary().getVisualBounds().getMinX());
        primaryStage.setY(Screen.getPrimary().getVisualBounds().getMinY());
        mainPane.prefWidthProperty().bind(pane.widthProperty());
        mainPane.prefHeightProperty().bind(pane.heightProperty());
        mainPane = (BorderPane) loader.load(getClass().getResourceAsStream(main));

        pane.getChildren().add(mainPane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    launch(args);
}
</code>```

}

test.fxml

```<code>    <BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="922.0" prefWidth="1314.0" style="-fx-background-color: white;" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1">
   <top>
      <VBox BorderPane.alignment="CENTER">
         <children>
            <MenuBar prefHeight="18.0" prefWidth="1078.0" style="-fx-background-color: #f0efef;">
              <menus>
                <Menu mnemonicParsing="false" text="File">
                  <items>
                    <MenuItem mnemonicParsing="false" text="Close" />
                  </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Edit">
                  <items>
                    <MenuItem mnemonicParsing="false" text="Delete" />
                  </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Help">
                  <items>
                    <MenuItem mnemonicParsing="false" text="About" />
                  </items>
                </Menu>
              </menus>
            </MenuBar>
            <ToolBar prefHeight="43.0" prefWidth="1078.0" style="-fx-background-color: #b0aacd;">
               <items>
                  <Label prefHeight="26.0" prefWidth="72.0" text=">>>">
                     <font>
                        <Font size="18.0" />
                     </font>
                  </Label>
                  <TextField fx:id="ip" prefHeight="29.0" prefWidth="198.0" />
                  <Button fx:id="start" mnemonicParsing="false" onAction="#onIp" prefHeight="29.0" prefWidth="88.0" style="-fx-background-color: #ddeedd;" text="start" />
               </items>
            </ToolBar>
         </children>
      </VBox>
   </top>
   <center>
      <VBox BorderPane.alignment="CENTER">
         <children>
            <AnchorPane prefHeight="221.0" prefWidth="1078.0">
               <children>
                  <Label layoutX="14.0" layoutY="11.0" prefHeight="34.0" prefWidth="210.0" text="Chapter1">
                     <font>
                        <Font name="Expo M" size="25.0" />
                     </font>
                  </Label>
                  <Separator layoutX="9.0" layoutY="46.0" prefHeight="3.0" prefWidth="1221.0" />
                  <Label layoutX="620.0" layoutY="57.0" text="age" AnchorPane.leftAnchor="620.0">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <Label layoutX="291.0" layoutY="57.0" text="name" AnchorPane.leftAnchor="291.0">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <Label layoutX="301.0" layoutY="99.0" text="choice" AnchorPane.leftAnchor="301.0">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <TextField fx:id="age" layoutX="677.0" layoutY="57.0" prefHeight="29.0" prefWidth="126.0" />
                  <ChoiceBox layoutX="416.0" layoutY="99.0" prefHeight="26.0" prefWidth="51.0" />
                  <Button fx:id="submit" layoutX="1120.0" layoutY="141.0" mnemonicParsing="false" style="-fx-background-color: #b0aacd;" text="submit">
                     <font>
                        <Font name="Ebrima Bold" size="15.0" />
                     </font>
                  </Button>
                  <TextField fx:id="name" layoutX="341.0" layoutY="57.0" prefHeight="29.0" prefWidth="126.0" />
                  <CheckBox fx:id="male" layoutX="615.0" layoutY="99.0" mnemonicParsing="false" text="male">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </CheckBox>
                  <CheckBox fx:id="female" layoutX="712.0" layoutY="99.0" mnemonicParsing="false" text="female">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </CheckBox>
               </children>
            </AnchorPane>
            <AnchorPane prefHeight="227.0" prefWidth="1078.0">
               <children>
                  <Label layoutX="14.0" layoutY="16.0" prefHeight="32.0" prefWidth="179.0" text="Chapter2">
                     <font>
                        <Font name="Expo M" size="25.0" />
                     </font>
                  </Label>
                  <Separator layoutX="14.0" layoutY="48.0" prefHeight="7.0" prefWidth="1225.0" />
                  <Label layoutX="176.0" layoutY="67.0" text="aaa">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <TextField fx:id="text1" editable="false" layoutX="285.0" layoutY="66.0" prefHeight="26.0" prefWidth="110.0" />
                  <Label layoutX="450.0" layoutY="67.0" text="ddd">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <TextField fx:id="text2" editable="false" layoutX="598.0" layoutY="66.0" prefHeight="26.0" prefWidth="110.0" />
                  <Label layoutX="767.0" layoutY="67.0" text="ggg">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <TextField fx:id="text3" editable="false" layoutX="900.0" layoutY="66.0" prefHeight="26.0" prefWidth="110.0" />
                  <Label layoutX="746.0" layoutY="155.0" text="Result">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <TextField fx:id="text8" editable="false" layoutX="900.0" layoutY="155.0" prefHeight="26.0" prefWidth="110.0" />
                  <Label layoutX="174.0" layoutY="110.0" text="bbb">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <TextField fx:id="text4" editable="false" layoutX="285.0" layoutY="110.0" prefHeight="26.0" prefWidth="110.0" />
                  <Label layoutX="458.0" layoutY="110.0" text="eee">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <TextField fx:id="text5" editable="false" layoutX="598.0" layoutY="110.0" prefHeight="26.0" prefWidth="110.0" />
                  <Label layoutX="178.0" layoutY="155.0" text="ccc">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <TextField fx:id="text6" editable="false" layoutX="285.0" layoutY="155.0" prefHeight="26.0" prefWidth="110.0" />
                  <Label layoutX="458.0" layoutY="155.0" text="fff">
                     <font>
                        <Font name="Ebrima" size="19.0" />
                     </font>
                  </Label>
                  <TextField fx:id="texxt7" editable="false" layoutX="598.0" layoutY="155.0" prefHeight="26.0" prefWidth="110.0" />
                  <Button fx:id="submit1" layoutX="1127.0" layoutY="170.0" mnemonicParsing="false" style="-fx-background-color: #b0aacd;" text="submit">
                     <font>
                        <Font name="Ebrima Bold" size="15.0" />
                     </font>
                  </Button>
               </children>
            </AnchorPane>
            <AnchorPane prefHeight="444.0" prefWidth="1078.0">
               <children>
                  <Label layoutX="491.0" layoutY="9.0" text="List" textAlignment="CENTER">
                     <font>
                        <Font name="Expo M" size="25.0" />
                     </font>
                  </Label>
                  <Separator layoutX="7.0" layoutY="40.0" prefHeight="14.0" prefWidth="1225.0" />
                  <TableView fx:id="List" layoutX="11.0" layoutY="56.0" maxHeight="-Infinity" prefHeight="380.0" prefWidth="1288.0">
                    <columns>
                      <TableColumn fx:id="No" prefWidth="34.0" style="-fx-background-color: white;" />
                        <TableColumn fx:id="a" prefWidth="83.0" style="-fx-background-color: white;" text="a" />
                        <TableColumn fx:id="b" prefWidth="256.0" style="-fx-background-color: white;" text="b" />
                        <TableColumn fx:id="c" prefWidth="90.0" style="-fx-background-color: white;" text="c" />
                        <TableColumn fx:id="d" prefWidth="89.0" style="-fx-background-color: white;" text="d" />
                        <TableColumn fx:id="e" prefWidth="135.0" style="-fx-background-color: white;" text="e" />
                        <TableColumn fx:id="f" prefWidth="87.0" style="-fx-background-color: white;" text="f" />
                        <TableColumn fx:id="g" prefWidth="75.0" text="g" />
                        <TableColumn fx:id="h" prefWidth="75.0" style="-fx-background-color: white;" text="h" />
                        <TableColumn fx:id="i" prefWidth="149.0" style="-fx-background-color: white;" text="i" />
                        <TableColumn fx:id="j" prefWidth="135.0" style="-fx-background-color: white;" text="j" />
                        <TableColumn fx:id="k" prefWidth="75.0" style="-fx-background-color: white;" text="k" />
                    </columns>
                  </TableView>
               </children>
            </AnchorPane>
         </children>
      </VBox>
   </center>
</BorderPane>
</code>```

The FXML file is located in the middle, but not the screen size.

答:
There are a couple things to point out with your code:

You are creating a new BorderPane and then overriding that when you load the FXML. No need to call BorderPane mainPane = new BorderPane()

After loading the FXML's BorderPane, you're placing it into a StackPane for some reason, but never configure the StackPane on how you want its children laid out.

There is no reason to have to determine the screen resolution/size like this. You can call either primaryStage.setMaximized(true) or primaryStage.setFullscreen(true), depending on whether you want the stage borders to be visible.

Consider the following code snippet that I've simplified a bit:

```<code>import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        try {
            // Create the loader and pass our text.fxml reference to it
            FXMLLoader loader = new FXMLLoader(getClass().getResource("test.fxml"));

            // If you do not specify a controller in the FXML itself, you can do so here
            loader.setController(new Controller());

            // Set our Stage's scene and load the FXML at the same time
            primaryStage.setScene(new Scene(loader.load()));

            // Maximize the stage (or set to fullscreen
            primaryStage.setMaximized(true);
//            primaryStage.setFullScreen(true);

            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

The Result:

Body:
My goal is get the size of user monitor and show FXML file accordingly.
However, the window appears to fit the size but the FXML file does not.
How do I fit the file into the BorderPane?

In addition, I hope it can be automatically resize when I change the screen size.

I wrote the code by referring to the following YouTube for window control.
https://www.youtube.com/watch?v=UzlXUlTD1Lo

Main.java

public class Main extends Application {
FXMLLoader loader = new FXMLLoader();
StackPane pane = new StackPane();
BorderPane mainPane = new BorderPane();
String main="test.fxml";
Scene scene = new Scene(pane, Screen.getPrimary().getVisualBounds().getWidth(), Screen.getPrimary().getVisualBounds().getHeight());

@Override
public void start(Stage primaryStage) {
    try {
        primaryStage.setX(Screen.getPrimary().getVisualBounds().getMinX());
        primaryStage.setY(Screen.getPrimary().getVisualBounds().getMinY());
        mainPane.prefWidthProperty().bind(pane.widthProperty());
        mainPane.prefHeightProperty().bind(pane.heightProperty());
        mainPane = (BorderPane) loader.load(getClass().getResourceAsStream(main));

        pane.getChildren().add(mainPane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    launch(args);
}

}

test.fxml

    <BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="922.0" prefWidth="1314.0" style="-fx-background-color: white;" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1">
   <top>
      <VBox BorderPane.alignment="CENTER">
         <children>
            <MenuBar prefHeight="18.0" prefWidth="1078.0" style="-fx-background-color: #f0efef;">
              <menus>
                <Menu mnemonicParsing="false" text="File">
                  <items>
                    <MenuItem mnemonicParsing="false" text="Close" />
                  </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Edit">
                  <items>
                    <MenuItem mnemonicParsing="false" text="Delete" />
                  </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Help">
                  <items>
                    <MenuItem mnemonicParsing="false" text="About" />
                  </items>
                </Menu>
              </menus>
            </MenuBar>
            <ToolBar prefHeight="43.0" prefWidth="1078.0" style="-fx-background-color: #b0aacd;">
               <items>
                  >>">

                  <TextField fx:id="ip" prefHeight="29.0" prefWidth="198.0" />
                  <Button fx:id="start" mnemonicParsing="false" onAction="#onIp" prefHeight="29.0" prefWidth="88.0" style="-fx-background-color: #ddeedd;" text="start" />
               </items>
            </ToolBar>
         </children>
      </VBox>
   </top>

      <VBox BorderPane.alignment="CENTER">
         <children>
            <AnchorPane prefHeight="221.0" prefWidth="1078.0">
               <children>

                  <Separator layoutX="9.0" layoutY="46.0" prefHeight="3.0" prefWidth="1221.0" />

                  <TextField fx:id="age" layoutX="677.0" layoutY="57.0" prefHeight="29.0" prefWidth="126.0" />
                  <ChoiceBox layoutX="416.0" layoutY="99.0" prefHeight="26.0" prefWidth="51.0" />
                  <Button fx:id="submit" layoutX="1120.0" layoutY="141.0" mnemonicParsing="false" style="-fx-background-color: #b0aacd;" text="submit">

                  </Button>
                  <TextField fx:id="name" layoutX="341.0" layoutY="57.0" prefHeight="29.0" prefWidth="126.0" />
                  <CheckBox fx:id="male" layoutX="615.0" layoutY="99.0" mnemonicParsing="false" text="male">

                  </CheckBox>
                  <CheckBox fx:id="female" layoutX="712.0" layoutY="99.0" mnemonicParsing="false" text="female">

                  </CheckBox>
               </children>
            </AnchorPane>
            <AnchorPane prefHeight="227.0" prefWidth="1078.0">
               <children>

                  <Separator layoutX="14.0" layoutY="48.0" prefHeight="7.0" prefWidth="1225.0" />

                  <TextField fx:id="text1" editable="false" layoutX="285.0" layoutY="66.0" prefHeight="26.0" prefWidth="110.0" />

                  <TextField fx:id="text2" editable="false" layoutX="598.0" layoutY="66.0" prefHeight="26.0" prefWidth="110.0" />

                  <TextField fx:id="text3" editable="false" layoutX="900.0" layoutY="66.0" prefHeight="26.0" prefWidth="110.0" />

                  <TextField fx:id="text8" editable="false" layoutX="900.0" layoutY="155.0" prefHeight="26.0" prefWidth="110.0" />

                  <TextField fx:id="text4" editable="false" layoutX="285.0" layoutY="110.0" prefHeight="26.0" prefWidth="110.0" />

                  <TextField fx:id="text5" editable="false" layoutX="598.0" layoutY="110.0" prefHeight="26.0" prefWidth="110.0" />

                  <TextField fx:id="text6" editable="false" layoutX="285.0" layoutY="155.0" prefHeight="26.0" prefWidth="110.0" />

                  <TextField fx:id="texxt7" editable="false" layoutX="598.0" layoutY="155.0" prefHeight="26.0" prefWidth="110.0" />
                  <Button fx:id="submit1" layoutX="1127.0" layoutY="170.0" mnemonicParsing="false" style="-fx-background-color: #b0aacd;" text="submit">

                  </Button>
               </children>
            </AnchorPane>
            <AnchorPane prefHeight="444.0" prefWidth="1078.0">
               <children>

                  <Separator layoutX="7.0" layoutY="40.0" prefHeight="14.0" prefWidth="1225.0" />
                  <TableView fx:id="List" layoutX="11.0" layoutY="56.0" maxHeight="-Infinity" prefHeight="380.0" prefWidth="1288.0">
                    <columns>
                      <TableColumn fx:id="No" prefWidth="34.0" style="-fx-background-color: white;" />
                        <TableColumn fx:id="a" prefWidth="83.0" style="-fx-background-color: white;" text="a" />
                        <TableColumn fx:id="b" prefWidth="256.0" style="-fx-background-color: white;" text="b" />
                        <TableColumn fx:id="c" prefWidth="90.0" style="-fx-background-color: white;" text="c" />
                        <TableColumn fx:id="d" prefWidth="89.0" style="-fx-background-color: white;" text="d" />
                        <TableColumn fx:id="e" prefWidth="135.0" style="-fx-background-color: white;" text="e" />
                        <TableColumn fx:id="f" prefWidth="87.0" style="-fx-background-color: white;" text="f" />
                        <TableColumn fx:id="g" prefWidth="75.0" text="g" />
                        <TableColumn fx:id="h" prefWidth="75.0" style="-fx-background-color: white;" text="h" />
                        <TableColumn fx:id="i" prefWidth="149.0" style="-fx-background-color: white;" text="i" />
                        <TableColumn fx:id="j" prefWidth="135.0" style="-fx-background-color: white;" text="j" />
                        <TableColumn fx:id="k" prefWidth="75.0" style="-fx-background-color: white;" text="k" />
                    </columns>
                  </TableView>
               </children>
            </AnchorPane>
         </children>
      </VBox>

</BorderPane>

The FXML file is located in the middle, but not the screen size.

Body:
There are a couple things to point out with your code:

You are creating a new BorderPane and then overriding that when you load the FXML. No need to call BorderPane mainPane = new BorderPane()

After loading the FXML's BorderPane, you're placing it into a StackPane for some reason, but never configure the StackPane on how you want its children laid out.

There is no reason to have to determine the screen resolution/size like this. You can call either primaryStage.setMaximized(true) or primaryStage.setFullscreen(true), depending on whether you want the stage borders to be visible.

Consider the following code snippet that I've simplified a bit:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        try {
            // Create the loader and pass our text.fxml reference to it
            FXMLLoader loader = new FXMLLoader(getClass().getResource("test.fxml"));

            // If you do not specify a controller in the FXML itself, you can do so here
            loader.setController(new Controller());

            // Set our Stage's scene and load the FXML at the same time
            primaryStage.setScene(new Scene(loader.load()));

            // Maximize the stage (or set to fullscreen
            primaryStage.setMaximized(true);
//            primaryStage.setFullScreen(true);

            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

The Result:


问:
Javascript recursion problem
I am trying to write a function that will change between an array of images. What I have makes sense to me, but when I run it as it is below then the first image loads, then the second image loads at some point (the transparency doesn't change) and then nothing happens. Here is the javascript code:

```<code>        var image1 = new Image();var image2 = new Image(); var image3 = new Image();
        image1.src = "images/website6.jpg"; image2.src = "images/website7.jpg"; image3.src = "images/sunset.jpg";
        var images = new Array("images/website6.jpg","images/website7.jpg","images/sunset.jpg");
        /*document.slide.style.opacity = 1;
        document.slide.stylebg.opacity = 0;*/
        setTimeout(function() { fade(images,0); }, 2000);
        function delay(arr,num)
        {
            document.slide.src = arr[num % 3];
            document.slide.style.opacity = 1;
            document.slidebg.style.opacity = 0;
            document.slidebg.src = arr[(num+1)%3];
            var number = num + 1;
            setTimeout(function() { fade(arr,number); }, 2000);
        }
        function fade(arr,num)
        {
            /*alert('fadebefore ' + (document.slide.style.opacity).toString())*/
            document.slide.style.opacity -= 0.1
            /*alert('fade')*/
            document.slide.stylebg.opacity += 0.1
            if (document.slide.style.opacity == 0)
            {
                setTimeout(function() { delay(arr,num); }, 150);
            }
            else
            {
                setTimeout(function() { fade(arr,num); }, 1500);
            }
        }
</code>```

The HTML is simple. I have two classes; style and stylebg. style sits in front of stylebg and then I change opacities and images as needed. The javascript seems logical to me, but it doesn't work as expected. Also worth noting is there are 3 comments. The first comment (line 3-4) is attemping to set the opacities to what they should be at the beginning. However, if I do this then I get even less progress than above: the first image loads and nothing else happens. The second two comments are used for debugging purposes. If I uncomment these then the image change occurs between the two alerts, which would seem to say the image change is caused by the opacity change.

So can anybody explain why it isn't doing what I expect it to? Thanks.

EDIT: Some more code:

HTML (This is the only part being affected):

```<code><div style="position: relative;">
<img src="images/sunset.jpg" id="slide" />
<img src="images/website6.jpg" id="slidebg" />
</div>
</code>```

CSS:

```#slide{
    display:block;
    margin-left:5;
    margin-right:auto;
    border: 1px solid black;
    z-index: 1;
    top: 0px;
    position: relative;
}
#slidebg{
    display:block;
    margin-left:auto;
    margin-right:auto;
    border: 1px solid black;
    z-index: 0;
    top: 0px;
    position: absolute;
}```

答:
Answering for formatting's sake. I have not debugged to see what would work, but this makes more sense to me

If you want to use ID, use document.getElementById, if you want to use name, use document.images[imgname] or document.imagename
You are mixing names and style too. document.slide.stylebg.opacity and such

This does something. Not sure it is what you want: http://jsfiddle.net/EcShW/2/

```<code><div style="position: relative;">
<img src="images/sunset.jpg" id="slide" name="slide" />
<img src="images/website6.jpg" id="slidebg" name="slidebg" />
</div>

    var images = []; // can be more elegant, but this is simpler
    images[0]=new Image(); images[0].src="images/website6.jpg";
    images[1]=new Image(); images[1].src="images/website7.jpg";
    images[2]=new Image(); images[2].src="images/sunset.jpg";
    var tid1,tid2,tid3
    tid1=setTimeout(function() { fade(images,0); }, 2000);
    function delay(arr,num)
    {
        document.slide.src = arr[num % 3].src;
        document.slide.style.opacity = 1;
        document.slidebg.style.opacity = 0;
        document.slidebg.src = arr[(num+1)%3].src;
        var number = num + 1;
        tid2=setTimeout(function() { fade(arr,number); }, 2000);
    }
    function fade(arr,num)
    {
        document.slide.style.opacity -= 0.1
        document.stylebg.style.opacity += 0.1
        if (document.slide.style.opacity == 0)
        {
            tid3=setTimeout(function() { delay(arr,num); }, 150);
        }
        else
        {
            tid3=setTimeout(function() { fade(arr,num); }, 1500);
        }
    }
</code>```

Title: Javascript recursion problem

Body:
I am trying to write a function that will change between an array of images. What I have makes sense to me, but when I run it as it is below then the first image loads, then the second image loads at some point (the transparency doesn't change) and then nothing happens. Here is the javascript code:

        var image1 = new Image();var image2 = new Image(); var image3 = new Image();
        image1.src = "images/website6.jpg"; image2.src = "images/website7.jpg"; image3.src = "images/sunset.jpg";
        var images = new Array("images/website6.jpg","images/website7.jpg","images/sunset.jpg");
        /*document.slide.style.opacity = 1;
        document.slide.stylebg.opacity = 0;*/
        setTimeout(function() { fade(images,0); }, 2000);
        function delay(arr,num)
        {
            document.slide.src = arr[num % 3];
            document.slide.style.opacity = 1;
            document.slidebg.style.opacity = 0;
            document.slidebg.src = arr[(num+1)%3];
            var number = num + 1;
            setTimeout(function() { fade(arr,number); }, 2000);
        }
        function fade(arr,num)
        {
            /*alert('fadebefore ' + (document.slide.style.opacity).toString())*/
            document.slide.style.opacity -= 0.1
            /*alert('fade')*/
            document.slide.stylebg.opacity += 0.1
            if (document.slide.style.opacity == 0)
            {
                setTimeout(function() { delay(arr,num); }, 150);
            }
            else
            {
                setTimeout(function() { fade(arr,num); }, 1500);
            }
        }

The HTML is simple. I have two classes; style and stylebg. style sits in front of stylebg and then I change opacities and images as needed. The javascript seems logical to me, but it doesn't work as expected. Also worth noting is there are 3 comments. The first comment (line 3-4) is attemping to set the opacities to what they should be at the beginning. However, if I do this then I get even less progress than above: the first image loads and nothing else happens. The second two comments are used for debugging purposes. If I uncomment these then the image change occurs between the two alerts, which would seem to say the image change is caused by the opacity change.

So can anybody explain why it isn't doing what I expect it to? Thanks.

EDIT: Some more code:

HTML (This is the only part being affected):

CSS:

#slide{
    display:block;
    margin-left:5;
    margin-right:auto;
    border: 1px solid black;
    z-index: 1;
    top: 0px;
    position: relative;
}
#slidebg{
    display:block;
    margin-left:auto;
    margin-right:auto;
    border: 1px solid black;
    z-index: 0;
    top: 0px;
    position: absolute;
}

Body:
Answering for formatting's sake. I have not debugged to see what would work, but this makes more sense to me

If you want to use ID, use document.getElementById, if you want to use name, use document.images[imgname] or document.imagename
You are mixing names and style too. document.slide.stylebg.opacity and such

This does something. Not sure it is what you want: http://jsfiddle.net/EcShW/2/

<div style="position: relative;">
<img src="images/sunset.jpg" id="slide" name="slide" />
<img src="images/website6.jpg" id="slidebg" name="slidebg" />
</div>

    var images = []; // can be more elegant, but this is simpler
    images[0]=new Image(); images[0].src="images/website6.jpg";
    images[1]=new Image(); images[1].src="images/website7.jpg";
    images[2]=new Image(); images[2].src="images/sunset.jpg";
    var tid1,tid2,tid3
    tid1=setTimeout(function() { fade(images,0); }, 2000);
    function delay(arr,num)
    {
        document.slide.src = arr[num % 3].src;
        document.slide.style.opacity = 1;
        document.slidebg.style.opacity = 0;
        document.slidebg.src = arr[(num+1)%3].src;
        var number = num + 1;
        tid2=setTimeout(function() { fade(arr,number); }, 2000);
    }
    function fade(arr,num)
    {
        document.slide.style.opacity -= 0.1
        document.stylebg.style.opacity += 0.1
        if (document.slide.style.opacity == 0)
        {
            tid3=setTimeout(function() { delay(arr,num); }, 150);
        }
        else
        {
            tid3=setTimeout(function() { fade(arr,num); }, 1500);
        }
    }


问:
Checking which object appears most times in a list c#
So i Have a temporary ListObject List used just to check the condition

```<code>class ListObject
{
    public string Key { get; set; }
    public int Value { get; set; }

    public void Convert(string str)
    {
        Key = str;
    }
}
</code>```

and I'm writing a method supposed to check which name appears most times in another List of objects. The ListObject.Key gets the name assigned, while ListObject.Value stores the number of appearances. I want to check if the name was already stored from the List I'm holding the value in, and if yes, then increase the Value on the ListObject field which stores the name.
The thing is that i have no idea how to point the field which should be increased. I would need something like list[*index of the wanted name].Value += 1; How am i supposed to point the index? And should I use KeyValue pair instead of my ListObject class?

答:
It looks like you're trying to re-invent a Dictionary<TKey,TValue>

```<code>var frequencyMap = new Dictionary<string,int>();
foreach(string item in itemList)
{
    if (!frequencyMap.ContainsKey(item))
        frequencyMap.Add(item, 0);

    frequencyMap[item] += 1;
}
</code>```

Body:
So i Have a temporary ListObject List used just to check the condition

class ListObject
{
    public string Key { get; set; }
    public int Value { get; set; }

    public void Convert(string str)
    {
        Key = str;
    }
}

and I'm writing a method supposed to check which name appears most times in another List of objects. The ListObject.Key gets the name assigned, while ListObject.Value stores the number of appearances. I want to check if the name was already stored from the List I'm holding the value in, and if yes, then increase the Value on the ListObject field which stores the name.
The thing is that i have no idea how to point the field which should be increased. I would need something like list[*index of the wanted name].Value += 1; How am i supposed to point the index? And should I use KeyValue pair instead of my ListObject class?

Body:
It looks like you're trying to re-invent a Dictionary<TKey,TValue>

var frequencyMap = new Dictionary<string,int>();
foreach(string item in itemList)
{
    if (!frequencyMap.ContainsKey(item))
        frequencyMap.Add(item, 0);

    frequencyMap[item] += 1;
}


问:
How to make std::istream_iterator read only until the end of line?
Having the following piece of code:

std::vector<int64> values;
std::copy(
  std::istream_iterator<int64>(std::cin),
  std::istream_iterator<int64>(),
  std::back_inserter(values)
);
```

I'd like to make it read the input stream only until the end of line. How can I do that with std::istream_iterator?

答:
Adapted from an earlier answer to a similar question (here):

```<code>#include <vector>
#include <algorithm>
#include <string>
#include <iterator>

namespace detail
{
    class Line : public std::string
    {
        friend std::istream & operator>>(std::istream & is, Line & line)
        {
            return std::getline(is, line);
        }
    };
}

template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
    typedef std::istream_iterator<detail::Line> InIt;
    std::copy_n(InIt(is), 1, dest);
}

int main()
{
    std::vector<std::string> v;
    read_lines(std::cin, std::back_inserter(v));

    return 0;
}
</code>```

This code should take only one line and saves it into the vector v. This is thanks to the use of std::copy_n function which takes the number of elements-to-be-copied as input. There is a quirk, though, reported here. Depending on your platform, one or two lines will be read even though only the first one will be saved into v.

That being said, if you want to make it fail-safe, you can just implement your own copy_n(...) function, like so:

```<code>template<class InIt, class Range, class OutIt>
OutIt own_copy_n(InIt first, Range count, OutIt dest)
{
  *dest = *first;
  while (0 < --count)
      *++dest = *++first;
  return (++dest);
}
</code>```

Then instead of using std::copy_n(...) in you code, you can use own_copy_n(...).
This way you'll be sure you'll have to input one line only, and that that line will be saved into your vector v.

Body:
Having the following piece of code:

std::vector<int64> values;
std::copy(
  std::istream_iterator<int64>(std::cin),
  std::istream_iterator<int64>(),
  std::back_inserter(values)
);

I'd like to make it read the input stream only until the end of line. How can I do that with std::istream_iterator?

Body:
Adapted from an earlier answer to a similar question (here):

#include <vector>
#include <algorithm>
#include <string>
#include <iterator>

namespace detail
{
    class Line : public std::string
    {
        friend std::istream & operator>>(std::istream & is, Line & line)
        {
            return std::getline(is, line);
        }
    };
}

template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
    typedef std::istream_iterator<detail::Line> InIt;
    std::copy_n(InIt(is), 1, dest);
}

int main()
{
    std::vector<std::string> v;
    read_lines(std::cin, std::back_inserter(v));

    return 0;
}

This code should take only one line and saves it into the vector v. This is thanks to the use of std::copy_n function which takes the number of elements-to-be-copied as input. There is a quirk, though, reported here. Depending on your platform, one or two lines will be read even though only the first one will be saved into v.

That being said, if you want to make it fail-safe, you can just implement your own copy_n(...) function, like so:

template<class InIt, class Range, class OutIt>
OutIt own_copy_n(InIt first, Range count, OutIt dest)
{
  *dest = *first;
  while (0 < --count)
      *++dest = *++first;
  return (++dest);
}

Then instead of using std::copy_n(...) in you code, you can use own_copy_n(...).
This way you'll be sure you'll have to input one line only, and that that line will be saved into your vector v.


问:
Embed two online websites in one HTML page
I am trying to embed two websites in one page like YouTube and Google using div tags and the links in between the div tags....is there any way this could work?</p>

答:
Generally the iframe-tag is used to embed whole websites. (see MDN article) But appearantly youtube & google have blocked that option. (see when running the snippet below)

```

Body:
Generally the iframe-tag is used to embed whole websites. (see MDN article) But appearantly youtube & google have blocked that option. (see when running the snippet below)

<iframe
    width="500"
    height="100"
    src="https://www.wikipedia.org">
</iframe>

<iframe
    width="500"
    height="100"
    src="https://www.google.com">
</iframe>

<iframe
    width="500"
    height="100"
    src="https://www.youtube.com">
</iframe>


问:
Did I refactor this example from Qt Wiki correctly?
I found this example on how to catch the press of the Enter key from Qt Wiki:

```<code>bool KeyEnterReceiver::eventFilter(QObject* obj, QEvent* event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent* key = static_cast<QKeyEvent*>(event);
        if ((key->key() == Qt::Key_Enter) || (key->key() == Qt::Key_Return)) {
            // Enter or return was pressed
        } else {
            return QObject::eventFilter(obj, event);
        }
        return true;
    } else {
        return QObject::eventFilter(obj, event);
    }
    return false;
}
</code>```

It seemed very cumbersome and I noticed I could refactor it to be a lot simpler:

```<code>bool KeyEnterReceiver::eventFilter(QObject* obj, QEvent* event)
{
    if (event->type() == QEvent::KeyPress) {
        auto* key = dynamic_cast<QKeyEvent*>(event);  // clang-tidy suggested to change static_cast to dynamic_cast
        if ((key->key() == Qt::Key_Enter) || (key->key() == Qt::Key_Return)) {
            // Enter or return was pressed
            return true;
        }
    }
    return QObject::eventFilter(obj, event);
}
</code>```

Did I miss anything or is my refactoring correct and identically functioning?

Could this be refactored to be even simpler?

答:
Yes, your code is equivalent. In fact, it's better than the original example, which has dead code in it that can never be reached. The return false; of the original code is impossible to reach. There is no branching path that can ever lead to it. You eliminated that in your version. You also eliminated the duplicated call to the overridden eventFilter().

The dynamic cast is not needed, because the static cast is guaranteed to be valid since event->type() == QEvent::KeyPress.

Anyway, the original code is quite bad, actually. Your version is better.

Body:
I found this example on how to catch the press of the Enter key from Qt Wiki:

bool KeyEnterReceiver::eventFilter(QObject* obj, QEvent* event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent* key = static_cast<QKeyEvent*>(event);
        if ((key->key() == Qt::Key_Enter) || (key->key() == Qt::Key_Return)) {
            // Enter or return was pressed
        } else {
            return QObject::eventFilter(obj, event);
        }
        return true;
    } else {
        return QObject::eventFilter(obj, event);
    }
    return false;
}

It seemed very cumbersome and I noticed I could refactor it to be a lot simpler:

bool KeyEnterReceiver::eventFilter(QObject* obj, QEvent* event)
{
    if (event->type() == QEvent::KeyPress) {
        auto* key = dynamic_cast<QKeyEvent*>(event);  // clang-tidy suggested to change static_cast to dynamic_cast
        if ((key->key() == Qt::Key_Enter) || (key->key() == Qt::Key_Return)) {
            // Enter or return was pressed
            return true;
        }
    }
    return QObject::eventFilter(obj, event);
}

Did I miss anything or is my refactoring correct and identically functioning?

Could this be refactored to be even simpler?


问:
Page is not re-rendering after adding select list code
I am new In salesforce, currently learning a visualforce elements.

I am having a problem in my code that when I insert a SelectList code in my visualForce page then page re-rendering stops working.

Without SelectList page re-rendering works fine.

I have provided a code snippets below. After adding SelectList save method from controller not getting called also contact  i am trying to insert is not getting inserted.

Any help is appreciated.

This is my visualforce page.

```<code><apex:page controller="ContactController">
    <apex:form >
        <apex:pageBlock>
            <apex:pageBlockSection >
                <apex:inputField value="{!Contact.AccountId}" label="Account Name:"/>
                <apex:inputField value="{!Contact.LastName}" label="LastName"/>
                <apex:inputField value="{!Contact.phone}" label="Phone"/>
                <apex:inputField value="{!Contact.Department}"/>
                <apex:inputField value="{!Contact.Designation__c}"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection id="id3">
                 <apex:pageBlockSectionItem >
                <apex:actionRegion >
                <apex:selectList value="{!Contact}" multiselect="true" id="slist1" style="overflow scroll; height : 100px;">
                    <apex:actionSupport event="onchange" rerender="id1" />
                    <apex:selectOptions value="{!ContactFields}"></apex:selectOptions>
                </apex:selectList><p/>
                </apex:actionRegion>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>

            <apex:pageBlockSection id="id1">
                <apex:pageBlockTable value="{!contactList}" var="c"  >
                    <apex:column headerValue="Last Name">
                        <apex:outputField value="{!c.Lastname}"/>
                    </apex:column>
                    <!--   <apex:column headerValue="Account">
<apex:outputField value="{!c.Account.Name}"/>
</apex:column> -->
                </apex:pageBlockTable>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}" reRender="id1"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>

</apex:page>
</code>```

This is my controller.

```<code>public class ContactController {
    public Account account { get; private set; }
    public Contact contact { get; set; }

    public List<Contact> contactList{get {return ([SELECT LastName,Account.Name FROM Contact where Account.Id = :ApexPages.currentPage().getParameters().get('id') order by createdDate DESC limit 5]);} set;}

    public Id id;
    Map<String, Schema.SobjectField> Contactfields{ get; set;}
    List<SelectOption> lstContactFields{get;set;}

    public ContactController() {
        contact=new Contact();
        id = ApexPages.currentPage().getParameters().get('id');
        contact.AccountId=id;
        Contactfields = Schema.SobjectType.Contact.fields.getMap();
    }

    public List<SelectOption> getContactFields(){
        if(lstContactFields==null){
            lstContactFields=new List<SelectOption>();
        }
        for(Schema.SObjectField s:Contactfields.values()){
            Schema.DescribeFieldResult fieldResult = s.getDescribe();
            lstContactFields.add(new SelectOption(String.valueof(fieldResult.getName()),String.valueof(fieldResult.getLabel())));
            //  lstContactFields.add(Contactfields.get(s).getDescribe().getLabel());
            //lstContactFields.add(String.valueOf(s));
        }

        return lstContactFields;
    }

    public PageReference save() {
        try {
            System.debug('save method');
            upsert contact;
            contact.Id=null;
            return null;
        } catch(System.DMLException e) {
            ApexPages.addMessages(e);
            return null;
        }
        //  After successful Save, navigate to the default view page
        //  PageReference pg = new PageReference(System.currentPageReference().getURL());
        //  pg.setRedirect(true);
        //    return pg;

    }

}
</code>```

答:
Your value bindings on these components aren't set up correctly.

```<code><apex:selectList value="{!Contact}" multiselect="true" id="slist1" style="overflow scroll; height : 100px;">
</code>```

An <apex:selectList> needs to be bound to a String or a List<String> (only for multiselect=true). Here, you've bound it to an sObject variable.

The fact that you've named your sObject variable the same as its class, Contact, is highly likely to cause further problems. Apex isn't case-sensitive, so contact and Contact are the same identifier. In general, you should not reuse reserved words or system class names as variable names, which you do again with id.

```<code><apex:selectOptions value="{!ContactFields}"></apex:selectOptions>
</code>```

<apex:selectOptions> has to have its value bound to a List<SelectOptions>. You've declared a property by that name with the wrong type:

```<code>Map<String, Schema.SobjectField> Contactfields{ get; set;}
</code>```

while also implementing a getter method with the right type:

```<code>public List<SelectOption> getContactFields(){
</code>```

Again, this is likely to produce unintuitive behavior, even if it does compile and render.

Body:
I am new In salesforce, currently learning a visualforce elements.

I am having a problem in my code that when I insert a SelectList code in my visualForce page then page re-rendering stops working.

Without SelectList page re-rendering works fine.

I have provided a code snippets below. After adding SelectList save method from controller not getting called also contact  i am trying to insert is not getting inserted.

Any help is appreciated.

This is my visualforce page.

<apex:page controller="ContactController">
    <apex:form >
        <apex:pageBlock>
            <apex:pageBlockSection >
                <apex:inputField value="{!Contact.AccountId}" label="Account Name:"/>
                <apex:inputField value="{!Contact.LastName}" label="LastName"/>
                <apex:inputField value="{!Contact.phone}" label="Phone"/>
                <apex:inputField value="{!Contact.Department}"/>
                <apex:inputField value="{!Contact.Designation__c}"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection id="id3">
                 <apex:pageBlockSectionItem >
                <apex:actionRegion >
                <apex:selectList value="{!Contact}" multiselect="true" id="slist1" style="overflow scroll; height : 100px;">
                    <apex:actionSupport event="onchange" rerender="id1" />
                    <apex:selectOptions value="{!ContactFields}"></apex:selectOptions>
                </apex:selectList>

                </apex:actionRegion>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>

            <apex:pageBlockSection id="id1">
                <apex:pageBlockTable value="{!contactList}" var="c"  >
                    <apex:column headerValue="Last Name">
                        <apex:outputField value="{!c.Lastname}"/>
                    </apex:column>

                </apex:pageBlockTable>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}" reRender="id1"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>

</apex:page>

This is my controller.

public class ContactController {
    public Account account { get; private set; }
    public Contact contact { get; set; }

    public List<Contact> contactList{get {return ([SELECT LastName,Account.Name FROM Contact where Account.Id = :ApexPages.currentPage().getParameters().get('id') order by createdDate DESC limit 5]);} set;}

    public Id id;
    Map<String, Schema.SobjectField> Contactfields{ get; set;}
    List<SelectOption> lstContactFields{get;set;}

    public ContactController() {
        contact=new Contact();
        id = ApexPages.currentPage().getParameters().get('id');
        contact.AccountId=id;
        Contactfields = Schema.SobjectType.Contact.fields.getMap();
    }

    public List<SelectOption> getContactFields(){
        if(lstContactFields==null){
            lstContactFields=new List<SelectOption>();
        }
        for(Schema.SObjectField s:Contactfields.values()){
            Schema.DescribeFieldResult fieldResult = s.getDescribe();
            lstContactFields.add(new SelectOption(String.valueof(fieldResult.getName()),String.valueof(fieldResult.getLabel())));
            //  lstContactFields.add(Contactfields.get(s).getDescribe().getLabel());
            //lstContactFields.add(String.valueOf(s));
        }

        return lstContactFields;
    }

    public PageReference save() {
        try {
            System.debug('save method');
            upsert contact;
            contact.Id=null;
            return null;
        } catch(System.DMLException e) {
            ApexPages.addMessages(e);
            return null;
        }
        //  After successful Save, navigate to the default view page
        //  PageReference pg = new PageReference(System.currentPageReference().getURL());
        //  pg.setRedirect(true);
        //    return pg;

    }

}

Body:
Your value bindings on these components aren't set up correctly.

<apex:selectList value="{!Contact}" multiselect="true" id="slist1" style="overflow scroll; height : 100px;">

An <apex:selectList> needs to be bound to a String or a List<String> (only for multiselect=true). Here, you've bound it to an sObject variable.

The fact that you've named your sObject variable the same as its class, Contact, is highly likely to cause further problems. Apex isn't case-sensitive, so contact and Contact are the same identifier. In general, you should not reuse reserved words or system class names as variable names, which you do again with id.

<apex:selectOptions value="{!ContactFields}"></apex:selectOptions>

<apex:selectOptions> has to have its value bound to a List<SelectOptions>. You've declared a property by that name with the wrong type:

Map<String, Schema.SobjectField> Contactfields{ get; set;}

while also implementing a getter method with the right type:

public List<SelectOption> getContactFields(){

Again, this is likely to produce unintuitive behavior, even if it does compile and render.


问:
Is there a way to save time by not calculating unnecessary sums?

The objective

Given a 2-dimensional array A, I have to keep adding +1 to the value of the first row in each column until the sums of the columns equal to the same value, for example 28.

My solution

It is probably not the best of solutions, but considering the point I'd like to make, it will do. This is meant to be a simplified example. In the original version it is based on a probability distribution whether the first or the second row gets the +1, and it differs among columns. Plus it has to be done one by one, for the probability distribution changes due to whether the first or the second row of a column got the +1 in the previous cycle. So summation of columns and iteration are necessary.

import numpy as np

A = np.arange(20).reshape(2, 10)
print(A)

MASK = A.sum(axis=0) < 28
print(A.sum(axis=0) < 28)

while np.any(MASK):
    LUCKYROW = np.repeat(0, np.count_nonzero(MASK))
    A[LUCKYROW, MASK] += 1
    MASK = A.sum(axis=0) < 28
    print(A.sum(axis=0) < 28)
print(A)
```

<p>Let's take a look at the output:</p>

```[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True False False]
[ True  True  True  True  True  True  True  True False False]
[ True  True  True  True  True  True  True False False False]
[ True  True  True  True  True  True  True False False False]
[ True  True  True  True  True  True False False False False]
[ True  True  True  True  True  True False False False False]
[ True  True  True  True  True False False False False False]
[ True  True  True  True  True False False False False False]
[ True  True  True  True False False False False False False]
[ True  True  True  True False False False False False False]
[ True  True  True False False False False False False False]
[ True  True  True False False False False False False False]
[ True  True False False False False False False False False]
[ True  True False False False False False False False False]
[ True False False False False False False False False False]
[ True False False False False False False False False False]
[False False False False False False False False False False]
[[18 17 16 15 14 13 12 11 10  9]
 [10 11 12 13 14 15 16 17 18 19]]
```

<p>Alright, it works, but why do I calculate the sum of each column in each cycle? Based on previous cycles I know which column's sum has already reached the target value. If I make use of this information, I can save time maybe.</p>

<h2>My second solution</h2>

<pre class="lang-py prettyprint-override"><code>import numpy as np

A = np.arange(20).reshape(2, 10)
print(A)

MASK = A.sum(axis=0) < 28
print(A.sum(axis=0) < 28)

while np.any(MASK):
    LUCKYROW = np.repeat(0, np.count_nonzero(MASK))
    A[LUCKYROW, MASK] += 1
    MASK[MASK] = A[:, MASK].sum(axis=0) < 28
    print(A[:, MASK].sum(axis=0) < 28)
print(A)
</code>```

And the output:

```<code>[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True]
[ True  True  True  True  True  True]
[ True  True  True  True  True  True]
[ True  True  True  True  True]
[ True  True  True  True  True]
[ True  True  True  True]
[ True  True  True  True]
[ True  True  True]
[ True  True  True]
[ True  True]
[ True  True]
[ True]
[ True]
[]
[[18 17 16 15 14 13 12 11 10  9]
 [10 11 12 13 14 15 16 17 18 19]]
</code>```

It seems to work. Although one problem emerges. It is not faster than the first solution. I have tried with 25000 columns and 74998 as target value, but they are roughly equal timewise.

My request

I think I may have a fundamental misunderstanding of either ndarray operations or ndarray indexing. The second solution should do less and less calculation with each cycle, so I'd expect a significant performance improvement. I am unable to find explanation. Where is my train of thought faulty?

答:
Since you're only changing the first row, you don't need to recalculate the sum of the columns on each iteration.  In fact, since the only change is adding 1 to some elements on the first row you don't need to iterate at all.

```<code>A = np.arange(20).reshape(2, 10)
s = A.sum(0)
d = max(s) - s
A[0] += d

>>> A
array([[18, 17, 16, 15, 14, 13, 12, 11, 10,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])
</code>```

This may not be possible with more complex calculations, but with sums it's an easy shortcut.

There could be a few reasons your "faster" code doesn't actually run faster.
First off, kudos for actually profiling the code.
The first reason is that A is very small.
Generally, numpy only gives a speed benefit with thousands or tens of thousands of elements in an array.

Second, in the "faster" code the line

```<code>MASK[MASK] = A[:, MASK].sum(axis=0) < 28
</code>```

creates a copy of all the rows in A indexed by MASK.
This can be a fairly expensive operation, so summing the extra rows in the original version using MASK = A.sum(axis=0) < 28 may be quicker simply because it doesn't need that extra copy.

Body:
The objective

Given a 2-dimensional array A, I have to keep adding +1 to the value of the first row in each column until the sums of the columns equal to the same value, for example 28.

My solution

It is probably not the best of solutions, but considering the point I'd like to make, it will do. This is meant to be a simplified example. In the original version it is based on a probability distribution whether the first or the second row gets the +1, and it differs among columns. Plus it has to be done one by one, for the probability distribution changes due to whether the first or the second row of a column got the +1 in the previous cycle. So summation of columns and iteration are necessary.

import numpy as np

A = np.arange(20).reshape(2, 10)
print(A)

MASK = A.sum(axis=0) < 28
print(A.sum(axis=0) < 28)

while np.any(MASK):
    LUCKYROW = np.repeat(0, np.count_nonzero(MASK))
    A[LUCKYROW, MASK] += 1
    MASK = A.sum(axis=0) < 28
    print(A.sum(axis=0) < 28)
print(A)

Let's take a look at the output:

[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True False False]
[ True  True  True  True  True  True  True  True False False]
[ True  True  True  True  True  True  True False False False]
[ True  True  True  True  True  True  True False False False]
[ True  True  True  True  True  True False False False False]
[ True  True  True  True  True  True False False False False]
[ True  True  True  True  True False False False False False]
[ True  True  True  True  True False False False False False]
[ True  True  True  True False False False False False False]
[ True  True  True  True False False False False False False]
[ True  True  True False False False False False False False]
[ True  True  True False False False False False False False]
[ True  True False False False False False False False False]
[ True  True False False False False False False False False]
[ True False False False False False False False False False]
[ True False False False False False False False False False]
[False False False False False False False False False False]
[[18 17 16 15 14 13 12 11 10  9]
 [10 11 12 13 14 15 16 17 18 19]]

Alright, it works, but why do I calculate the sum of each column in each cycle? Based on previous cycles I know which column's sum has already reached the target value. If I make use of this information, I can save time maybe.

My second solution

import numpy as np

A = np.arange(20).reshape(2, 10)
print(A)

MASK = A.sum(axis=0) < 28
print(A.sum(axis=0) < 28)

while np.any(MASK):
    LUCKYROW = np.repeat(0, np.count_nonzero(MASK))
    A[LUCKYROW, MASK] += 1
    MASK[MASK] = A[:, MASK].sum(axis=0) < 28
    print(A[:, MASK].sum(axis=0) < 28)
print(A)

And the output:

[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]
[ True  True  True  True  True  True  True  True  True False]
[ True  True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True]
[ True  True  True  True  True  True  True]
[ True  True  True  True  True  True]
[ True  True  True  True  True  True]
[ True  True  True  True  True]
[ True  True  True  True  True]
[ True  True  True  True]
[ True  True  True  True]
[ True  True  True]
[ True  True  True]
[ True  True]
[ True  True]
[ True]
[ True]
[]
[[18 17 16 15 14 13 12 11 10  9]
 [10 11 12 13 14 15 16 17 18 19]]

It seems to work. Although one problem emerges. It is not faster than the first solution. I have tried with 25000 columns and 74998 as target value, but they are roughly equal timewise.

My request

I think I may have a fundamental misunderstanding of either ndarray operations or ndarray indexing. The second solution should do less and less calculation with each cycle, so I'd expect a significant performance improvement. I am unable to find explanation. Where is my train of thought faulty?

Body:
Since you're only changing the first row, you don't need to recalculate the sum of the columns on each iteration.  In fact, since the only change is adding 1 to some elements on the first row you don't need to iterate at all.

A = np.arange(20).reshape(2, 10)
s = A.sum(0)
d = max(s) - s
A[0] += d

>>> A
array([[18, 17, 16, 15, 14, 13, 12, 11, 10,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])

This may not be possible with more complex calculations, but with sums it's an easy shortcut.

There could be a few reasons your "faster" code doesn't actually run faster.
First off, kudos for actually profiling the code.
The first reason is that A is very small.
Generally, numpy only gives a speed benefit with thousands or tens of thousands of elements in an array.

Second, in the "faster" code the line

MASK[MASK] = A[:, MASK].sum(axis=0) < 28

creates a copy of all the rows in A indexed by MASK.
This can be a fairly expensive operation, so summing the extra rows in the original version using MASK = A.sum(axis=0) < 28 may be quicker simply because it doesn't need that extra copy.


问:
How can I insert data into the database when an entity is created?
I'm creating a website for a school project which uses spring for the backend. I'm trying to insert data into the database when new data is saved to a specific table.

I've tried using @HandleAfterCreate and @PrePersist, but neither worked. I'm not very experienced with spring. The teacher told us to use it and now I don't know what do.

@HandleAfterCreate
public void handlePersonBeforeCreate(Person person){
    logger.info("Inside Person Before Create....");
    Set<Qualifikation> qualifikationen = new HashSet<>();
    kompetenzRepository.findAll().forEach(kompetenz -> {
        Qualifikation qualifikation = new Qualifikation();
        qualifikation.setAusmass(0);
        qualifikation.setKompetenz(kompetenz);
        qualifikation.setPerson(person);
    });
    person.setQualifikationen(qualifikationen);
    System.out.println(person.getDisplayName());
}
```

The code should set a person's "Qualifikation" to a default value when the person is inserted (via OAuth login). It should have every "Kompetenz" with a value of 0 by default. Kompetenz has a 1 to n relation to Qualifikation. If you need more information please ask me.

答:
It looks like you're trying to have access to the repository layer of your application inside an entity. This is generally not a good idea, as the entities should only know about the data they hold, not the other application components.

In this particular case it would be wise to use a @Service class with a method that you can call to insert the data into the database. In the method you could then insert any other entities as well. Let your repositories be fields of the service and make them @Autowired.

Body:
I'm creating a website for a school project which uses spring for the backend. I'm trying to insert data into the database when new data is saved to a specific table.

I've tried using @HandleAfterCreate and @PrePersist, but neither worked. I'm not very experienced with spring. The teacher told us to use it and now I don't know what do.

@HandleAfterCreate
public void handlePersonBeforeCreate(Person person){
    logger.info("Inside Person Before Create....");
    Set<Qualifikation> qualifikationen = new HashSet<>();
    kompetenzRepository.findAll().forEach(kompetenz -> {
        Qualifikation qualifikation = new Qualifikation();
        qualifikation.setAusmass(0);
        qualifikation.setKompetenz(kompetenz);
        qualifikation.setPerson(person);
    });
    person.setQualifikationen(qualifikationen);
    System.out.println(person.getDisplayName());
}

The code should set a person's "Qualifikation" to a default value when the person is inserted (via OAuth login). It should have every "Kompetenz" with a value of 0 by default. Kompetenz has a 1 to n relation to Qualifikation. If you need more information please ask me.


问:
Microservices - How to model a register flow with Authorization Server and Resource Server?
I'm using Java and Spring Boot to implement a Microservice ecosystem.

I have 3 logical boundaries:

Medicines (Resource Server)

Appointments (Resource Server)

Identity Federation (Authorization Server)

User's login information (username, password, roles, etc..) goes into the Identity Federation Microservice.
User's personal information (first name, last name, address, contact mediums, gender, etc..) goes into the Appointments Microservice.

Now, imagine a situation where at my Appointments Resource Server I have the following resource exposed:

GET /doctors/{id} - returns the personal information about the Doctor with the passed id

And at my Identity Federation Authorization Server I have the following:

POST /oauth/token - a resource that returns a token.

Now, imagine that I POST to /oauth/token at my Authorization Server and I got authenticated and receive a token.

Ok, now, I can use this token to do transactions with the Resource Servers.

If I send a GET to /doctor/1, my token gets parsed and I can read all of its claims. Roles, User Id, Username, etc..

The Doctor with id = 1 should not be able to see the personal information of other Doctor (eg.: Doctor with id = 4).

So, when the request arrives at /doctors/1, I need to check if the id on the token is the same that is being requested.

In Spring, would be something like this:

```<code>@GetMapping("/doctors/{id}")
@PreAuthorize("#id == authentication.doctorId")
public ResponseEntity<Object> handleGetDoctorsInformations(@PathVariable("id") Long id) {
    // logic and return
}
</code>```

But to be able to do that, I need to synchronize the ids on both Microservices (Appointments Resource Server and Identity Federation Authorization Server).

I can't use a Natural Key because I have three types of users (Doctor is just one of them) that can log-in, and the Natural Keys are different for both.

So, the id needs to be generated in somewhere.
I'm not sure which is the best way to it.

What our team have discussed:

Basically:

The front-end POST to Authorization Server with a whole Doctor JSON payload (with personal information AND login information).

The Authorization Server creates an account generating its unique id.

The Authorization Server increment the JSON payload with the generated id and then publishes the JSON to the Queue.

The Resource Server listens to the Queue, get the JSON and create the Doctor at his side, storing the Doctor personal Information.

Is this a bad way to do it?

答: In this specific case, you don't need to implement a queue with additional complexity just to verify special permission (here, read other doctors data) of a particular doctor. Instead, you can generate JWT token and embed specific privilege like 'READ_DOCTORS_INFO' on the payload of toke. Then your resource server which manages doctors information can verify provided token and allow specific user depending on the permissions embedded on JWT token.</p>

Body:
I'm using Java and Spring Boot to implement a Microservice ecosystem.

I have 3 logical boundaries:

Medicines (Resource Server)

Appointments (Resource Server)

Identity Federation (Authorization Server)

User's login information (username, password, roles, etc..) goes into the Identity Federation Microservice.
User's personal information (first name, last name, address, contact mediums, gender, etc..) goes into the Appointments Microservice.

Now, imagine a situation where at my Appointments Resource Server I have the following resource exposed:

GET /doctors/{id} - returns the personal information about the Doctor with the passed id

And at my Identity Federation Authorization Server I have the following:

POST /oauth/token - a resource that returns a token.

Now, imagine that I POST to /oauth/token at my Authorization Server and I got authenticated and receive a token.

Ok, now, I can use this token to do transactions with the Resource Servers.

If I send a GET to /doctor/1, my token gets parsed and I can read all of its claims. Roles, User Id, Username, etc..

The Doctor with id = 1 should not be able to see the personal information of other Doctor (eg.: Doctor with id = 4).

So, when the request arrives at /doctors/1, I need to check if the id on the token is the same that is being requested.

In Spring, would be something like this:

@GetMapping("/doctors/{id}")
@PreAuthorize("#id == authentication.doctorId")
public ResponseEntity<Object> handleGetDoctorsInformations(@PathVariable("id") Long id) {
    // logic and return
}

But to be able to do that, I need to synchronize the ids on both Microservices (Appointments Resource Server and Identity Federation Authorization Server).

I can't use a Natural Key because I have three types of users (Doctor is just one of them) that can log-in, and the Natural Keys are different for both.

So, the id needs to be generated in somewhere.
I'm not sure which is the best way to it.

What our team have discussed:

Basically:

The front-end POST to Authorization Server with a whole Doctor JSON payload (with personal information AND login information).

The Authorization Server creates an account generating its unique id.

The Authorization Server increment the JSON payload with the generated id and then publishes the JSON to the Queue.

The Resource Server listens to the Queue, get the JSON and create the Doctor at his side, storing the Doctor personal Information.

Is this a bad way to do it?