问:
Array initialization error while passing length value from one Activity to another
I am new in Android Development.
I am passing a value (int type) from an Activity using Intent.

```<code>Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("length", length);  //value is taken from a edit text
startActivity(intent);
</code>```

And then in NewActivity, I added this code in onCreate() method.

```<code>arrayLength = getIntent().getIntExtra("length", 0);  //int type arrayLength variabel is diclared globally.
</code>```

And then I am trying to initialize an array on NewActivity (out of function)as:

```<code>char[] array = new char[arrayLength];
</code>```

And then I added array elements in a loop and try to show in a TextView using a Button.
But it crashes my apps when I click on the Button to show array elements with this line of code :

```<code>arrayElemtsShow.setText(new String (array));
</code>```

But if I initialize this array with a constant like below, it works fine.

```<code>char[] array = new char[20];
</code>```

But its important to initialize this array using the value of previous Activity.
What can I do to fix this?
And why this is happening?

Logcat:

```<code>> 2020-06-03 08:43:41.449 30912-30912/? I/.aam.secretnam: Late-enabling
> -Xcheck:jni 2020-06-03 08:43:41.721 30912-30912/com.aam.secretname I/Perf: Connecting to perf service. 2020-06-03 08:43:41.836
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method
> Landroid/graphics/drawable/Drawable;->getOpticalInsets()Landroid/graphics/Insets;
> (light greylist, linking) 2020-06-03 08:43:41.836
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> field Landroid/graphics/Insets;->left:I (light greylist, linking)
> 2020-06-03 08:43:41.836 30912-30912/com.aam.secretname
> W/.aam.secretnam: Accessing hidden field
> Landroid/graphics/Insets;->right:I (light greylist, linking)
> 2020-06-03 08:43:41.836 30912-30912/com.aam.secretname
> W/.aam.secretnam: Accessing hidden field
> Landroid/graphics/Insets;->top:I (light greylist, linking) 2020-06-03
> 08:43:41.836 30912-30912/com.aam.secretname W/.aam.secretnam:
> Accessing hidden field Landroid/graphics/Insets;->bottom:I (light
> greylist, linking) 2020-06-03 08:43:41.970
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method
> Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z
> (light greylist, reflection) 2020-06-03 08:43:41.973
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V
> (light greylist, reflection) 2020-06-03 08:43:41.986
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method
> Landroid/widget/TextView;->getTextDirectionHeuristic()Landroid/text/TextDirectionHeuristic;
> (light greylist, linking) 2020-06-03 08:43:42.217
> 30912-30938/com.aam.secretname I/Adreno: QUALCOMM build
> : 4e21c4c, I21281c58c8
>     Build Date                       : 03/01/19
>     OpenGL ES Shader Compiler Version: EV031.25.03.02
>     Local Branch                     :
>     Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.7.5.R1.09.00.00.464.039
>     Remote Branch                    : NONE
>     Reconstruct Branch               : NOTHING 2020-06-03 08:43:42.217 30912-30938/com.aam.secretname I/Adreno: Build Config
> : S L 6.0.7 AArch32 2020-06-03 08:43:42.222
> 30912-30938/com.aam.secretname I/Adreno: PFP: 0x005ff110, ME:
> 0x005ff066 2020-06-03 08:43:42.227 30912-30938/com.aam.secretname
> I/ConfigStore:
> android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay
> retrieved: 0 2020-06-03 08:43:42.227 30912-30938/com.aam.secretname
> I/ConfigStore:
> android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay
> retrieved: 0 2020-06-03 08:43:42.227 30912-30938/com.aam.secretname
> I/OpenGLRenderer: Initialized EGL, version 1.4 2020-06-03 08:43:42.227
> 30912-30938/com.aam.secretname D/OpenGLRenderer: Swap behavior 2
> 2020-06-03 08:43:42.370 30912-30912/com.aam.secretname
> I/AssistStructure: Flattened final assist data: 2924 bytes, containing
> 1 windows, 10 views 2020-06-03 08:43:46.687
> 30912-30912/com.aam.secretname I/Timeline: Timeline:
> Activity_launch_request time:527917018 2020-06-03 08:43:46.728
> 30912-30912/com.aam.secretname W/ActivityThread:
> handleWindowVisibility: no activity for token
> android.os.BinderProxy@22a035f 2020-06-03 08:43:51.641
> 30912-30912/com.aam.secretname D/AndroidRuntime: Shutting down VM
> 2020-06-03 08:43:51.645 30912-30912/com.aam.secretname
> E/AndroidRuntime: FATAL EXCEPTION: main
>     Process: com.aam.secretname, PID: 30912
>     java.lang.IllegalStateException: Could not execute method for android:onClick
>         at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
>         at android.view.View.performClick(View.java:6608)
>         at android.view.View.performClickInternal(View.java:6585)
>         at android.view.View.access$3100(View.java:785)
>         at android.view.View$PerformClick.run(View.java:25919)
>         at android.os.Handler.handleCallback(Handler.java:873)
>         at android.os.Handler.dispatchMessage(Handler.java:99)
>         at android.os.Looper.loop(Looper.java:201)
>         at android.app.ActivityThread.main(ActivityThread.java:6826)
>         at java.lang.reflect.Method.invoke(Native Method)
>         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
>         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
>      Caused by: java.lang.reflect.InvocationTargetException
>         at java.lang.reflect.Method.invoke(Native Method)
>         at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
>         at android.view.View.performClick(View.java:6608)
>         at android.view.View.performClickInternal(View.java:6585)
>         at android.view.View.access$3100(View.java:785)
>         at android.view.View$PerformClick.run(View.java:25919)
>         at android.os.Handler.handleCallback(Handler.java:873)
>         at android.os.Handler.dispatchMessage(Handler.java:99)
>         at android.os.Looper.loop(Looper.java:201)
>         at android.app.ActivityThread.main(ActivityThread.java:6826)
>         at java.lang.reflect.Method.invoke(Native Method)
>         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
>         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
>      Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
>         at com.aam.secretname.FirstInput.getLineNumbers(FirstInput.java:71)
>         at com.aam.secretname.FirstInput.line3(FirstInput.java:57)
>         at java.lang.reflect.Method.invoke(Native Method)
>         at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
>         at android.view.View.performClick(View.java:6608)
>         at android.view.View.performClickInternal(View.java:6585)
>         at android.view.View.access$3100(View.java:785)
>         at android.view.View$PerformClick.run(View.java:25919)
>         at android.os.Handler.handleCallback(Handler.java:873)
>         at android.os.Handler.dispatchMessage(Handler.java:99)
>         at android.os.Looper.loop(Looper.java:201)
>         at android.app.ActivityThread.main(ActivityThread.java:6826)
>         at java.lang.reflect.Method.invoke(Native Method)
>         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
>         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
</code>```

first class xml

