问:
Android Studio Kotlin App Gives Crash FATAL EXCEPTION
I am a newbie at android studio and kotlin. Now im working with a firebase login/register app. On the code menu there is error but when i try on avg emulator app shutdown immediately. Can you help me Please

Here is my codes

My Manifest

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

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.ASSK">
    <activity
        android:name=".RegisterActivity"
        android:exported="false" />
    <activity
        android:name=".LoginActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:exported="false" />
</application>
</code>```

Here is my activity.kt

```<code>
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth

import kotlinx.android.synthetic.main.activity_register.*

class LoginActivity : AppCompatActivity()
{
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)```

        val btnlogin: Button = findViewById(R.id.btn_login)

        val etemail: EditText = findViewById(R.id.et_login_email)
        val etpassword: EditText = findViewById(R.id.et_login_password)
        btnlogin.setOnClickListener {

            if (etemail.text.toString().trim().isEmpty()) {
                Toast.makeText(
                    this@LoginActivity,
                    "Email Alanını Doldurun",
                    Toast.LENGTH_SHORT
                ).show()

                (etpassword.text.toString().trim().isEmpty())
                Toast.makeText(
                    this@LoginActivity,
                    "Şifre Alanını Doldurun",
                    Toast.LENGTH_SHORT
                ).show()
            } else {

                val email: String = etemail.text.toString().trim { it <= ' ' }
                val password: String = etpassword.text.toString().trim { it <= ' ' }

                FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(
                        OnCompleteListener<AuthResult> { task ->

                            if (task.isSuccessful) {

                                Toast.makeText(
                                    this@LoginActivity,
                                    "Başarı İle Giriş Yapıldı",
                                    Toast.LENGTH_SHORT
                                ).show()

                                val intent =
                                    Intent(this@LoginActivity, MainActivity::class.java)
                                intent.flags =
                                    Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                                intent.putExtra(
                                    "user_id", FirebaseAuth.getInstance().currentUser!!.uid)
                                intent.putExtra("email_id", email)
                                startActivity(intent)
                                finish()
                            } else {
                                Toast.makeText(
                                    this@LoginActivity,
                                    task.exception!!.message.toString(),
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    )

            }

        }
    }
}
```
<p>Idk why but import part and some of codes nor formatted sorry for that.</p>
<p>And for the last here is my layout.xml</p>
```<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity"
    android:background="@drawable/background">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="225dp"
        android:fontFamily="@font/league_spartan_bold"
        android:text="Giriş Yap"
        android:textColor="#222934"
        android:textSize="25sp"
        android:textStyle="normal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/et_login_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="20dp"
        android:inputType="textEmailAddress"
        app:helperText="Zorunlu"
        app:helperTextTextColor="@android:color/holo_red_dark"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_title"
        tools:text="abc@gmail.com"
        android:hint="E-Mail">

        <EditText
            android:id="@+id/til_login_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            tools:text="abc@gmail.com">
        </EditText>
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til_login_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="20dp"
        android:hint="Şifre"
        app:helperText="Zorunlu"
        app:helperTextTextColor="@android:color/holo_red_dark"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_login_email">

        <EditText
            android:id="@+id/et_login_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            tools:text="123456">
        </EditText>
    </com.google.android.material.textfield.TextInputLayout>

    <Button
        android:id="@+id/btn_login"
        android:foreground="?attr/selectableItemBackground"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginStart="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="20dp"
        android:background="@color/gri"
        android:gravity="center"
        android:text="Giriş Yap"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/til_login_password" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/btn_login">

        <TextView
            android:id="@+id/tv_dont_have_account"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:fontFamily="sans-serif-medium"
            android:padding="5dp"
            android:text="Mevcut Hesabın Yok mu ?">
        </TextView>

        <TextView
            android:id="@+id/tv_register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:fontFamily="@font/league_spartan_bold"
            android:foreground="?attr/selectableItemBackground"
            android:padding="5dp"
            android:text="Kayıt Ol"
            android:textStyle="normal">
        </TextView>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
```
<p>And here is my logcat report</p>
```    Process: com.example.assk, PID: 6762
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.assk/com.example.assk.LoginActivity}: java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to android.widget.EditText
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to android.widget.EditText
        at com.example.assk.LoginActivity.onCreate(LoginActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:8000)
        at android.app.Activity.performCreate(Activity.java:7984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)```

The format error happened again idk why it happens sorry for that. So here is my all codes what can i do pls help me
</code>```

答:
you are referencing to wrong view just change your code like this:

```<code>    val btnlogin: Button = findViewById(R.id.btn_login)
    val etemail: EditText = findViewById(R.id.til_login_email)
    val etpassword: EditText = findViewById(R.id.et_login_password)
</code>```

This should solve your problem.

Body:
I am a newbie at android studio and kotlin. Now im working with a firebase login/register app. On the code menu there is error but when i try on avg emulator app shutdown immediately. Can you help me Please

Here is my codes

My Manifest

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.ASSK">
    <activity
        android:name=".RegisterActivity"
        android:exported="false" />
    <activity
        android:name=".LoginActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:exported="false" />
</application>

Here is my activity.kt

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth

import kotlinx.android.synthetic.main.activity_register.*

class LoginActivity : AppCompatActivity()
{
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)```

        val btnlogin: Button = findViewById(R.id.btn_login)

        val etemail: EditText = findViewById(R.id.et_login_email)
        val etpassword: EditText = findViewById(R.id.et_login_password)
        btnlogin.setOnClickListener {

            if (etemail.text.toString().trim().isEmpty()) {
                Toast.makeText(
                    this@LoginActivity,
                    "Email Alanını Doldurun",
                    Toast.LENGTH_SHORT
                ).show()

                (etpassword.text.toString().trim().isEmpty())
                Toast.makeText(
                    this@LoginActivity,
                    "Şifre Alanını Doldurun",
                    Toast.LENGTH_SHORT
                ).show()
            } else {

                val email: String = etemail.text.toString().trim { it <= ' ' }
                val password: String = etpassword.text.toString().trim { it <= ' ' }

                FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(
                        OnCompleteListener<AuthResult> { task ->

                            if (task.isSuccessful) {

                                Toast.makeText(
                                    this@LoginActivity,
                                    "Başarı İle Giriş Yapıldı",
                                    Toast.LENGTH_SHORT
                                ).show()

                                val intent =
                                    Intent(this@LoginActivity, MainActivity::class.java)
                                intent.flags =
                                    Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                                intent.putExtra(
                                    "user_id", FirebaseAuth.getInstance().currentUser!!.uid)
                                intent.putExtra("email_id", email)
                                startActivity(intent)
                                finish()
                            } else {
                                Toast.makeText(
                                    this@LoginActivity,
                                    task.exception!!.message.toString(),
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    )

            }

        }
    }
}
</code></pre>
<p>Idk why but import part and some of codes nor formatted sorry for that.</p>
<p>And for the last here is my layout.xml</p>
<pre><code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity"
    android:background="@drawable/background">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="225dp"
        android:fontFamily="@font/league_spartan_bold"
        android:text="Giriş Yap"
        android:textColor="#222934"
        android:textSize="25sp"
        android:textStyle="normal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/et_login_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="20dp"
        android:inputType="textEmailAddress"
        app:helperText="Zorunlu"
        app:helperTextTextColor="@android:color/holo_red_dark"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_title"
        tools:text="abc@gmail.com"
        android:hint="E-Mail">

        <EditText
            android:id="@+id/til_login_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            tools:text="abc@gmail.com">
        </EditText>
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til_login_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="20dp"
        android:hint="Şifre"
        app:helperText="Zorunlu"
        app:helperTextTextColor="@android:color/holo_red_dark"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_login_email">

        <EditText
            android:id="@+id/et_login_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            tools:text="123456">
        </EditText>
    </com.google.android.material.textfield.TextInputLayout>

    <Button
        android:id="@+id/btn_login"
        android:foreground="?attr/selectableItemBackground"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginStart="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="20dp"
        android:background="@color/gri"
        android:gravity="center"
        android:text="Giriş Yap"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/til_login_password" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/btn_login">

        <TextView
            android:id="@+id/tv_dont_have_account"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:fontFamily="sans-serif-medium"
            android:padding="5dp"
            android:text="Mevcut Hesabın Yok mu ?">
        </TextView>

        <TextView
            android:id="@+id/tv_register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:fontFamily="@font/league_spartan_bold"
            android:foreground="?attr/selectableItemBackground"
            android:padding="5dp"
            android:text="Kayıt Ol"
            android:textStyle="normal">
        </TextView>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p>And here is my logcat report</p>
<pre><code>    Process: com.example.assk, PID: 6762
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.assk/com.example.assk.LoginActivity}: java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to android.widget.EditText
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.ClassCastException: com.google.android.material.textfield.TextInputLayout cannot be cast to android.widget.EditText
        at com.example.assk.LoginActivity.onCreate(LoginActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:8000)
        at android.app.Activity.performCreate(Activity.java:7984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)```

The format error happened again idk why it happens sorry for that. So here is my all codes what can i do pls help me

Body:
you are referencing to wrong view just change your code like this:

    val btnlogin: Button = findViewById(R.id.btn_login)
    val etemail: EditText = findViewById(R.id.til_login_email)
    val etpassword: EditText = findViewById(R.id.et_login_password)

This should solve your problem.


来源: stackexchange

问:
use variable in terragrunt config
can we use terraform variables inside terragrunt config?

below is my terragrunt config.

```<code>#terragrunt.hcl

