问:
issues with angular to call api input via parameters
I am trying to fetch data from the API server using angular 9 bypassing id in the input from to get the phone value from JSON in the API. in this mount that not working with me :(, I don't know what the problem even I use the same format in JSON API.
like this one

this.phone = this.results.address.phone
  Please, I need someone to guide me for the right answer.

thank you :)

I live a simple of my work down!

This is my app.component.ts

```<code>import { Component } from '@angular/core';
import { HttpClient } from  '@angular/common/http';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  constructor(private _http: HttpClient){}
url='https://jsonplaceholder.typicode.com/users/1';
id='';
phone='';
results : any;
getsearcha(){
  this._http.get('https://jsonplaceholder.typicode.com/users/'+this.id)
  .subscribe(

    data => {
      this.results = data['results'];
      this.phone = this.results.address.phone
     console.log(this._http.get(this.url));
    })
}
}
</code>```

as well the is my app.component.html

```<code><h1> test app</h1>
<input type="text" [(ngModel)]=id>

<button (click)="getsearcha()">Click</button>
<hr>
phone{{phone}}
</code>```

https://stackblitz.com/edit/angular-dryp3b

答:
Your API return only data.data['result'] is incorrect.</p>

```<code> { "id": 2,"name": "Ervin Howell","username": "Antonette","email":"Shanna@melissa.tv","address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
  "lat": "-43.9509",
  "lng": "-34.4618"
}},"phone": "010-692-6593 x09125","website": "anastasia.net","company": {"name": "Deckow-Crist","catchPhrase": "Proactive didactic contingency","bs": "synergize scalable supply-chains"}}
</code>```

Body:
I am trying to fetch data from the API server using angular 9 bypassing id in the input from to get the phone value from JSON in the API. in this mount that not working with me :(, I don't know what the problem even I use the same format in JSON API.
like this one

this.phone = this.results.address.phone
  Please, I need someone to guide me for the right answer.

thank you :)

I live a simple of my work down!

This is my app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from  '@angular/common/http';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  constructor(private _http: HttpClient){}
url='https://jsonplaceholder.typicode.com/users/1';
id='';
phone='';
results : any;
getsearcha(){
  this._http.get('https://jsonplaceholder.typicode.com/users/'+this.id)
  .subscribe(

    data => {
      this.results = data['results'];
      this.phone = this.results.address.phone
     console.log(this._http.get(this.url));
    })
}
}

as well the is my app.component.html

 test app

<input type="text" [(ngModel)]=id>

<button (click)="getsearcha()">Click</button>

phone{{phone}}

https://stackblitz.com/edit/angular-dryp3b

Body:
Your API return only data.data['result'] is incorrect.

 { "id": 2,"name": "Ervin Howell","username": "Antonette","email":"Shanna@melissa.tv","address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
  "lat": "-43.9509",
  "lng": "-34.4618"
}},"phone": "010-692-6593 x09125","website": "anastasia.net","company": {"name": "Deckow-Crist","catchPhrase": "Proactive didactic contingency","bs": "synergize scalable supply-chains"}}


来源: stackexchange

问:
How to place a a Shaded Line After DIV Tag in a HTML Page
Please see my image here:

http://www.tiikoni.com/tis/view/?id=10ca264

After placing the chart, my code starts like this as shown below

```<code><label style="font-weight: bold;">Select Period</label>
</code>```

My question is, as you can see from the image, after placing the chart, there is a line inserted.

Please tell me how to keep this line.

答:
```<code><hr />
</code>```

http://www.w3schools.com/tags/tag_hr.asp

ContentLicense: CC BY-SA 3.0

Body:
Please see my image here:

http://www.tiikoni.com/tis/view/?id=10ca264

After placing the chart, my code starts like this as shown below

Select Period

My question is, as you can see from the image, after placing the chart, there is a line inserted.

Please tell me how to keep this line.

Body:
<hr />

http://www.w3schools.com/tags/tag_hr.asp


问:
Error while using python file generated from SWIG (generated from C++)
I have a .cpp (called trial.cpp) file as follows:

```<code>   #include "trial.hpp"
   int main()
   {
        cout << "hello";
       return 0;
   }
</code>```

My header file (trial.hpp) is:

```<code>#include <iostream>
using namespace std;
</code>```

I have a .i file (trial.i) as follows:

```<code>%module trial
%{
#include "trial.hpp"
%}

%include trial.hpp
</code>```

I have used SWIG in the following manner in cmd to generate .pyd, .py, .o and .cxx files:

swig -c++ -python trial.i

g++ -c trial_wrap.cxx -I C:\Users.....Python\Python37\include

g++ -shared trial_wrap.o -o _trial.pyd -L
  C:\Users.....\Python\Python37\libs -l
  python37

The files are generated successfully

However when I open Python command prompt and run this:

from trial import *

main()

I get an error saying

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'main' is not defined

How can I resolve this issue?

Moreover, if I'm using another function name (say fn1()) instead of main(), I get the following error in the third command:

g++ -shared trial_wrap.o -o _trial.pyd -L
  C:\Users.....\Python\Python37\libs -l python37

The error is:

undefined reference to fn1()

I'd like to use fn1() instead of main()

How can I solve this issue?

答:
Fixed it!

Used these three statements instead:

swig -c++ -python trial.i

g++ -c trial_wrap.cxx trial.cpp -I C:\Users\ngoyal\AppData\Local\Programs\Python\Python37\include

g++ -shared -o _trial.pyd trial.o trial_wrap.o -L C:\Users\ngoyal\AppData\Local\Programs\Python\Python37\libs -l python37

Also had to change main() to a non reserved function name and gave the function definition in the header file.

ContentLicense: CC BY-SA 4.0

Body:
I have a .cpp (called trial.cpp) file as follows:

   #include "trial.hpp"
   int main()
   {
        cout << "hello";
       return 0;
   }

My header file (trial.hpp) is:

#include <iostream>
using namespace std;

I have a .i file (trial.i) as follows:

%module trial
%{
#include "trial.hpp"
%}

%include trial.hpp

I have used SWIG in the following manner in cmd to generate .pyd, .py, .o and .cxx files:

swig -c++ -python trial.i

g++ -c trial_wrap.cxx -I C:\Users.....Python\Python37\include

g++ -shared trial_wrap.o -o _trial.pyd -L
  C:\Users.....\Python\Python37\libs -l
  python37

The files are generated successfully

However when I open Python command prompt and run this:

from trial import *

main()

I get an error saying

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'main' is not defined

How can I resolve this issue?

Moreover, if I'm using another function name (say fn1()) instead of main(), I get the following error in the third command:

g++ -shared trial_wrap.o -o _trial.pyd -L
  C:\Users.....\Python\Python37\libs -l python37

The error is:

undefined reference to fn1()

I'd like to use fn1() instead of main()

How can I solve this issue?


问:
MSSQL Nodejs module throws invalid time in execution of a stored procedure
I've setup a nodejs server which provides an api to my mssql server.
I'm trying to execute a stored procedure of my mssql database in nodejs which inserts some data into one of my tables. I've got an input with the type 'sql.Time' which has the value '11:20:13'. Even tho the sql.Time Type requires sth like 'hh:mm:ss' which is the case, the mssql module in nodejs throws an error saying:

```<code>error: RequestError: Validation failed for parameter 'erreichbar_von'. Invalid time.
</code>```

This is the testdata: http://hastebin.com/xucomefizo.pl

This is the log: http://hastebin.com/mubezuweca.sm

I hope somebody can help me out with this problem since I'm out of ideas.

With best regards,
Tak3r07

答: I came across this error while working on a rest api for my sql server. I ended up having to pass the time as an ISO string instead of as "12:00". In javascript I used (new Date()).toISOString(); to produce "2020-02-18T04:32:23.019Z"

Body:
I've setup a nodejs server which provides an api to my mssql server.
I'm trying to execute a stored procedure of my mssql database in nodejs which inserts some data into one of my tables. I've got an input with the type 'sql.Time' which has the value '11:20:13'. Even tho the sql.Time Type requires sth like 'hh:mm:ss' which is the case, the mssql module in nodejs throws an error saying:

error: RequestError: Validation failed for parameter 'erreichbar_von'. Invalid time.

This is the testdata: http://hastebin.com/xucomefizo.pl

This is the log: http://hastebin.com/mubezuweca.sm

I hope somebody can help me out with this problem since I'm out of ideas.

With best regards,
Tak3r07


