问:
Integration testing with Selenium Webdrive on a project with Continous Integration
I have a question. When I run a selenium webdrive integration test on my webb app, the web app must be running, because selenium browses to a debug version of my app (which is launched in IIS Express from Visual Studios). The problem is that if I want to achive this using CI development practice, on a dedicated CI machine, that machine have to be running a version of my webb app that's based on the current mainline code from subversion directory.

The code base constantly changes, and so theoretically you could run and restart the web app on the CI machine with code from the subversion dir, so that the tests always cover the latests commit.

Each individual developer on the project doesn't have any problems running the integration tests on the pre-commit build/test. And the unit tests can be handled with Cruise Control, MsBuild, subversion and NUnit working together. But running the integration tests (selenium webdrive test) on the integration server automatically with dynamic codebase is what I'm wondering about. Does anyone have experience of this, perhaps examples?

EDIT:
Arran has suggested that you can utilize a dedicated test enviroment to solve this problem. I don't quite practically understand how dedicated test enviroments works, and how practically it would works to solve this problem. The answers received doesn't seems to be automatable to the point where it can be implemented with the concurrent integration flow of Continous Integration. Does anyone else have any experience or thoughts on the matter?

This is the Selenium Webdrive code for reference:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
using OpenQA.Selenium.Firefox;
using System.Threading.Tasks;
using System.Threading;

namespace ChatProj.Tests
{
    [TestFixture]
    class WebDriverTestClass
    {
        private IWebDriver _driver;
        private StringBuilder verificationErrors;
        private string baseURL;
        private bool acceptNextAlert = true;

        [SetUp]
        public void SetUp()
        {
            _driver = new FirefoxDriver();
            baseURL = "http://localhost:59932/";
            verificationErrors = new StringBuilder();
        }

        [TearDown]
        public void TeardownTest()
        {
            try
            {
                _driver.Quit();
            }
            catch (Exception)
            {
                // Ignore errors if unable to close the browser
            }
            Assert.AreEqual("", verificationErrors.ToString());
        }
        [Repeat(2)]
        [Test]
        public void TestFirefox()
        {

            _driver.Navigate().GoToUrl(baseURL + "");

            IWebElement userNameInput = _driver.FindElement(By.Name("UserName"));
            userNameInput.SendKeys("Svenneglenne");
            IWebElement passwordInput = _driver.FindElement(By.Name("Password"));
            passwordInput.SendKeys("password");
            _driver.FindElement(By.CssSelector("input[type=\"submit\"]")).Click();

            WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
            IWebElement messageBox = wait.Until<IWebElement>((d) =>
            {
                return d.FindElement(By.Id("message"));
            });

            IWebElement adminMessageWaiter = wait.Until<IWebElement>((d) =>
            {
                return d.FindElement(By.XPath("//ul[@id='discussion']/li[1]"));
            });

            System.Console.Out.WriteLine("STUFF");
            //IWebElement query = driver.FindElement(By.Id("message"));
            String textSnippet = "This is a selenium test";
            adminMessageWaiter.SendKeys("");

            messageBox.SendKeys("This is a selenium test");

            IWebElement waitForJava = wait.Until<IWebElement>((d) =>
            {
                return d.FindElement(By.XPath("//ul[@id='discussion']/li[1]"));
            });

            //Thread.Sleep(2000);

            WaitForPageLoad(10);

            _driver.FindElement(By.Id("sendmessage")).Click();
            //Thread.Sleep(2000);

            _driver.FindElement(By.LinkText("Logg")).Click();

            IWebElement loggWaiter = wait.Until<IWebElement>((d) =>
            {
                return d.FindElement(By.XPath("//div[@id='body']/section/table/tbody/tr/td[2]"));
            });
            Assert.AreEqual(textSnippet, loggWaiter.Text);

            _driver.FindElement(By.LinkText("MPM Graph")).Click();
            Thread.Sleep(2000);

        }

       public void WaitForPageLoad(int maxWaitTimeInSeconds)
       {
        string state = string.Empty;
        try
        {
            WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(maxWaitTimeInSeconds));

            //Checks every 500 ms whether predicate returns true if returns exit otherwise keep trying till it returns ture
            wait.Until(d =>
            {

                try
                {
                    state = ((IJavaScriptExecutor)_driver).ExecuteScript(@"return document.readyState").ToString();
                }
                catch (InvalidOperationException)
                {
                    //Ignore
                }
                catch (NoSuchWindowException)
                {
                    //when popup is closed, switch to last windows
                    _driver.SwitchTo().Window(_driver.WindowHandles.Last());
                }
                //In IE7 there are chances we may get state as loaded instead of complete
                return (state.Equals("complete", StringComparison.InvariantCultureIgnoreCase) || state.Equals("loaded", StringComparison.InvariantCultureIgnoreCase));

            });
        }
        catch (TimeoutException)
        {
            //sometimes Page remains in Interactive mode and never becomes Complete, then we can still try to access the controls
            if (!state.Equals("interactive", StringComparison.InvariantCultureIgnoreCase))
                throw;
        }
        catch (NullReferenceException)
        {
            //sometimes Page remains in Interactive mode and never becomes Complete, then we can still try to access the controls
            if (!state.Equals("interactive", StringComparison.InvariantCultureIgnoreCase))
                throw;
        }
        catch (WebDriverException)
        {
            if (_driver.WindowHandles.Count == 1)
            {
                _driver.SwitchTo().Window(_driver.WindowHandles[0]);
            }
            state = ((IJavaScriptExecutor)_driver).ExecuteScript(@"return document.readyState").ToString();
            if (!(state.Equals("complete", StringComparison.InvariantCultureIgnoreCase) || state.Equals("loaded", StringComparison.InvariantCultureIgnoreCase)))
                throw;
        }
}

    }
}
</code>```

答:
the basic answer for your test automation automation is to run it in your gitlab CI

i dont undrestand what do you mean by running on "to be running a version of my webb app"
is this version of your webb app has a spicific url or domaine ?
if not then the test automation project is continous integration every version of your app the test project gonna run on it , if it has upgrade , then you need to upgrade your test automation to follow the flow

i hope thats help

Body:
I have a question. When I run a selenium webdrive integration test on my webb app, the web app must be running, because selenium browses to a debug version of my app (which is launched in IIS Express from Visual Studios). The problem is that if I want to achive this using CI development practice, on a dedicated CI machine, that machine have to be running a version of my webb app that's based on the current mainline code from subversion directory.

The code base constantly changes, and so theoretically you could run and restart the web app on the CI machine with code from the subversion dir, so that the tests always cover the latests commit.

Each individual developer on the project doesn't have any problems running the integration tests on the pre-commit build/test. And the unit tests can be handled with Cruise Control, MsBuild, subversion and NUnit working together. But running the integration tests (selenium webdrive test) on the integration server automatically with dynamic codebase is what I'm wondering about. Does anyone have experience of this, perhaps examples?

EDIT:
Arran has suggested that you can utilize a dedicated test enviroment to solve this problem. I don't quite practically understand how dedicated test enviroments works, and how practically it would works to solve this problem. The answers received doesn't seems to be automatable to the point where it can be implemented with the concurrent integration flow of Continous Integration. Does anyone else have any experience or thoughts on the matter?

This is the Selenium Webdrive code for reference:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
using OpenQA.Selenium.Firefox;
using System.Threading.Tasks;
using System.Threading;

namespace ChatProj.Tests
{
    [TestFixture]
    class WebDriverTestClass
    {
        private IWebDriver _driver;
        private StringBuilder verificationErrors;
        private string baseURL;
        private bool acceptNextAlert = true;

        [SetUp]
        public void SetUp()
        {
            _driver = new FirefoxDriver();
            baseURL = "http://localhost:59932/";
            verificationErrors = new StringBuilder();
        }

        [TearDown]
        public void TeardownTest()
        {
            try
            {
                _driver.Quit();
            }
            catch (Exception)
            {
                // Ignore errors if unable to close the browser
            }
            Assert.AreEqual("", verificationErrors.ToString());
        }
        [Repeat(2)]
        [Test]
        public void TestFirefox()
        {

            _driver.Navigate().GoToUrl(baseURL + "");

            IWebElement userNameInput = _driver.FindElement(By.Name("UserName"));
            userNameInput.SendKeys("Svenneglenne");
            IWebElement passwordInput = _driver.FindElement(By.Name("Password"));
            passwordInput.SendKeys("password");
            _driver.FindElement(By.CssSelector("input[type=\"submit\"]")).Click();

            WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
            IWebElement messageBox = wait.Until<IWebElement>((d) =>
            {
                return d.FindElement(By.Id("message"));
            });

            IWebElement adminMessageWaiter = wait.Until<IWebElement>((d) =>
            {
                return d.FindElement(By.XPath("//ul[@id='discussion']/li[1]"));
            });

            System.Console.Out.WriteLine("STUFF");
            //IWebElement query = driver.FindElement(By.Id("message"));
            String textSnippet = "This is a selenium test";
            adminMessageWaiter.SendKeys("");

            messageBox.SendKeys("This is a selenium test");

            IWebElement waitForJava = wait.Until<IWebElement>((d) =>
            {
                return d.FindElement(By.XPath("//ul[@id='discussion']/li[1]"));
            });

            //Thread.Sleep(2000);

            WaitForPageLoad(10);

            _driver.FindElement(By.Id("sendmessage")).Click();
            //Thread.Sleep(2000);

            _driver.FindElement(By.LinkText("Logg")).Click();

            IWebElement loggWaiter = wait.Until<IWebElement>((d) =>
            {
                return d.FindElement(By.XPath("//div[@id='body']/section/table/tbody/tr/td[2]"));
            });
            Assert.AreEqual(textSnippet, loggWaiter.Text);

            _driver.FindElement(By.LinkText("MPM Graph")).Click();
            Thread.Sleep(2000);

        }

       public void WaitForPageLoad(int maxWaitTimeInSeconds)
       {
        string state = string.Empty;
        try
        {
            WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(maxWaitTimeInSeconds));

            //Checks every 500 ms whether predicate returns true if returns exit otherwise keep trying till it returns ture
            wait.Until(d =>
            {

                try
                {
                    state = ((IJavaScriptExecutor)_driver).ExecuteScript(@"return document.readyState").ToString();
                }
                catch (InvalidOperationException)
                {
                    //Ignore
                }
                catch (NoSuchWindowException)
                {
                    //when popup is closed, switch to last windows
                    _driver.SwitchTo().Window(_driver.WindowHandles.Last());
                }
                //In IE7 there are chances we may get state as loaded instead of complete
                return (state.Equals("complete", StringComparison.InvariantCultureIgnoreCase) || state.Equals("loaded", StringComparison.InvariantCultureIgnoreCase));

            });
        }
        catch (TimeoutException)
        {
            //sometimes Page remains in Interactive mode and never becomes Complete, then we can still try to access the controls
            if (!state.Equals("interactive", StringComparison.InvariantCultureIgnoreCase))
                throw;
        }
        catch (NullReferenceException)
        {
            //sometimes Page remains in Interactive mode and never becomes Complete, then we can still try to access the controls
            if (!state.Equals("interactive", StringComparison.InvariantCultureIgnoreCase))
                throw;
        }
        catch (WebDriverException)
        {
            if (_driver.WindowHandles.Count == 1)
            {
                _driver.SwitchTo().Window(_driver.WindowHandles[0]);
            }
            state = ((IJavaScriptExecutor)_driver).ExecuteScript(@"return document.readyState").ToString();
            if (!(state.Equals("complete", StringComparison.InvariantCultureIgnoreCase) || state.Equals("loaded", StringComparison.InvariantCultureIgnoreCase)))
                throw;
        }
}

    }
}


来源: stackexchange

问:
Insert Row Below Instead of Above
This code inserts a row as I want it to, but it inserts the row above the row containing 19 in column I and I want to insert the row below.  How can I modify this code to insert the row below?</p>
```<code>
Dim i As Integer
Dim lRow As Long

