问:
How to get img on the bottom & center of div without using absolute position
I am pretty new in HTML and CSS (2 weeks) and this is the first time iam using Stack overflow.
i am trying to make position of a img on the bottom of the div and in the center of the bottom side and are not able to find solution. I would like to do it without using position: absolute because img will move when you open page on smaller/bigger screen

it is this image i would like to move:"

body {
  text-align: center;
  margin:0;
}

h1 {
  font-size: 5.6rem;
  margin:0;
  color: white;
  line-height: 2;
  font-family: 'Clicker Script', cursive;
}

h2 {
  font-weight: normal;
  font-family: 'Kavivanar', cursive;
}

.nav {
  background-color: #87c6eb;
  text-align: right;
  padding-top: 50px;
}

.top {
  background-color: #87c6eb;
  height: 100vh;
}

.programer {
  font-size: 150%;
  color: white;
}

.top-cloud {
  position:absolute;
  top:100px;
  right: 300px;
  opacity: 70%;
}

.bottom-cloud {
  position:absolute;
  left: 350px;
  opacity: 45%;
}

.mnt {
  /* ???????? */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="top">
  <nav class="nav">
    About
    Work
    Contact
  </nav>
  <img class="top-cloud" src="cloud.png" alt="cloud img">
  <h1>I`m Veljko</h1>
  <h2 class="programer"><em>future programmer</em></h2>
  <img class="bottom-cloud" src="cloud.png" alt="cloud img">
  <img class="mnt"  src="mountain.png" alt="mountain img">
</div></code>```

答:
You can try this, it worked for me.</p>

```<code>#footer {
    position: fixed;
    bottom: 0;
    width: 100%;
}
<div id="footer">
    <img class="mnt"  src="mountain.png" alt="mountain img">
</div>
</code>```

Body:
I am pretty new in HTML and CSS (2 weeks) and this is the first time iam using Stack overflow.
i am trying to make position of a img on the bottom of the div and in the center of the bottom side and are not able to find solution. I would like to do it without using position: absolute because img will move when you open page on smaller/bigger screen

it is this image i would like to move:"

body {
  text-align: center;
  margin:0;
}

h1 {
  font-size: 5.6rem;
  margin:0;
  color: white;
  line-height: 2;
  font-family: 'Clicker Script', cursive;
}

h2 {
  font-weight: normal;
  font-family: 'Kavivanar', cursive;
}

.nav {
  background-color: #87c6eb;
  text-align: right;
  padding-top: 50px;
}

.top {
  background-color: #87c6eb;
  height: 100vh;
}

.programer {
  font-size: 150%;
  color: white;
}

.top-cloud {
  position:absolute;
  top:100px;
  right: 300px;
  opacity: 70%;
}

.bottom-cloud {
  position:absolute;
  left: 350px;
  opacity: 45%;
}

.mnt {
  /* ???????? */
}

    About
    Work
    Contact

I`m Veljko

future programmer

Body:
You can try this, it worked for me.

#footer {
    position: fixed;
    bottom: 0;
    width: 100%;
}
<div id="footer">
    <img class="mnt"  src="mountain.png" alt="mountain img">
</div>


来源: stackexchange

问:
Decorators with parameters?
I have a problem with the transfer of the variable insurance_mode by the decorator. I would do it by the following decorator statement:

```<code>@execute_complete_reservation(True)
def test_booking_gta_object(self):
    self.test_select_gta_object()
</code>```

but unfortunately, this statement does not work. Perhaps maybe there is better way to solve this problem.

```<code>def execute_complete_reservation(test_case,insurance_mode):
    def inner_function(self,*args,**kwargs):
        self.test_create_qsf_query()
        test_case(self,*args,**kwargs)
        self.test_select_room_option()
        if insurance_mode:
            self.test_accept_insurance_crosseling()
        else:
            self.test_decline_insurance_crosseling()
        self.test_configure_pax_details()
        self.test_configure_payer_details

    return inner_function
</code>```

答:
In case both the function and the decorator have to take arguments you can follow the below approach.

For example there is a decorator named decorator1 which takes an argument

```<code>@decorator1(5)
def func1(arg1, arg2):
    print (arg1, arg2)

func1(1, 2)
</code>```

Now if the decorator1 argument has to be dynamic, or passed while calling the function,

```<code>def func1(arg1, arg2):
    print (arg1, arg2)

a = 1
b = 2
seconds = 10

decorator1(seconds)(func1)(a, b)
</code>```

In the above code

seconds is the argument for decorator1

a, b are the arguments of func1

ContentLicense: CC BY-SA 4.0

Title: Decorators with parameters?

Body:
I have a problem with the transfer of the variable insurance_mode by the decorator. I would do it by the following decorator statement:

@execute_complete_reservation(True)
def test_booking_gta_object(self):
    self.test_select_gta_object()

but unfortunately, this statement does not work. Perhaps maybe there is better way to solve this problem.

def execute_complete_reservation(test_case,insurance_mode):
    def inner_function(self,*args,**kwargs):
        self.test_create_qsf_query()
        test_case(self,*args,**kwargs)
        self.test_select_room_option()
        if insurance_mode:
            self.test_accept_insurance_crosseling()
        else:
            self.test_decline_insurance_crosseling()
        self.test_configure_pax_details()
        self.test_configure_payer_details

    return inner_function

Body:
In case both the function and the decorator have to take arguments you can follow the below approach.

For example there is a decorator named decorator1 which takes an argument

@decorator1(5)
def func1(arg1, arg2):
    print (arg1, arg2)

func1(1, 2)

Now if the decorator1 argument has to be dynamic, or passed while calling the function,

def func1(arg1, arg2):
    print (arg1, arg2)

a = 1
b = 2
seconds = 10

decorator1(seconds)(func1)(a, b)

In the above code

seconds is the argument for decorator1

a, b are the arguments of func1


问:
How to get post values from first page to third page ,as post
i have 3 pages

Page1.php,page2.php,page3.php

In page1.php, i have some hidden values, for example 'name'

After the submission of page1.php, it will go to page2.

Then after some process in page2.php, it should need to automatically submit to page3.php(where page3.php is in another sever)

Finally,when i print the $_POST  variables in page3.php, i need to get the variable 'name'

答:
(1) Option is to add hidden input on page2 too.

(2) Option is to set the value from page1's name into session and use it on page3

ContentLicense: CC BY-SA 3.0


问:
Place ImageButton in top left corner
I have a very simple fragment layout (fragment_search.xml):

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.review.SearchFragment">

        <ImageButton
            android:id="@+id/search_bar_button"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:contentDescription="@string/switch_to_search_bar"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/ic_search_bar" />

        <TextView
            android:id="@+id/text_search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:textAlignment="center"
            android:textSize="20sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

The fragment is hosted by activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

My intention is for the ImageButton in fragment_search.xml to appear in the top-left corner with no gaps.  For some reason, when I run the app, the icon appears with a large gap above and a small gap to the left:

In Design view, the button appears in the top-left corner but with a 1mm gap between the button and the edge of the screen.

Why is the button not appearing in the top-left corner when I run the app, and how do I fix it?

答:
remove padding top from your activity root layout (contraintlayout) in activity_main.xml

android:paddingTop="?attr/actionBarSize"

Title: Place ImageButton in top left corner

Body:
I have a very simple fragment layout (fragment_search.xml):

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.review.SearchFragment">

        <ImageButton
            android:id="@+id/search_bar_button"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:contentDescription="@string/switch_to_search_bar"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/ic_search_bar" />

        <TextView
            android:id="@+id/text_search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:textAlignment="center"
            android:textSize="20sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

The fragment is hosted by activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

My intention is for the ImageButton in fragment_search.xml to appear in the top-left corner with no gaps.  For some reason, when I run the app, the icon appears with a large gap above and a small gap to the left:

In Design view, the button appears in the top-left corner but with a 1mm gap between the button and the edge of the screen.

Why is the button not appearing in the top-left corner when I run the app, and how do I fix it?


问:
AWS Beanstalk with Django: eb create complains about unknown config setting 'StaticFile'
I'm trying to deploy a django app with Elasticbeanstalk, following this setup

https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html

and this

https://www.1strategy.com/blog/2017/05/23/tutorial-django-elastic-beanstalk/

At the first attempt, in the .ebextension/django.config, I have

```<code>option_settings:
  "aws:elasticbeanstalk:application:environment":
    DJANGO_SETTINGS_MODULE: "my_django_path_name.settings"
    PYTHONPATH: "$PYTHONPATH"
  "aws:elasticbeanstalk:container:python":
    WSGIPath: "my_django_path_name/wsgi.py"
    StaticFiles: "/static/=www/static/"
</code>```

when calling eb create, it complains about

```<code>ERROR: ServiceError - Configuration validation exception: Invalid option specification (Namespace:
'aws:elasticbeanstalk:container:python', OptionName: 'StaticFiles'): Unknown configuration setting.
</code>```

So I took out the StaticFiles part, and eventually it becomes

```<code>option_settings:
  "aws:elasticbeanstalk:container:python":
    WSGIPath: "my_django_path_name/wsgi.py"
</code>```

and it STILL complains about the unknown OptionName: StaticFiles

Then I used the example in https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html#python-namespaces with minor tweaking

```<code>option_settings:
  aws:elasticbeanstalk:application:environment:
    DJANGO_SETTINGS_MODULE: production.settings

  aws:elasticbeanstalk:container:python:
    WSGIPath: ebdjango.wsgi:application
    NumProcesses: 3
    NumThreads: 20
</code>```

yet it STILL complains about the same thing.

I don't know where the StaticFiles option name is being read. It doesn't exist in the .config file. Is it cached somewhere or something?

答:
Based on the discussion in the comments, it was found that that the issue was caused by the fact eb was deploying an old version from git, rather then the local, corrected version of the application.

The solution was to push the changes to git so that new version get deployed.

Body:
I'm trying to deploy a django app with Elasticbeanstalk, following this setup

https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html

and this

https://www.1strategy.com/blog/2017/05/23/tutorial-django-elastic-beanstalk/

At the first attempt, in the .ebextension/django.config, I have

option_settings:
  "aws:elasticbeanstalk:application:environment":
    DJANGO_SETTINGS_MODULE: "my_django_path_name.settings"
    PYTHONPATH: "$PYTHONPATH"
  "aws:elasticbeanstalk:container:python":
    WSGIPath: "my_django_path_name/wsgi.py"
    StaticFiles: "/static/=www/static/"

when calling eb create, it complains about

ERROR: ServiceError - Configuration validation exception: Invalid option specification (Namespace:
'aws:elasticbeanstalk:container:python', OptionName: 'StaticFiles'): Unknown configuration setting.

So I took out the StaticFiles part, and eventually it becomes

option_settings:
  "aws:elasticbeanstalk:container:python":
    WSGIPath: "my_django_path_name/wsgi.py"

and it STILL complains about the unknown OptionName: StaticFiles

Then I used the example in https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html#python-namespaces with minor tweaking

option_settings:
  aws:elasticbeanstalk:application:environment:
    DJANGO_SETTINGS_MODULE: production.settings

  aws:elasticbeanstalk:container:python:
    WSGIPath: ebdjango.wsgi:application
    NumProcesses: 3
    NumThreads: 20

yet it STILL complains about the same thing.

I don't know where the StaticFiles option name is being read. It doesn't exist in the .config file. Is it cached somewhere or something?


问:
SQL Joining of Multiple Tables
SQL newbie here, I am trying to have the table print out the sum of the wages, make, and car model for all the people that own a particular make/model combination.  As of right now, the table prints out all the Car Make and Model values, but the SumWage column is all NULL. The SumWage should return the total sum of all the wages of people who have the Make/Model combination.(My select statement is all the way at the bottom of the code)?  All advice is much appreciated!</p>

```<code>IF OBJECT_ID ('Person', 'U') IS NULL

BEGIN

    CREATE TABLE Person (
        ID INT NOT NULL PRIMARY KEY,
        Name VARCHAR(32),
        BirthDate DATETIME
        );

    INSERT INTO Person
        ( ID, Name, BirthDate )
    VALUES
        (311113, 'Dan Lu', '01-22-33'),
        (123456, 'Seven Durant', '07-22-94'),
        (100100, 'Choochootrain Lu', '12-17-56'),
        (106542, 'Spider Ru', '07-22-36'),
        (101010, 'Ru Ru', '04-30-84');
END

IF OBJECT_ID ('Job', 'U') IS NULL

BEGIN

    CREATE TABLE Job (
        ID INT NOT NULL PRIMARY KEY,
        Company VARCHAR(64),
        Wage FLOAT,
        PersonID INT FOREIGN KEY REFERENCES Person(ID)
        );

    INSERT INTO Job
        ( ID, Company, Wage, PersonID )
    VALUES
        (01, 'Space Pizza Space', 1000.00, 311113),
        (02, 'Bread', 46.44, 101010),
        (03, 'Delivery Service', 400.99, 100100),
        (04, 'Nike', 999900.01, 106542),
        (05, 'Old McDonald', 6500210.77, 123456);
END

IF OBJECT_ID ('Car', 'U') IS NULL

BEGIN

    CREATE TABLE Car (
        ID INT NOT NULL PRIMARY KEY,
        Make VARCHAR(32),
        Model VARCHAR(32)
        );

    INSERT INTO Car
        ( ID, Make, Model )
    VALUES
        (1234, 'Lexus', 'SE'),
        (4444, 'Tesla', 'X'),
        (5007, 'Chevy', 'Cobalt'),
        (7771, 'Ford', 'Runner'),
        (6459, 'Toyota', 'Camry');
END

IF OBJECT_ID ('PersonCar', 'U') IS NULL

BEGIN

    CREATE TABLE PersonCar (
        ID INT,
        PersonID INT FOREIGN KEY REFERENCES Person(ID),
        CarID INT
        );

    INSERT INTO PersonCar
        ( ID, PersonID, CarID )
    VALUES
        (1, 311113, 1234),
        (2, 123456, 4444),
        (3, 100100, 5007),
        (4, 106542, 7771),
        (5, 101010, 6459);
END

SELECT SUM(Wage) AS SumWages, Car.Make, Car.Model
FROM Person
    INNER JOIN PersonCar
        ON PersonCar.ID = Person.ID
    INNER JOIN Job
        ON Job.PersonID = PersonCar.ID
    Right JOIN Car
        ON Car.ID = Person.ID
GROUP BY Wage, Make, Model;
</code>```

答:
I think that you want:

```<code>SELECT SUM(j.Wage) AS SumWages, c.Make, c.Model
FROM Car c
LEFT JOIN PersonCar pc ON pc.CarID = c.ID
LEFT JOIN Job j ON j.PersonID = pc.PersonID
GROUP BY c.Make, c.Model;
</code>```

This selects all Cars, and follows the relationships towards the Job table, that contains the Wage of each car owner. Data is aggregated by car model and model, and the corresponding wages are sumed.

When a given make/model tuple has no car owner, the sum comes out as null (if you want to just remove these rows from the resultset, use INNER JOINs instead of LEFT JOINs).

Note that you don't need to bring the Person table to get this resultset.

Title: SQL Joining of Multiple Tables

Body:
SQL newbie here, I am trying to have the table print out the sum of the wages, make, and car model for all the people that own a particular make/model combination.  As of right now, the table prints out all the Car Make and Model values, but the SumWage column is all NULL. The SumWage should return the total sum of all the wages of people who have the Make/Model combination.(My select statement is all the way at the bottom of the code)?  All advice is much appreciated!

IF OBJECT_ID ('Person', 'U') IS NULL

BEGIN

    CREATE TABLE Person (
        ID INT NOT NULL PRIMARY KEY,
        Name VARCHAR(32),
        BirthDate DATETIME
        );

    INSERT INTO Person
        ( ID, Name, BirthDate )
    VALUES
        (311113, 'Dan Lu', '01-22-33'),
        (123456, 'Seven Durant', '07-22-94'),
        (100100, 'Choochootrain Lu', '12-17-56'),
        (106542, 'Spider Ru', '07-22-36'),
        (101010, 'Ru Ru', '04-30-84');
END

IF OBJECT_ID ('Job', 'U') IS NULL

BEGIN

    CREATE TABLE Job (
        ID INT NOT NULL PRIMARY KEY,
        Company VARCHAR(64),
        Wage FLOAT,
        PersonID INT FOREIGN KEY REFERENCES Person(ID)
        );

    INSERT INTO Job
        ( ID, Company, Wage, PersonID )
    VALUES
        (01, 'Space Pizza Space', 1000.00, 311113),
        (02, 'Bread', 46.44, 101010),
        (03, 'Delivery Service', 400.99, 100100),
        (04, 'Nike', 999900.01, 106542),
        (05, 'Old McDonald', 6500210.77, 123456);
END

IF OBJECT_ID ('Car', 'U') IS NULL

BEGIN

    CREATE TABLE Car (
        ID INT NOT NULL PRIMARY KEY,
        Make VARCHAR(32),
        Model VARCHAR(32)
        );

    INSERT INTO Car
        ( ID, Make, Model )
    VALUES
        (1234, 'Lexus', 'SE'),
        (4444, 'Tesla', 'X'),
        (5007, 'Chevy', 'Cobalt'),
        (7771, 'Ford', 'Runner'),
        (6459, 'Toyota', 'Camry');
END

IF OBJECT_ID ('PersonCar', 'U') IS NULL

BEGIN

    CREATE TABLE PersonCar (
        ID INT,
        PersonID INT FOREIGN KEY REFERENCES Person(ID),
        CarID INT
        );

    INSERT INTO PersonCar
        ( ID, PersonID, CarID )
    VALUES
        (1, 311113, 1234),
        (2, 123456, 4444),
        (3, 100100, 5007),
        (4, 106542, 7771),
        (5, 101010, 6459);
END

SELECT SUM(Wage) AS SumWages, Car.Make, Car.Model
FROM Person
    INNER JOIN PersonCar
        ON PersonCar.ID = Person.ID
    INNER JOIN Job
        ON Job.PersonID = PersonCar.ID
    Right JOIN Car
        ON Car.ID = Person.ID
GROUP BY Wage, Make, Model;

Body:
I think that you want:

SELECT SUM(j.Wage) AS SumWages, c.Make, c.Model
FROM Car c
LEFT JOIN PersonCar pc ON pc.CarID = c.ID
LEFT JOIN Job j ON j.PersonID = pc.PersonID
GROUP BY c.Make, c.Model;

This selects all Cars, and follows the relationships towards the Job table, that contains the Wage of each car owner. Data is aggregated by car model and model, and the corresponding wages are sumed.

When a given make/model tuple has no car owner, the sum comes out as null (if you want to just remove these rows from the resultset, use INNER JOINs instead of LEFT JOINs).

Note that you don't need to bring the Person table to get this resultset.


问:
Qt: Storing a custom object in a collection by value
Let's say I have this class:

```<code>class Bear
{
public:
    Bear ();
    Bear (Bear &other);

    // ... methods

private:
    BearInfo* m_pInfo;
};
</code>```

Can I store Bear objects in a QList<Bear> by value?  According to the documentation:

Internally, QList<T> is represented as an array of pointers to items of type T. If T is itself a
  pointer type or a basic type that is no larger than a pointer, or if T is one of Qt's shared
  classes, then QList<T> stores the items directly in the pointer array.

While my class just consists of a pointer, it is neither a pointer type nor a basic type, so it seems to me that the QList will store pointers (Bear*), which is not what I want. And since the BearInfo structure must be mutable, I cannot derive Bear from QSharedDataPointer.

Any suggestions how I can enable this class to be stored by value in the Qt collections?

答:
Use a QVector, the Qt Documentation states this:

QList, QLinkedList, and QVarLengthArray provide similar functionality. Here's an overview:

For most purposes, QList is the right class to use. Operations like prepend() and insert() are usually faster than with QVector because of the way QList stores its items in memory (see Algorithmic Complexity for details), and its index-based API is more convenient than QLinkedList's iterator-based API. It also expands to less code in your executable.

If you need a real linked list, with guarantees of constant time insertions in the middle of the list and iterators to items rather than indexes, use QLinkedList.

If you want the items to occupy adjacent memory positions, or if your items are larger than a pointer and you want to avoid the overhead of allocating them on the heap individually at insertion time, then use QVector.

If you want a low-level variable-size array, QVarLengthArray may be sufficient.

Body:
Let's say I have this class:

class Bear
{
public:
    Bear ();
    Bear (Bear &other);

    // ... methods

private:
    BearInfo* m_pInfo;
};

Can I store Bear objects in a QList<Bear> by value?  According to the documentation:

Internally, QList<T> is represented as an array of pointers to items of type T. If T is itself a
  pointer type or a basic type that is no larger than a pointer, or if T is one of Qt's shared
  classes, then QList<T> stores the items directly in the pointer array.

While my class just consists of a pointer, it is neither a pointer type nor a basic type, so it seems to me that the QList will store pointers (Bear*), which is not what I want. And since the BearInfo structure must be mutable, I cannot derive Bear from QSharedDataPointer.

Any suggestions how I can enable this class to be stored by value in the Qt collections?


问:
Check if a collection of ranges is within, and covered another range
I have a range that is defined by start and end, and an array of ranges in collection

```<code>var start = 10;
var end = 60;

var collection = [
    {start:5, end:15},
    {start:15, end:30},
    {start:45, end:60}
];
</code>```

How to check if ranges in collection are within start and end and covered the whole range?

答:
I found the solution by :

Expanding the main range into array of numbers.

Loop collection, expand also those into array of numbers.

Check if the array is within the range, if it's within range remove those numbers from the main array,  if not return false (array to check is not witin range)

After the loop, check the length of main array, if it's more than 0 return false (array collection is within range, but doesn't cover the main range). If it's 0 meaning the collection array is within range, and cover the whole main array.

When googling I found the use of lodash. here is the code in my function :

```<code>let parentRange = _.range(start, end + 1); // Expand into array of numbers

for (var i = 0; i < collection.length; i++) {
    let rangeToCheck = _.range(collection[i].start, collection[i].end + 1); //Also expand into array of numbers
    if (_.difference(rangeToCheck, parentRange).length === 0) { // Check if collection range is within parent range
        _.pullAll(parentRange, rangeToCheck); // Remove the numbers from parent range that matches collcection range
    } else {
        return false; // Not within parent range
    }
}

// Check if parent range has values left
if (parentRange.length != 0) {
    return false; // Collection ranges does not cover parent range
} else {
    return true; // Collection ranges is within parent range, and cover the whole numbers
}
</code>```

Body:
I have a range that is defined by start and end, and an array of ranges in collection

var start = 10;
var end = 60;

var collection = [
    {start:5, end:15},
    {start:15, end:30},
    {start:45, end:60}
];

How to check if ranges in collection are within start and end and covered the whole range?

Body:
I found the solution by :

Expanding the main range into array of numbers.

Loop collection, expand also those into array of numbers.

Check if the array is within the range, if it's within range remove those numbers from the main array,  if not return false (array to check is not witin range)

After the loop, check the length of main array, if it's more than 0 return false (array collection is within range, but doesn't cover the main range). If it's 0 meaning the collection array is within range, and cover the whole main array.

When googling I found the use of lodash. here is the code in my function :

let parentRange = _.range(start, end + 1); // Expand into array of numbers

for (var i = 0; i < collection.length; i++) {
    let rangeToCheck = _.range(collection[i].start, collection[i].end + 1); //Also expand into array of numbers
    if (_.difference(rangeToCheck, parentRange).length === 0) { // Check if collection range is within parent range
        _.pullAll(parentRange, rangeToCheck); // Remove the numbers from parent range that matches collcection range
    } else {
        return false; // Not within parent range
    }
}

// Check if parent range has values left
if (parentRange.length != 0) {
    return false; // Collection ranges does not cover parent range
} else {
    return true; // Collection ranges is within parent range, and cover the whole numbers
}


问:
Rust Error: The size for values of type `(dyn std::error::Error + 'static)` cannot be known at compilation time
first of all I want to mention that there many similar question on StackOverflow and around the web but I just can't figure out how to solve this error for my case.

So I have a struct, which represents my own error type:

```<code>#[derive(Debug)]
pub struct Error {
    msg: String,
}
</code>```

Then I continued implementing Display and std::error::Error for my error type:

```<code>impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.msg)
    }
}

impl std::error::Error for Error {
    fn description(&self) -> &str {
        &self.msg
    }
}
</code>```

Now I tried to implement std::convert::From so I can use my error type  seamlessly with the ? operator:

```<code>impl From<dyn std::error::Error> for Error {
    fn from(err: dyn std::error::Error) -> Self {
        Error {
            msg: err.to_string(),
        }
    }
}
</code>```

But then the rust-compiler gives me this error:

```<code>error[E0277]: the size for values of type `(dyn std::error::Error + 'static)` cannot be known
at compilation time
  --> wasm_api/geohub_wasm_filehandler_api/src/lib.rs:33:6
   |
33 | impl From<dyn std::error::Error> for Error {
   |      ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
   |
</code>```

I know that by default, generic functions will work only on types that have a known size at compile time. But I cant figure out how to solve this problem properly.

Thanks for your help!

Link to code on Rust-Playground:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=568900e8c7847c1f79781fa9bb6d499d

答:
As @SirDarius says above, you can't do this for an Error because Error is not a type, it's a trait. (If you're coming from OOP, think of a Trait like an interface. You can't convert an interface into another type of object because the interface doesn't have any underlying state -- there's no "there" there.)

The right way to handle this is to implement From for each concrete type you need to support. This video really helped me understand how this all fits together.

Body:
first of all I want to mention that there many similar question on StackOverflow and around the web but I just can't figure out how to solve this error for my case.

So I have a struct, which represents my own error type:

#[derive(Debug)]
pub struct Error {
    msg: String,
}

Then I continued implementing Display and std::error::Error for my error type:

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.msg)
    }
}

impl std::error::Error for Error {
    fn description(&self) -> &str {
        &self.msg
    }
}

Now I tried to implement std::convert::From so I can use my error type  seamlessly with the ? operator:

impl From<dyn std::error::Error> for Error {
    fn from(err: dyn std::error::Error) -> Self {
        Error {
            msg: err.to_string(),
        }
    }
}

But then the rust-compiler gives me this error:

error[E0277]: the size for values of type `(dyn std::error::Error + 'static)` cannot be known
at compilation time
  --> wasm_api/geohub_wasm_filehandler_api/src/lib.rs:33:6
   |
33 | impl From<dyn std::error::Error> for Error {
   |      ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
   |

I know that by default, generic functions will work only on types that have a known size at compile time. But I cant figure out how to solve this problem properly.

Thanks for your help!

Link to code on Rust-Playground:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=568900e8c7847c1f79781fa9bb6d499d


问:
Json Data from FrontEnd not being Inserted to the database Via the backend using Knockout and MVC
I am working on a project where I save some stuff from the localstorage into my database using Knockout and MVC. The issue i am having is that the data i specify in the controller that i need to also send to the back end gets inserted but the data i am pulling from the front end does not get inserted.
Here is my frontend api.js :

```<code> function Save(data){
        // var promise = appsecurity.postApiCall(root+'/Save', ko.toJSON(data));
        return appsecurity.putApiCall(root+'/Save', ko.toJSON(data));
    }
</code>```

The projectfile.js

```<code>         self.changeButtonText = function(){
         self.ProcurementbuttonText(!self.ProcurementbuttonText())
         self.ElementData = ko.observable(localStorage.getItem('ElementDataWidget'));
         self.scorecardIDLocalStorage = ko.observable(localStorage.getItem('scorecardId'));
         self.AllData = ko.observableArray([]);
         self.AllData.push(self.scorecardIDLocalStorage,self.ElementData);

         var JSONData = ko.toJSON(self.AllData);
         PreferentialProcurementDashboardApi.Save(JSONData);
         console.log((JSONData));

        }
</code>```

So as you can see i am logging my JSONData to make sure i do get the data from the local storage, so that does show in my console. Here is my backend Code

Controller.cs:

```<code> [HttpPut]
    [Route("Save")]
    [ValidateModel]
    //[TrackActivity(section: "Dashboard", actionType: UserActivityActionType.Update, actionDescription: "Create/Update dashboard View Entry")]

    public IHttpActionResult Save(DashboardConfigEditViewModel dashboardConfigEditViewModel)
    {
        //var databaseDetails = _prefentialDashboardConfigService.GetById(dashboardConfigEditViewModel.DashboardId);
        //if (databaseDetails != null)
        //{
        //    return AccessDenied();
        //}

        //int id = SaveDashboardConfigEditViewModel(dashboardConfigEditViewModel);
        //return Ok(id);

        dashboardConfigEditViewModel.DateCreated = DateTime.Now;
        dashboardConfigEditViewModel.UserId = this.GetUserId();
        _prefentialDashboardConfigService.Create(PreferentialProcurmentConfigViewModelMapper.MapToDomain(dashboardConfigEditViewModel));
        return Ok();
    }
</code>```

My Mapper.cs:

```<code> public static PrefentialDashboardConfig MapToDomain(DashboardConfigEditViewModel dashboardconfigeditviewmodel)
    {
        var config = new PrefentialDashboardConfig();
        config.DashboardId = dashboardconfigeditviewmodel.DashboardId;
        config.ScorecardId = dashboardconfigeditviewmodel.ScorecardId;
        config.UserId = dashboardconfigeditviewmodel.UserId;
        config.DateCreate = dashboardconfigeditviewmodel.DateCreated;
        config.DashboardConfig = dashboardconfigeditviewmodel.DashboardConfig;

        return config;
    }
</code>```

My Dto.cs:

```<code> public class DashboardConfigEditViewModel
{

    //public DashboardConfigEditViewModel()
    //{

    //}

    public int DashboardId { get; set; }

    public Guid ScorecardId { get; set; }

    public Guid UserId { get; set; }

    public DateTime DateCreated { get; set; }

    public string DashboardConfig { get; set; }

}
</code>```

and this is the fields in my database:

```<code>Create Table [data].PrefentialDashboardConfig(
DashboardId int IDENTITY(1,1) PRIMARY KEY,
ScorecardId uniqueidentifier,
UserId uniqueidentifier,
DateCreate DateTime,
DashboardConfig varchar(255)

)
</code>```

Now if you look at my controller i set the date and userID in the backend, that gets inserted into my database but the scorecardID and the config i get from the front end, that does not get parsed all the way through to my backend

答:
Property name in the JSON(which we are sending to the server) should match with the property name of the MVC viewmodel class(Parameter of the Save ActionResult method).

Option 1:
If you are using ko.toJSON method then you should use your model like this below;

var dashboardConfigEditViewModel = {
        ScorecardId:ko.observable(localStorage.getItem('scorecardId')),
        DashboardConfig:ko.observable(localStorage.getItem('ElementDataWidget'))
};

var JSONData = ko.toJSON(dashboardConfigEditViewModel);
PreferentialProcurementDashboardApi.Save(JSONData);

```

<p><strong>Option 2:</strong>
If you dont want to use ko.toJSON method.You can use the below option.</p>

<pre class="lang-js prettyprint-override"><code>
var dashboardConfigEditViewModel = {
        'ScorecardId':ko.observable(localStorage.getItem('scorecardId'))(),
        'DashboardConfig':ko.observable(localStorage.getItem('ElementDataWidget'))()
};

PreferentialProcurementDashboardApi.Save(dashboardConfigEditViewModel);

</code>```

Note: Make sure you are using JSON.stringify() to convert the JSON into string before sending to the server.

Body:
I am working on a project where I save some stuff from the localstorage into my database using Knockout and MVC. The issue i am having is that the data i specify in the controller that i need to also send to the back end gets inserted but the data i am pulling from the front end does not get inserted.
Here is my frontend api.js :

 function Save(data){
        // var promise = appsecurity.postApiCall(root+'/Save', ko.toJSON(data));
        return appsecurity.putApiCall(root+'/Save', ko.toJSON(data));
    }

The projectfile.js

         self.changeButtonText = function(){
         self.ProcurementbuttonText(!self.ProcurementbuttonText())
         self.ElementData = ko.observable(localStorage.getItem('ElementDataWidget'));
         self.scorecardIDLocalStorage = ko.observable(localStorage.getItem('scorecardId'));
         self.AllData = ko.observableArray([]);
         self.AllData.push(self.scorecardIDLocalStorage,self.ElementData);

         var JSONData = ko.toJSON(self.AllData);
         PreferentialProcurementDashboardApi.Save(JSONData);
         console.log((JSONData));

        }

So as you can see i am logging my JSONData to make sure i do get the data from the local storage, so that does show in my console. Here is my backend Code

Controller.cs:

 [HttpPut]
    [Route("Save")]
    [ValidateModel]
    //[TrackActivity(section: "Dashboard", actionType: UserActivityActionType.Update, actionDescription: "Create/Update dashboard View Entry")]

    public IHttpActionResult Save(DashboardConfigEditViewModel dashboardConfigEditViewModel)
    {
        //var databaseDetails = _prefentialDashboardConfigService.GetById(dashboardConfigEditViewModel.DashboardId);
        //if (databaseDetails != null)
        //{
        //    return AccessDenied();
        //}

        //int id = SaveDashboardConfigEditViewModel(dashboardConfigEditViewModel);
        //return Ok(id);

        dashboardConfigEditViewModel.DateCreated = DateTime.Now;
        dashboardConfigEditViewModel.UserId = this.GetUserId();
        _prefentialDashboardConfigService.Create(PreferentialProcurmentConfigViewModelMapper.MapToDomain(dashboardConfigEditViewModel));
        return Ok();
    }

My Mapper.cs:

 public static PrefentialDashboardConfig MapToDomain(DashboardConfigEditViewModel dashboardconfigeditviewmodel)
    {
        var config = new PrefentialDashboardConfig();
        config.DashboardId = dashboardconfigeditviewmodel.DashboardId;
        config.ScorecardId = dashboardconfigeditviewmodel.ScorecardId;
        config.UserId = dashboardconfigeditviewmodel.UserId;
        config.DateCreate = dashboardconfigeditviewmodel.DateCreated;
        config.DashboardConfig = dashboardconfigeditviewmodel.DashboardConfig;

        return config;
    }

My Dto.cs:

 public class DashboardConfigEditViewModel
{

    //public DashboardConfigEditViewModel()
    //{

    //}

    public int DashboardId { get; set; }

    public Guid ScorecardId { get; set; }

    public Guid UserId { get; set; }

    public DateTime DateCreated { get; set; }

    public string DashboardConfig { get; set; }

}

and this is the fields in my database:

Create Table [data].PrefentialDashboardConfig(
DashboardId int IDENTITY(1,1) PRIMARY KEY,
ScorecardId uniqueidentifier,
UserId uniqueidentifier,
DateCreate DateTime,
DashboardConfig varchar(255)

)

Now if you look at my controller i set the date and userID in the backend, that gets inserted into my database but the scorecardID and the config i get from the front end, that does not get parsed all the way through to my backend

Body:
Property name in the JSON(which we are sending to the server) should match with the property name of the MVC viewmodel class(Parameter of the Save ActionResult method).

Option 1:
If you are using ko.toJSON method then you should use your model like this below;

var dashboardConfigEditViewModel = {
        ScorecardId:ko.observable(localStorage.getItem('scorecardId')),
        DashboardConfig:ko.observable(localStorage.getItem('ElementDataWidget'))
};

var JSONData = ko.toJSON(dashboardConfigEditViewModel);
PreferentialProcurementDashboardApi.Save(JSONData);

Option 2:
If you dont want to use ko.toJSON method.You can use the below option.

var dashboardConfigEditViewModel = {
        'ScorecardId':ko.observable(localStorage.getItem('scorecardId'))(),
        'DashboardConfig':ko.observable(localStorage.getItem('ElementDataWidget'))()
};

PreferentialProcurementDashboardApi.Save(dashboardConfigEditViewModel);

Note: Make sure you are using JSON.stringify() to convert the JSON into string before sending to the server.


问:
NodeJs API responding with incomplete object
I am trying to implement API using NodeJs that reads data from database collection and again form that data reads respective data from another collection and updating same object with  new key value pairs.

The objects are updating successfully but the API response that I recieve on Frontend is not updated with second collection values.

```<code>router.get('/exam/:_id' , (req , res) => {
    ExamModel.find({
        userId: req.params._id
    })
        .then(doc => {
            let i=0;
            for(let data of doc){
                i=i+1;
                ResponseModel.find({examId: data._id}).countDocuments()
                   .then(count=>{
                        data.responseCount= count;
                        if(i===doc.length){
                           res.json(doc)
                        }
                    })
                    .catch(err => {
                        res.status(500).json(err)
                    })

            }
        })
        .catch(err => {
            res.status(500).json(err)
        })
})
</code>```

The object recieved from ExamModel is

```<code>[
    {
        _id: "012",
        responseCount: 0,
        data: [array]
    },
    {
        _id: "015",
        responseCount: 0,
        data: [array]
    }
]
</code>```

after ResponseModel the object become

```<code>[
    {
        _id: "012",
        responseCount: 5,
        data: [array]
    },
    {
        _id: "015",
        responseCount: 2,
        data: [array]
    }
]
</code>```

But as a response of api, I am getting the first object not second.

And also I am getting error

```<code>(node:15012) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
</code>```

答:
The doc object returned by the query will be in an immutable state. In order to modify the object, you need to convert it to a plain javascript object first.

You can perform the below operation before the for loop.

const result = doc.map(d => d.toObject());
```

<p>Now you can use the <code>result</code> object in you for loop and make modification the result object.</p>

<p>Regarding the <code>ERR_HTTP_HEADERS_SENT</code> error. The <code>for</code> loop will complete the iteration long before the count query returns the promise. This will make the <code>if(i===doc.length)</code> condition true multiple times.</p>

<p>You can use async/await function as below in order to solve the issue</p>

<pre class="lang-js prettyprint-override"><code>router.get("/exam/:_id", async (req, res) => {
  try {
    const doc = await ExamModel.find({ userId: req.params._id });
    const result = doc.map((d) => d.toObject());
    for (let data of result) {
      const count = await ResponseModel.countDocuments({ examId: data._id });
      data.responseCount = count;
    }
    res.json(result);
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: "Interval Server Err" });
  }
});
</code>```

Body:
I am trying to implement API using NodeJs that reads data from database collection and again form that data reads respective data from another collection and updating same object with  new key value pairs.

The objects are updating successfully but the API response that I recieve on Frontend is not updated with second collection values.

router.get('/exam/:_id' , (req , res) => {
    ExamModel.find({
        userId: req.params._id
    })
        .then(doc => {
            let i=0;
            for(let data of doc){
                i=i+1;
                ResponseModel.find({examId: data._id}).countDocuments()
                   .then(count=>{
                        data.responseCount= count;
                        if(i===doc.length){
                           res.json(doc)
                        }
                    })
                    .catch(err => {
                        res.status(500).json(err)
                    })

            }
        })
        .catch(err => {
            res.status(500).json(err)
        })
})

The object recieved from ExamModel is

[
    {
        _id: "012",
        responseCount: 0,
        data: [array]
    },
    {
        _id: "015",
        responseCount: 0,
        data: [array]
    }
]

after ResponseModel the object become

[
    {
        _id: "012",
        responseCount: 5,
        data: [array]
    },
    {
        _id: "015",
        responseCount: 2,
        data: [array]
    }
]

But as a response of api, I am getting the first object not second.

And also I am getting error

(node:15012) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)

Body:
The doc object returned by the query will be in an immutable state. In order to modify the object, you need to convert it to a plain javascript object first.

You can perform the below operation before the for loop.

const result = doc.map(d => d.toObject());

Now you can use the result object in you for loop and make modification the result object.

Regarding the ERR_HTTP_HEADERS_SENT error. The for loop will complete the iteration long before the count query returns the promise. This will make the if(i===doc.length) condition true multiple times.

You can use async/await function as below in order to solve the issue

router.get("/exam/:_id", async (req, res) => {
  try {
    const doc = await ExamModel.find({ userId: req.params._id });
    const result = doc.map((d) => d.toObject());
    for (let data of result) {
      const count = await ResponseModel.countDocuments({ examId: data._id });
      data.responseCount = count;
    }
    res.json(result);
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: "Interval Server Err" });
  }
});


问:
spin-fiat not starting during hal config apply: services.front50.baseUrl
Hal Version

```<code>root@9d4ea3d3c90e:/workdir# hal --version
0.43.0-180317140630
</code>```

Applying config with hal

```<code>root@9d4ea3d3c90e:/workdir# hal deploy apply
+ Get current deployment
  Success
+ Prep deployment
  Success
Problems in default.provider.kubernetes.sandbox-spinnaker:
- WARNING Field KubernetesAccount.kinds not supported for Spinnaker
  version 1.6.0: Configuring kind caching behavior is not supported yet.
? Use at least 1.7.0 (It may not have been released yet).

- WARNING Field KubernetesAccount.omitKinds not supported for
  Spinnaker version 1.6.0: Configuring kind caching behavior is not supported
  yet.
? Use at least 1.7.0 (It may not have been released yet).

+ Preparation complete... deploying Spinnaker
+ Get current deployment
  Success
+ Apply deployment
  Success
+ Run `hal deploy connect` to connect to Spinnaker.
</code>```

Status of pods

```<code>$ kubectl get pods
NAME                               READY     STATUS             RESTARTS   AGE
spin-clouddriver-f54b887f-hmnsx    1/1       Running            0          19h
spin-deck-598f8df868-6jlhl         1/1       Running            0          19h
spin-echo-84d9b7d679-whv6n         1/1       Running            0          19h
spin-fiat-78b899d45d-dk767         0/1       CrashLoopBackOff   4          3m
spin-front50-65d476986f-hgnsq      1/1       Running            0          19h
spin-gate-67b6955476-b7dhj         1/1       Running            0          19h
spin-igor-56f7f9b85f-rj7fl         1/1       Running            0          19h
spin-orca-6c4f48cf49-5knlc         1/1       Running            0          19h
spin-redis-69b6cc4c46-vmfhr        1/1       Running            0          5d
</code>```

Log message from spin-fiat

```<code>$ kubectl logs spin-fiat-78b899d45d-dk767
...
2018-03-21 17:16:10.472 ERROR 1 --- [           main] o.s.boot.SpringApplication               : [] Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourcesConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'services.front50.baseUrl' in value "${services.front50.baseUrl}"
</code>```

I'm not sure why spin-fiat is not starting.

Any tips on how to troubleshoot appreciated.

答:
This issue is fixed in PR#1511

I suggest you upgrade your Spinnaker to version 1.20.X. That version uses the new Kubernetes V2 provider. Also the FIAT issue is gone. You must install or upgrade halyard for this new Spinnaker Release.

Upgrade Halyard

Upgrade Spinnaker to version 1.20.X

Body:
Hal Version

root@9d4ea3d3c90e:/workdir# hal --version
0.43.0-180317140630

Applying config with hal

root@9d4ea3d3c90e:/workdir# hal deploy apply
+ Get current deployment
  Success
+ Prep deployment
  Success
Problems in default.provider.kubernetes.sandbox-spinnaker:
- WARNING Field KubernetesAccount.kinds not supported for Spinnaker
  version 1.6.0: Configuring kind caching behavior is not supported yet.
? Use at least 1.7.0 (It may not have been released yet).

- WARNING Field KubernetesAccount.omitKinds not supported for
  Spinnaker version 1.6.0: Configuring kind caching behavior is not supported
  yet.
? Use at least 1.7.0 (It may not have been released yet).

+ Preparation complete... deploying Spinnaker
+ Get current deployment
  Success
+ Apply deployment
  Success
+ Run `hal deploy connect` to connect to Spinnaker.

Status of pods

$ kubectl get pods
NAME                               READY     STATUS             RESTARTS   AGE
spin-clouddriver-f54b887f-hmnsx    1/1       Running            0          19h
spin-deck-598f8df868-6jlhl         1/1       Running            0          19h
spin-echo-84d9b7d679-whv6n         1/1       Running            0          19h
spin-fiat-78b899d45d-dk767         0/1       CrashLoopBackOff   4          3m
spin-front50-65d476986f-hgnsq      1/1       Running            0          19h
spin-gate-67b6955476-b7dhj         1/1       Running            0          19h
spin-igor-56f7f9b85f-rj7fl         1/1       Running            0          19h
spin-orca-6c4f48cf49-5knlc         1/1       Running            0          19h
spin-redis-69b6cc4c46-vmfhr        1/1       Running            0          5d

Log message from spin-fiat

$ kubectl logs spin-fiat-78b899d45d-dk767
...
2018-03-21 17:16:10.472 ERROR 1 --- [           main] o.s.boot.SpringApplication               : [] Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourcesConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'services.front50.baseUrl' in value "${services.front50.baseUrl}"

I'm not sure why spin-fiat is not starting.

Any tips on how to troubleshoot appreciated.


问:
Laravel, bringing an array to view
```<code>        $vegetables = DB::select("select a.id, a.created_at, a.updated_at,a.storeid, a.itemno, a.type, a.vegie from stores a, storenames b where a.storeid = b.storeid");
        return view('stores', ['vegetables' => $vegetables]);
</code>```

I used the code above to query the DB and I got the following error in the view page:

```<code> @foreach($vegetables as $vegetable)
        <tbody>
            <tr>
                <th scope="row">{{ $vegetable['storeid'] }}</th>
                <td>{{ $vegetable['itemno'] }}</td>
                <td>{{ $vegetable['type'] }}</td>
                <td>{{ $vegetable['vegie'] }}</td>
            </tr>
            @endforeach
        </tbody>
</code>```

Facade\Ignition\Exceptions\ViewException
Cannot use object of type stdClass as array

Any help would be greatly appreciated.

答:
Seems like you need to cast the stdClass Objects as Array so you can have the structure you are looking for</p>

```<code>$vegetables = array_map(function ($value) {
    return (array)$value;
}, $vegetables);
</code>```

Title: Laravel, bringing an array to view

Body:
        $vegetables = DB::select("select a.id, a.created_at, a.updated_at,a.storeid, a.itemno, a.type, a.vegie from stores a, storenames b where a.storeid = b.storeid");
        return view('stores', ['vegetables' => $vegetables]);

I used the code above to query the DB and I got the following error in the view page:

 @foreach($vegetables as $vegetable)

                {{ $vegetable['storeid'] }}
                {{ $vegetable['itemno'] }}
                {{ $vegetable['type'] }}
                {{ $vegetable['vegie'] }}

            @endforeach

Facade\Ignition\Exceptions\ViewException
Cannot use object of type stdClass as array

Any help would be greatly appreciated.

Body:
Seems like you need to cast the stdClass Objects as Array so you can have the structure you are looking for

$vegetables = array_map(function ($value) {
    return (array)$value;
}, $vegetables);


问:
Find unique name of device?
I'm developing an app that uses zeroconf (bonjour) to discover devices - so I need to give each android device some kind of name (not just a bunch of numbers and letters, but something meaningful like "Alex's Device"). In iOS it can be easily done - is this possible in android?</p>

答:
you can get the IMEI of the Android Phone , it's Unique  ,

you can Get it by using the method getDeviceId() of the Class TelephonyManager

NOTE : you will need to add a permission in your manifest : READ_PHONE_STATE

Title: Find unique name of device?


答:
This is very easy with flex, I have increased .top height to 300vh, so you can see the result here easily,

body {
  text-align: center;
  margin:0;
}

h1 {
  font-size: 5.6rem;
  margin:0;
  color: white;
  line-height: 2;
  font-family: 'Clicker Script', cursive;
}

h2 {
  font-weight: normal;
  font-family: 'Kavivanar', cursive;
}

.nav {
  background-color: #87c6eb;
  text-align: right;
  padding-top: 50px;
}

.top {
  background-color: #87c6eb;
  height: 300vh;
display: flex;
flex-direction: column;
}

.programer {
  font-size: 150%;
  color: white;
}

.top-cloud {
  position:absolute;
  top:100px;
  right: 300px;
  opacity: 70%;
}

.bottom-cloud {
  position:absolute;
  left: 350px;
  opacity: 45%;
}

.mnt {
  /* ???????? */
margin: auto auto 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="top">
  <nav class="nav">
    About
    Work
    Contact
  </nav>
  <img class="top-cloud" src="cloud.png" alt="cloud img">
  <h1>I`m Veljko</h1>
  <h2 class="programer"><em>future programmer</em></h2>
  <img class="bottom-cloud" src="cloud.png" alt="cloud img">
  <img class="mnt"  src="mountain.png" alt="mountain img">
</div></code>```

Title: How to get img on the bottom & center of div without using absolute position

Body:
I am pretty new in HTML and CSS (2 weeks) and this is the first time iam using Stack overflow.
i am trying to make position of a img on the bottom of the div and in the center of the bottom side and are not able to find solution. I would like to do it without using position: absolute because img will move when you open page on smaller/bigger screen

it is this image i would like to move:"

body {
  text-align: center;
  margin:0;
}

h1 {
  font-size: 5.6rem;
  margin:0;
  color: white;
  line-height: 2;
  font-family: 'Clicker Script', cursive;
}

h2 {
  font-weight: normal;
  font-family: 'Kavivanar', cursive;
}

.nav {
  background-color: #87c6eb;
  text-align: right;
  padding-top: 50px;
}

.top {
  background-color: #87c6eb;
  height: 100vh;
}

.programer {
  font-size: 150%;
  color: white;
}

.top-cloud {
  position:absolute;
  top:100px;
  right: 300px;
  opacity: 70%;
}

.bottom-cloud {
  position:absolute;
  left: 350px;
  opacity: 45%;
}

.mnt {
  /* ???????? */
}

    About
    Work
    Contact

I`m Veljko

future programmer

Body:
This is very easy with flex, I have increased .top height to 300vh, so you can see the result here easily,

body {
  text-align: center;
  margin:0;
}

h1 {
  font-size: 5.6rem;
  margin:0;
  color: white;
  line-height: 2;
  font-family: 'Clicker Script', cursive;
}

h2 {
  font-weight: normal;
  font-family: 'Kavivanar', cursive;
}

.nav {
  background-color: #87c6eb;
  text-align: right;
  padding-top: 50px;
}

.top {
  background-color: #87c6eb;
  height: 300vh;
display: flex;
flex-direction: column;
}

.programer {
  font-size: 150%;
  color: white;
}

.top-cloud {
  position:absolute;
  top:100px;
  right: 300px;
  opacity: 70%;
}

.bottom-cloud {
  position:absolute;
  left: 350px;
  opacity: 45%;
}

.mnt {
  /* ???????? */
margin: auto auto 0;
}

<div class="top">
  <nav class="nav">
    <a href="#About" class="navigation">About</a>
    <a href="#Work" class="navigation">Work</a>
    <a href="#contact" class="navigation">Contact</a>
  </nav>
  <img class="top-cloud" src="cloud.png" alt="cloud img">
  <h1>I`m Veljko</h1>
  <h2 class="programer"><em>future programmer</em></h2>
  <img class="bottom-cloud" src="cloud.png" alt="cloud img">
  <img class="mnt"  src="mountain.png" alt="mountain img">
</div>


答:
Hey it looks like there are a couple errors with your JOINs
See if switching what you JOIN "ON" like below and changing the last JOIN from a RIGHT to an INNER will do for you. </p>

```<code>SELECT
  SUM(Job.Wage) AS SumWages
  , Car.Make
  , Car.Model
FROM
  Person
   INNER JOIN PersonCar
    ON PersonCar.PersonID = Person.ID
   INNER JOIN Job
    ON Job.PersonID = PersonCar.ID
   INNER JOIN Car
    ON Car.ID = PersonCar.CarID
GROUP BY SumWages, Make, Model
;
</code>```

Title: SQL Joining of Multiple Tables

Body:
Hey it looks like there are a couple errors with your JOINs
See if switching what you JOIN "ON" like below and changing the last JOIN from a RIGHT to an INNER will do for you.

SELECT
  SUM(Job.Wage) AS SumWages
  , Car.Make
  , Car.Model
FROM
  Person
   INNER JOIN PersonCar
    ON PersonCar.PersonID = Person.ID
   INNER JOIN Job
    ON Job.PersonID = PersonCar.ID
   INNER JOIN Car
    ON Car.ID = PersonCar.CarID
GROUP BY SumWages, Make, Model
;


问:
SQLAlchemy Obtain Primary Key With Autoincrement Before Commit
When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing?

I would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned in the previous operation.

答: You can use multiple transactions and manage it within scope.</p>

OwnerDisplayName: Sean

LastEditorDisplayName: Jacob Gabrielson

ContentLicense: CC BY-SA 2.5


问:
Unable to introducing generics into Typescript method without losing object key typings
I'm creating a method in Typescript that extracts allowable property types from an object of a constrained generic type.

Essentially, I have a type ParticipantBase which has properties first: string, last: string, extras: [key: string]: string. I have made a function getAllowedEntry which takes an object of type ParticipantBase and a key at which the value in the ParticipantBase object is of type AllowableType. This works just fine.

I want to be able to add generics to this function, but as soon as I do, errors begin popping up and the Typescript compiler no longer seems to be able to guarantee the typings.

I think there's something fundamental here that I'm not understanding about typings and generics in Typescript, if someone could help me out, that would be great.

Minimal Sample (also available in playground):

type PropertiesOfType = {
  [P in keyof U]: U[P] extends V ? P : never;
}[keyof U];

type AllowedPropertyTypes = string | number;

type ParticipantBase = {
  first: string;
  last: string;
  extras: { [property: string]: string };
};

// Doesn't work.
function getAllowedEntry<T, K extends PropertiesOfType<T, AllowedPropertyTypes>>(participant: T, key: K): AllowedPropertyTypes {
  return participant[key];
}

// Works just fine.
function getAllowedParticipantEntry<K extends PropertiesOfType<ParticipantBase, AllowedPropertyTypes>>(participant: ParticipantBase, key: K): AllowedPropertyTypes {
  return participant[key];
}

```

答:
You should replace your return type from AllowedPropertyTypes to
  T[K]

Error Hint: Type 'T[K]' is not assignable to type 'AllowedPropertyTypes'.

```<code>function getAllowedEntry<T, K extends PropertiesOfType<T, AllowedPropertyTypes>>(participant: T, key: K): T[K] {
      return participant[key];
    }
</code>```

Body:
I'm creating a method in Typescript that extracts allowable property types from an object of a constrained generic type.

Essentially, I have a type ParticipantBase which has properties first: string, last: string, extras: [key: string]: string. I have made a function getAllowedEntry which takes an object of type ParticipantBase and a key at which the value in the ParticipantBase object is of type AllowableType. This works just fine.

I want to be able to add generics to this function, but as soon as I do, errors begin popping up and the Typescript compiler no longer seems to be able to guarantee the typings.

I think there's something fundamental here that I'm not understanding about typings and generics in Typescript, if someone could help me out, that would be great.

Minimal Sample (also available in <a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBACgTge0nYBLCBnA8gMwCrgQA8AqgDRQBqAfFALxQDeAUFFANoxSoB2UA1hBAIcUEgF0AXGM7ioEAB7AIPACYYqUAPywo0nhABuEOAG5mAX3aDhoieeahIUAIIAbNwgDuEVfCQmoASQGgwYwHC8AOZQAD5QPACuALYARiYOTtAwAIYoqADGqGA5PMAAQjkY0AwsbDiocOHS4ZE8UeZsblXALRHRnfJKcFXSjBxgiMigfW1RUlCt0VAW5qvMzAD0m1AAIgiYPADkwFBeCHD8AHTMOIk8BWgIfFEQwO6ePqoAomVwIEQ8BQANJDZRqDT+abobD4QiAigfby+KGBEDBTDUagAChK+SKJTK0iBAiE0mBAEppEivqiUOjCBo6lA4G9EnA+Hi0ATSsBrEJxGsNtsoAB1C78DQAK0S4SgDQMNzuDyeLzeNJReW5xV5vwiANBinB6lgU0CMNwGKIuXxOrKlWqiI8yL8ZvpGIwWNxWsKdt6sB9PPtVQgFBs5KprmdtLdQUZTFYLLZHKgXN9hL5NkFlmYQA" rel="nofollow noreferrer">playground):

type PropertiesOfType = {
  [P in keyof U]: U[P] extends V ? P : never;
}[keyof U];

type AllowedPropertyTypes = string | number;

type ParticipantBase = {
  first: string;
  last: string;
  extras: { [property: string]: string };
};

// Doesn't work.
function getAllowedEntry<T, K extends PropertiesOfType<T, AllowedPropertyTypes>>(participant: T, key: K): AllowedPropertyTypes {
  return participant[key];
}

// Works just fine.
function getAllowedParticipantEntry<K extends PropertiesOfType<ParticipantBase, AllowedPropertyTypes>>(participant: ParticipantBase, key: K): AllowedPropertyTypes {
  return participant[key];
}

Body:
You should replace your return type from AllowedPropertyTypes to
  T[K]

Error Hint: Type 'T[K]' is not assignable to type 'AllowedPropertyTypes'.

function getAllowedEntry<T, K extends PropertiesOfType<T, AllowedPropertyTypes>>(participant: T, key: K): T[K] {
      return participant[key];
    }


问:
Grouping of Stem- Leaf plot in R
I have a got a stem-leaf plot as a question, which looks like this:

```<code>0 | 6
1 | 179
2 | 26
3 | 2478
4 | 15699
5 | 368
6 | 24457
7 |
8 | 56
</code>```

So, created a vector on my own which would create a stem plot as same as the above one.

```<code>data <- c(06,11,17,19,22,26,32,34,37,38,41,45,46,49,49,53,56,58,62,64,64,65,67,7,85,86)
</code>```

What I have to do is that, I need to group the stems by 2 and then plot the corresponding stem plot of that using R.

The solution would look somewhat like this:

```<code>0-2|6*179*26
3-5|2478*15699*368
6-8|244457**56
</code>```

"*" is used to separate the leaves of each stem in the group. i.e. For the group stem 0-2, it represents that leaf 6 in the first row corresponds to stem 0; leaves 1,7 and 9 correspond to stem 1 and leaves 2 and 6 corresponds to stem 2.

I found no use in stem(), so thought of separating the data by 2 using "interval" function, and then build one user-defined functions but it resulted out in giving me the same stem value.

Is there any way to get the desired solution, either by using in-built function/ by user-defined?
Thanks a lot in advance.!!

答:
This isn't going to win any beauty contest, but you can definitely use a combination of cut and some string processing to create your own grouped stem function.

Here's an example function, commented so you can extend it to suit your actual needs:

```<code>grouped_stem <- function(invec, n = 3) {
  # Sequence of lowest tens and highest tens in the input data, by 10
  cuts <- seq((min(invec) %/% 10) * 10, round(max(invec), -(nchar(max(invec))-1)), 10)
  # For pretty labels in `cut`
  labs <- sub("(.*).$", "\\1", cuts)
  labs <- replace(labs, !nzchar(labs), "0")
  # List of the values according to their `cut` intervals
  temp <- split(invec, cut(invec, cuts, labs[-length(labs)], right = FALSE))
  # Only interested in the last digit
  temp <- relist(sub(".*(.)$", "\\1", unlist(temp, use.names = FALSE)), temp)
  # Paste the values together. Add in a "*" that we can get rid of later if not required
  combined <- vapply(temp, function(y) sprintf("%s*", paste(y, collapse = "")), character(1L))
  # Split by number of groups of tens per stem
  splits <- split(combined, ((seq_along(combined)-1) %/% n))
  # Construct the stems and leaves
  stems <- vapply(splits, function(x) {
    paste(names(x)[1], names(x)[length(x)], sep = " to ")
  }, character(1L))
  leaves <- vapply(splits, function(x) {
    sub("[*]$", "", paste(x, sep = "", collapse = ""))
  }, character(1L))
  # Print and store
  cat(sprintf(sprintf("%%%ss | %%s", max(nchar(stems))+2), stems, leaves), sep = "\n")
  invisible(setNames(as.list(leaves), stems))
}
</code>```

Run on your sample data, it produces:

```<code>grouped_stem(data)
##   0 to 2 | 67*179*26
##   3 to 5 | 2478*15699*368
##   6 to 8 | 24457**56
</code>```

Title: Grouping of Stem- Leaf plot in R

Body:
I have a got a stem-leaf plot as a question, which looks like this:

0 | 6
1 | 179
2 | 26
3 | 2478
4 | 15699
5 | 368
6 | 24457
7 |
8 | 56

So, created a vector on my own which would create a stem plot as same as the above one.

data <- c(06,11,17,19,22,26,32,34,37,38,41,45,46,49,49,53,56,58,62,64,64,65,67,7,85,86)

What I have to do is that, I need to group the stems by 2 and then plot the corresponding stem plot of that using R.

The solution would look somewhat like this:

0-2|6*179*26
3-5|2478*15699*368
6-8|244457**56

"*" is used to separate the leaves of each stem in the group. i.e. For the group stem 0-2, it represents that leaf 6 in the first row corresponds to stem 0; leaves 1,7 and 9 correspond to stem 1 and leaves 2 and 6 corresponds to stem 2.

I found no use in stem(), so thought of separating the data by 2 using "interval" function, and then build one user-defined functions but it resulted out in giving me the same stem value.

Is there any way to get the desired solution, either by using in-built function/ by user-defined?
Thanks a lot in advance.!!

Body:
This isn't going to win any beauty contest, but you can definitely use a combination of cut and some string processing to create your own grouped stem function.

Here's an example function, commented so you can extend it to suit your actual needs:

grouped_stem <- function(invec, n = 3) {
  # Sequence of lowest tens and highest tens in the input data, by 10
  cuts <- seq((min(invec) %/% 10) * 10, round(max(invec), -(nchar(max(invec))-1)), 10)
  # For pretty labels in `cut`
  labs <- sub("(.*).$", "\\1", cuts)
  labs <- replace(labs, !nzchar(labs), "0")
  # List of the values according to their `cut` intervals
  temp <- split(invec, cut(invec, cuts, labs[-length(labs)], right = FALSE))
  # Only interested in the last digit
  temp <- relist(sub(".*(.)$", "\\1", unlist(temp, use.names = FALSE)), temp)
  # Paste the values together. Add in a "*" that we can get rid of later if not required
  combined <- vapply(temp, function(y) sprintf("%s*", paste(y, collapse = "")), character(1L))
  # Split by number of groups of tens per stem
  splits <- split(combined, ((seq_along(combined)-1) %/% n))
  # Construct the stems and leaves
  stems <- vapply(splits, function(x) {
    paste(names(x)[1], names(x)[length(x)], sep = " to ")
  }, character(1L))
  leaves <- vapply(splits, function(x) {
    sub("[*]$", "", paste(x, sep = "", collapse = ""))
  }, character(1L))
  # Print and store
  cat(sprintf(sprintf("%%%ss | %%s", max(nchar(stems))+2), stems, leaves), sep = "\n")
  invisible(setNames(as.list(leaves), stems))
}

Run on your sample data, it produces:

grouped_stem(data)
##   0 to 2 | 67*179*26
##   3 to 5 | 2478*15699*368
##   6 to 8 | 24457**56


问:
Azure DevOps Conditional execution of Job that depends on a Job in another Stage
I have a pipeline.yaml that looks like this

```<code>pool:
  vmImage: image

stages:
  -stage: A
   jobs:
     -job: a
      steps:
     - script: |
          echo "This is stage build"
          echo "##vso[task.setvariable variable=doThing;isOutput=true]Yes"
        name: BuildStageRun
  -stage: B
   jobs:
      -job: b
       steps: #do something in steps

      -job: c
       dependsOn: a
       condition: eq(dependencies.build.outputs['BuildStageRun.doThing'], 'Yes')
       steps:
        - script: echo "I am scripting"
</code>```

So, there are 2 stages, A with one job a, and B with 2 jobs b and c. I would like to have job c executed only when job a has executed. I tried to do so by setting the variable doThing in job a to Yes and then check this variable in job c.

But I get an error:

Stage plan job c depends on unknown job a.

The varible definition and the definition of condition was taken from Azure documentation

Do you have any suggestion on how to get this working?

答:
While Shayki is correct that it is not supported - there is a workaround that I am currently using. That I used with the help of this blog https://medium.com/microsoftazure/how-to-pass-variables-in-azure-pipelines-yaml-tasks-5c81c5d31763

Basically you create your output as normal, and then publish the variables as pipeline artifacts. In the next stage, you read the artifact in the first job, and use that to construct your conditionals e.g.

stages:

  - stage: firststage
    jobs:

      - job: setup_variables
        pool:
          vmImage: 'Ubuntu-16.04'
        steps:

          - powershell: |
              $ShouldBuildThing1 = $true
              # Write to normal output for other jobs in this stage
              Write-Output "##vso[task.setvariable variable=BuildThing1;isOutput=true]$ShouldBuildThing1"
              # Write to file to publish later
              mkdir -p $(PipelineWorkspace)/variables
              Write-Output "$ShouldBuildThing1" > $PipelineWorkspace/variables/BuildThing1
            name: variablesStep

          # Publish the folder as pipeline artifact
          - publish: $(Pipeline.Workspace)/variables
            artifact: VariablesArtifact

       - job: build_something
         pool:
          vmImage: 'Ubuntu-16.04'
         dependsOn: setup_variables
         condition: eq(dependencies.setup_variables.outputs['variablesStep.BuildThing1'], 'true')
         variables:
           BuildThing1: $[dependencies.setup_variables.outputs['variablesStep.BuildThing1']]
         steps:
           - powershell: |
               Write-Host "Look at me I can Read $env:BuildThing1"

           - somethingElse:
               someInputArgs: $(BuildThing1)

  - stage: secondstage
    jobs:

      - job: read_variables
        pool:
          vmImage: 'Ubuntu-16.04'
        steps:
          # If you download all artifacts then foldername will be same as artifact name under $(Pipeline.Workspace). Artifacts are also auto downloaded on deployment jobs.
          - task: DownloadPipelineArtifact@2
            inputs:
              artifact: "VariablesArtifact"
              path: $(Pipeline.Workspace)/VariablesArtifact

          - powershell: |
              $ShouldBuildThing1 = $(Get-Content $(Pipeline.Workspace)/VariablesArtifact/BuildThing1)
              Write-Output "##vso[task.setvariable variable=BuildThing1;isOutput=true]$ShouldBuildThing1"
            name: variablesStep

      - job: secondjob
        pool:
          vmImage: 'Ubuntu-16.04'
        dependsOn: read_variables
        condition: eq(dependencies.read_variables.outputs['variablesStep.BuildThing1'], 'true')
        variables:
           BuildThing1: $[dependencies.setup_variables.outputs['variablesStep.BuildThing1']]
         steps:
           - powershell: |
               Write-Host "Look at me I can Read $env:BuildThing1"

           - somethingElse:
               someInputArgs: $(BuildThing1)

```

Body:
I have a pipeline.yaml that looks like this

pool:
  vmImage: image

stages:
  -stage: A
   jobs:
     -job: a
      steps:
     - script: |
          echo "This is stage build"
          echo "##vso[task.setvariable variable=doThing;isOutput=true]Yes"
        name: BuildStageRun
  -stage: B
   jobs:
      -job: b
       steps: #do something in steps

      -job: c
       dependsOn: a
       condition: eq(dependencies.build.outputs['BuildStageRun.doThing'], 'Yes')
       steps:
        - script: echo "I am scripting"

So, there are 2 stages, A with one job a, and B with 2 jobs b and c. I would like to have job c executed only when job a has executed. I tried to do so by setting the variable doThing in job a to Yes and then check this variable in job c.

But I get an error:

Stage plan job c depends on unknown job a.

The varible definition and the definition of condition was taken from Azure documentation

Do you have any suggestion on how to get this working?


问:
Prismjs syntax highlighting in a MEVN stack
I am working on a blog using a MEVN stack where I use the tiny-mce-vue editor. Now, all working great except if I add some code sample, they don't retain the syntax highlighting outside of the editor see screenshot:

I have been surfing the web a lot to find an answer, and the best I found was this article where I found that I should use the function Prism.highlightAll()

mounted() {
    Prism.highlightAll()
}```

but it doesn't do anything running from mounted() inside my post.vue component, but if I run the Prism.highlightAll from the browser console it works as expected.

So In short I don't know what I am doing wrong here.

Here a codepen with my post.vue

答:
The moment that mounted is running is too early (the entire DOM is not really ready yet).  The fact that you can make this work in the console is a good indicator that this is a timing issue.

You should be able to rely on some standard JavaScript to figure out when things are "fully loaded and ready to go".  Perhaps one of these event would work?

```<code>mounted() {
  window.addEventListener('load', () => {
       // Prism magic goes here
  })
}
</code>```

...or...

```<code>mounted() {
  document.onreadystatechange = () => {
    if (document.readyState == "complete") {
      // Prism magic goes here
    }
  }
},
</code>```

If you add an event listener I believe you would want to remove it in beforeDestroy().

Body:
I am working on a blog using a MEVN stack where I use the tiny-mce-vue editor. Now, all working great except if I add some code sample, they don't retain the syntax highlighting outside of the editor see screenshot:

I have been surfing the web a lot to find an answer, and the best I found was this article where I found that I should use the function Prism.highlightAll()

mounted() {
    Prism.highlightAll()
}

but it doesn't do anything running from mounted() inside my post.vue component, but if I run the Prism.highlightAll from the browser console it works as expected.

So In short I don't know what I am doing wrong here.

Here a codepen with my post.vue

Body:
The moment that mounted is running is too early (the entire DOM is not really ready yet).  The fact that you can make this work in the console is a good indicator that this is a timing issue.

You should be able to rely on some standard JavaScript to figure out when things are "fully loaded and ready to go".  Perhaps one of these event would work?

mounted() {
  window.addEventListener('load', () => {
       // Prism magic goes here
  })
}

...or...

mounted() {
  document.onreadystatechange = () => {
    if (document.readyState == "complete") {
      // Prism magic goes here
    }
  }
},

If you add an event listener I believe you would want to remove it in beforeDestroy().


问:
Batch convert from XCF version 11
I have a folder of images saved in .xcf format, and I would like to batch convert them to a more convenient format.  I've tried a few approaches that haven't worked:

I used to do this using IrfanView, but that no longer works because it refuses to open the latest version of .xcf files.

I tried using IMageMagick mogrify and convert, but they both give me "memory allocation failed" -- perhaps they also don't understand the new format?

I tried the xcf2png command line tool and it gives me the message "Warning: XCF version 11 not supported (trying anyway...)" before creating an empty image.

My last hope is to write a batch convert script that will work in the latest version of Gimp itself, but I don't have any experience with ScriptFu.  I found a script that converts some other file types (http://beefchunk.com/documentation/lang/gimp/GIMP-Scripts-Fu.html#convertjpg-script-fu) but don't quite have the knowledge to modify it.  Does anybody know the right calls/arguments to read xcf and write png?

答:
Here is a self-contained bash script that should convert all xcf files in your current directory into png format copies.  It should work on any Linux computer with Gimp installed.  It does not require any installation in script directories:

```<code>#!/bin/bash
# xcfs2png.sh
# Invoke The GIMP with Script-Fu convert-xcf-png
# No error checking.
{
cat <<EOF
(define (convert-xcf-png filename outpath)
    (let* (
            (image (car (gimp-xcf-load RUN-NONINTERACTIVE filename filename )))
            (drawable (car (gimp-image-merge-visible-layers image CLIP-TO-IMAGE)))
            )
        (begin (display "Exporting ")(display filename)(display " -> ")(display outpath)(newline))
        (file-png-save2 RUN-NONINTERACTIVE image drawable outpath outpath 0 9 0 0 0 0 0 0 0)
        (gimp-image-delete image)
    )
)

(gimp-message-set-handler 1) ; Messages to standard output
EOF

for i in *.xcf; do
  echo "(convert-xcf-png \"$i\" \"${i%%.xcf}.png\")"
done

echo "(gimp-quit 0)"

} | gimp -i -b -
</code>```

Tested working with Gimp v2.10.18 on Kubuntu 20.04.
Thanks to patdavid at pixls.us for the original script.

Title: Batch convert from XCF version 11

Body:
Here is a self-contained bash script that should convert all xcf files in your current directory into png format copies.  It should work on any Linux computer with Gimp installed.  It does not require any installation in script directories:

#!/bin/bash
# xcfs2png.sh
# Invoke The GIMP with Script-Fu convert-xcf-png
# No error checking.
{
cat <<EOF
(define (convert-xcf-png filename outpath)
    (let* (
            (image (car (gimp-xcf-load RUN-NONINTERACTIVE filename filename )))
            (drawable (car (gimp-image-merge-visible-layers image CLIP-TO-IMAGE)))
            )
        (begin (display "Exporting ")(display filename)(display " -> ")(display outpath)(newline))
        (file-png-save2 RUN-NONINTERACTIVE image drawable outpath outpath 0 9 0 0 0 0 0 0 0)
        (gimp-image-delete image)
    )
)

(gimp-message-set-handler 1) ; Messages to standard output
EOF

for i in *.xcf; do
  echo "(convert-xcf-png \"$i\" \"${i%%.xcf}.png\")"
done

echo "(gimp-quit 0)"

} | gimp -i -b -

Tested working with Gimp v2.10.18 on Kubuntu 20.04.
Thanks to patdavid at pixls.us for the original script.


问:
Query with DynamoDB Secondary Index AWS SDK 2 Java exception creating DynamoDbIndex object
I'm having trouble running a query against a secondary index, getting an exception:

Ex getting dynamodb scan: java.lang.IllegalArgumentException: Attempt to execute an operation that requires a secondary index without defining the index attributes in the table metadata. Index name: category-timestamp-index

Can someone guide me on how I'm doing this wrong?

My table is idIT_RSS_Sources and I've created an index category-timestamp-index.

screenshot attached of index

My code is:

```<code>DynamoDbEnhancedClient enhancedClient = getEnhancedDBClient(region);

 // Create a DynamoDbTable object

logger.debug("getting RSS Source category-timestamp-index");

//this throws the exception
DynamoDbIndex<RSS_Source> catIndex =
        enhancedClient.table("idIT_RSS_Sources",
        TableSchema.fromBean(RSS_Source.class))
         .index("category-timestamp-index");

                logger.debug("building query attributes");

                AttributeValue att = AttributeValue.builder()
                        .s(theCategory)
                        .build();

                Map<String, AttributeValue> expressionValues = new HashMap<>();
                expressionValues.put(":value", att);

                Expression expression = Expression.builder()
                        .expression("category = :value")
                        .expressionValues(expressionValues)
                        .build();

                // Create a QueryConditional object that's used in the query operation
                QueryConditional queryConditional = QueryConditional
                        .keyEqualTo(Key.builder().partitionValue(theCategory)
                        .build());

                logger.debug("calling catIndex.query in getRSS...ForCategory");

                Iterator<Page<RSS_Source>> dbFeedResults =  (Iterator<Page<RSS_Source>>) catIndex.query(
                        QueryEnhancedRequest.builder()
                        .queryConditional(queryConditional)
                        .build());
</code>```

答:
solved, I was not using the proper annotation in my model class: </p>

```<code>@DynamoDbSecondaryPartitionKey(indexNames = { "category-index" })
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }
</code>```

Body:
I'm having trouble running a query against a secondary index, getting an exception:

Ex getting dynamodb scan: java.lang.IllegalArgumentException: Attempt to execute an operation that requires a secondary index without defining the index attributes in the table metadata. Index name: category-timestamp-index

Can someone guide me on how I'm doing this wrong?

My table is idIT_RSS_Sources and I've created an index category-timestamp-index.

screenshot attached of index

My code is:

DynamoDbEnhancedClient enhancedClient = getEnhancedDBClient(region);

 // Create a DynamoDbTable object

logger.debug("getting RSS Source category-timestamp-index");

//this throws the exception
DynamoDbIndex<RSS_Source> catIndex =
        enhancedClient.table("idIT_RSS_Sources",
        TableSchema.fromBean(RSS_Source.class))
         .index("category-timestamp-index");

                logger.debug("building query attributes");

                AttributeValue att = AttributeValue.builder()
                        .s(theCategory)
                        .build();

                Map<String, AttributeValue> expressionValues = new HashMap<>();
                expressionValues.put(":value", att);

                Expression expression = Expression.builder()
                        .expression("category = :value")
                        .expressionValues(expressionValues)
                        .build();

                // Create a QueryConditional object that's used in the query operation
                QueryConditional queryConditional = QueryConditional
                        .keyEqualTo(Key.builder().partitionValue(theCategory)
                        .build());

                logger.debug("calling catIndex.query in getRSS...ForCategory");

                Iterator<Page<RSS_Source>> dbFeedResults =  (Iterator<Page<RSS_Source>>) catIndex.query(
                        QueryEnhancedRequest.builder()
                        .queryConditional(queryConditional)
                        .build());

Body:
solved, I was not using the proper annotation in my model class:

@DynamoDbSecondaryPartitionKey(indexNames = { "category-index" })
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }


问:
Plotting mean and 95% confidence interval with Hmisc::xYplot and adjusting x axis
I'm trying to plot the results of a regression and I need to plot the coefficients estimated plus 95% confidence interval (actually I have 95% credibility interval, since I'm fitting a Bayesian model, but the idea is the same). And in the x axis, I need to put the name of each variable.

Here what I tried, but it didn't work.

```<code>library(lattice)
library(Hmisc)

betas1=c(0.4271611, -0.4730473, 0.8428530, -0.4356814,  0.2699920, -0.2308315)
quantiles.beta = matrix(c(-0.09015,-1.30900, 0.43290,  -0.85280, 0.02675, -0.56850, 0.93940, 0.37390, 1.28900, -0.03920, 0.52410, 0.07017), ncol=2)

xYplot(Cbind(betas1,quantiles.beta) ~ seq(0, 125, 25), varwidth = TRUE, ylab="Betas",
xlab="Ano", ylim=c(-1.5, 1.5),  scales=list(cex=1.2, x = list(at=seq(0,125, by=25),
labels = c("PIB per cap.", "democracia", "ginete_park", "educ","patentes", "FDI" ) ),
abline=c(list(h=0), lty="dotted",
col= "grey69"), main="Betas estimados no modelo 1",
sub="Inclinação das Covariáveis com respectivos 95% intervalo de credibilidade estimados no modelo1"))
</code>```

Thanks in advance for any help.

ps.: helping to set title, xlab and ylab font and size would be a plus to me.

答:
Sorry guys, but I found the errors on the code above. In this case, do I answer my own question?

Here the code that works...

```<code>xYplot(Cbind(betas1,quantiles.beta) ~ seq(0, 125, 25)
, varwidth = TRUE, ylab="Betas",xlab="Ano", ylim=c(-1.5, 1.5),
scales=list(cex=1.2, x = list(at=seq(0,125, by=25),
labels = c("PIB per cap.", "democracia", "ginete_park", "educ","patentes", "FDI" ))) ,
abline=c(list(h=0), lty="dotted", col= "grey69"), main="Betas estimados no modelo 1",
sub="Inclinação das Covariáveis com respectivos 95% intervalo de credibilidade estimados no modelo1")
</code>```

update: It was a silly mistake, so I don't know if I deserve an up vote for my answer after all. We don't wanna incentive people to ask silly question and answer them in order to get an up vote (I didn't this on purpose, of course). In any case, as requested, here what was wrong:

There was a missing parentesis after "labels". And I inserted this missing parentesis in the end of the code. So, I just put the parentesis in the proper place.

Body:
I'm trying to plot the results of a regression and I need to plot the coefficients estimated plus 95% confidence interval (actually I have 95% credibility interval, since I'm fitting a Bayesian model, but the idea is the same). And in the x axis, I need to put the name of each variable.

Here what I tried, but it didn't work.

library(lattice)
library(Hmisc)

betas1=c(0.4271611, -0.4730473, 0.8428530, -0.4356814,  0.2699920, -0.2308315)
quantiles.beta = matrix(c(-0.09015,-1.30900, 0.43290,  -0.85280, 0.02675, -0.56850, 0.93940, 0.37390, 1.28900, -0.03920, 0.52410, 0.07017), ncol=2)

xYplot(Cbind(betas1,quantiles.beta) ~ seq(0, 125, 25), varwidth = TRUE, ylab="Betas",
xlab="Ano", ylim=c(-1.5, 1.5),  scales=list(cex=1.2, x = list(at=seq(0,125, by=25),
labels = c("PIB per cap.", "democracia", "ginete_park", "educ","patentes", "FDI" ) ),
abline=c(list(h=0), lty="dotted",
col= "grey69"), main="Betas estimados no modelo 1",
sub="Inclinação das Covariáveis com respectivos 95% intervalo de credibilidade estimados no modelo1"))

Thanks in advance for any help.

ps.: helping to set title, xlab and ylab font and size would be a plus to me.

Body:
Sorry guys, but I found the errors on the code above. In this case, do I answer my own question?

Here the code that works...

xYplot(Cbind(betas1,quantiles.beta) ~ seq(0, 125, 25)
, varwidth = TRUE, ylab="Betas",xlab="Ano", ylim=c(-1.5, 1.5),
scales=list(cex=1.2, x = list(at=seq(0,125, by=25),
labels = c("PIB per cap.", "democracia", "ginete_park", "educ","patentes", "FDI" ))) ,
abline=c(list(h=0), lty="dotted", col= "grey69"), main="Betas estimados no modelo 1",
sub="Inclinação das Covariáveis com respectivos 95% intervalo de credibilidade estimados no modelo1")

update: It was a silly mistake, so I don't know if I deserve an up vote for my answer after all. We don't wanna incentive people to ask silly question and answer them in order to get an up vote (I didn't this on purpose, of course). In any case, as requested, here what was wrong:

There was a missing parentesis after "labels". And I inserted this missing parentesis in the end of the code. So, I just put the parentesis in the proper place.


问:
How do I access the state of another component via Redux store
Say I have two components, App and DialogBox;

so my react store also has two objects

```<code>const rootReducer = combineReducers({
    app: appReducer,
    dialog: dialogReducer
});

export const store = createStore(rootReducer);
</code>```

Now, when I have to open the Dialog box, I call the dialogBoxActions.openDialog()
And, when I close the Dialog box, I call dialogBoxActions.closeDialog() and also appActions.notifyDialogClosed();

This works, but is there a way to do this in more clearer way?

For example can I use the state.dialog from the store in App? This is what I tried in the App

```<code>const mapStateToProps = (state) => {
    return {
        checkCloseDialog: state.dialog.openDialog
    }
}
</code>```

The ComponentWillReceiveProps does get the checkCloseDialog object, but it gets the old state. I debugged to find out that it gets triggered correctly after the reducer function of the DialogBox component but I get old data.

Is there any elegant way of accessing each other's store or is it Redux's philosophy that components should communicate with each other via actions?

答:
Ah! Okay, my bad.

Yes, it is possible. And it works. My mistake was I was trying to use it inside ComponentWillReceiveProps() method. The thing is, it seems the redux store gets updated later. So, ComponentWillReceiveProps() will hold an old state.

Hence, render() and ComponentDidUpdate() methods get the updated state.

The aim here is to help reduce the multiple action calls between independent components.

For example, a Dialog should not be concerned with what the caller should do after it closes itself. Instead the caller should subscribe to the state of Dialog to decide what to do.

Hope this helps others.

Body:
Say I have two components, App and DialogBox;

so my react store also has two objects

const rootReducer = combineReducers({
    app: appReducer,
    dialog: dialogReducer
});

export const store = createStore(rootReducer);

Now, when I have to open the Dialog box, I call the dialogBoxActions.openDialog()
And, when I close the Dialog box, I call dialogBoxActions.closeDialog() and also appActions.notifyDialogClosed();

This works, but is there a way to do this in more clearer way?

For example can I use the state.dialog from the store in App? This is what I tried in the App

const mapStateToProps = (state) => {
    return {
        checkCloseDialog: state.dialog.openDialog
    }
}

The ComponentWillReceiveProps does get the checkCloseDialog object, but it gets the old state. I debugged to find out that it gets triggered correctly after the reducer function of the DialogBox component but I get old data.

Is there any elegant way of accessing each other's store or is it Redux's philosophy that components should communicate with each other via actions?