问:
HTML button click redirect to a
 tab on the same page
I have this code:

function openPage(pageName,elmnt,color) {
   var i, tabcontent, tablinks;
   tabcontent = document.getElementsByClassName("tabcontent");
   for (i = 0; i < tabcontent.length; i++) {
       tabcontent[i].style.display = "none";
   }

   tablinks = document.getElementsByClassName("tablink");
   for (i = 0; i < tablinks.length; i++) {
       tablinks[i].style.backgroundColor = "";
   }

   document.getElementById(pageName).style.display = "block";
   elmnt.style.backgroundColor = color;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="tablink" onclick="openPage('Settings', this, 'orange')">Settings</button>
<button class="tablink" onclick="openPage('About', this, 'orange')">About</button>

<div id="About" class="tabcontent">
    <h3>About:</h3>
    <input type="button" value="Refresh" onclick="history.go(0)" />
</div></code>```

This display on the same page a tab called About and Settings tab, in About tab I have a Refresh button.

I want this tab to redirect me to the Settings tab of the same html file. how can I do this ?

I have tried using the  to wrap the whole
 but it didnt do anything.

All redirect docs talk about redirecting to a link but i didnt find anything on redirecting to the same page to a different
 tab.

答:
use bookmarking

ex:

```<code> <a href="#your_Id">something</a>
  <div id="my-id">anything</div>
</code>```

Title: HTML button click redirect to a <div> tab on the same page

Body:
I have this code:

function openPage(pageName,elmnt,color) {
   var i, tabcontent, tablinks;
   tabcontent = document.getElementsByClassName("tabcontent");
   for (i = 0; i < tabcontent.length; i++) {
       tabcontent[i].style.display = "none";
   }

   tablinks = document.getElementsByClassName("tablink");
   for (i = 0; i < tablinks.length; i++) {
       tablinks[i].style.backgroundColor = "";
   }

   document.getElementById(pageName).style.display = "block";
   elmnt.style.backgroundColor = color;
}

<button class="tablink" onclick="openPage('Settings', this, 'orange')">Settings</button>
<button class="tablink" onclick="openPage('About', this, 'orange')">About</button>

About:

    <input type="button" value="Refresh" onclick="history.go(0)" />

This display on the same page a tab called About and Settings tab, in About tab I have a Refresh button.

I want this tab to redirect me to the Settings tab of the same html file. how can I do this ?

I have tried using the  to wrap the whole
 but it didnt do anything.

All redirect docs talk about redirecting to a link but i didnt find anything on redirecting to the same page to a different
 tab.

Body:
use bookmarking

ex:

 <a href="#your_Id">something</a>
  <div id="my-id">anything</div>


来源: stackexchange

问:
Syncing localStorage
I'm looking for a solution that allows a browser's localStorage to be less local, so that people can access their data on multiple devices. The traditional way is to run a database on a server and have people log in; but I'm trying to avoid doing that. I'd like the server side to be lightweight - perhaps even completely static if possible - and to not have the job of safely storing passwords, worrying about data protection etc.

Many browsers have a login of some sort -- Google Account, Firefox Account etc -- that ties a user's browsers together. So the ideal solution would be to store data in localStorage, but use that account to sync across devices. There are interfaces such as chrome.storage that seem to be available to packaged apps, but not to ordinary web pages.

Is something like this possible with present technologies?

答:
From Your webapp:

post an email address and the user data to the backend (PHP for example)

From Your back-end:

generate a UUID and save the user data inside a file which name is this UUID

send back to the client that UUID and save this identifier together with the data to the localStorage.

At this point, You can have a static link which You can either:

at client-side: print to the screen in clear-text or in form of a 2-D
barcode, ready to be recognized by Your mobile devices

at server-side: send by email to that given email address.

Now, You can get the user data from the back-end by posting that UUID

Discussion:

How safe is a UUID to store user-data?
I believe, a UUIDv4 (generated from 'random data') it is safe enough to create reasonably unique identifiers. So, pay attention how You are generating that random seeds. Here is a great reference: PHP function to generate v4 UUID.
So, that static link shall be safe enough, and You can use any already existing authentication system to share that link, by email or whatever You want.

Here is another approach: CROSS-STORAGE which enables multiple browser windows/tabs, across a variety of domains, to share a single localStorage. However, I strongly believe that UUID shall be generated at server-side.

ContentLicense: CC BY-SA 3.0

Title: Syncing localStorage

ContentLicense: CC BY-SA 4.0


问:
imbalanced dataset with Keras deep learning
I have a datasets that looks like this:  Training (Class 0: 471, Class 1: 986) Testing (Class 0: 177, Class 1: 246.
I split my data as 80% for training and 20% for validation.
I know that is an imbalanced dataset, and I have tried Class_weight but the problem remains.
I have retrained my Baseline CNN and I always have a result like as attached in the picture.
Could someone help me?

答:
I faced a similar problem while classifying events in 5 imbalanced categories. I found this loss function that implement a weighted categorical cross-entropy: https://gist.github.com/noparade/aaa8584e6e90ad64936e333e4e08ca5f
Combined with the Nadam optimizer, it allowed me to get over 95% true positive for all my categories.</p>


问:
SqlServer 2019 using table and scalar function into cursor
I occurred a strange error:

Msg 596, Level 21, State 1, Line 0

Cannot continue the execution because the session is in the kill
  state.

It seems that error is generated when I use a cursor like :

```<code>DECLARE dbCursor CURSOR
            FOR
                SELECT (SELECT TOP 1 VAL FROM dbo.fn_Table('n:',dbo.[fn_Scalar](var)) ORDER BY VAL)
                from table
</code>```

If I taken the select to run it, it is ok.

If in cursor I execute only fn_Table OR fn_Scalar, it is ok.

If in cursor I execute BOTH functions, I have the above error.

In older versions of SQL server (than 2019) the cursor is running properly.

Could you, please, give me an idea?

Thank you.

L.E.
The functions are:
ALTER function [dbo].[UrlDecode](@url nvarchar(max))
returns nvarchar(max)
as
begin
    declare @foo datetime=getdate();

DECLARE @Position INT,
        @Base CHAR(16),
        @High TINYINT,
        @Low TINYINT,
        @Pattern CHAR(21)

```<code>SELECT  @Base = '0123456789abcdef',
    @Pattern = '%[%][0-9a-f][0-9a-f]%',
    @URL = REPLACE(@URL, '+', ' '),
    @Position = PATINDEX(@Pattern, @URL)

WHILE @Position > 0
    SELECT  @High = CHARINDEX(SUBSTRING(@URL, @Position + 1, 1), @Base COLLATE Latin1_General_CI_AS),
        @Low = CHARINDEX(SUBSTRING(@URL, @Position + 2, 1), @Base COLLATE Latin1_General_CI_AS),
        @URL = STUFF(@URL, @Position, 3, CHAR(16 * @High + @Low - 17)),
        @Position = PATINDEX(@Pattern, @URL)

RETURN  @URL
</code>```

end

ALTER FUNCTION [dbo].[Split] (@sep VARCHAR(32), @s VARCHAR(MAX))

RETURNS @t TABLE
    (
        val VARCHAR(MAX)
    )

AS
BEGIN

```<code>--declare @foo datetime=getdate();
--Remove separator if the case
IF RIGHT(LTRIM(RTRIM(@s)),1) = @sep
    SET @s = LEFT(LTRIM(RTRIM(@s)), LEN(LTRIM(RTRIM(@s))) - 1);

DECLARE @xml XML
SET @XML = N'<root><r>' + REPLACE(@s, @sep, '</r><r>') + '</r></root>'

INSERT INTO @t(val)
SELECT r.value('.','VARCHAR(250)') as Item
FROM @xml.nodes('//root/r') AS RECORDS(r)

RETURN
</code>```

END

And the cursor is:
DECLARE cursor_product CURSOR
FOR
select (SELECT TOP 1 VAL FROM dbo.split('n:',dbo.UrlDecode) ORDER BY VAL) from  ABSENTEE

OPEN cursor_product;

FETCH NEXT FROM cursor_product
WHILE @@FETCH_STATUS = 0
    BEGIN

```<code>    FETCH NEXT FROM cursor_product
END;
</code>```

CLOSE cursor_product;
DEALLOCATE cursor_product;

Please, ignore how is defined the cursor, the error occours, anyway.
Thank you.

答:
As it stands, you'll have to change the cursor's select statement (scalar udf-inlining was just a blind guess [function+sql2019 not working, but works pre-sql2019] , the problem is the cursor's execution) :

Option 1:

```<code>The answer of Marc Guillot (populate a table and iterate over that)
</code>```

Option 2: APPLY( function calls)

```<code>DECLARE cursor_product CURSOR FOR
select f.VAL
from ABSENTEE as a
cross /*outer ?*/ apply
(
    SELECT TOP 1 VAL
    FROM dbo.split('n:',dbo.UrlDecode(a.columnXYZ))
    ORDER BY VAL
) as f;
</code>```

Option 3: aggregation on ABSENTEE table

```<code>DECLARE cursor_product CURSOR FOR
select (SELECT TOP 1 VAL FROM dbo.split('n:',dbo.UrlDecode(columnXYZ)) ORDER BY VAL)
from ABSENTEE
group by ABSENTEE.columnXYZ, ABSENTEE.othercolumn(s)
</code>```

Option 4: windowed aggregation on the function's result

```<code>DECLARE cursor_product CURSOR FOR
select
    MIN(
          (SELECT TOP 1 VAL FROM dbo.split('n:',dbo.UrlDecode(columnXYZ)) ORDER BY VAL)
       ) over(partition by columnXYZ)
from ABSENTEE
</code>```

Body:
I occurred a strange error:

Msg 596, Level 21, State 1, Line 0

Cannot continue the execution because the session is in the kill
  state.

It seems that error is generated when I use a cursor like :

DECLARE dbCursor CURSOR
            FOR
                SELECT (SELECT TOP 1 VAL FROM dbo.fn_Table('n:',dbo.[fn_Scalar](var)) ORDER BY VAL)
                from table

If I taken the select to run it, it is ok.

If in cursor I execute only fn_Table OR fn_Scalar, it is ok.

If in cursor I execute BOTH functions, I have the above error.

In older versions of SQL server (than 2019) the cursor is running properly.

Could you, please, give me an idea?

Thank you.

L.E.
The functions are:
ALTER function [dbo].[UrlDecode](@url nvarchar(max))
returns nvarchar(max)
as
begin
    declare @foo datetime=getdate();

DECLARE @Position INT,
        @Base CHAR(16),
        @High TINYINT,
        @Low TINYINT,
        @Pattern CHAR(21)

SELECT  @Base = '0123456789abcdef',
    @Pattern = '%[%][0-9a-f][0-9a-f]%',
    @URL = REPLACE(@URL, '+', ' '),
    @Position = PATINDEX(@Pattern, @URL)

WHILE @Position > 0
    SELECT  @High = CHARINDEX(SUBSTRING(@URL, @Position + 1, 1), @Base COLLATE Latin1_General_CI_AS),
        @Low = CHARINDEX(SUBSTRING(@URL, @Position + 2, 1), @Base COLLATE Latin1_General_CI_AS),
        @URL = STUFF(@URL, @Position, 3, CHAR(16 * @High + @Low - 17)),
        @Position = PATINDEX(@Pattern, @URL)

RETURN  @URL

end

ALTER FUNCTION [dbo].[Split] (@sep VARCHAR(32), @s VARCHAR(MAX))

RETURNS @t TABLE
    (
        val VARCHAR(MAX)
    )

AS
BEGIN

--declare @foo datetime=getdate();
--Remove separator if the case
IF RIGHT(LTRIM(RTRIM(@s)),1) = @sep
    SET @s = LEFT(LTRIM(RTRIM(@s)), LEN(LTRIM(RTRIM(@s))) - 1);

DECLARE @xml XML
SET @XML = N'<root><r>' + REPLACE(@s, @sep, '</r><r>') + '</r></root>'

INSERT INTO @t(val)
SELECT r.value('.','VARCHAR(250)') as Item
FROM @xml.nodes('//root/r') AS RECORDS(r)

RETURN

END

And the cursor is:
DECLARE cursor_product CURSOR
FOR
select (SELECT TOP 1 VAL FROM dbo.split('n:',dbo.UrlDecode) ORDER BY VAL) from  ABSENTEE

OPEN cursor_product;

FETCH NEXT FROM cursor_product
WHILE @@FETCH_STATUS = 0
    BEGIN

    FETCH NEXT FROM cursor_product
END;

CLOSE cursor_product;
DEALLOCATE cursor_product;

Please, ignore how is defined the cursor, the error occours, anyway.
Thank you.

Body:
As it stands, you'll have to change the cursor's select statement (scalar udf-inlining was just a blind guess [function+sql2019 not working, but works pre-sql2019] , the problem is the cursor's execution) :

Option 1:

The answer of Marc Guillot (populate a table and iterate over that)

Option 2: APPLY( function calls)

DECLARE cursor_product CURSOR FOR
select f.VAL
from ABSENTEE as a
cross /*outer ?*/ apply
(
    SELECT TOP 1 VAL
    FROM dbo.split('n:',dbo.UrlDecode(a.columnXYZ))
    ORDER BY VAL
) as f;

Option 3: aggregation on ABSENTEE table

DECLARE cursor_product CURSOR FOR
select (SELECT TOP 1 VAL FROM dbo.split('n:',dbo.UrlDecode(columnXYZ)) ORDER BY VAL)
from ABSENTEE
group by ABSENTEE.columnXYZ, ABSENTEE.othercolumn(s)

Option 4: windowed aggregation on the function's result

DECLARE cursor_product CURSOR FOR
select
    MIN(
          (SELECT TOP 1 VAL FROM dbo.split('n:',dbo.UrlDecode(columnXYZ)) ORDER BY VAL)
       ) over(partition by columnXYZ)
from ABSENTEE


问:
Why implicit property declaration in PHP?
I'm wondering why the PHP language allows implicit property declaration when most languages need to define properties within the class declaration itself (see code below). Is there a practical use for this type of coding style?</p>

```<code>$user1 = new User();
$user1->name = "Kylie";
echo $user1->name;

class User{}
</code>```

答: I'd say this comes from php having been and still being rather lax about it's data types, and to maintain at least a bit of downward compatibility for scripts which have been written in a earlier php version (<5).</p>

Body:
I'm wondering why the PHP language allows implicit property declaration when most languages need to define properties within the class declaration itself (see code below). Is there a practical use for this type of coding style?

$user1 = new User();
$user1->name = "Kylie";
echo $user1->name;

class User{}


问:
Sheets Arrayformula with IF, AND & OR
I really need some help.

Is it possible to create an arrayformula in Google Sheets for this:

```<code>=
IF(AND(OR($F3>0,$G3>0),$G$1=TRUE),"A",
IF(AND(OR($H3>0,$I3>0),$I$1=True),"B",
IF(AND(OR($J3>0,$K3>0),$K$1=True),"C",
IF(AND(OR($L3>0,$M3>0),$M$1=True),"D",
""))))
</code>```

I would like the arrayformula to cover each of the columns above e.g. F3:F>0, G3:G>0, etc.

Many, many thanks in advance.

Title: Sheets Arrayformula with IF, AND & OR

Body:
I really need some help.

Is it possible to create an arrayformula in Google Sheets for this:

=
IF(AND(OR($F3>0,$G3>0),$G$1=TRUE),"A",
IF(AND(OR($H3>0,$I3>0),$I$1=True),"B",
IF(AND(OR($J3>0,$K3>0),$K$1=True),"C",
IF(AND(OR($L3>0,$M3>0),$M$1=True),"D",
""))))

I would like the arrayformula to cover each of the columns above e.g. F3:F>0, G3:G>0, etc.

Many, many thanks in advance.

Body:
try:

=ARRAYFORMULA(
 IF((((F3:F>0)+(G3:G>0))*(G1=TRUE)); "A";
 IF((((H3:H>0)+(I3:I>0))*(I1=TRUE)); "B";
 IF((((J3:J>0)+(K3:K>0))*(K1=TRUE)); "C";
 IF((((L3:L>0)+(M3:M>0))*(M1=TRUE)); "D"; )))))


答:
Just replaced onClick event in refresh button. Hope this help you.

if (location.hash != '') {
  openPage('Settings', this, 'orange');
}

function refresh() {
  if (history.pushState) {
    var url = (location.href).replace("#setting", '');
    history.pushState(null, null, url + '#setting');
    location.reload();
  }
}

function openPage(pageName, elmnt, color) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablink");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].style.backgroundColor = "";
  }
  document.getElementById(pageName).style.display = "block";
  elmnt.style.backgroundColor = color;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="tablink" onclick="openPage('Settings', this, 'orange')">Settings</button>
<button class="tablink" onclick="openPage('About', this, 'orange')">About</button>

<div id="About" class="tabcontent">
  <h3>About:</h3>
  <input type="button" value="Refresh" onclick="refresh()" />
</div></code>```

Body:
Just replaced onClick event in refresh button. Hope this help you.

if (location.hash != '') {
  openPage('Settings', this, 'orange');
}

function refresh() {
  if (history.pushState) {
    var url = (location.href).replace("#setting", '');
    history.pushState(null, null, url + '#setting');
    location.reload();
  }
}

function openPage(pageName, elmnt, color) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablink");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].style.backgroundColor = "";
  }
  document.getElementById(pageName).style.display = "block";
  elmnt.style.backgroundColor = color;
}