For lRow = Cells(Cells.Rows.Count, "C").End(xlUp).Row To 3 Step -1
If Cells(lRow, "I") = "19" Then Rows(lRow).EntireRow.Insert
Next lRow
</code>```

答:
This bit of code might do the trick:

```<code>Rows(lRow).Resize(1).Insert xlUp
</code>```

And if you need to insert more rows you can change the "1" with the appropriate number.

ContentLicense: CC BY-SA 4.0

Title: Insert Row Below Instead of Above

Body:
This code inserts a row as I want it to, but it inserts the row above the row containing 19 in column I and I want to insert the row below.  How can I modify this code to insert the row below?

Dim i As Integer
Dim lRow As Long

For lRow = Cells(Cells.Rows.Count, "C").End(xlUp).Row To 3 Step -1
If Cells(lRow, "I") = "19" Then Rows(lRow).EntireRow.Insert
Next lRow

Body:
This bit of code might do the trick:

Rows(lRow).Resize(1).Insert xlUp

And if you need to insert more rows you can change the "1" with the appropriate number.


问:
How can I implement 2d subscripts via AT-POS for different classes?
here is an MRE (showing two attempts, with debug left in to be helpful) to try and get 2d subscripting working with AT-POS across a DataFrame that has columns of Series...

```<code>class Series does Positional {
    has Real @.data = [0.1,0.2,0.3];

    method AT-POS( $p ) {
        @!data[$p]
    }
}

class DataFrame does Positional {
    has Series @.series;

#`[ ATTEMPT #1
    method AT-POS( $p, $q? ) {
        given $q {
            when Int {                  #say 'Int';
                @!series[$p][$q]
            }
            when Whatever {             #say '*';
                @!series[$p].data
            }
            default {                   #say 'default';
                @!series[$p]
            }

        }
    }
#]
    # ATTEMPT #2
    method AT-POS(|c) is raw { #`[dd c;] @!series.AT-POS(|c) }
}

my $df = DataFrame.new( series => [Series.new xx 3] );

say $df[1].data;            #[0.1 0.2 0.3]
say $df[1][2];              #0.3
say $df[0,1];               #(Series.new(data => $[0.1, 0.2, 0.3]) Series.new(data => $[0.1, 0.2, 0.3]))
say $df[1;2];               #0.3
say $df[1;*];               #got (0.1) ... expected [0.1 0.2 0.3]
say $df[*;1];               #got (0.2) ... wanted [0.2 0.2 0.2]
</code>```

I already researched on SO and found three related questions here, here and here ... and the attempt #2 in my code seeks to apply @lizmats Answer to the third one. Encouragingly both the attempts in my MRE have the same behaviour. But I cannot workout

why the when Whatever {} option is not entered (attempt #1)

what the |c is doing - even though I can see that it works in the single subscript case (attempt #2)

I have done some experimenting with multi postcircumfix:<[ ]>( DataFrame:D $df, @slicer where Range|List ) is export {} but this seems to overcomplicate matters.

==================

Great answer from @jonathan building on the original from @Lizmat - thanks! Here is the final, working code:

```<code>class Series does Positional {
    has Real @.data = [0.1,0.2,0.3];

    method elems {
        @!data.elems
    }

    method AT-POS( |p ) is raw {
        @!data.AT-POS( |p )
    }
}

class DataFrame does Positional {
    has Series @.series;

    method elems {
        @!series.elems
    }