问:
How can I set width to th of table, and td below will inherit width?
I want to set width to my th and want to td's below to inherit width from th, I tried to set width to th but it does not work.</p>

答:
remove min-width from table and add width:100%. Set width for th, it will work

    div {
      border: 1px solid rgba(0,0,0,.12);
      border-radius: 4px;

      -webkit-overflow-scrolling: touch;
      display: inline-flex;
      flex-direction: column;
      box-sizing: border-box;
      overflow-x: auto;
    }
    table {
      font-family: Roboto, sans-serif;
      /* min-width: 100%; */
      border-collapse: collapse;

      width: 100%;
      white-space: nowrap;
      border-collapse: collapse;
      table-layout: fixed;
    }
    thead tr {
      border: 0;
    }
    tr {
      border-top: 1px solid rgba(0,0,0,.12);
    }
    th {
      font-weight: 500;
      height: 56px;
      line-height: 1.375rem;
      letter-spacing: .0071428571em;
      width: 8rem
    }
    td {
      font-weight: 400;
      height: 52px;
      line-height: 1.25rem;
      letter-spacing: .0178571429em;
    }
    td, th {
      padding: 0px 16px;
      text-align: left;
      font-size: .875rem;
      text-overflow: ellipsis;
      overflow: hidden;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <table>
    <thead>
      <tr>
        <th>ФИО</th>
        <th>Статус по Т.Д.</th>
        <th>Статус работника</th>
        <th>Должность</th>
        <th style="
">Подразделение</th>
        <th>Вид занятости</th>
        <th>Ставка</th>
        <th>Трудовой договор</th>
        <th>Приказ</th>
        <th>Основание</th>
        <th>Период работы</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td rowspan="3">Иванов Иван Иванович<arrow-button-component></arrow-button-component>
        </td>
        <td>Действующий</td>
        <td>На работе</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
      <tr>
        <td>Действующий</td>
        <td>На работе</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
      <tr>
        <td>Расторгнут</td>
        <td>Уволен/а</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
      <tr>
        <td rowspan="1">Анна Иванович<arrow-button-component></arrow-button-component>
        </td>
        <td>Действующий</td>
        <td>Уволен/а</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
      <tr>
        <td rowspan="2">Алишер Казболдинов<arrow-button-component></arrow-button-component>
        </td>
        <td>Действующий</td>
        <td>На работе</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
      <tr>
        <td>Расторгнут</td>
        <td>Уволен/а</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
    </tbody>
  </table>

</div></code>```

Body:
remove min-width from table and add width:100%. Set width for th, it will work

    div {
      border: 1px solid rgba(0,0,0,.12);
      border-radius: 4px;

      -webkit-overflow-scrolling: touch;
      display: inline-flex;
      flex-direction: column;
      box-sizing: border-box;
      overflow-x: auto;
    }
    table {
      font-family: Roboto, sans-serif;
      /* min-width: 100%; */
      border-collapse: collapse;

      width: 100%;
      white-space: nowrap;
      border-collapse: collapse;
      table-layout: fixed;
    }
    thead tr {
      border: 0;
    }
    tr {
      border-top: 1px solid rgba(0,0,0,.12);
    }
    th {
      font-weight: 500;
      height: 56px;
      line-height: 1.375rem;
      letter-spacing: .0071428571em;
      width: 8rem
    }
    td {
      font-weight: 400;
      height: 52px;
      line-height: 1.25rem;
      letter-spacing: .0178571429em;
    }
    td, th {
      padding: 0px 16px;
      text-align: left;
      font-size: .875rem;
      text-overflow: ellipsis;
      overflow: hidden;
    }

<div>
  <table>
    <thead>
      <tr>
        <th>ФИО</th>
        <th>Статус по Т.Д.</th>
        <th>Статус работника</th>
        <th>Должность</th>
        <th style="
">Подразделение</th>
        <th>Вид занятости</th>
        <th>Ставка</th>
        <th>Трудовой договор</th>
        <th>Приказ</th>
        <th>Основание</th>
        <th>Период работы</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td rowspan="3">Иванов Иван Иванович<arrow-button-component></arrow-button-component>
        </td>
        <td>Действующий</td>
        <td>На работе</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
      <tr>
        <td>Действующий</td>
        <td>На работе</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
      <tr>
        <td>Расторгнут</td>
        <td>Уволен/а</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
      <tr>
        <td rowspan="1">Анна Иванович<arrow-button-component></arrow-button-component>
        </td>
        <td>Действующий</td>
        <td>Уволен/а</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
      <tr>
        <td rowspan="2">Алишер Казболдинов<arrow-button-component></arrow-button-component>
        </td>
        <td>Действующий</td>
        <td>На работе</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
      <tr>
        <td>Расторгнут</td>
        <td>Уволен/а</td>
        <td>руководитель отдела разработки</td>
        <td>Департмент информационых технологии</td>
        <td>Основое</td>
        <td>1</td>
        <td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since</td>
        <td>Приказ о расторжении дополнительного соглашения</td>
        <td>Заявление. Статьи 34 и 36 Трудового кодекса Республики Казахстан</td>
        <td>с 15.11.2019 по 23.06.2020</td>
      </tr>
    </tbody>
  </table>

</div>


问:
Retrofit2 with Kotlin
I want to consume an API with this result:

```<code>{"result":true,"status":"success"}
</code>```

It seems the problem is in Kotlin. Here's my code:

```<code>class MainActivity : AppCompatActivity() {
private var response:Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    getRetrofit()

    btnLogin.setOnClickListener {

        getResponse()
        Toast.makeText(this,response.toString(),Toast.LENGTH_LONG).show()
    }
}

private fun getRetrofit(): Retrofit {
    return Retrofit.Builder()
        .baseUrl("http://192.168.43.243:2001/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

private fun getResponse() {
    doAsync {
        val call = getRetrofit().create(APIService::class.java).getResponse().execute()
        val res = call.body() as APIResponse
        uiThread {
            if(res.status == "success") {
                response = res.response

            }else{
                //showErrorDialog()
            }
        }
    }
}
</code>```

My variable 'response' always returns 'false' and I want to consume the API value. so 'response' should have a 'true' value.
Do you have any suggestion?

Thank you so much!

答:
```<code>// Sample Retrofit 2 Connection Android Using Kotlin

// API Connect On Activity / Fragment

        val apiService = ApiMockyClient.clientMocky!!.create(ApiInterface::class.java)

                val call: Call<TimeResponse> = apiService.setTime()

                call.enqueue(object : Callback<TimeResponse> {
                    @SuppressLint("SetTextI18n")
                    override fun onResponse(
                        call: Call<TimeResponse>,
                        response: Response<TimeResponse>
                    ) = when {
                        response.isSuccessful -> {
                            val status = (response.body() as TimeResponse).status
                            val message = (response.body() as TimeResponse).message

                            val resultData = response.body()
                            val valGSON = Gson()
                            val valuesStrings = valGSON.toJson(resultData)

                            Constant.logD(mTAG, "Fetch Time Response JSON Format : ", valuesStrings)

                            when (status) {
                                "Success" -> {

                                    val m24hours = response.body()!!.get24Hours()

                                    val m12hours = response.body()!!.get12Hours()

                                    Constant.logD(mTAG, "Fetch Employee Response Success : ", "" + message)
                                }
                                else -> {
                                    Constant.logE(mTAG, "Fetch Employee Response Failure : ", "" + message)
                                }
                            }
                        }
                        else -> {
                            Constant.logE(mTAG, "Fetch Time Response : ", "Else Condition !")
                        }
                    }

                    override fun onFailure(call: Call<TimeResponse>, t: Throwable) {
                        Constant.logE(mTAG, "Fetch Time Response Failure : ", t.message.toString())
                    }

                })

            // Pojo

            class TimeResponse(
            @SerializedName("status")
            @Expose var status: String,
            @SerializedName("message")
            @Expose var message: String,
            @SerializedName("24_hours")
            @Expose
            private var _24Hours: List<_24Hour>,
            @SerializedName("12_hours")
            @Expose
            private var _12Hours: List<_12Hour>
        ) {

            fun get24Hours(): List<_24Hour> {
                return _24Hours
            }

            fun set24Hours(_24Hours: List<_24Hour>) {
                this._24Hours = _24Hours
            }

            fun get12Hours(): List<_12Hour> {
                return _12Hours
            }

            fun set12Hours(_12Hours: List<_12Hour>) {
                this._12Hours = _12Hours
            }

            override fun equals(other: Any?): Boolean {
                if (this === other) return true
                if (javaClass != other?.javaClass) return false

                other as TimeResponse

                if (status != other.status) return false
                if (message != other.message) return false
                if (_24Hours != other._24Hours) return false
                if (_12Hours != other._12Hours) return false

                return true
            }

            override fun hashCode(): Int {
                var result = status.hashCode()
                result = 31 * result + message.hashCode()
                result = 31 * result + _24Hours.hashCode()
                result = 31 * result + _12Hours.hashCode()
                return result
            }

            override fun toString(): String {
                return "TimeResponse(status=$status, message=$message, _24Hours=$_24Hours, _12Hours=$_12Hours)"
            }

        }

        // API Client

        object ApiMockyClient {
            private var mBaseURLMocky: String = "https://www.mocky.io/v2/"

            private var retrofitMocky: Retrofit? = null

            val clientMocky: Retrofit?
                get() {
                    if (retrofitMocky == null) {
                        retrofitMocky =
                            Retrofit.Builder()
                                .baseUrl(mBaseURLMocky)
                                .addConverterFactory(GsonConverterFactory.create())
                                .build()
                    }
                    return retrofitMocky
                }

            init {
                retrofitMocky = null
            }
        }

        // API Interface
        interface ApiInterface {

        @GET("5e291efd3000005f00faed17")  // Get Or Post For Example Im Giving
        fun setTime(): Call<TimeResponse>

        }
</code>```

Title: Retrofit2 with Kotlin

Body:
I want to consume an API with this result:

{"result":true,"status":"success"}

It seems the problem is in Kotlin. Here's my code:

class MainActivity : AppCompatActivity() {
private var response:Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    getRetrofit()

    btnLogin.setOnClickListener {

        getResponse()
        Toast.makeText(this,response.toString(),Toast.LENGTH_LONG).show()
    }
}

private fun getRetrofit(): Retrofit {
    return Retrofit.Builder()
        .baseUrl("http://192.168.43.243:2001/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

private fun getResponse() {
    doAsync {
        val call = getRetrofit().create(APIService::class.java).getResponse().execute()
        val res = call.body() as APIResponse
        uiThread {
            if(res.status == "success") {
                response = res.response

            }else{
                //showErrorDialog()
            }
        }
    }
}

My variable 'response' always returns 'false' and I want to consume the API value. so 'response' should have a 'true' value.
Do you have any suggestion?

Thank you so much!


问:
I'm having a problem with reading a string in an if statement
I'm a beginner in C++ coding and I have a problem with an assignment question:

Write a C++ program that prompts the user to enter two characters and displays the major and status represented in the characters. The first character indicates the major and the second is number character 1, 2, 3, 4, which indicates whether a student is a freshman, sophomore, junior, or senior.
  Suppose the following characters are used to denote the majors:

  M: Mathematics

  C: Computer Science

  I: Information Technology

This is what I tried so far:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string i;
    cout <<"Enter two characters: ";
    cin>> i;
    i[0]=toupper(i[0]);
    if (i[0]=='M')
    {
        if (i[1]==1)
        {
            cout<<"Mathematics Freshman."<<endl;
        }
        else if (i[1]==2)
        {
            cout<<"Mathematics Sophomore."<<endl;
        }
        else if (i[1]==3)
        {
            cout<<"Mathematics Junior."<<endl;
        }
        else if (i[1]==4)
        {
            cout<<"Mathematics Senior."<<endl;
        }
        else
        {
            cout<<"Invalid status code."<<endl;
        }
    }
    return 0;
}
```

When I run and type for example "m1" it should print "Mathematics Freshman.", but it prints "invalid status code", which is the output from the else statement, and I don't know why.

答:
You should compare a character to character instead of the integer. Try this </p>

```<code>#include <iostream>
#include <string>
using namespace std;
int main()
{
    string i;
    cout <<"Enter two characters: ";
    cin>> i;
    i[0]=toupper(i[0]);
    if (i[0]=='M')
    {
        if (i[1]=='1')
        {
            cout<<"Mathematics Freshman."<<endl;
        }
        else if (i[1]=='2')
        {
            cout<<"Mathematics Sophomore."<<endl;
        }
        else if (i[1]=='3')
        {
            cout<<"Mathematics Junior."<<endl;
        }
        else if (i[1]=='4')
        {
            cout<<"Mathematics Senior."<<endl;
        }
        else
        {
            cout<<"Invalid status code."<<endl;
        }
    }
     return 0;
}
</code>```

Body:
I'm a beginner in C++ coding and I have a problem with an assignment question:

Write a C++ program that prompts the user to enter two characters and displays the major and status represented in the characters. The first character indicates the major and the second is number character 1, 2, 3, 4, which indicates whether a student is a freshman, sophomore, junior, or senior.
  Suppose the following characters are used to denote the majors:

  M: Mathematics

  C: Computer Science

  I: Information Technology

This is what I tried so far:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string i;
    cout <<"Enter two characters: ";
    cin>> i;
    i[0]=toupper(i[0]);
    if (i[0]=='M')
    {
        if (i[1]==1)
        {
            cout<<"Mathematics Freshman."<<endl;
        }
        else if (i[1]==2)
        {
            cout<<"Mathematics Sophomore."<<endl;
        }
        else if (i[1]==3)
        {
            cout<<"Mathematics Junior."<<endl;
        }
        else if (i[1]==4)
        {
            cout<<"Mathematics Senior."<<endl;
        }
        else
        {
            cout<<"Invalid status code."<<endl;
        }
    }
    return 0;
}

When I run and type for example "m1" it should print "Mathematics Freshman.", but it prints "invalid status code", which is the output from the else statement, and I don't know why.

Body:
You should compare a character to character instead of the integer. Try this

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string i;
    cout <<"Enter two characters: ";
    cin>> i;
    i[0]=toupper(i[0]);
    if (i[0]=='M')
    {
        if (i[1]=='1')
        {
            cout<<"Mathematics Freshman."<<endl;
        }
        else if (i[1]=='2')
        {
            cout<<"Mathematics Sophomore."<<endl;
        }
        else if (i[1]=='3')
        {
            cout<<"Mathematics Junior."<<endl;
        }
        else if (i[1]=='4')
        {
            cout<<"Mathematics Senior."<<endl;
        }
        else
        {
            cout<<"Invalid status code."<<endl;
        }
    }
     return 0;
}


问:
Instagram browser (form iOs) doesn't display all the elements on my ste
My site works perfectly across devices/browsers.

Except from the native Instagram browser. When you click the link from the bio (from an iphone - not sure about Android), it opens the site and finishes loading, except for all the images. If you navigate further into product pages, the product image gallery is also missing.

I have cleared the cache of the phone, of Instagram, Safari, Chrome. Nothing seems to be affecting it.

Can't find a way to replicate the issue on a desktop or find the exact setup of IG's browser.

Any ideas?

答: I had/have the same problem with an iPad Pro 11” running 13.3.1. Not sure why, but turning on Privacy mode seems to fix the issue.</p>


问:
How to read all message from Azure Service Bus topic using Python?
I want to read all messages from azure service bus using python. Currently it fetch only one message.

```<code>from azure.servicebus.control_client import ServiceBusService, Message, Topic, Rule, DEFAULT_RULE_NAME

    bus_service = ServiceBusService(
        service_namespace='<NameSpace>',
        shared_access_key_name='<KeyName>',
        shared_access_key_value='<ConnectionString>')

msg = bus_service.receive_subscription_message('topic', 'msglist', peek_lock=True)
print(msg.body)
</code>```

How can I get all the message in bulk from the topic with python 3

答:
This is possible by using a Receiver object which supports batch operations. Refer this sample which showcases how to get this object for a subscription.

To guarantee you get batches of messages, you have to set the prefetch argument of get_receiver() to your batch size and consequently the max_batch_size argument of fetch_next() to the same.

Body:
I want to read all messages from azure service bus using python. Currently it fetch only one message.

from azure.servicebus.control_client import ServiceBusService, Message, Topic, Rule, DEFAULT_RULE_NAME

    bus_service = ServiceBusService(
        service_namespace='<NameSpace>',
        shared_access_key_name='<KeyName>',
        shared_access_key_value='<ConnectionString>')

msg = bus_service.receive_subscription_message('topic', 'msglist', peek_lock=True)
print(msg.body)

How can I get all the message in bulk from the topic with python 3


问:
How to pass the data from list Component to edit component for data modification
//edit file

```<code>export class EditStoreComponent implements OnInit {
name = '';
id: ''

  constructor(private api:APIService, private router:Router, private cookieService: CookieService, private route:ActivatedRoute) {

      }
  ngOnInit() {

  }

  async updateStore(){
    let req = {
      id:this.id,
      name:this.name
    }
    console.log(req)
  let result = await this.api.UpdateStore(req)

  if (result){
    this.router.navigate(['../admin/liststore']);
    console.log(result)
    }
  }
}
</code>```

//list file

```<code>  rawlist;
  name = '';
  id = '';
  storeid = "";
  store: Store;

  constructor(private api: APIService, private router: Router, private route: ActivatedRoute, private cookieService: CookieService) { }

  ngOnInit() {
    this.storelist();

  }
  //store list
  async storelist() {
    this.rawlist = await this.api.ListStores();
    this.storelist = this.rawlist.items;
  }
</code>```

I am not sure how to pass ID from list to edit component. Basically i calling the api to update my data in the list. I only can passing the name, but I can not pass the id for specific user

答:
There are multiple way to pass data

using Subject.

using @input, @output decorator

using services

But if you want to pass ID or name (something like that ), you can just append id to route params.Like

```<code>this.router.navigate(["path", extra params(id)]);
</code>```

Body:
//edit file

export class EditStoreComponent implements OnInit {
name = '';
id: ''

  constructor(private api:APIService, private router:Router, private cookieService: CookieService, private route:ActivatedRoute) {

      }
  ngOnInit() {

  }

  async updateStore(){
    let req = {
      id:this.id,
      name:this.name
    }
    console.log(req)
  let result = await this.api.UpdateStore(req)

  if (result){
    this.router.navigate(['../admin/liststore']);
    console.log(result)
    }
  }
}

//list file

  rawlist;
  name = '';
  id = '';
  storeid = "";
  store: Store;

  constructor(private api: APIService, private router: Router, private route: ActivatedRoute, private cookieService: CookieService) { }

  ngOnInit() {
    this.storelist();

  }
  //store list
  async storelist() {
    this.rawlist = await this.api.ListStores();
    this.storelist = this.rawlist.items;
  }

I am not sure how to pass ID from list to edit component. Basically i calling the api to update my data in the list. I only can passing the name, but I can not pass the id for specific user

Body:
There are multiple way to pass data

using Subject.

using @input, @output decorator

using services

But if you want to pass ID or name (something like that ), you can just append id to route params.Like

this.router.navigate(["path", extra params(id)]);


问:
Remove single quotes and last comma in jquery string using Regex
I have a data

```<code>'abc','def','ghi',
</code>```

I want to remove the single quote on all character and want to remove only the last comma, example like below

```<code>abc,def,ghi
</code>```

How would i achieve that using regex for javascript?

I tried using this regex

```<code>.replace(^\'|,\s*$,"");
</code>```

But seems like it is only removing the first quote as shown below

```<code>abc','def','ghi',
</code>```

I am not very good in regex, i appreciate any help that i can get. Thanks

答: Can you please check replace(/'|(,)$/g," ") and it should work.

Body:
I have a data

'abc','def','ghi',

I want to remove the single quote on all character and want to remove only the last comma, example like below

abc,def,ghi

How would i achieve that using regex for javascript?

I tried using this regex

.replace(^\'|,\s*$,"");

But seems like it is only removing the first quote as shown below

abc','def','ghi',

I am not very good in regex, i appreciate any help that i can get. Thanks


问:
Filter on Tree or Nested Data
I have seen in one of the issues "Filter on Tree or Nested Data #1562" Oli has mentioned that

Hey @fr0z3nfyr
Filtering is supported on tree child nodes since version 4,2
Cheers
Oli :)

I am unable to find any example or the code to search nested data.
My code works perfectly fine for flat tables, but with nested tables it only works for the root node.

```<code>
            //data - the data for the row being filtered
            //filterParams - params object passed to the filter

            var match = false;
            for (var key in data) {

                if (data[key] != null) {
                    if ((data[key]).indexOf(filterParams.value) != -1) {
                        match = true;
                    }
                }

            }

            return match;
        }
        function updateFilter(){

            if ($("#filter-field").val() == "All Columns") {
                table.setFilter(matchAny,{ value:  $("#filter-value").val()});
            } else {
                table.setFilter($("#filter-field").val(), "like", $("#filter-value").val());
            }
            //var filter = $("#filter-field").val() == "All Columns" ? matchAny : $("#filter-field").val() ;

        }```

Oli could you please point me to an example where Nested data filtering is supported
```

答:
I was able to solve this, but by re-setting table data with filtered value  and also the tree structure is not maintained in the filtered list. I can maintain the tree structure with some changes in code, but this flat looks more like what I needed once filtering is done.

// This method iterates through the dataRows and its tree children and call a recursive function which creates the filtered table data.

```<code>function updateFilter() {

            var filtertableData = [];
            table.getRows().filter(function (row) {
                var rootData = row.getData();
                rootData._children = [];
                matchData(rootData, filtertableData);

                var childRows = row.getTreeChildren();
                searchForChildRows(rootData,childRows,filtertableData);
                 while (childRows.length != 0) {
                    for (var i = 0; i < childRows.length; i++) {
                        var childrow = childRows[i];
                        var childData = childrow.getData();
                        childData._children = [];
                        childRows = childrow.getTreeChildren();
                        searchForChildRows(childData,childRows,filtertableData);

                    }
                }

            });

           table.setData(filtertableData);
        }

function matchData(rootData, filtertableData, childdata) {
        if (typeof childdata === "undefined") {
            for (var key in rootData) {
                console.log(key);
                console.log(allVisibleCBSCols);
                if (rootData[key] != null && typeof rootData[key] == 'string' && allVisibleCBSCols.includes(key)) {
                    if ((rootData[key]).indexOf($("#filter-value-Project").val()) != -1) {

                        filtertableData.push(rootData);
                        break;
                    }
                }

            }
        } else {
            for (var key in childdata) {
                if (childdata[key] != null && typeof childdata[key] == 'string' && allVisibleCBSCols.includes(key)) {
                    if ((childdata[key]).indexOf($("#filter-value-Project").val()) != -1) {
                        //rootData._children.push(childdata);
                        filtertableData.push(childdata);
                        break;
                    }
                }

            }
        }
    }

 function searchForChildRows(rootData,childRows,filtertableData) {
        for (var i = 0; i < childRows.length; i++) {
             var childrow = childRows[i];
             var childData = childrow.getData();
             childData._children = [];
             matchData(rootData,filtertableData,childData);

        }
    }
</code>```

Title: Filter on Tree or Nested Data

Body:
I have seen in one of the issues "Filter on Tree or Nested Data #1562" Oli has mentioned that

Hey @fr0z3nfyr
Filtering is supported on tree child nodes since version 4,2
Cheers
Oli :)

I am unable to find any example or the code to search nested data.
My code works perfectly fine for flat tables, but with nested tables it only works for the root node.

            //data - the data for the row being filtered
            //filterParams - params object passed to the filter

            var match = false;
            for (var key in data) {

                if (data[key] != null) {
                    if ((data[key]).indexOf(filterParams.value) != -1) {
                        match = true;
                    }
                }

            }

            return match;
        }
        function updateFilter(){

            if ($("#filter-field").val() == "All Columns") {
                table.setFilter(matchAny,{ value:  $("#filter-value").val()});
            } else {
                table.setFilter($("#filter-field").val(), "like", $("#filter-value").val());
            }
            //var filter = $("#filter-field").val() == "All Columns" ? matchAny : $("#filter-field").val() ;

        }```

Oli could you please point me to an example where Nested data filtering is supported

Body:
I was able to solve this, but by re-setting table data with filtered value  and also the tree structure is not maintained in the filtered list. I can maintain the tree structure with some changes in code, but this flat looks more like what I needed once filtering is done.

// This method iterates through the dataRows and its tree children and call a recursive function which creates the filtered table data.

function updateFilter() {

            var filtertableData = [];
            table.getRows().filter(function (row) {
                var rootData = row.getData();
                rootData._children = [];
                matchData(rootData, filtertableData);

                var childRows = row.getTreeChildren();
                searchForChildRows(rootData,childRows,filtertableData);
                 while (childRows.length != 0) {
                    for (var i = 0; i < childRows.length; i++) {
                        var childrow = childRows[i];
                        var childData = childrow.getData();
                        childData._children = [];
                        childRows = childrow.getTreeChildren();
                        searchForChildRows(childData,childRows,filtertableData);

                    }
                }

            });

           table.setData(filtertableData);
        }

function matchData(rootData, filtertableData, childdata) {
        if (typeof childdata === "undefined") {
            for (var key in rootData) {
                console.log(key);
                console.log(allVisibleCBSCols);
                if (rootData[key] != null && typeof rootData[key] == 'string' && allVisibleCBSCols.includes(key)) {
                    if ((rootData[key]).indexOf($("#filter-value-Project").val()) != -1) {

                        filtertableData.push(rootData);
                        break;
                    }
                }

            }
        } else {
            for (var key in childdata) {
                if (childdata[key] != null && typeof childdata[key] == 'string' && allVisibleCBSCols.includes(key)) {
                    if ((childdata[key]).indexOf($("#filter-value-Project").val()) != -1) {
                        //rootData._children.push(childdata);
                        filtertableData.push(childdata);
                        break;
                    }
                }

            }
        }
    }

 function searchForChildRows(rootData,childRows,filtertableData) {
        for (var i = 0; i < childRows.length; i++) {
             var childrow = childRows[i];
             var childData = childrow.getData();
             childData._children = [];
             matchData(rootData,filtertableData,childData);

        }
    }


问:
Assign default role when new user register - drupal 8
I’m trying to assign default role for all new register user. but I got

```<code>Error: Call to a member function addRole() on array in my_module_user_insert()
</code>```

my code is

```<code>function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
if ($form_id == 'user_register_form') {
unset($form['account']['mail']['#description']);
unset($form['account']['name']['#description']);
unset($form['account']['pass']['#description']);
$form['actions']['submit']['#submit'][] = 'my_module_user_insert';
}
}
function my_module_user_insert($entity) {
  $entity->addRole('newcompanies');
  $entity->save();
}
</code>```

I try to use Administrator role in account settings [admin/config/people/accounts] page but not working. any idea?

答:
Try this in your custom module:

```<code>use Drupal\user\UserInterface;

function my_module_user_insert(UserInterface $user) {
    $rid = array_search('newcompanies', user_roles());

    $user->addRole($rid);
    $user->save();
}
</code>```

Explanation: You have to hook into the hook_ENTITY_TYPE_insert, and then add the desired role for the user being created. Note you have to add the role id instead of the role name!

I haven't tried it, just wrote it by memory, hope it helps!

Body:
I’m trying to assign default role for all new register user. but I got

Error: Call to a member function addRole() on array in my_module_user_insert()

my code is

function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
if ($form_id == 'user_register_form') {
unset($form['account']['mail']['#description']);
unset($form['account']['name']['#description']);
unset($form['account']['pass']['#description']);
$form['actions']['submit']['#submit'][] = 'my_module_user_insert';
}
}
function my_module_user_insert($entity) {
  $entity->addRole('newcompanies');
  $entity->save();
}

I try to use Administrator role in account settings [admin/config/people/accounts] page but not working. any idea?

Body:
Try this in your custom module:

use Drupal\user\UserInterface;

function my_module_user_insert(UserInterface $user) {
    $rid = array_search('newcompanies', user_roles());

    $user->addRole($rid);
    $user->save();
}

Explanation: You have to hook into the hook_ENTITY_TYPE_insert, and then add the desired role for the user being created. Note you have to add the role id instead of the role name!

I haven't tried it, just wrote it by memory, hope it helps!


问:
Terraform: Adding server logging to S3 bucket
I'm getting an error in my Terraform scripts when attempting to add logging to two buckets. These are part of one of my modules, and I've successfully used them before. I've come back to deploy a new environment...and now it's not working.

I'm getting the following error:

module.dev2_environment.module.portal.aws_s3_bucket.portal_bucket: 1 error occurred:
          * aws_s3_bucket.portal_bucket: Error putting S3 logging: InvalidTargetBucketForLogging: You must give the log-delivery group
  WRITE and READ_ACP permissions to the target bucket
          status code: 400, request id: 51AB42EFCACC9924, host id: nYCUxjHZE+xTisA1xG5syLTKVN/Rtwu8z3xF+O9GAPMdC2yGcafP4uwDURUGKd9Lx1SD8aHTcEI=

I'm executing via CLI, with Admin credentials. No code changes were made between the working state and the error. Any ideas on what could have changed? Syntax? AWS config someplace?

Terraform 11.14 and aws provider 2.16

Log bucket:

```<code>resource "aws_s3_bucket" "logs_bucket" {
  bucket = "XYZ-${var.env}-cdnlogs"
  acl    = "log-delivery-write"
  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"
      }
    }
  }
  tags {
    Finance     = "dev_env"
    Environment = "${var.env}"
  }
}
</code>```

Target Bucket:

```<code>resource "aws_s3_bucket" "portal_bucket" {
  bucket = "XYZ-${var.env}-portal"
  acl    = "private"
  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"
      }
    }
  }
  logging {
    target_bucket = "${aws_s3_bucket.logs_bucket.id}"
    target_prefix = "logs/portal/"
  }
  website {
    index_document = "index.html"
    error_document = "index.html"
  }
  // Needed to allow logos to be uploaded the "Portal"
  cors_rule {
    allowed_headers = ["*"]
    allowed_methods = ["GET", "HEAD", "PUT", "POST"]
    allowed_origins = ["*"]
    max_age_seconds = 3000
  }
  tags {
    Finance     = "dev_env"
    Environment = "${var.env}"
  }
}
</code>```

答:
I think the error is here
logging {
    target_bucket = "${aws_s3_bucket.**logs_bucket**.id}"
    target_prefix = "logs/portal/"
  }

It should be
logging {
    **target_bucket = "${aws_s3_bucket.portal_bucket.id}"**
    target_prefix = "logs/portal/"
  }

Body:
I'm getting an error in my Terraform scripts when attempting to add logging to two buckets. These are part of one of my modules, and I've successfully used them before. I've come back to deploy a new environment...and now it's not working.

I'm getting the following error:

module.dev2_environment.module.portal.aws_s3_bucket.portal_bucket: 1 error occurred:
          * aws_s3_bucket.portal_bucket: Error putting S3 logging: InvalidTargetBucketForLogging: You must give the log-delivery group
  WRITE and READ_ACP permissions to the target bucket
          status code: 400, request id: 51AB42EFCACC9924, host id: nYCUxjHZE+xTisA1xG5syLTKVN/Rtwu8z3xF+O9GAPMdC2yGcafP4uwDURUGKd9Lx1SD8aHTcEI=

I'm executing via CLI, with Admin credentials. No code changes were made between the working state and the error. Any ideas on what could have changed? Syntax? AWS config someplace?

Terraform 11.14 and aws provider 2.16

Log bucket:

resource "aws_s3_bucket" "logs_bucket" {
  bucket = "XYZ-${var.env}-cdnlogs"
  acl    = "log-delivery-write"
  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"
      }
    }
  }
  tags {
    Finance     = "dev_env"
    Environment = "${var.env}"
  }
}