```<code>    <TextView
        android:id="@+id/textView5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="serif-monospace"
        android:gravity="center"
        android:padding="4dp"
        android:text="@string/length"
        android:textColor="#66B1F3"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.243" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:autofillHints=""
        android:ems="10"
        android:background="@drawable/stroke"
        android:gravity="center"
        android:hint="@string/Enterlength"
        android:inputType="textPersonName"
        android:textColor="#FFFFFF"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView5"
        app:layout_constraintVertical_bias="0.122" />

    <Button
        android:id="@+id/button2"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="44dp"
        android:onClick="nextOnClick"
        android:text="@string/btnnext"
        android:background="@drawable/radius_button"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.491"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/btnexample"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:background="@drawable/radius_button"
        android:fontFamily="serif"
        android:text="@string/examplebtn"
        android:visibility="invisible"
        android:textAllCaps="false"
        android:textSize="18sp"
        android:onClick="exampleOnClick"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.781"
        app:layout_constraintStart_toStartOf="parent" />

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

Second class 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"
    android:background="@drawable/gradient_background">

    <TextView
        android:id="@+id/textView6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="4dp"
        android:text="@string/instruction"
        android:textColor="#2E183E"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line1"
        android:text="@string/alphabet_1"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView7" />

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line6"
        android:text="@string/alphabet_6"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button5"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line5"
        android:text="@string/alphabet_5"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button6" />

    <Button
        android:id="@+id/button6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line4"
        android:text="@string/alphabet_4"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button7" />

    <Button
        android:id="@+id/button7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line3"
        android:text="@string/alphabet_3"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button8" />

    <Button
        android:id="@+id/button8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line2"
        android:text="@string/alphabet_2"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button3" />

    <Button
        android:id="@+id/button9"
        android:layout_width="150sp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/radius_button"
        android:onClick="nextOnClick"
        android:text="@string/btnnext"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/stroke"
        android:gravity="center"
        android:hint="@string/line_numbers"
        android:padding="2dp"
        android:textColor="#fff"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView6" />

    <Button
        android:id="@+id/button10"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginBottom="4dp"
        android:background="@drawable/back_button"
        android:onClick="reset"
        android:text="@string/reset"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button20"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/radius_button"
        android:fontFamily="serif"
        android:text="@string/examplebtn"
        android:textAllCaps="false"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/button9"
        app:layout_constraintEnd_toEndOf="parent" />

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

First class

```<code>package com.aam.secretname;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LengthActivity extends AppCompatActivity {
    //variables
    int length = 0;
    Intent intent;

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

    public void nextOnClick(View view) {
        getLength();
        if ((length > 0) && (length < 20)) {
            intent = new Intent(LengthActivity.this, FirstInput.class);
            intent.putExtra("length", length);   //sending value in second activity
            startActivity(intent);
        }
    }

    public void exampleOnClick(View view) {
        TextView showInfo = (TextView) findViewById(R.id.textView5);
        Button example = (Button) findViewById(R.id.btnexample);
        showInfo.setText(R.string.example);
        example.setVisibility(View.INVISIBLE);
    }

    private void getLength() {
        try {
            EditText wordLength = (EditText) findViewById(R.id.editText);
            int tempLength = Integer.parseInt(wordLength.getText().toString());

            if ((tempLength<20) && (tempLength>0)) {
                length = tempLength;
            }
            else {
                TextView showInfo = (TextView) findViewById(R.id.textView5);
                showInfo.setTextColor(Color.RED);

                if (tempLength == 0) showInfo.setText(R.string.warningOfLenthZero);
                else showInfo.setText(R.string.warningOfLengthLimitation);
            }
        }
        catch (Exception e){
            TextView showInfo = (TextView) findViewById(R.id.textView5);
            Button example = (Button) findViewById(R.id.btnexample);
            showInfo.setTextColor(Color.RED);

            showInfo.setText(R.string.instuctForGivingLength);
            example.setVisibility(View.VISIBLE);
        }
    }
}
</code>```

Second Class

```<code>package com.aam.secretname;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Arrays;

public class FirstInput extends AppCompatActivity {
    //variables
    int wordLength;
    static int count = 0;
    char[] lineNumbers = new char[wordLength]; //problem
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_input);
        wordLength = getIntent().getIntExtra("length", 0);  //receiving value of previous activity
    }

    public void nextOnClick(View view) {
        intent = new Intent(FirstInput.this, FinalInput.class);
        if (lineNumbers[wordLength - 1] != '\0'){
            intent.putExtra("lineNumbers", new String(lineNumbers));
            intent.putExtra("length", wordLength);
            startActivity(intent);
        }
        else {
            TextView warning = (TextView) findViewById(R.id.textView6);
            warning.setTextColor(Color.RED);
            warning.setText(R.string.instuctionForTappingOnLine);
        }
    }

    public void reset(View view) {
        count = 0;
        Arrays.fill(lineNumbers, '\0');
        Toast.makeText(this, "Reseted", Toast.LENGTH_SHORT ).show();
        TextView showLineNumbers = (TextView) findViewById(R.id.textView7);
        showLineNumbers.setText("");
    }

    public void line1(View v){
        getLineNumbers('1');
    }
    public void line2(View v){
        getLineNumbers('2');
    }
    public void line3(View v){
        getLineNumbers('3');
    }
    public void line4(View v){
        getLineNumbers('4');
    }
    public void line5(View v){
        getLineNumbers('5');
    }
    public void line6(View v){
        getLineNumbers('6');
    }

    private void getLineNumbers(char line) {
        if(count < wordLength){
            lineNumbers[count++] = line;
            TextView showLineNumbers = (TextView) findViewById(R.id.textView7);
            showLineNumbers.setText(new String(lineNumbers));
        }
        else{
            TextView showInfo = (TextView) findViewById(R.id.textView6);
            showInfo.setText(R.string.completedInput);
        }
    }
}
</code>```

答:
You should provide the exception logcat; but I guess you you missed converting the String to int when you take the value from the EditText

```<code>intent.putExtra("length", Integer.parseInt(length));
</code>```

UPDATE:

The problem your problem is that you are initializing the lineNumbers array as a member with 0 values; that is because the default int value in java is 0.

So, when you use below declaration statement you are assigning a 0-length value to the lineNumbers array because wordLength is s till 0; so what you need to do is to do this assignment after you getIntent().getIntExtra() value.

To do that in code (notice the change marked with // <<<<<<<<<<<< Change here)

```<code>public class FirstInput extends AppCompatActivity {
    //variables
    int wordLength;
    static int count = 0;
    char[] lineNumbers; // <<<<<<<<<<<<<<<< Change here
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_input);
        wordLength = getIntent().getIntExtra("length", 0);  //receiving value of previous activity
         lineNumbers = new char[wordLength] // <<<<<<<<<<<<<<< Change here
    }