    method AT-POS( |p ) is raw {
        @!series.AT-POS( |p )
    }
}

my $df = DataFrame.new( series => Series.new xx 3 );

say $df[1].data;            #[0.1 0.2 0.3]
say $df[1][2];              #0.3
say $df[0,1];               #(Series.new(data => $[0.1, 0.2, 0.3]) Series.new(data => $[0.1, 0.2, 0.3]))
say $df[1;2];               #0.3
say $df[1;*];               #(0.1 0.2 0.3)
say $df[*;1];               #(0.2 0.2 0.2)
</code>```

答:
This answer is simply an elaboration of the point @raiph made in a comment:

You may be able to simplify the code by using handles

Indeed you can – so much so that I thought it was worth showing what that would look like in a code block without a comment's formatting limits.

Using handles, you can simplify each of the two classes from 9 non-whitespace lines to 3:

class Series does Positional {
    has Real @.data handles <elems AT-POS> = [0.1,0.2,0.3];
}

class DataFrame does Positional {
    has Series @.series handles <elems AT-POS>;
}
```

(or you could even have each class on 1 line, if you format them the way I'd be tempted to.)

This code produces all the same results to the say statements from the code in the question.

Body:
here is an MRE (showing two attempts, with debug left in to be helpful) to try and get 2d subscripting working with AT-POS across a DataFrame that has columns of Series...

class Series does Positional {
    has Real @.data = [0.1,0.2,0.3];

    method AT-POS( $p ) {
        @!data[$p]
    }
}

class DataFrame does Positional {
    has Series @.series;

#`[ ATTEMPT #1
    method AT-POS( $p, $q? ) {
        given $q {
            when Int {                  #say 'Int';
                @!series[$p][$q]
            }
            when Whatever {             #say '*';
                @!series[$p].data
            }
            default {                   #say 'default';
                @!series[$p]
            }

        }
    }
#]
    # ATTEMPT #2
    method AT-POS(|c) is raw { #`[dd c;] @!series.AT-POS(|c) }
}

my $df = DataFrame.new( series => [Series.new xx 3] );

say $df[1].data;            #[0.1 0.2 0.3]
say $df[1][2];              #0.3
say $df[0,1];               #(Series.new(data => $[0.1, 0.2, 0.3]) Series.new(data => $[0.1, 0.2, 0.3]))
say $df[1;2];               #0.3
say $df[1;*];               #got (0.1) ... expected [0.1 0.2 0.3]
say $df[*;1];               #got (0.2) ... wanted [0.2 0.2 0.2]

I already researched on SO and found three related questions here, here and here ... and the attempt #2 in my code seeks to apply @lizmats Answer to the third one. Encouragingly both the attempts in my MRE have the same behaviour. But I cannot workout

why the when Whatever {} option is not entered (attempt #1)

what the |c is doing - even though I can see that it works in the single subscript case (attempt #2)

I have done some experimenting with multi postcircumfix:<[ ]>( DataFrame:D $df, @slicer where Range|List ) is export {} but this seems to overcomplicate matters.

==================

Great answer from @jonathan building on the original from @Lizmat - thanks! Here is the final, working code:

class Series does Positional {
    has Real @.data = [0.1,0.2,0.3];

    method elems {
        @!data.elems
    }

    method AT-POS( |p ) is raw {
        @!data.AT-POS( |p )
    }
}

class DataFrame does Positional {
    has Series @.series;

    method elems {
        @!series.elems
    }

    method AT-POS( |p ) is raw {
        @!series.AT-POS( |p )
    }
}

my $df = DataFrame.new( series => Series.new xx 3 );

say $df[1].data;            #[0.1 0.2 0.3]
say $df[1][2];              #0.3
say $df[0,1];               #(Series.new(data => $[0.1, 0.2, 0.3]) Series.new(data => $[0.1, 0.2, 0.3]))
say $df[1;2];               #0.3
say $df[1;*];               #(0.1 0.2 0.3)
say $df[*;1];               #(0.2 0.2 0.2)

Body:
This answer is simply an elaboration of the point @raiph made in a comment:

You may be able to simplify the code by using handles

Indeed you can – so much so that I thought it was worth showing what that would look like in a code block without a comment's formatting limits.

Using handles, you can simplify each of the two classes from 9 non-whitespace lines to 3:

class Series does Positional {
    has Real @.data handles <elems AT-POS> = [0.1,0.2,0.3];
}

class DataFrame does Positional {
    has Series @.series handles <elems AT-POS>;
}

(or you could even have each class on 1 line, if you format them the way I'd be tempted to.)

This code produces all the same results to the say statements from the code in the question.


问:
leave gcloud project in terminal
How can I leave my current gcloud project via the cloud cli so I can revert back to my normal terminal?

```<code>15:40:08 in ~ using ☁  default/192085439987
</code>```

I just want to be using

```<code>15:40:08 in ~
</code>```

I have managed to swap between projects using

```<code>gcloud config set project <project id>
</code>```

But can't seem to leave anything

答:
When you use the gcloud command the terminal keeps the same properties, if any it could change the shell you're using, in that case to return back to your previous shell you can just type exit which normally would take you out of the last shell.

Here are some detailed instructions to go back the old shell or prompt depending on what changed on your side:

Determine the shell you're using before starting the gcloud command by typing echo $SHELL, this will provide the name of the shell which could be something like /bin/bash for bash or /bin/zsh for zshell.

Once that you have finished using gcloud, type $SHELL again and determine if the shell you're using now changed. If it did changed, normally with an exit command you would leave the old shell, if it doesn't work you can type the whole route of the binary and you will switch to it, for example type /bin/zsh to go back to zsh

If the prompt also changed, you can go back to the default one by executing . ./.profile, source ~/.zshrc for zsh or source ~/.bashrc for bash

If the prompt is changed since the beginning (before executing the gcloud command) then you probably have to edit your .profile or .zshrc files to set them as you like to have them, more information about it, can be found here

Title: leave gcloud project in terminal

Body:
How can I leave my current gcloud project via the cloud cli so I can revert back to my normal terminal?

15:40:08 in ~ using ☁  default/192085439987

I just want to be using

15:40:08 in ~

I have managed to swap between projects using

gcloud config set project <project id>

But can't seem to leave anything


问:
Problem with my Copy and Move constructor and assignment operators
I want to build my own full Vector class in C++. I started like this:

#include <iostream>
#include <initializer_list>

#define Print(x)(std::cout<< x << std::endl)

// Vector Class //
template <typename T>
class Vector
{
    // Attributes
    int length = 0;
    T* array;

    public:

    // Default constructor
    Vector()
    : length(0), array(nullptr)
    { }

    // Copy constructor
    template<typename U>
    Vector(const Vector& other)
        : Vector(other.len())
    {
        Print("Use Copy Constructor");
        // Coppying other data to new array
        array = new T[other.len()];
        for (auto i=0; i < other.len(); i++)
            array[i] = other[i];
    }

    // Move constructor
    Vector(Vector<T>&& other)
        : length(other.len()), array(other.array)
    {
        Print("Use Move Constructor");
        // Deleting other array
        other.length = 0;
        other.array = nullptr;
    }

    // Constructor (does not allow uniform initialisation)
    Vector(int length)
    : length(length), array(new T[length])
    { }

    // Constructor (with initialiser list and delegate constructor)
    Vector(std::initializer_list<T> list)
    : Vector((int)list.size())
    {
        std::uninitialized_copy(list.begin(), list.end(), array);
    }

    // Destructor
    ~Vector()
    {
        length = 0;
        delete[] array;
        array = nullptr;
    }

    // Function Len that returns the length
    int len() const
    {
        return length;
    }
    // Operator[](int i) and its const overload
    auto& operator[](int i)
    {
        return array[i];
    }

    auto& operator[](int i) const
    {
        return array[i];
    }

    // Copy assignment operator
    template<typename U>
    Vector& operator=(const Vector& other)
    {
        Print("Use Copy Operator");
        if (this != (Vector*)& other) {
            /*
            This works the same way but does not solve the problem:

            Vector<typename std::common_type<T,U>::type> temp(other);
            temp.swap(*this);
            */

            delete[] array;
            length = other.len();
            array = new T[other.len()];
            for (auto i = 0; i < other.len(); i++)
                array[i] = other[i];
        }
        return *this;
    }

    // Move assignment opertator
    Vector& operator=(Vector<T>&& other)
    {
        Print("Use Move Operator");
        if (this != (Vector*)&other){
            /*
            This works the same way but does not solve the problem:

            Vector<T> temp(std::move(other)); // moves the array
            temp.swap(*this);
            */

            delete[] array;
            length = other.len();
            array   = other.array;
            other.len() = 0;
            other.array   = nullptr;
        }
        return *this;
    }
};
```
<p>But if I now try to use the copy assignment operator like this:</p>
<pre class="lang-cpp prettyprint-override"><code>Vector<double> double_vector = {3.4677, 3.212, 2.2, 6.3};
Vector<double> a = double_vector;
</code>```

I get the following error message:

error: use of deleted function 'constexpr Vector<double>::Vector(const Vector<double>&)'

I assume that the problem lies within the copy constructor and copy assignment operator, but I sadly can't find a solution. What I find strange is that, if I comment out the move constructor and move assignment operator, the code does seem to work. This lets me think that the compiler has difficulty knowing which constructor to use. But I could also be very wrong about this.

Hope I gave enough info for an answer/push in the right direction.

答:
A template is never a copy constructor, that is a converting constructor.

And as you have defined a bunch of other constructors, the otherwise default copy constructor will be defined as deleted.

Body:
I want to build my own full Vector class in C++. I started like this:

#include <iostream>
#include <initializer_list>

#define Print(x)(std::cout<< x << std::endl)

// Vector Class //
template <typename T>
class Vector
{
    // Attributes
    int length = 0;
    T* array;

    public:

    // Default constructor
    Vector()
    : length(0), array(nullptr)
    { }

    // Copy constructor
    template<typename U>
    Vector(const Vector& other)
        : Vector(other.len())
    {
        Print("Use Copy Constructor");
        // Coppying other data to new array
        array = new T[other.len()];
        for (auto i=0; i < other.len(); i++)
            array[i] = other[i];
    }

    // Move constructor
    Vector(Vector<T>&& other)
        : length(other.len()), array(other.array)
    {
        Print("Use Move Constructor");
        // Deleting other array
        other.length = 0;
        other.array = nullptr;
    }

    // Constructor (does not allow uniform initialisation)
    Vector(int length)
    : length(length), array(new T[length])
    { }

    // Constructor (with initialiser list and delegate constructor)
    Vector(std::initializer_list<T> list)
    : Vector((int)list.size())
    {
        std::uninitialized_copy(list.begin(), list.end(), array);
    }

    // Destructor
    ~Vector()
    {
        length = 0;
        delete[] array;
        array = nullptr;
    }

    // Function Len that returns the length
    int len() const
    {
        return length;
    }
    // Operator[](int i) and its const overload
    auto& operator[](int i)
    {
        return array[i];
    }

    auto& operator[](int i) const
    {
        return array[i];
    }

    // Copy assignment operator
    template<typename U>
    Vector& operator=(const Vector& other)
    {
        Print("Use Copy Operator");
        if (this != (Vector*)& other) {
            /*
            This works the same way but does not solve the problem:

            Vector<typename std::common_type<T,U>::type> temp(other);
            temp.swap(*this);
            */

            delete[] array;
            length = other.len();
            array = new T[other.len()];
            for (auto i = 0; i < other.len(); i++)
                array[i] = other[i];
        }
        return *this;
    }

    // Move assignment opertator
    Vector& operator=(Vector<T>&& other)
    {
        Print("Use Move Operator");
        if (this != (Vector*)&other){
            /*
            This works the same way but does not solve the problem:

            Vector<T> temp(std::move(other)); // moves the array
            temp.swap(*this);
            */

            delete[] array;
            length = other.len();
            array   = other.array;
            other.len() = 0;
            other.array   = nullptr;
        }
        return *this;
    }
};

But if I now try to use the copy assignment operator like this:

Vector<double> double_vector = {3.4677, 3.212, 2.2, 6.3};
Vector<double> a = double_vector;

I get the following error message:

error: use of deleted function 'constexpr Vector<double>::Vector(const Vector<double>&)'

I assume that the problem lies within the copy constructor and copy assignment operator, but I sadly can't find a solution. What I find strange is that, if I comment out the move constructor and move assignment operator, the code does seem to work. This lets me think that the compiler has difficulty knowing which constructor to use. But I could also be very wrong about this.

Hope I gave enough info for an answer/push in the right direction.


问:
How to make Canonicals with PHP
I've search around on SO, but can't find an exact answer to my needs.

Generating a URL is pretty easy...

Like so:

```<code><link rel="canonical" href="https://example.com<?php echo ($_SERVER['REQUEST_URI']); ?>" />
</code>```

But, the issue with this is, the $_SERVER['REQUEST_URI']) will always fetch the current file in use, so the canonical URL could potentially change.

So it could flick between www.example.com/hello.php and www.example.com/hello/, and many other variations depending on how the user accesses your site.

How do I make it so it's always the same url? (preferably without .php)

答:
This will remove query parameters like ?search=abc&page=32

Option 1:

```<code>$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . strtok($_SERVER['REQUEST_URI'], '?');
</code>```

Option 2 (does the same) :

```<code>$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
</code>```

Then echo

```<code>echo '<link rel="canonical" href="' . $url . '" />';
</code>```

Title: How to make Canonicals with PHP

Body:
I've search around on SO, but can't find an exact answer to my needs.

Generating a URL is pretty easy...

Like so:

<link rel="canonical" href="https://example.com<?php echo ($_SERVER['REQUEST_URI']); ?>" />

But, the issue with this is, the $_SERVER['REQUEST_URI']) will always fetch the current file in use, so the canonical URL could potentially change.

So it could flick between www.example.com/hello.php and www.example.com/hello/, and many other variations depending on how the user accesses your site.

How do I make it so it's always the same url? (preferably without .php)

Body:
This will remove query parameters like ?search=abc&page=32

Option 1:

$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . strtok($_SERVER['REQUEST_URI'], '?');

Option 2 (does the same) :

$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);

Then echo

echo '<link rel="canonical" href="' . $url . '" />';


问:
XAMARIN.FORMS Android: FLAG_IMMUTABLE needs to be set when targeting Android S+
Ive seen this issue a few times now, but never for xamarin.forms:

When I am trying to deploy on android 12 I am getting:

com.interiorcircle.interiorcircledroid: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.

Here in picture:

Appearently, a flag needs to be set, but I cannot figure out where.

Anyone has some help here?

答:
If you cannot figure out where then you probably don't use PendingIntent in your code.

In that case it means that some of the packages that you use is using this code and they need to fix it. Possibly you need to report the problem to them if they are not already aware of it.


问:
Excel: How to merge two columns into one (from different sheets or separated columns)
I have met some problem with merging two columns to one.
I have some solution but not exactly fits to my problem (found here: Excel: Merge two columns into one column with alternating values)

As I understand two columns has to be one by one:

```<code>A       B       C
==================
A       1       A
B       2       1
C       3       B
                2
                C
                3
</code>```

To get the above solution in C column I should use:

```<code>=INDEX($A$2:$B$9;ROUND(ROW(A1)/2;0);MOD(ROW();2)+1)
</code>```

So in the formula I'm using data like A1:B4.

How to do it if I will have columns with data A and D and I dont want to include columns B and C?
Or for instance I will have one column from sheet_A and second column from sheet_B?

答:
This formula is total flexible. You can have your two seperate columns on different sheets. And the Result column also can be wherever you want.

```<code>=IF(ISEVEN(ROW())=FALSE;INDEX($A$4:$A$20;ROUND((ROWS($A$4:A4)/2);0));INDEX($B$6:$B$24;ROUND((ROWS($B$6:B6)/2);0)))
</code>```

Body:
I have met some problem with merging two columns to one.
I have some solution but not exactly fits to my problem (found here: Excel: Merge two columns into one column with alternating values)

As I understand two columns has to be one by one:

A       B       C
==================
A       1       A
B       2       1
C       3       B
                2
                C
                3

To get the above solution in C column I should use:

=INDEX($A$2:$B$9;ROUND(ROW(A1)/2;0);MOD(ROW();2)+1)

So in the formula I'm using data like A1:B4.

How to do it if I will have columns with data A and D and I dont want to include columns B and C?
Or for instance I will have one column from sheet_A and second column from sheet_B?

Body:
This formula is total flexible. You can have your two seperate columns on different sheets. And the Result column also can be wherever you want.

=IF(ISEVEN(ROW())=FALSE;INDEX($A$4:$A$20;ROUND((ROWS($A$4:A4)/2);0));INDEX($B$6:$B$24;ROUND((ROWS($B$6:B6)/2);0)))


问:
Image not taking full width of page
So I have the following html code

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.logo {
  max-width: 60px;
  padding: 5px;
}

.navigation {
  align-self: flex-end;
}

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #c5f3f7;
}

.banner {
  margin-top: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>
  <title>HTML Layout</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <header>
    <div class="logo">
      <img src="logo.png">
    </div>
    <nav class="navigation">
      <ul>
        <li>Home</li>
        <li>Products</li>
        <li>About</li>
        <li>News</li>
        <li>Contact</li>
      </ul>
    </nav>
  </header>
  <div class="banner">
    <img src="pagebanner.png" alt="page banner">
  </div>
</body>

</html></code>```

However the banner image does not take up the full width of the page. Instead, it is very small. I have tried doing width = 100% but this does not fix it. What can I do to make the banner image full width?

答:
I just added width: 100%; at the img, everything is fine for me.

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.logo {
  max-width: 60px;
  padding: 5px;
}
body > header > div > img {
  width: 7rem;
}
.navigation {
  align-self: flex-end;
}

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  background-color: #c5f3f7;
}
body > div > img {
  width: 100%;
}
.banner {
  margin-top: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="logo">
    <img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Android_O_Preview_Logo.png">
  </div>
  <nav class="navigation">
    <ul>
      <li>Home</li>
      <li>Products</li>
      <li>About</li>
      <li>News</li>
      <li>Contact</li>
    </ul>
  </nav>
</header>
<div class="banner">
  <img src="https://www.sci-techdaresbury.com/wp-content/uploads/2019/09/back_doitbetter-1200x300.jpg" alt="page banner">
</div></code>```

Title: Image not taking full width of page

Body:
So I have the following html code

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.logo {
  max-width: 60px;
  padding: 5px;
}

.navigation {
  align-self: flex-end;
}

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #c5f3f7;
}

.banner {
  margin-top: 30px;
}

<!doctype html>

  <title>HTML Layout</title>
  <link rel="stylesheet" href="style.css">

Home

Products

About

News

Contact

However the banner image does not take up the full width of the page. Instead, it is very small. I have tried doing width = 100% but this does not fix it. What can I do to make the banner image full width?

Body:
I just added width: 100%; at the img, everything is fine for me.

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.logo {
  max-width: 60px;
  padding: 5px;
}
body > header > div > img {
  width: 7rem;
}
.navigation {
  align-self: flex-end;
}

header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  background-color: #c5f3f7;
}
body > div > img {
  width: 100%;
}
.banner {
  margin-top: 30px;
}

<header>
  <div class="logo">
    <img src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Android_O_Preview_Logo.png">
  </div>
  <nav class="navigation">
    <ul>
      <li><a href="index.html">Home</a></li>
      <li><a href="products.html">Products</a></li>
      <li><a href="about.html">About</a></li>
      <li><a href="news.html">News</a></li>
      <li><a href="contact.html">Contact</a></li>
    </ul>
  </nav>
</header>
<div class="banner">
  <img src="https://www.sci-techdaresbury.com/wp-content/uploads/2019/09/back_doitbetter-1200x300.jpg" alt="page banner">
</div>


问:
How to connect Google adwords with Python
Hi I am looking for a simple solution to connect Google Adwords with Python in jupyter notebook, went through google on some blogs and websites but did not get a proper solution.

Any help would be highly appreciated.

Thanks

答:
The API quickstart is an excellent and easily digestible guide.
https://developers.google.com/google-ads/api/docs/first-call/overview

There's no reason this cannot be done in a Juypter notebook. What code are you using that isn't working?


问:
How to send additional data using PLupload?
I'm using plupload to make an ajax file uploading.
Now the plupload.Uploader class has many options but none are additional data.

For Example :

```<code>var uploader = new plupload.Uploader({
    runtimes : 'gears,html5,flash,silverlight,browserplus',
    browse_button : 'pickfiles',
    container : 'contact_container',
    max_file_size : '10mb',
    url : 'upload.php',
    flash_swf_url : '/plupload/js/plupload.flash.swf',
    silverlight_xap_url : '/plupload/js/plupload.silverlight.xap',
    filters : [
        {title : "Image files", extensions : "jpg,gif,png"},
        {title : "Zip files", extensions : "zip"}
    ],
    resize : {width : 320, height : 240, quality : 90}
});
</code>```

What i'm trying to achive is i have a folder in my server where all the uploads
are being saved.
I neeed inside the folder to create a sub-folder to each user that have uploaded files there.
How can i add data like id of the user to the instance of plupload.Uploader?
Or if i'll wrap a form inside the container div, will i be able to see it in the $_REQUEST?
Or is there some other way i can achive this?

答:
More up to date for 3.xx
After files added use this as an example with DEPOSITImageUploader being the declared plupload change as you wish</p>
```<code>BeforeUpload: function (up, files) {
            console.log("BEFORE UPLOAD ");
            var settings = DEPOSITImageUploader.settings;
            var params = settings.multipart_params;
            $.extend(up.settings.params, { deposit_id : $('#deposit_id').val() });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using plupload to make an ajax file uploading.
Now the plupload.Uploader class has many options but none are additional data.

For Example :

var uploader = new plupload.Uploader({
    runtimes : 'gears,html5,flash,silverlight,browserplus',
    browse_button : 'pickfiles',
    container : 'contact_container',
    max_file_size : '10mb',
    url : 'upload.php',
    flash_swf_url : '/plupload/js/plupload.flash.swf',
    silverlight_xap_url : '/plupload/js/plupload.silverlight.xap',
    filters : [
        {title : "Image files", extensions : "jpg,gif,png"},
        {title : "Zip files", extensions : "zip"}
    ],
    resize : {width : 320, height : 240, quality : 90}
});

What i'm trying to achive is i have a folder in my server where all the uploads
are being saved.
I neeed inside the folder to create a sub-folder to each user that have uploaded files there.
How can i add data like id of the user to the instance of plupload.Uploader?
Or if i'll wrap a form inside the container div, will i be able to see it in the $_REQUEST?
Or is there some other way i can achive this?

Body:
More up to date for 3.xx
After files added use this as an example with DEPOSITImageUploader being the declared plupload change as you wish

BeforeUpload: function (up, files) {
            console.log("BEFORE UPLOAD ");
            var settings = DEPOSITImageUploader.settings;
            var params = settings.multipart_params;
            $.extend(up.settings.params, { deposit_id : $('#deposit_id').val() });


问:
aws lambda docker fork/exec permission denied
I am trying to use AWS lambda with docker container. The container is built starting from ubuntu:latest

When running test with AWS lambda console, I get following error:

Launch error: fork/exec /root/miniconda3/bin/python: permission denied

Entrypoint: [/root/miniconda3/bin/python,-m,awslambdaric]

The /root/miniconda3/bin/python and awslambdaric files do have correct permission.

Any idea what could be reason?

答:
I just ran into a similar issue where /root had drwxr-x--- permissions (i.e. "others" could not read or execute). When this runs under Lambda, it doesn't run as root so it cannot access directories that are not readable/executable by "other".

When I added "RUN chmod o+rx /root" to my Dockerfile, my lambda ran successfully.

BTW, also check that /root/miniconda3/bin/python is not a symbolic link. I read somewhere that that could also cause this error.


问:
Spring Boot JPA interaction from reactive AMQP background thread
We have a regular, blocking Spring Boot (2.5.4) application serving a REST interface. We use Hibernate envers for audit logging. This service sends messages on our Service Bus in an asynchronous fashion via the ServiceBusSenderAsyncClient from the Azure SDK.
Now this service needs to receive messages from said Service Bus and write updates to the Database - also async. For this we use ServiceBusReceiverAsyncClient with a reactive stream. All of this generally works (I wrapped the whole database interaction in one Transactional function) but I'm encountering issues with envers via the beforeTransactionCompletion callback being null (when I deactivate envers, it works). This issues is Service Bus independent from my understanding and really rotates around accessing the JPA repo from a background thread. Following the schematic implementation:

ServiceBusReceiveController

```<code>@Component
public class SubscriptionReceiveController {
  @Autowired
  private MyService myService;