<button class="tablink" onclick="openPage('Settings', this, 'orange')">Settings</button>
<button class="tablink" onclick="openPage('About', this, 'orange')">About</button>

<div id="About" class="tabcontent">
  <h3>About:</h3>
  <input type="button" value="Refresh" onclick="refresh()" />
</div>


问:
Create instance using Activator
I got some troubles with Activator.CreateInstance. It throws "Constructor on type not found" exception.

Here is the method where error occurs:

```<code>private static void InitializeInternalProperty(Calculation calculation, Type type, IDataProvider dataProvider, params string[] precedants)
{
    PropertiesCollection precedantsCollection = new PropertiesCollection(); //Properties collection implements IKeyedCollection
    foreach (string precedant in precedants)
    {
        precedantsCollection.Add(calculation.properties[precedant]);
    }
    calculation.properties.Add((Property)Activator.CreateInstance(type, dataProvider, precedantsCollection));
}
</code>```

Here is the constructor, i am trying to use:

```<code>internal CountryRiskPremium(IDataProvider dataProvider, PropertiesCollection precedants)
{
    Name = Names.CountryRiskPremium;
    InitLinks(precedants);
    _dataProvider = dataProvider;
}
</code>```

I also tried:

```<code>object[] arguments = new object[2];
arguments[0] = dataProvider;
arguments[1] = precedantsCollection;
calculation.properties.Add((Property)Activator.CreateInstance(type, arguments));
</code>```

答: Activator only works with public constructors, with the simple overload of CreateInstance that you are using. For using private/protected/internal constructors, you need to use another overload. See https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance.

Title: Create instance using Activator

Body:
I got some troubles with Activator.CreateInstance. It throws "Constructor on type not found" exception.

Here is the method where error occurs:

private static void InitializeInternalProperty(Calculation calculation, Type type, IDataProvider dataProvider, params string[] precedants)
{
    PropertiesCollection precedantsCollection = new PropertiesCollection(); //Properties collection implements IKeyedCollection
    foreach (string precedant in precedants)
    {
        precedantsCollection.Add(calculation.properties[precedant]);
    }
    calculation.properties.Add((Property)Activator.CreateInstance(type, dataProvider, precedantsCollection));
}

Here is the constructor, i am trying to use:

internal CountryRiskPremium(IDataProvider dataProvider, PropertiesCollection precedants)
{
    Name = Names.CountryRiskPremium;
    InitLinks(precedants);
    _dataProvider = dataProvider;
}

I also tried:

object[] arguments = new object[2];
arguments[0] = dataProvider;
arguments[1] = precedantsCollection;
calculation.properties.Add((Property)Activator.CreateInstance(type, arguments));


问:
Replace text link with image: CSS problem
I'm using Technique #8 from Nine Techniques for CSS Image Replacement but I'm not seeing the results I expect: instead of nicely positioned images, I'm getting... well, look for yourself:

http://beatchamber.officemedic.net