remote_state {
  backend = "s3"
  generate = {
    path      = "remote_state.tf"
    if_exists = "overwrite_terragrunt"
  }
  # Terragrunt built-in function:
  # sets key relative to the modules
  config = {
    bucket         = ${var.bucket_name}
    key            = ${var.key}
    encrypt        = true
  }
}
</code>```

Inside root.yaml file, I have passed input values for variable bucket_name and key. these variables are defined inside terraform modules.

```<code>#root.yaml
bucket_name: "s3-bucket"
key:    "foo"
</code>```

this is not working, terragrunt is complaining that the variable is not defined. without creating a new variable to use for terragrunt, can't we use terraform variable inside terragrunt config?

答:
I've actually played around with this for a few hours and realized a few things.

Approach 1: Read variables from OS environment

if you are going to read the file as a system-level environment variable (a variable you defined in, let's say, Debian or RedHat Linux), the documentation suggests this:

https://terragrunt.gruntwork.io/docs/reference/built-in-functions/#get_env

Note that Terraform will read environment variables that start with
the prefix TF_VAR_, so one way to share a variable named foo between
Terraform and Terragrunt is to set its value as the environment
variable TF_VAR_foo and to read that value in using this get_env()
built-in function.

That implies that you can set TF_VAR_foo at the OS level and it will be available to get_env() function. I opened up ~/.bash_profile and added export TF_VAR_env=sandbox and ran source ~/.bash_profile but it didn't work. I then tried export env=sandbox in ~/.bash_profile and that indeed worked with get_env("env", "").

Approach 2: Read variables from file

Terragrunt has a file() built-in function. You can use it to read variables stored in a yml file:

```<code>locals {
  settings_default    = yamldecode(file("defaults.yml"))
}
</code>```

Inside defaults.yml, you can have key/value pairs:

```<code>---
some_var: some_val
</code>```

ContentLicense: CC BY-SA 4.0

Title: use variable in terragrunt config

Body:
can we use terraform variables inside terragrunt config?

below is my terragrunt config.

#terragrunt.hcl

remote_state {
  backend = "s3"
  generate = {
    path      = "remote_state.tf"
    if_exists = "overwrite_terragrunt"
  }
  # Terragrunt built-in function:
  # sets key relative to the modules
  config = {
    bucket         = ${var.bucket_name}
    key            = ${var.key}
    encrypt        = true
  }
}

Inside root.yaml file, I have passed input values for variable bucket_name and key. these variables are defined inside terraform modules.

#root.yaml
bucket_name: "s3-bucket"
key:    "foo"

this is not working, terragrunt is complaining that the variable is not defined. without creating a new variable to use for terragrunt, can't we use terraform variable inside terragrunt config?

Body:
I've actually played around with this for a few hours and realized a few things.

Approach 1: Read variables from OS environment

if you are going to read the file as a system-level environment variable (a variable you defined in, let's say, Debian or RedHat Linux), the documentation suggests this:

https://terragrunt.gruntwork.io/docs/reference/built-in-functions/#get_env

Note that Terraform will read environment variables that start with
the prefix TF_VAR_, so one way to share a variable named foo between
Terraform and Terragrunt is to set its value as the environment
variable TF_VAR_foo and to read that value in using this get_env()
built-in function.

That implies that you can set TF_VAR_foo at the OS level and it will be available to get_env() function. I opened up ~/.bash_profile and added export TF_VAR_env=sandbox and ran source ~/.bash_profile but it didn't work. I then tried export env=sandbox in ~/.bash_profile and that indeed worked with get_env("env", "").

Approach 2: Read variables from file

Terragrunt has a file() built-in function. You can use it to read variables stored in a yml file:

locals {
  settings_default    = yamldecode(file("defaults.yml"))
}

Inside defaults.yml, you can have key/value pairs:

---
some_var: some_val


问:
Append an array to another array

I have a problem with np.append(ar,values, axis=None)

Take a look at following codes:

import numpy as np

array1 = np.array([])
array2 = np.array([1,2])
array3 = np.array([3,4])
array4 = np.array([5,6])

array1 = np.append(array1, array2)
array1 = np.append(array1, array3)
array1 = np.append(array1, array4)

print(array1) # [1. 2. 3. 4. 5. 6.]
```
<p>So this is not what i want i want add exactly the array to the array1
and the array1 should be</p>
```[[1. 2.]
 [3. 4.]
 [5. 6.]]
```

How can i do that?

答:
You need to stack the arrays.

```<code>array1 = np.stack([array2, array3, array4])
</code>```

should do it.

Title: Append an array to another array

Body:
I have a problem with np.append(ar,values, axis=None)

Take a look at following codes:

import numpy as np

array1 = np.array([])
array2 = np.array([1,2])
array3 = np.array([3,4])
array4 = np.array([5,6])

array1 = np.append(array1, array2)
array1 = np.append(array1, array3)
array1 = np.append(array1, array4)

print(array1) # [1. 2. 3. 4. 5. 6.]

So this is not what i want i want add exactly the array to the array1
and the array1 should be

[[1. 2.]
 [3. 4.]
 [5. 6.]]

How can i do that?

Body:
You need to stack the arrays.

array1 = np.stack([array2, array3, array4])

should do it.


问:
Uncaught TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) in my React project
I am new to context API and trying to get my code to work. I am getting error:

Uncaught TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))

Would some of you good people help with this?

The initialUserState logs an object the looks like this: {name: nanny}

My context file is:

```<code>import { createContext, useState } from "react";

const initialUserState = JSON.parse(localStorage.getItem("user"));
console.log(initialUserState);
const initialFormValues = {
  video: "Video.mp4",
  hourly: "",
  ageRange: [],
  car: "",
  languages: [],
  homework: "",
  license: "",
  preference: "",
  vaccination: "",
  radius: "",
  booked: "",
  fileUpload: "file.jpg",
};

export const Global = createContext();

export default function GlobalContext({ children }) {
  const [state, setState] = useState(initialUserState);
  const [values, setValues] = useState(initialFormValues); //setting form state
  const [radioSelected, setRadioSelected] = useState();

  const changeState = (newState = {}) => {
    const tempState = { ...state, ...newState };
    setState(tempState);
    localStorage.setItem("user", JSON.stringify(tempState));
  };

  return (
    <Global.Provider
      value={[
        { ...state },
        changeState,
        values,
        setValues,
        radioSelected,
        setRadioSelected,
      ]}
    >
      {children}
    </Global.Provider>
  );
}
</code>```

then where I am getting state from, the initialFormValues does not log in the console:

```<code>const HourlyRate = () => {

  //context API

  const [values, setValues] = useContext(GlobalContext); **//this is where the error is being flagged from**

  //handle form value changes
  const handleChange = (e) => {
    e.preventDefault();

    const { name, value } = e.target;
    setValues({ ...values, [name]: value });
  };

  return (
    <div className="sub-settings-div">
      <Link className="back" to="/video-upload">
        <span>
          <ArrowBackIcon />
        </span>
        Back
      </Link>
      <h3 className="sub-settings-header">{t("common.title")}</h3>
      <h2 className="sub-settings-sub-header">{t("hourly.subTitle")}</h2>
      <p className="range">(10.45 € - 20 €) </p>
      <form className="input">
        <TextField
          className="input-field"
          required
          id="outlined-required"
          label="Hourly Rate"
          name="hourly"
          value={values.hourly}
          onChange={handleChange}
        />
      </form>
      <div className="nav-btns">
        <Link to="/video-upload" className="prev-link">
          <button className="prev">{t("buttons.back")}</button>
        </Link>
        <Link to="/age-range" className="next-link">
          <button className="next">
            {t("buttons.next")}
            <span>
              <ArrowForwardIcon />
            </span>
          </button>
        </Link>
      </div>
    </div>
  );
};

export default HourlyRate;
</code>```

答:
Couple issues I see:

You are passing the context provider component GlobalContext to the useContext hook, const [values, setValues] = useContext(GlobalContext);

The context value is an array, so when using array destructuring the order of the array elements matters.

Use the correct variable for the context. You may want to give the context the GlobalContext name, and rename the provider something like GlobalProvider. I suggest also using an object for the context value to eliminate the array element order destructuring issue.

```<code>export const GlobalContext = createContext();

export default function GlobalProvider({ children }) {
  const [state, setState] = useState(initialUserState);
  const [values, setValues] = useState(initialFormValues); //setting form state
  const [radioSelected, setRadioSelected] = useState();

  const changeState = (newState = {}) => {
    const tempState = { ...state, ...newState };
    setState(tempState);
    localStorage.setItem("user", JSON.stringify(tempState));
  };

  return (
    <Global.Provider
      value={{
        state,
        changeState,
        values,
        setValues,
        radioSelected,
        setRadioSelected,
      }}
    >
      {children}
    </Global.Provider>
  );
}
</code>```

Then assuming your main App component is correctly wrapped in the GlobalProvider, use object destructuring from the hook.

```<code>const { values, setValues } = useContext(GlobalContext);
</code>```

Body:
I am new to context API and trying to get my code to work. I am getting error:

Uncaught TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))

Would some of you good people help with this?

The initialUserState logs an object the looks like this: {name: nanny}

My context file is:

import { createContext, useState } from "react";