  @Autowired
  private ServiceBusReceiverAsyncClient receiver;

  @Autowired
  private ObjectMapper mapper;

  @PostConstruct
  public void run() {
    // continuously receive messages in the background
    receiver.receiveMessages().flatMap(message -> {
      MyObject object;
      try {
        object = mapper.readValue(message.getBody().toString(), MyClass.class);
      } catch (JsonProcessingException e) {
        throw new JsonProcessingRuntimeException("Failed to convert message to object", e);
      }

      // wrap the blocking JPA interaction
      Mono<MyObject> blockingWrapper = Mono.fromCallable(() -> {
        return myService.updateMyObject(object.getId());
      });

      // When the service returns, this is where it crashes
      return blockingWrapper.subscribeOn(Schedulers.boundedElastic());
    }).flatMap(response -> {
      // More processing steps
    }).subscribe();
  }
}
</code>```

MyService

```<code>@Service
public class MyService {

  @Autowired
  private MyRepository myRepository;

  @Transactional
  public MyObject updateMyObject(UUID objectId) {
    var object = myRepository.getById(objectId);
    object.setSomeProperty("myPropertyValue");

    return myRepository.save(object);
  }
}
</code>```

Causing following error message:

```<code>org.springframework.orm.jpa.JpaSystemException: Unable to perform beforeTransactionCompletion callback: null; nested exception is org.hibernate.HibernateException: Unable to perform beforeTransactionCompletion callback: null
Caused by: org.hibernate.HibernateException: Unable to perform beforeTransactionCompletion callback: null
        at org.hibernate.engine.spi.ActionQueue$BeforeTransactionCompletionProcessQueue.beforeTransactionCompletion(ActionQueue.java:960) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.engine.spi.ActionQueue.beforeTransactionCompletion(ActionQueue.java:525) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2381) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:448) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) ~[spring-orm-5.3.9.jar:5.3.9]
        ... 20 common frames omitted