....
</code>```

Body:
I am new in Android Development.
I am passing a value (int type) from an Activity using Intent.

Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("length", length);  //value is taken from a edit text
startActivity(intent);

And then in NewActivity, I added this code in onCreate() method.

arrayLength = getIntent().getIntExtra("length", 0);  //int type arrayLength variabel is diclared globally.

And then I am trying to initialize an array on NewActivity (out of function)as:

char[] array = new char[arrayLength];

And then I added array elements in a loop and try to show in a TextView using a Button.
But it crashes my apps when I click on the Button to show array elements with this line of code :

arrayElemtsShow.setText(new String (array));

But if I initialize this array with a constant like below, it works fine.

char[] array = new char[20];

But its important to initialize this array using the value of previous Activity.
What can I do to fix this?
And why this is happening?

Logcat:

> 2020-06-03 08:43:41.449 30912-30912/? I/.aam.secretnam: Late-enabling
> -Xcheck:jni 2020-06-03 08:43:41.721 30912-30912/com.aam.secretname I/Perf: Connecting to perf service. 2020-06-03 08:43:41.836
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method
> Landroid/graphics/drawable/Drawable;->getOpticalInsets()Landroid/graphics/Insets;
> (light greylist, linking) 2020-06-03 08:43:41.836
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> field Landroid/graphics/Insets;->left:I (light greylist, linking)
> 2020-06-03 08:43:41.836 30912-30912/com.aam.secretname
> W/.aam.secretnam: Accessing hidden field
> Landroid/graphics/Insets;->right:I (light greylist, linking)
> 2020-06-03 08:43:41.836 30912-30912/com.aam.secretname
> W/.aam.secretnam: Accessing hidden field
> Landroid/graphics/Insets;->top:I (light greylist, linking) 2020-06-03
> 08:43:41.836 30912-30912/com.aam.secretname W/.aam.secretnam:
> Accessing hidden field Landroid/graphics/Insets;->bottom:I (light
> greylist, linking) 2020-06-03 08:43:41.970
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method
> Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z
> (light greylist, reflection) 2020-06-03 08:43:41.973
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V
> (light greylist, reflection) 2020-06-03 08:43:41.986
> 30912-30912/com.aam.secretname W/.aam.secretnam: Accessing hidden
> method
> Landroid/widget/TextView;->getTextDirectionHeuristic()Landroid/text/TextDirectionHeuristic;
> (light greylist, linking) 2020-06-03 08:43:42.217
> 30912-30938/com.aam.secretname I/Adreno: QUALCOMM build
> : 4e21c4c, I21281c58c8
>     Build Date                       : 03/01/19
>     OpenGL ES Shader Compiler Version: EV031.25.03.02
>     Local Branch                     :
>     Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.7.5.R1.09.00.00.464.039
>     Remote Branch                    : NONE
>     Reconstruct Branch               : NOTHING 2020-06-03 08:43:42.217 30912-30938/com.aam.secretname I/Adreno: Build Config
> : S L 6.0.7 AArch32 2020-06-03 08:43:42.222
> 30912-30938/com.aam.secretname I/Adreno: PFP: 0x005ff110, ME:
> 0x005ff066 2020-06-03 08:43:42.227 30912-30938/com.aam.secretname
> I/ConfigStore:
> android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay
> retrieved: 0 2020-06-03 08:43:42.227 30912-30938/com.aam.secretname
> I/ConfigStore:
> android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay
> retrieved: 0 2020-06-03 08:43:42.227 30912-30938/com.aam.secretname
> I/OpenGLRenderer: Initialized EGL, version 1.4 2020-06-03 08:43:42.227
> 30912-30938/com.aam.secretname D/OpenGLRenderer: Swap behavior 2
> 2020-06-03 08:43:42.370 30912-30912/com.aam.secretname
> I/AssistStructure: Flattened final assist data: 2924 bytes, containing
> 1 windows, 10 views 2020-06-03 08:43:46.687
> 30912-30912/com.aam.secretname I/Timeline: Timeline:
> Activity_launch_request time:527917018 2020-06-03 08:43:46.728
> 30912-30912/com.aam.secretname W/ActivityThread:
> handleWindowVisibility: no activity for token
> android.os.BinderProxy@22a035f 2020-06-03 08:43:51.641
> 30912-30912/com.aam.secretname D/AndroidRuntime: Shutting down VM
> 2020-06-03 08:43:51.645 30912-30912/com.aam.secretname
> E/AndroidRuntime: FATAL EXCEPTION: main
>     Process: com.aam.secretname, PID: 30912
>     java.lang.IllegalStateException: Could not execute method for android:onClick
>         at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
>         at android.view.View.performClick(View.java:6608)
>         at android.view.View.performClickInternal(View.java:6585)
>         at android.view.View.access$3100(View.java:785)
>         at android.view.View$PerformClick.run(View.java:25919)
>         at android.os.Handler.handleCallback(Handler.java:873)
>         at android.os.Handler.dispatchMessage(Handler.java:99)
>         at android.os.Looper.loop(Looper.java:201)
>         at android.app.ActivityThread.main(ActivityThread.java:6826)
>         at java.lang.reflect.Method.invoke(Native Method)
>         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
>         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
>      Caused by: java.lang.reflect.InvocationTargetException
>         at java.lang.reflect.Method.invoke(Native Method)
>         at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
>         at android.view.View.performClick(View.java:6608)
>         at android.view.View.performClickInternal(View.java:6585)
>         at android.view.View.access$3100(View.java:785)
>         at android.view.View$PerformClick.run(View.java:25919)
>         at android.os.Handler.handleCallback(Handler.java:873)
>         at android.os.Handler.dispatchMessage(Handler.java:99)
>         at android.os.Looper.loop(Looper.java:201)
>         at android.app.ActivityThread.main(ActivityThread.java:6826)
>         at java.lang.reflect.Method.invoke(Native Method)
>         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
>         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
>      Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
>         at com.aam.secretname.FirstInput.getLineNumbers(FirstInput.java:71)
>         at com.aam.secretname.FirstInput.line3(FirstInput.java:57)
>         at java.lang.reflect.Method.invoke(Native Method)
>         at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
>         at android.view.View.performClick(View.java:6608)
>         at android.view.View.performClickInternal(View.java:6585)
>         at android.view.View.access$3100(View.java:785)
>         at android.view.View$PerformClick.run(View.java:25919)
>         at android.os.Handler.handleCallback(Handler.java:873)
>         at android.os.Handler.dispatchMessage(Handler.java:99)
>         at android.os.Looper.loop(Looper.java:201)
>         at android.app.ActivityThread.main(ActivityThread.java:6826)
>         at java.lang.reflect.Method.invoke(Native Method)
>         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
>         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

first class xml

    <TextView
        android:id="@+id/textView5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="serif-monospace"
        android:gravity="center"
        android:padding="4dp"
        android:text="@string/length"
        android:textColor="#66B1F3"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.243" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:autofillHints=""
        android:ems="10"
        android:background="@drawable/stroke"
        android:gravity="center"
        android:hint="@string/Enterlength"
        android:inputType="textPersonName"
        android:textColor="#FFFFFF"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView5"
        app:layout_constraintVertical_bias="0.122" />

    <Button
        android:id="@+id/button2"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="44dp"
        android:onClick="nextOnClick"
        android:text="@string/btnnext"
        android:background="@drawable/radius_button"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.491"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/btnexample"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:background="@drawable/radius_button"
        android:fontFamily="serif"
        android:text="@string/examplebtn"
        android:visibility="invisible"
        android:textAllCaps="false"
        android:textSize="18sp"
        android:onClick="exampleOnClick"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.781"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Second class 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"
    android:background="@drawable/gradient_background">

    <TextView
        android:id="@+id/textView6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="4dp"
        android:text="@string/instruction"
        android:textColor="#2E183E"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line1"
        android:text="@string/alphabet_1"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView7" />

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line6"
        android:text="@string/alphabet_6"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button5"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line5"
        android:text="@string/alphabet_5"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button6" />

    <Button
        android:id="@+id/button6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line4"
        android:text="@string/alphabet_4"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button7" />

    <Button
        android:id="@+id/button7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line3"
        android:text="@string/alphabet_3"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button8" />

    <Button
        android:id="@+id/button8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/line_button_background"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:onClick="line2"
        android:text="@string/alphabet_2"
        android:textColor="@color/line_color"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button3" />

    <Button
        android:id="@+id/button9"
        android:layout_width="150sp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/radius_button"
        android:onClick="nextOnClick"
        android:text="@string/btnnext"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:background="@drawable/stroke"
        android:gravity="center"
        android:hint="@string/line_numbers"
        android:padding="2dp"
        android:textColor="#fff"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView6" />

    <Button
        android:id="@+id/button10"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginBottom="4dp"
        android:background="@drawable/back_button"
        android:onClick="reset"
        android:text="@string/reset"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button20"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/radius_button"
        android:fontFamily="serif"
        android:text="@string/examplebtn"
        android:textAllCaps="false"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/button9"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

First class

package com.aam.secretname;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LengthActivity extends AppCompatActivity {
    //variables
    int length = 0;
    Intent intent;

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

    public void nextOnClick(View view) {
        getLength();
        if ((length > 0) && (length < 20)) {
            intent = new Intent(LengthActivity.this, FirstInput.class);
            intent.putExtra("length", length);   //sending value in second activity
            startActivity(intent);
        }
    }

    public void exampleOnClick(View view) {
        TextView showInfo = (TextView) findViewById(R.id.textView5);
        Button example = (Button) findViewById(R.id.btnexample);
        showInfo.setText(R.string.example);
        example.setVisibility(View.INVISIBLE);
    }

    private void getLength() {
        try {
            EditText wordLength = (EditText) findViewById(R.id.editText);
            int tempLength = Integer.parseInt(wordLength.getText().toString());

            if ((tempLength<20) && (tempLength>0)) {
                length = tempLength;
            }
            else {
                TextView showInfo = (TextView) findViewById(R.id.textView5);
                showInfo.setTextColor(Color.RED);

                if (tempLength == 0) showInfo.setText(R.string.warningOfLenthZero);
                else showInfo.setText(R.string.warningOfLengthLimitation);
            }
        }
        catch (Exception e){
            TextView showInfo = (TextView) findViewById(R.id.textView5);
            Button example = (Button) findViewById(R.id.btnexample);
            showInfo.setTextColor(Color.RED);

            showInfo.setText(R.string.instuctForGivingLength);
            example.setVisibility(View.VISIBLE);
        }
    }
}

Second Class

package com.aam.secretname;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Arrays;

public class FirstInput extends AppCompatActivity {
    //variables
    int wordLength;
    static int count = 0;
    char[] lineNumbers = new char[wordLength]; //problem
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_input);
        wordLength = getIntent().getIntExtra("length", 0);  //receiving value of previous activity
    }

    public void nextOnClick(View view) {
        intent = new Intent(FirstInput.this, FinalInput.class);
        if (lineNumbers[wordLength - 1] != '\0'){
            intent.putExtra("lineNumbers", new String(lineNumbers));
            intent.putExtra("length", wordLength);
            startActivity(intent);
        }
        else {
            TextView warning = (TextView) findViewById(R.id.textView6);
            warning.setTextColor(Color.RED);
            warning.setText(R.string.instuctionForTappingOnLine);
        }
    }

    public void reset(View view) {
        count = 0;
        Arrays.fill(lineNumbers, '\0');
        Toast.makeText(this, "Reseted", Toast.LENGTH_SHORT ).show();
        TextView showLineNumbers = (TextView) findViewById(R.id.textView7);
        showLineNumbers.setText("");
    }

    public void line1(View v){
        getLineNumbers('1');
    }
    public void line2(View v){
        getLineNumbers('2');
    }
    public void line3(View v){
        getLineNumbers('3');
    }
    public void line4(View v){
        getLineNumbers('4');
    }
    public void line5(View v){
        getLineNumbers('5');
    }
    public void line6(View v){
        getLineNumbers('6');
    }

    private void getLineNumbers(char line) {
        if(count < wordLength){
            lineNumbers[count++] = line;
            TextView showLineNumbers = (TextView) findViewById(R.id.textView7);
            showLineNumbers.setText(new String(lineNumbers));
        }
        else{
            TextView showInfo = (TextView) findViewById(R.id.textView6);
            showInfo.setText(R.string.completedInput);
        }
    }
}

Body:
You should provide the exception logcat; but I guess you you missed converting the String to int when you take the value from the EditText

intent.putExtra("length", Integer.parseInt(length));

UPDATE:

The problem your problem is that you are initializing the lineNumbers array as a member with 0 values; that is because the default int value in java is 0.

So, when you use below declaration statement you are assigning a 0-length value to the lineNumbers array because wordLength is s till 0; so what you need to do is to do this assignment after you getIntent().getIntExtra() value.

To do that in code (notice the change marked with // <<<<<<<<<<<< Change here)

public class FirstInput extends AppCompatActivity {
    //variables
    int wordLength;
    static int count = 0;
    char[] lineNumbers; // <<<<<<<<<<<<<<<< Change here
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_input);
        wordLength = getIntent().getIntExtra("length", 0);  //receiving value of previous activity
         lineNumbers = new char[wordLength] // <<<<<<<<<<<<<<< Change here
    }

....


来源: stackexchange

问:
Azure ACR task not able to pull the docker image from Azure container registry
I am following this article.
I have an Azure container registry as shown below image and I have defined the task as below.

```<code>az acr task create \
--name krushnaTask \
--registry krushna \
--cmd python-hello \
--schedule "1 10 * * *" \
--context /dev/null
</code>```

When the Azure is running the task it is giving below error :

```<code>2020/06/02 11:02:03 Alias support enabled for version >= 1.1.0, please see https://aka.ms/acr/tasks/task-aliases for more information.
2020/06/02 11:02:03 Creating Docker network: acb_default_network, driver: 'bridge'
2020/06/02 11:02:03 Successfully set up Docker network: acb_default_network
2020/06/02 11:02:03 Setting up Docker configuration...
2020/06/02 11:02:04 Successfully set up Docker configuration
2020/06/02 11:02:04 Logging in to registry: krushna.azurecr.io
2020/06/02 11:02:05 Successfully logged into krushna.azurecr.io
2020/06/02 11:02:05 Executing step ID: acb_step_0. Timeout(sec): 3600, Working directory: '', Network: 'acb_default_network'
2020/06/02 11:02:05 Launching container with name: acb_step_0
Unable to find image 'python-hello:latest' locally
docker: Error response from daemon: pull access denied for python-hello, repository does not   exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
2020/06/02 11:02:05 Container failed during run: acb_step_0. No retries remaining.
failed to run step ID: acb_step_0: exit status 125
</code>```

What can be done so the ACR task can access the docker image?

答:
I'm pretty sure the problem is that you need to input the image as krushna.azurecr.io/python-hello:tag since the image is in your ACR. When you input the image as python-hello, it means it's a public docker image in Docker hub, so it caused the error because it cannot find the image in the Docker hub. Change the command like below and it will work well:

```<code>az acr task create \
--name krushnaTask \
--registry krushna \
--cmd krushna.azurecr.io/python-hello \
--schedule "1 10 * * *" \
--context /dev/null
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am following this article.
I have an Azure container registry as shown below image and I have defined the task as below.