const initialUserState = JSON.parse(localStorage.getItem("user"));
console.log(initialUserState);
const initialFormValues = {
  video: "Video.mp4",
  hourly: "",
  ageRange: [],
  car: "",
  languages: [],
  homework: "",
  license: "",
  preference: "",
  vaccination: "",
  radius: "",
  booked: "",
  fileUpload: "file.jpg",
};

export const Global = createContext();

export default function GlobalContext({ children }) {
  const [state, setState] = useState(initialUserState);
  const [values, setValues] = useState(initialFormValues); //setting form state
  const [radioSelected, setRadioSelected] = useState();

  const changeState = (newState = {}) => {
    const tempState = { ...state, ...newState };
    setState(tempState);
    localStorage.setItem("user", JSON.stringify(tempState));
  };

  return (
    <Global.Provider
      value={[
        { ...state },
        changeState,
        values,
        setValues,
        radioSelected,
        setRadioSelected,
      ]}
    >
      {children}
    </Global.Provider>
  );
}

then where I am getting state from, the initialFormValues does not log in the console:

const HourlyRate = () => {

  //context API

  const [values, setValues] = useContext(GlobalContext); **//this is where the error is being flagged from**

  //handle form value changes
  const handleChange = (e) => {
    e.preventDefault();

    const { name, value } = e.target;
    setValues({ ...values, [name]: value });
  };

  return (

      <Link className="back" to="/video-upload">

          <ArrowBackIcon />

        Back
      </Link>

{t("common.title")}

{t("hourly.subTitle")}

(10.45 € - 20 €)

      <form className="input">
        <TextField
          className="input-field"
          required
          id="outlined-required"
          label="Hourly Rate"
          name="hourly"
          value={values.hourly}
          onChange={handleChange}
        />
      </form>

        <Link to="/video-upload" className="prev-link">
          <button className="prev">{t("buttons.back")}</button>
        </Link>
        <Link to="/age-range" className="next-link">
          <button className="next">
            {t("buttons.next")}

              <ArrowForwardIcon />

          </button>
        </Link>

  );
};

export default HourlyRate;

Body:
Couple issues I see:

You are passing the context provider component GlobalContext to the useContext hook, const [values, setValues] = useContext(GlobalContext);

The context value is an array, so when using array destructuring the order of the array elements matters.

Use the correct variable for the context. You may want to give the context the GlobalContext name, and rename the provider something like GlobalProvider. I suggest also using an object for the context value to eliminate the array element order destructuring issue.

export const GlobalContext = createContext();

export default function GlobalProvider({ children }) {
  const [state, setState] = useState(initialUserState);
  const [values, setValues] = useState(initialFormValues); //setting form state
  const [radioSelected, setRadioSelected] = useState();

  const changeState = (newState = {}) => {
    const tempState = { ...state, ...newState };
    setState(tempState);
    localStorage.setItem("user", JSON.stringify(tempState));
  };

  return (
    <Global.Provider
      value={{
        state,
        changeState,
        values,
        setValues,
        radioSelected,
        setRadioSelected,
      }}
    >
      {children}
    </Global.Provider>
  );
}

Then assuming your main App component is correctly wrapped in the GlobalProvider, use object destructuring from the hook.

const { values, setValues } = useContext(GlobalContext);


问:
ProcessPoolExecutor pass multiple arguments
ESPNPlayerFree

```<code>class ESPNPlayerFree:

def __init__(self, player_id, match_id, match_id_team):
...
</code>```

teamList1:

```<code> [('277906', 'cA2i150s81HI3qbq1fzi', 'za1Oq5CGHj3pkkXWNghG'), ('213674', 'cA2i150s81HI3qbq1fzi', 'za1Oq5CGHj3pkkXWNghG')]
</code>```

Code

```<code> with concurrent.futures.ProcessPoolExecutor(max_workers=30) as executor:
    results = list(executor.map(ESPNPlayerFree, teamList1))
</code>```

TypeError: __init__() missing 2 required positional arguments: 'match_id' and 'match_id_team'

答:
According to source code of Executor.map:

fs = [self.submit(fn, *args) for args in zip(*iterables)]
```
<p>So you can have:</p>
<pre class="lang-py prettyprint-override"><code>executor.map(ESPNPlayerFree, player_id_list, match_id_list, match_id_team_list)
</code>```

Body:
ESPNPlayerFree

class ESPNPlayerFree:

def __init__(self, player_id, match_id, match_id_team):
...

teamList1:

 [('277906', 'cA2i150s81HI3qbq1fzi', 'za1Oq5CGHj3pkkXWNghG'), ('213674', 'cA2i150s81HI3qbq1fzi', 'za1Oq5CGHj3pkkXWNghG')]

Code

 with concurrent.futures.ProcessPoolExecutor(max_workers=30) as executor:
    results = list(executor.map(ESPNPlayerFree, teamList1))

TypeError: __init__() missing 2 required positional arguments: 'match_id' and 'match_id_team'

Body:
According to source code of Executor.map:

fs = [self.submit(fn, *args) for args in zip(*iterables)]

So you can have:

executor.map(ESPNPlayerFree, player_id_list, match_id_list, match_id_team_list)


答:
Your value is:

```<code>[
    { ...state },
    changeState,
    values,
    setValues,
    radioSelected,
    setRadioSelected,
  ]
</code>```

and this line: const [values, setValues] = useContext(GlobalContext); will destructure the value (an array) but there is a key difference between destructuring an array and an object:
with an array, the destructuring is by order( unlike an object which is by name), meaning:
that the values variable will hold the the first object { ...state }
which is not iteratable.

If Your value will be an object:

```<code>{
    state,
    changeState,
    values,
    setValues,
    radioSelected,
    setRadioSelected,
  }
</code>```

and the useContext will be const {state,setValues} = useContext(GlobalContext);

Title: Uncaught TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) in my React project

Body:
Your value is:

[
    { ...state },
    changeState,
    values,
    setValues,
    radioSelected,
    setRadioSelected,
  ]

and this line: const [values, setValues] = useContext(GlobalContext); will destructure the value (an array) but there is a key difference between destructuring an array and an object:
with an array, the destructuring is by order( unlike an object which is by name), meaning:
that the values variable will hold the the first object { ...state }
which is not iteratable.

If Your value will be an object:

{
    state,
    changeState,
    values,
    setValues,
    radioSelected,
    setRadioSelected,
  }

and the useContext will be const {state,setValues} = useContext(GlobalContext);


问:
Autofit row height for specific range , then resize entire row height for each row ,as height of each cell after autofit on the cited range?
I need to Autofit row height only for specific range e.g ("B3:B8") But not autofit the entire row.

Autofit row height for specific range , then resize entire row height for each row ,depends on height of each cell after autofit on the cited range respectively.
On the below code , I did not use EntireRow but the code forcibly autofit entire row.

In advance, thanks for your help.

```<code>Sub AutoFit_Range()

    Dim rng As Range
     Set rng = ThisWorkbook.Sheets(1).Range("B3:B8")
         rng.Rows.AutoFit

End Sub
</code>```

答:
Here something.

```<code>Sub fitheightfromacell()

Range("B3:B8").Select
Selection.RowHeight = Range("B3").Height
Range("B3").Select
End Sub
</code>```

if want put specific height to b3:b8

you can do that too

```<code>Sub heightresize()

Range("B3:B8").Select
Selection.RowHeight = 30
Range("B3").Select
End Sub
</code>```

the 30 is the height you want manually.
if you want to take height from another cell, just uses the first code,

or autofit just selected rows

```<code>Sub autofitslectionrows()

Range("B3:B8").Select
Selection.Rows.AutoFit
Range("B3").Select
End Sub
</code>```

Body:
I need to Autofit row height only for specific range e.g ("B3:B8") But not autofit the entire row.

Autofit row height for specific range , then resize entire row height for each row ,depends on height of each cell after autofit on the cited range respectively.
On the below code , I did not use EntireRow but the code forcibly autofit entire row.

In advance, thanks for your help.

Sub AutoFit_Range()

    Dim rng As Range
     Set rng = ThisWorkbook.Sheets(1).Range("B3:B8")
         rng.Rows.AutoFit

End Sub

Body:
Here something.

Sub fitheightfromacell()

Range("B3:B8").Select
Selection.RowHeight = Range("B3").Height
Range("B3").Select
End Sub

if want put specific height to b3:b8

you can do that too

Sub heightresize()

Range("B3:B8").Select
Selection.RowHeight = 30
Range("B3").Select
End Sub

the 30 is the height you want manually.
if you want to take height from another cell, just uses the first code,

or autofit just selected rows

Sub autofitslectionrows()

Range("B3:B8").Select
Selection.Rows.AutoFit
Range("B3").Select
End Sub


问:
Change background image with styled-component
I want to change the backgroundImage dynamiclly, when i try it follow as, it did not work,but when i open the devtools in chrome, can show that background

```<code><RecommendWrapper>
     <RecommendItem imgUrl="../../static/banner.png" >
     </RecommendItem>
</RecommendWrapper>

export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background: url(${(props)=>props.imgUrl});
`;
</code>```

if i use like this,it can work,but can't change image dynamic.

```<code>import banner from "../../statics/banner.png"
export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background:url(${banner});
`;
</code>```

and if i use a network image(url likes "https://syean.cn/img/avatar.jpg") ,it also can work

答:
You should let the function in the background-image value return a string, url(your_image_link).</p>
```<code><RecommendWrapper>
     <RecommendItem imgUrl="img_link" >
     </RecommendItem>
</RecommendWrapper>

export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background: ${(props) => `url(${props.imgUrl})`};
</code>```