...

Caused by: java.lang.NullPointerException: null
        at com.my.package.revision.AuditRevisionListener.newRevision(AuditRevisionListener.java:10) ~[classes/:na]
        at org.hibernate.envers.internal.revisioninfo.DefaultRevisionInfoGenerator.generate(DefaultRevisionInfoGenerator.java:88) ~[hibernate-envers-5.4.28.Final.jar:5.4.28.Final]
        at org.hibernate.envers.internal.synchronization.AuditProcess.getCurrentRevisionData(AuditProcess.java:133) ~[hibernate-envers-5.4.28.Final.jar:5.4.28.Final]
        at org.hibernate.envers.internal.synchronization.AuditProcess.executeInSession(AuditProcess.java:115) ~[hibernate-envers-5.4.28.Final.jar:5.4.28.Final]
        at org.hibernate.envers.internal.synchronization.AuditProcess.doBeforeTransactionCompletion(AuditProcess.java:174) ~[hibernate-envers-5.4.28.Final.jar:5.4.28.Final]
        at org.hibernate.envers.internal.synchronization.AuditProcessManager$1.doBeforeTransactionCompletion(AuditProcessManager.java:47) ~[hibernate-envers-5.4.28.Final.jar:5.4.28.Final]
        at org.hibernate.engine.spi.ActionQueue$BeforeTransactionCompletionProcessQueue.beforeTransactionCompletion(ActionQueue.java:954) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        ... 28 common frames omitted
</code>```

What am I missing here, why is the transaction not fully finished within the Service implementation? Is there a better way/pattern for a background thread to write to a database via JPA?

Thanks

答:
I was facing the same problem with RevisionListener. It seems that there is a lack of communication between Spring Framework and Hibernate Envers as described in this issue:
https://github.com/spring-projects/spring-data-envers/issues/249.

Even after annotating my CustomRevisionListener with @Service, spring cannot find this bean and create an instance of it.

I've tried all the solutions listed here:
How to inject spring beans into the hibernate envers RevisionListener

But only the solution using the SecurityContextHolder (Solution 3) worked for me. I just needed to check if my entity that represents the logged user had an Id property and fill it with the user id that was retrieved from the database.

Here is my code:

```<code>public class MyRevisionListener implements RevisionListener {

   @Override
   public void newRevision(Object entity) {
      MyRevisionEntity revisionEntity = (MyRevisionEntity) entity;

      Long loggedUserId = Optional.ofNullable(SecurityContextHolder.getContext())
            .map(SecurityContext::getAuthentication)
            .filter(Authentication::isAuthenticated)
            .map(Authentication::getPrincipal)
            .map(JwtUser.class::cast)
            .map(JwtUser::getId)
            .orElse(null);

      revisionEntity.setUserId(loggedUserId);
      revisionEntity.setDate(new Date());
   }
}
</code>```

Body:
We have a regular, blocking Spring Boot (2.5.4) application serving a REST interface. We use Hibernate envers for audit logging. This service sends messages on our Service Bus in an asynchronous fashion via the ServiceBusSenderAsyncClient from the Azure SDK.
Now this service needs to receive messages from said Service Bus and write updates to the Database - also async. For this we use ServiceBusReceiverAsyncClient with a reactive stream. All of this generally works (I wrapped the whole database interaction in one Transactional function) but I'm encountering issues with envers via the beforeTransactionCompletion callback being null (when I deactivate envers, it works). This issues is Service Bus independent from my understanding and really rotates around accessing the JPA repo from a background thread. Following the schematic implementation:

ServiceBusReceiveController

@Component
public class SubscriptionReceiveController {
  @Autowired
  private MyService myService;

  @Autowired
  private ServiceBusReceiverAsyncClient receiver;

  @Autowired
  private ObjectMapper mapper;

  @PostConstruct
  public void run() {
    // continuously receive messages in the background
    receiver.receiveMessages().flatMap(message -> {
      MyObject object;
      try {
        object = mapper.readValue(message.getBody().toString(), MyClass.class);
      } catch (JsonProcessingException e) {
        throw new JsonProcessingRuntimeException("Failed to convert message to object", e);
      }

      // wrap the blocking JPA interaction
      Mono<MyObject> blockingWrapper = Mono.fromCallable(() -> {
        return myService.updateMyObject(object.getId());
      });

      // When the service returns, this is where it crashes
      return blockingWrapper.subscribeOn(Schedulers.boundedElastic());
    }).flatMap(response -> {
      // More processing steps
    }).subscribe();
  }
}

MyService

@Service
public class MyService {

  @Autowired
  private MyRepository myRepository;

  @Transactional
  public MyObject updateMyObject(UUID objectId) {
    var object = myRepository.getById(objectId);
    object.setSomeProperty("myPropertyValue");

    return myRepository.save(object);
  }
}

Causing following error message:

org.springframework.orm.jpa.JpaSystemException: Unable to perform beforeTransactionCompletion callback: null; nested exception is org.hibernate.HibernateException: Unable to perform beforeTransactionCompletion callback: null
Caused by: org.hibernate.HibernateException: Unable to perform beforeTransactionCompletion callback: null
        at org.hibernate.engine.spi.ActionQueue$BeforeTransactionCompletionProcessQueue.beforeTransactionCompletion(ActionQueue.java:960) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.engine.spi.ActionQueue.beforeTransactionCompletion(ActionQueue.java:525) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2381) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:448) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) ~[spring-orm-5.3.9.jar:5.3.9]
        ... 20 common frames omitted

...

Caused by: java.lang.NullPointerException: null
        at com.my.package.revision.AuditRevisionListener.newRevision(AuditRevisionListener.java:10) ~[classes/:na]
        at org.hibernate.envers.internal.revisioninfo.DefaultRevisionInfoGenerator.generate(DefaultRevisionInfoGenerator.java:88) ~[hibernate-envers-5.4.28.Final.jar:5.4.28.Final]
        at org.hibernate.envers.internal.synchronization.AuditProcess.getCurrentRevisionData(AuditProcess.java:133) ~[hibernate-envers-5.4.28.Final.jar:5.4.28.Final]
        at org.hibernate.envers.internal.synchronization.AuditProcess.executeInSession(AuditProcess.java:115) ~[hibernate-envers-5.4.28.Final.jar:5.4.28.Final]
        at org.hibernate.envers.internal.synchronization.AuditProcess.doBeforeTransactionCompletion(AuditProcess.java:174) ~[hibernate-envers-5.4.28.Final.jar:5.4.28.Final]
        at org.hibernate.envers.internal.synchronization.AuditProcessManager$1.doBeforeTransactionCompletion(AuditProcessManager.java:47) ~[hibernate-envers-5.4.28.Final.jar:5.4.28.Final]
        at org.hibernate.engine.spi.ActionQueue$BeforeTransactionCompletionProcessQueue.beforeTransactionCompletion(ActionQueue.java:954) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
        ... 28 common frames omitted

What am I missing here, why is the transaction not fully finished within the Service implementation? Is there a better way/pattern for a background thread to write to a database via JPA?

Thanks

Body:
I was facing the same problem with RevisionListener. It seems that there is a lack of communication between Spring Framework and Hibernate Envers as described in this issue:
https://github.com/spring-projects/spring-data-envers/issues/249.

Even after annotating my CustomRevisionListener with @Service, spring cannot find this bean and create an instance of it.

I've tried all the solutions listed here:
How to inject spring beans into the hibernate envers RevisionListener

But only the solution using the SecurityContextHolder (Solution 3) worked for me. I just needed to check if my entity that represents the logged user had an Id property and fill it with the user id that was retrieved from the database.

Here is my code:

public class MyRevisionListener implements RevisionListener {

   @Override
   public void newRevision(Object entity) {
      MyRevisionEntity revisionEntity = (MyRevisionEntity) entity;

      Long loggedUserId = Optional.ofNullable(SecurityContextHolder.getContext())
            .map(SecurityContext::getAuthentication)
            .filter(Authentication::isAuthenticated)
            .map(Authentication::getPrincipal)
            .map(JwtUser.class::cast)
            .map(JwtUser::getId)
            .orElse(null);

      revisionEntity.setUserId(loggedUserId);
      revisionEntity.setDate(new Date());
   }
}


问:
Finding rows which match the average value of a column
I'm using Oracle 11g. I have a couple of tables which look something like this (simplified a bit).

```<code>CREATE TABLE clients (
    id NUMBER(10) NOT NULL,
    gridx NUMBER(10),
    gridy NUMBER(10),
    CONSTRAINT clients_pk PRIMARY KEY (id)
);