Target Bucket:

resource "aws_s3_bucket" "portal_bucket" {
  bucket = "XYZ-${var.env}-portal"
  acl    = "private"
  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"
      }
    }
  }
  logging {
    target_bucket = "${aws_s3_bucket.logs_bucket.id}"
    target_prefix = "logs/portal/"
  }
  website {
    index_document = "index.html"
    error_document = "index.html"
  }
  // Needed to allow logos to be uploaded the "Portal"
  cors_rule {
    allowed_headers = ["*"]
    allowed_methods = ["GET", "HEAD", "PUT", "POST"]
    allowed_origins = ["*"]
    max_age_seconds = 3000
  }
  tags {
    Finance     = "dev_env"
    Environment = "${var.env}"
  }
}


问:
how to make bootstrap table clickable
I have a bootstrap like this in main.html page:

```<code><table class="table table-striped">
 <thead>
    <tr>
     <th scope="col">#</th>
     <th scope="col">First</th>
     <th scope="col">Last</th>
     <th scope="col">Handle</th>
   </tr>
 </thead>
 <tbody>
  <tr>
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>@mdo</td>
 </tr>
 <tr>
   <th scope="row">2</th>
   <td>Jacob</td>
   <td>Thornton</td>
   <td>@fat</td>
</tr>
<tr>
  <th scope="row">3</th>
  <td>Larry</td>
  <td>the Bird</td>
  <td>@twitter</td>
</tr>
</tbody>
</table>
</code>```