az acr task create \
--name krushnaTask \
--registry krushna \
--cmd python-hello \
--schedule "1 10 * * *" \
--context /dev/null

When the Azure is running the task it is giving below error :

2020/06/02 11:02:03 Alias support enabled for version >= 1.1.0, please see https://aka.ms/acr/tasks/task-aliases for more information.
2020/06/02 11:02:03 Creating Docker network: acb_default_network, driver: 'bridge'
2020/06/02 11:02:03 Successfully set up Docker network: acb_default_network
2020/06/02 11:02:03 Setting up Docker configuration...
2020/06/02 11:02:04 Successfully set up Docker configuration
2020/06/02 11:02:04 Logging in to registry: krushna.azurecr.io
2020/06/02 11:02:05 Successfully logged into krushna.azurecr.io
2020/06/02 11:02:05 Executing step ID: acb_step_0. Timeout(sec): 3600, Working directory: '', Network: 'acb_default_network'
2020/06/02 11:02:05 Launching container with name: acb_step_0
Unable to find image 'python-hello:latest' locally
docker: Error response from daemon: pull access denied for python-hello, repository does not   exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
2020/06/02 11:02:05 Container failed during run: acb_step_0. No retries remaining.
failed to run step ID: acb_step_0: exit status 125

What can be done so the ACR task can access the docker image?

