问:
INSERT INTO based on SELECT and versioned record
I have a table that contains the current state of employees like below :

```<code> SELECT EmployeeId ,OfficeId from EmpCurrent
</code>```

The output is like below :

```<code>EmployeeId OfficeId
54          67
64          57
89          23
</code>```

And I have another table containing the full history for an employee except for OfficeId which isn't historised (I added the column OfficeId which is NULL to insert from EmpCurrent) :

```<code>SELECT EmployeeId ,Func AS [Function],OfficeId,Version from EmpHistory
</code>```

The output is like below for EmployeeId=54:

```<code>EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   NULL     3
</code>```

I want to get the OfficeId from EmpCurrent and insert it in EmpHistory in the last Version(max version) of the each Employee, my output will be like below :

```<code>EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   67       3
</code>```

答:
demo on db<>fiddle

Firstly, You need to get 3 fields h.EmployeeId, c.OfficeId, max(Version) as MaxVersion.

Secondly, Update h.OfficeId = cte.OfficeId on #EmpHistory table with 2 conditions h.EmployeeId = cte.EmployeeId and MaxVersion = h.Version

Full Code

```<code>;with cte as(
select h.EmployeeId, c.OfficeId, max(Version) as MaxVersion
from #EmpHistory h
inner join #EmpCurrent c on h.EmployeeId = c.EmployeeId
group by h.EmployeeId, c.OfficeId
)

update h
set h.OfficeId = cte.OfficeId
from #EmpHistory h
inner join cte on h.EmployeeId = cte.EmployeeId and MaxVersion = h.Version
</code>```

Output

Body:
I have a table that contains the current state of employees like below :

 SELECT EmployeeId ,OfficeId from EmpCurrent

The output is like below :

EmployeeId OfficeId
54          67
64          57
89          23

And I have another table containing the full history for an employee except for OfficeId which isn't historised (I added the column OfficeId which is NULL to insert from EmpCurrent) :

SELECT EmployeeId ,Func AS [Function],OfficeId,Version from EmpHistory

The output is like below for EmployeeId=54:

EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   NULL     3

I want to get the OfficeId from EmpCurrent and insert it in EmpHistory in the last Version(max version) of the each Employee, my output will be like below :

EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   67       3

Body:
demo on db<>fiddle

Firstly, You need to get 3 fields h.EmployeeId, c.OfficeId, max(Version) as MaxVersion.

Secondly, Update h.OfficeId = cte.OfficeId on #EmpHistory table with 2 conditions h.EmployeeId = cte.EmployeeId and MaxVersion = h.Version

Full Code

;with cte as(
select h.EmployeeId, c.OfficeId, max(Version) as MaxVersion
from #EmpHistory h
inner join #EmpCurrent c on h.EmployeeId = c.EmployeeId
group by h.EmployeeId, c.OfficeId
)

update h
set h.OfficeId = cte.OfficeId
from #EmpHistory h
inner join cte on h.EmployeeId = cte.EmployeeId and MaxVersion = h.Version

Output


来源: stackexchange

问:
library module and google-services.json files
I am already using an application(has app module) which uses conversations.im as the base. This application has free, paid etc product flavors and debug and release build types. This project already has firebase integration and has 2 applications integrated. I have one google-services.json file in the root directory of the app module.

Now I want to move away from conversations.im(ejabber) and want to implement a separate chat component using cloud firestore. I have created this component as an android library module which I will use in my existing app module.

I want to have separate chat data for this chat library for debug and release types. This will require me to have unique application ids for this library module. But documentation says I cannot have applicationId in a library module.

I am confused where to keep the google-services.json files, in library module or in the app module which will use the chat library module. Looks like can't keep in library because of limitation. And if I keep in app module, library chat module can't work as a separate module in itself.

How should I go about this setup so that I could use different google-services.json files for debug and release types and at the same time make this new module as a library.

答:
I figured out that we don't have to put the google-services.json file in the library module. We can keep them in the app module which uses the library module.

Now the next question is, is it possible to view data sent from different build variants of the same app under different application views so that we don't accidentally corrupt the test data and production data in firestore?

ContentLicense: CC BY-SA 4.0


问:
SUM.PRODUCT - how to get an array of values that correspond to a single cell value
I'm trying to calculate weight average per user for three different processes. My table looks like this:

```<code>User       || Process   || Bonus[%] || Weight
John Smith || RETURNS   || 5        || 2
John Smith || PUTAWAY   || 10       || 3
John Smith || RECEIVING || 7        || 1
</code>```

So basically I want my formula in each row to look like this:

=SUM.PRODUCT({5,10,7},{2,3,1})/SUM({2,3,1})

The formula needs to have an array of values based on the User Name. How can I do that?

答:
You can use this:

```<code>=SUMPRODUCT(--(user_name_column="user name"),[Bonus %],[Weight])/SUMIF(user_name_column,"user name",[Weight])
</code>```

adjusting the ranges to match your data locations.

Body:
I'm trying to calculate weight average per user for three different processes. My table looks like this:

User       || Process   || Bonus[%] || Weight
John Smith || RETURNS   || 5        || 2
John Smith || PUTAWAY   || 10       || 3
John Smith || RECEIVING || 7        || 1

So basically I want my formula in each row to look like this:

=SUM.PRODUCT({5,10,7},{2,3,1})/SUM({2,3,1})

The formula needs to have an array of values based on the User Name. How can I do that?

Body:
You can use this:

=SUMPRODUCT(--(user_name_column="user name"),[Bonus %],[Weight])/SUMIF(user_name_column,"user name",[Weight])

adjusting the ranges to match your data locations.


问:
How to re-order a xml-file with xslt while keeping structure
I know it is a basic problem but I'm very new to XSL and I don't get it to work. I have a XML-File with a given structure and I want to rearrange the XML in alphabetical order based on one node while keeping the structure. I need that XSLT-Stylesheet to reorder a XML when importing it in Adobe InDesign.

My File:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
</Root>
</code>```

I want to rearange the document in the way that it is sorted alphabetically based on the tag <Last_name>. My desired output is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
</Root>
</code>```

I found some solutions to re-arange my output but it's always in respect to output HTML and not XML.

Update: As requested here is my atempt to solve the problem. I stuck because it copyies now all in one tag <Employee>.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
  <Root>
  <Employee>
      <xsl:for-each select="Root/Employee">
      <xsl:sort select="Last_Name"/>
        <First_Name><xsl:value-of select="First_Name"/></First_Name>
        <Last_Name><xsl:value-of select="Last_Name"/></Last_Name>
        <Salary><xsl:value-of select="Salary"/></Salary>
        <Performance><xsl:value-of select="Performance"/></Performance>
      </xsl:for-each>
  </Employee>
  </Root>
</xsl:template>

</xsl:stylesheet>
</code>```

答:
You were really close to the solution:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
  <Root>
      <xsl:for-each select="Root/Employee">

      <xsl:sort select="Last_Name"/>
      <Employee>
        <First_Name><xsl:value-of select="First_Name"/></First_Name>
        <Last_Name><xsl:value-of select="Last_Name"/></Last_Name>
        <Salary><xsl:value-of select="Salary"/></Salary>
        <Performance><xsl:value-of select="Performance"/></Performance>
       </Employee>
      </xsl:for-each>
  </Root>
</xsl:template>

</xsl:stylesheet>
</code>```