Body:
I want to change the backgroundImage dynamiclly, when i try it follow as, it did not work,but when i open the devtools in chrome, can show that background

<RecommendWrapper>
     <RecommendItem imgUrl="../../static/banner.png" >
     </RecommendItem>
</RecommendWrapper>

export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background: url(${(props)=>props.imgUrl});
`;

if i use like this,it can work,but can't change image dynamic.

import banner from "../../statics/banner.png"
export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background:url(${banner});
`;

and if i use a network image(url likes "https://syean.cn/img/avatar.jpg") ,it also can work

Body:
You should let the function in the background-image value return a string, url(your_image_link).

<RecommendWrapper>
     <RecommendItem imgUrl="img_link" >
     </RecommendItem>
</RecommendWrapper>

export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background: ${(props) => `url(${props.imgUrl})`};


问:
Writing recursive loop to calculate pressure in fortran
VERY new to fortran and feeling lost.
What I am trying to do is calculate pressure at water depth based on initial atmospheric pressure.
Then, each pressure will be based on the one previous to it.
Depth will increase by (-5) at each step.
The compiler does not like the notation of z(i)=(0:5:-50), which I intend to mean "jumps by -5 from 0 to -50.

This process needs to be repeated for 5 different initial atmospheric pressures.
What is the best way to then organize this info into columns to be printed?

Does this look like a reasonable way to go about accomplishing this goal?

Many thanks!

```<code>       program pressure
       real pk(11), zp(11), g, rz,z,dz, p_atm
       g= 9.81
       z(i)=(0:5:-50)
       dz= -5
       p_atm= (/0.97, 1.02, 1.04, 1.03, 1.01/)

       do
         i= 1,11
         d= z(i)

         if(d.GT.-10.0) then
           rz= 1020.0
         elseif(d.LT.-10.0 .and. d.GT.-50.0) then
           rz= 1020.0+(0.25*(ABS(d+10.0)))

         if d == 0
           p(i)= -(((-rz*g)*dz))+p_atm)
         else
           p(i)= -(((-rz*g)*dz))+p(i-1)

         endif

       open(20,file='pressure.txt', status='unknown')
       rewind(20)
       write(20,25) 'Model Day', '1', '2', '3', '4', '5'
       write(20,26) 'Patm (10^5 Pa)', '0.97', '1.02', '1.04', '1.03', '1.01'
  26   format(a14,12F9.2)
  25   format(a10,12F9.0)
</code>```

答:
Okay, let's go from the top.

Always use implicit none. If you don't use implicit none, you will get bugs.

Your indenting looks a bit like fixed-form fortran, but you're actually using free-form fortran (and we are in 2022, everyone should be using free-form fortran), so your indentation should really be consistent.

You don't have an end program line or an enddo line, presumably because this is just a snippet of code.

As VladimirF points out, the line do i=1,11 must be one line, not two.

Lets fix these first, to give

```<code>program pressure
  implicit none

  real pk(11), zp(11), g, rz,z,dz, p_atm

  g= 9.81
  z(i)=(0:5:-50)
  dz= -5
  p_atm= (/0.97, 1.02, 1.04, 1.03, 1.01/)

  do i= 1,11
    d= z(i)

    if(d.GT.-10.0) then
      rz= 1020.0
    elseif(d.LT.-10.0 .and. d.GT.-50.0) then
      rz= 1020.0+(0.25*(ABS(d+10.0)))

    if d == 0
      p(i)= -(((-rz*g)*dz))+p_atm)
    else
      p(i)= -(((-rz*g)*dz))+p(i-1)
    endif

    open(20,file='pressure.txt', status='unknown')
    rewind(20)
    write(20,25) 'Model Day', '1', '2', '3', '4', '5'
    write(20,26) 'Patm (10^5 Pa)', '0.97', '1.02', '1.04', '1.03', '1.01'
    26   format(a14,12F9.2)
    25   format(a10,12F9.0)
  enddo
end program
</code>```

Okay, now we can try compiling and see what happens. The compiler is going to shout at us for a number of reasons:

The variables i, d and p have not been declared.

z(i) either means a function call or an array element access (from context, you want the latter), but z is defined as a scalar variable, not a function or an array.

p_atm is being initialised as an array, but was declared as a scalar. You're also trying to add p_atm as a scalar, so let's add a loop over these pressures.

The if and endif statements don't match; you need to endif your first if block.

Your format strings don't match: you're printing character strings, but formatting them as floats ('0.97' is a character string, 0.97 is a float).

Your second if statement needs to have appropriate brackets and a then.

You close more brackets than you open in your first p(i)=... line. I'm going to have to guess here.

The comparison d==0 is a really bad idea. Never compare floats for equality. Let's replace this with i==1.

Okay, let's fix these problems:

```<code>program pressure
  implicit none

  real pk(11), zp(11), g, rz, z(11), dz, p_atm(5), p(11), d
  integer i,j

  g= 9.81
  z(i)=(0:5:-50)
  dz= -5
  p_atm= (/0.97, 1.02, 1.04, 1.03, 1.01/)

  do j=1,5
    do i= 1,11
      d= z(i)

      if(d.GT.-10.0) then
        rz= 1020.0
      elseif(d.LT.-10.0 .and. d.GT.-50.0) then
        rz= 1020.0+(0.25*(ABS(d+10.0)))
      endif

      if (i == 1) then
        p(i)= -(((-rz*g)*dz))+p_atm(j)
      else
        p(i)= -(((-rz*g)*dz))+p(i-1)
      endif

      open(20,file='pressure.txt', status='unknown')
      rewind(20)
      write(20,'(a14,5a9)') 'Model Day', '1', '2', '3', '4', '5'
      write(20,'(a14,5a9)') 'Patm (10^5 Pa)', '0.97', '1.02', '1.04', '1.03', '1.01'
    enddo
  enddo
end program
</code>```

Okay, now we get to initialising z. The most straightforward way of doing this is with a simple loop:

```<code>do i=1,11
  z(i) = 5-5*i
enddo
</code>```

but if you want to get fancy with it, you can use an implicit do loop:

```<code>z = [(5-5*i, i=1, 11)]
</code>```

Also, given your output file header, it probably makes sense to store p for all values of i and j, so let's make it a 2D array. Let's also move the file-writing to after we've calculated all values of p. Then, making a few modernisations along the way, your program looks like:

```<code>program pressure
  implicit none

  real :: pk(11), zp(11), g, rz, z(11), dz, p_atm(5), p(11,5), d
  integer :: i,j

  g = 9.81
  z = [(5-5*i, i=1, 11)]
  dz = -5
  p_atm = [0.97, 1.02, 1.04, 1.03, 1.01]

  do j=1,5
    do i=1,11
      d = z(i)

      if (d > -10.0) then
        rz = 1020.0
      elseif (d < -10.0 .and. d > -50.0) then
        rz = 1020.0 + 0.25*abs(d+10.0)
      endif

      if (i == 1) then
        p(i,j) = -(-rz*g*dz)+p_atm(j)
      else
        p(i,j) = -(-rz*g*dz)+p(i-1,j)
      endif
    enddo
  enddo

  open(20, file='pressure.txt', status='unknown')
  write(20,'(a14,5a9)') 'Model Day', '1', '2', '3', '4', '5'
  write(20,'(a14,5a9)') 'Patm (10^5 Pa)', '0.97', '1.02', '1.04', '1.03', '1.01'
  do i=1,11
    write(20,'(5f9.2)') p(i,:)
  enddo
  close(20)
end program
</code>```

Body:
VERY new to fortran and feeling lost.
What I am trying to do is calculate pressure at water depth based on initial atmospheric pressure.
Then, each pressure will be based on the one previous to it.
Depth will increase by (-5) at each step.
The compiler does not like the notation of z(i)=(0:5:-50), which I intend to mean "jumps by -5 from 0 to -50.

This process needs to be repeated for 5 different initial atmospheric pressures.
What is the best way to then organize this info into columns to be printed?

Does this look like a reasonable way to go about accomplishing this goal?

Many thanks!

       program pressure
       real pk(11), zp(11), g, rz,z,dz, p_atm
       g= 9.81
       z(i)=(0:5:-50)
       dz= -5
       p_atm= (/0.97, 1.02, 1.04, 1.03, 1.01/)

       do
         i= 1,11
         d= z(i)

         if(d.GT.-10.0) then
           rz= 1020.0
         elseif(d.LT.-10.0 .and. d.GT.-50.0) then
           rz= 1020.0+(0.25*(ABS(d+10.0)))

         if d == 0
           p(i)= -(((-rz*g)*dz))+p_atm)
         else
           p(i)= -(((-rz*g)*dz))+p(i-1)

         endif

       open(20,file='pressure.txt', status='unknown')
       rewind(20)
       write(20,25) 'Model Day', '1', '2', '3', '4', '5'
       write(20,26) 'Patm (10^5 Pa)', '0.97', '1.02', '1.04', '1.03', '1.01'
  26   format(a14,12F9.2)
  25   format(a10,12F9.0)

Body:
Okay, let's go from the top.

Always use implicit none. If you don't use implicit none, you will get bugs.

Your indenting looks a bit like fixed-form fortran, but you're actually using free-form fortran (and we are in 2022, everyone should be using free-form fortran), so your indentation should really be consistent.