Body:
I'm pretty sure the problem is that you need to input the image as krushna.azurecr.io/python-hello:tag since the image is in your ACR. When you input the image as python-hello, it means it's a public docker image in Docker hub, so it caused the error because it cannot find the image in the Docker hub. Change the command like below and it will work well:

az acr task create \
--name krushnaTask \
--registry krushna \
--cmd krushna.azurecr.io/python-hello \
--schedule "1 10 * * *" \
--context /dev/null


问:
Is there a Javascript support library for html5 file API and upload?
until now I was using flash based swfupload and its swfupload.js which provides users with callbacks from flash and a possibility to set it up.

I was wondering if there is anything like this for HTML5 File API. I'm asking before I make it from scratch myself. I don't want to reinvent a wheel when there might be a good library out there already.

答:
Plupload:

http://www.plupload.com

Has a total of 6 runtimes.

ContentLicense: CC BY-SA 3.0


问:
How to add class to header element if its href is contained within window href?
My current code applies a class to the proper header element if its href is an indexOf the window.location.href

```<code>$(function() {
    $('.sidebar-links li.active').removeClass("active");
    $('.sidebar-links li a').filter(function(){
        return this.href.indexOf(window.location.href) !== -1;
            }).parent().addClass("active");
});
</code>```

An example header href would be

http://localhost:8090/website/jobs.php

If my window.location.href matches that exactly, it works great. The issue that I am running into is, if I click on something that produces a query string like

http://localhost:8090/website/jobs.php?info=54

Then refresh the page, the header element no longer has the class.
Is it possible to change the function so that if the header element's href  is contained within the window.location.href that it will add the class? Or without the query string at all?

http://localhost:8090/website/jobs.php

http://localhost:8090/website/jobs.php?info=54

答:
You can remove the URL parameters using: url.replace(/\?.*/,'')

In your code, change this.href.indexOf(window.location.href) !== -1 to this.href.indexOf(window.location.href.replace(/\?.*/,'')) !== -1

Body:
My current code applies a class to the proper header element if its href is an indexOf the window.location.href

$(function() {
    $('.sidebar-links li.active').removeClass("active");
    $('.sidebar-links li a').filter(function(){
        return this.href.indexOf(window.location.href) !== -1;
            }).parent().addClass("active");
});

An example header href would be

http://localhost:8090/website/jobs.php

If my window.location.href matches that exactly, it works great. The issue that I am running into is, if I click on something that produces a query string like

http://localhost:8090/website/jobs.php?info=54

Then refresh the page, the header element no longer has the class.
Is it possible to change the function so that if the header element's href  is contained within the window.location.href that it will add the class? Or without the query string at all?

http://localhost:8090/website/jobs.php

http://localhost:8090/website/jobs.php?info=54


问:
Fetch from two APIs in loop and combine
I'm trying to do what I thought would be pretty straightforward, but is turning out to be pretty hard. Essentially what I want to do is when loading the page, loop through an array of IDs, make a call to two APIs for each ID, merge the responses together for each ID, and save that to a React state variable itemList.

This is the code I have so far. The two getInfo() and getOtherInfo() functions are doing a basic JavaScript Fetch and are returning a Promise and then the decoded JSON data asynchronously no problem. I can even display the returned data on the page as it gets loaded, so that part works fine.

```<code>useEffect(() => {
  idList.forEach((id) => {
    getInfo(id)
      .then((response) => {
        getOtherInfo(id).then((otherReponse) => {
          response.otherInfo = otherResponse;
        });
        setItemList((itemList) => [...itemList, response]);
      })
      .catch((error) => console.log("Loading failed: " + error));
  });
}, []);
</code>```

I know that the nested .then() is wrong, as it's trying to add response data to a potentially unresolved Promise, but it's my first time using React Hooks and the Fetch API so I'm not sure what the right way to do it is. I've found a couple other similar questions, but they don't seem to deal with joining the data together after it gets returned from the two APIs.

Can someone point me in the right direction here?

答:
Try this</p>

```<code>var promiseArr = [];
idList.forEach((id) => {
  promiseArr.push(getInfo(id));
    promiseArr.push(getOtherInfo(id));
});

Promise.all(promiseArr).then((resp) => {
   console.log(resp);
}).catch((error) => console.log("Loading failed: " + error));
</code>```

Title: Fetch from two APIs in loop and combine

Body:
I'm trying to do what I thought would be pretty straightforward, but is turning out to be pretty hard. Essentially what I want to do is when loading the page, loop through an array of IDs, make a call to two APIs for each ID, merge the responses together for each ID, and save that to a React state variable itemList.

This is the code I have so far. The two getInfo() and getOtherInfo() functions are doing a basic JavaScript Fetch and are returning a Promise and then the decoded JSON data asynchronously no problem. I can even display the returned data on the page as it gets loaded, so that part works fine.

useEffect(() => {
  idList.forEach((id) => {
    getInfo(id)
      .then((response) => {
        getOtherInfo(id).then((otherReponse) => {
          response.otherInfo = otherResponse;
        });
        setItemList((itemList) => [...itemList, response]);
      })
      .catch((error) => console.log("Loading failed: " + error));
  });
}, []);

I know that the nested .then() is wrong, as it's trying to add response data to a potentially unresolved Promise, but it's my first time using React Hooks and the Fetch API so I'm not sure what the right way to do it is. I've found a couple other similar questions, but they don't seem to deal with joining the data together after it gets returned from the two APIs.

Can someone point me in the right direction here?

Body:
Try this

var promiseArr = [];
idList.forEach((id) => {
  promiseArr.push(getInfo(id));
    promiseArr.push(getOtherInfo(id));
});

Promise.all(promiseArr).then((resp) => {
   console.log(resp);
}).catch((error) => console.log("Loading failed: " + error));


问:
Get comma separated string from Mysql
I'm saving a string from PHP to MySQL like this..

```<code>$groupid = "13, 14, 15, 16"
$write = mysql_query("INSERT INTO table VALUES ('','$groupid')");
</code>```

I'm then trying to extract data from the table if $a = "15"

```<code>$extract = mysql_query("SELECT * FROM table WHERE ustaffid='$ustaffid' AND groupid='$a'");
</code>```

How can I easily match what's in $groupid to $a, while extracting it? Can I do that with MySQL?

答:
```<code>SELECT *
FROM table
WHERE ustaffid='$ustaffid'
AND groupid LIKE '%$a,%'
</code>```

But you have to end your string with a comma at the end.

Title: Get comma separated string from Mysql

Body:
I'm saving a string from PHP to MySQL like this..

$groupid = "13, 14, 15, 16"
$write = mysql_query("INSERT INTO table VALUES ('','$groupid')");

I'm then trying to extract data from the table if $a = "15"

$extract = mysql_query("SELECT * FROM table WHERE ustaffid='$ustaffid' AND groupid='$a'");