Body:
I know it is a basic problem but I'm very new to XSL and I don't get it to work. I have a XML-File with a given structure and I want to rearrange the XML in alphabetical order based on one node while keeping the structure. I need that XSLT-Stylesheet to reorder a XML when importing it in Adobe InDesign.

My File:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
</Root>

I want to rearange the document in the way that it is sorted alphabetically based on the tag <Last_name>. My desired output is:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
</Root>

I found some solutions to re-arange my output but it's always in respect to output HTML and not XML.

Update: As requested here is my atempt to solve the problem. I stuck because it copyies now all in one tag <Employee>.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
  <Root>
  <Employee>
      <xsl:for-each select="Root/Employee">
      <xsl:sort select="Last_Name"/>
        <First_Name><xsl:value-of select="First_Name"/></First_Name>
        <Last_Name><xsl:value-of select="Last_Name"/></Last_Name>
        <Salary><xsl:value-of select="Salary"/></Salary>
        <Performance><xsl:value-of select="Performance"/></Performance>
      </xsl:for-each>
  </Employee>
  </Root>
</xsl:template>

</xsl:stylesheet>

Body:
You were really close to the solution:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
  <Root>
      <xsl:for-each select="Root/Employee">

      <xsl:sort select="Last_Name"/>
      <Employee>
        <First_Name><xsl:value-of select="First_Name"/></First_Name>
        <Last_Name><xsl:value-of select="Last_Name"/></Last_Name>
        <Salary><xsl:value-of select="Salary"/></Salary>
        <Performance><xsl:value-of select="Performance"/></Performance>
       </Employee>
      </xsl:for-each>
  </Root>
</xsl:template>

</xsl:stylesheet>


问:
Fetch client redirect
I'm executing a fetch request with the FetchClient (through an Aurelia wrapper).

The fetch client has three modes:

Follow, Error and Manual (I'll discard error for this question)

If I use follow, the fetch client automatically follows the redirection. The problem is that my original request uses basic auth. It works for the original request, but the redirected URL fails with those basic auth credentials.

If I use the "manual" mode, it doesn't follow through, but I don't get access to the "Location" of the redirected resource and I can't get the proper URL for the redirected resource.

How can I work around this?

It would either be a mode where I get access to the complete response, or an interceptor that allows me to modify the headers before requesting the redirected resource.

答:
You can check the url property of the response when redirected property is true

https://developer.mozilla.org/en-US/docs/Web/API/Response/url

```<code>fetch("someUrl")
.then(r=>{
  if(r.redirected){
     const redirectedToUrl = r.url
  }
}
</code>```

Title: Fetch client redirect

Body:
You can check the url property of the response when redirected property is true

https://developer.mozilla.org/en-US/docs/Web/API/Response/url

fetch("someUrl")
.then(r=>{
  if(r.redirected){
     const redirectedToUrl = r.url
  }
}


问:
Angular2: Custom material theme in each lazy loaded submodule

Problem with loading custom Angular Material 2 themes in separate submodules of Angular 7 app

I have angular wrapper module (app module) and many independent lazy-loaded sub-modules. Each sub-module behaves like a totaly separate app and needs its own angular material theme.

I've created custom theme for each sub-module and tried to reference the custom theme in each of components' .scss file with relative path.

Some of the Material components apply the custom theme (button) and some (mat-form-field) just take the theme specified in styles.scss.

One way I can avoid this is including each custom theme in 'styles' array of angular.json, but I'm afraid that, by doing this, each independent sub-module (app) will have to load every themes' compiled .css and it'll be overhead.

Is there any known issue with this or any better solution?

home-app.component.scss:

```<code>@import './theme.scss';

</code>```

VS.

angular.json

```<code>...
"styles": [
    "src/styles.scss",
    "src/app/orgs/home/theme.scss" // <-- FIXED BY ADDING THIS
],
...

</code>```

Expected:
Theme declared in the home-app.component.scss will be loaded and applied to every material component used in home-app.component.html

Actual:
If I don't add "src/app/orgs/home/theme.scss" to angular.json, the custom theme declared in styles.scss will be applied to some material components used in home-app.component.html, and some material components will use the imported theme specified in home-app.component.scss

答:
I think i understood your problem and here is a solution for you :)

So when you create a new ng-project with the cli with opt in material-theming, you will get a inital theming configuration like the following (or you can find the config in the Material Guides)

```<code>import '~@angular/material/theming';
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$candy-app-primary: mat-palette($mat-indigo);
$candy-app-accent:  mat-palette($mat-pink, A200, A100, A400);

// The warn palette is optional (defaults to red).
$candy-app-warn:    mat-palette($mat-red);

// Create the theme object (a Sass map containing all of the palettes).
$candy-app-theme: mat-light-theme($candy-app-primary, $candy-app-accent, $candy-app-warn);

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($candy-app-theme);
</code>```

The most important part of this is to remember that you must include just once the mat-core() in your application (in order to have a single material styles css file).

After that you can create custtom themes by including import '~@angular/material/theming'; wherever desired in the application and apply the theme by wrapping it in a css calss. For example after you include the mat-core once in you root .scss file, in a lazy loaded module you can do the following thing:

@import "~@angular/material/theming";

.theme1 {
  $theme-primary: mat-palette($mat-red);
  $theme-accent: mat-palette($mat-lime, A200, A100, A400);

  // The warn palette is optional (defaults to red).
  $theme-warn: mat-palette($mat-red);

  // Create the theme object (a Sass map containing all of the palettes).
  $theme-theme: mat-light-theme($theme-primary, $theme-accent, $theme-warn);

  // Include theme styles for core and each component used in your app.
  // Alternatively, you can import and @include the theme mixins for each component
  // that you are using.
  @include angular-material-theme($theme-theme);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="theme1">
  <mat-toolbar color="accent">
    <button color='primary' mat-button routerLink="/1">Go to 1</button>
    <button color='primary' mat-button routerLink="/2">Go to 2</button>
  </mat-toolbar>
</div></code>```

Of course instead of two buttons you can also place your router-outlet inside the container with class theme1 and achive the desired result (different theme per lazy loaded module). Keep in mind that we are just importing import '~@angular/material/theming';` in the places where we need custom theming.

Here is a live example: CodeSandbox

Body:
Problem with loading custom Angular Material 2 themes in separate submodules of Angular 7 app

I have angular wrapper module (app module) and many independent lazy-loaded sub-modules. Each sub-module behaves like a totaly separate app and needs its own angular material theme.

I've created custom theme for each sub-module and tried to reference the custom theme in each of components' .scss file with relative path.

Some of the Material components apply the custom theme (button) and some (mat-form-field) just take the theme specified in styles.scss.

One way I can avoid this is including each custom theme in 'styles' array of angular.json, but I'm afraid that, by doing this, each independent sub-module (app) will have to load every themes' compiled .css and it'll be overhead.

Is there any known issue with this or any better solution?

home-app.component.scss:

@import './theme.scss';

VS.

angular.json

...
"styles": [
    "src/styles.scss",
    "src/app/orgs/home/theme.scss" // <-- FIXED BY ADDING THIS
],
...

Expected:
Theme declared in the home-app.component.scss will be loaded and applied to every material component used in home-app.component.html

Actual:
If I don't add "src/app/orgs/home/theme.scss" to angular.json, the custom theme declared in styles.scss will be applied to some material components used in home-app.component.html, and some material components will use the imported theme specified in home-app.component.scss

Body:
I think i understood your problem and here is a solution for you :)

So when you create a new ng-project with the cli with opt in material-theming, you will get a inital theming configuration like the following (or you can find the config in the Material Guides)

import '~@angular/material/theming';
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$candy-app-primary: mat-palette($mat-indigo);
$candy-app-accent:  mat-palette($mat-pink, A200, A100, A400);

// The warn palette is optional (defaults to red).
$candy-app-warn:    mat-palette($mat-red);

// Create the theme object (a Sass map containing all of the palettes).
$candy-app-theme: mat-light-theme($candy-app-primary, $candy-app-accent, $candy-app-warn);

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($candy-app-theme);

The most important part of this is to remember that you must include just once the mat-core() in your application (in order to have a single material styles css file).

After that you can create custtom themes by including import '~@angular/material/theming'; wherever desired in the application and apply the theme by wrapping it in a css calss. For example after you include the mat-core once in you root .scss file, in a lazy loaded module you can do the following thing:

@import "~@angular/material/theming";

.theme1 {
  $theme-primary: mat-palette($mat-red);
  $theme-accent: mat-palette($mat-lime, A200, A100, A400);

  // The warn palette is optional (defaults to red).
  $theme-warn: mat-palette($mat-red);

  // Create the theme object (a Sass map containing all of the palettes).
  $theme-theme: mat-light-theme($theme-primary, $theme-accent, $theme-warn);

  // Include theme styles for core and each component used in your app.
  // Alternatively, you can import and @include the theme mixins for each component
  // that you are using.
  @include angular-material-theme($theme-theme);
}

<div class="theme1">
  <mat-toolbar color="accent">
    <button color='primary' mat-button routerLink="/1">Go to 1</button>
    <button color='primary' mat-button routerLink="/2">Go to 2</button>
  </mat-toolbar>
</div>

Of course instead of two buttons you can also place your router-outlet inside the container with class theme1 and achive the desired result (different theme per lazy loaded module). Keep in mind that we are just importing import '~@angular/material/theming';` in the places where we need custom theming.

Here is a live example: CodeSandbox


问:
How to persist data in tableview when i pop from tableview using navigationbar's left navigation item in iphone
i have a login controller when user enters his username and password and click on the submit button the table view fetches the data from the database and presents the data but the problem is when i click on the left navigation bar item on the navigation ans pop back again to my login controller and enter credentials and click on submit button the tableview is empty.What may be the problem</p>

答: i think you did a login controller code in viewdidload method. popupviewcontroller work out in viewwillappear:(Bool) method.Better once you login you may hide a backbutton</p>

ContentLicense: CC BY-SA 3.0


Title: SUM.PRODUCT - how to get an array of values that correspond to a single cell value

Body:
Try formula:

=SUMPRODUCT((A2=$A$2:$A$7)*($C$2:$C$7)*($D$2:$D$7))/SUMPRODUCT((A2=$A$2:$A$7)*($D$2:$D$7))


问:
Why NumberUtils.isNumber() is not working properly?
when i check with condition 08 or 09 or 010  and above leading with 0  in org.apache.commons.lang3.math.NumberUtils.isNumber("08")

答:
https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/math/NumberUtils.html#isCreatable-java.lang.String-

Use isCreatable instead.  I assume isNumber works basically the same way.

"Non-hexadecimal strings beginning with a leading zero are treated as octal values." Thus the string 09 will return false, since 9 is not a valid octal value. However, numbers beginning with 0. are treated as decimal."

00-07 are numbers. 08--010 are not interpreted as octal numbers, but that is a library issue.

See What do numbers starting with 0 mean in python?

When in doubt read the manual.


问:
How to extract substring from a blob variable in PL/SQL?
I have v_fileContent blob;, the value of which is returned by a different procedure, and I need to pass approximately 1000 first characters of it to another procedure. I've googled a lot and have only found ways of getting substrings of various lob type columns in tables. But how is it possible to get a substring of a variable?

答:
If you are using a single byte per character encoding (not Unicode) you can use:

Ask Tom Oracle Source

```<code>utl_raw.cast_to_varchar2( dbms_lob.substr( BLOB_LOCATOR, 1000, 1 ) );
</code>```

Body:
If you are using a single byte per character encoding (not Unicode) you can use:

Ask Tom Oracle Source

utl_raw.cast_to_varchar2( dbms_lob.substr( BLOB_LOCATOR, 1000, 1 ) );


问:
Does anyone has "Best Practice" to share for Unit/Integration/Regression testing with Snowflake?
We are embarking in a project using both Matillion and Snowflake and want to put in place some Unit/Integration/Regression testing.

Automated would be brilliant but manual would be good too.

We could invent something (simple) ourselves... but it would be better to benefit from other people experience.

答:
Indeed there is a lack of possibility to unit/integration testing your models within Matillion.
You need some external tools to implement these - we were using a Spring Boot Microservice with the following steps:

Setup the Testdata with some Plain SQL scripts via JDBC connection to the underlying Database

Run the correspondig job via the Matillion REST API

Using JUnit to make assertion and verify the outcome


问:
Python 3: unsupported operand type(s) for -: 'str' and 'float'
I'm currently learning matplot and I saw this code on the official tutorial, but I got the error unsupported operand type(s) for -: 'str' and 'float'. How could I fix this?

```<code>import matplotlib.pyplot as plt
import numpy as np

names = ["a", "b", "c"]
values = [1, 10, 100]

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()
</code>```

答:
EDIT: as pointed below, your code is also correct

plt.bar expects the first argument to be the x-coordinates of your bars, not labels. You can put the labels by doing:

```<code>plt.bar([1,2,3], values, tick_label=names)
</code>```

Body:
I'm currently learning matplot and I saw this code on the official tutorial, but I got the error unsupported operand type(s) for -: 'str' and 'float'. How could I fix this?

import matplotlib.pyplot as plt
import numpy as np

names = ["a", "b", "c"]
values = [1, 10, 100]

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()

Body:
EDIT: as pointed below, your code is also correct

plt.bar expects the first argument to be the x-coordinates of your bars, not labels. You can put the labels by doing:

plt.bar([1,2,3], values, tick_label=names)


问:
CASE query optimization
```<code>SELECT
  COUNT(CASE WHEN VALUE = 1 THEN 1 END) AS score_1,
  COUNT(CASE WHEN VALUE = 2 THEN 1 END) AS score_2,
  COUNT(CASE WHEN VALUE = 3 THEN 1 END) AS score_3,
  COUNT(CASE WHEN VALUE = 4 THEN 1 END) AS score_4,
  COUNT(CASE WHEN VALUE = 5 THEN 1 END) AS score_5,
  COUNT(CASE WHEN VALUE = 6 THEN 1 END) AS score_6,
  COUNT(CASE WHEN VALUE = 7 THEN 1 END) AS score_7,
  COUNT(CASE WHEN VALUE = 8 THEN 1 END) AS score_8,
  COUNT(CASE WHEN VALUE = 9 THEN 1 END) AS score_9,
  COUNT(CASE WHEN VALUE = 10 THEN 1 END) AS score_10
FROM
  `answers`
WHERE
`created_at` BETWEEN '2017-01-01 00:00:00' AND '2019-11-30 23:59:59'
</code>```

Is there a way to optimize this query, because I have 4 million answer records in my DB, and it runs very slowly?

答:
You could try add  a redundant composite index </p>

```<code>create idx1 on table answers(created_at, value)
</code>```

<p>using redudance in index  the query should be result without accessing to table data just using the index  content </p>

Title: CASE query optimization

Body:
SELECT
  COUNT(CASE WHEN VALUE = 1 THEN 1 END) AS score_1,
  COUNT(CASE WHEN VALUE = 2 THEN 1 END) AS score_2,
  COUNT(CASE WHEN VALUE = 3 THEN 1 END) AS score_3,
  COUNT(CASE WHEN VALUE = 4 THEN 1 END) AS score_4,
  COUNT(CASE WHEN VALUE = 5 THEN 1 END) AS score_5,
  COUNT(CASE WHEN VALUE = 6 THEN 1 END) AS score_6,
  COUNT(CASE WHEN VALUE = 7 THEN 1 END) AS score_7,
  COUNT(CASE WHEN VALUE = 8 THEN 1 END) AS score_8,
  COUNT(CASE WHEN VALUE = 9 THEN 1 END) AS score_9,
  COUNT(CASE WHEN VALUE = 10 THEN 1 END) AS score_10
FROM
  `answers`
WHERE
`created_at` BETWEEN '2017-01-01 00:00:00' AND '2019-11-30 23:59:59'

Is there a way to optimize this query, because I have 4 million answer records in my DB, and it runs very slowly?

Body:
You could try add  a redundant composite index

create idx1 on table answers(created_at, value)

using redudance in index  the query should be result without accessing to table data just using the index  content


问:
How to average two points in nalgebra?
I have a triangle ABC, and I want to generate triangle DEF.

Triangle DEF is created using the centre of all edges of ABC. Nalgebra doesn't seem to allow me to do add points together, only vectors.

use nalgebra::Point2;

fn get_def(a: Point2<f32>, b: Point2<f32>, c: Point2<f32>) -> [Point2<f32>; 3] {
    let d = (a + b) / 2.0; // error
    let e = (b + c) / 2.0; // error
    let f = (c + a) / 2.0; // error

    [d, e, f]
}
```

.

答:
Nalgebra has a function specifically for this, nalgebra::center.

use nalgebra::{Point2, center};

fn get_def(a: Point2<f32>, b: Point2<f32>, c: Point2<f32>) -> [Point2<f32>; 3] {
    let d = center(&a, &b);
    let e = center(&b, &c);
    let f = center(&c, &a;

    [d, e, f]
}
```

Title: How to average two points in nalgebra?

Body:
I have a triangle ABC, and I want to generate triangle DEF.

Triangle DEF is created using the centre of all edges of ABC. Nalgebra doesn't seem to allow me to do add points together, only vectors.

use nalgebra::Point2;

fn get_def(a: Point2<f32>, b: Point2<f32>, c: Point2<f32>) -> [Point2<f32>; 3] {
    let d = (a + b) / 2.0; // error
    let e = (b + c) / 2.0; // error
    let f = (c + a) / 2.0; // error

    [d, e, f]
}

.


问:
Swift: click inside programmatically generated view inside table
Tried many things, but none of it worked.

My current views hierarchy:

TableView Cell

Vertical Stack View

Programmatically generated View - gesture recognizer not fired

```<code>let vContainer = UIView()
vContainer.translatesAutoresizingMaskIntoConstraints = false
vContainer.isUserInteractionEnabled = true
vContainer.backgroundColor = .red
//Some view generation inside box is skipped (can be seen on image)
self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
vContainer.addGestureRecognizer(tapRecognizer)
</code>```

later in class:

```<code>    @objc private func showValuePicker(sender: UITapGestureRecognizer) {
        print("showValuePicker")
    }
</code>```

Red box is View, where i want to add click.

答:
Why have you specified the target to be nil?

at:

```<code>var tapRecognizer = UITapGestureRecognizer(target: nil, action: #selector(showValuePicker(sender:)))
</code>```

From the documentation:

Target

An object that is the recipient of action messages sent by the
  receiver when it recognizes a gesture. nil is not a valid value.

Can you try adding self as the target?

Body:
Tried many things, but none of it worked.

My current views hierarchy:

TableView Cell

Vertical Stack View

Programmatically generated View - gesture recognizer not fired

let vContainer = UIView()
vContainer.translatesAutoresizingMaskIntoConstraints = false
vContainer.isUserInteractionEnabled = true
vContainer.backgroundColor = .red
//Some view generation inside box is skipped (can be seen on image)
self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
vContainer.addGestureRecognizer(tapRecognizer)

later in class:

    @objc private func showValuePicker(sender: UITapGestureRecognizer) {
        print("showValuePicker")
    }

Red box is View, where i want to add click.

Body:
Why have you specified the target to be nil?

at:

var tapRecognizer = UITapGestureRecognizer(target: nil, action: #selector(showValuePicker(sender:)))

From the documentation:

Target

An object that is the recipient of action messages sent by the
  receiver when it recognizes a gesture. nil is not a valid value.

Can you try adding self as the target?


问:
Lighthouse testing with postGraphQL fails when using subscriptions
I have a laravel package which uses GraphQL (Lighthouse) to extend my base project(s). Everything works fine when adding my package and doing queries etc.

But since I try to make a postGraphQL request within my testing file, where the given query or mutation utilizes the @broadcast Directive, the request fails saying:

```<code>Add the SubscriptionServiceProvider to your config/app.php to enable subscriptions.
</code>```

The SubscriptionServiceProvider is added to providers array of app config when booting the test environment. I use orchestra/testbench and add the provider within the getEnvironmentSetUp method.

But I think that the generated postGraphQL request doesn't have the SubscriptionServiceProvider added.
I traced it back to the Illuminate\Foundation\Testing\Concerns\MakesHttpRequest class which creates a new kernel object that does the request and doesn't seem to boot up as it should.

Maybe the problem is me being within a laravel package and not in a "regular" laravel project, where one would define the SubscriptionServiceProvider within config/app.php.

Is this a bug or am I missing something? Anybody here who had this problem as well? I couldn't find anything here or googling around unfortunately.

答:
I solved it!
Instead of trying to add the SubscriptionServiceProvider to the app environment using the getEnvironmentSetUp method of orchestra I now add it within the method getPackageProviders together with the LighthouseServiceProvider like so:

```<code>protected function getPackageProviders($app)
{
    return [
        LighthouseServiceProvider::class,
        SubscriptionServiceProvider::class,
        MyOwnPackageProvider::class,
    ];
}
</code>```

And it works like a charm :)

Body:
I have a laravel package which uses GraphQL (Lighthouse) to extend my base project(s). Everything works fine when adding my package and doing queries etc.

But since I try to make a postGraphQL request within my testing file, where the given query or mutation utilizes the @broadcast Directive, the request fails saying:

Add the SubscriptionServiceProvider to your config/app.php to enable subscriptions.

The SubscriptionServiceProvider is added to providers array of app config when booting the test environment. I use orchestra/testbench and add the provider within the getEnvironmentSetUp method.

But I think that the generated postGraphQL request doesn't have the SubscriptionServiceProvider added.
I traced it back to the Illuminate\Foundation\Testing\Concerns\MakesHttpRequest class which creates a new kernel object that does the request and doesn't seem to boot up as it should.

Maybe the problem is me being within a laravel package and not in a "regular" laravel project, where one would define the SubscriptionServiceProvider within config/app.php.

Is this a bug or am I missing something? Anybody here who had this problem as well? I couldn't find anything here or googling around unfortunately.

Body:
I solved it!
Instead of trying to add the SubscriptionServiceProvider to the app environment using the getEnvironmentSetUp method of orchestra I now add it within the method getPackageProviders together with the LighthouseServiceProvider like so:

protected function getPackageProviders($app)
{
    return [
        LighthouseServiceProvider::class,
        SubscriptionServiceProvider::class,
        MyOwnPackageProvider::class,
    ];
}

And it works like a charm :)


问:
Spring Integration : send json as request body and headers in http outbound gateway
I want to invoke an external REST endpoint POST request with a JSON payload which would be getting called from another service through the http inbound gateway.

I am using the below configuration for my application :

```<code><int:channel id="xappSearchRequest" />
<int:channel id="xappSearchResponse" />

<int:channel id="xappFilterChannelOutput"/>
<int:channel id="discardFilterChannel"/>
<int:channel id="mutableMessageChannel"/>

<int:filter  input-channel="mutableMessageChannel" output-channel="xappFilterChannelOutput" discard-channel="discardFilterChannel" ref="structureValidationFilter"/>

 <int:transformer input-channel="xappSearchRequest" output-channel="mutableMessageChannel"
    ref="mutableMessageTransformer" />

<int-http:inbound-gateway id="inboundxappSearchRequestGateway"
    supported-methods="POST"
    request-channel="xappSearchRequest"
    reply-channel="xappSearchResponse"
    mapped-response-headers="Return-Status, Return-Status-Msg, HTTP_RESPONSE_HEADERS"
    path="${xapp.request.path}"
    reply-timeout="50000"
    request-payload-type="standalone.CFIRequestBody">
</int-http:inbound-gateway>

<int:service-activator id="xappServiceActivator"
                input-channel="xappFilterChannelOutput"
                output-channel="xappSearchResponse"
                ref="xappSearchService"
                method="handlexappRequest"
                requires-reply="true"
                send-timeout="60000"/>

<int:service-activator id="dicardPayloadServiceActivator"
                input-channel="discardFilterChannel"
                output-channel="xappSearchResponse"
                ref="invalidPayloadService"
                method="getInvalidMessage"
                requires-reply="true"
                send-timeout="60000"/>

<int-http:outbound-gateway id="get.outbound.gateway"
    request-channel="get_send_channel" url="${cms.stub.request.url}"
    http-method="POST" reply-channel="get_receive_channel"
    expected-response-type="standalone.StubResponseBody">
</int-http:outbound-gateway>
</code>```

Not able to figure out how to send a JSON payload and custom headers to call the POST endpoint.

答:
Figured that out .
I am using a outbound gateway like below :

```<code><int-http:outbound-gateway id="get.outbound.gateway"
    request-channel="postCmsChannel" url="${cms.stub.request.url}"
    http-method="POST" reply-channel="zappSearchResponse"
    expected-response-type="standalone.StubResponseBody">
</int-http:outbound-gateway>
</code>```

The 'postCmsChannel' is the output-channel of service activator :

```<code>   <int:service-activator id="zappServiceActivator"
input-channel="xappFilterChannelOutput"
output-channel="postCmsChannel"
ref="xappSearchService"
method="handleXappRequest"
send-timeout="60000"/>
</code>```

The 'xappSearchService' is like below :

```<code>@Autowired
@Qualifier("postCmsChannel")
MessageChannel postCmsChannel;

 public void handleXappRequest(Message<CFIRequestBody> inMessage){

       /*
       * Map<String, Object> responseHeaderMap = new HashMap<String, Object>();
       *
        * //MessageHeaders headers = inMessage.getHeaders(); StubResponseBody
       * info=inMessage.getPayload();
       *
        * setReturnStatusAndMessage(responseHeaderMap); Message<StubResponseBody>
       * message = new GenericMessage<StubResponseBody>(info, responseHeaderMap);
       * return message;
       */
       inMessage.getHeaders();
       Map<String,String> headerMap=new HashMap<String,String>();
       headerMap.put("X-JWS-SIGNATURE", "dshdgshdgasshgdywtwtqsabh232wgd7wdyt");
       headerMap.put("X-PARTICIPANT-ID", "CMDRV2112BB");
      postCmsChannel.send(MessageBuilder.withPayload(inMessage.getPayload())

.copyHeadersIfAbsent(inMessage.getHeaders()).copyHeadersIfAbsent(headerMap).build());

 }

}
</code>```

Body:
I want to invoke an external REST endpoint POST request with a JSON payload which would be getting called from another service through the http inbound gateway.

I am using the below configuration for my application :

<int:channel id="xappSearchRequest" />
<int:channel id="xappSearchResponse" />

<int:channel id="xappFilterChannelOutput"/>
<int:channel id="discardFilterChannel"/>
<int:channel id="mutableMessageChannel"/>

<int:filter  input-channel="mutableMessageChannel" output-channel="xappFilterChannelOutput" discard-channel="discardFilterChannel" ref="structureValidationFilter"/>

 <int:transformer input-channel="xappSearchRequest" output-channel="mutableMessageChannel"
    ref="mutableMessageTransformer" />

<int-http:inbound-gateway id="inboundxappSearchRequestGateway"
    supported-methods="POST"
    request-channel="xappSearchRequest"
    reply-channel="xappSearchResponse"
    mapped-response-headers="Return-Status, Return-Status-Msg, HTTP_RESPONSE_HEADERS"
    path="${xapp.request.path}"
    reply-timeout="50000"
    request-payload-type="standalone.CFIRequestBody">
</int-http:inbound-gateway>

<int:service-activator id="xappServiceActivator"
                input-channel="xappFilterChannelOutput"
                output-channel="xappSearchResponse"
                ref="xappSearchService"
                method="handlexappRequest"
                requires-reply="true"
                send-timeout="60000"/>

<int:service-activator id="dicardPayloadServiceActivator"
                input-channel="discardFilterChannel"
                output-channel="xappSearchResponse"
                ref="invalidPayloadService"
                method="getInvalidMessage"
                requires-reply="true"
                send-timeout="60000"/>

<int-http:outbound-gateway id="get.outbound.gateway"
    request-channel="get_send_channel" url="${cms.stub.request.url}"
    http-method="POST" reply-channel="get_receive_channel"
    expected-response-type="standalone.StubResponseBody">
</int-http:outbound-gateway>

Not able to figure out how to send a JSON payload and custom headers to call the POST endpoint.

Body:
Figured that out .
I am using a outbound gateway like below :

<int-http:outbound-gateway id="get.outbound.gateway"
    request-channel="postCmsChannel" url="${cms.stub.request.url}"
    http-method="POST" reply-channel="zappSearchResponse"
    expected-response-type="standalone.StubResponseBody">
</int-http:outbound-gateway>

The 'postCmsChannel' is the output-channel of service activator :

   <int:service-activator id="zappServiceActivator"
input-channel="xappFilterChannelOutput"
output-channel="postCmsChannel"
ref="xappSearchService"
method="handleXappRequest"
send-timeout="60000"/>

The 'xappSearchService' is like below :

@Autowired
@Qualifier("postCmsChannel")
MessageChannel postCmsChannel;

 public void handleXappRequest(Message<CFIRequestBody> inMessage){

       /*
       * Map<String, Object> responseHeaderMap = new HashMap<String, Object>();
       *
        * //MessageHeaders headers = inMessage.getHeaders(); StubResponseBody
       * info=inMessage.getPayload();
       *
        * setReturnStatusAndMessage(responseHeaderMap); Message<StubResponseBody>
       * message = new GenericMessage<StubResponseBody>(info, responseHeaderMap);
       * return message;
       */
       inMessage.getHeaders();
       Map<String,String> headerMap=new HashMap<String,String>();
       headerMap.put("X-JWS-SIGNATURE", "dshdgshdgasshgdywtwtqsabh232wgd7wdyt");
       headerMap.put("X-PARTICIPANT-ID", "CMDRV2112BB");
      postCmsChannel.send(MessageBuilder.withPayload(inMessage.getPayload())

.copyHeadersIfAbsent(inMessage.getHeaders()).copyHeadersIfAbsent(headerMap).build());

 }

}


问:
How to check the property value after mocking a function : Assertion Error ,mocha
As per suggestion in question enter link description here I mock readFileSync and mocked my outer function now I want to verify if the variables value is set as expected or not

file.js

```<code>    const fs1 = require('fs');
    let param;
    module.export = {
         test,
         param
    }

    function test (outputParam) {
     param = fs1.readFileSync(outputParam);
    }

</code>```

I have stubbed this readFileSync and it returns specified file content as shown in the test below

When I run the test I want to see the variable param has the file content value

test.spec.js

```<code>    let expect = require('chai').expect;
    let fs = require("fs");
    let sinon = require("sinon");
    let filejs = require('./file.js');

    it('should run only the outer function and test if variable param is set to `this is my file content` ' ,function() {

     let someArg ="file.xml";

     sinon.stub(fs,'readFileSync').callsFake ((someArg) => {
        return "this is my file content";
      });

      var mock = sinon.mock(filejs);
      mock.expects('test').withArgs(someArg);
      expect(filejs.param).to.equal('this is my file content');

  })
</code>```

From file.js, As you see property param gets value from "readFileSync" which is stubbed to return a value

When I run the test

expect(filejs.param).to.equal('this is my file content');

AssertionError: expected undefined to equal 'this is my file content'

答:
Note the correct spelling of module.exports - not module.export.

In your file.js the variable param is not initialized, so it will get the value undefined and will be exported with that value, too. The exported value does not change if you modify param later. An export only binds a property to a value, not to a variable. And in fact, you don't even need a local variable. To change the value of an export dynamically, at least in Node, you simply reassign the property on module.exports.

const fs1 = require('fs');

module.exports = {
     test
}

function test (outputParam) {
    module.exports.param = fs1.readFileSync(outputParam);
}
```

<p>As for your test.spec.js, you were already very close to get it to work. After stubbing the method(s) that should not be called under the hub, just call your <code>test</code> function, passing real parameters. No mock is required there.</p>

<pre class="lang-js prettyprint-override"><code>let expect = require('chai').expect;
let fs = require("fs");
let sinon = require("sinon");
let filejs = require('./file.js');

it('should run only the outer function and test if variable param is set to `this is my file content` ' ,function() {

 let someArg ="file.xml";

 sinon.stub(fs,'readFileSync').callsFake ((someArg) => {
    return "this is my file content";
  });

  filejs.test(someArg);

  expect(filejs.param).to.equal('this is my file content');

});

</code>```

Body:
As per suggestion in question enter link description here I mock readFileSync and mocked my outer function now I want to verify if the variables value is set as expected or not

file.js

    const fs1 = require('fs');
    let param;
    module.export = {
         test,
         param
    }

    function test (outputParam) {
     param = fs1.readFileSync(outputParam);
    }

I have stubbed this readFileSync and it returns specified file content as shown in the test below

When I run the test I want to see the variable param has the file content value

test.spec.js

    let expect = require('chai').expect;
    let fs = require("fs");
    let sinon = require("sinon");
    let filejs = require('./file.js');

    it('should run only the outer function and test if variable param is set to `this is my file content` ' ,function() {

     let someArg ="file.xml";

     sinon.stub(fs,'readFileSync').callsFake ((someArg) => {
        return "this is my file content";
      });

      var mock = sinon.mock(filejs);
      mock.expects('test').withArgs(someArg);
      expect(filejs.param).to.equal('this is my file content');

  })

From file.js, As you see property param gets value from "readFileSync" which is stubbed to return a value

When I run the test

expect(filejs.param).to.equal('this is my file content');

AssertionError: expected undefined to equal 'this is my file content'

Body:
Note the correct spelling of module.exports - not module.export.

In your file.js the variable param is not initialized, so it will get the value undefined and will be exported with that value, too. The exported value does not change if you modify param later. An export only binds a property to a value, not to a variable. And in fact, you don't even need a local variable. To change the value of an export dynamically, at least in Node, you simply reassign the property on module.exports.

const fs1 = require('fs');

module.exports = {
     test
}

function test (outputParam) {
    module.exports.param = fs1.readFileSync(outputParam);
}

As for your test.spec.js, you were already very close to get it to work. After stubbing the method(s) that should not be called under the hub, just call your test function, passing real parameters. No mock is required there.

let expect = require('chai').expect;
let fs = require("fs");
let sinon = require("sinon");
let filejs = require('./file.js');

it('should run only the outer function and test if variable param is set to `this is my file content` ' ,function() {

 let someArg ="file.xml";

 sinon.stub(fs,'readFileSync').callsFake ((someArg) => {
    return "this is my file content";
  });

  filejs.test(someArg);

  expect(filejs.param).to.equal('this is my file content');

});


问:
Making custom sliding menu and different from Navigation Drawer
Probably you have seen the side Navigation drawer of apps like Gmail. But how do you make such a drawer with custom widgets for example I present a navigation drawer that has some widgets placed randomly inside:

I'd like to use the constraintLayout inside the navigation view. Basically, I'd like it to be a normal layout/view that occupies a certain percentage of screen and has slide in and slide out animation.

Edit

If you don't add app:menu=@menu/menu_nav then it basically crashes and if you add a blank menu then you can't put just the constraintLayout inside of the navigation menu, you have to have the constraintLayout inside a FrameLayout and.... finally it doesn't work properly, say you use a match constraint in an imageView then the image doesn't display, although hardcoded strings are being ok for now, but that isn't really solving the problem of views being dynamic.

答:
In order to use a custom layout for the NavigationDrawer, you can wrap your custom layout within the NavigationView, so that your layout structure will look like the below:

```<code><?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout 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/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <!--  MainActivity Layout -->
    <include
        layout="@layout/activity_main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!--    NavigationView -->
    <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start">

        <!--   Custom NavigationView Layout-->

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

With that in place, you can freely customize your NavigationView layout as you want, like putting ConstraintLayout or any layout as you like. And you can also add buttons' listeners like you can do with a normal layout.

Here is a demo that you can start from, the credits of the VerticalButton back to this tutorial

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout 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/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ADADAD"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <!--  Main Layout -->
    <include
        layout="@layout/activity_main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!--    NavigationView Layout-->
    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#666666">

            <!--  Header Layout -->
            <include
                android:id="@+id/include"
                layout="@layout/nav_header_main" />

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:background="#ffff00"
                android:onClick="onNavigationButtonClick"
                android:text="Button1"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/include" />

            <com.example.android.customnavigationdrawerconstraintlayout.VerticalButton
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="24dp"
                android:layout_marginLeft="24dp"
                android:layout_marginTop="24dp"
                android:background="#ffff00"
                android:onClick="onNavigationButtonClick"
                android:text="Button2"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button1" />

            <com.example.android.customnavigationdrawerconstraintlayout.VerticalButton
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="24dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:background="#ffff00"
                android:onClick="onNavigationButtonClick"
                android:text="button3"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button1" />

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="64dp"
                android:layout_marginLeft="64dp"
                android:layout_marginTop="32dp"
                android:layout_marginEnd="64dp"
                android:layout_marginRight="64dp"
                android:layout_marginBottom="16dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button2"
                android:src="@drawable/ic_android" />

        </androidx.constraintlayout.widget.ConstraintLayout>

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

activity_main_content.xml (MainActivity layout)

```<code><?xml version="1.0" encoding="utf-8"?>

<androidx.coordinatorlayout.widget.CoordinatorLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar_main"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

        </androidx.appcompat.widget.Toolbar>

    </com.google.android.material.appbar.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">

        <TextView
            android:id="@+id/tv_main"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="22sp" />

    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

nav_header_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:background="@color/colorAccent"
    android:gravity="bottom"
    android:orientation="vertical"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:paddingTop="8dp"
        app:srcCompat="@drawable/ic_launcher_foreground" />

</LinearLayout>
</code>```

VerticalButton

```<code>public class VerticalButton extends Button {
    final boolean topDown;

    public VerticalButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        final int gravity = getGravity();
        if (Gravity.isVertical(gravity) && (gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
            setGravity((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
            topDown = true;
        } else
            topDown = false;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        TextPaint textPaint = getPaint();
        textPaint.setColor(getCurrentTextColor());
        textPaint.drawableState = getDrawableState();

        canvas.save();

        if (topDown) {
            canvas.translate(getWidth(), 0);
            canvas.rotate(90);
        } else {
            canvas.translate(0, getHeight());
            canvas.rotate(-90);
        }

        canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
        getLayout().draw(canvas);
        canvas.restore();
    }
}
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    DrawerLayout mDrawerLayout;
    NavigationView navView;
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDrawerLayout = findViewById(R.id.drawer);
        navView = findViewById(R.id.navView);
        toolbar = findViewById(R.id.toolbar_main);

        setupDrawer();

    }

    private void setupDrawer() {
        // Show the burger button on the ActionBar
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
                mDrawerLayout, toolbar,
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close);

        mDrawerLayout.addDrawerListener(toggle);
        toggle.syncState();
    }

    public void onNavigationButtonClick(View view) {

        TextView tvMain = findViewById(R.id.tv_main);
        tvMain.setText(((Button) view).getText().toString());
        mDrawerLayout.closeDrawer(navView);

        switch (view.getId()) {
            case R.id.button1:
                // Do something with button 1
                break;

            case R.id.button2:
                // Do something with button 2
                break;

            case R.id.button3:
                // Do something with button 3
                break;

        }
    }
}
</code>```

strings.xml

```<code><resources>
    <string name="app_name">Custom NavigationView</string>
    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
</resources>
</code>```

Material design dependency

```<code>implementation 'com.google.android.material:material:1.0.0'
</code>```

Preview

Body:
In order to use a custom layout for the NavigationDrawer, you can wrap your custom layout within the NavigationView, so that your layout structure will look like the below:

<?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout 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/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <!--  MainActivity Layout -->
    <include
        layout="@layout/activity_main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!--    NavigationView -->
    <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start">

        <!--   Custom NavigationView Layout-->

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

With that in place, you can freely customize your NavigationView layout as you want, like putting ConstraintLayout or any layout as you like. And you can also add buttons' listeners like you can do with a normal layout.

Here is a demo that you can start from, the credits of the VerticalButton back to this tutorial

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout 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/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ADADAD"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <!--  Main Layout -->
    <include
        layout="@layout/activity_main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!--    NavigationView Layout-->
    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#666666">

            <!--  Header Layout -->
            <include
                android:id="@+id/include"
                layout="@layout/nav_header_main" />

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:background="#ffff00"
                android:onClick="onNavigationButtonClick"
                android:text="Button1"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/include" />

            <com.example.android.customnavigationdrawerconstraintlayout.VerticalButton
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="24dp"
                android:layout_marginLeft="24dp"
                android:layout_marginTop="24dp"
                android:background="#ffff00"
                android:onClick="onNavigationButtonClick"
                android:text="Button2"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button1" />

            <com.example.android.customnavigationdrawerconstraintlayout.VerticalButton
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="24dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:background="#ffff00"
                android:onClick="onNavigationButtonClick"
                android:text="button3"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button1" />

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="64dp"
                android:layout_marginLeft="64dp"
                android:layout_marginTop="32dp"
                android:layout_marginEnd="64dp"
                android:layout_marginRight="64dp"
                android:layout_marginBottom="16dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/button2"
                android:src="@drawable/ic_android" />

        </androidx.constraintlayout.widget.ConstraintLayout>

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

activity_main_content.xml (MainActivity layout)

<?xml version="1.0" encoding="utf-8"?>

<androidx.coordinatorlayout.widget.CoordinatorLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar_main"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

        </androidx.appcompat.widget.Toolbar>

    </com.google.android.material.appbar.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">

        <TextView
            android:id="@+id/tv_main"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="22sp" />

    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

nav_header_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:background="@color/colorAccent"
    android:gravity="bottom"
    android:orientation="vertical"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:paddingTop="8dp"
        app:srcCompat="@drawable/ic_launcher_foreground" />

</LinearLayout>

VerticalButton

public class VerticalButton extends Button {
    final boolean topDown;

    public VerticalButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        final int gravity = getGravity();
        if (Gravity.isVertical(gravity) && (gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
            setGravity((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
            topDown = true;
        } else
            topDown = false;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        TextPaint textPaint = getPaint();
        textPaint.setColor(getCurrentTextColor());
        textPaint.drawableState = getDrawableState();

        canvas.save();

        if (topDown) {
            canvas.translate(getWidth(), 0);
            canvas.rotate(90);
        } else {
            canvas.translate(0, getHeight());
            canvas.rotate(-90);
        }

        canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
        getLayout().draw(canvas);
        canvas.restore();
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    DrawerLayout mDrawerLayout;
    NavigationView navView;
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDrawerLayout = findViewById(R.id.drawer);
        navView = findViewById(R.id.navView);
        toolbar = findViewById(R.id.toolbar_main);

        setupDrawer();

    }

    private void setupDrawer() {
        // Show the burger button on the ActionBar
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
                mDrawerLayout, toolbar,
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close);

        mDrawerLayout.addDrawerListener(toggle);
        toggle.syncState();
    }

    public void onNavigationButtonClick(View view) {

        TextView tvMain = findViewById(R.id.tv_main);
        tvMain.setText(((Button) view).getText().toString());
        mDrawerLayout.closeDrawer(navView);

        switch (view.getId()) {
            case R.id.button1:
                // Do something with button 1
                break;

            case R.id.button2:
                // Do something with button 2
                break;

            case R.id.button3:
                // Do something with button 3
                break;

        }
    }
}

strings.xml

<resources>
    <string name="app_name">Custom NavigationView</string>
    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
</resources>

Material design dependency

implementation 'com.google.android.material:material:1.0.0'

Preview


问:
TextView on recyclerview item is not showing on the right place
I am working on a recyclerview view that looks as follows in Android Studio:

As you may see, there are two textViews, one with "Sample" text as one with "TextView" text.

I need to put the second textView just below the first textView, like it is in the image.

The eight circled ImageViews may appear or not, depending on the item values.

The issue is that the item on a real device looks different depending on the item values, if there are not ImageViews (the small grey circles) everything looks as I want,like this

but in case of existing circled ImageViews on the item, the second textView appears much lower, below the second circled ImageViews row, like this:

This is my code for the view:

```<code><RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/profile_image"
            android:layout_width="65dp"
            android:layout_height="65dp"

            android:layout_marginLeft="5dp"
            android:layout_marginTop="5dp"
            android:background="@color/colorWhite"
            android:src="@drawable/ic_account_circle_black_24dp"
            card_view:civ_border_color="#FF000000"
            card_view:civ_border_width="2dp" />

        <TextView
            android:id="@+id/txtUsername"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_toRightOf="@id/profile_image"
            android:text="Sample"
            android:textColor="@color/grey_700"
            android:textSize="20dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/txtDate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/txtUsername"
            android:layout_alignStart="@id/txtUsername"
            android:layout_toRightOf="@id/profile_image"
            android:text="TextView"
            android:textSize="10sp" />

        <LinearLayout
            android:id="@+id/layout_deportes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/txtUsername"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@id/tres"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp1"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp2"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp3"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp4"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout_deportes2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/layout_deportes"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@id/tres"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp5"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp6"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_below="@+id/layout_deportes"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp7"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp8"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

        </LinearLayout>
</code>```

I guess something must be wrong on it, but I am not able to find out the reason for the issue.

答:
Check this

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/profile_image"
        android:layout_width="65dp"
        android:layout_height="65dp"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:background="@color/white_font"
        android:src="@drawable/img_card"
        card_view:civ_border_color="#FF000000"
        card_view:civ_border_width="2dp" />

    <TextView
        android:id="@+id/txtUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="3dp"
        android:layout_marginBottom="3dp"
        android:layout_toStartOf="@+id/rlImages"
        android:layout_toEndOf="@id/profile_image"
        android:text="Sample"
        android:textColor="@color/dark_font"
        android:textSize="20dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txtDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtUsername"
        android:layout_alignStart="@id/txtUsername"
        android:layout_toStartOf="@+id/rlImages"
        android:layout_toEndOf="@id/profile_image"
        android:text="TextView"
        android:textSize="10sp" />

    <RelativeLayout
        android:id="@+id/rlImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/txtUsername"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="20dp">

        <LinearLayout
            android:id="@+id/layout_deportes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp1"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp2"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp3"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp4"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout_deportes2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/layout_deportes"
            android:layout_marginTop="3dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp5"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp6"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_below="@+id/layout_deportes"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp7"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp8"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>
</code>```

Body:
I am working on a recyclerview view that looks as follows in Android Studio:

As you may see, there are two textViews, one with "Sample" text as one with "TextView" text.

I need to put the second textView just below the first textView, like it is in the image.

The eight circled ImageViews may appear or not, depending on the item values.

The issue is that the item on a real device looks different depending on the item values, if there are not ImageViews (the small grey circles) everything looks as I want,like this

but in case of existing circled ImageViews on the item, the second textView appears much lower, below the second circled ImageViews row, like this:

This is my code for the view:

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/profile_image"
            android:layout_width="65dp"
            android:layout_height="65dp"

            android:layout_marginLeft="5dp"
            android:layout_marginTop="5dp"
            android:background="@color/colorWhite"
            android:src="@drawable/ic_account_circle_black_24dp"
            card_view:civ_border_color="#FF000000"
            card_view:civ_border_width="2dp" />

        <TextView
            android:id="@+id/txtUsername"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_toRightOf="@id/profile_image"
            android:text="Sample"
            android:textColor="@color/grey_700"
            android:textSize="20dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/txtDate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/txtUsername"
            android:layout_alignStart="@id/txtUsername"
            android:layout_toRightOf="@id/profile_image"
            android:text="TextView"
            android:textSize="10sp" />

        <LinearLayout
            android:id="@+id/layout_deportes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/txtUsername"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@id/tres"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp1"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp2"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp3"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp4"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout_deportes2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/layout_deportes"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@id/tres"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp5"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp6"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_below="@+id/layout_deportes"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp7"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

            <ImageView
                android:id="@+id/sp8"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle"
                android:visibility="visible"
                card_view:srcCompat="@drawable/skate" />

        </LinearLayout>

I guess something must be wrong on it, but I am not able to find out the reason for the issue.

Body:
Check this

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/profile_image"
        android:layout_width="65dp"
        android:layout_height="65dp"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:background="@color/white_font"
        android:src="@drawable/img_card"
        card_view:civ_border_color="#FF000000"
        card_view:civ_border_width="2dp" />

    <TextView
        android:id="@+id/txtUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="3dp"
        android:layout_marginBottom="3dp"
        android:layout_toStartOf="@+id/rlImages"
        android:layout_toEndOf="@id/profile_image"
        android:text="Sample"
        android:textColor="@color/dark_font"
        android:textSize="20dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txtDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtUsername"
        android:layout_alignStart="@id/txtUsername"
        android:layout_toStartOf="@+id/rlImages"
        android:layout_toEndOf="@id/profile_image"
        android:text="TextView"
        android:textSize="10sp" />

    <RelativeLayout
        android:id="@+id/rlImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/txtUsername"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="20dp">

        <LinearLayout
            android:id="@+id/layout_deportes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp1"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp2"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp3"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp4"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout_deportes2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/layout_deportes"
            android:layout_marginTop="3dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/sp5"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp6"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_below="@+id/layout_deportes"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp7"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

            <ImageView
                android:id="@+id/sp8"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginRight="5dp"
                android:layout_weight="1"
                android:background="@drawable/circle_gradient"
                android:visibility="visible"
                card_view:srcCompat="@drawable/img_card" />

        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>