My requirement is:

When I click on any row of the table( either on the text or even in the space between two columns) it has to redirect to another Html page.

how can I do that?

答:
You can also achieve this by using Javascript on tr (inline)  : </p>

```<code><tr onclick="document.location = 'links.html';">
</code>```

<p>In this way you can set different links for different rows. Please check below updated HTML snippet : </p>

```<code><table class="table table-striped">
 <thead>
    <tr>
     <th scope="col">#</th>
     <th scope="col">First</th>
     <th scope="col">Last</th>
     <th scope="col">Handle</th>
   </tr>
 </thead>
 <tbody>
  <tr onclick="document.location = 'http://www.google.com';">
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>@mdo</td>
 </tr>
 <tr onclick="document.location = 'http://www.himanshu.com';">
   <th scope="row">2</th>
   <td>Jacob</td>
   <td>Thornton</td>
   <td>@fat</td>
</tr>
<tr onclick="document.location = '/links.html';">
  <th scope="row">3</th>
  <td>Larry</td>
  <td>the Bird</td>
  <td>@twitter</td>
</tr>
</tbody>
</table>
</code>```

Title: how to make bootstrap table clickable

Body:
I have a bootstrap like this in main.html page:

     #
     First
     Last
     Handle

    1
    Mark
    Otto
    @mdo

   2
   Jacob
   Thornton
   @fat

  3
  Larry
  the Bird
  @twitter