How can I easily match what's in $groupid to $a, while extracting it? Can I do that with MySQL?

Body:
SELECT *
FROM table
WHERE ustaffid='$ustaffid'
AND groupid LIKE '%$a,%'

But you have to end your string with a comma at the end.


问:
if cardNumberArray[0] == 4: IndexError: list index out of range
Just started learning python and I'm trying to print different things based on the user's input, however, when I run the code I get this error:

```<code>    if cardNumberArray[0] == 4:
    IndexError: list index out of range
</code>```

I don't understand why when a number of 14-16 integers is inputted, the program says that cardNumberArray[0] is out of range, and why my program won't even print the different values given the below code.

```<code>cardNumber = input("what is the number?\n")
cardNumberArray = []

for i in cardNumberArray:
  cardNumberArray.append(int(i))
  print(f"Ith value: {cardNumberArray[i]}")

if cardNumberArray[0] == 4:
    print("VISA")
elif cardNumberArray[0] == 5:
  if cardNumberArray[1] == 1 or cardNumberArray[1] == 2 or cardNumberArray[1] == 3 or cardNumberArray[1] == 4 or cardNumberArray[1] == 4 or cardNumberArray[1] == 5:
    print("MASTERCARD")
elif cardNumberArray[0] == 3:
  if cardNumberArray[1] == 4 or cardNumberArray[1] == 7:
    print("AMEX")
else:
  print("INVALID")
</code>```

答:
All this can be done much easier:</p>

```<code>cardNumber = input("what is the number?\n")
#cardNumberArray = []  <<-- don't need this

card_type = {
    '4' : 'VISA', '51' : 'MASTER', '52' : 'MASTER', '53' : 'MASTER',
   '54' : 'MASTER', '55' : 'MASTER', '34' : 'AMEX', '37' : 'AMEX'
}

cc_type = 'INVALID'
for ct in card_type :
    if cardNumber.startswith(ct) :
        cc_type = card_type[ct]
        break

print( cc_type )
</code>```

Body:
Just started learning python and I'm trying to print different things based on the user's input, however, when I run the code I get this error:

    if cardNumberArray[0] == 4:
    IndexError: list index out of range

I don't understand why when a number of 14-16 integers is inputted, the program says that cardNumberArray[0] is out of range, and why my program won't even print the different values given the below code.

cardNumber = input("what is the number?\n")
cardNumberArray = []

for i in cardNumberArray:
  cardNumberArray.append(int(i))
  print(f"Ith value: {cardNumberArray[i]}")

if cardNumberArray[0] == 4:
    print("VISA")
elif cardNumberArray[0] == 5:
  if cardNumberArray[1] == 1 or cardNumberArray[1] == 2 or cardNumberArray[1] == 3 or cardNumberArray[1] == 4 or cardNumberArray[1] == 4 or cardNumberArray[1] == 5:
    print("MASTERCARD")
elif cardNumberArray[0] == 3:
  if cardNumberArray[1] == 4 or cardNumberArray[1] == 7:
    print("AMEX")
else:
  print("INVALID")

Body:
All this can be done much easier:

cardNumber = input("what is the number?\n")
#cardNumberArray = []  <<-- don't need this

card_type = {
    '4' : 'VISA', '51' : 'MASTER', '52' : 'MASTER', '53' : 'MASTER',
   '54' : 'MASTER', '55' : 'MASTER', '34' : 'AMEX', '37' : 'AMEX'
}

cc_type = 'INVALID'
for ct in card_type :
    if cardNumber.startswith(ct) :
        cc_type = card_type[ct]
        break

print( cc_type )


问:
Row id not being passed properly to the modal popup
Ok I have an issue with my table its only getting the first records id passed to it. When I click the delete button the value

```<code><table class="table table-dark">
<thead>
    <tr>
        <th scope="col">Circuit name    </th>
        <th scope="col">Resistance </th>
        <th scope="col">Circuit type</th>
        <th scope="col">Passed</th>
        <th scope="col">Action </th>
    </tr>
</thead>
<tbody>
    @foreach (var item in Model) {
        var idx = 0;
        var tm = "#myModal" + item.Id;
        var mid = "myModal" + item.Id;
    <tr>
        <th scope="row">
            @Html.DisplayFor(modelItem => item.Name)
        </th>
        <td>@Html.DisplayFor(modelItem => item.Resitance)</td>
        <td>@Html.DisplayFor(modelItem => item.CirtcutType)</td>

        <td>
            @(item.Passed? "Yes": "No")

        </td>

        <td>

            <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myEditModal"><i class="fa fa-pencil"></i>  Edit</button>

            <button type="button" data-id="@item.Id" data-toggle="modal" class="btn btn-danger btn-lg" data-target="#deleteLink">
                <i class="fa fa-trash"></i>
                Delete
            </button>

            @{Html.RenderPartial("EditFormPartial",Model.Where(w=>w.Id==item.Id).FirstOrDefault());}

            <div id="deleteLink" class="modal fade" role="dialog">
                <div class="modal-dialog">
                    @using (Html.BeginForm("Delete", "Electrician", FormMethod.Post)) {
                        <!-- Modal content-->
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal">×</button>
                                <h4 class="modal-title">Delete Record!</h4>
                            </div>
                            <div class="modal-body">
                                Are you sure you wish to delete this record ?.
                                <!--this is how to pass the id through-->
                                <input type="text" name="linkId" value="@item.Id" />

                            </div>
                            <div class="modal-footer">

                                <button type="submit" id="btnSubmit" class="btn btn-danger"
                                        onclick="$('#testForm').submit()">
                                    Yes
                                </button>
                                <button class="btn btn-warning" data-dismiss="modal">No</button>
                            </div>
                        </div>
                    }
                </div>
            </div>
</code>```

The value here is only ever showing the first record id value of 15

```<code> <input type="text" name="linkId" value="@item.Id" />
</code>```

This is the javascript. How Do I ensure that im getting each id and not just the first one.

```<code><script>
  $('#deleteLink').on('show.bs.modal', function (e) {
    var dataId = $(this).attr("data-id");

});

function deleteConfirm()
{
    var url = "@Url.Action("Delete", "Electrician")/" + $("#Id").val();
    $.post(url).success(function () {
        location.href = "@Url.Action("Index", "Electrician")";
});
}
</code>```

答:
A simple way is to add a js function and pass the @item.Id to the function like below:

```<code>@model IEnumerable<Electrician>
<table class="table table-dark">
    <thead>
        <tr>
            <th scope="col">Circuit name    </th>
            <th scope="col">Resistance </th>
            <th scope="col">Circuit type</th>
            <th scope="col">Passed</th>
            <th scope="col">Action </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            var idx = 0;
            var tm = "#myModal" + item.Id;
            var mid = "myModal" + item.Id;
            <tr>
                <th scope="row">
                    @Html.DisplayFor(modelItem => item.Name)
                </th>
                <td>@Html.DisplayFor(modelItem => item.Resitance)</td>
                <td>@Html.DisplayFor(modelItem => item.CirtcutType)</td>
                <td>
                    @(item.Passed ? "Yes" : "No")
                </td>
                <td>
                    <button type="button" onclick="deleteModal(@item.Id)" data-id="@item.Id" data-toggle="modal" class="btn btn-danger btn-lg" data-target="#deleteLink">
                        <i class="fa fa-trash"></i>
                        Delete
                    </button>
                </td>
            </tr>
        }
    </tbody>
</table>
<div id="deleteLink" class="modal fade" role="dialog">
    <div class="modal-dialog">
        @using (Html.BeginForm("Delete", "Electrician", FormMethod.Post))
        {
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">Delete Record!</h4>
                </div>
                <div class="modal-body">
                    Are you sure you wish to delete this record ?.
                    <!--this is how to pass the id through-->
                    <input type="text" name="linkId"  id="linkId"/>

                </div>
                <div class="modal-footer">

                    <button type="submit" id="btnSubmit" class="btn btn-danger"
                            onclick="$('#testForm').submit()">
                        Yes
                    </button>
                    <button class="btn btn-warning" data-dismiss="modal">No</button>
                </div>
            </div>
        }
    </div>
</div>
@section Scripts
{
    <script>
        function deleteModal(id) {
            $("#linkId").val(id);
        }
    </script>
}
</code>```