One change I've made to the technique is to change all the width: 100%/height: 100% values to the actual sizes; without that the images didn't display at all. I'm baffled, however, as to why the technique isn't working. Any suggestions?

答: The reason is because your background images are larger than the space you want to put them in. Also, your background images have a fair amount of "padding" on the outside of them, lending to that strange spacing where the text starts. If you added more height/width to your list elements, or changed the padding, you could get them looking like you want them to. As-is, though, they get cut off by the 25px/75px width/height.</p>


问:
SwiftUI Transitions of Conditional Child Views
I'm trying to understand and experiment with swiftUI view transitions and could use some insight into why the following does not work the way I expect:

```<code>struct ContentView: View {
@State private var showOverlay: Bool = false

var body: some View {
    ZStack {
        VStack {
            Button(action: {
                withAnimation(.easeInOut) {
                    self.showOverlay = true
                }
            }) {
                Text("Hello, World!")
            }
        }
        .zIndex(0)
        .animation(nil)
        .blur(radius: showOverlay ? 3 : 0)

        if showOverlay {
            HStack {
                Button(action: {
                    withAnimation(.easeInOut) {
                        self.showOverlay = false
                    }
                }) {
                    Text("Close")
                }
                .frame(width: 80, height: 80)
                .background(Color.red)
                .transition(.move(edge: .top))

                Button(action: {
                    withAnimation(.easeInOut) {
                        self.showOverlay = false
                    }
                }) {
                    Text("Close")
                }
                .frame(width: 80, height: 80)
                .background(Color.red)
                .transition(.move(edge: .bottom))
            }
            .zIndex(1.0)
        }
    }
}
</code>```

There is a conditional HStack of two buttons.
When the @State parameter showOverlay is changed it is done within a withAnimation block.
The transitions on the individual buttons are not honored.

If I remove the HStack, and put the zIndex(1) on each button, then the removal transition occurs, but not the insertion transition.

I want both buttons to transition in their designated ways when their group is added to the view.

Questions:
Why does wrapping in an HStack cause the inner transitions to be ignored?
Why does the edge transition only work in 1 direction?

答:
In order to get two different animations, you can pull the conditional logic closer to the buttons, i.e., inside the HStack:

```<code>HStack {
  if showOverlay {
    Button(action: {
      withAnimation(.easeInOut) {
        self.showOverlay = false
      }
    }) {
      Text("Close")
    }
    .frame(width: 80, height: 80)
    .background(Color.red)
    .transition(.move(edge: .top))

    Button(action: {
      withAnimation(.easeInOut) {
        self.showOverlay = false
      }
    }) {
      Text("Close")
    }
    .frame(width: 80, height: 80)
    .background(Color.red)
    .transition(.move(edge: .bottom))
  }
}
.zIndex(1.0)
</code>```

This leaves you with an empty HStack when showOverlay == false, but that shouldn't be much of a problem, at least in this example.

Body:
I'm trying to understand and experiment with swiftUI view transitions and could use some insight into why the following does not work the way I expect:

struct ContentView: View {
@State private var showOverlay: Bool = false

var body: some View {
    ZStack {
        VStack {
            Button(action: {
                withAnimation(.easeInOut) {
                    self.showOverlay = true
                }
            }) {
                Text("Hello, World!")
            }
        }
        .zIndex(0)
        .animation(nil)
        .blur(radius: showOverlay ? 3 : 0)

        if showOverlay {
            HStack {
                Button(action: {
                    withAnimation(.easeInOut) {
                        self.showOverlay = false
                    }
                }) {
                    Text("Close")
                }
                .frame(width: 80, height: 80)
                .background(Color.red)
                .transition(.move(edge: .top))

                Button(action: {
                    withAnimation(.easeInOut) {
                        self.showOverlay = false
                    }
                }) {
                    Text("Close")
                }
                .frame(width: 80, height: 80)
                .background(Color.red)
                .transition(.move(edge: .bottom))
            }
            .zIndex(1.0)
        }
    }
}

There is a conditional HStack of two buttons.
When the @State parameter showOverlay is changed it is done within a withAnimation block.
The transitions on the individual buttons are not honored.

If I remove the HStack, and put the zIndex(1) on each button, then the removal transition occurs, but not the insertion transition.

I want both buttons to transition in their designated ways when their group is added to the view.

Questions:
Why does wrapping in an HStack cause the inner transitions to be ignored?
Why does the edge transition only work in 1 direction?

Body:
In order to get two different animations, you can pull the conditional logic closer to the buttons, i.e., inside the HStack:

HStack {
  if showOverlay {
    Button(action: {
      withAnimation(.easeInOut) {
        self.showOverlay = false
      }
    }) {
      Text("Close")
    }
    .frame(width: 80, height: 80)
    .background(Color.red)
    .transition(.move(edge: .top))

    Button(action: {
      withAnimation(.easeInOut) {
        self.showOverlay = false
      }
    }) {
      Text("Close")
    }
    .frame(width: 80, height: 80)
    .background(Color.red)
    .transition(.move(edge: .bottom))
  }
}
.zIndex(1.0)

This leaves you with an empty HStack when showOverlay == false, but that shouldn't be much of a problem, at least in this example.


问:
How do you manage developing with multiple versions of Grails using Windows?
We've been using Grails for a little while now and have been through a few Grails versions now. We don't always want to migrate our 'older' apps immediately but often use a newer version for new development. Changing the Windows environment variables is inconvenient since I sometimes have to work on two related projects at the same time that are running different versions of Grails.

In Linux, I'd probably create wrapper scripts or aliases to allow me to specify on the command line a version switch but I don't believe Grails supports this.

How are others that need to code against multiple versions of Grails managing it?

Update:

I created a gv.bat file to set the GRAILS\_HOME and PATH environment variables. I added a GRAILS\_INSTALLS environment variable (c:\usr\local\grails on my box) and removed the %GRAILS_HOME%\bin reference from my PATH.

gv.bat

```<code>@echo off
SET GRAILS_HOME=%GRAILS_INSTALLS%\grails-%1
SET PATH=%GRAILS_HOME%\bin;%PATH%
</code>```

To do any Grails work I run > gv 1.1.2 or whatever version I need to work with. I'd like to figure out how to do a string replace in the PATH to change the value but that turned out to be difficult for me

答:
Some answers are outdated.

Seems that the best option nowadays is SDKMAN!:

SDKMAN! installs smoothly on Mac OSX, Linux, WLS, Cygwin, Solaris and FreeBSD. We also support Bash and ZSH shells.

Is also possible to install on Windows, but SDKMAN "can not be installed natively on Windows and requires WLS, Cygwin or MSYS+MinGW".

After that, you can choose the Grails SDK and which version you want. For example:

```<code>sdk install grails 1.3.7
</code>```

Body:
We've been using Grails for a little while now and have been through a few Grails versions now. We don't always want to migrate our 'older' apps immediately but often use a newer version for new development. Changing the Windows environment variables is inconvenient since I sometimes have to work on two related projects at the same time that are running different versions of Grails.

In Linux, I'd probably create wrapper scripts or aliases to allow me to specify on the command line a version switch but I don't believe Grails supports this.

How are others that need to code against multiple versions of Grails managing it?

Update:

I created a gv.bat file to set the GRAILS\_HOME and PATH environment variables. I added a GRAILS\_INSTALLS environment variable (c:\usr\local\grails on my box) and removed the %GRAILS_HOME%\bin reference from my PATH.

gv.bat

@echo off
SET GRAILS_HOME=%GRAILS_INSTALLS%\grails-%1
SET PATH=%GRAILS_HOME%\bin;%PATH%

To do any Grails work I run > gv 1.1.2 or whatever version I need to work with. I'd like to figure out how to do a string replace in the PATH to change the value but that turned out to be difficult for me

Body:
Some answers are outdated.

Seems that the best option nowadays is SDKMAN!:

SDKMAN! installs smoothly on Mac OSX, Linux, WLS, Cygwin, Solaris and FreeBSD. We also support Bash and ZSH shells.

Is also possible to install on Windows, but SDKMAN "can not be installed natively on Windows and requires WLS, Cygwin or MSYS+MinGW".

After that, you can choose the Grails SDK and which version you want. For example:

sdk install grails 1.3.7


问:
Getting and printing data in one loop
I have the following code:

```<code>def print_dsv_data():
    for d in self.data:
        print('#'.join(map(str, self.get_data(d))))
</code>```

I would like to create a method get_dsv_data() which gets the data in DSV format, meaning it would look like:

```<code>def get_dsv_data():
    r = []
    for d in self.data:
        r.append('#'.join(map(str, self.get_data(d))))
    return r

def print_dsv_data():
    for d in self.get_dsv_data:
        print(d)
</code>```

The problem with that soultion is that I loop through data twice and I'm trying to figure out how I can do it with one loop, something like:

```<code>def get_dsv_data():
    r = []
    for d in self.data:
        r.append('#'.join(map(str, self.get_data(d))))
    return r

def print_dsv_data():
    print(self.get_dsv_data())
</code>```

But that way I just print the list as is.
Is it possible to achive? If so, how can I do it?

答:
Why not set an optional argument in the get_dsv_data, which toggles a print function?

```<code>def get_dsv_data(print_flag=False, delimiter='#'):
    r = []
    for d in self.data:
        row_str = delimiter.join(map(str, self.get_data(d)))
        if print_flag:
            print(row_str)
        r.append(row_str)
    return r
</code>```

This way, you only loop once.

Title: Getting and printing data in one loop

Body:
I have the following code:

def print_dsv_data():
    for d in self.data:
        print('#'.join(map(str, self.get_data(d))))

I would like to create a method get_dsv_data() which gets the data in DSV format, meaning it would look like:

def get_dsv_data():
    r = []
    for d in self.data:
        r.append('#'.join(map(str, self.get_data(d))))
    return r

def print_dsv_data():
    for d in self.get_dsv_data:
        print(d)

The problem with that soultion is that I loop through data twice and I'm trying to figure out how I can do it with one loop, something like:

def get_dsv_data():
    r = []
    for d in self.data:
        r.append('#'.join(map(str, self.get_data(d))))
    return r

def print_dsv_data():
    print(self.get_dsv_data())

But that way I just print the list as is.
Is it possible to achive? If so, how can I do it?

Body:
Why not set an optional argument in the get_dsv_data, which toggles a print function?

def get_dsv_data(print_flag=False, delimiter='#'):
    r = []
    for d in self.data:
        row_str = delimiter.join(map(str, self.get_data(d)))
        if print_flag:
            print(row_str)
        r.append(row_str)
    return r

This way, you only loop once.


问:
Django mail send_mail uses host IP instead of hostname returned by getfqdn
According to the documentation, django default backend uses smtplib.

I am using django email to send emails in the following manner:

```<code>email = EmailMessage(
    'Object',
    'body',
    my_from_addr,
    args.emails,
    [],
    reply_to=['my_from_addr'],
)
</code>```

with the following configuration in settings.py :

```<code>EMAIL_HOST = "mail_server.lan"
EMAIL_PORT = 25
</code>```

I need to set the helo/ehlo parameter to comply with the email server according to the sending server hostname. But django seems to be using the IP of the server instead of the hostname, until now my emails have been rejected with the error

```<code>smtplib.SMTPRecipientsRefused: {'args.emails': (450, b'4.7.1 Client host rejected: cannot find your hostname, [192.168.1.5]')}
</code>```

The smtplib documentation declares here

```<code>If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn().
</code>```

And this actually returns the proper hostname:

```<code>python3 -c 'import socket; print(socket.getfqdn())'
my_proper_hostname.lan
</code>```

Am I missing something? Why is django using the IP address instead of the real hostname?

答:
This seems to be misconfiguration on mail server mail_server.lan. not in django.

SMTPRecipientsRefused error indicates errors encountered while sending emails to recipients - and this operation is performed by smtp mail server.

It received message from django (as there are no connection errors) and tried to send individual email for each recipient (to / cc) of that message. And sending one of them failed.

Mail server makes similar helo / ehlo negotiation with upstream servers.

Does your mail server provides correct maildomain / hostname ? (ip in error message suggests that mail server is sending ip, not its domain).

Then, many servers will also check PTR record for your ip - first, resolve provided mail domain name to get ip, then resolve this ip back - to get PTR record - to check that it matches mail domain. PTR record usually can be set with your internet provider / hoster.

Body:
According to the documentation, django default backend uses smtplib.

I am using django email to send emails in the following manner:

email = EmailMessage(
    'Object',
    'body',
    my_from_addr,
    args.emails,
    [],
    reply_to=['my_from_addr'],
)

with the following configuration in settings.py :

EMAIL_HOST = "mail_server.lan"
EMAIL_PORT = 25

I need to set the helo/ehlo parameter to comply with the email server according to the sending server hostname. But django seems to be using the IP of the server instead of the hostname, until now my emails have been rejected with the error

smtplib.SMTPRecipientsRefused: {'args.emails': (450, b'4.7.1 Client host rejected: cannot find your hostname, [192.168.1.5]')}

The smtplib documentation declares here

If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn().

And this actually returns the proper hostname:

python3 -c 'import socket; print(socket.getfqdn())'
my_proper_hostname.lan

Am I missing something? Why is django using the IP address instead of the real hostname?


问:
Sass::SyntaxError: Undefined mixin 'background-image' in sproutcore sc-server
I am following the Sproutcore getting started guide from here: http://guides.sproutcore.com/getting_started.html

When I run sc-server inside the Sproutcore application directory and request http://localhost:4020/todos from the browser, I get the following error:

```<code>Sass::SyntaxError: Undefined mixin 'background-image'.
    ././tmp/chance/c252db965d416a210509d6610c706976.scss:79:in `background-image'
    ././tmp/chance/c252db965d416a210509d6610c706976.scss:79
    chance_main.css:2
...
</code>```

This is the section of the .scss file referred to:

```<code>    .sc-button {
79--> @include background-image(linear-gradient(#F9F9F9 1%, #DDD, #F2F2F2, #F7F7F7));
      border: 1px solid #828282;
      color: #000;
      float: right;
      padding: 0 5px;
</code>```

答:
OK, the problem had nothing to do with any of the other source files, but was due to a typo in my todo.js (the main application javascript file).
I had separated items in an associative array with a semicolon (;) instead of a comma (,).
The stack trace simply was not very helpful in this regard.</p>

Body:
I am following the Sproutcore getting started guide from here: http://guides.sproutcore.com/getting_started.html

When I run sc-server inside the Sproutcore application directory and request http://localhost:4020/todos from the browser, I get the following error:

Sass::SyntaxError: Undefined mixin 'background-image'.
    ././tmp/chance/c252db965d416a210509d6610c706976.scss:79:in `background-image'
    ././tmp/chance/c252db965d416a210509d6610c706976.scss:79
    chance_main.css:2
...

This is the section of the .scss file referred to:

    .sc-button {
79--> @include background-image(linear-gradient(#F9F9F9 1%, #DDD, #F2F2F2, #F7F7F7));
      border: 1px solid #828282;
      color: #000;
      float: right;
      padding: 0 5px;


问:
VueJS: dynamically set component's methods
I have a SPA application with single page components; I want to import certain methods for the component based on my route's name. How can I achieve that in Vue? Something like:</p>

```<code><template>
    <div>
        <div v-for="foo in customMethod()">{{foo.bar}}</div>
    </div>
</template>

<script>
export default {
    methods: {},

    mounted: function() {
        switch(this.$route.name) {
            case "route.name":
                this.methods = require('./external-script.js');
                break;
            case "another.route.name":
                this.methods = require('./another-external-script.js');
                break;
        }
    }
}

</script>
</code>```

答:
As Dan mentioned in comments, this is impossible. So I've approached Strategy pattern concept as suggested by Evandro. I'm importing the external files based on route name when component is mounted.

```<code><template>
    <div>
        <div v-for="foo in method1()">{{foo.bar}}</div>
    </div>
</template>

<script>
export default {
    data: function() {
        m: {},
        // ..
    },

    methods: {
        method1: function(params) {
            return m.method1(params)
        },

        method2: async function(params){
            return await m.method2(params, this.another_param);
        },

        // ...
    },

    mounted: function() {
        switch(this.$route.name) {
            case "route.name":
                this.m = require('./external-script.js');
                break;
            case "another.route.name":
                this.m = require('./another-external-script.js');
                break;
        }
    }
}

</script>
</code>```

Note that depending on how your component is mounted, including scripts based on route within mounted() may not always work.

Body:
I have a SPA application with single page components; I want to import certain methods for the component based on my route's name. How can I achieve that in Vue? Something like:

<template>

{{foo.bar}}

</template>

Body:
As Dan mentioned in comments, this is impossible. So I've approached Strategy pattern concept as suggested by Evandro. I'm importing the external files based on route name when component is mounted.

<template>
    <div>
        <div v-for="foo in method1()">{{foo.bar}}</div>
    </div>
</template>

<script>
export default {
    data: function() {
        m: {},
        // ..
    },

    methods: {
        method1: function(params) {
            return m.method1(params)
        },

        method2: async function(params){
            return await m.method2(params, this.another_param);
        },

        // ...
    },

    mounted: function() {
        switch(this.$route.name) {
            case "route.name":
                this.m = require('./external-script.js');
                break;
            case "another.route.name":
                this.m = require('./another-external-script.js');
                break;
        }
    }
}

</script>

Note that depending on how your component is mounted, including scripts based on route within mounted() may not always work.


问:
Getting exception jQuery must be included before Bootstrap's JavaScript
I am getting below exception

bootstrap.js:240 Uncaught TypeError:  Bootstrap's JavaScript requires
  jQuery. jQuery must be included before Bootstrap's JavaScript

at Object.jQueryDetection (bootstrap.js:240) at bootstrap.js:255 at
  bootstrap.js:9 at bootstrap.js:10

This is my code in Angular.json

```<code>"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts":
[
  "node_modules/jquery/dist/jquery.js",
  "node_modules/bootstrap/dist/js/bootstrap.js"
]
</code>```

How can I fix this issue?

答:
If you want to use bootstrap in your application, or if you already have in your project, make sure to include jQuery before including the bootstrap JavaScript file. Bootstrap’s JavaScript file requires jQuery.

```<code>"scripts": [ "node_modules/jquery/dist/jquery.min.js",
           "node_modules/bootstrap/dist/js/bootstrap.js"]
</code>```

After including jQuery, stop running your Angular CLI application. Then, re-run it using ng serve.

And then, if you want to use jQuery in your code at some point, all you have to do is to import it in whatever component you want to use jQuery.

```<code>import * as $ from 'jquery';
</code>```

or

```<code>declare var $: any;
</code>```

Body:
I am getting below exception

bootstrap.js:240 Uncaught TypeError:  Bootstrap's JavaScript requires
  jQuery. jQuery must be included before Bootstrap's JavaScript

at Object.jQueryDetection (bootstrap.js:240) at bootstrap.js:255 at
  bootstrap.js:9 at bootstrap.js:10

This is my code in Angular.json

"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts":
[
  "node_modules/jquery/dist/jquery.js",
  "node_modules/bootstrap/dist/js/bootstrap.js"
]

How can I fix this issue?

Body:
If you want to use bootstrap in your application, or if you already have in your project, make sure to include jQuery before including the bootstrap JavaScript file. Bootstrap’s JavaScript file requires jQuery.

"scripts": [ "node_modules/jquery/dist/jquery.min.js",
           "node_modules/bootstrap/dist/js/bootstrap.js"]

After including jQuery, stop running your Angular CLI application. Then, re-run it using ng serve.

And then, if you want to use jQuery in your code at some point, all you have to do is to import it in whatever component you want to use jQuery.

import * as $ from 'jquery';

or

declare var $: any;


问:
Restricting string length in XML Schema
I am new to XML and JAXB, I am trying to add the AdditionalDataDeposit field with restrictions to my XML schema so I can generate the POJO with Maven. When I try to build it in maven the error:

```<code>blahBlahBlahmsgfactory: Unable to parse input schema(s). Error messages should have been provided.
org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name
'LimitedString50' to a(n) 'type definition' component.
</code>```

my code:

Under AdditionalData complex type:

```<code><xs:element name="DEPOSIT" type="trmns:AdditionalDataDEPOSIT" minOccurs="0">
  <xs:annotation>
    <xs:documentation>Additional Deposit Data</xs:documentation>
  </xs:annotation>
</xs:element>
</code>```

then:

```<code>  <xs:complexType name="AdditionalDataDEPOSIT">
    <xs:annotation>
      <xs:documentation>Additional Deposit Data</xs:documentation>
    </xs:annotation>
    <xs:sequence>
      <xs:element name="depositorID" type="LimitedString50"/>
      <xs:element name="depositorNationality" type="LimitedString50"/>
      <xs:element name="fundSource" type="LimitedString50"/>
      <xs:element name="fullName" type="LimitedString100"/>
    </xs:sequence>
  </xs:complexType>
  <xs:simpleType name="LimitedString50">
    <xs:restriction base="xs:string">
      <xs:maxLength value="50" />
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="LimitedString100">
    <xs:restriction base="xs:string">
      <xs:maxLength value="100" />
    </xs:restriction>
  </xs:simpleType>
</code>```

I dont understand much of XML Schema's, but advice will be appreciated.

答:
Your XML schema so far I see has only one error: attribute "minOccurs" should not be defined for global elements. So the declaration of DEPOSIT element should look like this:

```<code><xs:element name="DEPOSIT" type="trmns:AdditionalDataDEPOSIT">
  <xs:annotation>
    <xs:documentation>Additional Deposit Data</xs:documentation>
  </xs:annotation>
</xs:element>
</code>```

An explanation regarding minOccurs for global elements is given e.g. here.

Title: Restricting string length in XML Schema

Body:
I am new to XML and JAXB, I am trying to add the AdditionalDataDeposit field with restrictions to my XML schema so I can generate the POJO with Maven. When I try to build it in maven the error:

blahBlahBlahmsgfactory: Unable to parse input schema(s). Error messages should have been provided.
org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name
'LimitedString50' to a(n) 'type definition' component.

my code:

Under AdditionalData complex type:

<xs:element name="DEPOSIT" type="trmns:AdditionalDataDEPOSIT" minOccurs="0">
  <xs:annotation>
    <xs:documentation>Additional Deposit Data</xs:documentation>
  </xs:annotation>
</xs:element>

then:

  <xs:complexType name="AdditionalDataDEPOSIT">
    <xs:annotation>
      <xs:documentation>Additional Deposit Data</xs:documentation>
    </xs:annotation>
    <xs:sequence>
      <xs:element name="depositorID" type="LimitedString50"/>
      <xs:element name="depositorNationality" type="LimitedString50"/>
      <xs:element name="fundSource" type="LimitedString50"/>
      <xs:element name="fullName" type="LimitedString100"/>
    </xs:sequence>
  </xs:complexType>
  <xs:simpleType name="LimitedString50">
    <xs:restriction base="xs:string">
      <xs:maxLength value="50" />
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="LimitedString100">
    <xs:restriction base="xs:string">
      <xs:maxLength value="100" />
    </xs:restriction>
  </xs:simpleType>

I dont understand much of XML Schema's, but advice will be appreciated.

Body:
Your XML schema so far I see has only one error: attribute "minOccurs" should not be defined for global elements. So the declaration of DEPOSIT element should look like this:

<xs:element name="DEPOSIT" type="trmns:AdditionalDataDEPOSIT">
  <xs:annotation>
    <xs:documentation>Additional Deposit Data</xs:documentation>
  </xs:annotation>
</xs:element>

An explanation regarding minOccurs for global elements is given e.g. here.


问:
How to perform set-like operations in pandas?
I need to fill a column with values, that are present in a set and not present in any other columns.

initial df

```<code>    c0  c1  c2  c3  c4  c5
0   4   5   6   3   2   1
1   1   5   4   0   2   3
2   5   6   4   0   1   3
3   5   4   6   2   0   1
4   5   6   4   0   1   3
5   0   1   4   5   6   2
</code>```

I need df['c6'] column that is a set-like difference operation product between a set of set([0,1,2,3,4,5,6]) and each row of df

so that the result df is

```<code>    c0  c1  c2  c3  c4  c5   c6
0   4   5   6   3   2   1    0
1   1   5   4   0   2   3    6
2   5   6   4   0   1   3    2
3   5   4   6   2   0   1    3
4   5   6   4   0   1   3    2
5   0   1   4   5   6   2    3
</code>```

Thank you!

答:
Use numpy setdiff1d to find the difference between the two arrays and assign the output to column c6    </p>

```<code>ck = np.array([0,1,2,3,4,5,6])
M = df.to_numpy()
df['c6'] = [np.setdiff1d(ck,i)[0] for i in M]

    c0  c1  c2  c3  c4  c5  c6
0   4   5   6   3   2   1   0
1   1   5   4   0   2   3   6
2   5   6   4   0   1   3   2
3   5   4   6   2   0   1   3
4   5   6   4   0   1   3   2
5   0   1   4   5   6   2   3
</code>```

Body:
I need to fill a column with values, that are present in a set and not present in any other columns.

initial df

    c0  c1  c2  c3  c4  c5
0   4   5   6   3   2   1
1   1   5   4   0   2   3
2   5   6   4   0   1   3
3   5   4   6   2   0   1
4   5   6   4   0   1   3
5   0   1   4   5   6   2

I need df['c6'] column that is a set-like difference operation product between a set of set([0,1,2,3,4,5,6]) and each row of df

so that the result df is

    c0  c1  c2  c3  c4  c5   c6
0   4   5   6   3   2   1    0
1   1   5   4   0   2   3    6
2   5   6   4   0   1   3    2
3   5   4   6   2   0   1    3
4   5   6   4   0   1   3    2
5   0   1   4   5   6   2    3

Thank you!

Body:
Use numpy setdiff1d to find the difference between the two arrays and assign the output to column c6

ck = np.array([0,1,2,3,4,5,6])
M = df.to_numpy()
df['c6'] = [np.setdiff1d(ck,i)[0] for i in M]

    c0  c1  c2  c3  c4  c5  c6
0   4   5   6   3   2   1   0
1   1   5   4   0   2   3   6
2   5   6   4   0   1   3   2
3   5   4   6   2   0   1   3
4   5   6   4   0   1   3   2
5   0   1   4   5   6   2   3


问:
How does Ceph use the STS service?
I want to use the STS service to generate temporary credentials for use by third-party clients.

I configured STS lite based on the documentation.

This is my configuration file:

```<code>[global]
fsid = 42a7cae1-84d1-423e-93f4-04b0736c14aa
mon_initial_members = admin, node1, node2, node3
mon_host = 192.168.199.81,192.168.199.82,192.168.199.83,192.168.199.84
auth_cluster_required = cephx
auth_service_required = cephx
auth_client_required = cephx

osd pool default size = 2

[client.rgw.admin]
rgw sts key = "1234567890"
rgw s3 auth use sts = true
</code>```

When I execute the getSessionToken method, return a 405 error:

```<code><Error>
    <Code>MethodNotAllowed</Code>
    <RequestId>tx000000000000000000003-005c73aed8-5e48-default</RequestId>
    <HostId>5e48-default-default</HostId>
</Error>
</code>```

This is my test code:

```<code>import os
import sys
import traceback

import boto3
from boto.s3.connection import S3Connection
from boto.sts import STSConnection

try:
    host = 'http://192.168.199.81:7480'
    access_key = '2324YFZ7QDEOSRL18QHR'
    secret_key = 'rL9FabxCOw5LDbrHtmykiGSCjzpKLmEs9WPiNjVJ'

    client = boto3.client('sts',
                          aws_access_key_id = access_key,
                          aws_secret_access_key = secret_key,
                          endpoint_url = host)
    response = client.get_session_token(DurationSeconds=999)
    print response
except:
    print traceback.format_exc()
</code>```

Can anyone tell me if my configuration is incorrect or if the version I tested does not provide STS service?

These are the versions I tested:

```<code>Ceph version 12.2.11 (26dc3775efc7bb286a1d6d66faee0ba30ea23eee) luminous (stable)
Ceph version 13.2.2 (02899bfda814146b021136e9d8e80eba494e1126) mimic (stable)
</code>```

答:
STS feature has been implemented since nautilus (14.2.x).

for more info: https://docs.ceph.com/docs/master/releases/nautilus/

Title: How does Ceph use the STS service?

Body:
I want to use the STS service to generate temporary credentials for use by third-party clients.

I configured STS lite based on the documentation.

This is my configuration file:

[global]
fsid = 42a7cae1-84d1-423e-93f4-04b0736c14aa
mon_initial_members = admin, node1, node2, node3
mon_host = 192.168.199.81,192.168.199.82,192.168.199.83,192.168.199.84
auth_cluster_required = cephx
auth_service_required = cephx
auth_client_required = cephx

osd pool default size = 2

[client.rgw.admin]
rgw sts key = "1234567890"
rgw s3 auth use sts = true

When I execute the getSessionToken method, return a 405 error:

<Error>
    MethodNotAllowed
    <RequestId>tx000000000000000000003-005c73aed8-5e48-default</RequestId>
    <HostId>5e48-default-default</HostId>
</Error>

This is my test code:

import os
import sys
import traceback

import boto3
from boto.s3.connection import S3Connection
from boto.sts import STSConnection

try:
    host = 'http://192.168.199.81:7480'
    access_key = '2324YFZ7QDEOSRL18QHR'
    secret_key = 'rL9FabxCOw5LDbrHtmykiGSCjzpKLmEs9WPiNjVJ'

    client = boto3.client('sts',
                          aws_access_key_id = access_key,
                          aws_secret_access_key = secret_key,
                          endpoint_url = host)
    response = client.get_session_token(DurationSeconds=999)
    print response
except:
    print traceback.format_exc()

Can anyone tell me if my configuration is incorrect or if the version I tested does not provide STS service?

These are the versions I tested:

Ceph version 12.2.11 (26dc3775efc7bb286a1d6d66faee0ba30ea23eee) luminous (stable)
Ceph version 13.2.2 (02899bfda814146b021136e9d8e80eba494e1126) mimic (stable)


问:
Show current video time on a timer (hours:minutes:seconds)
I have a simple timer which is displaying the current time of a video on my page. Sadly it's limited to only showing minutes and seconds, if the video duration is longer than the timer can handle, it will at some point start displaying an incorrect value.
After one hour, it will start displaying something like 61:01 (min:sec) And that's a real issue.

let video = document.querySelector('video');
let counter = document.querySelector('p');
let hrs, mins, secs;

window.setInterval(() => {
  mins = Math.floor(video.currentTime / 60);
  secs = Math.floor(video.currentTime % 60);
      if (secs < 10) {
        secs = '0' + String(secs);
      }
  counter.textContent = mins + ':' + secs;
},1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video controls src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" height='200px' width='330px'></video>
<p></p></code>```

Sadly I don't have any hour long videos to show the issue.... So could somebody please explain me how should I build this small function so it's capable of displaying hours? Right now I only found a buggy and very unreliable way but it's too pathetic for being shown here.

答:
Do you like?

```<code><video
  controls
  src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
  height="200px"
  width="330px"
></video>
<p></p>

<script>
  function secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor((d % 3600) / 60);
    var s = Math.floor((d % 3600) % 60);

    var hDisplay = h + ":";
    var mDisplay = m + ":";
    var sDisplay = s;

    return hDisplay + mDisplay + sDisplay;
  }

  let video = document.querySelector("video");
  let counter = document.querySelector("p");
  let hrs, mins, secs;

  window.setInterval(() => {
    counter.textContent = secondsToHms(video.currentTime);
  }, 0);
</script>
</code>```

Happy codding.

Body:
I have a simple timer which is displaying the current time of a video on my page. Sadly it's limited to only showing minutes and seconds, if the video duration is longer than the timer can handle, it will at some point start displaying an incorrect value.
After one hour, it will start displaying something like 61:01 (min:sec) And that's a real issue.

let video = document.querySelector('video');
let counter = document.querySelector('p');
let hrs, mins, secs;

window.setInterval(() => {
  mins = Math.floor(video.currentTime / 60);
  secs = Math.floor(video.currentTime % 60);
      if (secs < 10) {
        secs = '0' + String(secs);
      }
  counter.textContent = mins + ':' + secs;
},1000);

<video controls src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" height='200px' width='330px'></video>

Sadly I don't have any hour long videos to show the issue.... So could somebody please explain me how should I build this small function so it's capable of displaying hours? Right now I only found a buggy and very unreliable way but it's too pathetic for being shown here.

Body:
Do you like?

<video
  controls
  src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
  height="200px"
  width="330px"
></video>
<p></p>

<script>
  function secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor((d % 3600) / 60);
    var s = Math.floor((d % 3600) % 60);

    var hDisplay = h + ":";
    var mDisplay = m + ":";
    var sDisplay = s;

    return hDisplay + mDisplay + sDisplay;
  }

  let video = document.querySelector("video");
  let counter = document.querySelector("p");
  let hrs, mins, secs;

  window.setInterval(() => {
    counter.textContent = secondsToHms(video.currentTime);
  }, 0);
</script>

Happy codding.


问:
How to add clients logo on bottom Tab Bar
i am creating an android based mobile app using react native. I want to add a logo on my bottom tab. The tab bar also contains 4 tabs. I need to display a logo on left corner of my device. Logo is not a clickable one, just an image.</p>

答:
For React Navigation 5.
You can show custom BottomTabBar with tabBar options.

Define Tab stack

import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
const Tab = createBottomTabNavigator();
function MyTabs() {
  return (
    <Tab.Navigator tabBar={props => <BottomTabBar {...props} />}>
      <Tab.Screen name="Tab1" component={Screen3} />
      <Tab.Screen name="Tab2" component={Screen2} />
      <Tab.Screen name="Tab3" component={Screen2} />
      <Tab.Screen name="Tab4" component={Screen2} />
    </Tab.Navigator>
  );
}```
</div>
</div>
</p>

<ol start="2">
<li>Create Custom BottomTabBar</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import React from 'react';
import {View,Text,Image,Platform,TouchableOpacity,StyleSheet} from 'react-native';

const BottomTabBar = ({state, navigation, ...props}) => {
  const {routes = [], index: activeIndex} = state;
  return (
    <View style={styles.container}>
      <Image
        source={require('../../assets/logo.png')}
        style={styles.imageIcon}
      />
      <View style={styles.tabContainer}>
        {routes.map((it, index) => {
          return (
            <TouchableOpacity
              onPress={() => {
                navigation.jumpTo(it.name);
              }}
              style={[
                styles.tabButton,
                {
                  borderBottomWidth: activeIndex === index ? 1 : 0,
                },
              ]}>
              <Text>{it.name}</Text>
            </TouchableOpacity>
          );
        })}
      </View>
    </View>
  );
};
export default BottomTabBar;
const styles = StyleSheet.create({
  tabButton: {
    flex: 1,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomColor: 'red',
  },
  tabContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-evenly',
  },
  imageIcon: {
    width: 50,
    height: 50,
    resizeMode: 'contain',
  },
  container: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    height: 64,
    paddingHorizontal: 16,
    backgroundColor: 'white',
    paddingBottom: Platform.OS === 'ios' ? 15 : 0,
  },
});</code>```

ScreenShot

Body:
For React Navigation 5.
You can show custom BottomTabBar with tabBar options.

Define Tab stack

import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
const Tab = createBottomTabNavigator();
function MyTabs() {
  return (
    <Tab.Navigator tabBar={props => <BottomTabBar {...props} />}>
      <Tab.Screen name="Tab1" component={Screen3} />
      <Tab.Screen name="Tab2" component={Screen2} />
      <Tab.Screen name="Tab3" component={Screen2} />
      <Tab.Screen name="Tab4" component={Screen2} />
    </Tab.Navigator>
  );
}

Create Custom BottomTabBar

import React from 'react';
import {View,Text,Image,Platform,TouchableOpacity,StyleSheet} from 'react-native';

const BottomTabBar = ({state, navigation, ...props}) => {
  const {routes = [], index: activeIndex} = state;
  return (
    <View style={styles.container}>
      <Image
        source={require('../../assets/logo.png')}
        style={styles.imageIcon}
      />
      <View style={styles.tabContainer}>
        {routes.map((it, index) => {
          return (
            <TouchableOpacity
              onPress={() => {
                navigation.jumpTo(it.name);
              }}
              style={[
                styles.tabButton,
                {
                  borderBottomWidth: activeIndex === index ? 1 : 0,
                },
              ]}>
              <Text>{it.name}</Text>
            </TouchableOpacity>
          );
        })}
      </View>
    </View>
  );
};
export default BottomTabBar;
const styles = StyleSheet.create({
  tabButton: {
    flex: 1,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomColor: 'red',
  },
  tabContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-evenly',
  },
  imageIcon: {
    width: 50,
    height: 50,
    resizeMode: 'contain',
  },
  container: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    height: 64,
    paddingHorizontal: 16,
    backgroundColor: 'white',
    paddingBottom: Platform.OS === 'ios' ? 15 : 0,
  },
});

ScreenShot


问:
Sql 2016 - How to get only modified column in system-versioned temporal table
How to get only modified column in system-versioned temporal table.

I am using SQL 2016 system-versioned temporal table to track the changes. I have the history table populated with multiple rows which include modified and not modified columns for each version of row edit.

Is there any way to get only modified column value from history row data.

Appreciated your response.

Thanks

Abdul

答:
Thanks to @Abdul Azeez description, here is the sample code to achieve this goal:

Suppose that I have a table called MyTable, and I want to capture the changes on Name and LastName columns(both have varchar data type) FOR ALL the time.

```<code>;WITH T
AS (
    SELECT ID,
           LAG(Name) OVER (PARTITION BY ID ORDER BY SysStartTime, SysEndTime) AS Prev_Name,
           Name,
           LAG(LastName) OVER (PARTITION BY ID ORDER BY SysStartTime, SysEndTime) AS Prev_LastName,
           LastName,
           Email,
           SysStartTime,
           SysEndTime
    FROM dbo.MyTable FOR SYSTEM_TIME ALL
    WHERE Email = 'myEmail@somewhere.com'
)
SELECT T.SysStartTime,
       T.SysEndTime,
       C.ColName,
       C.prev_value,
       C.cur_value
FROM T
    CROSS APPLY
    (
        VALUES
            ('Name', T.Name, T.Prev_Name),
            ('LastName', T.LastName, T.Prev_LastName)
    ) AS C (ColName, cur_value, prev_value)
WHERE EXISTS
(
    SELECT cur_value
    EXCEPT
    SELECT C.prev_value
);
</code>```

Note: If the columns have different data types you might need to cast them to an appropriate data type.

Body:
Thanks to @Abdul Azeez description, here is the sample code to achieve this goal:

Suppose that I have a table called MyTable, and I want to capture the changes on Name and LastName columns(both have varchar data type) FOR ALL the time.

;WITH T
AS (
    SELECT ID,
           LAG(Name) OVER (PARTITION BY ID ORDER BY SysStartTime, SysEndTime) AS Prev_Name,
           Name,
           LAG(LastName) OVER (PARTITION BY ID ORDER BY SysStartTime, SysEndTime) AS Prev_LastName,
           LastName,
           Email,
           SysStartTime,
           SysEndTime
    FROM dbo.MyTable FOR SYSTEM_TIME ALL
    WHERE Email = 'myEmail@somewhere.com'
)
SELECT T.SysStartTime,
       T.SysEndTime,
       C.ColName,
       C.prev_value,
       C.cur_value
FROM T
    CROSS APPLY
    (
        VALUES
            ('Name', T.Name, T.Prev_Name),
            ('LastName', T.LastName, T.Prev_LastName)
    ) AS C (ColName, cur_value, prev_value)
WHERE EXISTS
(
    SELECT cur_value
    EXCEPT
    SELECT C.prev_value
);

Note: If the columns have different data types you might need to cast them to an appropriate data type.


问:
How to have a public APIG access a lambda inside a VPC?
I have a small web app deployed as an aws lambda that correctly operates when tested via the lambda management console. However running a test via the apig console yeilds this error:

```<code>Sun Jan 26 21:43:30 UTC 2020 : Execution failed due to configuration error: Invalid permissions on Lambda function
</code>```

However the apig is provisioned with the execute permission:

```<code>  apiGatewayRole:
    DependsOn:
      - squashApp
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - "apigateway.amazonaws.com"
            Action: "sts:AssumeRole"
      Path: "/"
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
      Policies:
        - PolicyName: "API_Service_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: "lambda:InvokeFunction"
                Resource: !GetAtt "squashApp.Arn"
                Effect: "Allow"
  lambdaApiGatewayInvoke:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "squashApp.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*/"
</code>```

Previously the permission was sufficient (The IAM policy is recently added) to permit the lambda invocation. The error started occuring after I moved the lambda inside a VPC.

```<code>squashApp:
    Type: AWS::Lambda::Function
    Properties:
      Environment:
        Variables:
          GO_ENV: production
          DB_HOST: !GetAtt "squashRDS.Endpoint.Address"
          DB_PORT: !GetAtt "squashRDS.Endpoint.Port"
          DB_USER_NAME: !Sub "${rdsUser}"
          DB_USER_PASS: !Sub "${rdsPassword}"
      Code:
        S3Bucket: '${lambdaHandoffBucket}'
        S3Key: !Sub 'functions/${lambdaVersion}/${lambdaHash}' # TODO make parameter
      Handler: 'app'
      Role: !GetAtt "squashLambdaRole.Arn"
      Runtime: 'go1.x'
      Timeout: 2
      FunctionName: !Ref "lambdaFunctionName"
      VpcConfig:
        SecurityGroupIds:
          - !Ref "lambdaSecurtiyGroup"
        SubnetIds:
          - !Ref "privateSubnet1"
          - !Ref "privateSubnet2"
  vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.192.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
  privateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.21.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "PrimaryAZ"
      Tags:
        - Key: Name
          Value: !Sub ${apiGatewayStageName} Private Subnet (AZ1)
  privateSubnet2:
    Type: "AWS::EC2::Subnet"
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.30.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "SecondaryAZ"

  privateRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  privateRouteTable2:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  noIngressSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: "no-ingress-sg"
      GroupDescription: "Security group with no ingress rule"
      VpcId: !Ref vpc
</code>```

The full cloud formation resource section:

```<code>Resources:
  apiGateway:
    Type: "AWS::ApiGateway::RestApi"
    Properties:
      Name: "SquashAPI"
      Description: "Squash Box Ladder"

  apiGatewayRootMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      AuthorizationType: "NONE"
      # This can be ANY | GET| POST | etc and references the api http method as seen by a client
      HttpMethod: "ANY"
      Integration:
        # This must be post or the integration between gateway and lambda fails
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt "squashApp.Arn"
      ResourceId: !GetAtt "apiGateway.RootResourceId"
      RestApiId: !Ref "apiGateway"

  apiGatewayCatchAllProxy:
    Type: AWS::ApiGateway::Resource
    Properties:
      PathPart: "{proxy+}"
      RestApiId: !Ref "apiGateway"
      ParentId: !GetAtt "apiGateway.RootResourceId"

  apiGatewayCatchAllMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      AuthorizationType: "NONE"
      HttpMethod: "ANY"
      Integration:
        # This must be post or the integration between gateway and lambda fails
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt "squashApp.Arn"
      ResourceId: !Ref "apiGatewayCatchAllProxy"
      RestApiId: !Ref "apiGateway"

  apiGatewayDeployment:
    Type: "AWS::ApiGateway::Deployment"
    DependsOn:
      - "apiGatewayRootMethod"
      - "apiGatewayCatchAllMethod"
    Properties:
      RestApiId: !Ref "apiGateway"
      StageName: !Ref "apiGatewayStageName"

  squashApp:
    Type: AWS::Lambda::Function
    Properties:
      Environment:
        Variables:
          GO_ENV: production
          DB_HOST: !GetAtt "squashRDS.Endpoint.Address"
          DB_PORT: !GetAtt "squashRDS.Endpoint.Port"
          DB_USER_NAME: !Sub "${rdsUser}"
          DB_USER_PASS: !Sub "${rdsPassword}"
      Code:
        S3Bucket: '${lambdaHandoffBucket}'
        S3Key: !Sub 'functions/${lambdaVersion}/${lambdaHash}' # TODO make parameter
      Handler: 'app'
      Role: !GetAtt "squashLambdaRole.Arn"
      Runtime: 'go1.x'
      Timeout: 2
      FunctionName: !Ref "lambdaFunctionName"
      VpcConfig:
        SecurityGroupIds:
          - !Ref "lambdaSecurtiyGroup"
        SubnetIds:
          - !Ref "privateSubnet1"
          - !Ref "privateSubnet2"

  lambdaSecurtiyGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: For Lambda Application
      VpcId: !Ref vpc

  lambdaEgres:
    Type: AWS::EC2::SecurityGroupEgress
    Properties:
      GroupId: !Ref lambdaSecurtiyGroup
      IpProtocol: tcp
      FromPort: !GetAtt "squashRDS.Endpoint.Port"
      ToPort: !GetAtt "squashRDS.Endpoint.Port"
      CidrIp: !GetAtt 'vpc.CidrBlock'

  lambdaApiGatewayInvoke:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "squashApp.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*/"

  squashLambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action:
              - "sts:AssumeRole"
            Effect: "Allow"
            Principal:
              Service:
                - "lambda.amazonaws.com"
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
      Policies:
        - PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Effect: "Allow"
                Resource:
                  - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${lambdaFunctionName}:*"
          PolicyName: "lambda"

  lambdaLogGroup:
    Type: "AWS::Logs::LogGroup"
    Properties:
      LogGroupName: !Sub "/aws/lambda/${lambdaFunctionName}"
      RetentionInDays: 14
  apiGatewayRole:
    DependsOn:
      - squashApp
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - "apigateway.amazonaws.com"
            Action: "sts:AssumeRole"
      Path: "/"
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
      Policies:
        - PolicyName: "API_Service_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: "lambda:InvokeFunction"
                Resource: !GetAtt "squashApp.Arn"
                Effect: "Allow"
  apiGwAccountConfig:
    Type: "AWS::ApiGateway::Account"
    Properties:
      CloudWatchRoleArn: !GetAtt "apiGatewayRole.Arn"
  squashRDS:
    Type: AWS::RDS::DBInstance
    Properties:
      DBInstanceClass: db.t2.micro
      AllocatedStorage: 20
      StorageType: "gp2"
      Engine: "postgres"
      MasterUsername: !Sub "${rdsUser}"
      MasterUserPassword: !Sub "${rdsPassword}"
      DBSubnetGroupName: !Ref "rdsSubnetGroup"
      VPCSecurityGroups:
        - !Ref rdsSecurityGroup
    DeletionPolicy: Snapshot

  rdsSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: For RDS Instance
      VpcId: !Ref vpc
      Tags:
        - Key: Name
          Value: RDS-SecurityGroup

  rdsSubnetGroup:
    Type: "AWS::RDS::DBSubnetGroup"
    Properties:
      DBSubnetGroupName: "RDS Subnet Group"
      DBSubnetGroupDescription: Subnet including the RDS into the VPC
      SubnetIds:
        - !Ref "privateSubnet1"
        - !Ref "privateSubnet2"

  rdsIngres:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref rdsSecurityGroup
      IpProtocol: tcp
      FromPort: !GetAtt "squashRDS.Endpoint.Port"
      ToPort: !GetAtt "squashRDS.Endpoint.Port"
      CidrIp: !GetAtt 'vpc.CidrBlock'

  vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.192.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
  privateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.21.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "PrimaryAZ"
  privateSubnet2:
    Type: "AWS::EC2::Subnet"
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.30.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "SecondaryAZ"

  privateRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  privateRouteTable2:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1

  noIngressSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: "no-ingress-sg"
      GroupDescription: "Security group with no ingress rule"
      VpcId: !Ref vpc

Outputs:
  apiGatewayInvokeURL:
    Value: !Sub "https://${apiGateway}.execute-api.${AWS::Region}.amazonaws.com/${apiGatewayStageName}"

  lambdaArn:
    Value: !GetAtt "squashApp.Arn"
</code>```

答:
The only thing I can think of is, the API gateway source Arn should end with a resource path. In your case, it ends with a /.

I would add an * at the end to allow any resource path to invoke the lambda. You can change it to a specific path once you get it working.

```<code>lambdaApiGatewayInvoke:
  Type: "AWS::Lambda::Permission"
  Properties:
    Action: "lambda:InvokeFunction"
    FunctionName: !GetAtt "squashApp.Arn"
    Principal: "apigateway.amazonaws.com"
    SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*/*"
</code>```

hope this helps. good luck.

Body:
I have a small web app deployed as an aws lambda that correctly operates when tested via the lambda management console. However running a test via the apig console yeilds this error:

Sun Jan 26 21:43:30 UTC 2020 : Execution failed due to configuration error: Invalid permissions on Lambda function

However the apig is provisioned with the execute permission:

  apiGatewayRole:
    DependsOn:
      - squashApp
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - "apigateway.amazonaws.com"
            Action: "sts:AssumeRole"
      Path: "/"
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
      Policies:
        - PolicyName: "API_Service_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: "lambda:InvokeFunction"
                Resource: !GetAtt "squashApp.Arn"
                Effect: "Allow"
  lambdaApiGatewayInvoke:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "squashApp.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*/"

Previously the permission was sufficient (The IAM policy is recently added) to permit the lambda invocation. The error started occuring after I moved the lambda inside a VPC.

squashApp:
    Type: AWS::Lambda::Function
    Properties:
      Environment:
        Variables:
          GO_ENV: production
          DB_HOST: !GetAtt "squashRDS.Endpoint.Address"
          DB_PORT: !GetAtt "squashRDS.Endpoint.Port"
          DB_USER_NAME: !Sub "${rdsUser}"
          DB_USER_PASS: !Sub "${rdsPassword}"
      Code:
        S3Bucket: '${lambdaHandoffBucket}'
        S3Key: !Sub 'functions/${lambdaVersion}/${lambdaHash}' # TODO make parameter
      Handler: 'app'
      Role: !GetAtt "squashLambdaRole.Arn"
      Runtime: 'go1.x'
      Timeout: 2
      FunctionName: !Ref "lambdaFunctionName"
      VpcConfig:
        SecurityGroupIds:
          - !Ref "lambdaSecurtiyGroup"
        SubnetIds:
          - !Ref "privateSubnet1"
          - !Ref "privateSubnet2"
  vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.192.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
  privateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.21.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "PrimaryAZ"
      Tags:
        - Key: Name
          Value: !Sub ${apiGatewayStageName} Private Subnet (AZ1)
  privateSubnet2:
    Type: "AWS::EC2::Subnet"
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.30.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "SecondaryAZ"

  privateRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  privateRouteTable2:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  noIngressSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: "no-ingress-sg"
      GroupDescription: "Security group with no ingress rule"
      VpcId: !Ref vpc

The full cloud formation resource section:

Resources:
  apiGateway:
    Type: "AWS::ApiGateway::RestApi"
    Properties:
      Name: "SquashAPI"
      Description: "Squash Box Ladder"

  apiGatewayRootMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      AuthorizationType: "NONE"
      # This can be ANY | GET| POST | etc and references the api http method as seen by a client
      HttpMethod: "ANY"
      Integration:
        # This must be post or the integration between gateway and lambda fails
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt "squashApp.Arn"
      ResourceId: !GetAtt "apiGateway.RootResourceId"
      RestApiId: !Ref "apiGateway"

  apiGatewayCatchAllProxy:
    Type: AWS::ApiGateway::Resource
    Properties:
      PathPart: "{proxy+}"
      RestApiId: !Ref "apiGateway"
      ParentId: !GetAtt "apiGateway.RootResourceId"

  apiGatewayCatchAllMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      AuthorizationType: "NONE"
      HttpMethod: "ANY"
      Integration:
        # This must be post or the integration between gateway and lambda fails
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt "squashApp.Arn"
      ResourceId: !Ref "apiGatewayCatchAllProxy"
      RestApiId: !Ref "apiGateway"

  apiGatewayDeployment:
    Type: "AWS::ApiGateway::Deployment"
    DependsOn:
      - "apiGatewayRootMethod"
      - "apiGatewayCatchAllMethod"
    Properties:
      RestApiId: !Ref "apiGateway"
      StageName: !Ref "apiGatewayStageName"

  squashApp:
    Type: AWS::Lambda::Function
    Properties:
      Environment:
        Variables:
          GO_ENV: production
          DB_HOST: !GetAtt "squashRDS.Endpoint.Address"
          DB_PORT: !GetAtt "squashRDS.Endpoint.Port"
          DB_USER_NAME: !Sub "${rdsUser}"
          DB_USER_PASS: !Sub "${rdsPassword}"
      Code:
        S3Bucket: '${lambdaHandoffBucket}'
        S3Key: !Sub 'functions/${lambdaVersion}/${lambdaHash}' # TODO make parameter
      Handler: 'app'
      Role: !GetAtt "squashLambdaRole.Arn"
      Runtime: 'go1.x'
      Timeout: 2
      FunctionName: !Ref "lambdaFunctionName"
      VpcConfig:
        SecurityGroupIds:
          - !Ref "lambdaSecurtiyGroup"
        SubnetIds:
          - !Ref "privateSubnet1"
          - !Ref "privateSubnet2"

  lambdaSecurtiyGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: For Lambda Application
      VpcId: !Ref vpc

  lambdaEgres:
    Type: AWS::EC2::SecurityGroupEgress
    Properties:
      GroupId: !Ref lambdaSecurtiyGroup
      IpProtocol: tcp
      FromPort: !GetAtt "squashRDS.Endpoint.Port"
      ToPort: !GetAtt "squashRDS.Endpoint.Port"
      CidrIp: !GetAtt 'vpc.CidrBlock'

  lambdaApiGatewayInvoke:
    Type: "AWS::Lambda::Permission"
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt "squashApp.Arn"
      Principal: "apigateway.amazonaws.com"
      SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*/"

  squashLambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action:
              - "sts:AssumeRole"
            Effect: "Allow"
            Principal:
              Service:
                - "lambda.amazonaws.com"
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
      Policies:
        - PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Effect: "Allow"
                Resource:
                  - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${lambdaFunctionName}:*"
          PolicyName: "lambda"

  lambdaLogGroup:
    Type: "AWS::Logs::LogGroup"
    Properties:
      LogGroupName: !Sub "/aws/lambda/${lambdaFunctionName}"
      RetentionInDays: 14
  apiGatewayRole:
    DependsOn:
      - squashApp
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - "apigateway.amazonaws.com"
            Action: "sts:AssumeRole"
      Path: "/"
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
      Policies:
        - PolicyName: "API_Service_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action: "lambda:InvokeFunction"
                Resource: !GetAtt "squashApp.Arn"
                Effect: "Allow"
  apiGwAccountConfig:
    Type: "AWS::ApiGateway::Account"
    Properties:
      CloudWatchRoleArn: !GetAtt "apiGatewayRole.Arn"
  squashRDS:
    Type: AWS::RDS::DBInstance
    Properties:
      DBInstanceClass: db.t2.micro
      AllocatedStorage: 20
      StorageType: "gp2"
      Engine: "postgres"
      MasterUsername: !Sub "${rdsUser}"
      MasterUserPassword: !Sub "${rdsPassword}"
      DBSubnetGroupName: !Ref "rdsSubnetGroup"
      VPCSecurityGroups:
        - !Ref rdsSecurityGroup
    DeletionPolicy: Snapshot

  rdsSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: For RDS Instance
      VpcId: !Ref vpc
      Tags:
        - Key: Name
          Value: RDS-SecurityGroup

  rdsSubnetGroup:
    Type: "AWS::RDS::DBSubnetGroup"
    Properties:
      DBSubnetGroupName: "RDS Subnet Group"
      DBSubnetGroupDescription: Subnet including the RDS into the VPC
      SubnetIds:
        - !Ref "privateSubnet1"
        - !Ref "privateSubnet2"

  rdsIngres:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref rdsSecurityGroup
      IpProtocol: tcp
      FromPort: !GetAtt "squashRDS.Endpoint.Port"
      ToPort: !GetAtt "squashRDS.Endpoint.Port"
      CidrIp: !GetAtt 'vpc.CidrBlock'

  vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.192.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
  privateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.21.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "PrimaryAZ"
  privateSubnet2:
    Type: "AWS::EC2::Subnet"
    Properties:
      VpcId: !Ref vpc
      CidrBlock: 10.192.30.0/24
      MapPublicIpOnLaunch: false
      AvailabilityZone: !Ref "SecondaryAZ"

  privateRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1
  privateRouteTable2:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
  privateSubnetRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref privateRouteTable1
      SubnetId: !Ref privateSubnet1

  noIngressSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: "no-ingress-sg"
      GroupDescription: "Security group with no ingress rule"
      VpcId: !Ref vpc

Outputs:
  apiGatewayInvokeURL:
    Value: !Sub "https://${apiGateway}.execute-api.${AWS::Region}.amazonaws.com/${apiGatewayStageName}"

  lambdaArn:
    Value: !GetAtt "squashApp.Arn"

Body:
The only thing I can think of is, the API gateway source Arn should end with a resource path. In your case, it ends with a /.

I would add an * at the end to allow any resource path to invoke the lambda. You can change it to a specific path once you get it working.

lambdaApiGatewayInvoke:
  Type: "AWS::Lambda::Permission"
  Properties:
    Action: "lambda:InvokeFunction"
    FunctionName: !GetAtt "squashApp.Arn"
    Principal: "apigateway.amazonaws.com"
    SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*/*"

hope this helps. good luck.


问:
My custom template tag in Django rendering template variables as string
Usage of tag -

{% for x in posts %}

{% render_con_form for shastra x.id %}

Instead of passing the value of x.id which would be an integer it passes - 'x.id' as it is.

How can I fix this ?

Edit -

```<code>def render(self, context):
    if self.app == 'broadcast' or self.app == 'shastra':
        form = CommentsForm()
    str = render_to_string('comments/form.html', {'form' : form, 'app' : self.app, 'id' : self.id})
    return str
</code>```

def __init__(self, app, id):

             self.app = str(app)

             self.id = Variable(id)

答:
try to use the solution of the accepted answer below:

Django-Template : Get Variables in a Tag block !

Inside your template tag

```<code>// obj is x.id
def __init__(self, obj):
    from django.template import Variable
    // get the variable value
    self.id = Variable(obj)

def render(self, context):
    id = self.id.resolve(context)
</code>```

Body:
Usage of tag -

{% for x in posts %}

{% render_con_form for shastra x.id %}

Instead of passing the value of x.id which would be an integer it passes - 'x.id' as it is.

How can I fix this ?

Edit -

def render(self, context):
    if self.app == 'broadcast' or self.app == 'shastra':
        form = CommentsForm()
    str = render_to_string('comments/form.html', {'form' : form, 'app' : self.app, 'id' : self.id})
    return str

def __init__(self, app, id):

             self.app = str(app)

             self.id = Variable(id)

Body:
try to use the solution of the accepted answer below:

Django-Template : Get Variables in a Tag block !

Inside your template tag

// obj is x.id
def __init__(self, obj):
    from django.template import Variable
    // get the variable value
    self.id = Variable(obj)

def render(self, context):
    id = self.id.resolve(context)


答:
A simple way I could think of is using a list comprehension and set difference:</p>

```<code>s = {0, 1, 2, 3, 4, 5, 6}
s
{0, 1, 2, 3, 4, 5, 6}

df['c6'] = [tuple(s.difference(vals))[0] for vals in df.values]
df
    c0  c1  c2  c3  c4  c5  c6
0   4   5   6   3   2   1   0
1   1   5   4   0   2   3   6
2   5   6   4   0   1   3   2
3   5   4   6   2   0   1   3
4   5   6   4   0   1   3   2
5   0   1   4   5   6   2   3
</code>```

Title: How to perform set-like operations in pandas?

Body:
A simple way I could think of is using a list comprehension and set difference:

s = {0, 1, 2, 3, 4, 5, 6}
s
{0, 1, 2, 3, 4, 5, 6}

df['c6'] = [tuple(s.difference(vals))[0] for vals in df.values]
df
    c0  c1  c2  c3  c4  c5  c6
0   4   5   6   3   2   1   0
1   1   5   4   0   2   3   6
2   5   6   4   0   1   3   2
3   5   4   6   2   0   1   3
4   5   6   4   0   1   3   2
5   0   1   4   5   6   2   3