My requirement is:

When I click on any row of the table( either on the text or even in the space between two columns) it has to redirect to another Html page.

how can I do that?

Body:
You can also achieve this by using Javascript on tr (inline)  :

<tr onclick="document.location = 'links.html';">

In this way you can set different links for different rows. Please check below updated HTML snippet :

<table class="table table-striped">
 <thead>
    <tr>
     <th scope="col">#</th>
     <th scope="col">First</th>
     <th scope="col">Last</th>
     <th scope="col">Handle</th>
   </tr>
 </thead>
 <tbody>
  <tr onclick="document.location = 'http://www.google.com';">
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>@mdo</td>
 </tr>
 <tr onclick="document.location = 'http://www.himanshu.com';">
   <th scope="row">2</th>
   <td>Jacob</td>
   <td>Thornton</td>
   <td>@fat</td>
</tr>
<tr onclick="document.location = '/links.html';">
  <th scope="row">3</th>
  <td>Larry</td>
  <td>the Bird</td>
  <td>@twitter</td>
</tr>
</tbody>
</table>


问:
How do I resize an image using PIL and maintain its aspect ratio?
Is there an obvious way to do this that I'm missing?  I'm just trying to make thumbnails.</p>

答:
Open your image file

```<code>from PIL import Image
im = Image.open("image.png")
</code>```