Result:

Body:
Ok I have an issue with my table its only getting the first records id passed to it. When I click the delete button the value

        Circuit name
        Resistance
        Circuit type
        Passed
        Action

    @foreach (var item in Model) {
        var idx = 0;
        var tm = "#myModal" + item.Id;
        var mid = "myModal" + item.Id;

            @Html.DisplayFor(modelItem => item.Name)

        @Html.DisplayFor(modelItem => item.Resitance)
        @Html.DisplayFor(modelItem => item.CirtcutType)

            @(item.Passed? "Yes": "No")

            <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myEditModal">  Edit</button>

            <button type="button" data-id="@item.Id" data-toggle="modal" class="btn btn-danger btn-lg" data-target="#deleteLink">

                Delete
            </button>

            @{Html.RenderPartial("EditFormPartial",Model.Where(w=>w.Id==item.Id).FirstOrDefault());}

                    @using (Html.BeginForm("Delete", "Electrician", FormMethod.Post)) {

                                <button type="button" class="close" data-dismiss="modal">×</button>

Delete Record!

                                Are you sure you wish to delete this record ?.

                                <input type="text" name="linkId" value="@item.Id" />

                                <button type="submit" id="btnSubmit" class="btn btn-danger"
                                        onclick="$('#testForm').submit()">
                                    Yes
                                </button>
                                <button class="btn btn-warning" data-dismiss="modal">No</button>

                    }

The value here is only ever showing the first record id value of 15

 <input type="text" name="linkId" value="@item.Id" />

This is the javascript. How Do I ensure that im getting each id and not just the first one.

Body:
A simple way is to add a js function and pass the @item.Id to the function like below:

@model IEnumerable<Electrician>
<table class="table table-dark">
    <thead>
        <tr>
            <th scope="col">Circuit name    </th>
            <th scope="col">Resistance </th>
            <th scope="col">Circuit type</th>
            <th scope="col">Passed</th>
            <th scope="col">Action </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            var idx = 0;
            var tm = "#myModal" + item.Id;
            var mid = "myModal" + item.Id;
            <tr>
                <th scope="row">
                    @Html.DisplayFor(modelItem => item.Name)
                </th>
                <td>@Html.DisplayFor(modelItem => item.Resitance)</td>
                <td>@Html.DisplayFor(modelItem => item.CirtcutType)</td>
                <td>
                    @(item.Passed ? "Yes" : "No")
                </td>
                <td>
                    <button type="button" onclick="deleteModal(@item.Id)" data-id="@item.Id" data-toggle="modal" class="btn btn-danger btn-lg" data-target="#deleteLink">
                        <i class="fa fa-trash"></i>&nbsp;&nbsp;
                        Delete
                    </button>
                </td>
            </tr>
        }
    </tbody>
</table>
<div id="deleteLink" class="modal fade" role="dialog">
    <div class="modal-dialog">
        @using (Html.BeginForm("Delete", "Electrician", FormMethod.Post))
        {
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Delete Record!</h4>
                </div>
                <div class="modal-body">
                    Are you sure you wish to delete this record ?.
                    <!--this is how to pass the id through-->
                    <input type="text" name="linkId"  id="linkId"/>

                </div>
                <div class="modal-footer">

                    <button type="submit" id="btnSubmit" class="btn btn-danger"
                            onclick="$('#testForm').submit()">
                        Yes
                    </button>
                    <button class="btn btn-warning" data-dismiss="modal">No</button>
                </div>
            </div>
        }
    </div>
</div>
@section Scripts
{
    <script>
        function deleteModal(id) {
            $("#linkId").val(id);
        }
    </script>
}

Result:


问:
Authorize AWS API Gateway with either API Key or Authorizer
In AWS API Gateway,

- We can set up a resource to reqiure API Key for access.

- We can also set up another resource to require Authorization (e.g. JWT token, handled via a lambda function or AWS Cognito).

The question: can we configure a resource to be accessible in either of the above two situations? Currently, if we enable "API Key Required" and "Authorization" simultaneously, the request needs both the API Key and the Authorization. We were hoping for it to pass with only one of the two.

Hack/workaround: Create two copies of the same resource, and authorize each separately, one with API Key and the other one with an authorizer.

答:
Let authorizer generate/map the API key for you

You have a Lambda authorizer return the API key as part of
  the authorization response. For more information on the authorization
  response, see Output from an Amazon API Gateway Lambda authorizer.

Pros:

Single end-point

API key is more for usage plan than authorization. Keep it that way.

Cons:

Authorizer will run on each request. Which cost money


问:
How to map truthy values to separate objects in js/lodash in an object to array?
How to convert this using lodash/vanilla javascript

```<code>const obj = {
'red': {'1': true, '2': false, '3':true},
'green': {'1': false, '2': false, '3':true},
'blue': {'1': true, '2': true, '3':true},
}
</code>```

to this:

```<code>const resultArray =
[
{'red': '1'}, {'red': '3'},
{'green': '3'},
{'blue': '1'}, {'blue': '2'},
]
</code>```

Here all the keys whose values are truthy are mapped to 'red', 'green' or 'blue' in array.

答:
So what you want to do is iterate all the object entries (keys => values) and for each of those, filter out the falsy values and map those entries your desired format.

You can then flatten the new array to get the final result you want.

const obj = {
'red': {'1': true, '2': false, '3':true},
'green': {'1': false, '2': false, '3':true},
'blue': {'1': true, '2': true, '3':true},
}

const resultArray = Object.entries(obj).map(([ key, vals ]) =>
  Object.entries(vals)
    .filter(([ _, flag ]) => flag)
    .map(([ idx ]) => ({ [key]: idx }))
).flat()

console.info(resultArray)```

Body:
How to convert this using lodash/vanilla javascript

const obj = {
'red': {'1': true, '2': false, '3':true},
'green': {'1': false, '2': false, '3':true},
'blue': {'1': true, '2': true, '3':true},
}

to this:

const resultArray =
[
{'red': '1'}, {'red': '3'},
{'green': '3'},
{'blue': '1'}, {'blue': '2'},
]

Here all the keys whose values are truthy are mapped to 'red', 'green' or 'blue' in array.


问:
save blob file (audio/ogg) using asp.net mvc core
must be a simple question but I've been struggling for a week with it. I have a super simple jquery based audio capture - what I just want is to save it as a file based on a controller action. The problem is that I can't figure out how to pass blob file to the controller. This is the code I have to capture audio (see below). With image I can just use

document.getElementById("canvas").toDataURL("image/png");

then pass it to controller and save it as image, something like this:

```<code>   using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            byte[] data = Convert.FromBase64String(imageData);
            bw.Write(data);
            bw.Close();
        }
        fs.Close();
    }