You don't have an end program line or an enddo line, presumably because this is just a snippet of code.

As VladimirF points out, the line do i=1,11 must be one line, not two.

Lets fix these first, to give

program pressure
  implicit none

  real pk(11), zp(11), g, rz,z,dz, p_atm

  g= 9.81
  z(i)=(0:5:-50)
  dz= -5
  p_atm= (/0.97, 1.02, 1.04, 1.03, 1.01/)

  do i= 1,11
    d= z(i)

    if(d.GT.-10.0) then
      rz= 1020.0
    elseif(d.LT.-10.0 .and. d.GT.-50.0) then
      rz= 1020.0+(0.25*(ABS(d+10.0)))

    if d == 0
      p(i)= -(((-rz*g)*dz))+p_atm)
    else
      p(i)= -(((-rz*g)*dz))+p(i-1)
    endif

    open(20,file='pressure.txt', status='unknown')
    rewind(20)
    write(20,25) 'Model Day', '1', '2', '3', '4', '5'
    write(20,26) 'Patm (10^5 Pa)', '0.97', '1.02', '1.04', '1.03', '1.01'
    26   format(a14,12F9.2)
    25   format(a10,12F9.0)
  enddo
end program

Okay, now we can try compiling and see what happens. The compiler is going to shout at us for a number of reasons:

The variables i, d and p have not been declared.

z(i) either means a function call or an array element access (from context, you want the latter), but z is defined as a scalar variable, not a function or an array.

p_atm is being initialised as an array, but was declared as a scalar. You're also trying to add p_atm as a scalar, so let's add a loop over these pressures.

The if and endif statements don't match; you need to endif your first if block.

Your format strings don't match: you're printing character strings, but formatting them as floats ('0.97' is a character string, 0.97 is a float).

Your second if statement needs to have appropriate brackets and a then.

You close more brackets than you open in your first p(i)=... line. I'm going to have to guess here.

The comparison d==0 is a really bad idea. Never compare floats for equality. Let's replace this with i==1.

Okay, let's fix these problems:

program pressure
  implicit none

  real pk(11), zp(11), g, rz, z(11), dz, p_atm(5), p(11), d
  integer i,j

  g= 9.81
  z(i)=(0:5:-50)
  dz= -5
  p_atm= (/0.97, 1.02, 1.04, 1.03, 1.01/)

  do j=1,5
    do i= 1,11
      d= z(i)

      if(d.GT.-10.0) then
        rz= 1020.0
      elseif(d.LT.-10.0 .and. d.GT.-50.0) then
        rz= 1020.0+(0.25*(ABS(d+10.0)))
      endif

      if (i == 1) then
        p(i)= -(((-rz*g)*dz))+p_atm(j)
      else
        p(i)= -(((-rz*g)*dz))+p(i-1)
      endif

      open(20,file='pressure.txt', status='unknown')
      rewind(20)
      write(20,'(a14,5a9)') 'Model Day', '1', '2', '3', '4', '5'
      write(20,'(a14,5a9)') 'Patm (10^5 Pa)', '0.97', '1.02', '1.04', '1.03', '1.01'
    enddo
  enddo
end program

Okay, now we get to initialising z. The most straightforward way of doing this is with a simple loop:

do i=1,11
  z(i) = 5-5*i
enddo

but if you want to get fancy with it, you can use an implicit do loop:

z = [(5-5*i, i=1, 11)]

Also, given your output file header, it probably makes sense to store p for all values of i and j, so let's make it a 2D array. Let's also move the file-writing to after we've calculated all values of p. Then, making a few modernisations along the way, your program looks like:

program pressure
  implicit none

  real :: pk(11), zp(11), g, rz, z(11), dz, p_atm(5), p(11,5), d
  integer :: i,j

  g = 9.81
  z = [(5-5*i, i=1, 11)]
  dz = -5
  p_atm = [0.97, 1.02, 1.04, 1.03, 1.01]

  do j=1,5
    do i=1,11
      d = z(i)

      if (d > -10.0) then
        rz = 1020.0
      elseif (d < -10.0 .and. d > -50.0) then
        rz = 1020.0 + 0.25*abs(d+10.0)
      endif

      if (i == 1) then
        p(i,j) = -(-rz*g*dz)+p_atm(j)
      else
        p(i,j) = -(-rz*g*dz)+p(i-1,j)
      endif
    enddo
  enddo

  open(20, file='pressure.txt', status='unknown')
  write(20,'(a14,5a9)') 'Model Day', '1', '2', '3', '4', '5'
  write(20,'(a14,5a9)') 'Patm (10^5 Pa)', '0.97', '1.02', '1.04', '1.03', '1.01'
  do i=1,11
    write(20,'(5f9.2)') p(i,:)
  enddo
  close(20)
end program


问:
Drawing on bitmap vs directly on canvas
In my application I need to draw a large network (basically, little boxes connected with lines) and the user will be able to zoom and pan it around.

My first option was to draw the network directly to the canvas, but I thought that was not very efficient, because each time a pan event occurs, the drawing process begins again.

So I tried to use a large mutable bitmap and draw my entire network only once (or at least whenever zoom occurs), and blit the necessary areas to the canvas.

My problem is, since the network is rather big, I get OOM exception when creating the bitmap…

What should I do? Draw directly to the canvas? Use several smaller bitmaps?

Thanks,
Direz

答:
You're probably not going to like this, but if all you're doing is drawing boxes and lines, the efficiency of the canvas is going to be pretty dang high.  Are you getting UI lag or something?

One thing I have messed around with is drawing collections of subcomponents that won't change much or at all to a bitmap then rendering (scaling/moving aren't all that expensive if done at the right level) to the canvas can help efficiency.  I have tried in the past to create a framework for rendering a tile-like subset of an existing larger image, but did not meet much success.  I've made things work, but the code just gets ugly.

Oh, also a quick test to see if the component you are rendering is within the rectangle created by the screen can save you a bunch of processor time.

ContentLicense: CC BY-SA 3.0

Title: Drawing on bitmap vs directly on canvas


问:
.htaccess redirects not working on localhost
I have the following .htaccess which is supposed to open /index.php for ALL requests, regardless of whether the requested folder or file exists:

```<code>RewriteEngine On
RewriteRule . index.php [END]
</code>```

Unfortunately, this doesn't work on my localhost:

http://localhost:9000/file -> opens /index.php (GOOD)

http://localhost:9000/folder/file -> opens /index.php if /folder/ doesn't exist (GOOD)

http://localhost:9000/folder/file -> "Not Found" if /folder/ exists (BAD)

http://localhost:9000/file.php -> opens the file if it exists and gives a "Not Found" if it doesn't exist (BAD)

http://localhost:9000/folder/file.php -> opens the file if it exists and gives a "Not Found" if it doesn't exist (BAD)

My localhost is running on macOS via php -S localhost:9000 in Terminal.

答:
From the comments to the question I understand that you are not using an apache http server for this, but rely on the http server built into php itself (php -S localhost:9000).

Please note that ".htaccess" style files are apache configuration files. I doubt that the builtin server has any idea about the purpose of those files ...

Instead that builtin server offers a feature to route all requests through a router script:

```<code>php -S localhost:9000 index.php
</code>```

This is documented under "Example #3 Using a Router Script" in https://www.php.net/manual/en/features.commandline.webserver.php

Body:
I have the following .htaccess which is supposed to open /index.php for ALL requests, regardless of whether the requested folder or file exists:

RewriteEngine On
RewriteRule . index.php [END]

Unfortunately, this doesn't work on my localhost:

http://localhost:9000/file -> opens /index.php (GOOD)

http://localhost:9000/folder/file -> opens /index.php if /folder/ doesn't exist (GOOD)

http://localhost:9000/folder/file -> "Not Found" if /folder/ exists (BAD)

http://localhost:9000/file.php -> opens the file if it exists and gives a "Not Found" if it doesn't exist (BAD)

http://localhost:9000/folder/file.php -> opens the file if it exists and gives a "Not Found" if it doesn't exist (BAD)

My localhost is running on macOS via php -S localhost:9000 in Terminal.

Body:
From the comments to the question I understand that you are not using an apache http server for this, but rely on the http server built into php itself (php -S localhost:9000).

Please note that ".htaccess" style files are apache configuration files. I doubt that the builtin server has any idea about the purpose of those files ...

Instead that builtin server offers a feature to route all requests through a router script:

php -S localhost:9000 index.php

This is documented under "Example #3 Using a Router Script" in https://www.php.net/manual/en/features.commandline.webserver.php


问:
jQuery loop through all h3 and selects on page and format output in textarea
So I have a basic structure of a page and my corresponding script:

jQuery('select').change(function() {
  var abc = jQuery("select option:selected").text();
  var def = jQuery("h3").text();
  jQuery('textarea[name="ghi"]', $form).val(def + "\n\n" + abc).change();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<h3>Title</h3>
<select>
  <option value="A">This is Option a</option>
</select>

<h3>Title</h3>
<select>
  <option value="B">This is Option b</option>
</select></code>```

This outputs each as

```<code>Title Title This is Option a This is Option b
</code>```

Which I understand - but how do I get the textarea to output as

```<code>Title This is Option a
Title This is Option b
</code>```

Is that even possible?

答:
After adding textarea to your HTML and removing change event on select because it makes no sense this is working solution. You can use it for as many selects and H3s that you want.

let abc = [];
let def = [];
$("select option:selected").each(function(el) {
  abc.push($(this).text())
});
$("h3").each(function(el) {
  def.push($(this).text())
});
for(let i = 0; i < abc.length; i++) {
  let text = $('textarea[name="ghi"]').val();
  $('textarea[name="ghi"]').val(text + def[i] + ' ' + abc[i] + '\n').change();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Title</h3>
<select><option value="A">This is Option a</option></select>

<h3>Title</h3>
<select><option value="B">This is Option b</option></select>
<textarea name='ghi'></textarea></code>```

And now this is solution with change event on select. But for this solution you will have to add at least one more option to both selects:

$('select').change(function() {
  $('textarea[name="ghi"]').val('').change(); //setting text area to ''
  let abc = [];
  let def = [];
  $("select option:selected").each(function(el) {
    abc.push($(this).text())
  });
  $("h3").each(function(el) {
    def.push($(this).text())
  });
  for(let i = 0; i < abc.length; i++) {
    let text = $('textarea[name="ghi"]').val();
    $('textarea[name="ghi"]').val(text + def[i] + ' ' + abc[i] + '\n').change();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Title</h3>
<select>
  <option value="A">This is Option a</option>
  <option value="B">This is Option b</option>
</select>

<h3>Title</h3>
<select>
  <option value="A">This is Option a</option>
  <option value="B">This is Option b</option>

</select>
<textarea name='ghi'></textarea></code>```

Body:
So I have a basic structure of a page and my corresponding script:

jQuery('select').change(function() {
  var abc = jQuery("select option:selected").text();
  var def = jQuery("h3").text();
  jQuery('textarea[name="ghi"]', $form).val(def + "\n\n" + abc).change();
});

Title

<select>
  <option value="A">This is Option a</option>
</select>

Title

<select>
  <option value="B">This is Option b</option>
</select>

This outputs each as

Title Title This is Option a This is Option b

Which I understand - but how do I get the textarea to output as

Title This is Option a
Title This is Option b

Is that even possible?

Body:
After adding textarea to your HTML and removing change event on select because it makes no sense this is working solution. You can use it for as many selects and H3s that you want.

let abc = [];
let def = [];
$("select option:selected").each(function(el) {
  abc.push($(this).text())
});
$("h3").each(function(el) {
  def.push($(this).text())
});
for(let i = 0; i < abc.length; i++) {
  let text = $('textarea[name="ghi"]').val();
  $('textarea[name="ghi"]').val(text + def[i] + ' ' + abc[i] + '\n').change();
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Title</h3>
<select><option value="A">This is Option a</option></select>

<h3>Title</h3>
<select><option value="B">This is Option b</option></select>
<textarea name='ghi'></textarea>

And now this is solution with change event on select. But for this solution you will have to add at least one more option to both selects:

$('select').change(function() {
  $('textarea[name="ghi"]').val('').change(); //setting text area to ''
  let abc = [];
  let def = [];
  $("select option:selected").each(function(el) {
    abc.push($(this).text())
  });
  $("h3").each(function(el) {
    def.push($(this).text())
  });
  for(let i = 0; i < abc.length; i++) {
    let text = $('textarea[name="ghi"]').val();
    $('textarea[name="ghi"]').val(text + def[i] + ' ' + abc[i] + '\n').change();
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Title</h3>
<select>
  <option value="A">This is Option a</option>
  <option value="B">This is Option b</option>
</select>

<h3>Title</h3>
<select>
  <option value="A">This is Option a</option>
  <option value="B">This is Option b</option>

</select>
<textarea name='ghi'></textarea>


问:
Can Maven be made less verbose?
Maven spews out far too many lines of output to my taste (I like the Unix way: no news is good news).

I want to get rid of all [INFO] lines, but I couldn't find any mention of an argument or config settings that controls the verbosity of Maven.

Is there no LOG4J-like way to set the log level?

答: Use the -q or --quiet command-line options</p>

OwnerDisplayName: Asaf Bartov

Title: Can Maven be made less verbose?

OwnerDisplayName: Sietse de Kaper

ContentLicense: CC BY-SA 2.5


问:
Represent number as currenct from paragraph
On my web page I have an paragraph which looks like this:

```<code><p class="article-content mb-1" id="cost"><strong>Cost [Euro]: </strong>1000000</p>
</code>```

Number is always something else (which I read from db and represent using Django forms) and I would like to represent it as currency (in this case 1.000.000).
I tried to get the value with:

function on_load() {
  var a = document.getElementById('cost').value;
  console.log(a)
}
on_load();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="article-content mb-1" id="cost"><strong>Cost [Euro]: </strong>1000000</p></code>```

but Console output is: 'undefined'. When I get value, I'll use something like

```<code>(12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');  // 12,345.67
</code>```

To convert to currency.

答:
p does not have a  value attribute. You can do this to get and format the number using intl number format

function on_load() {
  const costs = document.querySelector('#cost');
  let number = costs.childNodes[1].textContent;
  costs.childNodes[1].textContent = new Intl.NumberFormat('de-DE').format(number);
}
on_load();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="article-content mb-1" id="cost"><strong>Cost [Euro]: </strong>1000000</p></code>```

Body:
On my web page I have an paragraph which looks like this:

Cost [Euro]: 1000000

Number is always something else (which I read from db and represent using Django forms) and I would like to represent it as currency (in this case 1.000.000).
I tried to get the value with:

function on_load() {
  var a = document.getElementById('cost').value;
  console.log(a)
}
on_load();

Cost [Euro]: 1000000

but Console output is: 'undefined'. When I get value, I'll use something like

(12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');  // 12,345.67

To convert to currency.

Body:
p does not have a  value attribute. You can do this to get and format the number using intl number format

function on_load() {
  const costs = document.querySelector('#cost');
  let number = costs.childNodes[1].textContent;
  costs.childNodes[1].textContent = new Intl.NumberFormat('de-DE').format(number);
}
on_load();

<p class="article-content mb-1" id="cost"><strong>Cost [Euro]: </strong>1000000</p>


问:
How to remove the space under the bottom pill gesture bar Android?
How do I get rid of this tiny black space under the bottom "gesture bar"? Most apps extend all the way to the bottom, but I still see this tiny black bar on the bottom.

Main Activity XML

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="com.myProject.fragments.SignUpFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout="@layout/sign_up_fragment" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
As I know you can't remove this bar but you can make that transparent

here a little hack of code

Method 1

```<code>this.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

</code>```

as this will make your screen full and a transparent its a little hack but you can try this

here what above code does make your screen full screen and the gesture will be transparent an you will get your desire output

Method 2

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window w = getWindow(); // in Activity's onCreate() for instance
        w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }
</code>```

In your style change like this

```<code><resources>
<style name="Theme" parent="android:Theme.Material.Wallpaper.NoTitleBar">
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:navigationBarColor">@android:color/transparent</item>
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
</style>
</code>```

And in your activity where you want full screen to main layout give this flag

```<code>android:fitsSystemWindows="true"
</code>```

Method 3

This code is not mine i have taken from the some website i forgot from where i have taken but give refrence soon

Here A funtion to make tranparent

```<code>fun Activity.transparentStatusAndNavigation(
    systemUiScrim: Int = Color.parseColor("#40000000") // 25% black
) {
    var systemUiVisibility = 0
    // Use a dark scrim by default since light status is API 23+
    var statusBarColor = systemUiScrim
    //  Use a dark scrim by default since light nav bar is API 27+
    var navigationBarColor = systemUiScrim
    val winParams = window.attributes

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        systemUiVisibility = systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        statusBarColor = Color.TRANSPARENT
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        systemUiVisibility = systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
        navigationBarColor = Color.TRANSPARENT
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        systemUiVisibility = systemUiVisibility or
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        window.decorView.systemUiVisibility = systemUiVisibility
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        winParams.flags = winParams.flags or
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        winParams.flags = winParams.flags and
                (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or
                        WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION).inv()
        window.statusBarColor = statusBarColor
        window.navigationBarColor = navigationBarColor
    }

    window.attributes = winParams
}
</code>```

Hope this helps

Body:
How do I get rid of this tiny black space under the bottom "gesture bar"? Most apps extend all the way to the bottom, but I still see this tiny black bar on the bottom.

Main Activity XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="com.myProject.fragments.SignUpFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout="@layout/sign_up_fragment" />
</androidx.constraintlayout.widget.ConstraintLayout>

Body:
As I know you can't remove this bar but you can make that transparent

here a little hack of code

Method 1

this.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

as this will make your screen full and a transparent its a little hack but you can try this

here what above code does make your screen full screen and the gesture will be transparent an you will get your desire output

Method 2

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window w = getWindow(); // in Activity's onCreate() for instance
        w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

In your style change like this

<resources>
<style name="Theme" parent="android:Theme.Material.Wallpaper.NoTitleBar">
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:navigationBarColor">@android:color/transparent</item>
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
</style>

And in your activity where you want full screen to main layout give this flag

android:fitsSystemWindows="true"

Method 3

This code is not mine i have taken from the some website i forgot from where i have taken but give refrence soon

Here A funtion to make tranparent

fun Activity.transparentStatusAndNavigation(
    systemUiScrim: Int = Color.parseColor("#40000000") // 25% black
) {
    var systemUiVisibility = 0
    // Use a dark scrim by default since light status is API 23+
    var statusBarColor = systemUiScrim
    //  Use a dark scrim by default since light nav bar is API 27+
    var navigationBarColor = systemUiScrim
    val winParams = window.attributes

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        systemUiVisibility = systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        statusBarColor = Color.TRANSPARENT
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        systemUiVisibility = systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
        navigationBarColor = Color.TRANSPARENT
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        systemUiVisibility = systemUiVisibility or
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        window.decorView.systemUiVisibility = systemUiVisibility
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        winParams.flags = winParams.flags or
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        winParams.flags = winParams.flags and
                (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or
                        WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION).inv()
        window.statusBarColor = statusBarColor
        window.navigationBarColor = navigationBarColor
    }

    window.attributes = winParams
}

Hope this helps


问:
How to connect to alfresco using Alfresco api?
I'm following this tutorial: https://www.alfresco.com/abn/adf/docs/tutorials/working-with-data-table/

here is my mydatatable.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { AlfrescoApiService } from '@alfresco/adf-core';
import { ObjectDataTableAdapter, ObjectDataRow } from '@alfresco/adf-core';

@Component({
  selector: 'app-mydatatable',
  templateUrl: './mydatatable.component.html',
  styleUrls: ['./mydatatable.component.scss']
})
export class MydatatableComponent implements OnInit {

  data = new ObjectDataTableAdapter([],[]);

  constructor(private apiService: AlfrescoApiService) {

    let api: any = this.apiService.getInstance();
  //   let api2: any = this.apiService;

  api.webScript.executeWebScript(
    'GET',
    'people',
    [],
    null,
    '/alfresco/api/-default-/public/alfresco/versions/1',
    null
 ).then(
    (response: any) => {
       let results = [];
       for (var entry of response.list.entries) {
          results.push({
             id: entry.entry.id,
             firstName: entry.entry.firstName,
             lastName: entry.entry.lastName,
             status: 'green',
             icon: 'material-icons://accessibility'
          });
       }
       this.data.setRows(results.map(item => {
          return new ObjectDataRow(item);
       }));
    }
 );

}

  ngOnInit(): void {

  }

  onRowClick(event: any) {
    alert('We just clicked row id: ' + event.value.obj.status);
  }

}
</code>```

and mydatatable.component.html

```<code><adf-datatable

(rowClick)="onRowClick($event)"
  [data]="data">
  <data-columns>
    <data-column
      key="icon"
      type="image"
        [sortable]="false">
      </data-column>
    <data-column
      key="firstName"
      title="First Name">
    </data-column>
    <data-column
      key="lastName"
      title="Last Name"
      class="full-width name-column">
    </data-column>
    <data-column key="status" title="Status">
        <ng-template let-entry="$implicit">
          <span *ngIf="entry.data.getValue(entry.row, entry.col) == 'red'" style="background-color: red; width: 20px; height: 20px"></span>
          <span *ngIf="entry.data.getValue(entry.row, entry.col) == 'green'" style="background-color: green; width: 20px; height: 20px"></span>
        </ng-template>
      </data-column>

  </data-columns>
</adf-datatable>

</code>```

when I compile I get nothing on the http://localhost:4200/mydatatable. However in the console I get this error:

```<code>core.js:4442 ERROR TypeError: Cannot read properties of undefined (reading 'executeWebScript')
    at new MydatatableComponent (mydatatable.component.ts:22)
    at NodeInjectorFactory.MydatatableComponent_Factory [as factory] (mydatatable.component.ts:55)
    at getNodeInjectable (core.js:4274)
    at instantiateRootComponent (core.js:8026)
    at createRootComponent (core.js:13542)
    at ComponentFactory$1.create (core.js:24101)
    at ViewContainerRef.createComponent (core.js:10205)
    at RouterOutlet.activateWith (router.js:5178)
    at RouterOutlet.ngOnInit (router.js:5114)
    at callHook (core.js:3281)
</code>```

and this is my app.config.json:

```<code>{
 "$schema": "../node_modules/@alfresco/adf-core/app.config.schema.json",
 "ecmHost": "{protocol}//{hostname}{:port}",
 "bpmHost": "{protocol}//{hostname}{:port}",
 "providers": "ALL",
 "authType": "BASIC",
 "identityHost": "{protocol}//{hostname}{:port}/auth/realms/alfresco",
 "oauth2": {
   "host": "{protocol}//{hostname}{:port}/auth/realms/alfresco",
   "clientId": "alfresco",
   "scope": "openid",
   "secret": "",
   "implicitFlow": true,
   "silentLogin": true,
   "redirectSilentIframeUri": "{protocol}//{hostname}{:port}/assets/silent-refresh.html",
   "redirectUri": "/",
   "redirectUriLogout": "/logout"
 },
 "application": {
   "name": "GED ADF"
 },
 "languages": [
   {
     "key": "en",
     "label": "English"
   },
   {
     "key": "fr",
     "label": "French"
   },
   {
     "key": "de",
     "label": "German"
   },
   {
     "key": "it",
     "label": "Italian"
   },
   {
     "key": "es",
     "label": "Spanish"
   },
   {
     "key": "ja",
     "label": "Japanese"
   },
   {
     "key": "nl",
     "label": "Dutch"
   },
   {
     "key": "pt-BR",
     "label": "Brazilian Portuguese"
   },
   {
     "key": "nb",
     "label": "Norwegian"
   },
   {
     "key": "ru",
     "label": "Russian"
   },
   {
     "key": "zh-CN",
     "label": "Simplified Chinese"
   }
 ],
 "logLevel": "trace"
}

</code>```

PS: when I try the same url on postman it works
I'm using node v14.17.1 and npm 8.3.2

What could be the problem, and how I can fix it

Thank you in advance

答:
You can use below way:

By using AlfrescoApiService

constructor(private apiService: AlfrescoApiService) {
this.apiService.getInstance().webScripti.executeWebScript('GET',
'api/task-instances?authority=' +   this.authService.getEcmUsername())
}

https://www.alfresco.com/abn/adf/docs/core/services/people-content.service/

Body:
I'm following this tutorial: https://www.alfresco.com/abn/adf/docs/tutorials/working-with-data-table/

here is my mydatatable.component.ts

import { Component, OnInit } from '@angular/core';
import { AlfrescoApiService } from '@alfresco/adf-core';
import { ObjectDataTableAdapter, ObjectDataRow } from '@alfresco/adf-core';

@Component({
  selector: 'app-mydatatable',
  templateUrl: './mydatatable.component.html',
  styleUrls: ['./mydatatable.component.scss']
})
export class MydatatableComponent implements OnInit {

  data = new ObjectDataTableAdapter([],[]);

  constructor(private apiService: AlfrescoApiService) {

    let api: any = this.apiService.getInstance();
  //   let api2: any = this.apiService;

  api.webScript.executeWebScript(
    'GET',
    'people',
    [],
    null,
    '/alfresco/api/-default-/public/alfresco/versions/1',
    null
 ).then(
    (response: any) => {
       let results = [];
       for (var entry of response.list.entries) {
          results.push({
             id: entry.entry.id,
             firstName: entry.entry.firstName,
             lastName: entry.entry.lastName,
             status: 'green',
             icon: 'material-icons://accessibility'
          });
       }
       this.data.setRows(results.map(item => {
          return new ObjectDataRow(item);
       }));
    }
 );

}

  ngOnInit(): void {

  }

  onRowClick(event: any) {
    alert('We just clicked row id: ' + event.value.obj.status);
  }

}

and mydatatable.component.html

<adf-datatable

(rowClick)="onRowClick($event)"
  [data]="data">
  <data-columns>
    <data-column
      key="icon"
      type="image"
        [sortable]="false">
      </data-column>
    <data-column
      key="firstName"
      title="First Name">
    </data-column>
    <data-column
      key="lastName"
      title="Last Name"
      class="full-width name-column">
    </data-column>
    <data-column key="status" title="Status">
        <ng-template let-entry="$implicit">

        </ng-template>
      </data-column>

  </data-columns>
</adf-datatable>

when I compile I get nothing on the http://localhost:4200/mydatatable. However in the console I get this error:

core.js:4442 ERROR TypeError: Cannot read properties of undefined (reading 'executeWebScript')
    at new MydatatableComponent (mydatatable.component.ts:22)
    at NodeInjectorFactory.MydatatableComponent_Factory [as factory] (mydatatable.component.ts:55)
    at getNodeInjectable (core.js:4274)
    at instantiateRootComponent (core.js:8026)
    at createRootComponent (core.js:13542)
    at ComponentFactory$1.create (core.js:24101)
    at ViewContainerRef.createComponent (core.js:10205)
    at RouterOutlet.activateWith (router.js:5178)
    at RouterOutlet.ngOnInit (router.js:5114)
    at callHook (core.js:3281)

and this is my app.config.json:

{
 "$schema": "../node_modules/@alfresco/adf-core/app.config.schema.json",
 "ecmHost": "{protocol}//{hostname}{:port}",
 "bpmHost": "{protocol}//{hostname}{:port}",
 "providers": "ALL",
 "authType": "BASIC",
 "identityHost": "{protocol}//{hostname}{:port}/auth/realms/alfresco",
 "oauth2": {
   "host": "{protocol}//{hostname}{:port}/auth/realms/alfresco",
   "clientId": "alfresco",
   "scope": "openid",
   "secret": "",
   "implicitFlow": true,
   "silentLogin": true,
   "redirectSilentIframeUri": "{protocol}//{hostname}{:port}/assets/silent-refresh.html",
   "redirectUri": "/",
   "redirectUriLogout": "/logout"
 },
 "application": {
   "name": "GED ADF"
 },
 "languages": [
   {
     "key": "en",
     "label": "English"
   },
   {
     "key": "fr",
     "label": "French"
   },
   {
     "key": "de",
     "label": "German"
   },
   {
     "key": "it",
     "label": "Italian"
   },
   {
     "key": "es",
     "label": "Spanish"
   },
   {
     "key": "ja",
     "label": "Japanese"
   },
   {
     "key": "nl",
     "label": "Dutch"
   },
   {
     "key": "pt-BR",
     "label": "Brazilian Portuguese"
   },
   {
     "key": "nb",
     "label": "Norwegian"
   },
   {
     "key": "ru",
     "label": "Russian"
   },
   {
     "key": "zh-CN",
     "label": "Simplified Chinese"
   }
 ],
 "logLevel": "trace"
}

PS: when I try the same url on postman it works
I'm using node v14.17.1 and npm 8.3.2

What could be the problem, and how I can fix it

Thank you in advance


问:
How to find all the .txt file in the li tag need multiple time clicks using python selenium
anyone know how to find all the .txt file in the li tag using python selenium, this action requires multiple time clicks to reveal the folder content. I have tried to use the  all links by all_links = driver.find_elements_by_tag_name('a'). Then, using the for loop to see the return {for link in all_links:
print（link.get_attribute('href')）}. However, from the return, it seems it just finished one time click. So the directory that contains .txt files was not revealed.

I have tried to search the related answer but it seems that I have not found for my question; could anyone help me? Pls let me know if I am overlooked when there is the answer already.

the web page and .txt file that want to be scraped
the return using python selenium

答: I addressed it by parsing the url's patterns of these .txt files with Python request and bs4. Another idea could be to use Python Scrapy.</p>


问:
Google Sheet SUMIFS formula returning 0?
I have a SUMIFS formula in Google Sheets which is the following:

=SUMIFS('AWIN MASTER'!$AW:$AW,'AWIN MASTER'!$AT:$AT,">=" &A101,'AWIN MASTER'!$AT:$AT,"<" &A102)

This formula is the sum of a cost on another sheet, when the date is between two dates on the current sheet.

which is returning 0 when it shouldn't... it's working for my other formula but not mine... Could someone help please?

答:
I found that it was because of formatting through IMPORTRANGE

Thank you all for your help!


问:
Problem updating multi-row
table:ProductComapny

field:NameProduct

NameProduct

1

1

1

4

5

i want update fields NameProduct where NameProduct= 1 to(NameProduct=1,NameProduct=2,NameProduct=3

how can this work??

result

NameProduct

1

2

3

4

5

答:
```<code>var source = new int[] {1,1,1,4,5};
var result = source.Select( (val,i) => val==1 ? i : val );
</code>```

Title: Problem updating multi-row


问:
EF core Scaffold-DbContext doesn't work : Execution Timeout Expired
I'm trying to scaffold Models from an existing database.

```<code>Scaffold-DbContext "connectionString" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
</code>```

But I got this error:

Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

All required packages are installed (tried another connection string and it's working)

Tried (Connect timeout 15000 and Connection timeout 15000)

I can connect with the same connection string via Sql Server management / VS Server explorer

Any ideas?

答:
As far as I know there is no solution at the moment.
The SQL Server connection string does not allow to define the command timeout, but only the connection timeout.
I solved it using the --schema dbo option, which eliminated a dozen tables that have another schema, and now it works.
But for how long?

My code:

```<code>dotnet ef dbcontext scaffold "SERVER=.;DATABASE=dbstore0;Integrated Security=SSPI;Connection Timeout=300;TrustServerCertificate=True" Microsoft.EntityFrameworkCore.SqlServer -f -o DbStore\Models --context-dir DbStore\Contexts -c DbStoreContext -p Store.Domain.csproj --no-pluralize --schema dbo
</code>```

Body:
I'm trying to scaffold Models from an existing database.

Scaffold-DbContext "connectionString" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

But I got this error:

Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

All required packages are installed (tried another connection string and it's working)

Tried (Connect timeout 15000 and Connection timeout 15000)

I can connect with the same connection string via Sql Server management / VS Server explorer

Any ideas?

Body:
As far as I know there is no solution at the moment.
The SQL Server connection string does not allow to define the command timeout, but only the connection timeout.
I solved it using the --schema dbo option, which eliminated a dozen tables that have another schema, and now it works.
But for how long?

My code:

dotnet ef dbcontext scaffold "SERVER=.;DATABASE=dbstore0;Integrated Security=SSPI;Connection Timeout=300;TrustServerCertificate=True" Microsoft.EntityFrameworkCore.SqlServer -f -o DbStore\Models --context-dir DbStore\Contexts -c DbStoreContext -p Store.Domain.csproj --no-pluralize --schema dbo


问:
Strapi: Warning an error occurred while requesting the API
I've been struggling for hours trying to install Strapi on my Ubuntu server.

Ubuntu:  20.04

nodejs:  v14.19.0

npm:     6.14.16

strapi:  4

```<code>npx create-strapi-app@latest my-project --quickinstall
</code>```

All the installation process goes seamlessly but when I go to http://mydomain:1337/admin in order to create a first user I get this warning:

an error occurred while requesting the API.

I know this problem has been encountered several times but none of the suggested solutions have helped me so far.
I also found this error in the Chrome console but I'm not not sure it's related to the my problem:

main.815f1087.js:2 Refused to connect to
'http://localhost:1337/admin/project-type' because it violates the
following Content Security Policy directive: "connect-src 'self'
https:".

Any idea ?

答:
You need to build the app. Read this github issue

Run: npm run build or yarn build or strapi build depending on what you are using

Body:
I've been struggling for hours trying to install Strapi on my Ubuntu server.

Ubuntu:  20.04

nodejs:  v14.19.0

npm:     6.14.16

strapi:  4

npx create-strapi-app@latest my-project --quickinstall

All the installation process goes seamlessly but when I go to http://mydomain:1337/admin in order to create a first user I get this warning:

an error occurred while requesting the API.

I know this problem has been encountered several times but none of the suggested solutions have helped me so far.
I also found this error in the Chrome console but I'm not not sure it's related to the my problem:

main.815f1087.js:2 Refused to connect to
'http://localhost:1337/admin/project-type' because it violates the
following Content Security Policy directive: "connect-src 'self'
https:".

Any idea ?


问:
Chain Max and Where in Linq
Given this code:

```<code>Book[] books = new Book[3]
    {
        new Book("100", "Title1"),
        new Book("200", "Title2"),
        new Book("200", "Title3"),
    };

getBookWithMostPages() {
    var max = books.Max(book => book.pages);
    return books.FirstOrDefault((book) => book.pages == max);
}
</code>```

Is it possible (there is any documented way) to chain Max and FirstOrDefault and return the same result ?

答:
You can sort the array and return the first value:</p>
```<code>return books.OrderByDescending(book => book.pages)
            .FirstOrDefault();
</code>```

Title: Chain Max and Where in Linq

Body:
Given this code:

Book[] books = new Book[3]
    {
        new Book("100", "Title1"),
        new Book("200", "Title2"),
        new Book("200", "Title3"),
    };

getBookWithMostPages() {
    var max = books.Max(book => book.pages);
    return books.FirstOrDefault((book) => book.pages == max);
}

Is it possible (there is any documented way) to chain Max and FirstOrDefault and return the same result ?

Body:
You can sort the array and return the first value:

return books.OrderByDescending(book => book.pages)
            .FirstOrDefault();


问:
LINQ Compare TimeSpan
in my database a have rows like

And in my Blazor app i need to find the match if the clock is 15 minutes before TimeStart AND 15 minuttes before TimeEnd.

If the clock is between 9.45 and 10.45 I want RowID 27

If the clock is between 10.45 and 11.45 I want RowID 28

I have tried:

```<code> IEnumerable<Overview> mydata = from a in overview
    where (a.Timestart > Minus15Min &&
           a.Timeend.Value.Subtract(new TimeSpan(00, 15, 00)) > Minus15Min)
    select a;
</code>```

答:
Your problem is very symmetrical about Start and End but your code treats them differently. Also, you have two > for a range, that is very doubtful.

How about

```<code>var nowPlus15 = DateTime.Now.AddMinutes(15);
IEnumerable<Overview> mydata = from a in overview
    where (a.Timestart <= nowPlus15  &&
           a.Timeend > nowPlus15)
    select a;
</code>```

Title: LINQ Compare TimeSpan

Body:
in my database a have rows like

And in my Blazor app i need to find the match if the clock is 15 minutes before TimeStart AND 15 minuttes before TimeEnd.

If the clock is between 9.45 and 10.45 I want RowID 27

If the clock is between 10.45 and 11.45 I want RowID 28

I have tried:

 IEnumerable<Overview> mydata = from a in overview
    where (a.Timestart > Minus15Min &&
           a.Timeend.Value.Subtract(new TimeSpan(00, 15, 00)) > Minus15Min)
    select a;

Body:
Your problem is very symmetrical about Start and End but your code treats them differently. Also, you have two > for a range, that is very doubtful.

How about

var nowPlus15 = DateTime.Now.AddMinutes(15);
IEnumerable<Overview> mydata = from a in overview
    where (a.Timestart <= nowPlus15  &&
           a.Timeend > nowPlus15)
    select a;