Use PIL Image.resize(size, resample=0) method, where you substitute (width, height) of your image for the size 2-tuple.

This will display your image at original size:

```<code>display(im.resize((int(im.size[0]),int(im.size[1])), 0) )
</code>```

This will display your image at 1/2 the size:

```<code>display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )
</code>```

This will display your image at 1/3 the size:

```<code>display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )
</code>```

This will display your image at 1/4 the size:

```<code>display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )
</code>```

etc etc

OwnerDisplayName: saturdayplace

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ali

Body:
Open your image file

from PIL import Image
im = Image.open("image.png")

Use PIL Image.resize(size, resample=0) method, where you substitute (width, height) of your image for the size 2-tuple.

This will display your image at original size:

display(im.resize((int(im.size[0]),int(im.size[1])), 0) )

This will display your image at 1/2 the size:

display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )

This will display your image at 1/3 the size:

display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )

This will display your image at 1/4 the size:

display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )

etc etc


答:
Please find below the code that will redirect you to another link on click of any rows (except header row)

Add click event on all the rows inside the table body and execute your task.

$(function() {
  $('tbody tr').click(function() {
    window.location.href = 'https://www.google.com';
  })
})```

)

Title: how to make bootstrap table clickable

Body:
Please find below the code that will redirect you to another link on click of any rows (except header row)

Add click event on all the rows inside the table body and execute your task.

$(function() {
  $('tbody tr').click(function() {
    window.location.href = 'https://www.google.com';
  })
})

)


问:
How to add minutes to current time in swift
I am new to Swift and am trying a scheduler. I have the start time selected and I need to add 5 minutes (or multiples of it) to the start time and display it in an UILabel?

```<code>@IBAction func timePickerClicked(sender: UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
    var dateStr = dateFormatter.stringFromDate(startTime.date)
    let sttime = dateStr
    startTimeDisplay.text = dateStr
}

// How to advance time by 5 minutes for each section based on the   start time selected and display time
// section 1 = start time + 5
// section 2 = start time + 10*
</code>```

答:
You can use in swift 4 or 5

```<code>    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let current_date_time = dateFormatter.string(from: date)
    print("before add time-->",current_date_time)

    //adding 5 miniuts
    let addminutes = date.addingTimeInterval(5*60)
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let after_add_time = dateFormatter.string(from: addminutes)
    print("after add time-->",after_add_time)
</code>```

output:

```<code>before add time--> 2020-02-18 10:38:15
after add time--> 2020-02-18 10:43:15
</code>```

Body:
I am new to Swift and am trying a scheduler. I have the start time selected and I need to add 5 minutes (or multiples of it) to the start time and display it in an UILabel?

@IBAction func timePickerClicked(sender: UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
    var dateStr = dateFormatter.stringFromDate(startTime.date)
    let sttime = dateStr
    startTimeDisplay.text = dateStr
}

// How to advance time by 5 minutes for each section based on the   start time selected and display time
// section 1 = start time + 5
// section 2 = start time + 10*

Body:
You can use in swift 4 or 5

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let current_date_time = dateFormatter.string(from: date)
    print("before add time-->",current_date_time)

    //adding 5 miniuts
    let addminutes = date.addingTimeInterval(5*60)
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let after_add_time = dateFormatter.string(from: addminutes)
    print("after add time-->",after_add_time)

output:

before add time--> 2020-02-18 10:38:15
after add time--> 2020-02-18 10:43:15


问:
Insert URL column in a HTML table using Azure Logic App
I am creating a Logic App on Azure and in this process I have to create a HTML table with some data, insert that table in an email body and send that email using SendGrid.

Almost everything works, except that my table should have a column containing a URL to some website.

The problem is that somehow the Create HTML table action does not return  as HTML tag but  and the Send email's body (even if it's considered HTML content) can't process/interpret that.

I am using a concat(string1, string2 .. ) Expression to build the URL and I think it builds it correctly. The output look ok, only raw output is messed up.

Create HTML table action returns this:

Output:

Raw Output:

```<code><td><a="https: ...
</code>```

This is how the Output is injected into the email body of Send Email:

If the raw output could be changed to be in a more HTML format, the email body will parse it and display the URL in a correct way. (I'm not sure if I expressed myself very well. But even if I create a simple html file with that raw output, the a tag will be displayed in browser as simple text...)

Any ideas? I think that if I replace the concat() expression and generate the URL before, the raw output of Generate URL table will still mess up the final result.

Maybe if there is a way to stop the replacement of < and > with < and > it will work, but I don't know how to do that..

答:
For this problem, I initialize a variable to simulate your situation and we can just replace the < with < and replace the > with >. Then the send email action will work fine. Please refer to the steps below:

The whole expression is:

```<code>replace(replace(body('Create_HTML_table'), '<', '<'), '>', '>')
</code>```

Hope it helps~

Body:
I am creating a Logic App on Azure and in this process I have to create a HTML table with some data, insert that table in an email body and send that email using SendGrid.

Almost everything works, except that my table should have a column containing a URL to some website.

The problem is that somehow the Create HTML table action does not return  as HTML tag but  and the Send email's body (even if it's considered HTML content) can't process/interpret that.

I am using a concat(string1, string2 .. ) Expression to build the URL and I think it builds it correctly. The output look ok, only raw output is messed up.

Create HTML table action returns this:

Output:

Raw Output:

<a="https: ...

This is how the Output is injected into the email body of Send Email:

If the raw output could be changed to be in a more HTML format, the email body will parse it and display the URL in a correct way. (I'm not sure if I expressed myself very well. But even if I create a simple html file with that raw output, the a tag will be displayed in browser as simple text...)

Any ideas? I think that if I replace the concat() expression and generate the URL before, the raw output of Generate URL table will still mess up the final result.

Maybe if there is a way to stop the replacement of < and > with < and > it will work, but I don't know how to do that..

Body:
For this problem, I initialize a variable to simulate your situation and we can just replace the &lt; with < and replace the &gt; with >. Then the send email action will work fine. Please refer to the steps below:

The whole expression is:

replace(replace(body('Create_HTML_table'), '&lt;', '<'), '&gt;', '>')

Hope it helps~


问:
Paging with GridView and LINQ to SQL
My grideview:

```<code><asp:GridView runat="server" ID="MyGridView" AutoGenerateColumns="false"
    DataKeyNames="ID"
    OnRowCreated="MyGridView_RowCreated" AllowPaging="true" Width="100%"
    PageSize="5" onpageindexchanging="MyGridView_PageIndexChanging" >