CREATE TABLE requests (
    id NUMBER(10) NOT NULL,
    client_id NUMBER(10),
    CONSTRAINT clients_fk FOREIGN KEY (client_id) REFERENCES clients(id),
    CONSTRAINT requests_pk PRIMARY KEY (id)
);
</code>```

I need to find the grid sections which have seen the average number of requests. So far, I have come up with the following query which lists the number of requests made for each distinct grid location.

```<code>SELECT joined_tbl.gridx, joined_tbl.gridy, COUNT(joined_tbl.id) requests_cnt FROM (
    SELECT c.gridx, c.gridy, r.id
    FROM requests r
    INNER JOIN clients c ON c.id=r.client_id GROUP BY c.gridx, c.gridy, r.id ORDER BY r.id
) joined_tbl
GROUP BY joined_tbl.gridx, joined_tbl.gridy;
</code>```

This gives the following output

```<code> GRIDX      GRIDY REQUESTS_CNT
     1         -3            2
     2          5            4
    -1         -3            4
    -3         -2            6
</code>```

Next I need to take the average of the REQUESTS_CNT column and list all the rows which match the average value. How can I go about this? I can't use the AVG function in a WHERE clause, which I considered, so should I be using HAVING?

答:
Your query can be boiled down to:

```<code>SELECT c.gridx, c.gridy, COUNT(*) AS requests_cnt
FROM requests r
JOIN clients c ON c.id = r.client_id
GROUP BY c.gridx, c.gridy;
</code>```

i.e. get the request count per gridx/gridy. You want to determine the average count and then only show gridx/gridy pairs that occur exactly that often. In your example this would be the pairs (2|5), (-1|-3), but most often, I guess, that would be no pairs at all.

The easiest approach seems to be to get the average on-the-fly by applying AVG OVER:

```<code>SELECT gridx, gridy
FROM
(
  SELECT
    c.gridx, c.gridy, COUNT(*) AS requests_cnt,
    AVG(COUNT(*)) OVER () AS avg_requests_cnt
  FROM requests r
  JOIN clients c ON c.id = r.client_id
  GROUP BY c.gridx, c.gridy
) pairs
WHERE requests_cnt = avg_requests_cnt
ORDER BY gridx, gridy;
</code>```

Body:
I'm using Oracle 11g. I have a couple of tables which look something like this (simplified a bit).

CREATE TABLE clients (
    id NUMBER(10) NOT NULL,
    gridx NUMBER(10),
    gridy NUMBER(10),
    CONSTRAINT clients_pk PRIMARY KEY (id)
);

CREATE TABLE requests (
    id NUMBER(10) NOT NULL,
    client_id NUMBER(10),
    CONSTRAINT clients_fk FOREIGN KEY (client_id) REFERENCES clients(id),
    CONSTRAINT requests_pk PRIMARY KEY (id)
);

I need to find the grid sections which have seen the average number of requests. So far, I have come up with the following query which lists the number of requests made for each distinct grid location.

SELECT joined_tbl.gridx, joined_tbl.gridy, COUNT(joined_tbl.id) requests_cnt FROM (
    SELECT c.gridx, c.gridy, r.id
    FROM requests r
    INNER JOIN clients c ON c.id=r.client_id GROUP BY c.gridx, c.gridy, r.id ORDER BY r.id
) joined_tbl
GROUP BY joined_tbl.gridx, joined_tbl.gridy;

This gives the following output

 GRIDX      GRIDY REQUESTS_CNT
     1         -3            2
     2          5            4
    -1         -3            4
    -3         -2            6

Next I need to take the average of the REQUESTS_CNT column and list all the rows which match the average value. How can I go about this? I can't use the AVG function in a WHERE clause, which I considered, so should I be using HAVING?

Body:
Your query can be boiled down to:

SELECT c.gridx, c.gridy, COUNT(*) AS requests_cnt
FROM requests r
JOIN clients c ON c.id = r.client_id
GROUP BY c.gridx, c.gridy;

i.e. get the request count per gridx/gridy. You want to determine the average count and then only show gridx/gridy pairs that occur exactly that often. In your example this would be the pairs (2|5), (-1|-3), but most often, I guess, that would be no pairs at all.

The easiest approach seems to be to get the average on-the-fly by applying AVG OVER:

SELECT gridx, gridy
FROM
(
  SELECT
    c.gridx, c.gridy, COUNT(*) AS requests_cnt,
    AVG(COUNT(*)) OVER () AS avg_requests_cnt
  FROM requests r
  JOIN clients c ON c.id = r.client_id
  GROUP BY c.gridx, c.gridy
) pairs
WHERE requests_cnt = avg_requests_cnt
ORDER BY gridx, gridy;


问:
Redshift LIKE from a list of values
I would like to filter from my table orders all zipcodes that start with the letters "B1", "NW1", "C13", etc. For example, postcodes in the UK can be "NW8 8AB".

I am using this query in Redshift but it is very inefficient now that I have a list of 500 codes.

```<code>select * from orders
where zipcode like 'B1%' or zipcode like 'NW1%' or zipcode like 'C13%'
</code>```

Is there a way of doing it in a more efficient way?

I was thinking something like:

```<code>select * from orders
where zipcode like ('B1', 'NW1', 'C13') + %
</code>```

But, obviously, it doesn't work.

Thank you very much.

答:
I found the solution, which looks at all the content before the first space, which for this case it works given that I only have the first part of the postcodes before the space.</p>
```<code>select * from orders
where split_part(zipcode, ' ', 1) like ('B1', 'NW1', 'C13')
</code>```

Title: Redshift LIKE from a list of values

Body:
I would like to filter from my table orders all zipcodes that start with the letters "B1", "NW1", "C13", etc. For example, postcodes in the UK can be "NW8 8AB".

I am using this query in Redshift but it is very inefficient now that I have a list of 500 codes.

select * from orders
where zipcode like 'B1%' or zipcode like 'NW1%' or zipcode like 'C13%'

Is there a way of doing it in a more efficient way?

I was thinking something like:

select * from orders
where zipcode like ('B1', 'NW1', 'C13') + %

But, obviously, it doesn't work.

Thank you very much.

Body:
I found the solution, which looks at all the content before the first space, which for this case it works given that I only have the first part of the postcodes before the space.

select * from orders
where split_part(zipcode, ' ', 1) like ('B1', 'NW1', 'C13')


问:
React.Component vs React.PureComponent
The official React docs state that "React.PureComponent's shouldComponentUpdate() only shallowly compares the objects", and advises against this if state is "deep".

Given this, is there any reason why one should prefer React.PureComponent when creating React components?

Questions:

is there any performance impact in using React.Component that we may consider going for React.PureComponent?

I am guessing  shouldComponentUpdate() of PureComponent performs only shallow comparisons. If this is the case, can't said method be used for deeper comparisons?

"Furthermore, React.PureComponent's shouldComponentUpdate() skips prop updates for the whole component subtree" - Does this mean that prop changes are ignored?

Question arose from reading into this medium blog, if it helps.

答: I think PureComponent are more efficient than the Regular Component. The fact is that you don't have to write too much of code and it will handle the shouldComponentUpdate() method for you.

Title: React.Component vs React.PureComponent


问:
How can I find the name of axis in multiple range axis JFreeChart?
I have 3 variables in Y axis and I am trying to get the name of the axis according to value which I look for.

.

Variables are attached here. I can get the value of the variable with label, but I can't get the name of variable.

.

I want to write the name of the variable in front of the label. How can I find it? My code looks like:

```<code>public void chartMouseMoved(ChartMouseEvent event){
   ChartEntity chartEntity = event.getEntity();
   if ( chartEntity instanceof XYItemEntity) {
      XYItemEntity xyItemEntity = (XYItemEntity) chartEntity;
      XYDataSet xyDataSet = xyItemEntity.getDataset();

      double xValue = xyDataSet .getXValue(xyItemEntity.getSeriesIndex(), xyItemEntity.getItem());
      double yValue = xyDataSet .getYValue(xyItemEntity.getSeriesIndex(), xyItemEntity.getItem());

      this.xCrosshair.setValue(xValue);
      this.yCrosshair.setValue(yValue);

      label.setText(String.format("%.2f, yValue));
      label.setSize(label.getPreferredSize());

      }
   }
}
</code>```

答:
An XYPlot has methods to access the axes used to construct the chart. Starting from this complete, two-axis example, the following loop prints the names of the range axes to the console:

```<code>for (int i = 0; i < plot.getRangeAxisCount(); i++) {
    System.out.println(plot.getRangeAxis(i).getLabel());
}
</code>```

Console:

```<code>Meters
Feet
</code>```

Body:
I have 3 variables in Y axis and I am trying to get the name of the axis according to value which I look for.

.

Variables are attached here. I can get the value of the variable with label, but I can't get the name of variable.

.

I want to write the name of the variable in front of the label. How can I find it? My code looks like:

public void chartMouseMoved(ChartMouseEvent event){
   ChartEntity chartEntity = event.getEntity();
   if ( chartEntity instanceof XYItemEntity) {
      XYItemEntity xyItemEntity = (XYItemEntity) chartEntity;
      XYDataSet xyDataSet = xyItemEntity.getDataset();

      double xValue = xyDataSet .getXValue(xyItemEntity.getSeriesIndex(), xyItemEntity.getItem());
      double yValue = xyDataSet .getYValue(xyItemEntity.getSeriesIndex(), xyItemEntity.getItem());

      this.xCrosshair.setValue(xValue);
      this.yCrosshair.setValue(yValue);

      label.setText(String.format("%.2f, yValue));
      label.setSize(label.getPreferredSize());

      }
   }
}

Body:
An XYPlot has methods to access the axes used to construct the chart. Starting from this complete, two-axis example, the following loop prints the names of the range axes to the console:

for (int i = 0; i < plot.getRangeAxisCount(); i++) {
    System.out.println(plot.getRangeAxis(i).getLabel());
}

Console:

Meters
Feet


问:
How to import packages into another package(or files in the same package) using "import" explicitly only once
I'm using chisel based on scala with IntilliJ IDEA. The files in my project are in the same package named mypackage, and I need to import the chisel's library:

// file1.scala
package mypackage
import chisel3._
import chisel3.util._
/** my code */

// file2.scala
package mypackage
import chisel3._
import chisel3.util._
/** my code */

...

I hope to automatically/implicitly add the two libraries above to all files in mypackage, so that I don't need to repeat "import" in every file.

Thanks!

答: I would suggest not to do that because we can import each class specifically in scala. You should make use of that advantage. I had answered a similar question long back. Importing a particular class makes it light weight. That way you are importing only the packages you are using. https://stackoverflow.com/a/59148346/12197961 If you are looking to just optimize your code and reduce the number of lines in your code you can probably do this. https://stackoverflow.com/a/5745305/12197961</p>


问:
How to get the tallest height of a div in every 3
I want to get the tallest height of a div in blocks of 3 - as I have a 3 column layout -

```<code>var maxHeight = 0;
$(".grid-item .inner .content").each(function() {
if ($(this).outerHeight() > maxHeight) {
  maxHeight = $(this).outerHeight();
}
}).height(maxHeight);
</code>```

This gets the tallest height of ".grid-item .inner .content" - but I want to get the tallest height of the first 3 ".grid-item .inner .content" divs, then set those 3 to the tallest height, then get the tallest height of the next 3 - set it again, etc etc...

Any thoughts on how to achieve this?

so i was thinking of looking at divs 1-3 - setting a var for that tallest height - then applying that to divs 1-3, then looking at divs 4-6, again get the tallest height in a var, set that var to the height of divs 4-6 but I cant get my head around how...

.content {
border: 1px solid red;
}
.grid-item {
width: 33%;
display: inline-block;
vertical-align: top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>

   function logicCall() {

    var maxHeight = 0;
       $(".grid-item .inner .content").each(function() {
        if ($(this).outerHeight() > maxHeight) {
        maxHeight = $(this).outerHeight();
        }
       }).height(maxHeight);

   }

    logicCall();

</script>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>Content goes here</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>Content goes here, so this one is gonna be taller than the 1st and 3rd one...</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>Content goes here for 3rd item</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>4th Content goes here</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>5th item is this one</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>6th item</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>7th Content goes here, 7th Content goes here, 7th Content goes here, 7th Content goes here,</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>8th item is this one</p>
</div>
</div>
</div>

<div class="grid-item">
<div class="inner">
<div class="content">
<p>9th item</p>
</div>
</div>
</div></code>```

答:
Here's one way - use a counter and when it hits 3, loop back and set the height

let maxHeight = 0,
  tmp = [];
let els = $(".grid-item .inner .content");
els.each(function(i) {
  i = i + 1;
  maxHeight = Math.max($(this).outerHeight(), maxHeight);
  tmp.push($(this))
  if (i % 3 === 0 || i >= els.length) {
    // go back and apply
    // console.log('setting h:', maxHeight);
    tmp.forEach(div => div.height(maxHeight))
    maxHeight = 0;
    tmp = [];
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content {
  border: 1px solid #ccc;
  width: 200px;
  float: left;
}</code>```

      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
      sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
      incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea
      voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
      sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
      incidunt ut labore et dolore magnam

      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
      sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione

      Sed ut perspiciatis

      Sed ut perspiciatis unde omnis iste natus error sit voluptatem

      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim

      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
      sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
      incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea
      voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas

```

Body:
I want to get the tallest height of a div in blocks of 3 - as I have a 3 column layout -

var maxHeight = 0;
$(".grid-item .inner .content").each(function() {
if ($(this).outerHeight() > maxHeight) {
  maxHeight = $(this).outerHeight();
}
}).height(maxHeight);

This gets the tallest height of ".grid-item .inner .content" - but I want to get the tallest height of the first 3 ".grid-item .inner .content" divs, then set those 3 to the tallest height, then get the tallest height of the next 3 - set it again, etc etc...

Any thoughts on how to achieve this?

so i was thinking of looking at divs 1-3 - setting a var for that tallest height - then applying that to divs 1-3, then looking at divs 4-6, again get the tallest height in a var, set that var to the height of divs 4-6 but I cant get my head around how...

.content {
border: 1px solid red;
}
.grid-item {
width: 33%;
display: inline-block;
vertical-align: top;
}

Content goes here

Content goes here, so this one is gonna be taller than the 1st and 3rd one...

Content goes here for 3rd item

4th Content goes here

5th item is this one

6th item

7th Content goes here, 7th Content goes here, 7th Content goes here, 7th Content goes here,

8th item is this one

9th item

Body:
Here's one way - use a counter and when it hits 3, loop back and set the height

let maxHeight = 0,
  tmp = [];
let els = $(".grid-item .inner .content");
els.each(function(i) {
  i = i + 1;
  maxHeight = Math.max($(this).outerHeight(), maxHeight);
  tmp.push($(this))
  if (i % 3 === 0 || i >= els.length) {
    // go back and apply
    // console.log('setting h:', maxHeight);
    tmp.forEach(div => div.height(maxHeight))
    maxHeight = 0;
    tmp = [];
  }

});

.content {
  border: 1px solid #ccc;
  width: 200px;
  float: left;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='grid-item'>
  <div class='inner'>
    <div class='content'>
      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
      sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
      incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea
      voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
    </div>

    <div class='content'>
      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
      sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
      incidunt ut labore et dolore magnam
    </div>

    <div class='content'>
      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
      sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione
    </div>

    <div class='content'>
      Sed ut perspiciatis
    </div>

    <div class='content'>
      Sed ut perspiciatis unde omnis iste natus error sit voluptatem
    </div>

    <div class='content'>
      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim
    </div>

    <div class='content'>
      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
      sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
      incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea
      voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
    </div>

    <div class='content'>
      Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas

    </div>
  </div>
</div>


问:
Change the color of particular card on taping it in flutter?
I am using flutter I want to change the color of a particular card when I tap on it, not all the cards at the same time. The code is attached below. I am glad if someone helps.
...

```<code>Widget options(context,String title,String subtitle,String price,

  String info, String plan) {
return GestureDetector(
  child: Container(
    height: 166,
    width: 119,
    child: Card(
      color: Colors.white,
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Container(
            width: 120,
            decoration: BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.only(
                topLeft: const Radius.circular(7),
                topRight: const Radius.circular(7),
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.only(bottom: 8, top: 8),
              child: Text(
                title,
                textAlign: TextAlign.center,
                style: TextStyle(
                    color: Color.fromRGBO(255, 255, 255, 1),
                    fontSize: 15,
                    fontFamily: 'CeroPro',
                    fontWeight: FontWeight.bold),
              ),
            ),
            ),
          )
        ],
      ),
    ),
  ),
);
</code>```

}
}
...

答:
You could use a stateful widget.

So it would look something like this

```<code>class MyCard extends StatefulWidget {
  MyCard(this.title, this.subtitle, this.price, this.info, this.plan);
  String title;
  String subtitle;
  String price;

  String info;
  String plan;
  @override
  _MyCardState createState() => _MyCardState();
}

class _MyCardState extends State<MyCard> {
  // initial color
  Color color = Colors.white;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          //where newColor is the color it turns to
          color = newColor;
        });
      },
      child: Container(
        height: 166,
        width: 119,
        child: Card(
          // color is now a variable
          color: color,
          elevation: 3,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            children: [
              Container(
                width: 120,
                decoration: BoxDecoration(
                  color: Colors.black,
                  borderRadius: BorderRadius.only(
                    topLeft: const Radius.circular(7),
                    topRight: const Radius.circular(7),
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.only(bottom: 8, top: 8),
                  child: Text(
                    // to access the stateful widget's parameters, use widget.<parameter>
                    widget.title,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: Color.fromRGBO(255, 255, 255, 1),
                        fontSize: 15,
                        fontFamily: 'CeroPro',
                        fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Body:
I am using flutter I want to change the color of a particular card when I tap on it, not all the cards at the same time. The code is attached below. I am glad if someone helps.
...

Widget options(context,String title,String subtitle,String price,

  String info, String plan) {
return GestureDetector(
  child: Container(
    height: 166,
    width: 119,
    child: Card(
      color: Colors.white,
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Container(
            width: 120,
            decoration: BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.only(
                topLeft: const Radius.circular(7),
                topRight: const Radius.circular(7),
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.only(bottom: 8, top: 8),
              child: Text(
                title,
                textAlign: TextAlign.center,
                style: TextStyle(
                    color: Color.fromRGBO(255, 255, 255, 1),
                    fontSize: 15,
                    fontFamily: 'CeroPro',
                    fontWeight: FontWeight.bold),
              ),
            ),
            ),
          )
        ],
      ),
    ),
  ),
);

}
}
...

Body:
You could use a stateful widget.

So it would look something like this

class MyCard extends StatefulWidget {
  MyCard(this.title, this.subtitle, this.price, this.info, this.plan);
  String title;
  String subtitle;
  String price;

  String info;
  String plan;
  @override
  _MyCardState createState() => _MyCardState();
}

class _MyCardState extends State<MyCard> {
  // initial color
  Color color = Colors.white;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          //where newColor is the color it turns to
          color = newColor;
        });
      },
      child: Container(
        height: 166,
        width: 119,
        child: Card(
          // color is now a variable
          color: color,
          elevation: 3,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            children: [
              Container(
                width: 120,
                decoration: BoxDecoration(
                  color: Colors.black,
                  borderRadius: BorderRadius.only(
                    topLeft: const Radius.circular(7),
                    topRight: const Radius.circular(7),
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.only(bottom: 8, top: 8),
                  child: Text(
                    // to access the stateful widget's parameters, use widget.<parameter>
                    widget.title,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: Color.fromRGBO(255, 255, 255, 1),
                        fontSize: 15,
                        fontFamily: 'CeroPro',
                        fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


问:
Algorithm for slicing a dynamic graph
I am currently working on a project based on graph and I am searching for an algorithm for slicing an dynamic graph. I have already done some research but most algorithms that I have found works only for a static graph. In my environment, the graph is dynamic, it means that users add/delete elements, create/delete dependences at runtime.
(In reality I am working with UML models but UML models can be also represented by typed graphs, wich are composed of typed Vertices and edges)
I also search for the terms graph fragmentation but I did not find anything. And I would like to know if exist such algorithm for slicing a dynamic graph?

[UPDATE]

Sorry for not being clear and I am updating my question.Let me first expose the context.

In MDE (Model Driven Engineering), large-scale industrial systems involve nowadays hundreds of developpers working on hundreds of models representing pars of the whole system specification. In a such context, the approach commonly adopted is to use a central repository. The solution I provide for my project (I am currently working on a research lab), is a solution which is peer-to-peer oriented, that means that every developper has his own replication of the system specification.

My main problem is how to replicate this data, the models.
For instance, imagine Alice and Bob working on this UML diagram and Alice has the whole diagram in his repository. Bob wants to have the elements {FeedOrEntry, Entry}, how can I slice this diagram UML?
I search for the terms of "model Slicing".I have found one paper which gives an approach for slicing UML Class Diagrams but the problem with this algorithm is it only works for a static graph. In our context, developpers add/update/remove elements constantly and the shared elements should be consistent with the other replicas.

Since UML Models can also be seen as a graph, I also search for the terms for "graph slicing" or "graph fragment" but I have found nothing useful.
And I would like to know if exist such algorithm for slicing a dynamic graph

答: Sounds like maybe you need a NoSQL graph database such as Neo4J or FlockDB.  They can store billions of vertexes and edges.</p>

Title: Algorithm for slicing a dynamic graph


问:
MySQL: Invalid use of group function
I am using MySQL. Here is my schema:

Suppliers(sid: integer, sname: string, address string)

Parts(pid: integer, pname: string, color: string)

Catalog(sid: integer, pid: integer, cost: real)

(primary keys are bolded)

I am trying to write a query to select all parts that are made by at least two suppliers:

```<code>-- Find the pids of parts supplied by at least two different suppliers.
SELECT c1.pid                      -- select the pid
FROM Catalog AS c1                 -- from the Catalog table
WHERE c1.pid IN (                  -- where that pid is in the set:
    SELECT c2.pid                  -- of pids
    FROM Catalog AS c2             -- from catalog
    WHERE c2.pid = c1.pid AND COUNT(c2.sid) >= 2 -- where there are at least two corresponding sids
);
</code>```

First off, am I even going about this the right way?

Secondly, I get this error:

1111 - Invalid use of group function

What am I doing wrong?

答:
If you don't have an aggregate function in your where clause, another possible source of the 1111 - Invalid use of group function error is if you have nested aggregate functions:

```<code>select sum(avg(close)) from prices;
(1111, 'Invalid use of group function')
</code>```

You can get around this by breaking up the problem into two steps:

Save the inner aggregation into a variable

```<code>select @avg:=avg(close) from prices;
</code>```

Run the outer aggregation against the variable

```<code>select sum(@avg) from prices;
</code>```

Title: MySQL: Invalid use of group function

Body:
I am using MySQL. Here is my schema:

Suppliers(sid: integer, sname: string, address string)

Parts(pid: integer, pname: string, color: string)

Catalog(sid: integer, pid: integer, cost: real)

(primary keys are bolded)

I am trying to write a query to select all parts that are made by at least two suppliers:

-- Find the pids of parts supplied by at least two different suppliers.
SELECT c1.pid                      -- select the pid
FROM Catalog AS c1                 -- from the Catalog table
WHERE c1.pid IN (                  -- where that pid is in the set:
    SELECT c2.pid                  -- of pids
    FROM Catalog AS c2             -- from catalog
    WHERE c2.pid = c1.pid AND COUNT(c2.sid) >= 2 -- where there are at least two corresponding sids
);

First off, am I even going about this the right way?

Secondly, I get this error:

1111 - Invalid use of group function

What am I doing wrong?

Body:
If you don't have an aggregate function in your where clause, another possible source of the 1111 - Invalid use of group function error is if you have nested aggregate functions:

select sum(avg(close)) from prices;
(1111, 'Invalid use of group function')

You can get around this by breaking up the problem into two steps:

Save the inner aggregation into a variable

select @avg:=avg(close) from prices;

Run the outer aggregation against the variable

select sum(@avg) from prices;


问:
Get Spotify access token with spotipy on Django and Python
I'm new to Django and I'm trying to link Spotify to my webapp. I'm using Spotify to do it and it correctly access to Spotify.

To do it I have a button that opens the view below

views.py

```<code>@authenticated_user
def spotify_login(request):

    sp_auth = SpotifyOAuth(client_id=str(os.getenv('SPOTIPY_CLIENT_ID')),
                           client_secret=str(os.getenv('SPOTIPY_CLIENT_SECRET')),
                           redirect_uri="http://127.0.0.1:8000/",
                           scope="user-library-read")
    redirect_url = sp_auth.get_authorize_url()
    auth_token = sp_auth.get_access_token()
    print(auth_token)
    print("----- this is the AUTH_TOKEN url -------", auth_token)
    return HttpResponseRedirect(redirect_url)
</code>```

If I don't use auth_token = sp_auth.get_access_token() everything works fine and I got redirected to the correct. Unfortunately, if I add that line of code to access the access token, instead of staying on the same page, it opens another tab on the browser with the Spotify auth_code and lets the original page load forever.

Is there a way to retrieve the access token in the background without making my view reload or open another tab in the browser?

答:
You are being redirected to exactly where you are telling django to go.

redirect_url is just a spotify api redirect containing a code, which is captured and used to get the access token.

Set your expected response as return value.

By the way, keep in mind:

redirect_uri="http://127.0.0.1:8000/", should be added in spotify app (usually as http://127.0.0.1:8000/callback",)

auth_token is a json, you can find token in auth_token['access_token']

Body:
I'm new to Django and I'm trying to link Spotify to my webapp. I'm using Spotify to do it and it correctly access to Spotify.

To do it I have a button that opens the view below

views.py

@authenticated_user
def spotify_login(request):

    sp_auth = SpotifyOAuth(client_id=str(os.getenv('SPOTIPY_CLIENT_ID')),
                           client_secret=str(os.getenv('SPOTIPY_CLIENT_SECRET')),
                           redirect_uri="http://127.0.0.1:8000/",
                           scope="user-library-read")
    redirect_url = sp_auth.get_authorize_url()
    auth_token = sp_auth.get_access_token()
    print(auth_token)
    print("----- this is the AUTH_TOKEN url -------", auth_token)
    return HttpResponseRedirect(redirect_url)

If I don't use auth_token = sp_auth.get_access_token() everything works fine and I got redirected to the correct. Unfortunately, if I add that line of code to access the access token, instead of staying on the same page, it opens another tab on the browser with the Spotify auth_code and lets the original page load forever.

Is there a way to retrieve the access token in the background without making my view reload or open another tab in the browser?