</code>```

so ideally I would want something akin to how I save images.

$(function () {
    $('body').append(
        $('<button/>')
            .attr("id", "start")
            .html("start")
    ).append(
        $('<button/>')
            .attr("id", "stop")
            .html("stop")
    ).append(
        $('
').
            attr("id", "ul")
    )

    let log = console.log.bind(console),
        ul = $('#ul')[0],
        start = $('#start')[0],
        stop = $('#stop')[0],
        stream,
        recorder,
        counter = 1,
        chunks,
        media;
    media = {
        tag: 'audio',
        type: 'audio/ogg',
        ext: '.ogg',
        gUM: { audio: true }
    }
    navigator.mediaDevices.getUserMedia(media.gUM).then(_stream => {
        stream = _stream;
        recorder = new MediaRecorder(stream);
        recorder.ondataavailable = e => {
            chunks.push(e.data);
            if (recorder.state == 'inactive') makeLink();
        };
        log('got media successfully');
    }).catch(log);

    start.onclick = e => {
        start.disabled = true;
        stop.removeAttribute('disabled');
        chunks = [];
        recorder.start();
    }

    stop.onclick = e => {
        stop.disabled = true;
        recorder.stop();
        start.removeAttribute('disabled');
    }
    function makeLink() {
        let blob = new Blob(chunks, { type: media.type })
            , url = URL.createObjectURL(blob)
            , div = document.createElement('div')
            , mt = document.createElement(media.tag)
            , hf = document.createElement('a')
            ;
        mt.controls = true;
        mt.src = url;
        hf.href = url;
        hf.download = `${counter++}${media.ext}`;
        hf.innerHTML = `donwload ${hf.download}`;
        div.appendChild(mt);
        ul.appendChild(div);
    }
});```
<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></code>```

Much appreciated

答:
So just in case anyone else stumples on it, as expected it was quite simple (not the cleanest code but here you go):

create a new Blob value:

```<code>        recorder.ondataavailable = e => {
        chunks.push(e.data);
        superBuffer = new Blob(chunks, { type: 'audio/ogg' });
        if (recorder.state == 'inactive') makeLink(); //console.log(e.data)
</code>```

Then use Ajax to send this to server:

```<code>            var reader = new window.FileReader();
            reader.readAsDataURL(superBuffer);

            reader.onloadend = function () {
                base64 = reader.result;
                base64 = base64.split(',')[1];

                $.ajax({
                    url: 'MyController/Action1',
                    type: 'POST',
                    data: {
                        audioname: "hello",//obviously change to something dynamic
                        chunks: base64
                    },
                    success: function (response) { console.log(response); },
                    error: function (response) { console.log(response); }
                });
</code>```

Then in the code-behind:

```<code>        [HttpPost]
    public IActionResult Action1(string audioname, string chunks)
    {

        string fileNameWitPath = Path.Combine(_hostingEnvironment.WebRootPath, "audio", "test.ogg");

        using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
        {
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                byte[] data = Convert.FromBase64String(chunks);
                bw.Write(data);
                bw.Close();
            }
            fs.Close();
        }
     return Content(chunks) ;//this is for testing - sends back full chunk on success, would probably just want some confirm all is good message
    }
</code>```

Note this is work in progress obviously with things to fill, but in general works

Body:
must be a simple question but I've been struggling for a week with it. I have a super simple jquery based audio capture - what I just want is to save it as a file based on a controller action. The problem is that I can't figure out how to pass blob file to the controller. This is the code I have to capture audio (see below). With image I can just use

document.getElementById("canvas").toDataURL("image/png");

then pass it to controller and save it as image, something like this:

   using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            byte[] data = Convert.FromBase64String(imageData);
            bw.Write(data);
            bw.Close();
        }
        fs.Close();
    }

so ideally I would want something akin to how I save images.

$(function () {
    $('body').append(
        $('<button/>')
            .attr("id", "start")
            .html("start")
    ).append(
        $('<button/>')
            .attr("id", "stop")
            .html("stop")
    ).append(
        $('
').
            attr("id", "ul")
    )

    let log = console.log.bind(console),
        ul = $('#ul')[0],
        start = $('#start')[0],
        stop = $('#stop')[0],
        stream,
        recorder,
        counter = 1,
        chunks,
        media;
    media = {
        tag: 'audio',
        type: 'audio/ogg',
        ext: '.ogg',
        gUM: { audio: true }
    }
    navigator.mediaDevices.getUserMedia(media.gUM).then(_stream => {
        stream = _stream;
        recorder = new MediaRecorder(stream);
        recorder.ondataavailable = e => {
            chunks.push(e.data);
            if (recorder.state == 'inactive') makeLink();
        };
        log('got media successfully');
    }).catch(log);

    start.onclick = e => {
        start.disabled = true;
        stop.removeAttribute('disabled');
        chunks = [];
        recorder.start();
    }

    stop.onclick = e => {
        stop.disabled = true;
        recorder.stop();
        start.removeAttribute('disabled');
    }
    function makeLink() {
        let blob = new Blob(chunks, { type: media.type })
            , url = URL.createObjectURL(blob)
            , div = document.createElement('div')
            , mt = document.createElement(media.tag)
            , hf = document.createElement('a')
            ;
        mt.controls = true;
        mt.src = url;
        hf.href = url;
        hf.download = `${counter++}${media.ext}`;
        hf.innerHTML = `donwload ${hf.download}`;
        div.appendChild(mt);
        ul.appendChild(div);
    }
});

Much appreciated

Body:
So just in case anyone else stumples on it, as expected it was quite simple (not the cleanest code but here you go):

create a new Blob value:

        recorder.ondataavailable = e => {
        chunks.push(e.data);
        superBuffer = new Blob(chunks, { type: 'audio/ogg' });
        if (recorder.state == 'inactive') makeLink(); //console.log(e.data)

Then use Ajax to send this to server:

            var reader = new window.FileReader();
            reader.readAsDataURL(superBuffer);

            reader.onloadend = function () {
                base64 = reader.result;
                base64 = base64.split(',')[1];

                $.ajax({
                    url: 'MyController/Action1',
                    type: 'POST',
                    data: {
                        audioname: "hello",//obviously change to something dynamic
                        chunks: base64
                    },
                    success: function (response) { console.log(response); },
                    error: function (response) { console.log(response); }
                });

Then in the code-behind:

        [HttpPost]
    public IActionResult Action1(string audioname, string chunks)
    {

        string fileNameWitPath = Path.Combine(_hostingEnvironment.WebRootPath, "audio", "test.ogg");

        using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
        {
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                byte[] data = Convert.FromBase64String(chunks);
                bw.Write(data);
                bw.Close();
            }
            fs.Close();
        }
     return Content(chunks) ;//this is for testing - sends back full chunk on success, would probably just want some confirm all is good message
    }

Note this is work in progress obviously with things to fill, but in general works


答:
const obj = {
'red': {'1': true, '2': false, '3':true},
'green': {'1': false, '2': false, '3':true},
'blue': {'1': true, '2': true, '3':true},
};

const out = Object.keys(obj).flatMap(color => {
  return Object.entries(obj[color])
    .filter(([k, v]) => Boolean(v))
    .map(([k]) => ({[color]: k}));
});

console.log(out);```

Title: How to map truthy values to separate objects in js/lodash in an object to array?