</code>```

My code behind on page_load:

```<code>MyGridView.DataSource = new Emp.GetData();
MyGridView.DataBind();
</code>```

My code:

```<code>using (DataContext db = new DataContext())
{
    var query = //valid query here

    query = query.Skip(StartRowIndex *5 ).Take(5);

    return query.ToList();
}
</code>```

if i have 15 records in my db, upon page load i see links for page 1,2 3 with data for page 1 shown - 5 records. then when i go to page 2 with 5 records, i see page 1 and 3 links. when i go to page 3 i see only 2 records instead of 5 and sometimes the paging link does not show up correctly either.

I want to display 5 records per page and want the GridView to determine how many pages to show.

i am not using a LinqDataSource, just have a method that returns a list.

答:
Alternatively, you could use the PagedDataSource class to achieve this.

Here's an article explaining how it works.

Title: Paging with GridView and LINQ to SQL

Body:
My grideview:

<asp:GridView runat="server" ID="MyGridView" AutoGenerateColumns="false"
    DataKeyNames="ID"
    OnRowCreated="MyGridView_RowCreated" AllowPaging="true" Width="100%"
    PageSize="5" onpageindexchanging="MyGridView_PageIndexChanging" >

My code behind on page_load:

MyGridView.DataSource = new Emp.GetData();
MyGridView.DataBind();

My code:

using (DataContext db = new DataContext())
{
    var query = //valid query here

    query = query.Skip(StartRowIndex *5 ).Take(5);

    return query.ToList();
}

if i have 15 records in my db, upon page load i see links for page 1,2 3 with data for page 1 shown - 5 records. then when i go to page 2 with 5 records, i see page 1 and 3 links. when i go to page 3 i see only 2 records instead of 5 and sometimes the paging link does not show up correctly either.

I want to display 5 records per page and want the GridView to determine how many pages to show.

i am not using a LinqDataSource, just have a method that returns a list.


问:
Laravel Eloquent ORM - Removing rows and all the inner relationships
I have three tables, table1, table2, and table3. table1 is one-to-many to table2 and table2 is one-to-many to table3.

I want to invoke Table1::find($id)::delete() and have all the rows from table2 and table3 deleted as well.

I added the following to my tables:

Table1

```<code>public function delete()
{
    $this->table2()->delete();
    return parent::delete();
}
</code>```

Table2

```<code>public function delete()
{
    $this->table3()->delete();
    return parent::delete();
}
</code>```

However, my rows from table3 are not deleted. Table3's rows get deleted if I manually call the delete function from the model table2. The way I have written the code, shouldn't the delete() function from table2 be called when table1 calls it?

答:
I found this from laracasts and found it useful for me.
Let me paste the answer here:
So I have two models - User and Property User.php

```<code>public function properties()
    {
        return $this->hasMany('App\Models\Property');
    }
</code>```

Property.php

```<code>public function user()
    {
        return $this->belongsTo('App\User');
    }
</code>```

Thus, if I want to delete a particular user, and of course, I don't want any his properties to be retained in the database:

```<code>public function destroy($id)
    {
        $user = User::findOrFail($id);

        $user->properties()->delete();

        $user->delete();

        return [
            'message' => 'Delete Complete!'
        ];
    }
</code>```

I hope you or anyone else finds this useful! Regards :)

Source: https://laracasts.com/discuss/channels/eloquent/laravel-delete-model-with-all-relations

Body:
I have three tables, table1, table2, and table3. table1 is one-to-many to table2 and table2 is one-to-many to table3.

I want to invoke Table1::find($id)::delete() and have all the rows from table2 and table3 deleted as well.

I added the following to my tables:

Table1

public function delete()
{
    $this->table2()->delete();
    return parent::delete();
}

Table2

public function delete()
{
    $this->table3()->delete();
    return parent::delete();
}

However, my rows from table3 are not deleted. Table3's rows get deleted if I manually call the delete function from the model table2. The way I have written the code, shouldn't the delete() function from table2 be called when table1 calls it?

Body:
I found this from laracasts and found it useful for me.
Let me paste the answer here:
So I have two models - User and Property User.php

public function properties()
    {
        return $this->hasMany('App\Models\Property');
    }

Property.php

public function user()
    {
        return $this->belongsTo('App\User');
    }

Thus, if I want to delete a particular user, and of course, I don't want any his properties to be retained in the database:

public function destroy($id)
    {
        $user = User::findOrFail($id);

        $user->properties()->delete();

        $user->delete();

        return [
            'message' => 'Delete Complete!'
        ];
    }

I hope you or anyone else finds this useful! Regards :)

Source: https://laracasts.com/discuss/channels/eloquent/laravel-delete-model-with-all-relations


问:
Making the back and next button fixed on top of line chart
I'm using line chart and I have two navigational buttons which user can use to scroll the graph. Currently when I'm scrolling the graph, 2 buttons also getting scrolled. I need to make these 2 buttons fixed regardless of the scrolling of graph.

In addition, I want to hide the scrollbar without losing the scrollbar functionality.

```<code><div class = "col-5">
   <div id="wrapperChart" className="hideScroll wrapperScroll sc-line-chart">
      <div className="chartContainer">
         <canvas id="chart"></canvas>
      </div>
      <span type="button" className="sc-btn-icon sc-btn-icon--small sc-line-chart__icon sc-line-chart__icon--left">
         <i className="sc-kiosk-arrow-left2"></i>
      </span>
      <span type="button" className="sc-btn-icon sc-btn-icon--small sc-line-chart__icon sc-line-chart__icon--right">
         <i className="sc-kiosk-arrow-right2"></i>
      </span>
   </div>
</code>```

CSS:

```<code>.sc-line-chart{
    position: relative;
    overflow-x: auto;
    &__icon{
        position: absolute;
        &--left{
            bottom: 0;
            left: 0.15rem;
        }
        &--right{
            bottom: 0;
            right: 0;
        }
    }
}
</code>```

答:
You could work with frames. Put the chart on one frame and the 2 buttons on another frame. For example :</p>

```<code><frameset cols="90%,10%">
  <frame src="frame_chart.htm">
  <frame src="frame_buttons.htm">
</frameset>
</code>```

Body:
I'm using line chart and I have two navigational buttons which user can use to scroll the graph. Currently when I'm scrolling the graph, 2 buttons also getting scrolled. I need to make these 2 buttons fixed regardless of the scrolling of graph.

In addition, I want to hide the scrollbar without losing the scrollbar functionality.

         <canvas id="chart"></canvas>

CSS:

.sc-line-chart{
    position: relative;
    overflow-x: auto;
    &__icon{
        position: absolute;
        &--left{
            bottom: 0;
            left: 0.15rem;
        }
        &--right{
            bottom: 0;
            right: 0;
        }
    }
}

Body:
You could work with frames. Put the chart on one frame and the 2 buttons on another frame. For example :

<frameset cols="90%,10%">
  <frame src="frame_chart.htm">
  <frame src="frame_buttons.htm">
</frameset>


问:
Navigation Drawer For multiple Activities Without Selecting Navigation Drawer activity
I am new to android. I would like to implement a navigation drawer consisting of a list of items, which when clicked opens a new activity. Basically a navigation drawer across all the activities. When I select an item from the navigation drawer that particular activity opens.navigation drawer code is implemented by taking empty activity. I would like to implement navigation drawer functionality in all activities that activities are taken as empty activity in that activities already have some functionality along with this functionality the navigation drawer functionality also works. Please help me.

This is activity_header File

```<code><android.support.v4.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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer"
tools:context=".MainActivity">
<android.support.design.widget.NavigationView
    app:headerLayout="@layout/header"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:background="@color/white"
    app:menu="@menu/drawermenu"
    android:layout_gravity="start"
    android:id="@+id/navigationView"
    >
   </android.support.design.widget.NavigationView>
 </android.support.v4.widget.DrawerLayout>
</code>```

This is My Main Activity

```<code><GridView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/gridview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:columnWidth="90dp"
   android:numColumns="2"
   android:verticalSpacing="10dp"
   android:horizontalSpacing="10dp"
   android:stretchMode="columnWidth"
   android:gravity="center"
   android:layout_marginTop="30dp"/>
</code>```

This is Header Activity java code

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

protected DrawerLayout myDrawerLayout;
protected ActionBarDrawerToggle toggle;
protected NavigationView navigationView;

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

    myDrawerLayout=(DrawerLayout)findViewById(R.id.drawer);
    navigationView=(NavigationView) findViewById(R.id.navigationView);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

            Log.e("log_cat", "Error Response" + "Error");

            switch (menuItem.getItemId())
            {
                case R.id.dashboard:
                    Toast.makeText(HeaderActivity.this,"Dashboard Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.devotional:
                    Toast.makeText(HeaderActivity.this,"devotional Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.inspiration:
                    Toast.makeText(HeaderActivity.this,"inspiration Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.happy:
                    Toast.makeText(HeaderActivity.this,"happy Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.sad:
                    Toast.makeText(HeaderActivity.this,"sad Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.love:
                    Toast.makeText(HeaderActivity.this,"love Clicked",Toast.LENGTH_LONG).show();
                    break;

            }
            return false;
        }
    });
    toggle = new ActionBarDrawerToggle(
            this,
            myDrawerLayout,
            R.string.open,
            R.string.close
    ) {
        public void onDrawerClosed(View view) {
            //Snackbar.make(view, R.string.drawer_close, Snackbar.LENGTH_SHORT).show();
        }

        public void onDrawerOpened(View drawerView) {
            //Snackbar.make(drawerView, R.string.drawer_open, Snackbar.LENGTH_SHORT).show();
        }
    };
    myDrawerLayout.addDrawerListener(toggle);
    toggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // gridview.setAdapter(i);

}

@Override
public boolean onOptionsItemSelected (MenuItem item) {
    if (toggle.onOptionsItemSelected (item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);

}
</code>```

}

This is My main activity java code

public class MainActivity extends HeaderActivity  {

```<code>GridView grid;
public static String[] osNameList = {
        "Devotional",
        "Inspirational",
        "Happy",
        "Sad",
        "Love"

} ;
public static int[] osImages = {
        R.drawable.devotional,
        R.drawable.inspirational,
        R.drawable.happy,
        R.drawable.sad,
        R.drawable.love

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getLayoutInflater().inflate(R.layout.activity_main, myDrawerLayout);
    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this, osNameList, osImages));

}
</code>```

}

In this code setNavigationItemSelectedListener is not working in mainactivity but setOnClickListener on Grid is working. When we click on any navigation menu element it move to that activity.

答:
If you want to include NavigationDrawer in all pages, you should use Fragment for feature pages.
If you want to see an example, you can see at here

Additionally I want you to recommend to use Android Jetpack Navigation Component with NavigationUI and DrawerLayout.

Body:
I am new to android. I would like to implement a navigation drawer consisting of a list of items, which when clicked opens a new activity. Basically a navigation drawer across all the activities. When I select an item from the navigation drawer that particular activity opens.navigation drawer code is implemented by taking empty activity. I would like to implement navigation drawer functionality in all activities that activities are taken as empty activity in that activities already have some functionality along with this functionality the navigation drawer functionality also works. Please help me.

This is activity_header File

<android.support.v4.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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer"
tools:context=".MainActivity">
<android.support.design.widget.NavigationView
    app:headerLayout="@layout/header"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:background="@color/white"
    app:menu="@menu/drawermenu"
    android:layout_gravity="start"
    android:id="@+id/navigationView"
    >
   </android.support.design.widget.NavigationView>
 </android.support.v4.widget.DrawerLayout>

This is My Main Activity

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/gridview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:columnWidth="90dp"
   android:numColumns="2"
   android:verticalSpacing="10dp"
   android:horizontalSpacing="10dp"
   android:stretchMode="columnWidth"
   android:gravity="center"
   android:layout_marginTop="30dp"/>

This is Header Activity java code

public class HeaderActivity extends AppCompatActivity {

protected DrawerLayout myDrawerLayout;
protected ActionBarDrawerToggle toggle;
protected NavigationView navigationView;

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

    myDrawerLayout=(DrawerLayout)findViewById(R.id.drawer);
    navigationView=(NavigationView) findViewById(R.id.navigationView);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

            Log.e("log_cat", "Error Response" + "Error");

            switch (menuItem.getItemId())
            {
                case R.id.dashboard:
                    Toast.makeText(HeaderActivity.this,"Dashboard Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.devotional:
                    Toast.makeText(HeaderActivity.this,"devotional Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.inspiration:
                    Toast.makeText(HeaderActivity.this,"inspiration Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.happy:
                    Toast.makeText(HeaderActivity.this,"happy Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.sad:
                    Toast.makeText(HeaderActivity.this,"sad Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.love:
                    Toast.makeText(HeaderActivity.this,"love Clicked",Toast.LENGTH_LONG).show();
                    break;

            }
            return false;
        }
    });
    toggle = new ActionBarDrawerToggle(
            this,
            myDrawerLayout,
            R.string.open,
            R.string.close
    ) {
        public void onDrawerClosed(View view) {
            //Snackbar.make(view, R.string.drawer_close, Snackbar.LENGTH_SHORT).show();
        }

        public void onDrawerOpened(View drawerView) {
            //Snackbar.make(drawerView, R.string.drawer_open, Snackbar.LENGTH_SHORT).show();
        }
    };
    myDrawerLayout.addDrawerListener(toggle);
    toggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // gridview.setAdapter(i);

}

@Override
public boolean onOptionsItemSelected (MenuItem item) {
    if (toggle.onOptionsItemSelected (item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);

}

}

This is My main activity java code

public class MainActivity extends HeaderActivity  {

GridView grid;
public static String[] osNameList = {
        "Devotional",
        "Inspirational",
        "Happy",
        "Sad",
        "Love"

} ;
public static int[] osImages = {
        R.drawable.devotional,
        R.drawable.inspirational,
        R.drawable.happy,
        R.drawable.sad,
        R.drawable.love

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getLayoutInflater().inflate(R.layout.activity_main, myDrawerLayout);
    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this, osNameList, osImages));

}

}

In this code setNavigationItemSelectedListener is not working in mainactivity but setOnClickListener on Grid is working. When we click on any navigation menu element it move to that activity.


问:
How to create a dynamic const name for an array using dropdown options in reactjs or nextjs?
Is it possible to create a dynamic const name of an array using dropdown options?</p>

```<code>Import {array1, array2, array3} from './myfilesystem/arrays';

const somename = array1;

</code>```

答:
You need to:

Put your arrays in a keyed object.

Put the keys in the drop-down.

Put the selected key in a variable.

Use the value of that variable to look up the array in the object.

Like this:

```<code>const arrays = {
  array1: [...],
  array2: [...],
  array3: [...]
}

const optionsForDropdown = Object.keys(arrays) // ["array1", "array2",...]

function returnSelectedArray(selectedKey) {
  return arrays[selectedKey]
}
</code>```

So if you call returnSelectedArray("array1") or you do:

```<code>const key = "array1"
returnSelectedArray(key)
</code>```

you will get arrays.array1 back.

Body:
Is it possible to create a dynamic const name of an array using dropdown options?

Import {array1, array2, array3} from './myfilesystem/arrays';

const somename = array1;

Body:
You need to:

Put your arrays in a keyed object.

Put the keys in the drop-down.

Put the selected key in a variable.

Use the value of that variable to look up the array in the object.

Like this:

const arrays = {
  array1: [...],
  array2: [...],
  array3: [...]
}

const optionsForDropdown = Object.keys(arrays) // ["array1", "array2",...]

function returnSelectedArray(selectedKey) {
  return arrays[selectedKey]
}

So if you call returnSelectedArray("array1") or you do:

const key = "array1"
returnSelectedArray(key)

you will get arrays.array1 back.